diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..9e97020058 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,69 @@ + + +Fixes # + + + +## Problem + + + +## Change + + + +**Not in this PR:** + +## How it was checked + +- [ ] `cargo xtask ci` passes on this branch, rebased on current `main` +- [ ] A test that fails without this change (for a crash fix: a regression test that panicked before it) +- [ ] User-visible change: ran the app and looked at the result + + + +## Screenshots + + + +## Merging + + + +- **Overlap:** +- **Existing edits and libraries:** +- **Shared numbers taken:** +- **Where it came from:** +- **New dependencies, `unsafe`, build scripts, network access, spawned processes, deleted files, CI or `xtask` gate + changes:** + +## Checklist + +- [ ] No new panic path in non-test code: no `unwrap` / `expect` / `panic!`, no indexing or unchecked arithmetic on a + number from a file, a person or an agent (`get`, `checked_mul`, NaN and char boundaries handled) +- [ ] New text on screen goes through `tr()` and has its key in `crates/ui-egui/locales/*.json`; a new shortcut is + free in `docs/library-shortcuts.md` +- [ ] The feature's rows in `docs/parity-checklist.md` and its entry in `docs/gaps.md` are updated, honestly (🟡 when + it is partial), in the same commit +- [ ] New code has a caller: no command, module or setting that nothing reaches yet +- [ ] Every new image, icon or other asset has its entry in `assets/ATTRIBUTION.md`; no font or media files added +- [ ] Ready to merge (otherwise open it as a draft) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..a309a9fb38 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +name: CI + +# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the +# suite's shared gate workflow in craft-common-actions. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +# A newer push to a PR branch cancels its older run; every push to main runs to the end. +concurrency: + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + gate: + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + # Same craft-fonts commit as release.yml. + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + timeout-minutes: 90 + # xtask ci runs cargo test: the demo scene cache is per process, so nextest is slower here. + tools: "" + packages: >- + pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev + libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers + libgl1-mesa-dev libdbus-1-dev diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index d85332b235..9077bac2cd 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -1,23 +1,18 @@ # FreeBSD build and package check in a QEMU VM. name: FreeBSD +# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every pull +# request: a drifted dependency still shows up within a day, and always before a release ships. +# PRs that change the FreeBSD workflow or packaging itself still run it. on: push: - branches: [main] - paths: - - ".github/workflows/freebsd.yml" - - "packaging/freebsd/**" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + branches: [release] pull_request: - branches: [main] paths: - - ".github/workflows/freebsd.yml" - - "packaging/freebsd/**" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + - .github/workflows/freebsd.yml + - packaging/freebsd/** + schedule: + - cron: "7 4 * * *" workflow_dispatch: concurrency: @@ -33,4 +28,4 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: require-craft-fonts: true - craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index 01cb9cd663..2fe7cd3ac9 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -18,6 +18,44 @@ concurrency: cancel-in-progress: true jobs: + git-sources: + name: Git dependencies come from storytold + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Git dependencies come from storytold + run: | + set -euo pipefail + test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } + # Source replacement, patches and path overrides in cargo config never show up + # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. + # Cargo still reads the legacy .cargo/config. + python3 - <<'PY' + import os, sys, tomllib + for path in (".cargo/config", ".cargo/config.toml"): + if not os.path.exists(path): + continue + config = tomllib.load(open(path, "rb")) + replaced = [name for name, source in config.get("source", {}).items() + if isinstance(source, dict) and "replace-with" in source] + if replaced or "patch" in config or "paths" in config: + print(f"{path} replaces, patches or overrides a source") + sys.exit(1) + PY + # Fails when Cargo.lock is out of date with the manifests. + cargo metadata --locked --format-version 1 > /dev/null + python3 - <<'PY' + import sys, tomllib + lock = tomllib.load(open("Cargo.lock", "rb")) + bad = sorted({p["source"] for p in lock.get("package", []) + if p.get("source", "").startswith("git+") + and not p["source"].startswith("git+https://github.com/storytold/")}) + if bad: + print("Git dependencies outside github.com/storytold:", *bad, sep="\n") + sys.exit(1) + PY + nix: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/nix.yml@main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b8fb013261..d1841ebe7a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,13 +20,53 @@ concurrency: cancel-in-progress: false jobs: + git-sources: + name: Git dependencies come from storytold + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Git dependencies come from storytold + run: | + set -euo pipefail + test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } + # Source replacement, patches and path overrides in cargo config never show up + # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. + # Cargo still reads the legacy .cargo/config. + python3 - <<'PY' + import os, sys, tomllib + for path in (".cargo/config", ".cargo/config.toml"): + if not os.path.exists(path): + continue + config = tomllib.load(open(path, "rb")) + replaced = [name for name, source in config.get("source", {}).items() + if isinstance(source, dict) and "replace-with" in source] + if replaced or "patch" in config or "paths" in config: + print(f"{path} replaces, patches or overrides a source") + sys.exit(1) + PY + # Fails when Cargo.lock is out of date with the manifests. + cargo metadata --locked --format-version 1 > /dev/null + python3 - <<'PY' + import sys, tomllib + lock = tomllib.load(open("Cargo.lock", "rb")) + bad = sorted({p["source"] for p in lock.get("package", []) + if p.get("source", "").startswith("git+") + and not p["source"].startswith("git+https://github.com/storytold/")}) + if bad: + print("Git dependencies outside github.com/storytold:", *bad, sep="\n") + sys.exit(1) + PY + release: + needs: git-sources # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: app-name: lightcraft app-title: LightCraft - craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} secrets: diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index ecee45a6d8..e78fe1ea3b 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -11,7 +11,8 @@ permissions: concurrency: group: sonarcloud-${{ github.ref }} - cancel-in-progress: true + # A push to main is the run that publishes coverage; superseded runs there would never finish. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} jobs: sonarcloud: diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 0033346dc7..3321939985 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -5,23 +5,17 @@ # on GitHub Actions' native windows-11-arm runner. name: Windows ARM64 +# Nightly on main and on pushes to `release` (dependency and runner-image drift shows up within a +# day, and always before a release ships), and on PRs that change the Windows packaging itself. on: + schedule: + - cron: "3 5 * * *" push: - branches: [main] - paths: - - ".github/workflows/windows-arm64.yml" - - "packaging/windows/**" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + branches: [release] pull_request: - branches: [main] paths: - - ".github/workflows/windows-arm64.yml" - - "packaging/windows/**" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + - .github/workflows/windows-arm64.yml + - packaging/windows/** workflow_dispatch: concurrency: diff --git a/CLAUDE.md b/CLAUDE.md index d2d538d652..416ffc0a8d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,7 +68,10 @@ of it. Full standard: `../craftrules/standards/never-crash.md` `Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row. - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm). +- **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages' + tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR + (`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see + the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. ## Assets: icons, images, fonts (ABSOLUTE RULE — never violate) diff --git a/Cargo.lock b/Cargo.lock index 216fdeca4e..a9a326ab8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,21 +20,21 @@ checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" [[package]] name = "accesskit" -version = "0.24.1" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" dependencies = [ "uuid", ] [[package]] name = "accesskit_atspi_common" -version = "0.18.1" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954" +checksum = "52c182f9c282ac9c5638d876d551d15e5f7d397ec263349a0c6a2b61595dd5e4" dependencies = [ "accesskit", - "accesskit_consumer 0.36.0", + "accesskit_consumer", "atspi-common", "phf", "serde", @@ -43,43 +43,37 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.35.0" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10" +checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" dependencies = [ "accesskit", - "hashbrown 0.16.1", + "hashbrown 0.17.1", ] [[package]] -name = "accesskit_consumer" -version = "0.36.0" +name = "accesskit_ios" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60" +checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937" dependencies = [ "accesskit", - "hashbrown 0.16.1", -] - -[[package]] -name = "accesskit_consumer" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" -dependencies = [ - "accesskit", - "hashbrown 0.16.1", + "accesskit_consumer", + "hashbrown 0.17.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", ] [[package]] name = "accesskit_macos" -version = "0.26.3" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" dependencies = [ "accesskit", - "accesskit_consumer 0.38.0", - "hashbrown 0.16.1", + "accesskit_consumer", + "hashbrown 0.17.1", "objc2 0.5.2", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", @@ -87,9 +81,9 @@ dependencies = [ [[package]] name = "accesskit_unix" -version = "0.21.1" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c" +checksum = "202f24df034a7476d07b7f74284de84f6d62aabd858dbe7ee9cad3b7ad6f8f9d" dependencies = [ "accesskit", "accesskit_atspi_common", @@ -105,13 +99,13 @@ dependencies = [ [[package]] name = "accesskit_windows" -version = "0.32.1" +version = "0.35.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21" +checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb" dependencies = [ "accesskit", - "accesskit_consumer 0.35.0", - "hashbrown 0.16.1", + "accesskit_consumer", + "hashbrown 0.17.1", "static_assertions", "windows", "windows-core", @@ -119,11 +113,12 @@ dependencies = [ [[package]] name = "accesskit_winit" -version = "0.32.2" +version = "0.34.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313" +checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77" dependencies = [ "accesskit", + "accesskit_ios", "accesskit_macos", "accesskit_unix", "accesskit_windows", @@ -164,7 +159,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] @@ -218,13 +213,28 @@ version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + [[package]] name = "alloc-stdlib" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" dependencies = [ - "alloc-no-stdlib", + "alloc-no-stdlib 2.0.4", +] + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib 3.0.0", ] [[package]] @@ -288,14 +298,15 @@ dependencies = [ "clipboard-win", "image", "log", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.60.2", + "windows-sys 0.59.0", + "wl-clipboard-rs", "x11rb", ] @@ -584,21 +595,18 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" -[[package]] -name = "bit-set" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec 0.8.0", -] - [[package]] name = "bit-set" version = "0.10.0" @@ -609,10 +617,13 @@ dependencies = [ ] [[package]] -name = "bit-vec" -version = "0.8.0" +name = "bit-set" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.1", +] [[package]] name = "bit-vec" @@ -620,6 +631,16 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -671,7 +692,7 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" dependencies = [ - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] @@ -688,14 +709,38 @@ dependencies = [ ] [[package]] -name = "brotli" -version = "8.0.4" +name = "borsh" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "brotli" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.0.1", ] [[package]] @@ -704,8 +749,18 @@ version = "5.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", +] + +[[package]] +name = "brotli-decompressor" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", ] [[package]] @@ -833,7 +888,7 @@ dependencies = [ "safetensors 0.7.0", "thiserror 2.0.21", "yoke 0.8.3", - "zip", + "zip 7.2.0", ] [[package]] @@ -843,7 +898,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fdfe9d06de16ce49961e49084e5b79a75a9bdf157246e7c7b6328e87a7aa25d" dependencies = [ "half", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-foundation 0.3.2", "objc2-metal 0.3.2", "once_cell", @@ -920,7 +975,18 @@ checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", ] [[package]] @@ -930,7 +996,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" dependencies = [ "aead", - "chacha20", + "chacha20 0.9.1", "cipher", "poly1305", "zeroize", @@ -1042,6 +1108,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -1055,7 +1131,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -1068,10 +1144,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1081,6 +1163,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1089,17 +1180,42 @@ source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09 [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675" +source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f" dependencies = [ "egui", "serde", ] +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=495e5971bc024aa96e6ed318cb6e7cd3a0103184#495e5971bc024aa96e6ed318cb6e7cd3a0103184" +dependencies = [ + "chrono", + "dunce", + "egui", + "flate2", + "getrandom 0.3.4", + "log", + "plist", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip 9.1.0", +] + [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ "cfg-if", ] @@ -1188,7 +1304,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "curve25519-dalek-derive", "digest", "fiat-crypto", @@ -1219,6 +1335,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "dhat" version = "0.3.3" @@ -1275,7 +1397,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.6.2", "libc", - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] @@ -1308,6 +1430,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-stack" version = "0.10.0" @@ -1350,9 +1478,8 @@ dependencies = [ [[package]] name = "ecolor" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "bytemuck", "emath", @@ -1384,9 +1511,8 @@ dependencies = [ [[package]] name = "eframe" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55ad41fac6e3149abb4866e93df37dbd33baa95db525c3368c944584e95a5dc2" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "ahash", "bytemuck", @@ -1401,7 +1527,7 @@ dependencies = [ "image", "js-sys", "log", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "parking_lot", @@ -1409,6 +1535,7 @@ dependencies = [ "pollster 1.0.1", "profiling", "raw-window-handle", + "send_wrapper", "static_assertions", "wasm-bindgen", "web-sys", @@ -1420,9 +1547,8 @@ dependencies = [ [[package]] name = "egui" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "accesskit", "ahash", @@ -1440,9 +1566,8 @@ dependencies = [ [[package]] name = "egui-wgpu" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cef1f6d1bba40b09a4d0d62cb822b81030922cfbf65c5373398c3a3caafc5bd" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "ahash", "bytemuck", @@ -1460,30 +1585,33 @@ dependencies = [ [[package]] name = "egui-winit" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "accesskit_winit", "arboard", + "block2 0.6.2", "bytemuck", "egui", + "image", "log", - "objc2 0.6.4", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "objc2-ui-kit 0.3.2", + "parking_lot", "profiling", "raw-window-handle", "smithay-clipboard", "web-time", + "windows-sys 0.61.2", "winit", ] [[package]] name = "egui_glow" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "bytemuck", "egui", @@ -1495,9 +1623,8 @@ dependencies = [ [[package]] name = "egui_kittest" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eb3f3effb2726fee23449293e67acbf6cc6ce35525b1722bd5743bb348114d5" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "dify", "eframe", @@ -1543,9 +1670,8 @@ dependencies = [ [[package]] name = "emath" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "bytemuck", ] @@ -1591,9 +1717,8 @@ dependencies = [ [[package]] name = "epaint" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "ahash", "bytemuck", @@ -1601,7 +1726,7 @@ dependencies = [ "emath", "epaint_default_fonts", "font-types", - "harfrust", + "harfrust 0.12.0", "log", "nohash-hasher", "parking_lot", @@ -1609,16 +1734,17 @@ dependencies = [ "self_cell", "skrifa", "smallvec", + "unicode-bidi", "unicode-general-category", + "unicode-properties", "unicode-segmentation", "vello_cpu", ] [[package]] name = "epaint_default_fonts" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" [[package]] name = "equator" @@ -1673,7 +1799,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1790,12 +1916,28 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "flate2" version = "1.1.10" @@ -1825,6 +1967,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -2336,8 +2484,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -2379,12 +2530,12 @@ dependencies = [ [[package]] name = "glifo" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a" +checksum = "282a26c1e23de04bdab3e34a21b6f877a479b96737792516b9b8b8f69b6661be" dependencies = [ "bytemuck", - "foldhash", + "foldhash 0.2.0", "hashbrown 0.17.1", "log", "peniko", @@ -2419,7 +2570,7 @@ dependencies = [ "glutin_glx_sys", "glutin_wgl_sys", "libloading", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", @@ -2528,10 +2679,32 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" dependencies = [ "bitflags 2.13.2", "bytemuck", - "read-fonts", + "read-fonts 0.41.0", "smallvec", ] +[[package]] +name = "harfrust" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "948d0741125ba89cd3e1c23e5642415b6ade7e1d29d67ba25fb925b533e989d6" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "once_cell", + "read-fonts 0.43.3", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -2540,7 +2713,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", "serde", "serde_core", ] @@ -2551,7 +2724,7 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "foldhash", + "foldhash 0.2.0", ] [[package]] @@ -2599,6 +2772,22 @@ dependencies = [ "digest", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "image" version = "0.25.10" @@ -2885,7 +3074,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46" dependencies = [ - "brotli-decompressor", + "brotli-decompressor 5.0.3", "jxl-bitstream", "jxl-frame", "jxl-grid", @@ -2917,7 +3106,7 @@ version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3" dependencies = [ - "brotli-decompressor", + "brotli-decompressor 5.0.3", "jxl-bitstream", "jxl-color", "jxl-frame", @@ -3012,12 +3201,12 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" [[package]] name = "kittest" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ceaa75eb0036a32b6b9833962eb18137449e9817e2e586006471925b727fd5" +checksum = "0bb81a721ba76aa095b7f45deb180504f786904e56ca4b8e141f66eb89a78b75" dependencies = [ "accesskit", - "accesskit_consumer 0.35.0", + "accesskit_consumer", ] [[package]] @@ -3043,9 +3232,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libfuzzer-sys" @@ -3087,9 +3276,10 @@ dependencies = [ [[package]] name = "lightcraft" -version = "0.11.0" +version = "0.14.0" dependencies = [ "chrono", + "craft-update", "eframe", "egui", "lightcraft-codecs", @@ -3100,7 +3290,7 @@ dependencies = [ "lightcraft-ui-egui", "log", "muda", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "pollster 1.0.1", @@ -3113,7 +3303,7 @@ dependencies = [ [[package]] name = "lightcraft-catalog" -version = "0.11.0" +version = "0.14.0" dependencies = [ "chrono", "crc32fast", @@ -3131,7 +3321,7 @@ dependencies = [ [[package]] name = "lightcraft-cli" -version = "0.11.0" +version = "0.14.0" dependencies = [ "dhat", "lightcraft-codecs", @@ -3147,7 +3337,7 @@ dependencies = [ [[package]] name = "lightcraft-codecs" -version = "0.11.0" +version = "0.14.0" dependencies = [ "avif-serialize", "bytemuck", @@ -3178,7 +3368,7 @@ dependencies = [ [[package]] name = "lightcraft-color" -version = "0.11.0" +version = "0.14.0" dependencies = [ "lightcraft-geom", "proptest", @@ -3187,12 +3377,12 @@ dependencies = [ [[package]] name = "lightcraft-denoise" -version = "0.11.0" +version = "0.14.0" dependencies = [ "faer-core", "lightcraft-denoise-core", "lightcraft-raster", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "proptest", "rayon", "serde", @@ -3204,10 +3394,11 @@ dependencies = [ [[package]] name = "lightcraft-denoise-core" -version = "0.11.0" +version = "0.14.0" dependencies = [ + "dhat", "lightcraft-raster", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "proptest", "rayon", "serde", @@ -3219,11 +3410,11 @@ dependencies = [ [[package]] name = "lightcraft-develop" -version = "0.11.0" +version = "0.14.0" dependencies = [ "lightcraft-color", "lightcraft-geom", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "proptest", "serde", "serde_json", @@ -3231,12 +3422,12 @@ dependencies = [ [[package]] name = "lightcraft-engine" -version = "0.11.0" +version = "0.14.0" dependencies = [ "ab_glyph", "chrono", "craft-docpath", - "harfrust", + "harfrust 0.13.3", "jxl-oxide", "libc", "lightcraft-catalog", @@ -3264,7 +3455,7 @@ dependencies = [ "lightcraft-testkit", "lightcraft-tiff", "log", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "rayon", "serde", "serde_json", @@ -3275,7 +3466,7 @@ dependencies = [ [[package]] name = "lightcraft-faces" -version = "0.11.0" +version = "0.14.0" dependencies = [ "lightcraft-testkit", "matrixmultiply", @@ -3290,7 +3481,7 @@ dependencies = [ [[package]] name = "lightcraft-fetch" -version = "0.11.0" +version = "0.14.0" dependencies = [ "log", "rustls", @@ -3301,15 +3492,15 @@ dependencies = [ [[package]] name = "lightcraft-geocode" -version = "0.11.0" +version = "0.14.0" dependencies = [ - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "serde", ] [[package]] name = "lightcraft-geom" -version = "0.11.0" +version = "0.14.0" dependencies = [ "proptest", "serde", @@ -3317,7 +3508,7 @@ dependencies = [ [[package]] name = "lightcraft-gpu" -version = "0.11.0" +version = "0.14.0" dependencies = [ "bytemuck", "lightcraft-color", @@ -3337,7 +3528,7 @@ dependencies = [ [[package]] name = "lightcraft-heif" -version = "0.11.0" +version = "0.14.0" dependencies = [ "heic-rs", "rayon", @@ -3345,23 +3536,23 @@ dependencies = [ [[package]] name = "lightcraft-inpaint" -version = "0.11.0" +version = "0.14.0" dependencies = [ "rayon", ] [[package]] name = "lightcraft-lensdb" -version = "0.11.0" +version = "0.14.0" dependencies = [ "lightcraft-develop", "lightcraft-geom", - "quick-xml 0.38.4", + "quick-xml 0.41.0", ] [[package]] name = "lightcraft-mcp" -version = "0.11.0" +version = "0.14.0" dependencies = [ "lightcraft-codecs", "lightcraft-engine", @@ -3372,7 +3563,7 @@ dependencies = [ [[package]] name = "lightcraft-merge" -version = "0.11.0" +version = "0.14.0" dependencies = [ "lightcraft-codecs", "lightcraft-color", @@ -3388,21 +3579,22 @@ dependencies = [ [[package]] name = "lightcraft-meta" -version = "0.11.0" +version = "0.14.0" dependencies = [ "chrono", "lightcraft-geom", "lightcraft-tiff", "proptest", - "quick-xml 0.38.4", + "quick-xml 0.41.0", "serde", "serde_json", ] [[package]] name = "lightcraft-pipeline" -version = "0.11.0" +version = "0.14.0" dependencies = [ + "dhat", "image", "lightcraft-color", "lightcraft-develop", @@ -3419,7 +3611,7 @@ dependencies = [ [[package]] name = "lightcraft-preview" -version = "0.11.0" +version = "0.14.0" dependencies = [ "jpeg-encoder", "lightcraft-raster", @@ -3431,7 +3623,7 @@ dependencies = [ [[package]] name = "lightcraft-raster" -version = "0.11.0" +version = "0.14.0" dependencies = [ "libc", "lightcraft-color", @@ -3443,7 +3635,7 @@ dependencies = [ [[package]] name = "lightcraft-raw" -version = "0.11.0" +version = "0.14.0" dependencies = [ "dhat", "jpeg-encoder", @@ -3454,7 +3646,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-testkit", "lightcraft-tiff", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "proptest", "rayon", "serde", @@ -3467,7 +3659,7 @@ dependencies = [ [[package]] name = "lightcraft-scenes" -version = "0.11.0" +version = "0.14.0" dependencies = [ "image", "lightcraft-color", @@ -3478,7 +3670,7 @@ dependencies = [ [[package]] name = "lightcraft-segment" -version = "0.11.0" +version = "0.14.0" dependencies = [ "candle-core", "candle-nn", @@ -3492,7 +3684,7 @@ dependencies = [ [[package]] name = "lightcraft-slideshow" -version = "0.11.0" +version = "0.14.0" dependencies = [ "lightcraft-raster", "serde", @@ -3501,15 +3693,15 @@ dependencies = [ [[package]] name = "lightcraft-sysmem" -version = "0.11.0" +version = "0.14.0" [[package]] name = "lightcraft-testkit" -version = "0.11.0" +version = "0.14.0" [[package]] name = "lightcraft-tiff" -version = "0.11.0" +version = "0.14.0" dependencies = [ "proptest", "serde", @@ -3518,9 +3710,10 @@ dependencies = [ [[package]] name = "lightcraft-ui-egui" -version = "0.11.0" +version = "0.14.0" dependencies = [ "craft-ui", + "craft-update", "egui", "egui_kittest", "lightcraft-catalog", @@ -3547,7 +3740,7 @@ dependencies = [ [[package]] name = "lightcraft-web" -version = "0.11.0" +version = "0.14.0" dependencies = [ "crc32fast", "eframe", @@ -3737,18 +3930,17 @@ dependencies = [ [[package]] name = "muda" -version = "0.21.0" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6744ab645ebe79f9c428455c7cb9dfa4275fa3b50a25408e08f927da8dc618c" +checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" dependencies = [ "crossbeam-channel", "dpi", "keyboard-types", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", - "once_cell", "png", "thiserror 2.0.21", "windows-sys 0.61.2", @@ -3843,6 +4035,18 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "no_std_io2" version = "0.9.4" @@ -3923,6 +4127,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -4033,9 +4243,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ "objc2-encode", ] @@ -4064,7 +4274,7 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", @@ -4114,7 +4324,7 @@ checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", "dispatch2", - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] @@ -4125,7 +4335,7 @@ checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", "dispatch2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", ] @@ -4182,7 +4392,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.6.2", "libc", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", ] @@ -4193,7 +4403,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ "bitflags 2.13.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", ] @@ -4230,7 +4440,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.6.2", "dispatch2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-foundation 0.3.2", ] @@ -4255,7 +4465,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ "bitflags 2.13.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", @@ -4300,7 +4510,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" dependencies = [ "bitflags 2.13.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-foundation 0.3.2", ] @@ -4360,6 +4570,12 @@ dependencies = [ "libc", ] +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + [[package]] name = "orbclient" version = "0.3.55" @@ -4389,6 +4605,16 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "owned_ttf_parser" version = "0.25.1" @@ -4492,10 +4718,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] -name = "phf" -version = "0.13.1" +name = "petgraph" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ "phf_macros", "phf_shared", @@ -4504,9 +4741,9 @@ dependencies = [ [[package]] name = "phf_generator" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ "fastrand", "phf_shared", @@ -4514,9 +4751,9 @@ dependencies = [ [[package]] name = "phf_macros" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ "phf_generator", "phf_shared", @@ -4527,9 +4764,9 @@ dependencies = [ [[package]] name = "phf_shared" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" dependencies = [ "siphasher", ] @@ -4615,6 +4852,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.18.1" @@ -4660,7 +4910,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" dependencies = [ - "cpufeatures", + "cpufeatures 0.2.17", "opaque-debug", "universal-hash", ] @@ -4681,7 +4931,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "opaque-debug", "universal-hash", ] @@ -4701,6 +4951,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -4764,16 +5020,17 @@ dependencies = [ [[package]] name = "proptest" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ - "bit-set 0.8.0", - "bit-vec 0.8.0", + "bit-set 0.11.1", + "bit-vec 0.10.1", "bitflags 2.13.2", + "chacha20 0.10.2", + "core_detect", "num-traits", - "rand 0.9.5", - "rand_chacha 0.9.0", + "rand 0.10.3", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -4850,18 +5107,18 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" [[package]] name = "quick-xml" -version = "0.38.4" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" dependencies = [ "memchr", ] [[package]] name = "quick-xml" -version = "0.41.0" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" dependencies = [ "memchr", ] @@ -4907,6 +5164,16 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -4945,6 +5212,12 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "rand_distr" version = "0.5.1" @@ -4957,11 +5230,11 @@ dependencies = [ [[package]] name = "rand_xorshift" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" dependencies = [ - "rand_core 0.9.5", + "rand_core 0.10.1", ] [[package]] @@ -5050,7 +5323,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" dependencies = [ - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-foundation 0.3.2", "objc2-quartz-core 0.3.2", @@ -5093,6 +5366,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.43.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -5159,7 +5443,7 @@ dependencies = [ "js-sys", "libc", "log", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", @@ -5266,22 +5550,36 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ + "log", "once_cell", + "ring", "rustls-pki-types", "rustls-webpki 0.103.15", "subtle", "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -5291,6 +5589,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki 0.103.15", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-rustcrypto" version = "0.0.2-alpha" @@ -5391,6 +5716,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -5417,6 +5751,29 @@ dependencies = [ "zeroize", ] +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -5428,6 +5785,16 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" [[package]] name = "seq-macro" @@ -5467,9 +5834,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -5505,7 +5872,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -5579,7 +5946,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", ] [[package]] @@ -5790,6 +6157,16 @@ dependencies = [ "walkdir", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -5797,10 +6174,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5872,6 +6249,36 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tokio" version = "1.53.1" @@ -5964,6 +6371,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] + [[package]] name = "ttf-parser" version = "0.25.1" @@ -5985,6 +6403,12 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.1" @@ -6043,6 +6467,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -6055,6 +6485,12 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + [[package]] name = "unicode-segmentation" version = "1.13.3" @@ -6083,6 +6519,41 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "uuid" version = "1.26.1" @@ -6107,9 +6578,9 @@ dependencies = [ [[package]] name = "vello_common" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2" +checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd" dependencies = [ "bytemuck", "fearless_simd", @@ -6122,9 +6593,9 @@ dependencies = [ [[package]] name = "vello_cpu" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea" +checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9" dependencies = [ "bytemuck", "glifo", @@ -6132,6 +6603,16 @@ dependencies = [ "vello_common", ] +[[package]] +name = "verifysign" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6acfcc42a8d44f340d001193d97ef56bf33210b51ad760ae8308c97d5241ca51" +dependencies = [ + "core-foundation 0.10.1", + "windows-sys 0.61.2", +] + [[package]] name = "version_check" version = "0.9.5" @@ -6384,10 +6865,19 @@ dependencies = [ ] [[package]] -name = "webpki-roots" -version = "1.0.9" +name = "webpki-root-certs" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -6526,7 +7016,7 @@ dependencies = [ "naga", "naga-types", "ndk-sys", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", @@ -6587,7 +7077,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6697,7 +7187,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -6706,16 +7196,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", + "windows-targets", ] [[package]] @@ -6733,31 +7214,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -6775,101 +7239,52 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winit" version = "0.30.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" dependencies = [ "ahash", "android-activity", @@ -6880,7 +7295,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -6926,21 +7341,55 @@ dependencies = [ ] [[package]] -name = "winresource" -version = "0.1.31" +name = "winreg" +version = "0.55.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0986a8b1d586b7d3e4fe3d9ea39fb451ae22869dcea4aa109d287a374d866087" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" dependencies = [ "toml", "version_check", ] +[[package]] +name = "winsafe" +version = "0.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" + [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wl-clipboard-rs" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.5", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "x11-dl" version = "2.21.0" @@ -7017,7 +7466,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.11.0" +version = "0.14.0" dependencies = [ "brotli", "flate2", @@ -7254,7 +7703,24 @@ dependencies = [ "crc32fast", "indexmap", "memchr", - "typed-path", + "typed-path 0.12.3", +] + +[[package]] +name = "zip" +version = "9.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +dependencies = [ + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "memchr", + "nix", + "typed-path 0.13.0", + "windows-sys 0.61.2", + "zopfli", ] [[package]] @@ -7269,6 +7735,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zune-core" version = "0.5.3" @@ -7333,3 +7811,23 @@ dependencies = [ "syn 3.0.6", "winnow", ] + +[[patch.unused]] +name = "egui_demo_lib" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui_inspection" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui_system_font_provider" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" diff --git a/Cargo.toml b/Cargo.toml index 0a0d78e5f6..71fd2566cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,15 +3,16 @@ resolver = "3" members = ["crates/*", "apps/*", "xtask"] [workspace.package] -version = "0.11.0" +version = "0.14.0" edition = "2024" license = "MIT OR Apache-2.0" -rust-version = "1.90" +rust-version = "1.95" repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184", features = ["egui"] } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false } @@ -60,8 +61,8 @@ libc = "0.2" # dev-only: process CPU time in benches dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds # formats -quick-xml = "0.38" -miniz_oxide = "0.8" +quick-xml = "0.41" +miniz_oxide = "0.9" # codecs image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "webp"] } @@ -91,10 +92,13 @@ wgpu = { version = "30", default-features = false, features = ["std", "parking_l pollster = "1" # ui -egui = "0.36" -egui_extras = { version = "0.36", default-features = false } -eframe = { version = "0.36", default-features = false } -egui_kittest = "0.36" +# 0.37: `default_fonts` is no longer an egui default and the monochrome emoji faces moved behind +# `monochrome_emoji_fonts`. Every resolution root (native, CLI/headless, kittest, wasm) needs both: +# kittest's own dev-dependencies do not propagate to its consumers. +egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] } +egui_extras = { version = "0.37", default-features = false } +eframe = { version = "0.37", default-features = false } +egui_kittest = "0.37" rfd = "0.17" muda = { version = "0.21", default-features = false } # native menu bar (macOS: objc2/AppKit, pure Rust; no GTK) # macOS: the profile of the screen showing the window (safe AppKit bindings; muda and wgpu use the same) @@ -125,9 +129,11 @@ excessive_precision = "allow" [profile.dev.package."*"] opt-level = 2 +debug = false [profile.dev] opt-level = 1 +debug = "line-tables-only" [profile.release] debug = "line-tables-only" @@ -167,3 +173,21 @@ jpeg-decoder = { opt-level = 3 } jpeg-encoder = { opt-level = 3 } png = { opt-level = 3 } miniz_oxide = { opt-level = 3 } + +# Keep the complete egui family and native event bridge on reviewed fork commits. +[patch.crates-io] +ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/NOTICE b/NOTICE index 8b16eeba0f..39eb49db2c 100644 --- a/NOTICE +++ b/NOTICE @@ -12,7 +12,9 @@ Third-party material This product bundles third-party material under its own licenses, listed below. The per-file list (author, source, license) is in assets/ATTRIBUTION.md. -Inter (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-Inter.txt. +Inter (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. The licence text is +assets/fonts/OFL-Inter.txt in the source tree; release packages ship it beside NOTICE as +OFL-Inter.txt (Windows installers include it in FONT-LICENCES.txt). Showcase photographs by Ansel Adams, Dorothea Lange and NASA (docs/images/) — public domain. See assets/ATTRIBUTION.md. crates/raw/src/spectral_table.rs (lightcraft-raw) holds camera colour matrices derived from the @@ -50,11 +52,15 @@ maintainer decision. The ONNX reader and CPU/GPU executor are our Rust implement no darktable, RawSpeed, LibRaw or other GPL decoder/runtime code is included. Builds made with craft-fonts (the optional CRAFT_FONTS_DIR build input; all official releases) -also embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md -(BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic and Noto Sans -Thai), under the SIL Open Font License 1.1. The web build embeds BIZ UDPGothic Regular and Noto -Sans Thai Regular, and loads Noto Sans CJK SC separately. Release packages include each font's -licence as OFL-.txt; Windows installers include their texts in FONT-LICENCES.txt. +also embed the default fonts listed in +https://github.com/storytold/craft-fonts/blob/b076417b5880bd4154bd22f00695b1d28c6bea83/ATTRIBUTION.md (BIZ UDPGothic, BIZ UDMincho, +Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans Thai, Noto Sans Georgian, +NanumGothic, Noto Sans Symbols, Noto Sans Symbols 2, Noto Sans Hebrew and +Noto Sans Devanagari), under the SIL Open Font License 1.1. The opt-in LXGW WenKai Lite face +(fonts/simplified-chinese-manifest.txt in craft-fonts) is not embedded. The web build embeds +BIZ UDPGothic Regular, Noto Sans Thai Regular and Noto Sans Georgian Regular, and loads Noto Sans +CJK SC separately. Release packages include each font's licence as OFL-.txt; Windows +installers include their texts in FONT-LICENCES.txt. Place names for reverse geocoding (Photo > Fill Location from GPS) are not part of LightCraft and are never distributed with it. On the user's request (Photo > Download Place Names) the app @@ -62,3 +68,270 @@ downloads cities15000.zip, admin1CodesASCII.txt and countryInfo.txt from GeoName (https://download.geonames.org/export/dump/) into the settings folder. GeoNames data is licensed under Creative Commons Attribution 4.0 (https://creativecommons.org/licenses/by/4.0/); attribution: "GeoNames, geonames.org". The lookup code (crates/geocode) is our own. + + +epaint_default_fonts, the egui default-font crate LightCraft builds with, also bundles Hack Regular +and Ubuntu Light, and Noto Emoji Regular when egui's `monochrome_emoji_fonts` feature is on (the +LightCraft workspace enables both `default_fonts` and `monochrome_emoji_fonts` on egui 0.37). The +LightCraft binaries embed these faces unmodified, registered through egui's default font definitions. +Source for all of them (the same pin as the icon fonts below): +https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts + +Hack Regular (Hack-Regular.ttf) is Copyright (c) 2018 Source Foundry Authors and +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. It is licensed under the MIT License, and +the Bitstream Vera parts under the Bitstream Vera License with Reserved Font Names "Bitstream" and +"Vera": the font as a whole is MIT AND Bitstream Vera License. The work in the DejaVu project it +derives from was committed to the public domain. +The following text is reproduced verbatim from Hack-Regular.txt: + +The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License + +The work in the DejaVu project was committed to the public domain. + +Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera" +MIT License + +Copyright (c) 2018 Source Foundry Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +BITSTREAM VERA LICENSE + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: + +The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera". + +This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names. + +The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org. + + +Ubuntu Light (Ubuntu-Light.ttf) is Copyright 2011 Canonical Ltd., was designed by Dalton Maag Ltd, +and is licensed under the Ubuntu Font Licence 1.0 (not the SIL Open Font License). +The following text is reproduced verbatim from UFL.txt; that file carries no copyright line, so the +copyright notice above is taken from the font's own name table: + +------------------------------- +UBUNTU FONT LICENCE Version 1.0 +------------------------------- + +PREAMBLE +This licence allows the licensed fonts to be used, studied, modified and +redistributed freely. The fonts, including any derivative works, can be +bundled, embedded, and redistributed provided the terms of this licence +are met. The fonts and derivatives, however, cannot be released under +any other licence. The requirement for fonts to remain under this +licence does not require any document created using the fonts or their +derivatives to be published under this licence, as long as the primary +purpose of the document is not to be a vehicle for the distribution of +the fonts. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this licence and clearly marked as such. This may +include source files, build scripts and documentation. + +"Original Version" refers to the collection of Font Software components +as received under this licence. + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to +a new environment. + +"Copyright Holder(s)" refers to all individuals and companies who have a +copyright ownership of the Font Software. + +"Substantially Changed" refers to Modified Versions which can be easily +identified as dissimilar to the Font Software by users of the Font +Software comparing the Original Version with the Modified Version. + +To "Propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification and with or without charging +a redistribution fee), making available to the public, and in some +countries other activities as well. + +PERMISSION & CONDITIONS +This licence does not grant any rights under trademark law and all such +rights are reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to propagate the Font Software, subject to +the below conditions: + +1) Each copy of the Font Software must contain the above copyright +notice and this licence. These can be included either as stand-alone +text files, human-readable headers or in the appropriate machine- +readable metadata fields within text or binary files as long as those +fields can be easily viewed by the user. + +2) The font name complies with the following: +(a) The Original Version must retain its name, unmodified. +(b) Modified Versions which are Substantially Changed must be renamed to +avoid use of the name of the Original Version or similar names entirely. +(c) Modified Versions which are not Substantially Changed must be +renamed to both (i) retain the name of the Original Version and (ii) add +additional naming elements to distinguish the Modified Version from the +Original Version. The name of such Modified Versions must be the name of +the Original Version, with "derivative X" where X represents the name of +the new work, appended to that name. + +3) The name(s) of the Copyright Holder(s) and any contributor to the +Font Software shall not be used to promote, endorse or advertise any +Modified Version, except (i) as required by this licence, (ii) to +acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with +their explicit written permission. + +4) The Font Software, modified or unmodified, in part or in whole, must +be distributed entirely under this licence, and must not be distributed +under any other licence. The requirement for fonts to remain under this +licence does not affect any document created using the Font Software, +except any version of the Font Software extracted from a document +created using the Font Software may only be distributed under this +licence. + +TERMINATION +This licence becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. + + +Noto Emoji Regular (NotoEmoji-Regular.ttf) is Copyright 2013 Google Inc. All Rights Reserved. It was +designed by the Monotype Design Team and is licensed under the SIL Open Font License 1.1. +The following text is reproduced verbatim from OFL.txt; that file carries no copyright line, so the +copyright notice above is taken from the font's own name table: + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + +The UI's egui-icons.ttf subset and emoji-icon-font.ttf fallback are provided by epaint_default_fonts +and registered through egui's default font definitions. They derive from emoji-icon-font by +John Slegers, under the MIT License. The subset and full face share the following upstream notice. +Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts +Original: https://github.com/jslegers/emoji-icon-font +The following text is reproduced verbatim from emoji-icon-font-mit-license.txt: + +MIT License + +Copyright (c) 2014 John Slegers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 15f8a7d83f..71f30d4c26 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@

+

+ LightCraft icon: an engraved lynx on an amber tile +

+

LightCraft

Your photos. Your pixels. Your machine.

@@ -344,7 +348,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det casual use.** It's great for JPEG/DNG and most Sony / Panasonic / Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera. - **The biggest gaps:** - - **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix; + - **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix; - **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md); - **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and @@ -401,15 +405,26 @@ cargo run --release -p lightcraft -- --control 7980 # with the automation ch cargo xtask web --serve # the same app in the browser: http://127.0.0.1:8080/ cargo run --release -p lightcraft-cli -- render photo.jpg -o out.jpg --set light.exposure=0.5 cargo xtask ci # fmt, clippy, HEIF, tests, parity, layers, assets, WASM +cargo xtask ci --quick # only what your branch's changes can break (minutes) ``` +`cargo xtask ci --quick` compares with the merge base of `origin/main` (`--base REF` for another) +and runs fmt, clippy, the tests of the changed packages, layers and assets, plus HEIF, parity and +the wasm check when the changes touch them; a change to `Cargo.toml`, `Cargo.lock` or the lint +config tests everything. GitHub runs the full `cargo xtask ci` on every pull request +(`.github/workflows/ci.yml`). Only one `ci` runs at a time per machine: a second one, from another +worktree say, waits for the first and names it, since several at once take longer in total than in +turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the lock. + CI defaults to line-table debug information and one build job per 1.5 GB of RAM available when it starts (at most one per CPU; 4 if memory can't be read), so an 8 GB machine with 6 GB free builds with 4, and a busy machine with little free -builds with fewer. Test threads follow, capped at 4. Full-debuginfo linkers, one -per CPU, otherwise exhaust RAM before any test runs. GPU coverage is unchanged. Explicit -`CARGO_PROFILE_DEV_DEBUG`, `CARGO_BUILD_JOBS` and `RUST_TEST_THREADS` settings -override these defaults. Ordinary development commands keep their own settings. +builds with fewer. Test threads follow, capped at 4. +Full-debuginfo linkers, one per CPU, otherwise exhaust RAM before any test runs. GPU coverage is +unchanged. Explicit `CARGO_PROFILE_DEV_DEBUG`, `CARGO_BUILD_JOBS`, `RUST_TEST_THREADS` and +`NEXTEST_TEST_THREADS` settings override these defaults. The tests run under +`cargo test`; `LIGHTCRAFT_NEXTEST=1` runs them under [cargo-nextest](https://nexte.st) instead (one +process per test, slower here because each regenerates the demo scenes). Ordinary development commands keep their own settings. **Release builds on memory-constrained machines:** [#1196](https://github.com/storytold/lightcraft/issues/1196) reports Arch/AUR release-link OOM kills on a 16 GB machine when the desktop and CLI build concurrently diff --git a/README.zh-hans.md b/README.zh-hans.md index 824913f140..2c6ca81916 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -298,18 +298,18 @@ lightcraft --control 7980 ~/Pictures/trip ## Feature status -LightCraft 很年轻,而且进展很快。**我们如实所处的位置**(细节见[路线图](ROADMAP.md#where-we-stand)): +LightCraft 很年轻,而且进展很快。**我们如实所处的位置**(细节见[路线图](ROADMAP.md)): - **按功能数量算,我们达到了约 79%**(核心功能 98%),逐行记录在 - [docs/parity.md](docs/parity.md)。 + [docs/parity-checklist.md](docs/parity-checklist.md)。 - **作为日常使用的工具,我们更接近 60–70%。** 在单台机器上处理 JPEG/DNG 以及大多数尼康/索尼/ 较老佳能的 raw 都很出色。 - **最大的缺口:** - - **相机色彩校准:** 索尼、尼康、松下、富士和佳能 CR3 的 raw 会从各自的相机 JPEG 得到受保护的估计值,内置 ILCA-99M2、ILCE-7CR、ILCE-7M4、X-H2S、X-T4、尼康 Z 6II、Z 8 和 D5300 配置文件;实测校准仍然缺失,其他 raw 或被拒绝的拟合会保留中性矩阵; + - **相机色彩校准:** 索尼、尼康、松下、富士和佳能 CR3 的 raw 会从各自的相机 JPEG 得到受保护的估计值,内置 ILCA-99M2、ILCE-7CR、ILCE-7M4、ILCE-7RM5、X-H2S、X-T4、尼康 Z 6II、Z 8 和 D5300 配置文件;实测校准仍然缺失,其他 raw 或被拒绝的拟合会保留中性矩阵; - **压缩的奥林巴斯 raw 和不受支持的 CR3 变体:** 这些在有内嵌 JPEG 预览时使用预览。富士无损/有损压缩 RAF 现在能解码传感器数据;[验证与已有图库重新加载说明](docs/raf-compression.md); - **AI 蒙版与降噪:** 主体和天空选择目前是经典启发式算法; - **屏幕上的 HDR 显示、视频,以及经典版式中的打印/画册/地图模块。** -- **接下来做什么:** 见[我们要去往哪里](ROADMAP.md#where-were-going)。 +- **接下来做什么:** 见[我们要去往哪里](ROADMAP.md#upcoming)。 | 领域 | 状态 | |---|---| @@ -333,7 +333,7 @@ LightCraft 很年轻,而且进展很快。**我们如实所处的位置**( | 镜头校正(畸变、暗角、自动 + 手动色差、去边、DNG 文件内嵌的镜头校正以及松下/徕卡 RW2/RWL 畸变数据)、几何(变换、限制裁剪)、垂直校正(自动/水平/垂直/完整/引导式) | ✅ · 相机镜头配置文件(我们自己的)⬜ | | 照片合并:HDR(自动对齐、去重影)、全景(球面/圆柱/透视、边界变形、自动裁剪)、HDR 全景 → DNG | ✅ | | GPU 管线(wgpu 计算,与 CPU 一致到 1/255 以内)、设备限制/出错时回退到 CPU | ✅ · 浏览器中的 WebGPU 🚧 | -| AI:分割蒙版、AI 降噪、超分辨率、人脸;视频 | ⬜(见[路线图](ROADMAP.md#where-were-going)) | +| AI:分割蒙版、AI 降噪、超分辨率、人脸;视频 | ⬜(见[路线图](ROADMAP.md#upcoming)) | | 网页版(通过 WASM 在浏览器中使用同一界面):图库持久化在 OPFS/IndexedDB、Web Worker 渲染、导出下载 | ✅ · WebGPU、Safari/Firefox 测试 🚧 | ✅ 现已可用 · 🚧 进行中 · ⬜ 尚未开始 @@ -357,7 +357,7 @@ CI 默认使用行表调试信息,并按启动时可用内存每 1.5 GB 开一 (每个 CPU 最多一个;读不到内存时为 4 个),所以一台 8 GB、空闲 6 GB 的机器会用 4 个任务构建, 而一台空闲内存很少的繁忙机器会用更少。测试线程数随之调整,上限为 4。否则,每个 CPU 一个的 完整调试信息链接器会在任何测试运行之前就耗尽内存。GPU 覆盖范围不变。显式设置 -`CARGO_PROFILE_DEV_DEBUG`、`CARGO_BUILD_JOBS` 和 `RUST_TEST_THREADS` 会覆盖这些默认值。 +`CARGO_PROFILE_DEV_DEBUG`、`CARGO_BUILD_JOBS`、`RUST_TEST_THREADS` 和 `NEXTEST_TEST_THREADS` 会覆盖这些默认值。 日常开发命令保持它们各自的设置。 **内存受限机器上的 release 构建:** [#1196](https://github.com/storytold/lightcraft/issues/1196) diff --git a/README.zh-hant.md b/README.zh-hant.md index a17505f3f4..ca624ce68b 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -320,7 +320,7 @@ LightCraft 還很年輕,而且進展飛快:**Alpha 階段**。**老實說, 在單機上處理 JPEG/DNG,以及大多數 Sony/Panasonic/ Fujifilm/Nikon/較舊款 Canon 的 raw 都很出色;各機型詳情見 [docs/raw-parity.md](docs/raw-parity.md)。 - **最大的缺口:** - - **相機色彩校正:** Sony、Nikon、Panasonic、Fujifilm 和 Canon CR3 的 raw 會從各自的相機 JPEG 得到受保護的估計值,內建 ILCA-99M2、ILCE-7CR、ILCE-7M4、X-H2S、X-T4、Nikon Z 6II、Z 8 和 D5300 描述檔;仍缺少實測校正,其他 raw 或被拒絕的擬合會保留中性矩陣; + - **相機色彩校正:** Sony、Nikon、Panasonic、Fujifilm 和 Canon CR3 的 raw 會從各自的相機 JPEG 得到受保護的估計值,內建 ILCA-99M2、ILCE-7CR、ILCE-7M4、ILCE-7RM5、X-H2S、X-T4、Nikon Z 6II、Z 8 和 D5300 描述檔;仍缺少實測校正,其他 raw 或被拒絕的擬合會保留中性矩陣; - **壓縮的 Olympus raw 與不受支援的 CR3 變體:** 這些在有內嵌 JPEG 預覽時會改用預覽畫面。Fujifilm 無損/有損壓縮 RAF 現在能解碼感光元件資料;[驗證與現有照片庫重新載入說明](docs/raf-compression.md); - **AI 遮色片與降噪:** 主體與天空選取目前是傳統啟發式演算法; - **網路照片庫:** 預覽只讀取 raw 的標頭 — 或者,對於 CR3 或預覽標籤位於其後的 TIFF raw,只讀取稀疏規劃器指定的範圍 — 以及其內嵌的 JPEG(56.5 MB → 5.9 MB,10 秒 → 1 秒,測得於測試用的網路共用資料夾),但*顯影後*的畫面仍需要透過網路傳輸感光元件資料;詳見 [docs/raw-preview-reads.md](docs/raw-preview-reads.md); @@ -375,7 +375,7 @@ CI 預設使用行表除錯資訊,並依啟動時可用記憶體每 1.5 GB 開 (每個 CPU 最多一個;讀不到記憶體時為 4 個),所以一台 8 GB、剩餘 6 GB 可用的機器會用 4 個任務建置, 而一台忙碌、剩餘記憶體很少的機器會用更少。測試執行緒數隨之調整,上限為 4。若不限制,每個 CPU 各跑 一個帶完整除錯資訊的連結器,測試還沒開始記憶體就會耗盡。GPU 測試的涵蓋範圍不受影響。明確設定 -`CARGO_PROFILE_DEV_DEBUG`、`CARGO_BUILD_JOBS` 與 `RUST_TEST_THREADS` 會覆寫這些預設值。 +`CARGO_PROFILE_DEV_DEBUG`、`CARGO_BUILD_JOBS`、`RUST_TEST_THREADS` 與 `NEXTEST_TEST_THREADS` 會覆寫這些預設值。 日常開發指令保留各自的設定。 **記憶體受限機器上的 release 建置:** [#1196](https://github.com/storytold/lightcraft/issues/1196) diff --git a/ROADMAP.md b/ROADMAP.md index ec392e88d3..6802f92342 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~14 points and ~340–600 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in @@ -114,6 +114,11 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ ## Progress log +- 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判 + (89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200), + 六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog + and `print.set` take their customary names, and names are matched case-, space- and + punctuation-insensitively (`L判`, `l`, `L-size` are one paper). - 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277. @@ -121,7 +126,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ RGGB and GBRG, as-shot WB from `WBG`); DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D verified on CC0 files. 551 models verified, 201 preview-only; headline numbers unchanged. - 2026-10-14: 97 Canon CR2, Pentax and Ricoh models verified, one CC0 raw.pixls.us file each pinned and - checked against the camera JPEG (`crates/raw/tests/canon_pentax_corpus.rs`). 334 models verified, ~50% of + checked against the camera JPEG (`crates/raw/tests/it/canon_pentax_corpus.rs`). 334 models verified, ~50% of photographers on a verified body; headline numbers unchanged. - 2026-10-12: Mamiya MEF (ZD) decodes from sensor data and is imported; verified on a CC0 file. 241 models verified, 35 unsupported; headline numbers unchanged. @@ -135,7 +140,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ decode. The EOS R6 Mark III gets its as-shot white balance (`ColorData` 66). 259 models verified; RAW decoding 77% → 83%; mainstream ~49% → ~51%, essentials ~64% → ~65%, full ~61%. - 2026-10-12: 117 Nikon and Fujifilm bodies verified, one CC0 raw.pixls.us file each pinned and checked - against the camera JPEG (`crates/raw/tests/body_corpus.rs`); the sweep found COOLPIX 5700 / 8400 / 8800 + against the camera JPEG (`crates/raw/tests/it/body_corpus.rs`); the sweep found COOLPIX 5700 / 8400 / 8800 decoding wrongly. 354 models verified, ~58% of photographers on a verified body; headline numbers unchanged. - 2026-10-11: Canon EOS R5 Mark II C-RAW decodes from sensor data (57% of its files opened as a preview): the CRX QP map's first-symbol literal and limited-length escape; four CC0 R5 Mark II files @@ -186,6 +191,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged | | 2026-10-19 | minor | Indonesian interface (`id`): every plain and formats message, plus 69 command labels, locale, menu command and tests; What's New left in English; Localization ~55% → ~64% (mean of the 12 key languages), 8 of 12 present | | 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged | | 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged | diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index c8371cbb98..c1f9d258c6 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -819,6 +819,7 @@ fn snapshot(args: &[String]) -> Result<(), String> { let services = lightcraft_ui_egui::Services { write_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)), write: Some(Box::new(lightcraft_engine::export::write_file)), + write_new: Some(Box::new(lightcraft_engine::export::write_file_new)), png: Some(Box::new(|img: &lightcraft_raster::Rgba8| { lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default() })), @@ -935,7 +936,11 @@ fn snapshot(args: &[String]) -> Result<(), String> { fn commands(args: &[String]) -> Result<(), String> { let mut h = Headless::demo(); - let cmds = h.call("engine.commands", json!({}))?; + let mut cmds = h.call("engine.commands", json!({}))?; + // Listed by id so each family (`photo.*`, `mask.*`, …) reads together; the registry keeps its own order. + if let Some(list) = cmds.as_array_mut() { + list.sort_by(|a, b| a["id"].as_str().unwrap_or("").cmp(b["id"].as_str().unwrap_or(""))); + } let mut out = std::io::stdout().lock(); if args.iter().any(|a| a == "--json") { writeln!(out, "{}", serde_json::to_string_pretty(&cmds).unwrap_or_default()).map_err(|e| e.to_string())?; diff --git a/apps/lightcraft-cli/tests/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs similarity index 95% rename from apps/lightcraft-cli/tests/cli.rs rename to apps/lightcraft-cli/tests/it/cli.rs index 8f56bafe66..1c8910d9d8 100644 --- a/apps/lightcraft-cli/tests/cli.rs +++ b/apps/lightcraft-cli/tests/it/cli.rs @@ -286,6 +286,38 @@ fn commands_subcommand_lists_registry() { assert!(String::from_utf8_lossy(&o.stdout).contains("light.exposure")); } +#[test] +fn commands_subcommand_lists_commands_sorted_by_id() { + let o = Command::new(BIN).args(["commands", "--json"]).output().unwrap(); + assert!(o.status.success()); + let v: Value = serde_json::from_slice(&o.stdout).unwrap(); + let cmds = v.as_array().unwrap(); + for c in cmds { + for field in ["id", "label", "menu", "shortcut", "params", "enabled"] { + assert!(c.get(field).is_some(), "every command should keep its {field}: {c}"); + } + } + let ids: Vec<&str> = cmds.iter().filter_map(|c| c["id"].as_str()).collect(); + assert_eq!(ids.len(), cmds.len(), "every command should have a string id"); + let unsorted = ids.windows(2).find(|w| w[0] >= w[1]); + assert!(unsorted.is_none(), "--json should list commands sorted by id, but {unsorted:?} are out of order"); + + let o = Command::new(BIN).arg("commands").output().unwrap(); + assert!(o.status.success()); + let text = String::from_utf8_lossy(&o.stdout); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 2 * ids.len(), "each command should take an id line and a params line"); + let listed: Vec<&str> = lines.iter().step_by(2).filter_map(|l| l.split_whitespace().next()).collect(); + assert_eq!(listed, ids, "the text output should list the same commands in the same order as --json"); + assert!(lines.iter().skip(1).step_by(2).all(|l| l.trim_start().starts_with("params:")), "each id line should be followed by its params line"); + for (line, c) in lines.iter().step_by(2).zip(cmds) { + assert!(line.contains(c["label"].as_str().unwrap()), "{line:?} should show the label of {c}"); + if let Some(sc) = c["shortcut"].as_str() { + assert!(line.contains(&format!("[{sc}]")), "{line:?} should show the shortcut of {c}"); + } + } +} + #[test] fn snapshot_subcommand_renders_the_ui_headlessly() { let script = tmp("snap.jsonl"); diff --git a/apps/lightcraft-cli/tests/it/main.rs b/apps/lightcraft-cli/tests/it/main.rs new file mode 100644 index 0000000000..0c07c64385 --- /dev/null +++ b/apps/lightcraft-cli/tests/it/main.rs @@ -0,0 +1,4 @@ +//! The integration tests, one module per file, linked into one test binary. + +mod cli; +mod mcp_shutdown; diff --git a/apps/lightcraft-cli/tests/mcp_shutdown.rs b/apps/lightcraft-cli/tests/it/mcp_shutdown.rs similarity index 100% rename from apps/lightcraft-cli/tests/mcp_shutdown.rs rename to apps/lightcraft-cli/tests/it/mcp_shutdown.rs diff --git a/apps/lightcraft-web/src/automation.rs b/apps/lightcraft-web/src/automation.rs new file mode 100644 index 0000000000..ff11e0ee9f --- /dev/null +++ b/apps/lightcraft-web/src/automation.rs @@ -0,0 +1,48 @@ +//! The page's automation entry point, `lightcraft.command(id, params)` (see `web.rs`): what the +//! params text means. Plain Rust, so it is tested natively. + +use serde_json::Value; + +/// The command parameters in `text`: a JSON object, or `{}` when the text is empty or blank (or +/// `null`). Anything else is an error, never `{}`: a command run without its params acts on the +/// selection or with defaults, so a typo such as `{ids: [3]}` must not delete or reset the +/// selected photos. The control channel and MCP refuse such params the same way. +pub fn params(text: &str) -> Result { + let text = text.trim(); + if text.is_empty() { + return Ok(Value::Object(Default::default())); + } + match serde_json::from_str::(text) { + Ok(Value::Null) => Ok(Value::Object(Default::default())), + Ok(v @ Value::Object(_)) => Ok(v), + Ok(_) => Err("params must be a JSON object, e.g. {\"ids\": [3]}".into()), + Err(e) => Err(format!("params are not valid JSON ({e}); nothing was run")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn blank_or_null_params_are_an_empty_object() { + for text in ["", " ", "\n", "null", " null "] { + assert_eq!(params(text), Ok(json!({})), "{text:?}"); + } + } + + #[test] + fn an_object_is_passed_through() { + assert_eq!(params(r#"{"ids": [3], "rating": 5}"#), Ok(json!({"ids": [3], "rating": 5}))); + } + + /// Before, any of these ran the command with `{}`: `photo.delete` then removed the selection. + #[test] + fn invalid_json_or_a_non_object_is_refused() { + for text in ["{ids: [3]}", "{\"ids\": [3]", "ids=3", "[3]", "3", "\"{}\"", "true"] { + assert!(params(text).is_err(), "{text:?} must not run the command"); + } + assert!(params("{ids: [3]}").unwrap_err().contains("nothing was run")); + } +} diff --git a/apps/lightcraft-web/src/bench.rs b/apps/lightcraft-web/src/bench.rs index b1b976bfa4..484c0041f6 100644 --- a/apps/lightcraft-web/src/bench.rs +++ b/apps/lightcraft-web/src/bench.rs @@ -39,7 +39,7 @@ pub struct Bench { } impl Bench { - /// `start_ms`: the page's time origin in the same clock as [`lightcraft_ui_egui::now_ms`]. + /// `start_ms`: an origin on the same monotonic clock as [`lightcraft_ui_egui::monotonic_ms`]. pub fn new(start_ms: f64) -> Self { Bench { phase: Phase::Idle, @@ -54,13 +54,16 @@ impl Bench { } } + /// The render key of the main preview texture, or `None` while that slot holds no texture. + /// A changed key means the benchmark's requested main-image render has arrived. fn main_key(app: &LightcraftApp) -> Option { app.renderer.textures.get(&Slot::Main).map(|t| t.key) } - /// Call once per frame after `LightcraftApp::logic`. Returns the report when finished. + /// Call once per root UI pass after `LightcraftApp::ui` (a UI-phase step, never a hidden tick). + /// Returns the report when finished. pub fn step(&mut self, app: &mut LightcraftApp) -> Option { - let now = lightcraft_ui_egui::now_ms(); + let now = lightcraft_ui_egui::monotonic_ms(); self.frames += 1; if self.first_frame_ms.is_none() && self.frames > 1 { self.first_frame_ms = Some(now - self.start_ms); diff --git a/apps/lightcraft-web/src/lib.rs b/apps/lightcraft-web/src/lib.rs index 5ff569fc5e..dfae8b8f39 100644 --- a/apps/lightcraft-web/src/lib.rs +++ b/apps/lightcraft-web/src/lib.rs @@ -18,6 +18,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod automation; pub mod backup; pub mod bench; pub mod files; diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 9cadb301c1..a0f7741857 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -24,7 +24,11 @@ use crate::store::{Originals, content_hash, download_name, storage_key}; use crate::wire::ThumbIndex; use crate::workers::{THUMB_INDEX, Workers}; -const ACCEPT: &str = ".jpg,.jpeg,.png,.tif,.tiff,.webp,.dng,.cr2,.nef,.arw,.psd,.jxl,.gif,.bmp"; +/// The web picker's accept list, derived from the engine's import extensions (both +/// cases) so no format the engine can import is silently filtered out of the dialog. +fn accept_list() -> String { + lightcraft_engine::import::accept_list() +} /// After a failed save, wait this long before trying again (ms). const SAVE_RETRY_MS: f64 = 2000.0; @@ -127,7 +131,7 @@ fn open_picker(originals: Originals, backend: Option, ctx: egui::Contex let Ok(input) = doc.create_element("input").map(|e| e.unchecked_into::()) else { return }; input.set_type("file"); input.set_multiple(true); - input.set_accept(ACCEPT); + input.set_accept(&accept_list()); let inp = input.clone(); let on_change = Closure::::new(move || { if let Some(files) = inp.files() { @@ -168,6 +172,9 @@ fn download(path: &str, bytes: &[u8]) -> Result<(), String> { Ok(()) } +/// Build the browser host's `Services`: library backup/restore through browser storage and a +/// download, asynchronous file picking, downloads for writes, and PNG encoding. Desktop-only +/// services (native pickers, reveal, model folders) stay unset. fn services( originals: Originals, backend: Option, @@ -249,7 +256,12 @@ fn services( save_curve_preset_file: None, pick_slideshow_templates: None, save_slideshow_template: None, + pick_print_templates: None, + save_print_template: None, write: Some(write), + // the browser download path has no meaningful create-new file write; the control channel + // (and therefore screenshot paths) is not available on the web + write_new: None, // downloads happen on the main thread: exports run in the foreground on the web write_shared: None, png: Some(Box::new(|img: &lightcraft_raster::Rgba8| { @@ -292,13 +304,14 @@ async fn flush(files: Files, backend: Backend, dir: String, flushing: Rc, first_frame_logged: bool, + /// The page title last set (`document.title`), so it is written only when it changes. + title: String, last_save: f64, ui_written: Vec, bridge: Option, } impl WebApp { + /// Construct the web app from the boot options: install originals and open the library from + /// browser storage (a read failure starts an empty session and a blocking `LibraryProblem`), + /// load the stored UI state, start render workers and the optional benchmark. fn new(cc: &eframe::CreationContext<'_>, boot: Boot, chinese_font: Vec) -> Self { let Boot { opts, backend, files, index, lib_dir, bridge, load_error } = boot; let originals = Originals::default(); @@ -525,7 +543,7 @@ impl WebApp { log::warn!("lightcraft: the page framing LightCraft could not be told the app is ready"); } } - let origin = lightcraft_ui_egui::now_ms() - perf_now(); + let origin = lightcraft_ui_egui::monotonic_ms(); WebApp { app, originals, @@ -538,6 +556,7 @@ impl WebApp { lib_dir, bench: opts.bench.then(|| Bench::new(origin)), first_frame_logged: false, + title: String::new(), last_save: 0.0, ui_written, bridge, @@ -583,24 +602,41 @@ impl WebApp { self.files.is_dirty() || self.flushing.get() || self.app.session.unsaved().is_some() } + /// Consume the drops the raw-input hook queued once (never re-read `raw.dropped_files` in a + /// hidden logic tick), and add originals whose bytes have arrived. fn import_dropped(&mut self, ctx: &egui::Context) { - let dropped = ctx.input(|i| i.raw.dropped_files.clone()); + let dropped = self.app.take_dropped_files(); + // a dialog is on screen (the card said so while the files hovered): nothing is read or imported + // (files read from an earlier drop still finish below) + if !dropped.is_empty() && self.app.ui.dialog.is_some() { + self.app.toast(ctx, lightcraft_ui_egui::i18n::tr("Close the open dialog, then drop the files again")); + return; + } for f in dropped { let (originals, backend, ctx) = (self.originals.clone(), self.backend.clone(), ctx.clone()); wasm_bindgen_futures::spawn_local(async move { - let name = f.path().to_string_lossy().to_string(); - match f.bytes_async().await { + let name = egui::DroppedFile::path(f.as_ref()).to_string_lossy().to_string(); + match egui::DroppedFile::bytes_async(f.as_ref()).await { Ok(bytes) => store_file(originals, backend, name, bytes, ctx).await, - Err(e) => log::warn!("reading dropped {name}: {e}"), + Err(e) => notice(lightcraft_ui_egui::i18n::dropped_file_unreadable(&name, &e.to_string())), } }); } let paths = self.originals.take_pending(); if !paths.is_empty() { - let n = paths.len(); match self.app.run("library.import", json!({"paths": paths})) { - Ok(_) => self.app.toast(ctx, format!("Added {n} photo{}", if n == 1 { "" } else { "s" })), - Err(e) => log::warn!("import: {e}"), + // what the import did, not what was submitted: duplicates and unsupported files add nothing, + // a drop that only finds duplicates says nothing (as the desktop import's toast does when it + // shows where they are), and one whose files could not be read says so + Ok(report) => { + if let Some(notice) = lightcraft_ui_egui::i18n::dropped_photos_outcome(&report) { + self.app.toast(ctx, notice); + } + } + Err(e) => { + log::warn!("import: {e}"); + self.app.toast(ctx, lightcraft_ui_egui::i18n::dropped_import_failed(&e)); + } } } } @@ -640,7 +676,7 @@ impl WebApp { if self.frozen.get() { return; } - let now = perf_now(); + let now = lightcraft_ui_egui::monotonic_ms(); if now - self.last_save >= SAVE_EVERY_MS { self.last_save = now; self.app.session.save_view(); @@ -716,8 +752,11 @@ impl WebApp { fn run_inbox(&mut self) { let inbox = INBOX.with(|q| std::mem::take(&mut *q.borrow_mut())); for (id, params, (resolve, reject)) in inbox { - let params: serde_json::Value = serde_json::from_str(¶ms).unwrap_or(json!({})); - let r = if id == "web.stats" { Ok(self.web_stats()) } else { self.app.run(&id, params) }; + let r = match crate::automation::params(¶ms) { + Err(e) => Err(format!("{id}: {e}")), + Ok(_) if id == "web.stats" => Ok(self.web_stats()), + Ok(params) => self.app.run(&id, params), + }; let _ = match r { Ok(v) => resolve.call1(&JsValue::NULL, &v.to_string().into()), Err(e) => reject.call1(&JsValue::NULL, &e.into()), @@ -727,14 +766,15 @@ impl WebApp { } impl eframe::App for WebApp { + /// eframe's non-drawing pass for the browser host: drain safety notices and queued inbox work, + /// load originals the UI requested, apply the cache budget, run the app's logic, then save. fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { for text in safety::take_notices() { - let now = ctx.input(|i| i.time); + let now = self.app.tick_now(); self.app.ui.toast = Some((text, now + NOTICE_SECS, None)); } self.run_inbox(); self.run_host(ctx); - self.import_dropped(ctx); self.load_originals(ctx); if let Some(w) = &self.workers { // `library.preferences ▸ cacheMb` is read by the session; the worker index prunes on @@ -746,27 +786,49 @@ impl eframe::App for WebApp { if let Some(b) = &self.bridge { b.report_dirty(self.dirty_for_host()); } - if let Some(b) = self.bench.as_mut() - && let Some(report) = b.step(&mut self.app) - { - log::info!("lightcraft-bench {report}"); - if let Some((alive, ready, remote, inline)) = self.workers.as_ref().map(Workers::stats) { - log::info!("lightcraft-workers {{\"alive\":{alive},\"ready\":{ready},\"remote_jobs\":{remote},\"inline_jobs\":{inline}}}"); - } - set_status(&format!("bench: {report}")); - self.bench = None; - } - if self.bench.is_some() { - ctx.request_repaint(); - } } - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { - self.app.raw_input_hook(raw); + /// Pass the browser's raw input to the app hook before egui processes it, so prompt barriers + /// and synthetic or dropped input are applied consistently with the desktop host. + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + self.app.raw_input_hook(ctx, raw); } + /// eframe's UI pass: import queued drops unless a prompt blocks input, draw the app, update the + /// page title, and advance the benchmark once per root pass. fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + // Drops are the UI phase's: a hidden `logic`/`run_logic` tick must not import them twice. + // A prompt owns the library too: keep taking the queue only after it is gone, so a drop + // during a notice cannot add photos behind it. + let ctx = ui.ctx().clone(); + if !lightcraft_ui_egui::panels::notices::blocks_input(&self.app) { + self.import_dropped(&ctx); + } self.app.ui(ui); + // eframe's web runner ignores `ViewportCommand::Title`: name the open photo in the page title + let title = self.app.page_title(self.files.is_dirty() || self.flushing.get()); + if title != self.title + && let Some(doc) = window().and_then(|w| w.document()) + { + doc.set_title(&title); + self.title = title; + } + // The benchmark is a UI-phase step: a second layout pass or a hidden tick must not count a frame. + if ui.ctx().current_pass_index() == 0 { + if let Some(b) = self.bench.as_mut() + && let Some(report) = b.step(&mut self.app) + { + log::info!("lightcraft-bench {report}"); + if let Some((alive, ready, remote, inline)) = self.workers.as_ref().map(Workers::stats) { + log::info!("lightcraft-workers {{\"alive\":{alive},\"ready\":{ready},\"remote_jobs\":{remote},\"inline_jobs\":{inline}}}"); + } + set_status(&format!("bench: {report}")); + self.bench = None; + } + if self.bench.is_some() { + ctx.request_repaint(); + } + } if !self.first_frame_logged && !self.app.widgets.is_empty() { self.first_frame_logged = true; log::info!("lightcraft first UI frame at {:.0} ms after navigation start", perf_now()); diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 08f9e898d3..53d389b6f7 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -522,7 +522,7 @@ mod tests { } }; frame(&mut watch, &mut index); // an empty filtered view: no render request yet - cache.clear(); // File ▸ Clear Preview Cache + cache.clear(); // File ▸ Discard Preview Cache frame(&mut watch, &mut index); // the filter is removed: the first thumbnail request (`Workers::try_start`) gone.extend(watch.observe(&cache, cache.generation(), &mut index)); diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index 95e080974f..d00bc41e99 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -23,7 +23,9 @@ lightcraft-sysmem = { workspace = true } lightcraft-ui-egui = { workspace = true } lightcraft-codecs = { workspace = true } lightcraft-raster = { workspace = true } -eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11"] } +# `clipboard` is a separate eframe feature in 0.37: without it egui-winit simulates an in-process +# clipboard and cut/copy/paste, RequestPaste and the Wayland PRIMARY path are unavailable. +eframe = { workspace = true, features = ["default_fonts", "clipboard", "wgpu", "glow", "accesskit", "wayland", "x11"] } egui = { workspace = true } serde_json = { workspace = true } chrono = { workspace = true } @@ -53,3 +55,6 @@ objc2-foundation = { workspace = true } [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } + +[target.'cfg(windows)'.dependencies] +craft-update = { workspace = true } diff --git a/apps/lightcraft/src/control_server.rs b/apps/lightcraft/src/control_server.rs index 7778319429..95aa108964 100644 --- a/apps/lightcraft/src/control_server.rs +++ b/apps/lightcraft/src/control_server.rs @@ -240,11 +240,17 @@ mod tests { } impl Connection { - fn new(open: &Arc, idle: Duration) -> Self { + /// `before` acts on the client before the worker starts reading, so what it sends is + /// already there however late this thread gets scheduled. + fn new(open: &Arc, idle: Duration, before: impl FnOnce(&mut TcpStream)) -> Self { let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); client.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); let (stream, _) = listener.accept().unwrap(); + // Small test messages must not wait for Nagle's algorithm or a delayed ACK. + client.set_nodelay(true).unwrap(); + stream.set_nodelay(true).unwrap(); + before(&mut client); let (tx, requests) = channel(); let worker = spawn_connection(stream, tx, egui::Context::default(), Arc::clone(open), idle).unwrap(); Self { client: BufReader::new(client), requests, worker: Some(worker) } @@ -271,9 +277,8 @@ mod tests { fn idle_connections_release_their_slots_without_dispatching() { for input in ["", "{\"method\":\"engine.execute\""] { let open = Arc::new(AtomicUsize::new(0)); - let mut connection = Connection::new(&open, Duration::from_millis(100)); + let mut connection = Connection::new(&open, Duration::from_millis(100), |c| c.write_all(input.as_bytes()).unwrap()); assert_eq!(open.load(Ordering::SeqCst), 1); - connection.client.get_mut().write_all(input.as_bytes()).unwrap(); let mut reply = String::new(); let closed = connection.client.read_to_string(&mut reply); assert!(closed.is_ok(), "idle connection stayed open: {closed:?}"); @@ -285,8 +290,7 @@ mod tests { assert!(reply["error"].as_str().unwrap().contains("idle read timed out")); // A subsequent connection is admitted through the same accounting path. - let mut next = Connection::new(&open, Duration::from_secs(1)); - next.client.get_mut().shutdown(std::net::Shutdown::Write).unwrap(); + let mut next = Connection::new(&open, Duration::from_secs(1), |c| c.shutdown(std::net::Shutdown::Write).unwrap()); let mut eof = String::new(); next.client.read_to_string(&mut eof).unwrap(); next.join(); @@ -298,21 +302,32 @@ mod tests { #[test] fn persistent_requests_and_slow_replies_outlive_the_idle_read_timeout() { let open = Arc::new(AtomicUsize::new(0)); - let mut connection = Connection::new(&open, Duration::from_millis(100)); + let request = |id: u64| format!("{}\n", json!({"id": id, "method": "engine.commands"})); + // Each request reaches the socket before the worker reads it (the next one while the worker + // waits for the reply), so only the reply waits outlast the idle timeout, however slowly + // this thread runs. + let mut connection = Connection::new(&open, Duration::from_millis(100), |c| c.write_all(request(1).as_bytes()).unwrap()); for id in [1, 2] { - writeln!(connection.client.get_mut(), "{}", json!({"id": id, "method": "engine.commands"})).unwrap(); - let req = connection.requests.recv_timeout(Duration::from_secs(3)).unwrap(); + let req = connection.requests.recv_timeout(Duration::from_secs(10)).unwrap(); assert_eq!(req.method, "engine.commands"); assert!(req.take()); + if id == 1 { + connection.client.get_mut().write_all(request(2).as_bytes()).unwrap(); + } else { + connection.client.get_mut().shutdown(std::net::Shutdown::Write).unwrap(); + } // A dispatched command waits for its reply, not for socket input. std::thread::sleep(Duration::from_millis(250)); req.reply.send(json!({"ok": true, "result": id})).unwrap(); + if id == 2 { + // The worker must reach EOF even before the client reads its final reply. + connection.join(); + } let mut reply = String::new(); connection.client.read_line(&mut reply).unwrap(); let reply: Value = serde_json::from_str(&reply).unwrap(); assert_eq!(reply, json!({"id": id, "ok": true, "result": id})); } - connection.client.get_mut().shutdown(std::net::Shutdown::Write).unwrap(); let mut eof = String::new(); connection.client.read_to_string(&mut eof).unwrap(); connection.join(); @@ -327,7 +342,8 @@ mod tests { let (req, rrx) = ControlRequest::new("ui.inspect", json!({})); let t0 = std::time::Instant::now(); let r = await_reply(&rrx, &req.state, || 7, || {}, Duration::from_millis(50), Duration::from_secs(10)); - assert!(t0.elapsed() < Duration::from_secs(2)); + // the frame window (50 ms), not the 10 s timeout; the margin is for a slow machine + assert!(t0.elapsed() < Duration::from_secs(5), "{:?}", t0.elapsed()); assert_eq!(r["ok"], false); assert!(r["error"].as_str().unwrap().contains("not visible"), "{r}"); assert!(!req.take(), "the app does not run it once it shows up"); diff --git a/apps/lightcraft/src/editors.rs b/apps/lightcraft/src/editors.rs index cf6d660797..3ca748f473 100644 --- a/apps/lightcraft/src/editors.rs +++ b/apps/lightcraft/src/editors.rs @@ -31,22 +31,14 @@ pub fn check(app: &str) -> Result<(), String> { /// Open `path` in `app` (see [`check`]). Spawned, never waited for: the editor runs alongside. pub fn open_with(path: &str, app: &str) -> Result<(), String> { let mut c = match launcher(app)? { - Launcher::Default if cfg!(target_os = "macos") => { - let mut c = Command::new("open"); - c.arg(path); - c - } + Launcher::Default if cfg!(target_os = "macos") => return run_open(&[path]), Launcher::Default if cfg!(target_os = "windows") => windows_default_command(path), Launcher::Default => { let mut c = Command::new("xdg-open"); c.arg(path); c } - Launcher::MacApp(app) => { - let mut c = Command::new("open"); - c.args(["-a", &app, path]); - c - } + Launcher::MacApp(app) => return run_open(&["-a", &app, path]), Launcher::Program(p) => { let mut c = Command::new(p); c.arg(path); @@ -61,6 +53,22 @@ pub fn open_with(path: &str, app: &str) -> Result<(), String> { c.spawn().map(|_| ()).map_err(|e| e.to_string()) } +/// macOS: run `open` and wait for it (it returns as soon as LaunchServices has handed the file +/// over), so an application it can't find or start is reported instead of silently doing nothing. +fn run_open(args: &[&str]) -> Result<(), String> { + let out = Command::new("open").args(args).output().map_err(|e| e.to_string())?; + open_result(out.status.success(), &String::from_utf8_lossy(&out.stderr)) +} + +/// What `open` said, as a result: its own message when it failed. +fn open_result(ok: bool, stderr: &str) -> Result<(), String> { + if ok { + return Ok(()); + } + let msg = stderr.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("the application couldn't be started"); + Err(msg.to_string()) +} + /// Open every file in `paths` with one start of `app`, as a file manager hands over a selection: /// an editor that keeps a single window (DxO PhotoLab) loses the files that arrive while it is /// still starting when it is started once per file. The system default opens them one by one @@ -119,10 +127,15 @@ fn launcher(app: &str) -> Result { fn find_photocraft() -> Option { let env = |k: &str| std::env::var_os(k).map(|v| v.to_string_lossy().to_string()); if cfg!(target_os = "macos") { - // LaunchServices finds the app wherever it is; these are only the usual places + // the usual places, then wherever Spotlight knows it (by bundle id or bundle name) let home = env("HOME").map(|h| Path::new(&h).join("Applications/PhotoCraft.app")); - let found = [Some(PathBuf::from("/Applications/PhotoCraft.app")), home].into_iter().flatten().find(|p| p.is_dir()); - return Some(Launcher::MacApp(found.map_or_else(|| PHOTOCRAFT.to_string(), |p| p.to_string_lossy().to_string()))); + let usual = [Some(PathBuf::from("/Applications/PhotoCraft.app")), home].into_iter().flatten().find(|p| p.is_dir()); + let spotlight = || { + let query = format!("kMDItemCFBundleIdentifier == '{PHOTOCRAFT_ID}' || kMDItemFSName == 'PhotoCraft.app'"); + let out = Command::new("mdfind").arg(query).output().ok().filter(|o| o.status.success())?; + mdfind_app(&String::from_utf8_lossy(&out.stdout)) + }; + return usual.or_else(spotlight).map(|p| Launcher::MacApp(p.to_string_lossy().to_string())); } if cfg!(target_os = "windows") { let install_dir = reg_query(r"HKLM\Software\PhotoCraft", Some("InstallDir")); @@ -130,16 +143,34 @@ fn find_photocraft() -> Option { return windows_candidates(install_dir, app_path, env).into_iter().find(|p| p.is_file()).map(Launcher::Program); } // Linux, FreeBSD: on the PATH (.deb, .rpm, tarball), a desktop entry (AppImage, which - // registers one on first run), else the Flatpak - let on_path = - env("PATH").into_iter().flat_map(|p| std::env::split_paths(&p).collect::>()).map(|d| d.join("photocraft")).find(|p| p.is_file()); + // registers one on first run; its Exec a path or a name on the PATH), an AppImage where people + // keep them, else the Flatpak + let path_dirs: Vec = env("PATH").into_iter().flat_map(|p| std::env::split_paths(&p).collect::>()).collect(); + let on_path = |name: &Path| resolve_program(name, &path_dirs); let from_entry = || { desktop_entry_dirs(env).into_iter().find_map(|d| { let text = std::fs::read_to_string(d.join(format!("{PHOTOCRAFT_ID}.desktop"))).ok()?; - desktop_exec(&text).filter(|p| p.is_file()) + desktop_exec(&text) + // a wrapper (`Exec=env VAR=1 /opt/PhotoCraft/photocraft %F`) would be started with the photo only: + // skip it and look further + .filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().to_lowercase().contains("photocraft"))) + .and_then(|p| on_path(&p)) }) }; - if let Some(p) = on_path.or_else(from_entry) { + let appimage = || { + let home = env("HOME")?; + let dirs = [Path::new(&home).join("Applications"), Path::new(&home).join(".local/bin")]; + // both folders, so the newest version wins whichever it is in + let mut found: Vec = dirs + .iter() + .filter_map(|d| std::fs::read_dir(d).ok()) + .flat_map(|rd| rd.flatten().map(|e| e.path()).filter(|p| is_photocraft_appimage(p) && p.is_file()).collect::>()) + .collect(); + // the newest version by name (1.10 after 1.9) + found.sort_by_key(|p| version_key(&p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default())); + found.pop() + }; + if let Some(p) = on_path(Path::new("photocraft")).or_else(from_entry).or_else(appimage) { return Some(Launcher::Program(p)); } let flatpak = Command::new("flatpak").args(["info", PHOTOCRAFT_ID]).output().is_ok_and(|o| o.status.success()); @@ -205,10 +236,44 @@ fn desktop_exec(entry: &str) -> Option { Some(rest) => rest.split('"').next()?, None => exec.split_whitespace().next()?, }; - // a bare name (`photocraft %F`) was already looked for on the PATH. Desktop entries are a - // freedesktop (POSIX) format: absolute means a leading `/` on every platform the parser runs on - // (`Path::is_absolute` wants a drive letter on Windows, where the tests run too) - program.starts_with('/').then(|| PathBuf::from(program)) + // a path, or a bare name (`photocraft %F`) the caller looks for on the PATH + (!program.is_empty()).then(|| PathBuf::from(program)) +} + +/// A program from a desktop entry or the PATH: a path as it is (if it is a file), a bare name +/// looked for in `dirs`. A leading `/` counts as absolute on every platform (desktop entries are +/// a POSIX format; `Path::is_absolute` wants a drive letter on Windows, where the tests run too). +fn resolve_program(name: &Path, dirs: &[PathBuf]) -> Option { + if name.is_absolute() || name.starts_with("/") { + return Some(name.to_path_buf()).filter(|p| p.is_file()); + } + dirs.iter().map(|d| d.join(name)).find(|p| p.is_file()) +} + +/// A sort key that orders the digit runs in a name by value (`1.9` before `1.10`). +fn version_key(name: &str) -> Vec<(u64, String)> { + let mut out = Vec::new(); + let mut rest = name; + while !rest.is_empty() { + let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len(); + let (num, tail) = rest.split_at(digits); + let text_len = tail.find(|c: char| c.is_ascii_digit()).unwrap_or(tail.len()); + let (text, next) = tail.split_at(text_len); + out.push((num.parse().unwrap_or(u64::MAX), text.to_string())); + rest = next; + } + out +} + +/// An AppImage of PhotoCraft by its file name (`PhotoCraft-1.2-x86_64.AppImage`, any case). +fn is_photocraft_appimage(p: &Path) -> bool { + let name = p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default(); + name.contains("photocraft") && name.ends_with(".appimage") +} + +/// The first application bundle in `mdfind` output (one path per line). +fn mdfind_app(output: &str) -> Option { + output.lines().map(str::trim).find(|l| l.ends_with(".app")).map(PathBuf::from) } #[cfg(test)] @@ -275,13 +340,59 @@ mod tests { let appimage = "[Desktop Entry]\nName=PhotoCraft\nExec=\"/home/simon/Apps/photocraft-1.2-linux-x86_64.AppImage\" %F\n"; assert_eq!(desktop_exec(appimage), Some(PathBuf::from("/home/simon/Apps/photocraft-1.2-linux-x86_64.AppImage"))); assert_eq!(desktop_exec("Exec=/opt/photocraft/photocraft %F\n"), Some(PathBuf::from("/opt/photocraft/photocraft"))); - assert_eq!(desktop_exec("Exec=photocraft %F\nTryExec=photocraft\n"), None, "a bare name is a PATH lookup"); + assert_eq!(desktop_exec("Exec=photocraft %F\nTryExec=photocraft\n"), Some(PathBuf::from("photocraft")), "a bare name, for a PATH lookup"); assert_eq!(desktop_exec("[Desktop Entry]\n"), None); let dirs = desktop_entry_dirs(|k| (k == "HOME").then(|| "/home/simon".to_string())); assert_eq!(dirs[0], PathBuf::from("/home/simon/.local/share/applications")); assert!(dirs.contains(&PathBuf::from("/usr/share/applications"))); } + #[test] + fn a_bare_exec_name_is_found_on_the_path() { + let a = std::env::temp_dir().join(format!("lc-editors-a-{}", std::process::id())); + let b = std::env::temp_dir().join(format!("lc-editors-b-{}", std::process::id())); + std::fs::create_dir_all(&a).unwrap(); + std::fs::create_dir_all(&b).unwrap(); + std::fs::write(b.join("photocraft"), b"").unwrap(); + let dirs = vec![a.clone(), b.clone()]; + assert_eq!(resolve_program(Path::new("photocraft"), &dirs), Some(b.join("photocraft"))); + assert_eq!(resolve_program(Path::new("nothere"), &dirs), None); + let abs = b.join("photocraft"); + assert_eq!(resolve_program(&abs, &[]), Some(abs.clone()), "a path needs no PATH"); + assert_eq!(resolve_program(&b.join("missing"), &dirs), None); + let _ = std::fs::remove_dir_all(&a); + let _ = std::fs::remove_dir_all(&b); + } + + #[test] + fn appimage_versions_sort_numerically() { + let mut names = ["photocraft-1.10-x86_64.appimage", "photocraft-1.9-x86_64.appimage", "photocraft-1.2-x86_64.appimage"]; + names.sort_by_key(|n| version_key(n)); + assert_eq!(names[2], "photocraft-1.10-x86_64.appimage"); + assert_eq!(names[0], "photocraft-1.2-x86_64.appimage"); + } + + #[test] + fn a_failed_open_is_an_error() { + assert!(open_result(true, "").is_ok()); + assert!(open_result(false, "Unable to find application\n").is_err()); + assert!(open_result(false, "").is_err(), "even when it says nothing"); + } + + #[test] + fn odd_detection_input_does_not_panic() { + for text in ["", "Exec=", "Exec=\"", "Exec=\"\"", "\u{0}\u{fffd}", "Exec= %F", "[Desktop Entry]\nExec=\u{e9}\u{301}"] { + let _ = desktop_exec(text); + let _ = mdfind_app(text); + let _ = reg_value(text); + } + for p in ["", "/", ".AppImage", "\u{e9}.appimage", "a/../b"] { + let _ = is_photocraft_appimage(Path::new(p)); + } + let _ = desktop_entry_dirs(|_| None); + let _ = windows_candidates(None, Some("\"".into()), |_| None); + } + #[test] fn other_editors_are_used_as_named() { assert_eq!(launcher("").unwrap(), Launcher::Default); diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 95739b3e97..815fbd70f2 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -3,8 +3,10 @@ //! Usage: `lightcraft [--library DIR | --memory] [--no-demo] [--control ] [files or folders…]` //! //! The library (catalog, presets, thumbnail cache) lives in `--library DIR`, else -//! `$LIGHTCRAFT_LIBRARY`, else the library last opened with Settings → Open Library…, else -//! `~/Pictures/LightCraft Library`; a new library starts with the +//! `$LIGHTCRAFT_LIBRARY`, else — with Settings ▸ General ▸ At launch set to *Ask me*, or Alt/Option +//! held as the window appears — the one chosen in a list of the recent libraries, else the library +//! last opened, else `~/Pictures/LightCraft Library` +//! ([`lightcraft_ui_egui::panels::library_problem::launch_plan`]); a new library starts with the //! procedural demo photos unless `--no-demo` or files are given. Files and folders on the command //! line are imported (duplicates are skipped). `--memory` runs an in-memory session that writes //! nothing (demo photos unless files are given; used by the README showcase scripts). A library @@ -39,7 +41,7 @@ mod window_gpu; use dialog_filter::FileDialogExt as _; use lightcraft_engine::Session; -use lightcraft_ui_egui::panels::library_problem::LibraryProblem; +use lightcraft_ui_egui::panels::library_problem::{Launch, LibraryProblem}; use lightcraft_ui_egui::{LightcraftApp, Services, UiState}; /// Reverse-DNS app id: Wayland app id, `.desktop` file and hicolor icon name. @@ -73,8 +75,10 @@ impl eframe::App for App { self.0.logic(ctx); self.1.tick(&mut self.0, ctx); } - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { - self.0.raw_input_hook(raw); + /// Forwards the host's raw-input pass to the app's hook before egui processes it, keeping + /// modal/prompt input barriers and queued synthetic or dropped input ahead of the panels. + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + self.0.raw_input_hook(ctx, raw); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0); @@ -363,7 +367,7 @@ struct PrefsWriter { impl PrefsWriter { fn save(&mut self, app: &LightcraftApp) -> Result<(), String> { - self.save_ui(&app.ui, app.library_problem.is_some()) + self.save_ui(&app.ui, app.library_problem.as_ref().is_some_and(LibraryProblem::saves_nothing)) } /// Write `ui` if it changed since the last write; `temporary` (the library couldn't be @@ -402,15 +406,26 @@ impl PrefsWriter { } } + /// Per-frame host tick: records the window's placement while visible, asks for a repaint when + /// a remembered size is due, and saves settings/library at most every three seconds or + /// immediately after the library path changes; a failed save is reported once and retried. fn tick(&mut self, app: &mut LightcraftApp, ctx: &egui::Context) { // (asked for before the input is read: the context is not asked from inside its own lock) let zoom = ctx.zoom_factor(); - let (now, seen) = ctx.input(|i| (i.time, lightcraft_ui_egui::window_place::Seen::of(i.viewport(), i.content_rect(), zoom))); + // The monotonic app clock: `i.time` stands still while the window is hidden. + let now = app.tick_now(); + let (hidden, seen) = ctx.input(|i| { + let hidden = i.viewport().visible() == Some(false); + (hidden, lightcraft_ui_egui::window_place::Seen::of(i.viewport(), i.content_rect(), zoom)) + }); // how the window is, to open like that next time (written with the settings below). What - // the settings hold is checked first: a script may have set it (`ui.set`) + // the settings hold is checked first: a script may have set it (`ui.set`). A hidden + // `run_logic` pass has no fresh content rect: keep the last known placement. let remembered = app.ui.window.and_then(lightcraft_ui_egui::window_place::WindowPlace::checked); let at = self.window_since.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64(); - app.ui.window = self.window.note(remembered, &seen, at); + if !hidden { + app.ui.window = self.window.note(remembered, &seen, at); + } if let Some(wait) = self.window.waits(at) { // (a size is only remembered once the window has rested at it: look again then, though // nothing else asks for a frame) @@ -704,9 +719,28 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> .save_file() .map(|p| p.to_string_lossy().to_string()) })), + pick_print_templates: Some(Box::new(|| { + file_dialog() + .set_title(lightcraft_ui_egui::i18n::tr("Import Print Templates")) + .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Print Templates"), &[lightcraft_engine::print::template::FILE_EXT]) + .pick_files() + .unwrap_or_default() + .into_iter() + .map(|p| p.to_string_lossy().to_string()) + .collect() + })), + save_print_template: Some(Box::new(|name: &str| { + file_dialog() + .set_title(lightcraft_ui_egui::i18n::tr("Export Print Template")) + .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Print Templates"), &[lightcraft_engine::print::template::FILE_EXT]) + .set_file_name(name) + .save_file() + .map(|p| p.to_string_lossy().to_string()) + })), // atomic (temp file + sync + rename): a failed write never leaves a truncated file write_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)), write: Some(Box::new(lightcraft_engine::export::write_file)), + write_new: Some(Box::new(lightcraft_engine::export::write_file_new)), png: Some(Box::new(|img: &lightcraft_raster::Rgba8| { lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default() })), @@ -718,9 +752,13 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> } /// The library session with the folders face models (`/models`) and slideshow templates -/// (`/slideshow-templates`) are kept in. -fn open_session(in_memory: bool, dir: Option, seed_demo: bool) -> (Session, Option) { - let (mut s, problem) = open_library_session(in_memory, dir, seed_demo); +/// (`/slideshow-templates`) are kept in. With [`Launch::Ask`] no library is opened yet: +/// the window lists the recent ones. +fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> (Session, Option) { + let (mut s, problem) = match launch { + Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None), + Launch::Open { dir, .. } => open_library_session(in_memory, dir.clone(), seed_demo), + }; s.face_models_dir = lightcraft_engine::config::default_face_models_dir(); s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME)); // Control requests are answered on the UI thread: Add to Apple Photos must not wait there @@ -769,7 +807,9 @@ lightcraft — photo library + raw developer USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported) OPTIONS: - --library DIR open (or create) this library (default: ~/Pictures/LightCraft Library; env LIGHTCRAFT_LIBRARY) + --library DIR open (or create) this library (env LIGHTCRAFT_LIBRARY; default: the last library opened, or + a list of the recent ones with Settings > General > At launch: Ask me or Alt/Option held, + else ~/Pictures/LightCraft Library) --no-demo don't seed a new library with the procedural demo photos --memory throwaway in-memory session (alias --demo); nothing is saved --control PORT serve the JSON-lines control channel on 127.0.0.1:PORT (env LIGHTCRAFT_CONTROL_PORT; @@ -841,6 +881,11 @@ fn panic_log_path_with(env: impl Fn(&str) -> Option, temp: s } fn main() -> eframe::Result { + // Windows: the update helper is a copy of this program started with `--finish-update`. + #[cfg(windows)] + if let Some(result) = craft_update::self_update::finish(&craft_update::suite::LIGHTCRAFT, &std::env::args_os().skip(1).collect::>()) { + std::process::exit(i32::from(result.is_err())); + } // First, so every start-up record is kept for the log file (`logging`). let logger = logging::install(); lightcraft_engine::guard::install_hook(panic_log_path_with(|name| std::env::var_os(name), std::env::temp_dir())); @@ -900,15 +945,15 @@ fn main() -> eframe::Result { if let Some(ui) = &prefs { lightcraft_ui_egui::i18n::set_language(ui.language); } - // --library, else the library last opened from Settings, else the default location - let library_dir = library_dir.or_else(|| { - prefs - .as_ref() - .map(|u| u.settings.library_path.clone()) - .filter(|p| !p.is_empty() && std::env::var_os("LIGHTCRAFT_LIBRARY").is_none()) - .map(Into::into) - }); - let library_dir = library_dir.or_else(lightcraft_engine::library::default_dir); + // --library, else LIGHTCRAFT_LIBRARY, else the list of recent libraries if Settings say Ask + // me, else the library last opened from Settings, else the default location + let launch = lightcraft_ui_egui::panels::library_problem::launch_plan( + in_memory, + library_dir, + std::env::var_os("LIGHTCRAFT_LIBRARY").filter(|p| !p.is_empty()).map(Into::into), + prefs.as_ref().map(|u| &u.settings), + lightcraft_engine::library::default_dir(), + ); // GPU compute: off if the preference says so, or if the last launch died creating the device // (issue #136) — before anything can create it let gpu_crash = gpu_crash_check(in_memory).or_else(|| gpu_lost_check_at(gpu_lost_marker_path().as_deref(), in_memory)); @@ -961,7 +1006,7 @@ fn main() -> eframe::Result { // the window's renderer is up (eframe calls this after creating it) win_files_app.started(window_renderer); came_up_app.store(true, std::sync::atomic::Ordering::Relaxed); - let (mut session, problem) = open_session(in_memory, library_dir, seed_demo && files.is_empty()); + let (mut session, mut problem) = open_session(in_memory, &launch, seed_demo && files.is_empty()); // AI masks: the SAM 3 checkpoint (facebook/sam3) in /models/sam3, or LIGHTCRAFT_SAM3_DIR // (never required: without it, AI masks offer to download it; see docs/ai-masks.md) // and the user's own download locations, one base URL per line (LIGHTCRAFT_SAM3_MIRRORS too) @@ -969,9 +1014,15 @@ fn main() -> eframe::Result { // HDR display: SDR unless the surface, platform and display all allow HDR hdr_display::report(cc.wgpu_render_state.as_ref().map(|r| r.target_format)); let mut app = LightcraftApp::new(session, services(cc, app_log_file.as_deref())); + app.set_startup_update_check(true); if let Some(ui) = prefs { app.ui = ui; } + // the recent libraries to choose from (issue #1290), checked on a worker once shown + if launch == Launch::Ask { + problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + } + app.alt_asks_for_library = matches!(launch, Launch::Open { alt_asks: true, .. }); lightcraft_ui_egui::i18n::set_language(app.ui.language); app.integrated_titlebar = cfg!(target_os = "macos"); app.notices.extend(prefs_warning); @@ -1145,12 +1196,40 @@ mod tests { /// adds to Apple Photos on a worker (headless sessions wait instead). #[test] fn the_desktop_session_adds_to_apple_photos_in_the_background() { - let (s, problem) = open_session(true, None, false); + let (s, problem) = open_session(true, &Launch::Open { dir: None, alt_asks: false }, false); assert!(problem.is_none()); assert!(s.apple_photos_background); assert!(!lightcraft_engine::Session::new().apple_photos_background); } + /// Issue #1290: with Settings ▸ At launch ▸ Ask me nothing is opened (nor seeded with demo + /// photos) before the user chooses, and the settings are still saved while the list shows (a + /// removed entry is kept), unlike the failed-library window's temporary session. + #[test] + fn asking_at_launch_opens_nothing_and_still_saves_the_settings() { + let (s, problem) = open_session(false, &Launch::Ask, true); + assert!(problem.is_none() && s.library.is_none() && s.catalog.is_empty()); + assert!(s.apple_photos_background, "the same desktop session as an opened one"); + + let d = dir("writer-ask"); + let path = d.join("ui.json"); + let mut app = LightcraftApp::new(s, Services::default()); + app.ui.settings.recent_libraries = vec!["/gone/a".into(), "/gone/b".into()]; + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut w = PrefsWriter { path: Some(path.clone()), ..Default::default() }; + app.ui.settings.recent_libraries.remove(0); + w.save(&app).unwrap(); + let saved: UiState = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved.settings.recent_libraries, ["/gone/b"]); + // the failed-library window still writes nothing + app.library_problem = Some(LibraryProblem::new("/gone/b", "not there")); + app.ui.settings.recent_libraries.clear(); + w.save(&app).unwrap(); + let saved: UiState = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved.settings.recent_libraries, ["/gone/b"]); + let _ = std::fs::remove_dir_all(&d); + } + /// Issue #103: a damaged ui.json (which holds the library location) is kept aside and /// reported, not silently replaced by the defaults. #[test] diff --git a/apps/lightcraft/src/native_menu.rs b/apps/lightcraft/src/native_menu.rs index 4ac40bcacb..a5a14e2088 100644 --- a/apps/lightcraft/src/native_menu.rs +++ b/apps/lightcraft/src/native_menu.rs @@ -11,12 +11,19 @@ //! - while a text field has keyboard focus, accelerators without ⌘ (`G`, `1`, `Delete`…) and the //! text-editing ones (⌘A/⌘C/⌘V/⌘X/⌘Z) are removed, so typing and text editing work; they come //! back when the field loses focus. +//! +//! Menu events never pass through the egui shortcut handler. [`NativeMenu::update`] therefore runs +//! every queued command through [`lightcraft_ui_egui::menubar::run_native_command`]: while the +//! blocking library window or a quit/settings notice owns input it drops the command (Settings… +//! and About included), and only Quit stays available for the host's existing confirmation. use std::collections::{HashMap, HashSet}; use std::sync::mpsc::{Receiver, channel}; use lightcraft_ui_egui::LightcraftApp; -use lightcraft_ui_egui::menubar::{MenuNode, menu_bar}; +use lightcraft_ui_egui::menubar::{ + MenuNode, menu_bar, native_item_presentation, native_menu_delivers as menu_delivers, native_menu_structure as structure_of, +}; use muda::accelerator::{Accelerator, Code, Modifiers}; use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu}; use serde_json::Value; @@ -39,18 +46,140 @@ enum Handle { struct Item { handle: Handle, + /// The submenu the item sits in, to swap the item when its accelerator has to go (macOS). + parent: Submenu, cmd: String, params: Value, shortcut: Option, + /// The accelerator the item's shortcut maps to. accel: Option, + /// The accelerator the native item has now: `accel`, or `None` while it yields. + current: Option, label: String, enabled: bool, checked: Option, + /// Whether the item may be replaced to drop its key. Not in the Help menu: a swap there left + /// the old row and added a second one (muda 0.21, macOS 27), so those keys stay. + swappable: bool, +} + +impl Item { + /// The row's text as installed: `label` is already what the row shows (translated, with a + /// borrowed key's hint, `native_item_presentation`). + fn native_label(&self) -> String { + self.label.replace('&', "&&") + } + + /// Puts `want` on the native item. muda's `set_accelerator(None)` does nothing on macOS (the + /// old key equivalent stays and the menu still takes the key), so there the item is replaced + /// by an identical one without an accelerator, at the same position and with the same id, + /// text, enabled and checked state. Only done when the accelerator changes (and again while a + /// native call keeps failing), never per frame otherwise. + fn set_accelerator(&mut self, want: Option) { + if self.current == want { + return; + } + if cfg!(target_os = "macos") && want.is_none() && self.swappable { + // `current` follows the native item: it changes only when the swap went through, so a + // failed swap (the old item, key and all, is still there) is tried again + let done = self.replace_without_accelerator(); + self.current = settled(self.current, want, done); + return; + } + let done = match &self.handle { + Handle::Plain(h) => h.set_accelerator(want), + Handle::Check(h) => h.set_accelerator(want), + } + .is_ok(); + self.current = settled(self.current, want, done); + } + + /// Replaces the native item by one without an accelerator. `self.handle` changes only when the + /// new item is attached; on failure the old item is still the one in the submenu. + fn replace_without_accelerator(&mut self) -> bool { + let (id, old): (_, &dyn muda::IsMenuItem) = match &self.handle { + Handle::Plain(h) => (h.id().clone(), h), + Handle::Check(h) => (h.id().clone(), h), + }; + let Some(position) = self.parent.items().iter().position(|k| *k.id() == id) else { return false }; + let new = match &self.handle { + Handle::Plain(_) => Handle::Plain(MenuItem::with_id(id, self.native_label(), self.enabled, None)), + Handle::Check(h) => Handle::Check(CheckMenuItem::with_id(id, self.native_label(), self.enabled, h.is_checked(), None)), + }; + let new_ref: &dyn muda::IsMenuItem = match &new { + Handle::Plain(h) => h, + Handle::Check(h) => h, + }; + if !swap_item(&self.parent, old, new_ref, position) { + return false; + } + self.handle = new; + true + } +} + +/// The accelerator the native item has after trying to put `want` on it: `want` when the native +/// call worked, else what it had, so the caller sees the mismatch and tries again. +fn settled(had: Option, want: Option, native_call_worked: bool) -> Option { + if native_call_worked { want } else { had } +} + +/// Whether the per-frame accelerator sync has to run: the focus or recording state changed, or an +/// earlier sync left an item whose native accelerator is not the wanted one (a failed swap). +fn sync_needed(focus: bool, capturing: bool, synced_focus: bool, synced_capturing: bool, pending: bool) -> bool { + focus != synced_focus || capturing != synced_capturing || pending +} + +/// The three submenu calls a swap needs, so the failure paths can be tested without a main-thread +/// `muda::Menu`. +trait SwapTarget { + type Row: ?Sized; + fn remove(&self, row: &Self::Row) -> bool; + fn insert(&self, row: &Self::Row, position: usize) -> bool; + fn append(&self, row: &Self::Row) -> bool; +} + +impl SwapTarget for Submenu { + type Row = dyn muda::IsMenuItem; + fn remove(&self, row: &Self::Row) -> bool { + Submenu::remove(self, row).is_ok() + } + fn insert(&self, row: &Self::Row, position: usize) -> bool { + Submenu::insert(self, row, position).is_ok() + } + fn append(&self, row: &Self::Row) -> bool { + Submenu::append(self, row).is_ok() + } +} + +/// Puts `new` where `old` is. Returns whether `new` is attached; when it is not, `old` is back in +/// the menu (at its position, else at the end), so the caller keeps `old` as its handle. +fn swap_item(target: &T, old: &T::Row, new: &T::Row, position: usize) -> bool { + if !target.remove(old) { + return false; + } + // (an item at the end beats a missing one) + if target.insert(new, position) || target.append(new) { + return true; + } + let _ = target.insert(old, position) || target.append(old); + false +} + +/// The accelerator a native item has: none while a shortcut is being recorded, and none for the +/// keys a focused text field needs. +fn wanted_accelerator(accel: Option, sc: &str, text_focus: bool, capturing: bool) -> Option { + if capturing || (text_focus && yields_to_text(sc)) { None } else { accel } } pub struct NativeMenu { menu: Menu, items: HashMap, + /// Settings… and Quit in the application submenu: ordinary items, so they give up ⌘, and ⌘Q + /// to the shortcut recorder like the rest. (The system's own items there and in File/Window, + /// such as Hide ⌘H, Close Window ⌘W and Minimize ⌘M, are muda predefined items whose key + /// cannot be changed or swapped.) + app_items: Vec, rx: Receiver, /// Structure of the installed menu (ids, kinds, submenu names); a change rebuilds it. structure: String, @@ -58,6 +187,8 @@ pub struct NativeMenu { /// The keyboard shortcuts editor is recording a key: every accelerator is off so the key /// press reaches it. capturing: bool, + /// An item's native accelerator is not the wanted one (its swap or accelerator call failed): sync again next frame. + accelerators_pending: bool, } /// `Cmd+Shift+Z` → a muda accelerator (`None` for keys we leave to egui, e.g. Escape). @@ -154,13 +285,6 @@ fn yields_to_text(sc: &str) -> bool { !sc.contains("Cmd") && !sc.contains("Ctrl") || TEXT_EDIT.contains(&sc) } -/// Whether AppKit hands this shortcut to the menu bar: only key presses with ⌘ or ⌃, and function -/// keys. A plain `C` or `⇧P` never reaches it (the window's view takes the key), so egui has to run -/// those even though their menu item shows the key. -fn menu_delivers(sc: &str) -> bool { - sc.split('+').any(|part| matches!(part, "Cmd" | "Ctrl") || part.strip_prefix('F').is_some_and(|n| n.parse::().is_ok())) -} - /// The shortcuts the menu bar runs itself, for `LightcraftApp::native_shortcuts`. fn owned_by_menu<'a>(installed: impl Iterator, text_focus: bool) -> HashSet { installed.filter(|sc| menu_delivers(sc) && !(text_focus && yields_to_text(sc))).map(str::to_string).collect() @@ -171,34 +295,6 @@ fn label_text(s: &str) -> String { lightcraft_ui_egui::i18n::tr(s).replace('&', "&&") } -fn structure_of(bar: &[(String, Vec)]) -> String { - fn walk(n: &[MenuNode], out: &mut String) { - for x in n { - match x { - MenuNode::Item { id, params, checked, shortcut, .. } => { - out.push_str(&MenuNode::key(id, params)); - out.push(if checked.is_some() { 'c' } else { 'i' }); - out.push_str(shortcut.as_deref().unwrap_or("")); - } - MenuNode::Separator => out.push('-'), - MenuNode::Submenu { label, children } => { - out.push('['); - out.push_str(label); - walk(children, out); - out.push(']'); - } - } - out.push(';'); - } - } - let mut s = format!("{};", lightcraft_ui_egui::i18n::language().code()); - for (t, items) in bar { - s.push_str(t); - walk(items, &mut s); - } - s -} - /// Drop a trailing separator (left behind when an item moved to the app menu). fn tidy_separators(mut nodes: Vec) -> Vec { while matches!(nodes.last(), Some(MenuNode::Separator)) { @@ -216,17 +312,28 @@ impl NativeMenu { let _ = tx.send(e.id.0); repaint.request_repaint(); })); - let mut m = NativeMenu { menu: Menu::new(), items: HashMap::new(), rx, structure: String::new(), text_focus: false, capturing: false }; + let mut m = NativeMenu { + menu: Menu::new(), + items: HashMap::new(), + app_items: Vec::new(), + rx, + structure: String::new(), + text_focus: false, + capturing: false, + accelerators_pending: false, + }; m.rebuild(app); app.native_menu = true; m } + /// Recreate native handles and shortcut ownership from the current shared menu model. fn rebuild(&mut self, app: &mut LightcraftApp) { let bar = menu_bar(app); - self.structure = structure_of(&bar); + self.structure = structure_of(&bar, &app.ui.settings.keymap); self.menu = Menu::new(); self.items.clear(); + self.app_items.clear(); // the application menu let app_menu = Submenu::new("LightCraft", true); @@ -246,6 +353,22 @@ impl NativeMenu { &PredefinedMenuItem::separator(), &quit, ]); + for (handle, cmd, shortcut, text) in [(&settings, SETTINGS, SETTINGS_KEY, "Settings…"), (&quit, QUIT, "Cmd+Q", "Quit LightCraft")] { + let accel = accelerator(shortcut); + self.app_items.push(Item { + handle: Handle::Plain(handle.clone()), + parent: app_menu.clone(), + swappable: true, + cmd: cmd.to_string(), + params: Value::Null, + shortcut: Some(shortcut.to_string()), + accel, + current: accel, + label: lightcraft_ui_egui::menubar::display_item_label(cmd, &Value::Null, text).to_string(), + enabled: true, + checked: None, + }); + } let _ = self.menu.append(&app_menu); for (title, nodes) in &bar { @@ -264,7 +387,9 @@ impl NativeMenu { .cloned() .collect(); let nodes = tidy_separators(nodes); - self.append_nodes(&sub, &nodes); + // Swapping an item in the Help menu leaves the old row in place and adds a second one + // (measured on macOS 27 with muda 0.21): the Help menu is not addressed row for row. + self.append_nodes(&sub, &nodes, &app.ui.settings.keymap, title != "Help"); if title == "File" { // ⌘W, the system's own item let _ = sub.append_items(&[ @@ -287,10 +412,13 @@ impl NativeMenu { self.menu.init_for_nsapp(); self.text_focus = false; self.capturing = false; + self.accelerators_pending = false; self.publish_shortcuts(app); } - fn append_nodes(&mut self, sub: &Submenu, nodes: &[MenuNode]) { + /// Install translated rows with their effective accelerators, preserving hint-only keys. + /// `swappable`: whether its items may be replaced to drop their key (see `Item::swappable`). + fn append_nodes(&mut self, sub: &Submenu, nodes: &[MenuNode], keymap: &lightcraft_ui_egui::shortcuts::Keymap, swappable: bool) { for n in nodes { match n { MenuNode::Separator => { @@ -298,7 +426,7 @@ impl NativeMenu { } MenuNode::Submenu { label, children } => { let s = Submenu::new(label_text(label), true); - self.append_nodes(&s, children); + self.append_nodes(&s, children, keymap, swappable); let _ = sub.append(&s); } MenuNode::Item { id, params, label, shortcut, enabled, checked } => { @@ -306,26 +434,16 @@ impl NativeMenu { if self.items.contains_key(&key) { continue; // muda ids must be unique } - let accel = shortcut.as_deref().filter(|s| !CONTEXTUAL.contains(s)).and_then(accelerator); + let (native_label, native_key) = native_item_presentation(keymap, id, params, label, shortcut.as_deref()); + let accel = native_key.filter(|s| !CONTEXTUAL.contains(s)).and_then(accelerator); let handle = match checked { Some(c) => { - let it = CheckMenuItem::with_id( - key.clone(), - lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&"), - *enabled, - *c, - accel, - ); + let it = CheckMenuItem::with_id(key.clone(), native_label.replace('&', "&&"), *enabled, *c, accel); let _ = sub.append(&it); Handle::Check(it) } None => { - let it = MenuItem::with_id( - key.clone(), - lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&"), - *enabled, - accel, - ); + let it = MenuItem::with_id(key.clone(), native_label.replace('&', "&&"), *enabled, accel); let _ = sub.append(&it); Handle::Plain(it) } @@ -334,11 +452,14 @@ impl NativeMenu { key, Item { handle, + parent: sub.clone(), + swappable, cmd: id.clone(), params: params.clone(), shortcut: shortcut.clone(), accel, - label: label.clone(), + current: accel, + label: native_label, enabled: *enabled, checked: *checked, }, @@ -364,36 +485,43 @@ impl NativeMenu { lightcraft_ui_egui::i18n::set_language(app.ui.language); let mut quit = false; while let Ok(key) = self.rx.try_recv() { - if key == QUIT { + // Resolve the native id to its command, then let the shared policy decide. Native menu + // events never reach `shortcuts::handle`, so this is the one guard for AppKit's + // accelerators and clicks: while the blocking library window or a quit/settings notice + // owns input, a queued command is dropped (Quit stays for the existing confirmation). + let (cmd, params) = if key == QUIT { + (key, serde_json::json!({})) + } else if key == "app.about" || key == SETTINGS { + (key, serde_json::json!({})) + } else if let Some(it) = self.items.get(&key) { + (it.cmd.clone(), it.params.clone()) + } else { + continue; + }; + if lightcraft_ui_egui::menubar::run_native_command(app, &cmd, params) == lightcraft_ui_egui::menubar::NativeCommand::Quit { quit = true; - continue; - } - if key == "app.about" || key == SETTINGS { - let _ = app.run(&key, serde_json::json!({})); - continue; - } - if let Some(it) = self.items.get(&key) { - let (cmd, params) = (it.cmd.clone(), it.params.clone()); - let _ = lightcraft_ui_egui::menubar::run_item(app, &cmd, params); } } let bar = menu_bar(app); - if structure_of(&bar) != self.structure { + if structure_of(&bar, &app.ui.settings.keymap) != self.structure { + // (no early return: a rebuild installs every accelerator and resets the state they were synced + // to, so the sync below runs in this same frame and no key reaches the menu in between) self.rebuild(app); - return quit; } - fn walk(nodes: &[MenuNode], items: &mut HashMap) { + /// Synchronize live labels and states; accelerator ownership changes already triggered a rebuild. + fn walk(nodes: &[MenuNode], items: &mut HashMap, keymap: &lightcraft_ui_egui::shortcuts::Keymap) { for n in nodes { match n { - MenuNode::Submenu { children, .. } => walk(children, items), - MenuNode::Item { id, params, label, enabled, checked, .. } => { + MenuNode::Submenu { children, .. } => walk(children, items, keymap), + MenuNode::Item { id, params, label, shortcut, enabled, checked } => { let Some(it) = items.get_mut(&MenuNode::key(id, params)) else { continue }; - if it.label != *label { + let (native_label, _) = native_item_presentation(keymap, id, params, label, shortcut.as_deref()); + if it.label != native_label { match &it.handle { - Handle::Plain(h) => h.set_text(lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&")), - Handle::Check(h) => h.set_text(lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&")), + Handle::Plain(h) => h.set_text(native_label.replace('&', "&&")), + Handle::Check(h) => h.set_text(native_label.replace('&', "&&")), } - it.label = label.clone(); + it.label = native_label; } if it.enabled != *enabled { match &it.handle { @@ -414,24 +542,24 @@ impl NativeMenu { } } } - walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::>(), &mut self.items); + walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::>(), &mut self.items, &app.ui.settings.keymap); let focus = ctx.egui_wants_keyboard_input(); let capturing = app.recording_shortcut.is_some(); - if focus != self.text_focus || capturing != self.capturing { + if sync_needed(focus, capturing, self.text_focus, self.capturing, self.accelerators_pending) { self.text_focus = focus; self.capturing = capturing; - for it in self.items.values() { + let mut pending = false; + for it in self.items.values_mut().chain(self.app_items.iter_mut()) { let Some(sc) = it.shortcut.as_deref() else { continue }; if it.accel.is_none() { continue; } - let accel = if capturing || (focus && yields_to_text(sc)) { None } else { it.accel }; - let _ = match &it.handle { - Handle::Plain(h) => h.set_accelerator(accel), - Handle::Check(h) => h.set_accelerator(accel), - }; + let want = wanted_accelerator(it.accel, sc, focus, capturing); + it.set_accelerator(want); + pending |= it.current != want; } + self.accelerators_pending = pending; self.publish_shortcuts(app); } quit @@ -454,15 +582,102 @@ mod tests { let mut seen = std::collections::BTreeSet::new(); for language in Locale::ALL { set_language(*language); - assert!(seen.insert(structure_of(&bar)), "{language:?} shares another language's menu structure key"); + assert!(seen.insert(structure_of(&bar, &app.ui.settings.keymap)), "{language:?} shares another language's menu structure key"); } - set_language(Locale::ZhHant); - assert_eq!(label_text("File"), "檔案"); - assert_eq!(label_text("Settings…"), "設定…"); - assert_eq!(label_text("Quit LightCraft"), "結束 LightCraft"); set_language(Locale::En); } + #[test] + fn accelerators_yield_to_text_focus_and_shortcut_recording() { + let g = accelerator("G"); + let cmd_s = accelerator("Cmd+S"); + assert_eq!(wanted_accelerator(g, "G", false, false), g); + assert_eq!(wanted_accelerator(g, "G", true, false), None, "typing a G in a field"); + assert_eq!(wanted_accelerator(cmd_s, "Cmd+S", true, false), cmd_s, "⌘S still saves while typing"); + assert_eq!(wanted_accelerator(cmd_s, "Cmd+S", false, true), None, "the editor records the key"); + assert_eq!(wanted_accelerator(cmd_s, "Cmd+S", true, true), None, "recording wins over typing"); + // the application menu's Settings… and Quit are tracked like the other items + for sc in [SETTINGS_KEY, "Cmd+Q"] { + let a = accelerator(sc); + assert!(a.is_some()); + assert_eq!(wanted_accelerator(a, sc, true, false), a, "{sc} stays while typing"); + assert_eq!(wanted_accelerator(a, sc, false, true), None, "{sc} goes while recording"); + } + assert_eq!(wanted_accelerator(None, "Escape", false, false), None, "no accelerator stays none"); + } + + /// A submenu of numbers whose calls can be made to fail, to run `swap_item`'s failure paths. + /// Row 2 is the old item and row 9 its replacement. + #[derive(Default)] + struct Fake { + rows: std::cell::RefCell>, + fail_remove: bool, + /// The new item (9) cannot be inserted / appended. + reject_new_insert: bool, + reject_new_append: bool, + /// The old item (2) cannot be inserted back. + reject_old_insert: bool, + } + impl SwapTarget for Fake { + type Row = u32; + fn remove(&self, row: &u32) -> bool { + if self.fail_remove { + return false; + } + self.rows.borrow_mut().retain(|x| x != row); + true + } + fn insert(&self, row: &u32, position: usize) -> bool { + if (self.reject_new_insert && *row == 9) || (self.reject_old_insert && *row == 2) { + return false; + } + self.rows.borrow_mut().insert(position, *row); + true + } + fn append(&self, row: &u32) -> bool { + if self.reject_new_append && *row == 9 { + return false; + } + self.rows.borrow_mut().push(*row); + true + } + } + + fn swap(fake: Fake) -> (bool, Vec) { + *fake.rows.borrow_mut() = vec![1, 2, 3]; + let done = swap_item(&fake, &2, &9, 1); + (done, fake.rows.into_inner()) + } + + #[test] + fn a_swap_changes_the_item_only_when_the_new_one_is_attached() { + assert_eq!(swap(Fake::default()), (true, vec![1, 9, 3]), "in place"); + assert_eq!(swap(Fake { fail_remove: true, ..Default::default() }), (false, vec![1, 2, 3]), "remove fails: the old item stays"); + assert_eq!(swap(Fake { reject_new_insert: true, ..Default::default() }), (true, vec![1, 3, 9]), "insert fails: the new item goes last"); + assert_eq!( + swap(Fake { reject_new_insert: true, reject_new_append: true, ..Default::default() }), + (false, vec![1, 2, 3]), + "neither works: the old item is back where it was" + ); + assert_eq!( + swap(Fake { reject_new_insert: true, reject_new_append: true, reject_old_insert: true, ..Default::default() }), + (false, vec![1, 3, 2]), + "the old item cannot go back in place either: it is appended" + ); + } + + #[test] + fn a_failed_native_call_is_retried_while_the_state_holds() { + let g = accelerator("G"); + assert_eq!(settled(g, None, true), None, "the swap worked"); + assert_eq!(settled(g, None, false), g, "it failed: the native item still has its key"); + assert_eq!(settled(None, g, false), None, "restoring a key failed"); + assert!(!sync_needed(true, false, true, false, false), "nothing changed"); + assert!(sync_needed(true, false, false, false, false), "focus changed"); + assert!(sync_needed(false, true, false, false, false), "recording changed"); + assert!(sync_needed(true, false, true, false, true), "a swap failed last time: try again with the state unchanged"); + } + #[test] fn shortcuts_map_to_accelerators() { assert_eq!(accelerator("Cmd+Shift+Z"), Some(Accelerator::new(Modifiers::META | Modifiers::SHIFT, Code::KeyZ))); diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index 1f84ec4775..fefa65a516 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -93,7 +93,6 @@ pub fn choose(files: &Files) -> Chosen { let compiled = wgpu::Instance::enabled_backend_features(); let os = std::env::consts::OS; let order = backend::window_renderer_order(forced, remembered, failed, os, compiled, true); - let mut notice = failed.map(|f| format!("The window could not start with its {} renderer last time.", f.name())); let mut problems = Vec::new(); let chosen = if cfg!(windows) { pick_probed(&order, &mut problems) @@ -104,18 +103,7 @@ pub fn choose(files: &Files) -> Chosen { Some((WindowRenderer::Wgpu(backend::window_backends()), None)) }; let (which, existing) = chosen.unwrap_or((WindowRenderer::Glow, None)); - if !problems.is_empty() { - notice = Some(format!("{} {}", notice.unwrap_or_default(), problems.join(" ")).trim().to_string()); - } - let notice = notice.map(|n| { - format!( - "{n} {app} now draws its window with {}. To choose another, start {app} with {var}=dx12, vulkan, gl or glow \ - (see docs/gpu-pipeline.md → Troubleshooting).", - which.name(), - app = "LightCraft", - var = "LIGHTCRAFT_GPU_BACKEND", - ) - }); + let notice = user_notice(failed, forced, &problems, which); log::info!("window: renderer {} (order {:?})", which.name(), order.iter().map(|r| r.name()).collect::>()); let mut wgpu_options = base_options(); let renderer = match (which, existing) { @@ -134,6 +122,25 @@ pub fn choose(files: &Files) -> Chosen { Chosen { renderer, wgpu_options, which, notice } } +/// What to tell the user about the window's renderer. A renderer that failed its probe is skipped +/// silently (it is logged, and the one that worked is remembered): the app works, so a pop-up with +/// wgpu's error only alarms (#1624). Shown: the last start died, or the forced renderer failed. +fn user_notice(failed: Option, forced: Option, problems: &[String], which: WindowRenderer) -> Option { + let mut notice = failed.map(|f| format!("The window could not start with its {} renderer last time.", f.name())); + if forced.is_some() && !problems.is_empty() { + notice = Some(format!("{} {}", notice.unwrap_or_default(), problems.join(" ")).trim().to_string()); + } + notice.map(|n| { + format!( + "{n} {app} now draws its window with {}. To choose another, start {app} with {var}=dx12, vulkan, gl or glow \ + (see docs/gpu-pipeline.md → Troubleshooting).", + which.name(), + app = "LightCraft", + var = "LIGHTCRAFT_GPU_BACKEND", + ) + }) +} + /// eframe's defaults with the app's backends and DX12 shader compiler (issues #136, #471). pub fn base_options() -> WgpuConfiguration { let mut c = WgpuConfiguration::default(); @@ -269,6 +276,20 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// #1624: a renderer skipped by the probe (DX12 → Vulkan) is no pop-up; a died start or a + /// failed forced renderer still is. + #[test] + fn probe_fallback_is_silent() { + let (dx, vk) = (WindowRenderer::Wgpu(Backends::DX12), WindowRenderer::Wgpu(Backends::VULKAN)); + let problems = vec!["The dx12 renderer failed (Validation Error).".to_string()]; + assert_eq!(user_notice(None, None, &problems, vk), None); + assert_eq!(user_notice(None, None, &[], vk), None); + let forced = user_notice(None, Some(dx), &problems, vk).unwrap(); + assert!(forced.starts_with("The dx12 renderer failed") && forced.contains("now draws its window with vulkan"), "{forced}"); + let died = user_notice(Some(dx), None, &problems, vk).unwrap(); + assert!(died.contains("last time") && !died.contains("Validation Error"), "{died}"); + } + /// The crash report: a pipeline that fails validation must come back as an error, never as /// wgpu's default panic. Needs an adapter; skipped where there is none (CI without a GPU). #[test] diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index 30eea5654c..e5ed8090e7 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -8,6 +8,10 @@ covers a whole directory), or if a licence file referenced in the Licence column | Path | Asset | Creator | Source | Licence | Added | Modifications | |---|---|---|---|---|---|---| +| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | egui icon subset and monochrome fallback | John Slegers | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | 2026-10-24 (notice audit) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full fallback. Registered by production default font definitions; dependency assets unmodified here, no font file copied into this repository. | +| `epaint_default_fonts::HACK_REGULAR` (dependency font input) | Hack Regular (the monospace default) | Source Foundry Authors (built on the DejaVu project, which was committed to the public domain) and Bitstream Inc. | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts) | MIT AND Bitstream Vera License (Copyright (c) 2018 Source Foundry Authors; Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.; full upstream texts in `NOTICE`) | 2026-10-25 (notice audit) | unmodified egui default font embedded in the binary and registered by the production default font definitions (egui's `default_fonts`); no font file copied into this repository | +| `epaint_default_fonts::UBUNTU_LIGHT` (dependency font input) | Ubuntu Light (the proportional default) | Canonical Ltd.; designed by Dalton Maag Ltd | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts) | Ubuntu Font Licence 1.0, not the SIL Open Font License (Copyright 2011 Canonical Ltd.; full upstream text in `NOTICE`) | 2026-10-25 (notice audit) | unmodified egui default font embedded in the binary and registered by the production default font definitions (egui's `default_fonts`); no font file copied into this repository | +| `epaint_default_fonts::NOTO_EMOJI_REGULAR` (dependency font input) | Noto Emoji Regular | Google Inc.; designed by the Monotype Design Team | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts) | SIL Open Font License 1.1 (Copyright 2013 Google Inc. All Rights Reserved.; full upstream text in `NOTICE`) | 2026-10-25 (notice audit) | unmodified egui default font embedded in the binary and registered by the production default font definitions (egui's `default_fonts` and `monochrome_emoji_fonts`); no font file copied into this repository | | `assets/fonts/Inter-*.ttf` (Regular, Medium, SemiBold) | Inter | Rasmus Andersson | https://github.com/rsms/inter | SIL Open Font License 1.1 (`assets/fonts/OFL-Inter.txt`) | 2026-09-30 | none | | `assets/app-icon/` (`lightcraft.svg` and the PNG/ICNS/ICO/SVG files derived from it) | LightCraft app icon (lynx) | LightCraft project owner (drawn in ArtCraft) | original work (vectorised from the owner's drawing; see `assets/app-icon/README.md`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | 2026-10-02 | vectorised to SVG; rendered to PNG/ICNS/ICO by `packaging/icons.sh` | | `assets/camera-profiles/*.json` | Camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | ILCE-7M4: Harald Hoyer | original work: fitted by `lightcraft-cli calibrate` to the contributor's own raw photos and their in-camera JPEGs (597 ILCE-7M4 photos, 2026); aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-07 | none | @@ -18,6 +22,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `assets/camera-profiles/NIKON_Z_6_2.json` | Nikon Z 6II camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 296 usable Z 6II NEFs of my own (of 299, 2024 to 2026, Standard and Auto picture controls; NIKKOR Z 20mm f/1.8 S, Z 24-70mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | | `assets/camera-profiles/NIKON_Z_8.json` | Nikon Z 8 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 261 usable Z 8 NEFs of my own (of 278, 2023 and 2026, nearly all Standard picture control, lossless 14-bit; NIKKOR Z 24-120mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | | `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | +| `assets/camera-profiles/ILCE-7RM5.json` | Sony ILCE-7RM5 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Yule (Brian) Wang (@peaperfish) | original work: fitted by `lightcraft-cli calibrate` to 220 usable ILCE-7RM5 ARWs of my own (of 241, 2025 to 2026, Standard creative style; Sigma 24-70mm F2.8 DG DN II Art and Sony FE 200-600mm F5.6-6.3 G OSS) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-26 | none | | `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix | | `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none | | `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a | @@ -29,7 +34,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `docs/images/*-blue-marble.jpg`, `docs/images/grid-pd.jpg` | "The Blue Marble" (AS17-148-22727) | NASA, Apollo 17 crew (1972) | https://commons.wikimedia.org/wiki/File:The_Earth_seen_from_Apollo_17.jpg | Public domain (NASA) | 2026-09-30 | developed in LightCraft; shown inside app screenshots | | `docs/images/*.jpg` (UI) | LightCraft application screenshots | LightCraft contributors | original work (captured with `docs/showcase/`) | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `docs/brand/` (artcraft-logo and artcraft-mark, SVG and PNG) | ArtCraft wordmark and mark | ArtCraft Team | original work (https://getartcraft.com/) | ArtCraft trademark, see `docs/brand/LICENSE-brand.txt` (not open source) | 2026-10-01 | none | -| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular | The Noto Project Authors (Arabic and Thai); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the manifest fonts (all official releases); the web build embeds BIZ UDPGothic Regular and Noto Sans Thai Regular and ships Noto Sans CJK SC Regular as a separate font file | +| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular, Noto Sans Georgian Regular, NanumGothic Regular, Noto Sans Symbols Regular, Noto Sans Symbols 2 Regular, Noto Sans Hebrew Regular, Noto Sans Devanagari Regular | The Noto Project Authors (Arabic, Thai, Georgian, Symbols, Symbols 2, Hebrew and Devanagari); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; NHN Corporation and Sandoll Communications (NanumGothic); Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/b076417b5880bd4154bd22f00695b1d28c6bea83/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the default `fonts/manifest.txt` set (all official releases; the opt-in LXGW WenKai Lite face in `fonts/simplified-chinese-manifest.txt` is not embedded); the web build embeds BIZ UDPGothic Regular, Noto Sans Thai Regular and Noto Sans Georgian Regular and ships Noto Sans CJK SC Regular as a separate font file | | `crates/ui-egui/locales/uk.json`, `crates/ui-egui/locales/uk-formats.json` | Ukrainian interface catalogs | @dmatviichuk with Codex; PhotoCraft, FilmCraft and VectorCraft translation contributors for reused labels | original translations from English source; 337 initial English-key matches reviewed from [PhotoCraft 69c41f3](https://github.com/storytold/photocraft/blob/69c41f3523e147eb215da8c7b4c29b18b35d1c63/crates/ui-egui/src/i18n/uk.tsv), [FilmCraft 4854c27](https://github.com/storytold/filmcraft/blob/4854c277536fe8118257362304b6a7d82d8e704b/crates/ui-egui/src/i18n/uk.tsv), [VectorCraft 4b44265](https://github.com/storytold/vectorcraft/blob/4b44265965fdd6ffedfd6182a892c1a6c360d344/crates/ui-egui/src/i18n/uk.tsv) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-09 | adapted to LightCraft photo-development context, completed catalogs, reviewed spelling and placeholders | | `crates/ui-egui/locales/cs.json`, `crates/ui-egui/locales/cs-formats.json` | Czech interface catalogs | @Losminek with AI assistance (Codex) | original work: translations of English source phrases, reviewed against the app UI conventions; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-11 | catalog coverage, Czech dates and count-neutral wording; independent scope/terminology review; native-speaker proofreading pending | | `crates/ui-egui/locales/it.json`, `crates/ui-egui/locales/it-formats.json` | Italian interface catalogs | @GabrielePecchioli with Claude Code; PhotoCraft, VectorCraft, PdfCraft and WordCraft translation contributors for reused labels | original translations from English source; 410 initial English-key matches reviewed from [PhotoCraft da3da09](https://github.com/storytold/photocraft/blob/da3da0942c14c1159f40c652afcf33584332c733/crates/ui-egui/src/i18n/it.tsv), [VectorCraft 5432821](https://github.com/storytold/vectorcraft/blob/543282148007bcb5633c493a5374cd26b0339c8d/crates/ui-egui/src/i18n/it.tsv), [PdfCraft e8e275c](https://github.com/storytold/pdfcraft/blob/e8e275cbd40ccd0dc6b56f82b16a575571043702/crates/ui-egui/src/i18n/it.tsv) and the Italian WordCraft catalog ([storytold/wordcraft#598](https://github.com/storytold/wordcraft/pull/598)); 46 of them retranslated where the sibling's meaning didn't fit a photo app | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-12 | adapted to LightCraft photo-development context, count-neutral labels for Italian plural agreement, reviewed placeholders | @@ -40,6 +45,9 @@ covers a whole directory), or if a licence file referenced in the Licence column | `crates/ui-egui/locales/vi.json`, `crates/ui-egui/locales/vi-formats.json` | Vietnamese interface catalogs | @duydev (DUY Tran Nhat) with AI assistance (Cursor) | original work: translations of English source phrases; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-13 | plural-neutral counts, Vietnamese dates and weekdays, reviewed placeholders | Notes +- egui's default fonts (Hack, Ubuntu Light, Noto Emoji, egui-icons and emoji-icon-font) come from the + `epaint_default_fonts` dependency, not from files in this repository; their creators, licences and the full + upstream texts are recorded in the rows above and in `NOTICE`. - Fonts authored or published by Adobe (Source Sans/Serif/Code, Source Han, …) are not used, even though some are OFL-licensed: the asset rule excludes anything from Adobe. Source Sans 3 was removed on 2026-09-30 and replaced by Inter. - CJK fonts (BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC) are not in this repository. They live in diff --git a/assets/camera-profiles/ILCE-7RM5.json b/assets/camera-profiles/ILCE-7RM5.json new file mode 100644 index 0000000000..787bfb062d --- /dev/null +++ b/assets/camera-profiles/ILCE-7RM5.json @@ -0,0 +1,9031 @@ +{ + "version": 1, + "model": "ILCE-7RM5", + "files": 220, + "samples": 790553, + "matrix": [ + [ + 1.249584732786861, + -0.3300570108987344, + 0.07738524309065298 + ], + [ + -0.09371116474358132, + 1.2038743929103433, + -0.1120131503658719 + ], + [ + -0.03422832387281005, + -0.8688172281950557, + 1.937872050399747 + ] + ], + "hue_sat": { + "hue_divisions": 72, + "sat_divisions": 5, + "val_divisions": 5, + "data": [ + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.6575432, + 1.0169075, + 1.0 + ], + [ + 0.045065638, + 1.0544671, + 1.0 + ], + [ + 0.2621381, + 1.0540911, + 1.0 + ], + [ + 0.5927048, + 1.0288227, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.568119, + 1.0037564, + 1.0 + ], + [ + -0.4427149, + 1.0345306, + 1.0 + ], + [ + -0.41775778, + 1.0446787, + 1.0 + ], + [ + 0.086332865, + 1.0200883, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.272573, + 1.0058666, + 1.0 + ], + [ + -0.5253304, + 0.9976382, + 1.0 + ], + [ + -1.19747, + 1.0018761, + 1.0 + ], + [ + -0.79130363, + 0.98982924, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.8305438, + 1.013145, + 1.0 + ], + [ + -0.64092255, + 1.0028768, + 1.0 + ], + [ + -1.6476865, + 0.98830545, + 1.0 + ], + [ + -1.8518519, + 0.9801241, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.9341725, + 1.02301, + 1.0 + ], + [ + -1.0185463, + 1.0157639, + 1.0 + ], + [ + -2.5776067, + 0.99842805, + 1.0 + ], + [ + -3.2994924, + 0.9785849, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.5423042, + 1.0483397, + 1.0 + ], + [ + -1.4740537, + 1.032285, + 1.0 + ], + [ + -3.7110608, + 1.0046949, + 1.0 + ], + [ + -5.396528, + 0.967783, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.6425831, + 1.0778131, + 1.0 + ], + [ + -2.4365096, + 1.0424513, + 1.0 + ], + [ + -4.570945, + 1.0063766, + 1.0 + ], + [ + -6.660486, + 0.95838326, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.14437525, + 1.0805831, + 1.0 + ], + [ + -3.1429949, + 1.0347922, + 1.0 + ], + [ + -4.7743, + 1.0044911, + 1.0 + ], + [ + -6.743695, + 0.9554359, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.7822553, + 1.099207, + 1.0 + ], + [ + -2.1562428, + 1.0492018, + 1.0 + ], + [ + -4.6814117, + 0.9976052, + 1.0 + ], + [ + -7.334759, + 0.9328078, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.4186356, + 1.1193541, + 1.0 + ], + [ + -1.2648852, + 1.0724756, + 1.0 + ], + [ + -4.010651, + 1.001225, + 1.0 + ], + [ + -6.9021163, + 0.93410987, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.0874636, + 1.1538868, + 1.0 + ], + [ + 0.23989654, + 1.0897437, + 1.0 + ], + [ + -2.9069233, + 1.0008082, + 1.0 + ], + [ + -6.942227, + 0.9103677, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.2319875, + 1.1964883, + 1.0 + ], + [ + 1.6361779, + 1.1026742, + 1.0 + ], + [ + -1.7622405, + 0.99407303, + 1.0 + ], + [ + -7.6075315, + 0.87470096, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.200221, + 1.2336057, + 1.0 + ], + [ + 2.4819555, + 1.1164554, + 1.0 + ], + [ + -0.67436194, + 0.9800342, + 1.0 + ], + [ + -6.7233605, + 0.8354304, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.7635767, + 1.258256, + 1.0 + ], + [ + 2.755172, + 1.1187295, + 1.0 + ], + [ + 0.58612347, + 0.95909715, + 1.0 + ], + [ + -3.4647129, + 0.8201187, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.7450001, + 1.2654432, + 1.0 + ], + [ + 2.2866368, + 1.1127598, + 1.0 + ], + [ + 1.7782547, + 0.96788186, + 1.0 + ], + [ + 0.64800644, + 0.8437623, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.4756403, + 1.2495352, + 1.0 + ], + [ + 1.8023143, + 1.1058493, + 1.0 + ], + [ + 2.4051156, + 0.97594136, + 1.0 + ], + [ + 3.1766913, + 0.8713939, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.15415932, + 1.2347906, + 1.0 + ], + [ + 1.3704019, + 1.0905327, + 1.0 + ], + [ + 2.8927534, + 0.95705473, + 1.0 + ], + [ + 4.9556255, + 0.85762197, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.45234466, + 1.2126856, + 1.0 + ], + [ + 1.3297142, + 1.0610285, + 1.0 + ], + [ + 3.5847495, + 0.92722595, + 1.0 + ], + [ + 6.0845156, + 0.84810686, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.0763642, + 1.1915482, + 1.0 + ], + [ + 1.087915, + 1.0379584, + 1.0 + ], + [ + 3.107092, + 0.9336573, + 1.0 + ], + [ + 4.6096416, + 0.87201273, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.8927168, + 1.1797738, + 1.0 + ], + [ + 0.3604307, + 1.0387832, + 1.0 + ], + [ + 1.8885725, + 0.9472845, + 1.0 + ], + [ + 2.5527375, + 0.8916758, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.8154569, + 1.1746649, + 1.0 + ], + [ + -0.75731444, + 1.0539931, + 1.0 + ], + [ + 0.15679865, + 0.99418485, + 1.0 + ], + [ + 0.26365867, + 0.97036415, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -3.6557531, + 1.1808895, + 1.0 + ], + [ + -2.146421, + 1.0872095, + 1.0 + ], + [ + -1.216422, + 1.0318732, + 1.0 + ], + [ + -0.14712709, + 1.0002339, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -4.503687, + 1.1711676, + 1.0 + ], + [ + -2.6333165, + 1.0882001, + 1.0 + ], + [ + -0.9562701, + 1.0260637, + 1.0 + ], + [ + -0.035742544, + 1.0006093, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -5.3313165, + 1.1779693, + 1.0 + ], + [ + -3.511713, + 1.0934967, + 1.0 + ], + [ + -0.77989405, + 1.0125425, + 1.0 + ], + [ + -0.15130846, + 0.9985428, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -6.7568846, + 1.1773652, + 1.0 + ], + [ + -4.3852744, + 1.0850232, + 1.0 + ], + [ + -2.9159627, + 0.9900688, + 1.0 + ], + [ + -2.1400974, + 0.9775968, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -6.7892175, + 1.1440657, + 1.0 + ], + [ + -4.395312, + 1.0594687, + 1.0 + ], + [ + -3.1968632, + 0.9905179, + 1.0 + ], + [ + -1.8385077, + 0.98149014, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.615582, + 1.1392046, + 1.0 + ], + [ + -4.00538, + 1.0335472, + 1.0 + ], + [ + -0.9200221, + 0.99787354, + 1.0 + ], + [ + -0.11120706, + 0.9992187, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.523595, + 1.1210346, + 1.0 + ], + [ + -4.8383403, + 1.0227709, + 1.0 + ], + [ + -1.0064363, + 0.9959147, + 1.0 + ], + [ + -0.049839716, + 0.99975395, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.567221, + 1.109696, + 1.0 + ], + [ + -3.7778788, + 1.0227439, + 1.0 + ], + [ + -0.3094657, + 0.99754596, + 1.0 + ], + [ + -0.01160631, + 0.9998476, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.9242926, + 1.1014805, + 1.0 + ], + [ + -2.6735833, + 1.0197709, + 1.0 + ], + [ + -0.10607915, + 0.9988134, + 1.0 + ], + [ + -0.0016143449, + 0.99994075, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.489351, + 1.0988349, + 1.0 + ], + [ + -2.0020316, + 1.0113986, + 1.0 + ], + [ + -0.060160246, + 0.9993989, + 1.0 + ], + [ + -0.00045636468, + 0.99998945, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.7909346, + 1.0950327, + 1.0 + ], + [ + -3.1690855, + 1.0192778, + 1.0 + ], + [ + -0.20098883, + 1.0008932, + 1.0 + ], + [ + -0.0010797405, + 1.0000042, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.812833, + 1.0921811, + 1.0 + ], + [ + -3.6212065, + 1.016884, + 1.0 + ], + [ + -0.2872315, + 1.000208, + 1.0 + ], + [ + -0.0022921215, + 0.9999986, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.7691603, + 1.0748369, + 1.0 + ], + [ + -2.2901673, + 1.0061964, + 1.0 + ], + [ + -0.2540361, + 0.9997461, + 1.0 + ], + [ + -0.002999882, + 0.9999967, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.285355, + 1.0752903, + 1.0 + ], + [ + -2.8977985, + 1.008037, + 1.0 + ], + [ + -0.389354, + 1.0001613, + 1.0 + ], + [ + -0.0048222253, + 1.0000017, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.331701, + 1.0774896, + 1.0 + ], + [ + -3.3062727, + 1.0165391, + 1.0 + ], + [ + -0.24283074, + 1.0005523, + 1.0 + ], + [ + -0.0019910862, + 1.0000027, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.720209, + 1.0690521, + 1.0 + ], + [ + -4.8786044, + 1.0175062, + 1.0 + ], + [ + -0.48560837, + 1.0014203, + 1.0 + ], + [ + -0.0033854088, + 1.0000086, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -11.556501, + 1.0456746, + 1.0 + ], + [ + -4.985604, + 1.0003452, + 1.0 + ], + [ + -0.41515103, + 0.9995448, + 1.0 + ], + [ + -0.003054782, + 0.9999918, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -11.729045, + 1.0217354, + 1.0 + ], + [ + -3.521123, + 0.98780435, + 1.0 + ], + [ + -0.30965137, + 0.99440813, + 1.0 + ], + [ + -0.008598875, + 0.9997742, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -12.221271, + 0.98520076, + 1.0 + ], + [ + -4.486184, + 0.97454756, + 1.0 + ], + [ + -0.41762093, + 0.9899926, + 1.0 + ], + [ + -0.03436083, + 0.9983804, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -13.70429, + 0.9197576, + 1.0 + ], + [ + -6.0378523, + 0.93986017, + 1.0 + ], + [ + -0.41832632, + 0.99216044, + 1.0 + ], + [ + -0.01641741, + 0.99925196, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -14.093513, + 0.8699881, + 1.0 + ], + [ + -6.8281274, + 0.9147011, + 1.0 + ], + [ + -0.30128792, + 0.99418074, + 1.0 + ], + [ + -0.0026745356, + 0.9999154, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -12.529678, + 0.84677386, + 1.0 + ], + [ + -7.347991, + 0.897593, + 1.0 + ], + [ + -0.39531615, + 0.9915446, + 1.0 + ], + [ + -0.000654911, + 0.9999173, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -10.297008, + 0.8246169, + 1.0 + ], + [ + -6.991395, + 0.8822463, + 1.0 + ], + [ + -0.8904233, + 0.98326087, + 1.0 + ], + [ + -0.005210178, + 0.99982196, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.1014814, + 0.870403, + 1.0 + ], + [ + -4.2737536, + 0.9510795, + 1.0 + ], + [ + -1.0143899, + 0.9928547, + 1.0 + ], + [ + 0.0069134138, + 0.9990259, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.2389834, + 1.0089513, + 1.0 + ], + [ + 0.59233487, + 1.0836766, + 1.0 + ], + [ + 2.109882, + 1.0953512, + 1.0 + ], + [ + 0.57811993, + 1.0165061, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.42605868, + 1.0736833, + 1.0 + ], + [ + 2.6112878, + 1.1127571, + 1.0 + ], + [ + 3.734751, + 1.1181016, + 1.0 + ], + [ + 2.895584, + 1.0769328, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.7645093, + 1.0585829, + 1.0 + ], + [ + 2.7074714, + 1.1086032, + 1.0 + ], + [ + 4.612825, + 1.121013, + 1.0 + ], + [ + 4.2159166, + 1.090578, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.317804, + 1.0096856, + 1.0 + ], + [ + 2.410078, + 1.0813844, + 1.0 + ], + [ + 4.022777, + 1.0866787, + 1.0 + ], + [ + 1.5960958, + 1.0285214, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.7581048, + 0.94621634, + 1.0 + ], + [ + 3.344702, + 1.031301, + 1.0 + ], + [ + 1.6271458, + 1.0360217, + 1.0 + ], + [ + 0.045802835, + 1.0040928, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.2102604, + 0.8877613, + 1.0 + ], + [ + 2.5063229, + 0.9831511, + 1.0 + ], + [ + 1.0589613, + 1.0087296, + 1.0 + ], + [ + 0.044849876, + 1.0006486, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.8181234, + 0.84908885, + 1.0 + ], + [ + 1.2979459, + 0.9558577, + 1.0 + ], + [ + 0.95269287, + 0.9990587, + 1.0 + ], + [ + 0.13956869, + 0.99899775, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.4218108, + 0.8245256, + 1.0 + ], + [ + 0.980773, + 0.95178086, + 1.0 + ], + [ + 0.44153172, + 1.004565, + 1.0 + ], + [ + 0.083737634, + 0.9998738, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.3112286, + 0.81245995, + 1.0 + ], + [ + 1.2433338, + 0.94633913, + 1.0 + ], + [ + -0.45147318, + 1.0128739, + 1.0 + ], + [ + -0.040671885, + 1.0012027, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.0959775, + 0.82676107, + 1.0 + ], + [ + 0.19708328, + 0.9494545, + 1.0 + ], + [ + -0.71126884, + 1.0130774, + 1.0 + ], + [ + -0.066266306, + 1.0014489, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.0682087, + 0.85580033, + 1.0 + ], + [ + 0.33310115, + 0.9754608, + 1.0 + ], + [ + -0.038120847, + 1.0069447, + 1.0 + ], + [ + -0.0039369226, + 1.0006703, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.4665134, + 0.8869471, + 1.0 + ], + [ + 1.394241, + 0.9861353, + 1.0 + ], + [ + 0.39206934, + 1.0029631, + 1.0 + ], + [ + 0.012310251, + 1.0002207, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.840249, + 0.885747, + 1.0 + ], + [ + 2.030714, + 0.97694564, + 1.0 + ], + [ + 0.48313063, + 0.9986679, + 1.0 + ], + [ + 0.015092909, + 1.0000398, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 6.364709, + 0.93935746, + 1.0 + ], + [ + 3.27353, + 1.0063933, + 1.0 + ], + [ + 0.47039714, + 1.0006171, + 1.0 + ], + [ + 0.0095254835, + 0.9999786, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.708454, + 0.9936273, + 1.0 + ], + [ + 3.0144715, + 1.0396764, + 1.0 + ], + [ + 0.76019174, + 1.0015196, + 1.0 + ], + [ + 0.031606715, + 0.9997963, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.081264, + 1.007644, + 1.0 + ], + [ + 0.9569218, + 1.0373055, + 1.0 + ], + [ + -0.29632938, + 1.0081192, + 1.0 + ], + [ + -0.020595783, + 1.0002273, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.4333196, + 0.9922466, + 1.0 + ], + [ + 0.8624292, + 1.0051231, + 1.0 + ], + [ + -0.124487296, + 1.0007266, + 1.0 + ], + [ + 0.0014794656, + 1.0001725, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.0025764, + 0.9966404, + 1.0 + ], + [ + 0.32528183, + 1.0222802, + 1.0 + ], + [ + -1.4467791, + 1.0029583, + 1.0 + ], + [ + -0.09876483, + 1.0001086, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.9974155, + 0.9894437, + 1.0 + ], + [ + 2.0329673, + 1.0394019, + 1.0 + ], + [ + -0.49002603, + 1.0067779, + 1.0 + ], + [ + -0.091952406, + 0.9999813, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.90883, + 0.9736301, + 1.0 + ], + [ + 2.7153323, + 1.0357952, + 1.0 + ], + [ + 0.37018985, + 1.0083603, + 1.0 + ], + [ + -0.0096038, + 1.0001452, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.1170373, + 0.98292226, + 1.0 + ], + [ + 1.2927599, + 1.035257, + 1.0 + ], + [ + 0.3150436, + 1.0090348, + 1.0 + ], + [ + 0.0004185312, + 1.0000962, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.3353724, + 0.9857392, + 1.0 + ], + [ + 0.9401049, + 1.0468453, + 1.0 + ], + [ + -0.13837458, + 1.0182233, + 1.0 + ], + [ + -0.024829892, + 1.0004286, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.5100236, + 1.0068982, + 1.0 + ], + [ + 0.93617123, + 1.0617714, + 1.0 + ], + [ + 0.047028802, + 1.0331767, + 1.0 + ], + [ + 0.0046950956, + 1.0010607, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.6971107, + 1.0113055, + 1.0 + ], + [ + -0.20543085, + 1.0561123, + 1.0 + ], + [ + -0.47802702, + 1.0383303, + 1.0 + ], + [ + 0.07525184, + 1.0021627, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.8135715, + 1.0148535, + 1.0 + ], + [ + 0.23203266, + 1.0550131, + 1.0 + ], + [ + -0.023389658, + 1.04285, + 1.0 + ], + [ + 0.19465668, + 1.002981, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.6685414, + 1.0124575, + 1.0 + ], + [ + 0.59984475, + 1.0448725, + 1.0 + ], + [ + 0.69587445, + 1.0372711, + 1.0 + ], + [ + 0.60554105, + 1.005815, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.5002728, + 1.0161368, + 1.0 + ], + [ + 0.56248856, + 1.058378, + 1.0 + ], + [ + 0.9347412, + 1.0511781, + 1.0 + ], + [ + 0.8927735, + 1.0201077, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.8510935, + 1.0004079, + 1.0 + ], + [ + -0.13690601, + 1.0438355, + 1.0 + ], + [ + 0.5490022, + 1.0381058, + 1.0 + ], + [ + 1.4847147, + 1.0113307, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.2298164, + 0.98695815, + 1.0 + ], + [ + -0.5338396, + 1.008648, + 1.0 + ], + [ + -0.1529312, + 1.0192995, + 1.0 + ], + [ + 1.3007274, + 0.98695505, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.9663947, + 0.9861699, + 1.0 + ], + [ + 0.3281501, + 0.9828017, + 1.0 + ], + [ + -0.9316485, + 0.9753089, + 1.0 + ], + [ + -0.45177975, + 0.9492595, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.8109272, + 0.98814505, + 1.0 + ], + [ + -0.06094338, + 0.99206847, + 1.0 + ], + [ + -1.5175383, + 0.982531, + 1.0 + ], + [ + -1.9885272, + 0.954517, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.5236363, + 0.9898073, + 1.0 + ], + [ + -0.5354513, + 1.0057786, + 1.0 + ], + [ + -2.319607, + 1.0002798, + 1.0 + ], + [ + -3.4267511, + 0.97033256, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.6655283, + 1.0100801, + 1.0 + ], + [ + -1.0105478, + 1.0113044, + 1.0 + ], + [ + -3.3712995, + 0.9907962, + 1.0 + ], + [ + -5.3614125, + 0.957974, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.55430204, + 1.0288806, + 1.0 + ], + [ + -2.2823086, + 1.0114845, + 1.0 + ], + [ + -4.29412, + 0.9850471, + 1.0 + ], + [ + -6.70813, + 0.94654834, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.28653958, + 1.029249, + 1.0 + ], + [ + -2.9026222, + 1.0021783, + 1.0 + ], + [ + -4.3481326, + 0.98601437, + 1.0 + ], + [ + -6.742446, + 0.94504565, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.840411, + 1.0304451, + 1.0 + ], + [ + -1.7543678, + 1.0166836, + 1.0 + ], + [ + -4.263933, + 0.98349094, + 1.0 + ], + [ + -7.782672, + 0.9144162, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.9039959, + 1.0615926, + 1.0 + ], + [ + -0.6004897, + 1.0442605, + 1.0 + ], + [ + -3.2590501, + 0.9852762, + 1.0 + ], + [ + -6.0829635, + 0.92023736, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.113609, + 1.1155086, + 1.0 + ], + [ + 0.7005239, + 1.0668454, + 1.0 + ], + [ + -1.9628628, + 0.9854875, + 1.0 + ], + [ + -5.3814754, + 0.90371615, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.0877285, + 1.1595732, + 1.0 + ], + [ + 1.9560493, + 1.0802444, + 1.0 + ], + [ + -0.77529097, + 0.9800677, + 1.0 + ], + [ + -5.565922, + 0.8722543, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.288913, + 1.2051771, + 1.0 + ], + [ + 2.74089, + 1.1004237, + 1.0 + ], + [ + 0.012938409, + 0.9697918, + 1.0 + ], + [ + -5.393885, + 0.8341304, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.8245485, + 1.2282706, + 1.0 + ], + [ + 2.9895375, + 1.1039253, + 1.0 + ], + [ + 1.2145354, + 0.95314676, + 1.0 + ], + [ + -2.3480604, + 0.8217049, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.0588024, + 1.2314723, + 1.0 + ], + [ + 2.7796125, + 1.0972726, + 1.0 + ], + [ + 2.4223437, + 0.9613367, + 1.0 + ], + [ + 1.6759906, + 0.8447568, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.8357061, + 1.210052, + 1.0 + ], + [ + 2.2408845, + 1.0848253, + 1.0 + ], + [ + 2.808005, + 0.9623734, + 1.0 + ], + [ + 3.4482584, + 0.8608864, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.69474894, + 1.1947756, + 1.0 + ], + [ + 1.6912163, + 1.0640128, + 1.0 + ], + [ + 3.070553, + 0.93303436, + 1.0 + ], + [ + 5.026965, + 0.83831453, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.02924209, + 1.1594467, + 1.0 + ], + [ + 1.437672, + 1.0297697, + 1.0 + ], + [ + 3.5909321, + 0.90887827, + 1.0 + ], + [ + 5.7714977, + 0.8360717, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.73282367, + 1.1322978, + 1.0 + ], + [ + 1.0370998, + 1.0152173, + 1.0 + ], + [ + 2.9553826, + 0.93621993, + 1.0 + ], + [ + 4.670117, + 0.86914015, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.619349, + 1.1252851, + 1.0 + ], + [ + 0.15239729, + 1.0244952, + 1.0 + ], + [ + 1.6071638, + 0.960652, + 1.0 + ], + [ + 2.7668586, + 0.8957443, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.4471934, + 1.1201713, + 1.0 + ], + [ + -0.9853024, + 1.0402389, + 1.0 + ], + [ + -0.10679894, + 1.0003766, + 1.0 + ], + [ + 0.38707855, + 0.9576168, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -3.6268017, + 1.1333272, + 1.0 + ], + [ + -2.5076745, + 1.071064, + 1.0 + ], + [ + -1.8380454, + 1.0375947, + 1.0 + ], + [ + -0.49257776, + 1.0004728, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -4.8864617, + 1.1463132, + 1.0 + ], + [ + -3.6842506, + 1.0934086, + 1.0 + ], + [ + -2.3747447, + 1.0497583, + 1.0 + ], + [ + -0.121673696, + 1.0016263, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -6.1770673, + 1.1691642, + 1.0 + ], + [ + -4.8939047, + 1.1140888, + 1.0 + ], + [ + -2.1122801, + 1.0347022, + 1.0 + ], + [ + -0.2781079, + 0.9971531, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.824204, + 1.1899806, + 1.0 + ], + [ + -6.7190065, + 1.1285441, + 1.0 + ], + [ + -5.1226296, + 0.9854947, + 1.0 + ], + [ + -4.016408, + 0.9494332, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.926484, + 1.1482611, + 1.0 + ], + [ + -7.6249037, + 1.0958742, + 1.0 + ], + [ + -5.6792645, + 0.9760871, + 1.0 + ], + [ + -4.0723734, + 0.94808024, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.670957, + 1.1153084, + 1.0 + ], + [ + -8.038458, + 1.0422579, + 1.0 + ], + [ + -5.8509502, + 0.9850574, + 1.0 + ], + [ + -0.8264564, + 0.9961184, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -10.342434, + 1.0856272, + 1.0 + ], + [ + -9.040556, + 1.0213751, + 1.0 + ], + [ + -7.0447855, + 0.9760523, + 1.0 + ], + [ + -0.8563134, + 0.9967798, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -11.15017, + 1.0738698, + 1.0 + ], + [ + -8.293659, + 1.0015079, + 1.0 + ], + [ + -3.465691, + 0.95468867, + 1.0 + ], + [ + -0.26872262, + 0.996449, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -12.361571, + 1.0671077, + 1.0 + ], + [ + -8.069062, + 0.9878739, + 1.0 + ], + [ + -1.8393602, + 0.9616174, + 1.0 + ], + [ + -0.062451784, + 0.99806386, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -11.813561, + 1.0733019, + 1.0 + ], + [ + -6.277449, + 0.9938862, + 1.0 + ], + [ + -0.91688836, + 0.98827964, + 1.0 + ], + [ + -0.015721286, + 0.99975455, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -11.033608, + 1.0607992, + 1.0 + ], + [ + -5.8924174, + 1.0059938, + 1.0 + ], + [ + -0.4630321, + 0.99918526, + 1.0 + ], + [ + -0.0028961068, + 0.9999799, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -13.24634, + 1.0676687, + 1.0 + ], + [ + -8.926855, + 1.0089554, + 1.0 + ], + [ + -1.2582607, + 0.998966, + 1.0 + ], + [ + -0.01142765, + 0.9999851, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -14.128018, + 1.0785146, + 1.0 + ], + [ + -8.119614, + 1.0094862, + 1.0 + ], + [ + -1.2649353, + 0.99898714, + 1.0 + ], + [ + -0.015170822, + 0.9999889, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -12.451852, + 1.0737165, + 1.0 + ], + [ + -6.9139895, + 1.0113754, + 1.0 + ], + [ + -1.088725, + 1.0001466, + 1.0 + ], + [ + -0.013777146, + 1.0000031, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -12.380149, + 1.0823865, + 1.0 + ], + [ + -6.0622687, + 1.0224757, + 1.0 + ], + [ + -0.49693757, + 1.0009257, + 1.0 + ], + [ + -0.004322603, + 1.0000051, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -13.628408, + 1.0830122, + 1.0 + ], + [ + -7.603063, + 1.0293987, + 1.0 + ], + [ + -0.7915703, + 1.0023602, + 1.0 + ], + [ + -0.005485728, + 1.0000141, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -15.070874, + 1.025278, + 1.0 + ], + [ + -8.004763, + 0.9920342, + 1.0 + ], + [ + -0.6927761, + 0.99896514, + 1.0 + ], + [ + -0.0051751113, + 0.99998105, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -15.791659, + 0.9914543, + 1.0 + ], + [ + -7.6757627, + 0.9670585, + 1.0 + ], + [ + -0.94827396, + 0.98121995, + 1.0 + ], + [ + -0.042875327, + 0.99850494, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -15.504122, + 0.918028, + 1.0 + ], + [ + -9.548977, + 0.89464694, + 1.0 + ], + [ + -2.6915827, + 0.9125134, + 1.0 + ], + [ + -0.46877646, + 0.9763951, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -15.834205, + 0.86167675, + 1.0 + ], + [ + -11.029793, + 0.8641353, + 1.0 + ], + [ + -2.304663, + 0.940338, + 1.0 + ], + [ + -0.22860166, + 0.9885806, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -15.163353, + 0.80446744, + 1.0 + ], + [ + -10.703714, + 0.82697487, + 1.0 + ], + [ + -1.8142037, + 0.948325, + 1.0 + ], + [ + -0.0477379, + 0.998123, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -14.573051, + 0.76530474, + 1.0 + ], + [ + -10.532188, + 0.808058, + 1.0 + ], + [ + -1.7215453, + 0.94441307, + 1.0 + ], + [ + -0.0065259486, + 0.99902344, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -11.712678, + 0.78053474, + 1.0 + ], + [ + -9.12928, + 0.8284735, + 1.0 + ], + [ + -3.0647676, + 0.9377219, + 1.0 + ], + [ + -0.02522077, + 0.9987442, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.4553695, + 0.88699067, + 1.0 + ], + [ + -4.486537, + 0.9664551, + 1.0 + ], + [ + -1.3492911, + 1.0004994, + 1.0 + ], + [ + 0.20210887, + 0.98605, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.5626588, + 1.0187794, + 1.0 + ], + [ + -0.16849272, + 1.0859944, + 1.0 + ], + [ + 1.1092399, + 1.1023259, + 1.0 + ], + [ + 1.3777262, + 1.0548018, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.040617283, + 1.066993, + 1.0 + ], + [ + 1.53646, + 1.1038263, + 1.0 + ], + [ + 2.3726995, + 1.106449, + 1.0 + ], + [ + 2.8319159, + 1.0958794, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.8091955, + 1.042359, + 1.0 + ], + [ + 2.302053, + 1.0939299, + 1.0 + ], + [ + 3.1255443, + 1.0935813, + 1.0 + ], + [ + 3.7047086, + 1.0906761, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.4341065, + 0.9560042, + 1.0 + ], + [ + 2.3559563, + 1.0608075, + 1.0 + ], + [ + 3.3579242, + 1.0881857, + 1.0 + ], + [ + 3.2111607, + 1.0706342, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.0547562, + 0.8983519, + 1.0 + ], + [ + 3.383354, + 0.9991967, + 1.0 + ], + [ + 1.8556306, + 1.0425386, + 1.0 + ], + [ + 0.0885949, + 1.0138919, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.7682338, + 0.8603291, + 1.0 + ], + [ + 3.0132825, + 0.9588983, + 1.0 + ], + [ + 1.9995759, + 1.0111612, + 1.0 + ], + [ + 0.47482064, + 1.006286, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.6232177, + 0.8233142, + 1.0 + ], + [ + 2.0865932, + 0.9309424, + 1.0 + ], + [ + 2.7574844, + 0.97783035, + 1.0 + ], + [ + 0.95219344, + 0.99299604, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.6943194, + 0.79197764, + 1.0 + ], + [ + 1.8879877, + 0.920102, + 1.0 + ], + [ + 1.2647737, + 0.9986511, + 1.0 + ], + [ + 0.3897333, + 1.0005867, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.7574468, + 0.78670424, + 1.0 + ], + [ + 2.1780686, + 0.9121051, + 1.0 + ], + [ + -0.5525949, + 1.0213124, + 1.0 + ], + [ + -0.2346502, + 1.0064204, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.4999485, + 0.7841847, + 1.0 + ], + [ + 1.9435306, + 0.9184122, + 1.0 + ], + [ + -1.5851839, + 1.0305399, + 1.0 + ], + [ + -0.36774108, + 1.0069425, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.909163, + 0.80230415, + 1.0 + ], + [ + 2.1358707, + 0.935365, + 1.0 + ], + [ + -0.84193116, + 1.0221872, + 1.0 + ], + [ + -0.14351588, + 1.0037925, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 6.5533886, + 0.8221586, + 1.0 + ], + [ + 3.3628576, + 0.95415354, + 1.0 + ], + [ + 0.8394116, + 1.0065193, + 1.0 + ], + [ + 0.021697784, + 1.000693, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 8.034471, + 0.84136575, + 1.0 + ], + [ + 4.6422033, + 0.9475814, + 1.0 + ], + [ + 1.4912386, + 0.99571365, + 1.0 + ], + [ + 0.018330399, + 1.0000721, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 7.851116, + 0.9006105, + 1.0 + ], + [ + 5.2049785, + 0.9920339, + 1.0 + ], + [ + 1.2569566, + 0.99717367, + 1.0 + ], + [ + 0.0052652257, + 0.9997678, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 7.6648865, + 0.9650344, + 1.0 + ], + [ + 4.729117, + 1.0339372, + 1.0 + ], + [ + 2.091848, + 0.99583614, + 1.0 + ], + [ + 0.10322704, + 0.99907774, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 7.6680355, + 0.9877355, + 1.0 + ], + [ + 3.6761901, + 1.0451121, + 1.0 + ], + [ + -0.04351923, + 1.0153469, + 1.0 + ], + [ + -0.03283479, + 1.0004294, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 6.463548, + 0.96174765, + 1.0 + ], + [ + 2.6405559, + 1.0113807, + 1.0 + ], + [ + -0.0145218745, + 1.0030446, + 1.0 + ], + [ + 0.02793165, + 1.0006396, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 6.7405667, + 0.97143346, + 1.0 + ], + [ + 1.3641241, + 1.0326787, + 1.0 + ], + [ + -3.4862273, + 1.0015736, + 1.0 + ], + [ + -0.47250292, + 0.99943143, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 8.19507, + 0.96321476, + 1.0 + ], + [ + 3.4350495, + 1.058396, + 1.0 + ], + [ + -3.5258145, + 1.0094136, + 1.0 + ], + [ + -1.0841179, + 0.9979366, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 7.8372226, + 0.95261025, + 1.0 + ], + [ + 4.014715, + 1.0542111, + 1.0 + ], + [ + 0.26240677, + 1.0264678, + 1.0 + ], + [ + -0.21519896, + 1.0007783, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.1908545, + 0.95756376, + 1.0 + ], + [ + 1.8382027, + 1.0398521, + 1.0 + ], + [ + 0.32465455, + 1.0176383, + 1.0 + ], + [ + -0.07286978, + 0.99991214, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 6.5853324, + 0.9502199, + 1.0 + ], + [ + 0.9021832, + 1.0475446, + 1.0 + ], + [ + -0.38347927, + 1.0296501, + 1.0 + ], + [ + -0.10875285, + 1.0017142, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 7.5904784, + 0.95001745, + 1.0 + ], + [ + 0.3187001, + 1.0552145, + 1.0 + ], + [ + -0.065457314, + 1.0441794, + 1.0 + ], + [ + 0.1682706, + 1.0044458, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 7.727416, + 0.9608402, + 1.0 + ], + [ + -0.4404374, + 1.0511845, + 1.0 + ], + [ + 0.13549781, + 1.0374392, + 1.0 + ], + [ + 1.0298581, + 1.0050887, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 7.1869535, + 0.96325994, + 1.0 + ], + [ + 0.21250498, + 1.0488186, + 1.0 + ], + [ + 0.5558834, + 1.0353485, + 1.0 + ], + [ + 1.3571175, + 1.0007496, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 6.2386184, + 0.97497666, + 1.0 + ], + [ + 0.37397635, + 1.0394269, + 1.0 + ], + [ + 0.7773281, + 1.034625, + 1.0 + ], + [ + 1.4875422, + 1.0045793, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.65055, + 0.98630524, + 1.0 + ], + [ + 0.3505162, + 1.0497316, + 1.0 + ], + [ + 1.0327646, + 1.0434405, + 1.0 + ], + [ + 1.5126252, + 1.0201807, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.1305985, + 0.95614517, + 1.0 + ], + [ + -0.6686687, + 0.96170896, + 1.0 + ], + [ + 0.31405145, + 0.94526744, + 1.0 + ], + [ + 0.7571128, + 0.93466496, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.7789507, + 0.96007, + 1.0 + ], + [ + 0.025442632, + 0.9322739, + 1.0 + ], + [ + 1.002043, + 0.92365426, + 1.0 + ], + [ + 1.4359783, + 0.9207567, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.5217903, + 0.9649529, + 1.0 + ], + [ + 1.3698361, + 0.93013364, + 1.0 + ], + [ + 0.81097263, + 0.8966511, + 1.0 + ], + [ + 1.3134359, + 0.9056901, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.4688148, + 0.94516605, + 1.0 + ], + [ + 1.1258384, + 0.9285592, + 1.0 + ], + [ + -0.03493635, + 0.9379082, + 1.0 + ], + [ + -0.34919712, + 0.92182875, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.0855563, + 0.9416833, + 1.0 + ], + [ + 0.61865765, + 0.95953137, + 1.0 + ], + [ + -0.53801084, + 0.98488677, + 1.0 + ], + [ + -1.3929236, + 0.9545244, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.280524, + 0.9401836, + 1.0 + ], + [ + 0.5206633, + 0.91849095, + 1.0 + ], + [ + -0.5855471, + 0.9109686, + 1.0 + ], + [ + -1.857449, + 0.9108761, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.1066036, + 0.91177595, + 1.0 + ], + [ + -0.2379211, + 0.90215147, + 1.0 + ], + [ + -0.662678, + 0.8674564, + 1.0 + ], + [ + -1.6655282, + 0.8560494, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.3806509, + 0.91369975, + 1.0 + ], + [ + -1.1977674, + 0.9291132, + 1.0 + ], + [ + -2.1955984, + 0.9157609, + 1.0 + ], + [ + -3.2753534, + 0.8795514, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.27487, + 0.8657369, + 1.0 + ], + [ + 0.84525156, + 0.8752064, + 1.0 + ], + [ + -1.1533172, + 0.88577944, + 1.0 + ], + [ + -4.5261264, + 0.8575033, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.6447818, + 0.8502878, + 1.0 + ], + [ + 1.9611719, + 0.87647694, + 1.0 + ], + [ + -0.25773066, + 0.88421917, + 1.0 + ], + [ + -2.0909984, + 0.84323335, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.3915353, + 0.95410204, + 1.0 + ], + [ + 1.9980977, + 0.9531656, + 1.0 + ], + [ + 0.5931035, + 0.88896406, + 1.0 + ], + [ + -1.3361316, + 0.8371896, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.3264365, + 1.0299196, + 1.0 + ], + [ + 2.5364761, + 0.97348475, + 1.0 + ], + [ + 1.3221674, + 0.88718134, + 1.0 + ], + [ + -0.9853643, + 0.8285287, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.1308208, + 1.0718769, + 1.0 + ], + [ + 2.790149, + 0.9912555, + 1.0 + ], + [ + 1.4749019, + 0.8944228, + 1.0 + ], + [ + -1.1555754, + 0.8163407, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.2958386, + 1.088511, + 1.0 + ], + [ + 2.6916971, + 0.9975709, + 1.0 + ], + [ + 1.9740455, + 0.88601756, + 1.0 + ], + [ + 0.36857194, + 0.80993265, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.5474374, + 1.0788504, + 1.0 + ], + [ + 2.225414, + 0.97936237, + 1.0 + ], + [ + 1.8757105, + 0.88728917, + 1.0 + ], + [ + 1.5990429, + 0.8291341, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.2438161, + 1.036749, + 1.0 + ], + [ + 1.3613421, + 0.9619165, + 1.0 + ], + [ + 1.4527313, + 0.8871177, + 1.0 + ], + [ + 2.0332718, + 0.8303382, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.09551922, + 1.0317862, + 1.0 + ], + [ + 0.43391225, + 0.9460805, + 1.0 + ], + [ + 1.4488848, + 0.8737923, + 1.0 + ], + [ + 3.4753993, + 0.81625134, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.7019963, + 1.0077614, + 1.0 + ], + [ + -0.051761873, + 0.9282602, + 1.0 + ], + [ + 1.9012142, + 0.8732041, + 1.0 + ], + [ + 4.1987333, + 0.82554394, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.6378045, + 1.0135831, + 1.0 + ], + [ + -0.38506448, + 0.9445609, + 1.0 + ], + [ + 1.5109704, + 0.91002667, + 1.0 + ], + [ + 3.479174, + 0.8619353, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.4618201, + 1.033089, + 1.0 + ], + [ + -1.2937772, + 0.97869325, + 1.0 + ], + [ + 0.10574721, + 0.9512708, + 1.0 + ], + [ + 1.488456, + 0.92858106, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -3.1203666, + 1.0350168, + 1.0 + ], + [ + -2.2538068, + 0.99723995, + 1.0 + ], + [ + -1.1310667, + 0.97431004, + 1.0 + ], + [ + 0.084608465, + 0.98049074, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -4.3735642, + 1.0520235, + 1.0 + ], + [ + -3.6140828, + 1.0261108, + 1.0 + ], + [ + -1.7979896, + 1.003871, + 1.0 + ], + [ + -0.05716326, + 0.9986102, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -5.2478585, + 1.0614483, + 1.0 + ], + [ + -4.203233, + 1.0365448, + 1.0 + ], + [ + -1.1785761, + 1.0052958, + 1.0 + ], + [ + -0.012518613, + 0.999905, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -5.7618976, + 1.0709513, + 1.0 + ], + [ + -4.2346697, + 1.041181, + 1.0 + ], + [ + -0.55711687, + 1.0027059, + 1.0 + ], + [ + -0.012013823, + 0.99982893, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -7.164432, + 1.0977043, + 1.0 + ], + [ + -4.544374, + 1.0551589, + 1.0 + ], + [ + -0.9486156, + 1.0006344, + 1.0 + ], + [ + -0.2880987, + 0.99641603, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.89083, + 1.0878369, + 1.0 + ], + [ + -5.120464, + 1.0464156, + 1.0 + ], + [ + -0.8068461, + 0.99902976, + 1.0 + ], + [ + -0.2889861, + 0.9960283, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.618337, + 1.0371728, + 1.0 + ], + [ + -5.1906323, + 1.007005, + 1.0 + ], + [ + -2.135625, + 0.9941443, + 1.0 + ], + [ + -0.21111596, + 0.99932176, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.985677, + 1.0003744, + 1.0 + ], + [ + -5.3432465, + 0.98975044, + 1.0 + ], + [ + -2.6925411, + 0.99021024, + 1.0 + ], + [ + -0.2637423, + 0.99901223, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.557486, + 1.0012228, + 1.0 + ], + [ + -5.126186, + 0.97562605, + 1.0 + ], + [ + -1.487278, + 0.9767831, + 1.0 + ], + [ + -0.09417072, + 0.99855137, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.93245, + 0.9848428, + 1.0 + ], + [ + -5.005292, + 0.95344836, + 1.0 + ], + [ + -1.0024476, + 0.97530013, + 1.0 + ], + [ + -0.03428691, + 0.9989181, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -10.067035, + 0.99813294, + 1.0 + ], + [ + -3.760256, + 0.9666209, + 1.0 + ], + [ + -0.43569535, + 0.9912011, + 1.0 + ], + [ + -0.007490502, + 0.99986094, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.267269, + 0.975714, + 1.0 + ], + [ + -3.3425367, + 0.97395366, + 1.0 + ], + [ + -0.16193047, + 0.99658626, + 1.0 + ], + [ + -0.00091553305, + 0.9999671, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.993388, + 1.0000288, + 1.0 + ], + [ + -4.422481, + 0.985607, + 1.0 + ], + [ + -0.32398883, + 0.9973332, + 1.0 + ], + [ + -0.0023061063, + 0.99997354, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.084186, + 0.9982832, + 1.0 + ], + [ + -2.7218752, + 0.9938026, + 1.0 + ], + [ + -0.17255202, + 0.9993347, + 1.0 + ], + [ + -0.0015168872, + 0.99999547, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.26013, + 0.9777609, + 1.0 + ], + [ + -2.3467531, + 0.98704755, + 1.0 + ], + [ + -0.09092708, + 0.9993146, + 1.0 + ], + [ + -0.00067042705, + 0.9999976, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.507622, + 0.9864571, + 1.0 + ], + [ + -1.6202773, + 0.9965017, + 1.0 + ], + [ + -0.03161555, + 0.999892, + 1.0 + ], + [ + -0.00015287292, + 0.9999998, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.677804, + 0.9922909, + 1.0 + ], + [ + -1.5864677, + 1.0017024, + 1.0 + ], + [ + -0.029533267, + 1.0000547, + 1.0 + ], + [ + -0.00012411954, + 1.0000002, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.914085, + 0.95310205, + 1.0 + ], + [ + -2.334698, + 0.99508375, + 1.0 + ], + [ + -0.04895491, + 0.99995136, + 1.0 + ], + [ + -0.00017408784, + 0.9999993, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -13.237178, + 0.8746589, + 1.0 + ], + [ + -3.9431214, + 0.96841735, + 1.0 + ], + [ + -0.13730685, + 0.99794483, + 1.0 + ], + [ + -0.0053191665, + 0.999769, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -14.975474, + 0.80612254, + 1.0 + ], + [ + -5.441822, + 0.93426883, + 1.0 + ], + [ + -0.5847607, + 0.97942346, + 1.0 + ], + [ + -0.0973578, + 0.99491835, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -16.96701, + 0.7174082, + 1.0 + ], + [ + -7.501978, + 0.8796432, + 1.0 + ], + [ + -0.55444115, + 0.9846425, + 1.0 + ], + [ + -0.0493976, + 0.9975046, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -19.691572, + 0.6349826, + 1.0 + ], + [ + -11.398152, + 0.7708063, + 1.0 + ], + [ + -0.78708935, + 0.97114944, + 1.0 + ], + [ + -0.013223002, + 0.99905497, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -18.446426, + 0.61982644, + 1.0 + ], + [ + -14.164779, + 0.6866288, + 1.0 + ], + [ + -1.6122752, + 0.95558673, + 1.0 + ], + [ + -0.004578955, + 0.9995476, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -13.488046, + 0.67327017, + 1.0 + ], + [ + -11.041826, + 0.6985784, + 1.0 + ], + [ + -3.797718, + 0.8836202, + 1.0 + ], + [ + -0.021354746, + 0.9991143, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.215271, + 0.79168403, + 1.0 + ], + [ + -5.9288893, + 0.82115835, + 1.0 + ], + [ + -3.627646, + 0.8675918, + 1.0 + ], + [ + -0.10416387, + 0.9819024, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -3.4996793, + 0.90832794, + 1.0 + ], + [ + -1.8338926, + 0.95480883, + 1.0 + ], + [ + -1.2572361, + 0.96503127, + 1.0 + ], + [ + -0.7744646, + 0.9684802, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.1851404, + 0.9754471, + 1.0 + ], + [ + -0.38070896, + 0.9967761, + 1.0 + ], + [ + -0.20595744, + 0.99183595, + 1.0 + ], + [ + -0.04291819, + 0.991432, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.24601784, + 0.9362298, + 1.0 + ], + [ + 0.4131334, + 1.0015087, + 1.0 + ], + [ + 0.6097395, + 1.0106862, + 1.0 + ], + [ + 0.80979943, + 1.0157323, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.15171635, + 0.7862158, + 1.0 + ], + [ + 0.88354856, + 0.9524625, + 1.0 + ], + [ + 1.2969238, + 1.0249856, + 1.0 + ], + [ + 1.3480076, + 1.0304265, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.2697306, + 0.74219435, + 1.0 + ], + [ + 2.2566214, + 0.8504037, + 1.0 + ], + [ + 0.43116477, + 0.98642737, + 1.0 + ], + [ + -0.62197345, + 0.9856124, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.9409392, + 0.7197661, + 1.0 + ], + [ + 2.657014, + 0.82564926, + 1.0 + ], + [ + 0.75268286, + 0.9767613, + 1.0 + ], + [ + 0.055744026, + 0.9941756, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.8314111, + 0.7361832, + 1.0 + ], + [ + 2.2688785, + 0.83848625, + 1.0 + ], + [ + 0.86895645, + 0.979231, + 1.0 + ], + [ + 0.0529236, + 1.0007346, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.6000655, + 0.7524115, + 1.0 + ], + [ + 2.0968463, + 0.888389, + 1.0 + ], + [ + 0.18316315, + 0.9902795, + 1.0 + ], + [ + -0.048968393, + 0.99920696, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.5598903, + 0.763862, + 1.0 + ], + [ + 1.1714306, + 0.8932834, + 1.0 + ], + [ + -0.57951224, + 0.985895, + 1.0 + ], + [ + -0.13511501, + 0.99782085, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.1605225, + 0.7730435, + 1.0 + ], + [ + 1.3596042, + 0.9008872, + 1.0 + ], + [ + -0.47168514, + 0.99376947, + 1.0 + ], + [ + -0.07464302, + 1.000353, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.752158, + 0.79429775, + 1.0 + ], + [ + 0.96804696, + 0.9385464, + 1.0 + ], + [ + -1.3032031, + 0.99664253, + 1.0 + ], + [ + -0.2467647, + 0.99934804, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.692927, + 0.817162, + 1.0 + ], + [ + 1.2399592, + 0.9601324, + 1.0 + ], + [ + -0.2092135, + 0.99869674, + 1.0 + ], + [ + -0.04914082, + 0.9998154, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.3077126, + 0.8646981, + 1.0 + ], + [ + 1.169301, + 0.9719851, + 1.0 + ], + [ + -0.14287929, + 0.9983894, + 1.0 + ], + [ + -0.070898615, + 0.9997087, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.741663, + 0.89205533, + 1.0 + ], + [ + 0.64960855, + 0.9830752, + 1.0 + ], + [ + -0.11191467, + 0.9987406, + 1.0 + ], + [ + -0.047313914, + 0.99977046, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.5162182, + 0.94403803, + 1.0 + ], + [ + 0.07143193, + 0.9925508, + 1.0 + ], + [ + -0.72076577, + 0.9948075, + 1.0 + ], + [ + -0.1948217, + 0.9987798, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.585983, + 0.96052504, + 1.0 + ], + [ + 1.0876106, + 0.9904767, + 1.0 + ], + [ + -0.27299738, + 0.99780345, + 1.0 + ], + [ + -0.080156155, + 0.99953175, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.779256, + 0.9310572, + 1.0 + ], + [ + 0.7266878, + 0.986474, + 1.0 + ], + [ + 0.035173222, + 0.99929446, + 1.0 + ], + [ + 0.0016433608, + 1.0000198, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.0365615, + 0.94872975, + 1.0 + ], + [ + 0.30465418, + 0.9817023, + 1.0 + ], + [ + -0.34721652, + 0.99478245, + 1.0 + ], + [ + -0.061744135, + 0.99972767, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.8961987, + 0.92921335, + 1.0 + ], + [ + 0.23940657, + 0.9766385, + 1.0 + ], + [ + -1.319209, + 0.99436516, + 1.0 + ], + [ + -0.2552591, + 0.9993648, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.820354, + 0.9000567, + 1.0 + ], + [ + 0.93661356, + 0.9792745, + 1.0 + ], + [ + -1.2972772, + 1.0013816, + 1.0 + ], + [ + -0.2005057, + 1.0001276, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.8547032, + 0.8771825, + 1.0 + ], + [ + -0.40298477, + 0.92672235, + 1.0 + ], + [ + -0.76510406, + 0.983101, + 1.0 + ], + [ + -0.10773284, + 0.9988855, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.1437955, + 0.87208176, + 1.0 + ], + [ + -0.35798803, + 0.9345046, + 1.0 + ], + [ + -0.6719991, + 0.9889946, + 1.0 + ], + [ + -0.12287665, + 0.9989714, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.7768846, + 0.90311426, + 1.0 + ], + [ + -0.6762936, + 0.95233446, + 1.0 + ], + [ + -1.8836145, + 0.9920913, + 1.0 + ], + [ + -0.860416, + 0.9946867, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.8961434, + 0.8824976, + 1.0 + ], + [ + -0.33391425, + 0.92908406, + 1.0 + ], + [ + -0.3221192, + 0.9918024, + 1.0 + ], + [ + -0.09044509, + 0.9966171, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 6.8632536, + 0.90186435, + 1.0 + ], + [ + 0.58749425, + 0.9437153, + 1.0 + ], + [ + 0.48553416, + 0.98712, + 1.0 + ], + [ + 0.19696854, + 0.99386424, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.8013225, + 0.9050866, + 1.0 + ], + [ + -0.49256903, + 0.9264555, + 1.0 + ], + [ + -1.7974619, + 0.9501046, + 1.0 + ], + [ + -1.5920177, + 0.97445244, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.4498076, + 0.92861384, + 1.0 + ], + [ + -0.7343135, + 0.9649644, + 1.0 + ], + [ + -1.2369624, + 0.9541305, + 1.0 + ], + [ + -1.1794292, + 0.9540083, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.9042714, + 0.9180204, + 1.0 + ], + [ + -2.219778, + 0.86444235, + 1.0 + ], + [ + -2.4816806, + 0.823798, + 1.0 + ], + [ + -1.5569929, + 0.8375031, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.83755153, + 0.91707826, + 1.0 + ], + [ + 0.22283489, + 0.86605746, + 1.0 + ], + [ + 0.4647223, + 0.8345799, + 1.0 + ], + [ + 0.72768146, + 0.84671277, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.523536, + 0.9087665, + 1.0 + ], + [ + 1.2768013, + 0.85424995, + 1.0 + ], + [ + 2.1177902, + 0.8432673, + 1.0 + ], + [ + 2.3680518, + 0.8740304, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.2746108, + 0.81840515, + 1.0 + ], + [ + 2.7676985, + 0.7900528, + 1.0 + ], + [ + 1.9201541, + 0.8856915, + 1.0 + ], + [ + 1.8866074, + 0.9185119, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.6828327, + 0.8136951, + 1.0 + ], + [ + 2.175628, + 0.84009886, + 1.0 + ], + [ + 2.0939028, + 0.8847502, + 1.0 + ], + [ + 2.5929403, + 0.8947538, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.768817, + 0.7967659, + 1.0 + ], + [ + 3.2244751, + 0.7584971, + 1.0 + ], + [ + 3.6050847, + 0.7831417, + 1.0 + ], + [ + 4.268032, + 0.8045191, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.3562844, + 0.7890957, + 1.0 + ], + [ + 3.7188308, + 0.7199401, + 1.0 + ], + [ + 5.9207273, + 0.6976366, + 1.0 + ], + [ + 7.6120353, + 0.70215327, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.0832772, + 0.7600011, + 1.0 + ], + [ + 2.2862017, + 0.76166797, + 1.0 + ], + [ + 3.6557348, + 0.74157053, + 1.0 + ], + [ + 5.3892546, + 0.731114, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.7183886, + 0.6808121, + 1.0 + ], + [ + 3.3387003, + 0.70804834, + 1.0 + ], + [ + 3.3728793, + 0.7371294, + 1.0 + ], + [ + 4.041886, + 0.73437375, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.624325, + 0.6674578, + 1.0 + ], + [ + 4.5378666, + 0.6732078, + 1.0 + ], + [ + 4.398033, + 0.71216196, + 1.0 + ], + [ + 5.5895276, + 0.7182609, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 5.306699, + 0.747718, + 1.0 + ], + [ + 4.879655, + 0.70281416, + 1.0 + ], + [ + 5.1314225, + 0.7001976, + 1.0 + ], + [ + 5.486214, + 0.72053, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 4.146373, + 0.78986615, + 1.0 + ], + [ + 3.90747, + 0.7194833, + 1.0 + ], + [ + 4.436473, + 0.7135913, + 1.0 + ], + [ + 3.9732492, + 0.7439657, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.051203, + 0.8220685, + 1.0 + ], + [ + 2.5377185, + 0.73653644, + 1.0 + ], + [ + 3.6690881, + 0.73991066, + 1.0 + ], + [ + 2.8405402, + 0.76611686, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.0629168, + 0.88988215, + 1.0 + ], + [ + 1.5405259, + 0.80136687, + 1.0 + ], + [ + 2.3380709, + 0.755409, + 1.0 + ], + [ + 1.6457901, + 0.78002536, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.9272873, + 0.8686442, + 1.0 + ], + [ + 0.6143116, + 0.7969848, + 1.0 + ], + [ + 0.5216986, + 0.7725941, + 1.0 + ], + [ + 0.27696848, + 0.79700214, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.18347983, + 0.7820147, + 1.0 + ], + [ + -0.2920065, + 0.78137934, + 1.0 + ], + [ + -0.7294265, + 0.8024376, + 1.0 + ], + [ + -0.6821398, + 0.81814516, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.23992704, + 0.7879301, + 1.0 + ], + [ + -0.88038236, + 0.8075125, + 1.0 + ], + [ + -0.9809185, + 0.8284354, + 1.0 + ], + [ + -0.07751103, + 0.8428534, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.80605406, + 0.8354792, + 1.0 + ], + [ + -1.559409, + 0.80948555, + 1.0 + ], + [ + -0.7388032, + 0.83500856, + 1.0 + ], + [ + 0.69942343, + 0.88329875, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.6294653, + 0.85172844, + 1.0 + ], + [ + -1.7645487, + 0.8297184, + 1.0 + ], + [ + -0.7100293, + 0.8840055, + 1.0 + ], + [ + 0.2274858, + 0.9601816, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.2752452, + 0.8992305, + 1.0 + ], + [ + -2.2524478, + 0.9024475, + 1.0 + ], + [ + -0.6900573, + 0.96735644, + 1.0 + ], + [ + -0.01443623, + 0.99743444, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.3342621, + 0.9171061, + 1.0 + ], + [ + -2.169138, + 0.9233468, + 1.0 + ], + [ + -0.38522747, + 0.9775049, + 1.0 + ], + [ + 0.0013864042, + 0.9985635, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.9786882, + 0.9581507, + 1.0 + ], + [ + -1.0984265, + 0.9696264, + 1.0 + ], + [ + -0.10668975, + 0.9950265, + 1.0 + ], + [ + -0.0001844623, + 0.99983454, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.8451796, + 0.9728855, + 1.0 + ], + [ + -0.75453144, + 0.9875004, + 1.0 + ], + [ + -0.03869543, + 0.998888, + 1.0 + ], + [ + -0.00016324317, + 0.99999046, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.4833093, + 0.9710839, + 1.0 + ], + [ + -0.4503776, + 0.99415845, + 1.0 + ], + [ + -0.014969094, + 0.9998039, + 1.0 + ], + [ + -0.00005460353, + 0.99999875, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.155806, + 0.9922136, + 1.0 + ], + [ + -0.24781401, + 0.9983759, + 1.0 + ], + [ + -0.009547606, + 0.9999699, + 1.0 + ], + [ + -0.00066759216, + 0.9999967, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.4516653, + 0.99805427, + 1.0 + ], + [ + -0.20918414, + 0.999779, + 1.0 + ], + [ + -0.006043913, + 0.9999931, + 1.0 + ], + [ + -0.00048581572, + 0.99999654, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.9392998, + 0.98668915, + 1.0 + ], + [ + -0.14349174, + 0.99852246, + 1.0 + ], + [ + -0.01090069, + 0.99995995, + 1.0 + ], + [ + -0.00083713053, + 0.99999756, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.1864663, + 0.9834442, + 1.0 + ], + [ + -0.18628179, + 0.99777365, + 1.0 + ], + [ + -0.014109625, + 0.99992806, + 1.0 + ], + [ + -0.001064983, + 0.9999959, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.0547693, + 0.98770183, + 1.0 + ], + [ + -0.17180885, + 0.9951577, + 1.0 + ], + [ + -0.014593571, + 0.99926215, + 1.0 + ], + [ + -0.00052392326, + 0.99998504, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.3548598, + 0.97179633, + 1.0 + ], + [ + -0.51838243, + 0.95328885, + 1.0 + ], + [ + -0.06852023, + 0.99208575, + 1.0 + ], + [ + -0.00085176574, + 0.99991536, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.3932482, + 0.9842496, + 1.0 + ], + [ + -0.21709155, + 0.9691371, + 1.0 + ], + [ + -0.014957193, + 0.99505883, + 1.0 + ], + [ + -0.00015723599, + 0.99995285, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.95742047, + 0.9800242, + 1.0 + ], + [ + -0.09572666, + 0.9719048, + 1.0 + ], + [ + -0.0004223666, + 0.9954867, + 1.0 + ], + [ + 0.000010266345, + 0.9999555, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.8219641, + 0.97176534, + 1.0 + ], + [ + -0.10358055, + 0.9572014, + 1.0 + ], + [ + -0.0028769998, + 0.99260867, + 1.0 + ], + [ + -0.0000138675605, + 0.9999241, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.81078154, + 0.9853913, + 1.0 + ], + [ + -0.07060721, + 0.99701566, + 1.0 + ], + [ + -0.0011506415, + 0.99966466, + 1.0 + ], + [ + -0.0000053977897, + 0.99999666, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.8799515, + 0.9880938, + 1.0 + ], + [ + -0.09139433, + 0.99895227, + 1.0 + ], + [ + -0.0011206032, + 0.99998325, + 1.0 + ], + [ + -0.0000023958048, + 0.99999994, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -1.203021, + 0.98468393, + 1.0 + ], + [ + -0.09533536, + 0.9993307, + 1.0 + ], + [ + -0.0006138411, + 0.9999971, + 1.0 + ], + [ + -4.9110037e-7, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.98682314, + 0.98741007, + 1.0 + ], + [ + -0.07803176, + 0.99942106, + 1.0 + ], + [ + -0.0005139681, + 0.9999974, + 1.0 + ], + [ + -3.048391e-7, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.0533085, + 0.95174795, + 1.0 + ], + [ + -0.15526569, + 0.9967907, + 1.0 + ], + [ + -0.0011854534, + 0.9999825, + 1.0 + ], + [ + -0.0000012432189, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -4.3160176, + 0.8893779, + 1.0 + ], + [ + -0.37086096, + 0.99144685, + 1.0 + ], + [ + -0.0031809295, + 0.9999518, + 1.0 + ], + [ + -0.000015129414, + 0.9999994, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.65379, + 0.80011606, + 1.0 + ], + [ + -0.97619027, + 0.98192537, + 1.0 + ], + [ + -0.011185538, + 0.9998816, + 1.0 + ], + [ + -0.00027599925, + 0.999986, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -13.900999, + 0.6643516, + 1.0 + ], + [ + -2.2590377, + 0.93988913, + 1.0 + ], + [ + -0.021305703, + 0.99952126, + 1.0 + ], + [ + -0.00016454396, + 0.9999922, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -18.50311, + 0.5672969, + 1.0 + ], + [ + -6.324091, + 0.8226143, + 1.0 + ], + [ + -0.09798097, + 0.99709153, + 1.0 + ], + [ + -0.0001432513, + 0.99998575, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -17.64413, + 0.5391097, + 1.0 + ], + [ + -10.467655, + 0.66710144, + 1.0 + ], + [ + -0.2899716, + 0.9890324, + 1.0 + ], + [ + -0.00047773414, + 0.9999807, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -13.92279, + 0.5472615, + 1.0 + ], + [ + -10.895535, + 0.59090734, + 1.0 + ], + [ + -2.0764418, + 0.9041057, + 1.0 + ], + [ + -0.006843486, + 0.9997131, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.823085, + 0.59954053, + 1.0 + ], + [ + -8.007232, + 0.64031166, + 1.0 + ], + [ + -5.934222, + 0.7216933, + 1.0 + ], + [ + -0.21140227, + 0.98925734, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -6.0854692, + 0.68398213, + 1.0 + ], + [ + -4.9988737, + 0.7475099, + 1.0 + ], + [ + -4.5387487, + 0.783282, + 1.0 + ], + [ + -3.1189833, + 0.85521823, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -4.5944576, + 0.7649848, + 1.0 + ], + [ + -4.2297106, + 0.8085376, + 1.0 + ], + [ + -4.0575027, + 0.8316775, + 1.0 + ], + [ + -3.6946223, + 0.857067, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -4.07587, + 0.76617646, + 1.0 + ], + [ + -3.7157166, + 0.84208333, + 1.0 + ], + [ + -3.0963829, + 0.88380915, + 1.0 + ], + [ + -2.4804156, + 0.9129343, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.87624, + 0.6232938, + 1.0 + ], + [ + -2.6126328, + 0.7971155, + 1.0 + ], + [ + -1.7279347, + 0.92270774, + 1.0 + ], + [ + -1.2290946, + 0.95807064, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.7994735, + 0.57053953, + 1.0 + ], + [ + -0.84233916, + 0.6636242, + 1.0 + ], + [ + -2.5714352, + 0.87382954, + 1.0 + ], + [ + -3.015385, + 0.8965249, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.3739244, + 0.61843336, + 1.0 + ], + [ + 0.4184842, + 0.76101744, + 1.0 + ], + [ + -0.6304034, + 0.94809633, + 1.0 + ], + [ + -0.7494771, + 0.9597989, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.97610384, + 0.7327941, + 1.0 + ], + [ + -0.014398668, + 0.87566924, + 1.0 + ], + [ + -0.052118707, + 0.9924021, + 1.0 + ], + [ + 0.008521295, + 0.99918205, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.5996346, + 0.8233891, + 1.0 + ], + [ + 0.3935372, + 0.9229845, + 1.0 + ], + [ + -0.09391027, + 0.99190533, + 1.0 + ], + [ + -0.03780514, + 0.998876, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.9291275, + 0.9039172, + 1.0 + ], + [ + 0.74847955, + 0.9787055, + 1.0 + ], + [ + -0.16242525, + 0.9931886, + 1.0 + ], + [ + -0.072900325, + 0.9978617, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.3570204, + 0.94836956, + 1.0 + ], + [ + 0.2503319, + 0.99067676, + 1.0 + ], + [ + -0.06907828, + 0.9989688, + 1.0 + ], + [ + -0.017280824, + 0.9998503, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.26804498, + 0.9617563, + 1.0 + ], + [ + -0.30944353, + 0.9933201, + 1.0 + ], + [ + -0.83434904, + 0.9959094, + 1.0 + ], + [ + -0.16132122, + 0.999225, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.45194325, + 0.97071046, + 1.0 + ], + [ + -0.040852666, + 0.99767536, + 1.0 + ], + [ + -0.18153699, + 0.9991148, + 1.0 + ], + [ + -0.03368746, + 0.99983805, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.58231443, + 0.987187, + 1.0 + ], + [ + -0.11279778, + 0.9996504, + 1.0 + ], + [ + -0.007223121, + 0.999977, + 1.0 + ], + [ + -0.0013776413, + 0.9999941, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.27319077, + 0.9664841, + 1.0 + ], + [ + -0.21705957, + 0.9958635, + 1.0 + ], + [ + -0.017606068, + 0.99986523, + 1.0 + ], + [ + -0.0026193615, + 0.9999856, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.21634439, + 0.9787581, + 1.0 + ], + [ + -0.2651225, + 0.9962405, + 1.0 + ], + [ + -0.19124968, + 0.99883384, + 1.0 + ], + [ + -0.042182684, + 0.99975127, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.008343396, + 0.96074563, + 1.0 + ], + [ + -0.06034358, + 0.99365026, + 1.0 + ], + [ + -0.07409725, + 0.99946153, + 1.0 + ], + [ + -0.0167451, + 0.99990094, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.21916604, + 0.97861654, + 1.0 + ], + [ + 0.011656337, + 0.9968962, + 1.0 + ], + [ + 0.000026073394, + 0.9999265, + 1.0 + ], + [ + -0.00011303921, + 0.9999988, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.8516588, + 0.983058, + 1.0 + ], + [ + 0.05317016, + 0.9960106, + 1.0 + ], + [ + 0.0021729777, + 0.9996684, + 1.0 + ], + [ + -0.00008834622, + 0.9999944, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.33492264, + 0.97982824, + 1.0 + ], + [ + -0.023441888, + 0.9941379, + 1.0 + ], + [ + -0.012700134, + 0.9997447, + 1.0 + ], + [ + -0.0015705364, + 0.9999959, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.98577476, + 0.9558412, + 1.0 + ], + [ + 0.11146073, + 0.9861902, + 1.0 + ], + [ + -0.039014447, + 0.9995021, + 1.0 + ], + [ + -0.004039938, + 0.9999989, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 1.4198768, + 0.92014015, + 1.0 + ], + [ + 0.017510591, + 0.95569116, + 1.0 + ], + [ + -0.07619311, + 0.99643916, + 1.0 + ], + [ + -0.0026185187, + 0.99994844, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.02523843, + 0.90478045, + 1.0 + ], + [ + -1.0690092, + 0.92566043, + 1.0 + ], + [ + -0.27379805, + 0.99030024, + 1.0 + ], + [ + -0.012234708, + 0.9998211, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.112236924, + 0.94679946, + 1.0 + ], + [ + -0.619657, + 0.96057886, + 1.0 + ], + [ + -0.9257425, + 0.9906025, + 1.0 + ], + [ + -0.29495418, + 0.99792683, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.21400073, + 0.91529566, + 1.0 + ], + [ + -0.7458604, + 0.93239814, + 1.0 + ], + [ + -1.0380262, + 0.98454165, + 1.0 + ], + [ + -0.59706265, + 0.99349016, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.4457225, + 0.91300154, + 1.0 + ], + [ + -1.336635, + 0.9316419, + 1.0 + ], + [ + -2.2979734, + 0.9655022, + 1.0 + ], + [ + -1.344974, + 0.9845655, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.25027204, + 0.9015076, + 1.0 + ], + [ + -3.4001799, + 0.8766961, + 1.0 + ], + [ + -6.167441, + 0.87958527, + 1.0 + ], + [ + -3.0434742, + 0.9592666, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.8902801, + 0.87916595, + 1.0 + ], + [ + -3.0949912, + 0.86760527, + 1.0 + ], + [ + -5.8532324, + 0.81513554, + 1.0 + ], + [ + -4.114237, + 0.86317617, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.026975641, + 0.99708, + 1.0 + ], + [ + -0.64516276, + 0.9682286, + 1.0 + ], + [ + -2.8310719, + 0.86257124, + 1.0 + ], + [ + -1.7226968, + 0.90401584, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.082811065, + 0.9958276, + 1.0 + ], + [ + 0.029035931, + 0.98919505, + 1.0 + ], + [ + -0.10363939, + 0.9313849, + 1.0 + ], + [ + 0.010599485, + 0.93757856, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.30115137, + 0.995358, + 1.0 + ], + [ + 0.13033178, + 0.99306947, + 1.0 + ], + [ + 0.6179642, + 0.9668538, + 1.0 + ], + [ + 0.8925493, + 0.96109754, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.46534216, + 0.9799625, + 1.0 + ], + [ + 0.38193727, + 0.97773105, + 1.0 + ], + [ + 0.24684222, + 0.9894079, + 1.0 + ], + [ + 0.37070882, + 0.987069, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.28666112, + 0.9715252, + 1.0 + ], + [ + 0.6129641, + 0.9612684, + 1.0 + ], + [ + 1.5519472, + 0.9354917, + 1.0 + ], + [ + 2.0365298, + 0.9501482, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.5976872, + 0.95618755, + 1.0 + ], + [ + 2.4345472, + 0.8642554, + 1.0 + ], + [ + 4.334619, + 0.8086935, + 1.0 + ], + [ + 4.563015, + 0.845538, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.8365076, + 0.92973554, + 1.0 + ], + [ + 4.732671, + 0.7514679, + 1.0 + ], + [ + 8.749074, + 0.67412585, + 1.0 + ], + [ + 9.21404, + 0.70109785, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.420841, + 0.77831614, + 1.0 + ], + [ + 3.1613727, + 0.7190518, + 1.0 + ], + [ + 5.003848, + 0.7066909, + 1.0 + ], + [ + 6.8984137, + 0.7076504, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 3.2887714, + 0.6649921, + 1.0 + ], + [ + 3.2296984, + 0.6861676, + 1.0 + ], + [ + 3.542693, + 0.7290553, + 1.0 + ], + [ + 3.7580287, + 0.7677797, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 2.8353093, + 0.7206155, + 1.0 + ], + [ + 3.213582, + 0.7210075, + 1.0 + ], + [ + 3.050782, + 0.7906282, + 1.0 + ], + [ + 2.910971, + 0.86843896, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.73087895, + 0.9480793, + 1.0 + ], + [ + 1.3393304, + 0.90520597, + 1.0 + ], + [ + 1.8712325, + 0.8813981, + 1.0 + ], + [ + 1.7535455, + 0.9178119, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.2656817, + 0.9784777, + 1.0 + ], + [ + 0.6957168, + 0.93848366, + 1.0 + ], + [ + 1.0034746, + 0.92618793, + 1.0 + ], + [ + 0.6805362, + 0.95591986, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.07101682, + 0.9880643, + 1.0 + ], + [ + 0.3550513, + 0.96534646, + 1.0 + ], + [ + 0.7367733, + 0.952579, + 1.0 + ], + [ + 0.41733772, + 0.96733385, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.021202909, + 0.99511874, + 1.0 + ], + [ + 0.03845068, + 0.98727, + 1.0 + ], + [ + 0.13032648, + 0.9788461, + 1.0 + ], + [ + 0.08247721, + 0.9886881, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.019193187, + 0.99454707, + 1.0 + ], + [ + -0.01639945, + 0.9824369, + 1.0 + ], + [ + -0.034814365, + 0.97299594, + 1.0 + ], + [ + 0.000092838956, + 0.9879655, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.0020077226, + 0.98501676, + 1.0 + ], + [ + -0.01932977, + 0.98477453, + 1.0 + ], + [ + -0.08714962, + 0.9838237, + 1.0 + ], + [ + -0.05911569, + 0.99138635, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.028955147, + 0.9820292, + 1.0 + ], + [ + -0.0068421336, + 0.9893989, + 1.0 + ], + [ + -0.066570766, + 0.99078333, + 1.0 + ], + [ + -0.044429842, + 0.995392, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.032754235, + 0.99281675, + 1.0 + ], + [ + -0.024249062, + 0.9940026, + 1.0 + ], + [ + -0.016773215, + 0.99763656, + 1.0 + ], + [ + -0.00368944, + 0.99956965, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.013820456, + 0.9963605, + 1.0 + ], + [ + -0.023061087, + 0.99682546, + 1.0 + ], + [ + -0.006765129, + 0.99912953, + 1.0 + ], + [ + -0.00025614, + 0.99994946, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.03831513, + 0.9965622, + 1.0 + ], + [ + -0.026358912, + 0.9984241, + 1.0 + ], + [ + -0.0031044614, + 0.99983025, + 1.0 + ], + [ + -0.00004853841, + 0.99999666, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.042360652, + 0.99709636, + 1.0 + ], + [ + -0.02741898, + 0.99857044, + 1.0 + ], + [ + -0.0024811549, + 0.99984425, + 1.0 + ], + [ + -0.0000068021504, + 0.99999624, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.015694104, + 0.99947315, + 1.0 + ], + [ + -0.004300875, + 0.9996656, + 1.0 + ], + [ + -0.00022572257, + 0.99996036, + 1.0 + ], + [ + -2.7103656e-8, + 0.9999994, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.031804975, + 0.9993172, + 1.0 + ], + [ + -0.0036146475, + 0.9998796, + 1.0 + ], + [ + -0.00006266851, + 0.9999905, + 1.0 + ], + [ + -2.0947002e-7, + 0.99999994, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.03432048, + 0.99876255, + 1.0 + ], + [ + -0.0027313528, + 0.999917, + 1.0 + ], + [ + -0.00002901146, + 0.99999934, + 1.0 + ], + [ + -5.272942e-8, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.010446178, + 0.9998674, + 1.0 + ], + [ + -0.0009102314, + 0.9999884, + 1.0 + ], + [ + -0.000010674661, + 0.9999999, + 1.0 + ], + [ + -6.7580764e-8, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.0119908275, + 0.9999285, + 1.0 + ], + [ + -0.00078701315, + 0.9999947, + 1.0 + ], + [ + -0.0000061383644, + 0.99999994, + 1.0 + ], + [ + -3.791176e-8, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.005170042, + 0.99979734, + 1.0 + ], + [ + -0.0004141604, + 0.9999835, + 1.0 + ], + [ + -0.0000034080406, + 0.9999999, + 1.0 + ], + [ + -4.582497e-8, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.00895596, + 0.9998542, + 1.0 + ], + [ + -0.000709496, + 0.99998856, + 1.0 + ], + [ + -0.0000056245453, + 0.99999994, + 1.0 + ], + [ + -5.8625062e-8, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.0146880755, + 0.9997208, + 1.0 + ], + [ + -0.0018232282, + 0.9998647, + 1.0 + ], + [ + -0.00015326608, + 0.9999809, + 1.0 + ], + [ + -0.0000014805827, + 0.9999998, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.022968672, + 0.99913424, + 1.0 + ], + [ + -0.014809832, + 0.99827707, + 1.0 + ], + [ + -0.0020878739, + 0.9997331, + 1.0 + ], + [ + -0.000020184694, + 0.99999744, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.011431702, + 0.99970055, + 1.0 + ], + [ + -0.0039257053, + 0.999323, + 1.0 + ], + [ + -0.00048654518, + 0.9998965, + 1.0 + ], + [ + -0.000004697737, + 0.999999, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.0041034487, + 0.99944717, + 1.0 + ], + [ + -0.00006548014, + 0.99873835, + 1.0 + ], + [ + 0.000027589553, + 0.9997964, + 1.0 + ], + [ + 2.7555294e-7, + 0.999998, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.009381899, + 0.9987364, + 1.0 + ], + [ + -0.00043260615, + 0.9972713, + 1.0 + ], + [ + 0.000017650782, + 0.9995557, + 1.0 + ], + [ + 2.0419672e-7, + 0.99999547, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.008616836, + 0.99971557, + 1.0 + ], + [ + -0.00045231776, + 0.9998694, + 1.0 + ], + [ + -9.984535e-7, + 0.9999807, + 1.0 + ], + [ + 7.740104e-9, + 0.9999998, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.0056563327, + 0.9998474, + 1.0 + ], + [ + -0.00033137825, + 0.99999225, + 1.0 + ], + [ + -0.0000016325387, + 1.0, + 1.0 + ], + [ + -1.0257498e-9, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.014827684, + 0.99960244, + 1.0 + ], + [ + -0.0007938461, + 0.99998146, + 1.0 + ], + [ + -0.00000293517, + 0.99999994, + 1.0 + ], + [ + -8.377253e-10, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.011590649, + 0.9997409, + 1.0 + ], + [ + -0.00065725995, + 0.9999863, + 1.0 + ], + [ + -0.0000025172164, + 0.99999994, + 1.0 + ], + [ + -7.089178e-10, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.11034412, + 0.99728817, + 1.0 + ], + [ + -0.006188652, + 0.9998468, + 1.0 + ], + [ + -0.000022063721, + 0.99999946, + 1.0 + ], + [ + -5.30563e-9, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.11615519, + 0.9962155, + 1.0 + ], + [ + -0.006629864, + 0.9997772, + 1.0 + ], + [ + -0.000026530815, + 0.99999917, + 1.0 + ], + [ + -9.810042e-9, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.2699671, + 0.992111, + 1.0 + ], + [ + -0.01619867, + 0.99955577, + 1.0 + ], + [ + -0.0000889456, + 0.99999845, + 1.0 + ], + [ + -7.3219084e-8, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.84938484, + 0.9749287, + 1.0 + ], + [ + -0.0546363, + 0.99835104, + 1.0 + ], + [ + -0.00042785166, + 0.99998784, + 1.0 + ], + [ + -6.3949227e-7, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -2.9408712, + 0.91166395, + 1.0 + ], + [ + -0.28487697, + 0.99084896, + 1.0 + ], + [ + -0.0041404446, + 0.99987274, + 1.0 + ], + [ + -0.00000840042, + 0.99999976, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -6.1285825, + 0.7972419, + 1.0 + ], + [ + -0.82483685, + 0.96542543, + 1.0 + ], + [ + -0.007825383, + 0.99962455, + 1.0 + ], + [ + -0.0000082233155, + 0.9999996, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.914042, + 0.6662763, + 1.0 + ], + [ + -3.2296083, + 0.84786505, + 1.0 + ], + [ + -0.09797766, + 0.9948829, + 1.0 + ], + [ + -0.000322063, + 0.999986, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.49761, + 0.5991851, + 1.0 + ], + [ + -8.209785, + 0.6332046, + 1.0 + ], + [ + -2.2356362, + 0.88977855, + 1.0 + ], + [ + -0.03691413, + 0.9986572, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -8.16435, + 0.6105177, + 1.0 + ], + [ + -8.482127, + 0.6289409, + 1.0 + ], + [ + -8.195307, + 0.6653821, + 1.0 + ], + [ + -1.5681657, + 0.93180954, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.227832, + 0.6095772, + 1.0 + ], + [ + -9.688233, + 0.62955517, + 1.0 + ], + [ + -9.770227, + 0.6534116, + 1.0 + ], + [ + -7.684848, + 0.7312607, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -9.040249, + 0.61375934, + 1.0 + ], + [ + -9.414042, + 0.64601433, + 1.0 + ], + [ + -9.124609, + 0.6859369, + 1.0 + ], + [ + -6.8619404, + 0.76940507, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -4.1956196, + 0.65328926, + 1.0 + ], + [ + -6.4505258, + 0.6780245, + 1.0 + ], + [ + -6.7652173, + 0.777878, + 1.0 + ], + [ + -5.9136004, + 0.9036394, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.8208507, + 0.76508826, + 1.0 + ], + [ + -1.3313887, + 0.8808544, + 1.0 + ], + [ + -9.083516, + 0.86273944, + 1.0 + ], + [ + -10.492065, + 0.8505087, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.051133215, + 0.93782914, + 1.0 + ], + [ + -0.07260832, + 0.9849166, + 1.0 + ], + [ + -0.9264943, + 0.9826398, + 1.0 + ], + [ + -1.1677287, + 0.97983795, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.07751575, + 0.97048557, + 1.0 + ], + [ + -0.043188777, + 0.9823848, + 1.0 + ], + [ + -0.002534433, + 0.99882054, + 1.0 + ], + [ + -0.00013920956, + 0.9999524, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.07916742, + 0.97018796, + 1.0 + ], + [ + -0.031966496, + 0.97699416, + 1.0 + ], + [ + -0.0035643438, + 0.99836385, + 1.0 + ], + [ + -0.00040987533, + 0.99998116, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.01877379, + 0.9972593, + 1.0 + ], + [ + 0.01205297, + 0.9989108, + 1.0 + ], + [ + -0.0013474375, + 0.99986976, + 1.0 + ], + [ + -0.0007788474, + 0.9999769, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.00081947824, + 0.99965537, + 1.0 + ], + [ + 0.00408295, + 0.9999879, + 1.0 + ], + [ + -0.0004688936, + 0.9999954, + 1.0 + ], + [ + -0.00016395445, + 0.9999985, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.0022904403, + 0.9998439, + 1.0 + ], + [ + -0.0030316855, + 0.9999691, + 1.0 + ], + [ + -0.008458131, + 0.9999591, + 1.0 + ], + [ + -0.0015517423, + 0.99999255, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.008486173, + 0.9998458, + 1.0 + ], + [ + 0.00014019103, + 0.99998724, + 1.0 + ], + [ + -0.0017433885, + 0.99999154, + 1.0 + ], + [ + -0.00032057063, + 0.99999845, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.005678298, + 0.9997919, + 1.0 + ], + [ + -0.0006329326, + 0.99999183, + 1.0 + ], + [ + -0.000014824767, + 1.0, + 1.0 + ], + [ + -0.0000014804741, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.024680974, + 0.9990245, + 1.0 + ], + [ + 0.0004288364, + 0.9999345, + 1.0 + ], + [ + -0.000051545532, + 0.99999934, + 1.0 + ], + [ + -0.000005476217, + 0.99999994, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.0061284457, + 0.9994695, + 1.0 + ], + [ + -0.0008772137, + 0.9999514, + 1.0 + ], + [ + -0.0005471564, + 0.9999964, + 1.0 + ], + [ + -0.00011416538, + 0.99999934, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.019823374, + 0.99714184, + 1.0 + ], + [ + 0.0006233722, + 0.99973315, + 1.0 + ], + [ + -0.00020987287, + 0.99999684, + 1.0 + ], + [ + -0.000045174842, + 0.99999976, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.0055233804, + 0.99932915, + 1.0 + ], + [ + 0.00019314369, + 0.999932, + 1.0 + ], + [ + -0.000004102488, + 0.9999994, + 1.0 + ], + [ + -3.2671397e-7, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.017069608, + 0.99980605, + 1.0 + ], + [ + 0.0011378126, + 0.9999736, + 1.0 + ], + [ + 0.0000045061006, + 0.9999994, + 1.0 + ], + [ + 4.9558377e-8, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.0025704305, + 0.9998648, + 1.0 + ], + [ + -0.00016181398, + 0.9999653, + 1.0 + ], + [ + -0.000009765289, + 0.9999992, + 1.0 + ], + [ + -2.9514266e-7, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.011738374, + 0.99957114, + 1.0 + ], + [ + 0.0013190353, + 0.99990016, + 1.0 + ], + [ + 9.2287684e-7, + 0.99999744, + 1.0 + ], + [ + -0.0000011511228, + 1.0, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + 0.04013104, + 0.99884504, + 1.0 + ], + [ + 0.00018569271, + 0.99945897, + 1.0 + ], + [ + -0.0010192711, + 0.9999544, + 1.0 + ], + [ + -0.000013688198, + 0.9999996, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.02411725, + 0.99782336, + 1.0 + ], + [ + -0.09172129, + 0.9966743, + 1.0 + ], + [ + -0.017824568, + 0.9994446, + 1.0 + ], + [ + -0.00024212734, + 0.9999933, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.0085046105, + 0.9991983, + 1.0 + ], + [ + -0.032236904, + 0.9988923, + 1.0 + ], + [ + -0.03258688, + 0.9995004, + 1.0 + ], + [ + -0.022160465, + 0.99972326, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.047657337, + 0.9974346, + 1.0 + ], + [ + -0.17287616, + 0.9967666, + 1.0 + ], + [ + -1.7228909, + 0.97827595, + 1.0 + ], + [ + -1.5301245, + 0.9807228, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.1092619, + 0.9939699, + 1.0 + ], + [ + -0.28823772, + 0.9942406, + 1.0 + ], + [ + -2.4151208, + 0.9694442, + 1.0 + ], + [ + -2.120977, + 0.973369, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.046760842, + 0.99341387, + 1.0 + ], + [ + -0.46058732, + 0.9879337, + 1.0 + ], + [ + -0.9992375, + 0.97709274, + 1.0 + ], + [ + -0.27791965, + 0.9942543, + 1.0 + ], + [ + 0.0, + 1.0, + 1.0 + ], + [ + -0.055317637, + 0.988727, + 1.0 + ], + [ + -0.7323104, + 0.971684, + 1.0 + ], + [ + -2.933847, + 0.90179116, + 1.0 + ], + [ + -1.3042065, + 0.95250934, + 1.0 + ] + ], + "srgb_value": true + } +} \ No newline at end of file diff --git a/contributors/people.toml b/contributors/people.toml index 4eb002cef1..95e58421a0 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -38,6 +38,9 @@ sync_github_name = true [people.Losminek] sync_github_name = true +[people.nicolasfalesy] +sync_github_name = true + [people.FooVoo] real_name = "Aleksandr Batyrev" sync_github_name = true @@ -58,9 +61,16 @@ sync_github_name = false real_name = "Ege Gursel" sync_github_name = true +[people.valenfys] +sync_github_name = true + [people.mahmatias] display_name = "Márcio Matias de Andrade" sync_github_name = true [people.ronibalthazar] sync_github_name = true + +[people.dotCooCoo] +real_name = "Robert Lee" +sync_github_name = true diff --git a/crates/catalog/src/dates.rs b/crates/catalog/src/dates.rs index 2b71049eee..2dfebbf906 100644 --- a/crates/catalog/src/dates.rs +++ b/crates/catalog/src/dates.rs @@ -43,19 +43,63 @@ pub fn weekday(iso: &str) -> Option<&'static str> { /// Shift an ISO time by `secs`, keeping anything after the seconds (fractions, zone) as it was. /// A date without a time gets one. `None` if it doesn't parse, or if the result leaves years /// 0000–9999 (an ISO date here has four year digits, so it couldn't be read back); `secs` may be -/// anything, it never overflows. +/// anything, it never overflows. Stricter than [`iso_seconds`], which reads what it can for sorting: +/// a time cut short, seconds that aren't digits or anything after the zone is `None` here, not +/// written back as a clean-looking time. pub fn shift_iso(iso: &str, secs: i64) -> Option { + let iso = iso.trim(); + let tail = iso.get(tail_start(iso)?..)?; let t = iso_seconds(iso)?.checked_add(secs)?; let (first, last) = (iso_seconds("0000-01-01T00:00:00")?, iso_seconds("9999-12-31T23:59:59")?); if !(first..=last).contains(&t) { return None; } - let iso = iso.trim(); - // the seconds are optional (`10:00+02:00`): without them the tail starts right after the minutes - let tail = iso.get(if iso.get(16..17) == Some(":") { 19 } else { 16 }..).unwrap_or(""); Some(format!("{}{tail}", civil(t))) } +/// Where the part of an ISO time that [`shift_iso`] keeps as it was (fraction, zone) starts, or +/// `None` unless `iso` is a date alone (`2026-01-01`) or a date and `HH:MM`, optional `:SS` with +/// an optional fraction (`.5`), and an optional zone (`Z`, `+02:00`, `-0500`, `+02`), and nothing after. +fn tail_start(iso: &str) -> Option { + let b = iso.as_bytes(); + let digits = |x: &[u8]| !x.is_empty() && x.iter().all(u8::is_ascii_digit); + let digits_at = |a: usize, z: usize| b.get(a..z).is_some_and(digits); + let at = |i: usize, c: u8| b.get(i) == Some(&c); + if !(digits_at(0, 4) && at(4, b'-') && digits_at(5, 7) && at(7, b'-') && digits_at(8, 10)) { + return None; + } + if b.len() == 10 { + return Some(10); + } + if !((at(10, b'T') || at(10, b' ')) && digits_at(11, 13) && at(13, b':') && digits_at(14, 16)) { + return None; + } + // the seconds are optional (`10:00+02:00`): without them the tail starts right after the minutes + let start = if !at(16, b':') { + 16 + } else if digits_at(17, 19) { + 19 + } else { + return None; + }; + let mut zone = b.get(start..)?; + // a fraction only after the seconds: `10:00.5` is half a minute, not half a second + if let ([b'.', rest @ ..], 19) = (zone, start) { + let n = rest.iter().take_while(|c| c.is_ascii_digit()).count(); + zone = rest.get(n..)?; + if n == 0 { + return None; + } + } + let ok = match zone { + [] | [b'Z'] => true, + [b'+' | b'-', h1, h2, b':', m1, m2] => digits(&[*h1, *h2, *m1, *m2]), + [b'+' | b'-', hm @ ..] => matches!(hm.len(), 2 | 4) && digits(hm), + _ => false, + }; + ok.then_some(start) +} + /// Normalize user input to `YYYY-MM-DDTHH:MM:SS` (accepts a space instead of `T`, missing /// seconds or time). `None` if it isn't a valid date. pub fn normalize_iso(s: &str) -> Option { @@ -260,6 +304,65 @@ mod tests { assert_eq!(iso_seconds("2026-01-01T10:00+02:00"), iso_seconds("2026-01-01T10:00")); } + #[test] + fn shift_refuses_a_time_it_cant_fully_read() { + for bad in [ + "2026-01-01T10:0", + "2026-01-01T10", + "2026-01-01T", + "2026-01-01T10:00:xx", + "2026-01-01T10:00:0", + "2026-01-01T10:00:00+", + "2026-01-01T10:00:00+2", + "2026-01-01T10:00:00+02:0", + "2026-01-01T10:00:00.", + "2026-01-01T10:00:00.5.5", + "2026-01-01T10:00.5", + "2026-01-01T10:00:00ZZ", + "2026-01-01T10:00:00 and more", + "2026-01-01T10:00 and more", + "2026-01-01x10:00:00", + "2026/01/01T10:00:00", + ] { + assert_eq!(shift_iso(bad, 3600), None, "{bad} doesn't fully read, so it must not be written back"); + } + // multi-byte characters where the time, the seconds and the zone start never panic + for at in [11, 16, 18, 21] { + let mut s = String::from("2026-01-01T10:00:00+02:00"); + s.replace_range(at..at + 1, "é"); + assert_eq!(shift_iso(&s, 3600), None, "{s}"); + assert_eq!(shift_iso(s.get(..at + 2).unwrap(), 3600), None, "{s}"); + } + } + + #[test] + fn shift_keeps_a_fraction_and_zone_and_reads_back() { + for (from, to) in [ + ("2026-01-01", "2026-01-01T01:00:00"), + (" 2026-01-01T10:00 ", "2026-01-01T11:00:00"), + ("2026-01-01 10:00:30", "2026-01-01T11:00:30"), + ("2026-01-01T10:00:30.5", "2026-01-01T11:00:30.5"), + ("2026-01-01T10:00:30Z", "2026-01-01T11:00:30Z"), + ("2026-01-01T10:00:30+02:00", "2026-01-01T11:00:30+02:00"), + ("2026-01-01T10:00:30-0500", "2026-01-01T11:00:30-0500"), + ("2026-01-01T10:00:30+02", "2026-01-01T11:00:30+02"), + ("2026-01-01T10:00:30.125+02:00", "2026-01-01T11:00:30.125+02:00"), + ] { + assert_eq!(shift_iso(from, 3600).as_deref(), Some(to), "{from}"); + assert_eq!(shift_iso(to, 0).as_deref(), Some(to), "{to} reads back"); + } + } + + /// Sorting, grouping and date rules read with `iso_seconds`, which stays lenient: only the + /// write path refuses what it can't fully read. + #[test] + fn reading_stays_lenient_for_sorting() { + let at_ten = iso_seconds("2026-01-01T10:00:00"); + assert_eq!(iso_seconds("2026-01-01T10:00:00 and more"), at_ten); + assert_eq!(iso_seconds("2026-01-01T10:00:xx"), at_ten); + assert_eq!(iso_seconds("2026-01-01T10:0"), iso_seconds("2026-01-01")); + } + #[test] fn impossible_times_are_rejected_not_rolled_over() { for bad in ["2026-04-01T10:75:00", "2026-04-01 10:00:75", "2026-04-01T10:60", "2026-04-01T24:00:00", "2026-04-01T10:59:60"] { diff --git a/crates/catalog/src/folders.rs b/crates/catalog/src/folders.rs index aab3b867bd..e2d3b312dd 100644 --- a/crates/catalog/src/folders.rs +++ b/crates/catalog/src/folders.rs @@ -207,14 +207,31 @@ impl Catalog { /// folder that is no longer there and are dropped (undo restores them). Empty when there is /// nothing to carry or drop. pub fn folder_records_follow(&self, from: &str, to: &str) -> Vec { + self.folder_records_carried(from, to, true) + } + + /// [`Catalog::folder_records_follow`] for a folder located where it already is on disk + /// (`folder.updateLocation`): nothing arrived at `to`, the library only learned that the + /// folder is there. So what it knows about folders at or below `to` (other folders of the + /// library there) stays; a record carried over replaces the one at the same place. + pub fn folder_records_located(&self, from: &str, to: &str) -> Vec { + self.folder_records_carried(from, to, false) + } + + fn folder_records_carried(&self, from: &str, to: &str, clear_destination: bool) -> Vec { let (Some(root), Some(dest)) = (record_key(from), record_key(to)) else { return Vec::new() }; if root == dest { return Vec::new(); } + // a folder located below itself: what is already at or below `to` belongs to the folders + // of the library there, not to the folder located, so it is neither carried nor cleared + // (the record of `from` itself still lands at `to`, replacing the one there) + let nested = !clear_destination && key_within(&dest, &root); + let carried = |k: &str| key_within(k, &root) && !(nested && key_within(k, &dest)); let moved: Vec<(String, FolderRecord)> = self .folder_records .iter() - .filter(|(k, _)| key_within(k, &root)) + .filter(|(k, _)| carried(k)) .filter_map(|(k, r)| { let rest = folder_rest(k, &root)?; let base = dest.trim_end_matches('/'); @@ -224,7 +241,7 @@ impl Catalog { .collect(); // what was known at the old place goes, and so does what is left at the new one (also // when the moved folder carries nothing: the folder now there is not the one it was about) - let stale = self.folder_records.keys().filter(|k| key_within(k, &root) || key_within(k, &dest)); + let stale = self.folder_records.keys().filter(|k| carried(k) || (clear_destination && key_within(k, &dest))); let mut ops: Vec = stale.map(|k| Op::SetFolderRecord { folder: k.clone(), record: None }).collect(); ops.extend(moved.into_iter().map(|(k, r)| Op::SetFolderRecord { folder: k, record: Some(r) })); ops diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index edcfae22ae..2600d794a4 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -263,14 +263,36 @@ fn newer(what: String) -> CatalogError { CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older")) } +/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid +/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start +/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt +/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps +/// and reports, same state as before, minus the CPU. +const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB + /// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed /// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns /// the fragment's length and the record, if that record continues the log (`seq <= last + 1`). /// The record's CRC must match, so damage is never mistaken for it. fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> { const START: &[u8] = b"{\"seq\":"; + // One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and + // one validation covers every candidate; only a line that is not wholly valid re-checks, and + // then up to the budget rather than the suffix length times the candidate count. + let whole = std::str::from_utf8(line).ok(); + let mut spent = 0usize; (1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| { - let rec = std::str::from_utf8(&line[i..]).ok().map(|l| l.trim_end_matches('\r')).and_then(decode_record)?; + let text = match &whole { + Some(t) => &t[i..], + None => { + if spent >= RESYNC_BUDGET_BYTES { + return None; + } + spent = spent.saturating_add(line.len() - i); + std::str::from_utf8(&line[i..]).ok()? + } + }; + let rec = decode_record(text.trim_end_matches('\r'))?; (rec.0 <= last.saturating_add(1)).then_some((i, rec)) }) } @@ -714,3 +736,28 @@ impl Drop for Journal { } } } + +#[cfg(test)] +mod tests_resync { + use super::*; + + /// A torn first line may end at any byte and a failed append's retried records may follow its + /// own start `{"seq":` more than once: `resync` finds the CRC-valid record after a fragment of + /// many record starts. UTF-8 is validated once for a valid line, and for a line that isn't + /// wholly valid only up to the budget instead of the suffix length per candidate (CWE-407). + #[test] + fn resync_finds_the_retried_record_after_a_fragment_of_many_starts() { + let op = Op::Batch { ops: vec![] }; + let record = encode_record(5, &op); + let mut line = Vec::from(b"\xf2" as &[u8]); // an invalid byte, so the whole line is not UTF-8 + for i in 0..1024 { + line.extend_from_slice(format!("{{\"seq\":{},\"crc\":{{", i).as_bytes()); + } + let fragment = line.len(); + line.extend_from_slice(record.as_bytes()); + assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5))); + // a retry is still recognised past `last`: the fragment logs nothing valid, but the CRC + // matches, so the double `Some` is only reached with `last >= 4` + assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5))); + } +} diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index 0d8b666a13..6b0c97f5a3 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -48,7 +48,11 @@ pub fn reparent(k: &str, from: &str, to: &str) -> String { /// name, its parents' and synonyms flat besides its path). Each once, cleaned. pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec { let mut out: Vec = hierarchical.iter().map(|k| clean(k)).collect(); - out.extend(flat.iter().map(|k| clean(k)).filter(|k| !hierarchical.iter().any(|h| h.split(SEP).any(|level| same(level.trim(), k))))); + // One lowered set of every hierarchical level, not a search of `hierarchical` for each flat + // keyword: disjoint lists from sidecars made the old approach quadratic in both (CWE-407), and + // `same` allocates two lower-cased strings per comparison. + let levels: std::collections::HashSet = hierarchical.iter().flat_map(|h| h.split(SEP).map(|l| l.trim().to_lowercase())).collect(); + out.extend(flat.iter().map(|k| clean(k)).filter(|k| !levels.contains(&k.to_lowercase()))); dedupe(&mut out); out } @@ -78,6 +82,9 @@ pub fn parse_keyword_list(text: &str) -> Result> { let mut out: Vec<(String, KeywordInfo)> = Vec::new(); // where each keyword is in `out`, by lower-case path (a search of `out` per line was quadratic) let mut index: std::collections::HashMap = std::collections::HashMap::new(); + // synonyms already accepted, by keyword (a search of each keyword's growing synonym list per + // line was quadratic and re-allocated both spellings every comparison — CWE-407) + let mut synonyms: std::collections::HashMap> = std::collections::HashMap::new(); // the keyword at each level above the line: its path and where it is in `out` let mut above: Vec<(String, usize)> = Vec::new(); for (i, line) in text.split('\n').enumerate() { @@ -103,9 +110,9 @@ pub fn parse_keyword_list(text: &str) -> Result> { if synonym.contains(SEP) { return Err(bad(n, "“|” separates a keyword's levels: a synonym can't hold one")); } - if let Some((_, info)) = out.get_mut(at) - && !synonym.is_empty() - && !info.synonyms.iter().any(|s| same(s, synonym)) + if !synonym.is_empty() + && synonyms.entry(at).or_default().insert(synonym.to_lowercase()) + && let Some((_, info)) = out.get_mut(at) { info.synonyms.push(synonym.to_string()); } @@ -264,7 +271,14 @@ impl Catalog { let mut chain: Vec = Vec::new(); let mut path = String::new(); let mut lower = String::new(); - for part in k.split(SEP).map(str::trim).filter(|s| !s.is_empty()) { + // Level paths hold their every prefix (`path` and `lower` both), so a photo's XMP + // keyword split far more levels than a list file accepts (`MAX_LEVELS`) made the + // stored prefixes quadratic in the level count: a keyword nests [MAX_LEVELS] + // levels here, as a list file would, and what lies below is left out (CWE-400). + for (part_n, part) in (1..).zip(k.split(SEP).map(str::trim).filter(|s| !s.is_empty())) { + if part_n > MAX_LEVELS { + break; + } if !path.is_empty() { path.push(SEP); lower.push(SEP); @@ -505,7 +519,24 @@ impl Catalog { } } let mut file = KeywordListFile::default(); + // The tree is capped at [`MAX_LEVELS`] (its level rows hold every level's prefix twice, so a + // synthetic keyword past that depth made the stored bytes quadratic); whatever lies deeper + // comes from the photos' and list's own spellings instead, named unwritable as before. + let mut over_deep: std::collections::HashSet = Default::default(); + for k in self.listed_keywords().map(|k| &k.path) { + if k.split(SEP).count() > MAX_LEVELS { + over_deep.insert(k.clone()); + } + } + for p in self.photos().filter(|p| p.in_library()) { + for k in &p.meta.keywords { + if clean(k).split(SEP).count() > MAX_LEVELS { + over_deep.insert(k.clone()); + } + } + } write(self, &self.keyword_tree(), 0, &mut file); + file.unwritable.extend(over_deep); file } @@ -1470,4 +1501,35 @@ mod tests { let s = c.keyword_suggestions(&[], "E", 5); assert_eq!(s, ["eagle", "beach", "parade"], "prefix matches before substring matches"); } + + /// A flat keyword already covered by a hierarchical level only in another spelling is not kept + /// again, whatever the size of either list (the per-flat-keyword search of every level, twice + /// lower-cased per comparison, was quadratic: CWE-407). + #[test] + fn from_file_matches_levels_in_any_case() { + let flat = ["Rome".to_string(), "Seaside".to_string()]; + let hierarchical = ["travel|ITALY|rome".to_string()]; + assert_eq!(from_file(&flat, &hierarchical), ["travel|ITALY|rome", "Seaside"]); + } + + /// The same synonym, in any spelling, is kept once (the search of each keyword's growing + /// synonym list per line was quadratic, with lower-cased copies made per comparison).(CWE-407) + #[test] + fn parse_keyword_list_keeps_a_synonym_once() { + let read = parse_keyword_list("Travel\n\t{Trip}\n\t{journey}\n\t{TRIP}\n").unwrap(); + assert_eq!(read.len(), 1); + assert_eq!(read[0].1.synonyms, ["Trip", "journey"]); + } + + /// A keyword split into far more levels than a list file accepts is cut at [`MAX_LEVELS`] in the + /// tree, whose level rows hold every prefix twice: unbounded it made the stored bytes quadratic + /// in the level count of one short keyword (CWE-400). + #[test] + fn keyword_tree_caps_a_keyword_at_the_list_depth() { + let deep: Vec = (0..4096).map(|i| format!("k{i}")).collect(); + let joined = deep.join("|"); + let (c, _) = lib(&[&[joined.as_str()]]); + let deepest = tree_paths(&c.keyword_tree()).iter().map(|(p, _)| p.split(SEP).count()).max().unwrap_or(0); + assert_eq!(deepest, MAX_LEVELS); + } } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 1776c895c1..453b68a697 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -36,7 +36,7 @@ pub use folders::{FolderNode, FolderRecord}; pub use journal::{Journal, LoadReport, PersistStats, SnapshotPolicy, SnapshotTiming}; pub use keywords::KeywordNode; use lightcraft_develop::DevelopSettings; -pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, folder_of}; +pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of}; pub use lock::{LibraryLock, LockError, LockOwner}; pub use model::*; pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey, mix64}; @@ -284,7 +284,8 @@ pub struct Catalog { /// What the library keeps about its folders (folder identity → record), see [`folders`]. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] folder_records: BTreeMap, - /// Increments on every applied op. + /// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog + /// changed, so what is keyed by the revision is out of date). #[serde(skip)] pub revision: u64, /// Which photos the latest ops touched ([`Catalog::touched_since`]). @@ -348,6 +349,8 @@ struct Changes { /// outside (a library just loaded takes a range of its own, so that nothing kept from another library is /// taken for this one's): nothing is known of how the catalog got to where it is. seen: u64, + /// A batch that failed could not be rolled back whole: what it changed stays, so what it noted must too. + torn: bool, } impl PartialEq for Changes { @@ -610,13 +613,40 @@ impl Catalog { self.albums.get_mut(&id).ok_or(CatalogError::NoAlbum(id)) } - /// Apply an op; returns its inverse. On error nothing changes. + /// Apply an op; returns its inverse. On error the catalog is as it was, the revision included, and nothing is + /// remembered of the op in what the latest ops touched. The one exception is a batch whose rollback fails: the + /// catalog did change, so the revision advances and anything may be taken to have changed. pub fn apply(&mut self, op: Op) -> Result { if self.changes.seen != self.revision { // the revision was set from outside: what is remembered is of another past self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() }; } - let inv = self.apply_inner(op)?; + let broad = self.changes.broad; + self.changes.torn = false; + let inv = match self.apply_inner(op) { + Ok(inv) => inv, + Err(e) => { + let made = self.revision.saturating_add(1); + if self.changes.torn { + // (a batch the rollback of which failed changed something and says not what: it makes a + // revision, so what is kept for the one before is dropped, and anything may have changed, as + // after an op of a wider reach) + self.changes.torn = false; + self.changes.broad = made; + self.revision = made; + self.changes.seen = made; + } else { + // (everything the failed op, or the rollback of a batch, noted was made for the revision it + // would have made: nothing earlier has that one. A note the cap already dropped stays + // dropped, which only says less than is known, as the cap does.) + while self.changes.touched.back().is_some_and(|(r, _, _)| *r == made) { + self.changes.touched.pop_back(); + } + self.changes.broad = broad; + } + return Err(e); + } + }; self.revision += 1; self.changes.seen = self.revision; Ok(inv) @@ -962,7 +992,9 @@ impl Catalog { Err(e) => { // roll back what was applied for inv in inverses.into_iter().rev() { - let _ = self.apply_inner(inv); + if self.apply_inner(inv).is_err() { + self.changes.torn = true; + } } return Err(e); } @@ -1066,26 +1098,41 @@ impl Catalog { } st.photos.len() >= 2 }); - let parents: Vec<(AlbumId, Option)> = self.albums.values().map(|a| (a.id, a.parent)).collect(); - for (id, parent) in parents { - let Some(p) = parent else { continue }; - let mut cur = Some(p); - let mut steps = 0usize; - let ok = loop { - match cur { - None => break true, - Some(c) if c == id || steps > self.albums.len() => break false, - Some(c) => match self.albums.get(&c) { - Some(a) if a.folder => cur = a.parent, - _ => break false, - }, + let albums: Vec = self.albums.keys().copied().collect(); + // Validate each parent link once (CWE-407), caching only chains that now reach a root. + // A cached bad verdict is not enough: skipping its ancestors would leave their broken + // links/cycle intact when a lower-id child was the first to walk into that chain. + let mut valid: std::collections::HashSet = std::collections::HashSet::new(); + for id in albums { + let mut walked: Vec = Vec::new(); + let broken = { + let mut cur = id; + let mut on: std::collections::HashSet = std::collections::HashSet::new(); + loop { + if valid.contains(&cur) { + break None; + } + if !on.insert(cur) { + // Detach one actual cycle node, not the child that first reached it. + break self.albums.get(&cur).and_then(|a| a.parent).map(|parent| (cur, parent)); + } + walked.push(cur); + let Some(parent) = self.albums.get(&cur).and_then(|a| a.parent) else { break None }; + if !self.albums.get(&parent).is_some_and(|a| a.folder) { + break Some((cur, parent)); + } + cur = parent; } - steps += 1; }; - if !ok && let Some(a) = self.albums.get_mut(&id) { + if let Some((id, p)) = broken + && let Some(a) = self.albums.get_mut(&id) + { changed.push(format!("album {}: its folder {} is missing, not a folder or inside it: moved to the top level", id.0, p.0)); a.parent = None; } + // Only visited nodes are cached, after every one can reach the repaired root or a + // previously validated chain. Unvisited ancestors never inherit a guessed verdict. + valid.extend(walked); } let past = |last: Option| last.map_or(1, |v| v.saturating_add(1)); let (photo, album, stack) = ( @@ -1164,4 +1211,6 @@ mod tests_repair; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_tally; +#[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/local.rs b/crates/catalog/src/local.rs index 093c224271..20cb3d5b45 100644 --- a/crates/catalog/src/local.rs +++ b/crates/catalog/src/local.rs @@ -34,6 +34,15 @@ use serde::Serialize; use crate::{Catalog, Op, Photo, PhotoId, Source}; +/// The Local records of some files ([`Catalog::local_records_of`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LocalRecords { + /// Only a record of having looked: nothing was changed on them and nothing refers to them. + pub untouched: Vec, + /// Holding something of the person's, with their files. + pub kept: Vec<(PhotoId, String)>, +} + /// Default for how long a Local folder may go unbrowsed before its untouched records are /// forgotten (days). pub const DEFAULT_FORGET_DAYS: u32 = 30; @@ -64,7 +73,8 @@ pub fn folder_of(p: &Photo) -> Option { // `/` and `\` are both separators whatever the platform (a catalog can move between them) Source::File { path } => { let key = crate::query::folder_key(path); - key.rsplit_once('/').map(|(dir, _)| if dir.is_empty() { "/".to_string() } else { dir.to_string() }) + // a drive or share root keeps its trailing `/` in its key (`c:/`, `//srv/share/`) + key.rsplit_once('/').map(|(dir, _)| if dir.is_empty() { "/".to_string() } else { crate::query::folder_key(&format!("{dir}/")) }) } Source::Demo { .. } => None, } @@ -176,6 +186,34 @@ impl Catalog { &self.browsed } + /// The Local records of `files` (paths as stored), for library photos about to point at + /// those files (a folder located where it was browsed, `folder.updateLocation`): a file has one + /// record, so the Local one gives way. Told apart: those that are only a record of having + /// looked (untouched, see the module docs, and nothing refers to them), which can go, and + /// those that hold something of the person's (a rating, an edit, a place in an album), with + /// their files. Records in Recently Deleted are not Local records to this. + pub fn local_records_of(&self, files: &HashSet) -> LocalRecords { + let mut out = LocalRecords::default(); + if files.is_empty() { + return out; + } + let referenced = self.referenced(); + for p in self.photos.values().filter(|p| p.local && !p.deleted) { + let Source::File { path } = &p.source else { continue }; + if !files.contains(path) { + continue; + } + if p.untouched_local() && !referenced.contains(&p.id) { + out.untouched.push(p.id); + } else { + out.kept.push((p.id, path.clone())); + } + } + out.untouched.sort_unstable(); + out.kept.sort_unstable(); + out + } + /// Plan forgetting untouched Local records whose folder wasn't browsed for `days` days (as of /// `now`, ISO 8601). `in_use` keeps records the caller still needs. `days == 0` (never) or an /// unreadable `now` forgets nothing. See the module docs. diff --git a/crates/catalog/src/lock.rs b/crates/catalog/src/lock.rs index d699da0491..f701087a69 100644 --- a/crates/catalog/src/lock.rs +++ b/crates/catalog/src/lock.rs @@ -25,7 +25,7 @@ //! - Browser storage (OPFS) has no file locks: see the web host for its own guard. use std::fs::{File, OpenOptions, TryLockError}; -use std::io; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; /// The lock file in the library directory. @@ -116,9 +116,11 @@ impl LibraryLock { } Err(TryLockError::Error(e)) => return Ok(unlocked(e)), } + // A new file in place of whatever is at the name: a link planted there in a library folder + // someone else prepared is removed, never written through (as for the staging files, #1502). let owner = LockOwner::this_process(program); if let Ok(json) = serde_json::to_vec_pretty(&owner) - && let Err(e) = std::fs::write(dir.join(OWNER), json) + && let Err(e) = crate::store::create_staging(&dir.join(OWNER)).and_then(|mut f| f.write_all(&json)) { log::warn!("library {}: can't write {OWNER}: {e}", dir.display()); } diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index a94421369a..ff94268a8b 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -29,6 +29,10 @@ pub struct Filter { /// Only these photos (Find Similar results…); empty = no constraint. #[serde(skip_serializing_if = "Vec::is_empty")] pub only: Vec, + /// Show nothing: an explicit empty result (Find Similar with no matches), since an empty + /// `only` means "no constraint". + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub only_none: bool, /// Any of these labels (the filter bar's multi-select); empty = no constraint. #[serde(skip_serializing_if = "Vec::is_empty")] pub labels: Vec, @@ -236,6 +240,17 @@ fn has_person(p: &Photo, name: &str) -> bool { } impl Filter { + /// The labels that `label` and `labels` let through together (they AND), in `labels`' order; + /// `None` when neither is set, empty when they exclude each other. The chip and the filter + /// bar's buttons show this, so they match what is filtered. + pub fn labels_shown(&self) -> Option> { + match (self.label, self.labels.is_empty()) { + (None, true) => None, + (Some(l), true) => Some(vec![l]), + (l, false) => Some(self.labels.iter().copied().filter(|x| l.is_none_or(|l| l == *x)).collect()), + } + } + /// Human-readable summary of the active rules (smart album tooltips, `album.list`). pub fn describe(&self) -> String { self.describe_in(None) @@ -374,6 +389,9 @@ impl Filter { if !self.labels.is_empty() && !p.label.is_some_and(|l| self.labels.contains(&l)) { return false; } + if self.only_none { + return false; + } if !self.only.is_empty() && !prepared.only.as_ref().map_or_else(|| self.only.contains(&p.id), |only| only.contains(&p.id)) { return false; } diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 667509d6f5..2976a2659b 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -432,12 +432,79 @@ thread_local! { std::cell::RefCell::new(std::collections::HashMap::new()); } +thread_local! { + /// While [`AlbumPass`] is alive on this thread: the photos of each smart album that was counted whole, with + /// the longest chain of smart albums (itself included) its rules lead through. + static PASS: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +/// One pass over one catalog state that counts every smart album whole. Each album put in with `remember` +/// answers [`smart_album_holds`] from its photos, not from its rules, until the pass is dropped (it can't outlive +/// the state it was made of: it exists only inside the counting function). +/// +/// Only an album whose rules lead to no loop may be remembered, and only with the height of its chain: its answer +/// then doesn't depend on which albums are being evaluated around it, as long as the chain still fits under +/// [`MAX_ALBUM_DEPTH`] from where it is asked (checked on every use; otherwise the rules are evaluated as before). +pub(crate) struct AlbumPass { + outer: Option>, +} + +impl AlbumPass { + pub(crate) fn begin() -> AlbumPass { + AlbumPass { outer: PASS.with_borrow_mut(|p| p.replace(std::collections::HashMap::new())) } + } + + /// `id` holds exactly `members`, and its rules lead through a chain of `height` smart albums (itself included), + /// none of them in a loop. + pub(crate) fn remember(&self, id: crate::AlbumId, height: usize, members: crate::tally::Members) { + PASS.with_borrow_mut(|p| { + if let Some(p) = p { + p.insert(id, (height, members)); + } + }); + } + + /// Ends the pass, giving back what was remembered. + pub(crate) fn finish(self) -> std::collections::HashMap { + PASS.with_borrow_mut(Option::take).unwrap_or_default().into_iter().map(|(id, (_, members))| (id, members)).collect() + } +} + +impl Drop for AlbumPass { + fn drop(&mut self) { + let outer = self.outer.take(); + PASS.with_borrow_mut(|p| *p = outer); + } +} + +/// What a counting pass knows of smart album `id` for `photo`, when asking now can't give another answer than +/// evaluating its rules would: the chain below it fits under [`MAX_ALBUM_DEPTH`] from the albums being evaluated. +fn pass_answer(id: crate::AlbumId, photo: crate::PhotoId) -> Option { + PASS.with_borrow(|p| { + let (height, members) = p.as_ref()?.get(&id)?; + let depth = EVALUATING.with_borrow(Vec::len); + (depth + height <= MAX_ALBUM_DEPTH).then(|| members.holds(photo)) + }) +} + +#[cfg(test)] +thread_local! { + /// How many times a smart album's rules were worked out on this thread (tests count them). + pub(crate) static EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Whether `photo` is in smart album `id`, by `matches` (its rules), remembered for the rest of the /// outermost question and guarded by [`evaluating`] (a loop or a chain too deep holds nothing). pub(crate) fn smart_album_holds(id: crate::AlbumId, photo: crate::PhotoId, matches: impl FnOnce() -> bool) -> bool { + if let Some(known) = pass_answer(id, photo) { + return known; + } if let Some(known) = ANSWERS.with_borrow(|a| a.get(&(id, photo)).copied()) { return known; } + #[cfg(test)] + EVALUATED.with(|n| n.set(n.get() + 1)); // the outermost question forgets the answers when it ends, however it ends struct Forget(bool); impl Drop for Forget { @@ -456,7 +523,7 @@ pub(crate) fn smart_album_holds(id: crate::AlbumId, photo: crate::PhotoId, match } /// How deep smart albums may test smart albums before the innermost counts as holding nothing. -const MAX_ALBUM_DEPTH: usize = 32; +pub(crate) const MAX_ALBUM_DEPTH: usize = 32; /// Run `f` as the evaluation of smart album `id`'s rules: `None` (so it holds nothing) when `id` /// is already being evaluated (a loop the check would refuse, saved anyway) or the chain is @@ -670,6 +737,11 @@ fn number(v: &Value) -> Option { } } +/// Widens an `f32` to the `f64` nearest its shortest decimal form (1.4f32 -> 1.4), so it compares equal to the value a user types. +fn f32_as_decimal(v: f32) -> f64 { + v.to_string().parse().unwrap_or(v as f64) +} + fn num_op(op: &str, have: Option, value: &Value) -> bool { if op == "between" { let (a, b) = match value { @@ -953,8 +1025,8 @@ impl Rule { "editDate" => date_op(op, p.edited.as_deref(), value), "shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)), "iso" => num_op(op, m.iso.map(|v| v as f64), value), - "aperture" => num_op(op, m.aperture.map(|v| v as f64), value), - "focalLength" => num_op(op, m.focal_mm.map(|v| v as f64), value), + "aperture" => num_op(op, m.aperture.map(f32_as_decimal), value), + "focalLength" => num_op(op, m.focal_mm.map(f32_as_decimal), value), "longEdge" | "shortEdge" => { let (w, h) = p.shown_size(); num_op(op, Some(if field == "longEdge" { w.max(h) } else { w.min(h) }.round()), value) @@ -1129,6 +1201,25 @@ mod tests { serde_json::from_value(v).unwrap() } + #[test] + fn f32_boundary_values_match_gte_lte() { + let cat = Catalog::new(); + let matches = + |p: &Photo, field: &str, op: &str, value: f64| rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat); + for v in [1.4f32, 1.8, 2.8, 5.6, 0.95] { + let mut p = photo(1); + p.meta.aperture = Some(v); + p.meta.focal_mm = Some(v); + let w = v.to_string().parse::().unwrap(); + for field in ["aperture", "focalLength"] { + assert!(matches(&p, field, "gte", w), "{field} gte {w}"); + assert!(matches(&p, field, "lte", w), "{field} lte {w}"); + assert!(!matches(&p, field, "gt", w), "{field} gt {w}"); + assert!(!matches(&p, field, "lt", w), "{field} lt {w}"); + } + } + } + #[test] fn fields_ops_and_groups() { let cat = Catalog::new(); diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index 553eb241f1..a79930f14a 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -45,6 +45,18 @@ pub trait Store: Send { } } +/// Appends and truncates open the name's own file, so anything else at the name is the library's +/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device +/// hangs the open. Refused with an error the open can show, before anything is written through. +fn check_regular_directory_entry(path: &Path) -> io::Result<()> { + match std::fs::symlink_metadata(path) { + Ok(md) if md.is_file() => Ok(()), + Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), + } +} + /// Files in a directory. pub struct FsStore { dir: PathBuf, @@ -75,8 +87,8 @@ impl FsStore { /// A new staging file at `tmp`: whatever is already there (a leftover from a crashed save, or a link) is removed first /// (a link itself, never what it points to), then the file is created exclusively, so a write never follows a link -/// planted at that name into another file (issue #1502). -fn create_staging(tmp: &std::path::Path) -> io::Result { +/// planted at that name into another file (issue #1502). Also writes the lock's owner note. +pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result { if std::fs::symlink_metadata(tmp).is_ok() { std::fs::remove_file(tmp)?; } @@ -137,6 +149,7 @@ impl Store for FsStore { fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> { use std::io::Write; if self.appender.as_ref().is_none_or(|(n, _)| n != name) { + check_regular_directory_entry(&self.path(name))?; let existed = self.path(name).exists(); let f = std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?; if !existed { @@ -159,6 +172,7 @@ impl Store for FsStore { if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } + check_regular_directory_entry(&self.path(name))?; let f = match std::fs::OpenOptions::new().write(true).open(self.path(name)) { Ok(f) => f, // nothing to cut (an append that failed before creating the file) @@ -266,4 +280,28 @@ mod tests_staging { assert_eq!(std::fs::read(dir.join("catalog.log")).unwrap(), b"[1]"); let _ = std::fs::remove_dir_all(&dir); } + + /// The journal's append and truncate (which recovery uses) refuse a non-regular file at the + /// name instead of following it, so a link planted at `catalog.log` never receives library + /// bytes (CWE-59, Audit row 107); the snapshot write already removes such a link (#1502). + #[test] + fn append_and_truncate_refuse_a_link_at_the_name() { + let dir = std::env::temp_dir().join(format!("lc-log-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let victim = dir.join("victim.txt"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(&victim, b"keep").unwrap(); + std::os::unix::fs::symlink(&victim, dir.join("catalog.log")).unwrap(); + let mut store = FsStore::open(&dir).unwrap(); + assert!(store.append("catalog.log", b"appended").is_err()); + assert!(store.truncate("catalog.log", 0).is_err()); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep"); + assert!(std::fs::symlink_metadata(dir.join("catalog.log")).unwrap().file_type().is_symlink()); + // A regular file keeps working. + std::fs::remove_file(dir.join("catalog.log")).unwrap(); + std::fs::write(dir.join("catalog.log"), b"abc").unwrap(); + store.truncate("catalog.log", 1).unwrap(); + assert_eq!(std::fs::read(dir.join("catalog.log")).unwrap(), b"a"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/catalog/src/tally.rs b/crates/catalog/src/tally.rs index 8f15e5ec46..e8fdc61979 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -8,7 +8,9 @@ use std::collections::{HashMap, HashSet}; -use crate::{AlbumId, Aspects, Catalog, PhotoId}; +use crate::query::Filter; +use crate::rules::{AlbumPass, MAX_ALBUM_DEPTH}; +use crate::{Album, AlbumId, Aspects, Catalog, PhotoId}; /// The most photos an edit may touch for the counts to follow it photo by photo. const MAX_FOLLOWED: usize = 256; @@ -20,7 +22,7 @@ const WORDS_TO_START: usize = 1024; /// The photos a smart album holds. #[derive(Clone, Debug)] -enum Members { +pub(crate) enum Members { /// One bit a photo id, and how many are set. Bits { words: Vec, @@ -41,8 +43,7 @@ impl Members { } } - #[cfg(test)] - fn holds(&self, id: PhotoId) -> bool { + pub(crate) fn holds(&self, id: PhotoId) -> bool { match self { Members::Bits { words, .. } => { usize::try_from(id.0 / 64).ok().and_then(|at| words.get(at)).is_some_and(|word| word & (1u64 << (id.0 % 64)) != 0) @@ -114,21 +115,46 @@ pub struct AlbumTally { impl AlbumTally { /// Counted from every photo. + /// + /// A smart album that tests another (`album is #14`) reads that album's photos, counted once for the whole + /// pass, instead of working its rules out again for every photo: albums are counted shortest chain first. + /// The photos are kept only until this function returns, so they can't be older than the catalog counted. + /// An album whose rules lead into a loop, or through a chain too deep to be sure of, is counted by its rules + /// as before: the pass ends before the first of them (they sort last), so nothing they evaluate reads it. pub fn of(cat: &Catalog) -> AlbumTally { + let heights = chain_heights(cat); + let height_of = |id: AlbumId| heights.get(&id).copied().flatten().filter(|h| *h <= MAX_ALBUM_DEPTH); + let mut smart: Vec = cat.albums().filter(|a| a.is_smart()).map(|a| a.id).collect(); + smart.sort_by_key(|id| height_of(*id).unwrap_or(usize::MAX)); + let held_by = |id: AlbumId| { + let mut held = Members::none(); + for p in cat.photos().filter(|p| cat.album_contains(id, p)) { + held.set(p.id, true); + } + held + }; + let mut counts = HashMap::new(); let mut members = HashMap::new(); - for album in cat.albums() { - if album.is_smart() { - let mut held = Members::none(); - for p in cat.photos().filter(|p| cat.album_contains(album.id, p)) { - held.set(p.id, true); - } - counts.insert(album.id, held.len()); - members.insert(album.id, held); - } else { - counts.insert(album.id, cat.album_count(album.id)); + let split = smart.partition_point(|id| height_of(*id).is_some()); + let (with_height, without) = smart.split_at(split); + let pass = AlbumPass::begin(); + for id in with_height { + let held = held_by(*id); + counts.insert(*id, held.len()); + if let Some(height) = height_of(*id) { + pass.remember(*id, height, held); } } + members.extend(pass.finish()); + for id in without { + let held = held_by(*id); + counts.insert(*id, held.len()); + members.insert(*id, held); + } + for album in cat.albums().filter(|a| !a.is_smart()) { + counts.insert(album.id, cat.album_count(album.id)); + } AlbumTally { revision: cat.revision, counts, members } } @@ -184,6 +210,57 @@ impl AlbumTally { } } +/// For each smart album, the most smart albums in a chain its rules lead through (itself included), or `None` +/// when a loop is reachable from it (its answer may then depend on which albums are being evaluated around it). +fn chain_heights(cat: &Catalog) -> HashMap> { + struct Frame { + id: AlbumId, + tests: Vec, + next: usize, + tallest: usize, + loops: bool, + } + let tests = |id: AlbumId| -> Vec { + let tested = cat.album(id).and_then(|a| a.smart.as_deref()).map(Filter::albums_tested).unwrap_or_default(); + tested.into_iter().filter(|t| cat.album(*t).is_some_and(Album::is_smart)).collect() + }; + let frame = |id: AlbumId| Frame { id, tests: tests(id), next: 0, tallest: 0, loops: false }; + let mut done: HashMap> = HashMap::new(); + let mut open: HashSet = HashSet::new(); + for root in cat.albums().filter(|a| a.is_smart()).map(|a| a.id) { + if done.contains_key(&root) { + continue; + } + open.insert(root); + let mut stack = vec![frame(root)]; + while let Some(top) = stack.last_mut() { + if let Some(&kid) = top.tests.get(top.next) { + top.next += 1; + match done.get(&kid) { + Some(Some(h)) => top.tallest = top.tallest.max(*h), + Some(None) => top.loops = true, + None if open.contains(&kid) => top.loops = true, + None => { + open.insert(kid); + stack.push(frame(kid)); + } + } + } else if let Some(finished) = stack.pop() { + open.remove(&finished.id); + let height = (!finished.loops).then_some(finished.tallest + 1); + done.insert(finished.id, height); + if let Some(parent) = stack.last_mut() { + match height { + Some(h) => parent.tallest = parent.tallest.max(h), + None => parent.loops = true, + } + } + } + } + } + done +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index f8b72dad84..579175086e 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -952,12 +952,13 @@ fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them() c.apply(Op::SetRating { id: a, rating: 1 }).unwrap(); assert_eq!(c.touched_since(loaded), Some(vec![a])); assert_eq!(c.touched_since(old), None); - // an op that fails changes nothing, and what is remembered never says less than what happened + // an op that fails changes nothing and is not remembered let before = c.revision; assert!(c.apply(Op::SetRating { id: PhotoId(9_999), rating: 1 }).is_err()); assert_eq!(c.revision, before); + assert_eq!(c.touched_since(before), Some(vec![])); c.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap(); - assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a))); + assert_eq!(c.touched_since(before), Some(vec![a])); assert!(c.aspects_since(before).is_some_and(|x| x.any_of(Aspects::FLAG))); // a batch that fails midway is undone as a whole; a batch in a batch is remembered photo by photo; a batch // with an op that changes more than photos is not @@ -965,8 +966,8 @@ fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them() assert!(c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 5 }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }).is_err()); assert_eq!((c.revision, c.photo(a).map(|p| p.rating)), (before, Some(1))); c.apply(Op::Batch { ops: vec![Op::Batch { ops: vec![Op::SetRating { id: a, rating: 2 }] }] }).unwrap(); - // (the photo the failed batch asked for and never found may be named too: more is said, never less) - assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a))); + // (the failed batch is not remembered: only the batch that worked) + assert_eq!(c.touched_since(before), Some(vec![a])); let before = c.revision; c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 3 }, Op::RenameAlbum { id: album, name: "Journey".into() }] }).unwrap(); assert_eq!(c.touched_since(before), None); @@ -978,3 +979,70 @@ fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them() assert_eq!(c.touched_since(long_ago), None); assert_eq!(c.touched_since(c.revision - 10), Some(vec![a])); } + +/// An op that fails leaves nothing behind in what the catalog remembers of its ops: no photo it never changed (one +/// that does not even exist), and, for a batch rolled back, none of what its first ops had touched. +#[test] +fn an_op_that_fails_leaves_no_touched_photos_behind() { + let mut c = Catalog::default(); + let add = |c: &mut Catalog, name: &str| { + let id = c.alloc_photo_id(); + c.apply(Op::AddPhoto { + photo: Box::new(Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00")), + }) + .unwrap(); + id + }; + let (a, b) = (add(&mut c, "a.jpg"), add(&mut c, "b.jpg")); + let missing = PhotoId(9_999); + let start = c.revision; + // every op that names a photo, on one that does not exist + for op in [Op::SetRating { id: missing, rating: 1 }, Op::SetFlag { id: missing, flag: Flag::Pick }, Op::RemovePhoto { id: missing }] { + assert!(c.apply(op).is_err()); + assert_eq!(c.revision, start, "a failed op makes no revision"); + assert_eq!(c.touched_since(start), Some(vec![])); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + } + // an op that changes more than photos and fails does not make earlier revisions unknown + assert!(c.apply(Op::RenameAlbum { id: AlbumId(77), name: "x".into() }).is_err()); + assert_eq!(c.touched_since(start), Some(vec![])); + // a batch that fails on its second op names nothing of its first, nor of the rollback + assert!(c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 5 }, Op::SetRating { id: missing, rating: 1 }] }).is_err()); + assert_eq!(c.revision, start); + assert_eq!(c.touched_since(start), Some(vec![])); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + assert_eq!(c.photo(a).map(|p| p.rating), Some(0)); + // a batch that ends in a failed removal of a photo that exists + assert!(c.apply(Op::Batch { ops: vec![Op::RemovePhoto { id: b }, Op::RemovePhoto { id: b }] }).is_err()); + assert!(c.photo(b).is_some()); + assert_eq!(c.touched_since(start), Some(vec![])); + // what succeeded after the failures is remembered, and only that + c.apply(Op::SetRating { id: a, rating: 2 }).unwrap(); + assert_eq!(c.touched_since(start), Some(vec![a])); + assert_eq!(c.aspects_since(start), Some(Aspects::RATING)); +} + +/// A batch the rollback of which fails halfway leaves the catalog changed (here a stack is lost), so what the +/// catalog remembers must not say that nothing changed: anything may have. +#[test] +fn a_batch_that_cannot_be_rolled_back_whole_makes_earlier_changes_unknown() { + let mut c = Catalog::default(); + let mut ids = Vec::new(); + for name in ["a.jpg", "b.jpg"] { + let id = c.alloc_photo_id(); + let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + ids.push(id); + } + let stack = c.alloc_stack_id(); + c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + let start = c.revision; + // the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later + let failing = + Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; + assert!(c.apply(failing).is_err()); + assert_eq!(c.revision, start + 1, "the catalog changed, so what is kept for the revision before is out of date"); + assert!(c.photo(ids[0]).is_some() && c.stack(stack).is_none(), "the rollback went only part of the way"); + assert_eq!(c.touched_since(start), None, "so nothing is said of what changed"); + assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again"); +} diff --git a/crates/catalog/src/tests_folder_records.rs b/crates/catalog/src/tests_folder_records.rs index 3ae19c33a1..a572db9958 100644 --- a/crates/catalog/src/tests_folder_records.rs +++ b/crates/catalog/src/tests_folder_records.rs @@ -161,6 +161,63 @@ fn an_unlabelled_folder_moved_onto_a_stale_label_does_not_inherit_it() { assert_eq!(c.folder_color_label("/pics/holiday"), Some(ColorLabel::Purple)); } +#[test] +fn a_located_folder_keeps_what_the_library_knows_of_the_folders_already_at_the_destination() { + let mut c = library(); + label(&mut c, "/pics/trip", Some(ColorLabel::Red)); + label(&mut c, "/pics/trip/day1", Some(ColorLabel::Green)); + // other folders of the library at the place it is said to be at: nothing arrived there + label(&mut c, "/pics/home", Some(ColorLabel::Blue)); + label(&mut c, "/pics/home/old", Some(ColorLabel::Yellow)); + let before = c.to_snapshot(); + let ops = c.folder_records_located("/pics/trip", "/pics/home"); + let undo = c.apply(Op::Batch { ops }).unwrap(); + assert_eq!(c.folder_record("/pics/trip"), None, "what was known at the old place goes"); + assert_eq!(c.folder_record("/pics/trip/day1"), None); + assert_eq!(c.folder_color_label("/pics/home"), Some(ColorLabel::Red), "a record carried over replaces the one at the same place"); + assert_eq!(c.folder_color_label("/pics/home/old"), Some(ColorLabel::Yellow), "a folder of the library there keeps its own"); + c.apply(undo).unwrap(); + assert_eq!(c.to_snapshot(), before); +} + +#[test] +fn a_located_folder_with_labels_inside_lands_them_at_the_same_places_below() { + let mut c = library(); + label(&mut c, "/pics/trip", Some(ColorLabel::Red)); + label(&mut c, "/pics/trip/day1", Some(ColorLabel::Green)); + let ops = c.folder_records_located("/pics/trip", "/mnt/nas/trip"); + c.apply(Op::Batch { ops }).unwrap(); + assert_eq!(c.folder_color_label("/mnt/nas/trip"), Some(ColorLabel::Red)); + assert_eq!(c.folder_color_label("/mnt/nas/trip/day1"), Some(ColorLabel::Green)); +} + +#[test] +fn a_folder_located_below_itself_leaves_the_records_of_the_folders_already_there_in_place() { + let mut c = library(); + label(&mut c, "/pics/trip", Some(ColorLabel::Red)); + label(&mut c, "/pics/trip/day1", Some(ColorLabel::Green)); + // another folder of the library already sits at the place the folder is said to be at + label(&mut c, "/pics/trip/day1/raw", Some(ColorLabel::Blue)); + let before = c.to_snapshot(); + let ops = c.folder_records_located("/pics/trip", "/pics/trip/day1"); + let undo = c.apply(Op::Batch { ops }).unwrap(); + assert_eq!(c.folder_record("/pics/trip"), None, "what was known at the old place goes"); + assert_eq!(c.folder_color_label("/pics/trip/day1"), Some(ColorLabel::Red), "a record carried over replaces the one at the same place"); + assert_eq!(c.folder_color_label("/pics/trip/day1/raw"), Some(ColorLabel::Blue), "a folder below the destination keeps its own"); + assert_eq!(c.folder_record("/pics/trip/day1/day1"), None, "the record at the destination is not carried below itself"); + assert_eq!(c.folder_record("/pics/trip/day1/day1/raw"), None); + c.apply(undo).unwrap(); + assert_eq!(c.to_snapshot(), before); +} + +#[test] +fn a_folder_located_where_it_is_or_without_labels_gives_no_ops() { + let mut c = library(); + assert!(c.folder_records_located("/pics/trip", "/elsewhere/trip").is_empty()); + label(&mut c, "/pics/trip", Some(ColorLabel::Red)); + assert!(c.folder_records_located("/pics/trip", "/pics/trip").is_empty()); +} + #[test] fn labels_survive_the_journal_without_a_snapshot() { let m = MemStore::new(); diff --git a/crates/catalog/src/tests_local.rs b/crates/catalog/src/tests_local.rs index 4b76dace69..0082763d01 100644 --- a/crates/catalog/src/tests_local.rs +++ b/crates/catalog/src/tests_local.rs @@ -1,5 +1,6 @@ //! Forgetting untouched Local browse records (see [`crate::local`]). +use std::collections::HashSet; use std::sync::Arc; use lightcraft_develop::DevelopSettings; @@ -265,3 +266,51 @@ fn op_photo_ids_cover_nested_ops() { op.photo_ids(&mut |id| ids.push(id.0)); assert_eq!(ids, vec![1, 2, 3, 4]); } + +#[test] +fn drive_and_share_root_records_are_forgotten() { + for (path, folder) in [("C:\\IMG_1.JPG", "C:\\"), ("//srv/share/x.jpg", "//srv/share/")] { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, OLD); + p.local = true; + p.set_local_baseline(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + c.apply(Op::SetBrowsed { folder: folder.into(), at: Some(OLD.into()) }).unwrap(); + assert_eq!(plan(&c, 30).evict, vec![id], "{path}"); + } +} + +fn paths(folder: &str, ns: &[u32]) -> HashSet { + ns.iter().map(|i| format!("/pics/{folder}/IMG_{i}.JPG")).collect() +} + +#[test] +fn local_records_of_files_tell_what_can_give_way_from_what_holds_something() { + let mut c = Catalog::new(); + let untouched = local(&mut c, "trip", 1); + let rated = local(&mut c, "trip", 2); + let in_album = local(&mut c, "trip", 3); + let _elsewhere = local(&mut c, "trip", 4); + c.apply(Op::SetRating { id: rated, rating: 3 }).unwrap(); + let a = c.alloc_album_id(); + let mut album = Album::new(a, "A"); + album.photos.push(in_album); + c.apply(Op::AddAlbum { album }).unwrap(); + + let found = c.local_records_of(&paths("trip", &[1, 2, 3])); + assert_eq!(found.untouched, vec![untouched]); + assert_eq!(found.kept, vec![(rated, "/pics/trip/IMG_2.JPG".to_string()), (in_album, "/pics/trip/IMG_3.JPG".to_string())]); +} + +#[test] +fn local_records_of_files_leave_out_library_photos_and_recently_deleted_ones() { + let mut c = Catalog::new(); + let gone = local(&mut c, "trip", 1); + c.apply(Op::SetDeleted { id: gone, deleted: true }).unwrap(); + let id = c.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: "/pics/trip/IMG_2.JPG".into() }, "IMG_2.JPG", "JPEG", 60, 40, OLD); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + assert_eq!(c.local_records_of(&paths("trip", &[1, 2])), LocalRecords::default()); + assert_eq!(c.local_records_of(&HashSet::new()), LocalRecords::default()); +} diff --git a/crates/catalog/src/tests_lock.rs b/crates/catalog/src/tests_lock.rs index baa8da6596..2472ba92ac 100644 --- a/crates/catalog/src/tests_lock.rs +++ b/crates/catalog/src/tests_lock.rs @@ -62,6 +62,28 @@ fn leftover_lock_files_are_not_a_lock() { let _ = std::fs::remove_dir_all(&dir); } +/// A link planted at the owner note's name (`catalog.lock.owner`) in a library folder someone else +/// prepared is removed, never written through: the file it points to keeps its bytes, and the note +/// still lands in the library (as for the catalog's staging files, issue #1502). +#[cfg(unix)] +#[test] +fn a_link_at_the_owner_note_is_never_written_through() { + let _serial = serial(); + let dir = temp_dir("owner-link"); + let victim = dir.join("victim.txt"); + std::fs::write(&victim, b"keep").unwrap(); + std::os::unix::fs::symlink(&victim, dir.join(OWNER)).unwrap(); + let l = LibraryLock::acquire(&dir, "LightCraft").unwrap(); + assert!(l.held()); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep"); + assert!(!std::fs::symlink_metadata(dir.join(OWNER)).unwrap().file_type().is_symlink(), "the link was replaced by the note"); + let owner: LockOwner = serde_json::from_slice(&std::fs::read(dir.join(OWNER)).unwrap()).unwrap(); + assert_eq!(owner.pid, std::process::id()); + drop(l); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep"); + let _ = std::fs::remove_dir_all(&dir); +} + /// Another process holds the lock; when it is killed (a crash), the OS releases it. #[test] fn lock_held_by_another_process_is_released_when_it_dies() { diff --git a/crates/catalog/src/tests_repair.rs b/crates/catalog/src/tests_repair.rs index 493c895446..9feb038a53 100644 --- a/crates/catalog/src/tests_repair.rs +++ b/crates/catalog/src/tests_repair.rs @@ -108,6 +108,74 @@ fn folder_loops_and_missing_parents_move_to_the_top() { let _ = c.apply(Op::MoveAlbum { id: AlbumId(11), parent: Some(AlbumId(10)) }); } +/// Check the postcondition needed by every consumer that follows parent folders. This inspects +/// the repaired catalog, not its cache or a second implementation of the repair algorithm. +fn assert_all_album_chains_reach_roots(c: &Catalog) { + for album in c.albums.values() { + let mut seen = std::collections::HashSet::new(); + let mut current = album; + while let Some(parent) = current.parent { + assert!(seen.insert(current.id), "album {} still reaches a cycle", album.id.0); + current = c.albums.get(&parent).expect("every retained parent exists"); + assert!(current.folder, "every retained parent is a folder"); + } + } +} + +#[test] +fn a_child_visited_before_a_folder_cycle_keeps_its_content_and_gets_a_rooted_chain() { + let (c, ids) = sound(); + let (mut c, report) = load_edited(&c, |v| { + // BTreeMap order visits10 first: cached Bad11/12 used to be skipped without repair. + v["albums"]["10"] = serde_json::to_value(album(10, Some(11), false, vec![ids[2]])).unwrap(); + v["albums"]["11"] = serde_json::to_value(album(11, Some(12), true, vec![])).unwrap(); + v["albums"]["12"] = serde_json::to_value(album(12, Some(11), true, vec![])).unwrap(); + }); + assert_all_album_chains_reach_roots(&c); + assert_eq!(c.album(AlbumId(10)).unwrap().parent, Some(AlbumId(11)), "the child remains in its actual folder"); + assert_eq!(c.album(AlbumId(10)).unwrap().photos, vec![ids[2]], "repair preserves the child's photos"); + assert_eq!(c.album(AlbumId(11)).unwrap().parent, None, "one cycle edge is repaired"); + assert_eq!(c.album(AlbumId(12)).unwrap().parent, Some(AlbumId(11)), "the other folder edge is retained"); + assert!(report.repaired.iter().any(|message| message.starts_with("album 11:")), "{:?}", report.repaired); + assert!(c.repair().is_empty(), "a second repair is idempotent"); +} + +#[test] +fn a_child_visited_before_a_folder_with_a_missing_parent_does_not_hide_the_bad_ancestor() { + let (c, ids) = sound(); + let (mut c, report) = load_edited(&c, |v| { + v["albums"]["10"] = serde_json::to_value(album(10, Some(11), false, vec![ids[2]])).unwrap(); + v["albums"]["11"] = serde_json::to_value(album(11, Some(999), true, vec![])).unwrap(); + }); + assert_all_album_chains_reach_roots(&c); + assert_eq!(c.album(AlbumId(10)).unwrap().parent, Some(AlbumId(11))); + assert_eq!(c.album(AlbumId(10)).unwrap().photos, vec![ids[2]]); + assert_eq!(c.album(AlbumId(11)).unwrap().parent, None, "repair the missing-parent edge itself"); + assert!(report.repaired.iter().any(|message| message.starts_with("album 11:")), "{:?}", report.repaired); + assert!(c.repair().is_empty()); +} + +#[test] +fn a_long_valid_folder_chain_is_retained_when_its_child_is_visited_first() { + let (c, ids) = sound(); + let (mut c, report) = load_edited(&c, |v| { + v["albums"]["10"] = serde_json::to_value(album(10, Some(100), false, vec![ids[2]])).unwrap(); + for id in 100..612 { + v["albums"][id.to_string()] = serde_json::to_value(album(id, Some(id + 1), true, vec![])).unwrap(); + } + v["albums"]["612"] = serde_json::to_value(album(612, None, true, vec![])).unwrap(); + }); + assert_all_album_chains_reach_roots(&c); + assert_eq!(c.album(AlbumId(10)).unwrap().parent, Some(AlbumId(100))); + assert_eq!(c.album(AlbumId(10)).unwrap().photos, vec![ids[2]]); + for id in 100..612 { + assert_eq!(c.album(AlbumId(id)).unwrap().parent, Some(AlbumId(id + 1)), "valid edge{id} remains"); + } + assert_eq!(c.album(AlbumId(612)).unwrap().parent, None); + assert!(!report.repaired.iter().any(|message| message.starts_with("album ")), "valid parents must not be repaired: {:?}", report.repaired); + assert!(c.repair().is_empty()); +} + /// Id counters left at the top (or behind the ids in use) by a damaged file: allocating no longer /// overflows (a panic in debug builds) and never hands out an id already in use. #[test] diff --git a/crates/catalog/src/tests_tally.rs b/crates/catalog/src/tests_tally.rs new file mode 100644 index 0000000000..4953a8bd1e --- /dev/null +++ b/crates/catalog/src/tests_tally.rs @@ -0,0 +1,172 @@ +//! A whole count of every album (`AlbumTally::of`) keeps each smart album's photos for the pass, so an album testing +//! another doesn't work its rules out again. The counts must be the ones each album gets counted alone. + +use serde_json::json; + +use super::*; +use crate::tally::AlbumTally; + +fn smart(id: u64, rules: serde_json::Value) -> Album { + let rule_set = Some(serde_json::from_value(rules).unwrap()); + Album { smart: Some(Box::new(Filter { rule_set, ..Default::default() })), ..Album::new(AlbumId(id), format!("Smart {id}")) } +} + +fn photos(n: u64) -> Vec { + (0..n) + .map(|i| { + // folders with capitals, accents and a Windows path, so the text rules see every spelling + let dir = ["Asian/Japanese", "Été/Ünï", "C:\\Users\\Me\\Pictures", "plain", "[SITES]/x"][(i % 5) as usize]; + let mut p = Photo::new( + PhotoId(i + 1), + Source::File { path: format!("/Volumes/share/photos/{dir}/name{}/IMG_{i:04}.jpg", i % 9) }, + &format!("IMG_{i:04}.jpg"), + "JPEG", + 6000, + 4000, + "2026-01-01T00:00:00", + ); + p.rating = (i % 6) as u8; + p.flag = [Flag::None, Flag::Pick, Flag::Reject][(i % 3) as usize]; + p.label = (i % 4 == 0).then_some(ColorLabel::Red); + p.meta.keywords = (0..i % 4).map(|k| format!("kw{k}")).collect(); + p.deleted = i % 37 == 0; + Op::AddPhoto { photo: Box::new(p) } + }) + .collect() +} + +fn is(album: u64) -> serde_json::Value { + json!({"field": "album", "op": "is", "value": album}) +} + +fn is_not(album: u64) -> serde_json::Value { + json!({"field": "album", "op": "isNot", "value": album}) +} + +fn path(op: &str, value: &str) -> serde_json::Value { + json!({"field": "filePath", "op": op, "value": value}) +} + +/// Every album's count in `c`, each album counted alone (no pass, rules worked out per photo). +fn counted_alone(c: &Catalog) -> Vec<(AlbumId, usize)> { + let mut v: Vec<_> = c.albums().map(|a| (a.id, c.album_count(a.id))).collect(); + v.sort_unstable(); + v +} + +fn counted_together(c: &Catalog) -> Vec<(AlbumId, usize)> { + let tally = AlbumTally::of(c); + let mut v: Vec<_> = tally.counts().iter().map(|(id, n)| (*id, *n)).collect(); + v.sort_unstable(); + v +} + +#[test] +fn a_whole_count_equals_each_album_counted_alone() { + let mut c = Catalog::new(); + let mut ops = photos(240); + let mut plain = Album::new(AlbumId(1), "Picks"); + plain.photos = (0..240).step_by(4).map(|i| PhotoId(i + 1)).collect(); + let folder = Album { folder: true, ..Album::new(AlbumId(2), "Trips") }; + let inside = Album { parent: Some(AlbumId(2)), photos: (0..240).step_by(3).map(|i| PhotoId(i + 1)).collect(), ..Album::new(AlbumId(3), "In") }; + ops.extend([plain, folder, inside].map(|album| Op::AddAlbum { album })); + // the inner albums: #2-like, #14-like, then albums chained on it, the other way round, in groups and in different orders + ops.push(Op::AddAlbum { + album: smart( + 10, + json!({"match": "any", "rules": [{"field": "flag", "op": "is", "value": "reject"}, {"field": "label", "op": "is", "value": "red"}]}), + ), + }); + ops.push(Op::AddAlbum { + album: smart(11, json!({"match": "all", "rules": [is_not(10), path("notContains", "Été"), path("notContains", "plain")]})), + }); + for k in 0..9u64 { + let tail = path("contains", &format!("NAME{k}")); + let rules = match k % 3 { + 0 => json!({"match": "all", "rules": [is(11), tail]}), + 1 => json!({"match": "all", "rules": [json!({"field": "keywordCount", "op": "lte", "value": 2}), is(11), tail]}), + _ => json!({"match": "all", "rules": [tail, is(11)]}), + }; + ops.push(Op::AddAlbum { album: smart(12 + k, rules) }); + } + ops.push(Op::AddAlbum { + album: smart( + 21, + json!({"match": "all", "rules": [{"group": {"match": "any", "rules": [is(11), is(1)]}}, {"field": "rating", "op": "gte", "value": 2}]}), + ), + }); + ops.push(Op::AddAlbum { album: smart(22, json!({"match": "all", "rules": [is_not(21), is(3)]})) }); + ops.push(Op::AddAlbum { album: smart(23, json!({"match": "any", "rules": [is(2), is(999), is(1)]})) }); + // a loop saved anyway (30 ↔ 31), albums that test it from outside (32, 33), and one that tests both worlds + ops.push(Op::AddAlbum { album: smart(30, json!({"rules": []})) }); + ops.push(Op::AddAlbum { album: smart(31, json!({"rules": [is_not(30)]})) }); + ops.push(Op::AddAlbum { album: smart(32, json!({"rules": [is(31), {"field": "rating", "op": "gte", "value": 1}]})) }); + ops.push(Op::AddAlbum { album: smart(33, json!({"rules": [is_not(32), is(11)]})) }); + ops.push(Op::AddAlbum { album: smart(34, json!({"rules": [is(34)]})) }); + // a chain deeper than the limit on how deep albums may test albums + ops.push(Op::AddAlbum { album: smart(100, json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})) }); + for k in 101..=140u64 { + ops.push(Op::AddAlbum { album: smart(k, json!({"rules": [is(k - 1)]})) }); + } + ops.push(Op::AddAlbum { album: smart(141, json!({"rules": [is(140), is_not(11)]})) }); + // an album past the depth limit that also tests a memoized album directly: where the shared album is read from the + // pass near the top, the chain below must still find it answered as it always did (200 ← 231 … 201, height 32) + ops.push(Op::AddAlbum { album: smart(200, json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})) }); + for k in 201..=230u64 { + ops.push(Op::AddAlbum { album: smart(k, json!({"rules": [is(k + 1)]})) }); + } + ops.push(Op::AddAlbum { album: smart(231, json!({"rules": [is(200)]})) }); + ops.push(Op::AddAlbum { album: smart(250, json!({"match": "all", "rules": [is(200), is(201)]})) }); + c.apply(Op::Batch { ops }).unwrap(); + c.apply(Op::SetAlbumRules { + id: AlbumId(30), + rules: Box::new(Filter { rule_set: Some(serde_json::from_value(json!({"rules": [is_not(31)]})).unwrap()), ..Default::default() }), + }) + .unwrap(); + + let alone = counted_alone(&c); + let count = |id: u64| alone.iter().find(|(a, _)| a.0 == id).map(|(_, n)| *n); + assert!(count(11) > Some(0) && count(131) > Some(0), "{alone:?}"); + assert_eq!(count(132), Some(0), "the chain is too deep from here: holds nothing, as it did"); + assert!(count(250) > Some(0), "200 is answered near the top, so the chain finds it answered"); + assert_eq!(counted_together(&c), alone); + // the pass leaves nothing behind: the same answers whichever album asks first, and again after an edit + c.apply(Op::SetAlbumRules { + id: AlbumId(10), + rules: Box::new(Filter { + rule_set: Some(serde_json::from_value(json!({"rules": [{"field": "rating", "op": "is", "value": 5}]})).unwrap()), + ..Default::default() + }), + }) + .unwrap(); + let after = counted_alone(&c); + assert_ne!(after, alone); + assert_eq!(counted_together(&c), after); +} + +/// The reason for the pass: with an album tested by many, its rules are worked out once per photo, not once per +/// photo for each album that tests it. +#[test] +fn an_album_tested_by_many_is_worked_out_once_a_photo() { + let mut c = Catalog::new(); + let mut ops: Vec = (0..60u64) + .map(|i| { + let mut p = Photo::new(PhotoId(i + 1), Source::Demo { scene: 0 }, "a.jpg", "JPEG", 10, 10, "2026-01-01T00:00:00"); + p.rating = (i % 6) as u8; + Op::AddPhoto { photo: Box::new(p) } + }) + .collect(); + ops.push(Op::AddAlbum { album: smart(1, json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})) }); + for k in 0..10u64 { + ops.push(Op::AddAlbum { album: smart(2 + k, json!({"rules": [is(1), {"field": "rating", "op": "lte", "value": k % 6}]})) }); + } + c.apply(Op::Batch { ops }).unwrap(); + let alone = counted_alone(&c); + crate::rules::EVALUATED.with(|n| n.set(0)); + let tally = AlbumTally::of(&c); + let worked = crate::rules::EVALUATED.with(std::cell::Cell::get); + assert_eq!(worked, 11 * 60, "each of the 11 smart albums asks each of the 60 photos once"); + let mut together: Vec<_> = tally.counts().iter().map(|(id, n)| (*id, *n)).collect(); + together.sort_unstable(); + assert_eq!(together, alone); +} diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 5902243fc0..c9d5cec7df 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -100,7 +100,7 @@ jpegxl-rs / imagequant (GPL / C), dav1d / libheif (C). ## Performance (Apple M-series, release, synthetic 24 MP JPEG q90 4:2:0) -Run `cargo test --release -p lightcraft-codecs --test bench -- --ignored --nocapture`. +Run `cargo test --release -p lightcraft-codecs --test it bench:: -- --ignored --nocapture`. | Operation | Time | |---|---| diff --git a/crates/codecs/src/jpeg.rs b/crates/codecs/src/jpeg.rs index b8de12bddc..d8b0241a13 100644 --- a/crates/codecs/src/jpeg.rs +++ b/crates/codecs/src/jpeg.rs @@ -17,6 +17,8 @@ pub(crate) struct Markers { pub sof: u8, /// Number of components in the first scan (< `components` for non-interleaved sequential files). pub first_scan_components: u8, + /// Number of APP1 segments: capped before the allocating decoders walk them again. + pub app1: u32, pub exif: Option>, /// Offset of the EXIF TIFF header within the file. pub exif_offset: usize, @@ -83,6 +85,7 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option { m.components = seg[5]; } 0xE1 => { + m.app1 = m.app1.saturating_add(1); if seg.starts_with(b"Exif\0\0") && m.exif.is_none() { m.exif = Some(seg[6..].to_vec()); m.exif_offset = start + 6; @@ -121,6 +124,8 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { decode_with_fallback(bytes, opts, None) } +const MAX_APP1: u32 = 128; + /// Stored dimensions and EXIF orientation from the markers, without decoding the scan data. The /// file is refused, as a decode would refuse it, when it has no frame header, an unsupported frame /// type or component count, or when its markers don't run to an end-of-image marker after the @@ -178,6 +183,11 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback: return Err(Error::Malformed(F, "no frame header".into())); } check_size(F, m.width as u64, m.height as u64, opts)?; + // The allocating decoders below parse the markers again, all of them: the count is capped so + // their quadratic/unbounded handling of APP1 metadata stays linear in file size. + if m.app1 > MAX_APP1 { + return Err(Error::Malformed(F, "too many APP1 markers".into())); + } let scale_to = opts.max_size.filter(|&(mw, mh)| mw > 0 && mh > 0 && (m.width >= mw.saturating_mul(2) || m.height >= mh.saturating_mul(2))); // zune-jpeg handles the common cases fastest; jpeg-decoder covers DCT scaling, CMYK/YCCK, // 12-bit, non-interleaved sequential scans (which zune-jpeg 0.5 mis-decodes with subsampling) @@ -185,9 +195,9 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback: let lossless = m.sof == 0xC3; let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components; let raw = if m.components == 4 || scale_to.is_some() || m.precision > 8 || non_interleaved || lossless { - decode_jpeg_decoder(bytes, &m, scale_to)? + decode_jpeg_decoder(bytes, &m, scale_to, opts)? } else { - decode_zune(bytes, &m)? + decode_zune(bytes, &m, opts)? }; // A raw container may carry the colour declaration of an otherwise untagged preview. // Apply it before linearization/resizing; existing JPEG metadata always wins. @@ -196,7 +206,7 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback: finish(F, raw, meta, (m.width, m.height), opts) } -fn decode_zune(bytes: &[u8], m: &Markers) -> Result { +fn decode_zune(bytes: &[u8], m: &Markers, budget: &DecodeOptions) -> Result { use zune_core::bytestream::ZCursor; use zune_core::colorspace::ColorSpace; use zune_core::options::DecoderOptions; @@ -207,6 +217,11 @@ fn decode_zune(bytes: &[u8], m: &Markers) -> Result { ColorSpace::RGB }); let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), opts); + // zune's `decode` allocates straight from the frame header it parses, with its own caps + // set in us: check that header against the same limits the other decoders honour first. + d.decode_headers().map_err(|e| Error::Malformed(F, e.to_string()))?; + let (zw, zh) = d.info().map(|i| (i.width as u64, i.height as u64)).ok_or_else(|| Error::Malformed(F, "no info".into()))?; + check_size(F, zw, zh, budget)?; let px = d.decode().map_err(|e| Error::Malformed(F, e.to_string()))?; let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?; let (w, h) = (info.width as usize, info.height as usize); @@ -217,10 +232,15 @@ fn decode_zune(bytes: &[u8], m: &Markers) -> Result { Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf: Buf::U8(px), bit_depth: 8 }) } -fn decode_jpeg_decoder(bytes: &[u8], m: &Markers, scale_to: Option<(u32, u32)>) -> Result { +fn decode_jpeg_decoder(bytes: &[u8], m: &Markers, scale_to: Option<(u32, u32)>, budget: &DecodeOptions) -> Result { use jpeg_decoder::PixelFormat; let mut d = jpeg_decoder::Decoder::new(bytes); d.read_info().map_err(|e| Error::Malformed(F, e.to_string()))?; + // Its frame header is what a decode allocates from (progressive coefficient buffers follow the + // unscaled MCU grid): check it against the same limits the other decoders honour, before any + // DCT scale is requested. + let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?; + check_size(F, info.width as u64, info.height as u64, budget)?; // `scale` is the DCT size, not a lossless resample: on a lossless frame it would cut the // output to the top-left of each plane. Those decode at full size; `finish` scales after. if let Some((mw, mh)) = scale_to.filter(|_| m.sof != 0xC3) { @@ -369,11 +389,18 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec MAX_APP1 { + return Err(Error::Malformed(F, "too many APP1 markers".into())); + } if !matches!(m.components, 1 | 3) || m.precision != 8 { return Err(Error::Malformed(F, "expected an 8-bit greyscale or RGB image".into())); } let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components; - let raw = if non_interleaved { decode_jpeg_decoder(bytes, &m, None)? } else { decode_zune(bytes, &m)? }; + let raw = if non_interleaved { + decode_jpeg_decoder(bytes, &m, None, &DecodeOptions::default())? + } else { + decode_zune(bytes, &m, &DecodeOptions::default())? + }; let ch = raw.model.channels(); match raw.buf { Buf::U8(v) if v.len() >= raw.width * raw.height * ch => Ok((raw.width, raw.height, ch, v)), @@ -513,7 +540,7 @@ mod tests { fn lossless_grayscale_samples_are_native_endian_and_left_justified() { let bytes = lossless_jpeg(1, 8, 12); let m = parse_markers(&bytes).unwrap(); - let raw = decode_jpeg_decoder(&bytes, &m, None).unwrap(); + let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap(); let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") }; assert_eq!(v, &vec![2048u16 << 4; 8], "0x0800 native-endian, left-justified"); assert_eq!((raw.model, raw.bit_depth), (Model::Gray, 16)); @@ -525,7 +552,7 @@ mod tests { fn lossless_high_precision_rgb_is_16_bit() { let bytes = lossless_jpeg(3, 2, 12); let m = parse_markers(&bytes).unwrap(); - let raw = decode_jpeg_decoder(&bytes, &m, None).unwrap(); + let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap(); let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") }; assert_eq!(v, &vec![2048u16 << 4; 6]); assert_eq!(raw.model, Model::Rgb); @@ -536,7 +563,7 @@ mod tests { fn lossless_high_precision_cmyk_is_16_bit() { let bytes = lossless_jpeg(4, 2, 12); let m = parse_markers(&bytes).unwrap(); - let raw = decode_jpeg_decoder(&bytes, &m, None).unwrap(); + let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap(); let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") }; assert_eq!(v, &vec![2048u16 << 4; 8]); assert_eq!((raw.model, raw.bit_depth), (Model::Cmyk, 16)); @@ -551,4 +578,77 @@ mod tests { assert_eq!((d.width, d.height), (8, 1)); assert_eq!(d.bit_depth, 8); } + + /// Rewrites an encoded file's frame-header dimensions: same tables and scan, a hostile + /// annotated size. + fn with_dims(bytes: &[u8], w: u16, h: u16) -> Vec { + let mut out = bytes.to_vec(); + let mut p = 2usize; + while p + 1 < out.len() { + if out[p] != 0xFF { + p += 1; + continue; + } + match out[p + 1] { + 0xC0..=0xCF if out[p + 1] != 0xC4 && out[p + 1] != 0xC8 && out[p + 1] != 0xCC => { + out[p + 5..p + 7].copy_from_slice(&h.to_be_bytes()); + out[p + 7..p + 9].copy_from_slice(&w.to_be_bytes()); + return out; + } + 0x01 | 0xD0..=0xD9 => p += 2, + 0xFF => p += 1, + _ => { + let Some(l) = out.get(p + 2..p + 4) else { return out }; + p += 2 + usize::from(u16::from_be_bytes([l[0], l[1]])); + } + } + } + out + } + + /// A file claiming 65535×65535 must be refused for size before zune-jpeg allocates from + /// its frame header (4 GB+ of samples from roughly five hundred bytes of tables). + #[test] + fn zune_refuses_its_own_frame_header_over_the_budget() { + use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let pixels = vec![128u8; 32 * 24]; + let jpeg = encode_jpeg(&EncodeImage::new(32, 24, 1, Samples::U8(&pixels)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap(); + let hostile = with_dims(&jpeg, 65535, 65535); + assert_ne!(hostile, jpeg); + match crate::decode(&hostile, DecodeOptions::default()) { + Err(Error::TooLarge(w, h)) => assert_eq!((w, h), (65535, 65535)), + other => panic!("unexpected: {other:?}"), + } + } + + /// The jpeg-decoder branch (a 4-component file) is checked the same way: its own + /// `read_info` result is what a full-size decode allocates from. + #[test] + fn jpeg_decoder_refuses_its_own_frame_header_over_the_budget() { + use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let pixels = vec![128u8; 32 * 24 * 4]; + let jpeg = encode_jpeg(&EncodeImage::new(32, 24, 4, Samples::U8(&pixels)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap(); + let hostile = with_dims(&jpeg, 65535, 65535); + match crate::decode(&hostile, DecodeOptions::default()) { + Err(Error::TooLarge(w, h)) => assert_eq!((w, h), (65535, 65535)), + other => panic!("unexpected: {other:?}"), + } + } + + /// Extended XMP is reassembled from every APP1 fragment: an unbounded count is quadratic + /// memory in a marker walk, so the count is capped. + #[test] + fn an_app1_flood_is_refused_before_the_decoders_rewalk_it() { + let mut b = vec![0xFF, 0xD8]; + // a 1-component SOF0: 8-bit, 2×2, component (1, 0x11, Q0) + b.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 8, 0, 2, 0, 2, 1, 0x01, 0x11, 0x00]); + for _ in 0..200 { + b.extend_from_slice(&[0xFF, 0xE1, 0x00, 0x02]); + } + b.extend_from_slice(&[0xFF, 0xD9]); + match crate::decode(&b, DecodeOptions::default()) { + Err(Error::Malformed(F, m)) => assert!(m.contains("APP1"), "{m}"), + other => panic!("unexpected: {other:?}"), + } + } } diff --git a/crates/codecs/src/other.rs b/crates/codecs/src/other.rs index d5659de90a..ebba2eaedf 100644 --- a/crates/codecs/src/other.rs +++ b/crates/codecs/src/other.rs @@ -5,6 +5,9 @@ use crate::{DecodeOptions, Decoded, Error, Format, Result}; use image::{DynamicImage, ImageDecoder}; pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Result { + if format == Format::Gif { + gated_first_frame(bytes, opts)?; + } let err = |e: image::ImageError| Error::Malformed(format, e.to_string()); let cursor = std::io::Cursor::new(bytes); let (img, icc) = match format { @@ -36,3 +39,83 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu let raw = Raw { width: w as usize, height: h as usize, model, alpha, premultiplied: false, buf: Buf::U8(buf), bit_depth: 8 }; finish(format, raw, Meta { icc, ..Default::default() }, (w, h), opts) } + +/// Bounds a GIF's first image descriptor: the decoder composites frames into the logical screen +/// (bounded by [`check_size`] on the canvas) but allocates its own frame buffers at the frame's +/// declared size, which a small file can inflate far past the canvas. The canvas check cannot +/// see that size, so it is read from the block headers here. +fn gated_first_frame(bytes: &[u8], opts: &DecodeOptions) -> Result<()> { + // The constants of the header grammar: signature, logical screen descriptor (with its global + // colour table), extension blocks (0x21, skipped by their sub-block chains) and image + // descriptors (0x2C). + const SCREEN: usize = 13; + if bytes.len() < SCREEN { + return Ok(()); // too broken for a frame; the decoder reports the damage itself + } + let gct_entries = 1usize << (u32::from(bytes[10] & 0x07) + 1); // at most 256 + let gct_bytes = if (bytes[10] & 0x80) != 0 { gct_entries * 3 } else { 0 }; + let mut p = SCREEN.saturating_add(gct_bytes); + while let Some(&kind) = bytes.get(p) { + match kind { + 0x2C => { + // Image descriptor: two LE coordinates then two LE edges, after the separator. + let end = p.checked_add(10).filter(|&e| e <= bytes.len()); + let Some(d) = end.and_then(|e| bytes.get(p + 1..e)) else { + break; // cut short mid-descriptor: the decoder reports that + }; + let (w, h) = (u16::from_le_bytes([d[4], d[5]]) as u64, u16::from_le_bytes([d[6], d[7]]) as u64); + return check_size(Format::Gif, w, h, opts); + } + 0x21 => { + // Extension: a label byte, then sub-blocks ended by a zero length. + p = p.saturating_add(2); + loop { + let Some(&len) = bytes.get(p) else { + return Ok(()); // ran past the data: decode reports the truncation + }; + p = p.saturating_add(1); + if len == 0 { + break; + } + p = p.saturating_add(len as usize); + } + } + _ => p = p.saturating_add(1), + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use crate::{DecodeOptions, Error}; + + fn gif(blocks: &[u8]) -> Vec { + let mut b = b"GIF89a".to_vec(); + // logical screen: 2×2, no global colour table, background 0, aspect 0 + b.extend_from_slice(&[2, 0, 2, 0, 0x00, 0, 0]); + b.extend_from_slice(blocks); + b + } + + /// `image`'s GIF decoder allocates its frame buffer at the image descriptor's declared + /// size, which the canvas bound ([`crate::decode`]'s `max_pixels` on the logical screen) + /// does not cover. A 20-byte file used to buy a 4 GB allocation before the gate. + #[test] + fn a_first_frame_over_the_bound_is_refused_without_allocating_it() { + let bytes = gif(&[0x2C, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0x00]); + match crate::decode(&bytes, DecodeOptions::default()) { + Err(Error::TooLarge(w, h)) => assert_eq!((w, h), (65535, 65535)), + other => panic!("unexpected: {other:?}"), + } + } + + /// A frame within the bound still reaches the decoder (which reports the truncated data); + /// the gate may only refuse on size. + #[test] + fn a_first_frame_within_the_bound_is_not_refused() { + let bytes = gif(&[0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0x00]); + let r = crate::decode(&bytes, DecodeOptions::default()); + assert!(matches!(r, Err(Error::Malformed(..)) | Err(Error::TooLarge(..))), "{r:?}"); + } +} diff --git a/crates/codecs/src/png_codec.rs b/crates/codecs/src/png_codec.rs index 098f1cfaab..6837d178ee 100644 --- a/crates/codecs/src/png_codec.rs +++ b/crates/codecs/src/png_codec.rs @@ -7,6 +7,10 @@ use lightcraft_color::{Mat3, RgbSpace, Xy}; const F: Format = Format::Png; +/// Expansion cap for a compressed text chunk's payload: real XMP documents are a few hundred +/// kilobytes, so anything past this is hostile input, not metadata. +const MAX_TEXT_CHUNK: usize = 4 << 20; + fn err(e: impl std::fmt::Display) -> Error { Error::Malformed(F, e.to_string()) } @@ -42,11 +46,18 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { }; let raw = Raw { width: out.width as usize, height: out.height as usize, model, alpha, premultiplied: false, buf: samples, bit_depth: depth }; + // png's `get_text()` inflates a compressed chunk with no bound of its own: a tiny + // iTXt can claim an XMP document of arbitrary size. Expand through the bounded path + // instead, and drop any XMP bigger than the cap. let xmp = info .utf8_text .iter() .find(|t| t.keyword == "XML:com.adobe.xmp") - .and_then(|t| t.get_text().ok()) + .and_then(|t| { + let mut t = t.clone(); + t.decompress_text_with_limit(MAX_TEXT_CHUNK).ok()?; + t.get_text().ok() + }) .or_else(|| info.uncompressed_latin1_text.iter().find(|t| t.keyword == "XML:com.adobe.xmp").map(|t| t.text.clone())); let exif = info.exif_metadata.as_ref().map(|e| { let e = e.to_vec(); @@ -168,3 +179,55 @@ fn rgb_to_xyz_d50_checked(space: &RgbSpace) -> Option { } Some(crate::space::rgb_to_xyz_d50(space)) } + +#[cfg(test)] +mod tests { + use crate::DecodeOptions; + + /// A compressed text chunk is expanded by `png` through our own cap: an XMP document + /// bigger than it is dropped, not inflated. Compressing an 8 MiB string is a few + /// kilobytes — the reverse of what the unbounded `get_text()` path allowed. + #[test] + fn compressed_xmp_over_the_cap_is_dropped() { + let out = png_with_compressed_xmp(&"x".repeat(8 << 20)); + let d = crate::decode(&out, DecodeOptions::default()).unwrap(); + assert!(d.xmp.is_none()); + assert_eq!((d.width, d.height), (1, 1)); + } + + /// XMP within the cap is still read, compressed or not. + #[test] + fn compressed_xmp_under_the_cap_is_read() { + let out = png_with_compressed_xmp(&"".repeat(100)); + let d = crate::decode(&out, DecodeOptions::default()).unwrap(); + assert!(d.xmp.as_deref().is_some_and(|x| x.contains("xmp/"))); + } + + /// A little-endian PNG with one compressed iTXt chunk carrying `payload` as XMP. + fn png_with_compressed_xmp(payload: &str) -> Vec<u8> { + use png::text_metadata::{EncodableTextChunk, ITXtChunk}; + let mut base = Vec::new(); + { + let mut enc = png::Encoder::new(&mut base, 1, 1); + enc.set_color(png::ColorType::Grayscale); + enc.set_depth(png::BitDepth::Eight); + let mut w = enc.write_header().unwrap(); + w.write_image_data(&[0x7F]).unwrap(); + w.finish().unwrap(); + } + // `ITXtChunk::encode` writes the complete chunk (length, type, payload, CRC), with + // the text compressed. + let mut chunk = Vec::new(); + let mut xmp = ITXtChunk::new("XML:com.adobe.xmp", payload); + xmp.compressed = true; + xmp.compress_text().unwrap(); + xmp.encode(&mut chunk).unwrap(); + // Text chunks after IDAT land in `info` once the stream is finished: insert ours + // before the trailing IEND (a zero-length chunk is exactly 12 bytes). + let split = base.len() - 12; + let mut out = base[..split].to_vec(); + out.extend_from_slice(&chunk); + out.extend_from_slice(&base[split..]); + out + } +} diff --git a/crates/codecs/tests/bench.rs b/crates/codecs/tests/it/bench.rs similarity index 97% rename from crates/codecs/tests/bench.rs rename to crates/codecs/tests/it/bench.rs index 4c6f03fa19..c66feeb77d 100644 --- a/crates/codecs/tests/bench.rs +++ b/crates/codecs/tests/it/bench.rs @@ -1,5 +1,5 @@ //! Benchmark-ish, ignored by default. Run with: -//! `cargo test --release -p lightcraft-codecs --test bench -- --ignored --nocapture` +//! `cargo test --release -p lightcraft-codecs --test it bench:: -- --ignored --nocapture` use lightcraft_codecs::*; use std::time::Instant; diff --git a/crates/codecs/tests/corpus.rs b/crates/codecs/tests/it/corpus.rs similarity index 100% rename from crates/codecs/tests/corpus.rs rename to crates/codecs/tests/it/corpus.rs diff --git a/crates/codecs/tests/float_tiff.rs b/crates/codecs/tests/it/float_tiff.rs similarity index 100% rename from crates/codecs/tests/float_tiff.rs rename to crates/codecs/tests/it/float_tiff.rs diff --git a/crates/codecs/tests/fuzz.rs b/crates/codecs/tests/it/fuzz.rs similarity index 100% rename from crates/codecs/tests/fuzz.rs rename to crates/codecs/tests/it/fuzz.rs diff --git a/crates/codecs/tests/header.rs b/crates/codecs/tests/it/header.rs similarity index 100% rename from crates/codecs/tests/header.rs rename to crates/codecs/tests/it/header.rs diff --git a/crates/codecs/tests/heif.rs b/crates/codecs/tests/it/heif.rs similarity index 99% rename from crates/codecs/tests/heif.rs rename to crates/codecs/tests/it/heif.rs index d14f51ac4f..3364aec4d3 100644 --- a/crates/codecs/tests/heif.rs +++ b/crates/codecs/tests/it/heif.rs @@ -1,7 +1,6 @@ //! HEIC/HEIF through the codec API (feature `heif`), on lossless synthetic files from //! `lightcraft_heif::testdata`: an iPhone-like grid with a Display P3 profile, rotation, EXIF, a //! thumbnail and an HDR gain map; `nclx`-only colour; 10-bit; and hostile input. -#![cfg(feature = "heif")] use lightcraft_codecs::*; use lightcraft_heif::testdata::{Prop, Spec, build}; diff --git a/crates/codecs/tests/jxl_streaming.rs b/crates/codecs/tests/it/jxl_streaming.rs similarity index 98% rename from crates/codecs/tests/jxl_streaming.rs rename to crates/codecs/tests/it/jxl_streaming.rs index 298034656c..a16a82e726 100644 --- a/crates/codecs/tests/jxl_streaming.rs +++ b/crates/codecs/tests/it/jxl_streaming.rs @@ -1,5 +1,3 @@ -#![cfg(all(feature = "jxl", not(target_arch = "wasm32")))] - use lightcraft_codecs::exif::minimal_exif; use lightcraft_codecs::*; use lightcraft_raster::Rgba8; diff --git a/crates/codecs/tests/it/main.rs b/crates/codecs/tests/it/main.rs new file mode 100644 index 0000000000..6075620253 --- /dev/null +++ b/crates/codecs/tests/it/main.rs @@ -0,0 +1,13 @@ +//! The integration tests, one module per file, linked into one test binary. +//! `tests/jxl_tail_heap.rs` stays a binary of its own: it installs dhat as the global allocator. + +mod bench; +mod corpus; +mod float_tiff; +mod fuzz; +mod header; +#[cfg(feature = "heif")] +mod heif; +#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))] +mod jxl_streaming; +mod roundtrip; diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/it/roundtrip.rs similarity index 100% rename from crates/codecs/tests/roundtrip.rs rename to crates/codecs/tests/it/roundtrip.rs diff --git a/crates/denoise-core/Cargo.toml b/crates/denoise-core/Cargo.toml index b65f90ae40..d0a0b10c10 100644 --- a/crates/denoise-core/Cargo.toml +++ b/crates/denoise-core/Cargo.toml @@ -24,3 +24,4 @@ web-time = { workspace = true } [dev-dependencies] proptest = { workspace = true } +dhat = { workspace = true } diff --git a/crates/denoise-core/src/product.rs b/crates/denoise-core/src/product.rs index 5a607c8f49..c33b1d4c2a 100644 --- a/crates/denoise-core/src/product.rs +++ b/crates/denoise-core/src/product.rs @@ -9,7 +9,7 @@ //! compressed length and CRC-32, then the strips' bytes. `key` says what the product was made from (the photo's //! content, the model, this code's version, the settings it depends on); a file with another key is stale. -use std::io::{Read, Write}; +use std::io::{Read, Seek, Write}; use std::path::Path; use lightcraft_raster::Rgb32f; @@ -216,6 +216,10 @@ fn read_start(r: &mut impl Read) -> Result<Start, ProductError> { r.read_exact(&mut e)?; let l = u32::from_le_bytes([e[0], e[1], e[2], e[3]]) as usize; let c = u32::from_le_bytes([e[4], e[5], e[6], e[7]]); + // a strip never compresses to nothing (it has at least one row, so at least one deflated pixel) + if l == 0 { + return Err(ProductError::Format("a strip is empty".into())); + } // a strip never compresses to much more than its raw size if l > 12 * h.strip * h.width + 4096 { return Err(ProductError::Format("a strip is larger than it can be".into())); @@ -305,7 +309,6 @@ pub fn read_window(path: &Path, key: &str, window: Option<Window>, factor: usize } // the picture rows and columns the blocks cover let (x_end, y_end) = if whole { (w.x + w.width, w.y + w.height) } else { (w.x + ow * factor, w.y + oh * factor) }; - let mut out = Rgb32f { width: ow, height: oh, data: allocate(ow * oh, [0.0; 3])? }; let lut = f16_table(); let value = |raw: &[u8], c: usize, n: usize, i: usize| -> f32 { let (lo, hi) = (raw.get(2 * c * n + i).copied().unwrap_or(0), raw.get((2 * c + 1) * n + i).copied().unwrap_or(0)); @@ -318,6 +321,21 @@ pub fn read_window(path: &Path, key: &str, window: Option<Window>, factor: usize let strips: Vec<usize> = (0..table.len()).filter(|&s| wanted(s)).collect(); // skip the strips before the first one wanted let skipped: usize = table.iter().take(strips.first().copied().unwrap_or(0)).map(|e| e.0).sum(); + // The output is reserved only after the wanted strips' compressed bytes are present and match their checksums: + // a malformed cache whose strips are empty, damaged or short are rejected here, before the (large) result is + // allocated, not after. Reading them twice is cheap next to decoding them, and the fold below re-seeks here. + let strips_at = f.stream_position()?; + f.seek_relative(i64::try_from(skipped).map_err(|_| ProductError::Format("the file is too large".into()))?)?; + for &s in &strips { + let Some(&(len, expected)) = table.get(s) else { return Err(ProductError::Format("a strip is missing".into())) }; + let mut packed = allocate(len, 0u8)?; + f.read_exact(&mut packed)?; + if crc(&packed) != expected { + return Err(ProductError::Format(format!("strip {s} is damaged"))); + } + } + let mut out = Rgb32f { width: ow, height: oh, data: allocate(ow * oh, [0.0; 3])? }; + f.seek(std::io::SeekFrom::Start(strips_at))?; f.seek_relative(i64::try_from(skipped).map_err(|_| ProductError::Format("the file is too large".into()))?)?; for group in strips.chunks(GROUP) { let mut packed = Vec::with_capacity(group.len()); @@ -422,6 +440,21 @@ mod tests { let _ = std::fs::remove_file(p); } + #[test] + fn an_empty_strip_entry_is_rejected_by_the_header() { + let p = temp("empty-strip"); + let header = serde_json::to_vec(&Header { width: 16, height: 1, strip: STRIP_ROWS, key: "k".into() }).unwrap(); + let mut bytes = Vec::from(MAGIC.as_slice()); + bytes.extend_from_slice(&[VERSION, 0, 0, 0]); + bytes.extend_from_slice(&(header.len() as u32).to_le_bytes()); + bytes.extend_from_slice(&header); + // one strip with a zero-length entry: it has a row, so its deflated bytes are never empty + bytes.extend_from_slice(&[0; 8]); + std::fs::write(&p, bytes).unwrap(); + assert!(matches!(read_header_at(&p), Err(ProductError::Format(why)) if why.contains("empty"))); + let _ = std::fs::remove_file(p); + } + fn temp(name: &str) -> std::path::PathBuf { std::env::temp_dir().join(format!("lc-denoise-{name}-{}.lcdn", std::process::id())) } diff --git a/crates/denoise-core/tests/product_heap.rs b/crates/denoise-core/tests/product_heap.rs new file mode 100644 index 0000000000..40c170861d --- /dev/null +++ b/crates/denoise-core/tests/product_heap.rs @@ -0,0 +1,50 @@ +//! Peak heap of a `read_window` that must reject a product's strips (`crates/denoise-core/src/product.rs`), measured +//! with dhat's testing mode. The result is allocated only after the wanted strips' checksums are verified, so a cache +//! whose compressed bytes are damaged or absent fails without first reserving the (multi-megabyte) output. One test +//! per binary (dhat's profiler is global). + +use lightcraft_denoise_core::product::read_window; + +#[global_allocator] +static ALLOC: dhat::Alloc = dhat::Alloc; + +fn temp(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("lc-denoise-{name}-{}.lcdn", std::process::id())) +} + +/// A 2000 × 1024 product of key `k` (a 24 MB result): its 8 strips each claim 8 bytes that do not match their +/// checksum, and the file is exactly the length its header and table declare. A 24 MB peak means the output was +/// reserved; the cap here bounds the header, the table and the strips' own bytes. +fn damaged_product() -> Vec<u8> { + let header = br#"{"width":2000,"height":1024,"strip":128,"key":"k"}"#; + const STRIP_LEN: usize = 8; + let mut bytes = Vec::from(b"LCDN".as_slice()); + bytes.extend_from_slice(&[1, 0, 0, 0]); + bytes.extend_from_slice(&(header.len() as u32).to_le_bytes()); + bytes.extend_from_slice(header); + let expected_len = 12 + header.len() + 8 * 8 + 8 * STRIP_LEN; + for _ in 0..8 { + // 8 claimed bytes whose recorded checksum does not match theirs (0xAA bytes do not have this CRC) + bytes.extend_from_slice(&(STRIP_LEN as u32).to_le_bytes()); + bytes.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]); + } + for _ in 0..8 { + bytes.extend_from_slice(&[0xAAu8; STRIP_LEN]); + } + assert_eq!(bytes.len(), expected_len, "the crafted file lies about its length"); + bytes +} + +#[test] +fn a_damaged_product_is_rejected_before_its_output_is_allocated() { + let bytes = damaged_product(); + let p = temp("damaged-product-heap"); + std::fs::write(&p, &bytes).unwrap(); + let _profiler = dhat::Profiler::builder().testing().build(); + let why = read_window(&p, "k", None, 1, None).err().unwrap().to_string(); + let peak = dhat::HeapStats::get().max_bytes; + let _ = std::fs::remove_file(p); + assert!(why.contains("damaged"), "{why}"); + eprintln!("peak heap {peak} bytes"); + assert!(peak < 4 << 20, "peak heap {peak} bytes: the output was reserved before the strips were checked"); +} diff --git a/crates/denoise/src/reference.rs b/crates/denoise/src/reference.rs index ef58b5b9ce..488e9a7b7c 100644 --- a/crates/denoise/src/reference.rs +++ b/crates/denoise/src/reference.rs @@ -4,6 +4,12 @@ use crate::net::{Net, NetError, Op, TensorId}; use crate::run::{Error, TileRunner}; +/// The tensors' size cap: the same one the real runner's buffers share (`crates/denoise/src/cpu.rs`). A hostile `Net` +/// only ever has to satisfy the final shape: a `ConvT2` doubles the sides and a `MaxPool` halves them, so a small +/// accepted graph can zoom its intermediates far out and back. Every tensor is counted here, and a run whose layers +/// would retain more than one real tile's whole working set is refused before the memory behind it is reserved. +const MAX_VALUES: usize = 128 * 1024 * 1024; + /// A tensor in `[channels][side][side]` order. struct T { channels: usize, @@ -11,12 +17,36 @@ struct T { data: Vec<f32>, } +/// A tensor's plain float count, in bounds. +fn count(channels: usize, side: usize) -> Result<usize, NetError> { + channels + .checked_mul(side) + .and_then(|n| n.checked_mul(side)) + .filter(|&n| n > 0 && n <= MAX_VALUES) + .ok_or_else(|| NetError::Invalid("a tensor has no size or is too large".into())) +} + +/// A zeroed tensor, keeping the memory the run keeps alive in bounds (`tensors` retains every layer's result). +fn tensor(channels: usize, side: usize, total: &mut usize) -> Result<Vec<f32>, NetError> { + let n = count(channels, side)?; + *total = (*total).saturating_add(n); + if *total > MAX_VALUES { + return Err(NetError::Invalid("the tile needs too much working memory".into())); + } + let mut data = Vec::new(); + data.try_reserve_exact(n).map_err(|_| NetError::Invalid("not enough memory for a reference tile".into()))?; + data.resize(n, 0.0); + Ok(data) +} + /// Run `net` on `input` (`in_channels` planes of `tile × tile`). pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError> { if !net.fits_tile(tile) || input.len() != net.in_channels * tile * tile { return Err(NetError::Invalid("the tile does not fit the network".into())); } - let mut tensors: Vec<T> = vec![T { channels: net.in_channels, side: tile, data: input.to_vec() }]; + let input = input.to_vec(); + let mut total = input.len(); + let mut tensors = vec![T { channels: net.in_channels, side: tile, data: input }]; let get = |tensors: &[T], id: TensorId| -> Result<usize, NetError> { if id < tensors.len() { Ok(id) } else { Err(NetError::Invalid("a layer reads a tensor that does not exist yet".into())) } }; @@ -27,7 +57,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError> let b = c.src2.map(|s| get(&tensors, s)).transpose()?; let side = tensors[a].side; let pad = (c.k - 1) / 2; - let mut data = vec![0f32; c.cout * side * side]; + let mut data = tensor(c.cout, side, &mut total)?; // the input channels in order: the first source's, then the second's let planes: Vec<&[f32]> = std::iter::once(&tensors[a]).chain(b.map(|b| &tensors[b])).flat_map(|t| t.data.chunks(side * side)).collect(); @@ -56,7 +86,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError> let a = get(&tensors, c.src)?; let side = tensors[a].side; let out_side = 2 * side; - let mut data = vec![0f32; c.cout * out_side * out_side]; + let mut data = tensor(c.cout, out_side, &mut total)?; for co in 0..c.cout { for y in 0..side { for x in 0..side { @@ -77,7 +107,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError> Op::MaxPool2 { src } => { let a = get(&tensors, *src)?; let (channels, side) = (tensors[a].channels, tensors[a].side / 2); - let mut data = vec![0f32; channels * side * side]; + let mut data = tensor(channels, side, &mut total)?; for ch in 0..channels { for y in 0..side { for x in 0..side { @@ -92,7 +122,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError> let a = get(&tensors, *src)?; let (channels, side) = (tensors[a].channels / 4, tensors[a].side); let out_side = 2 * side; - let mut data = vec![0f32; channels * out_side * out_side]; + let mut data = tensor(channels, out_side, &mut total)?; for ch in 0..channels { for y in 0..side { for x in 0..side { @@ -131,3 +161,39 @@ impl TileRunner for ReferenceRunner { run(&self.net, self.tile, input).map_err(|e| Error::Runtime(e.to_string())) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::ConvT2; + + fn convt(src: TensorId, cin: usize, cout: usize) -> Op { + Op::ConvT2(ConvT2 { src, cin, cout, weight: vec![0.1; cin * cout * 4], bias: vec![0.0; cout], leaky: None }) + } + + /// A graph that fits the final-shape check while zooming its intermediates out and back: 256 `ConvT2`s double + /// the sides (256 tiers), 255 `MaxPool`s halve them back to the layer above the input. + fn hostile() -> Net { + let mut ops = Vec::new(); + let mut last = 0usize; + for _ in 0..256 { + ops.push(convt(last, 1, 1)); + last += 1; + } + for _ in 0..255 { + ops.push(Op::MaxPool2 { src: last }); + last += 1; + } + Net::new(1, ops).unwrap() + } + + /// The zoomed-out layers' memory was never reserved: either one tensor or the retained whole (the two bounds + /// share the cap) says why the run stops. + #[test] + fn a_graph_that_zooms_its_intermediates_out_and_back_is_refused_before_their_memory_is_reserved() { + assert!(matches!( + run(&hostile(), 1, &[1.0]), + Err(NetError::Invalid(why)) if why.contains("too large") || why.contains("too much working memory") + )); + } +} diff --git a/crates/denoise/tests/it/main.rs b/crates/denoise/tests/it/main.rs new file mode 100644 index 0000000000..010fac0e24 --- /dev/null +++ b/crates/denoise/tests/it/main.rs @@ -0,0 +1,4 @@ +//! The integration tests, one module per file, linked into one test binary. + +#[cfg(feature = "runtime")] +mod real_model; diff --git a/crates/denoise/tests/real_model.rs b/crates/denoise/tests/it/real_model.rs similarity index 99% rename from crates/denoise/tests/real_model.rs rename to crates/denoise/tests/it/real_model.rs index 203e993789..ee6c27694c 100644 --- a/crates/denoise/tests/real_model.rs +++ b/crates/denoise/tests/it/real_model.rs @@ -2,7 +2,7 @@ //! //! ```text //! LC_DENOISE_MODEL=<model_bayer.onnx> LC_DENOISE_MOSAICS=<folder> LC_DENOISE_OUT=<folder> \ -//! cargo test --release -p lightcraft-denoise --features runtime --test real_model -- --ignored --nocapture +//! cargo test --release -p lightcraft-denoise --features runtime --test it real_model:: -- --ignored --nocapture //! ``` //! //! `LC_DENOISE_MOSAICS` holds `<name>.mosaic.f32` (little-endian f32, normalised: black 0, white 1, not white @@ -11,8 +11,6 @@ //! once, default 8), `LC_DENOISE_ONLY` (one name), `LC_DENOISE_ISO` (noise strength, default 1.0; 0 adds none), //! `LC_DENOISE_FULL` (the whole frame instead of a 2048 × 1536 crop). -#![cfg(feature = "runtime")] - use std::path::{Path, PathBuf}; use std::time::Instant; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9caa8cdb0e..0b203f7954 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -39,7 +39,7 @@ thiserror = { workspace = true } log = { workspace = true } ab_glyph = { workspace = true } # Apply the font’s vertical substitutions and origins to Japanese watermarks. -harfrust = { version = "0.12", default-features = false, features = ["std"] } +harfrust = { version = "0.13", default-features = false, features = ["std"] } unicode-segmentation = "1.13" lightcraft-segment = { workspace = true, optional = true } diff --git a/crates/engine/src/availability.rs b/crates/engine/src/availability.rs index 5976a3b2ee..3cf5ce19c3 100644 --- a/crates/engine/src/availability.rs +++ b/crates/engine/src/availability.rs @@ -7,6 +7,16 @@ //! there"; the render worker finds out if it isn't), known answers are rechecked after //! [`RECHECK`]. Everywhere else (CLI, MCP, tests) the default is synchronous: every question is a //! fresh check, as before. +//! +//! The same worker can check a list of files, such as every library photo's, now and then +//! ([`Availability::sweep`]), one at a time and only while nothing is asked. That is for the +//! Missing Photos count ([`Availability::is_gone`]): one stream of checks on a share, not one per +//! thing that wants to know. The app starts the sweeps; nothing here does. +//! +//! A sweep of a large library on a share takes tens of minutes, and its `stat`s compete with the +//! reads of an import or a scan on the same share. So the worker starts no sweep check while the +//! caller says files are busy ([`Availability::sweep_yields_to`]); what is asked still gets +//! answered (within [`YIELD_POLL`]), and the sweep goes on where it stopped when the work ends. use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; @@ -14,9 +24,16 @@ use std::time::Duration; /// Checks whether a path exists (injectable: tests use a slow one). pub type ExistsProbe = Arc<dyn Fn(&str) -> bool + Send + Sync>; -/// Called (from the worker) when an answer changed, e.g. to repaint the UI. +/// Called (from the worker) when an answer changed, e.g. to repaint the UI (a sweep's first look +/// at a file that is there changes no answer anyone sees, so it wakes nobody). pub type Waker = Arc<dyn Fn() + Send + Sync>; +/// Whether file work that a sweep should not compete with is going on. +pub type Busy = Arc<dyn Fn() -> bool + Send + Sync>; + +/// How often a sweep that is giving way looks whether the work has ended. +const YIELD_POLL: Duration = Duration::from_millis(250); + /// How long a cached answer is used before it is checked again (it is still returned meanwhile). pub const RECHECK: Duration = Duration::from_secs(15); @@ -31,9 +48,17 @@ struct State { known: HashMap<String, (bool, std::time::Instant)>, queue: VecDeque<String>, queued: HashSet<String>, + /// What a sweep has left to check: after the queue, whatever it holds. + sweep: VecDeque<String>, + /// The files found not there (and not found there since). + gone: HashSet<String>, worker: bool, - /// Bumped whenever an answer changes (callers recompute what depends on it). - generation: u64, + /// Bumped when the sweep under way is dropped for another one ([`Availability::restart_sweeps`]). + sweep_epoch: u64, + /// Whether file work a sweep gives way to is going on. + busy: Option<Busy>, + /// Bumped whenever a file is found gone, or found back. + gone_generation: u64, } fn lock(m: &Mutex<State>) -> MutexGuard<'_, State> { @@ -66,7 +91,8 @@ impl Availability { self.probe = probe; let mut st = lock(&self.state); st.known.clear(); - st.generation += 1; + st.gone.clear(); + st.gone_generation += 1; } /// Answer from the cache and check on a worker thread from now on; `wake` runs when an @@ -78,6 +104,14 @@ impl Availability { self.background = Some(wake); } + /// The sweep starts no check while `busy` says so (the caller's import, scan or Local read in + /// flight); asked files are answered all the same, and the sweep resumes where it was left when + /// `busy` turns false. `busy` should read state that a task's guard owns (the activity stack), so + /// a task that never ends cleanly can't hold the sweep for good. + pub fn sweep_yields_to(&self, busy: Busy) { + lock(&self.state).busy = Some(busy); + } + /// The existence check itself (blocking: for worker threads, e.g. the Rename preview's). pub fn probe(&self) -> ExistsProbe { self.probe.clone() @@ -99,12 +133,7 @@ impl Availability { if cached.is_none_or(|(_, at)| now.saturating_duration_since(at) >= RECHECK) && !st.queued.contains(path) { st.queued.insert(path.to_string()); st.queue.push_back(path.to_string()); - if !st.worker { - st.worker = true; - drop(st); - self.spawn_worker(wake.clone()); - return cached.map(|c| c.0); - } + self.start(st, wake); } cached.map(|c| c.0) } @@ -114,9 +143,10 @@ impl Availability { self.exists(path) == Some(false) } - /// Changes whenever a cached answer changes. - pub fn generation(&self) -> u64 { - lock(&self.state).generation + /// Changes whenever a file is found gone or found back: what [`Availability::is_offline`] + /// says changed for some file. (A file found there at its first check changes nothing.) + pub fn gone_generation(&self) -> u64 { + lock(&self.state).gone_generation } /// Paths waiting for the worker. @@ -124,37 +154,123 @@ impl Availability { lock(&self.state).queue.len() } + /// Check `paths` too, in the background and after whatever is asked meanwhile, skipping those + /// checked less than [`RECHECK`] ago. One sweep at a time: `false` (and nothing queued) while + /// one is under way, or in synchronous mode. A sweep's answers wake only when a file is found + /// gone or back. + pub fn sweep(&self, paths: Vec<String>) -> bool { + self.sweep_checked(None, paths) + } + + fn sweep_checked(&self, epoch: Option<u64>, paths: Vec<String>) -> bool { + let Some(wake) = &self.background else { return false }; + let mut st = lock(&self.state); + if !st.sweep.is_empty() || epoch.is_some_and(|e| e != st.sweep_epoch) { + return false; + } + st.sweep = paths.into(); + self.start(st, wake); + true + } + + /// Drop what the sweep under way has left (another library was opened: its files are not the + /// ones to check now) and say which sweeps may start from here ([`Availability::sweep_in`]): a + /// list of files being made for the old one is then refused. + pub fn restart_sweeps(&self) -> u64 { + let mut st = lock(&self.state); + st.sweep.clear(); + st.sweep_epoch += 1; + st.sweep_epoch + } + + /// [`Availability::sweep`], unless [`Availability::restart_sweeps`] was called since it + /// returned `epoch`. + pub fn sweep_in(&self, epoch: u64, paths: Vec<String>) -> bool { + self.sweep_checked(Some(epoch), paths) + } + + /// Whether the file at `path` was found gone (and not found there since): `false` for a file + /// not checked yet. + pub fn is_gone(&self, path: &str) -> bool { + lock(&self.state).gone.contains(path) + } + + /// How many files are found gone. + pub fn gone_len(&self) -> usize { + lock(&self.state).gone.len() + } + + /// What the sweep under way has left to check (0: none under way, though its last file may still + /// be in flight). + pub fn sweeping(&self) -> usize { + lock(&self.state).sweep.len() + } + + /// Start the worker, unless it runs. + fn start(&self, mut st: MutexGuard<'_, State>, wake: &Waker) { + if !st.worker { + st.worker = true; + drop(st); + self.spawn_worker(wake.clone()); + } + } + fn spawn_worker(&self, wake: Waker) { let (state, probe) = (self.state.clone(), self.probe.clone()); let started = std::thread::Builder::new().name("lc-availability".into()).spawn(move || { loop { - let path = { + // what was asked first; a sweep's next file when nothing is (unless it is asked + // about too, or was checked a moment ago) + let (path, asked) = { let mut st = lock(&state); - let Some(p) = st.queue.pop_front() else { - st.worker = false; - return; - }; - p + let giving_way = if st.queue.is_empty() && !st.sweep.is_empty() { st.busy.clone() } else { None }; + if let Some(busy) = giving_way { + drop(st); + if busy() { + // (the worker stays: a question asked meanwhile is answered within YIELD_POLL) + std::thread::sleep(YIELD_POLL); + continue; + } + st = lock(&state); + } + match st.queue.pop_front() { + Some(p) => (p, true), + None => loop { + let Some(p) = st.sweep.pop_front() else { + st.worker = false; + return; + }; + let fresh = st.known.get(&p).is_some_and(|(_, at)| at.elapsed() < RECHECK); + if !fresh && !st.queued.contains(&p) { + break (p, false); + } + }, + } }; let ok = probe(&path); - let changed = { + let wakes = { let mut st = lock(&state); - st.queued.remove(&path); + if asked { + st.queued.remove(&path); + } + let gone_changed = if ok { st.gone.remove(&path) } else { st.gone.insert(path.clone()) }; let prev = st.known.insert(path, (ok, std::time::Instant::now())); let changed = prev.map(|p| p.0) != Some(ok); - if changed { - st.generation += 1; + if gone_changed { + st.gone_generation += 1; } - changed + (asked && changed) || gone_changed }; - if changed { + if wakes { wake(); } } }); if started.is_err() { - // try again on the next question - lock(&self.state).worker = false; + // try again on the next question; a sweep nobody works on would refuse every new one + let mut st = lock(&self.state); + st.worker = false; + st.sweep.clear(); } } } @@ -210,6 +326,209 @@ mod tests { assert!(a.is_offline("gone") && !a.is_offline("here") && !a.is_offline("unknown")); assert_eq!(on_caller.load(Ordering::SeqCst), 0, "never probed on the calling thread"); assert!(woke.load(Ordering::SeqCst) >= 2); - assert!(a.generation() >= 2); + assert!(a.gone_generation() >= 2); + } + + fn wait_until(what: &str, done: impl Fn() -> bool) { + let deadline = std::time::Instant::now() + Duration::from_secs(20); + while !done() { + assert!(std::time::Instant::now() < deadline, "timed out waiting: {what}"); + std::thread::sleep(Duration::from_millis(2)); + } + } + + fn held<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// A background `Availability` whose probe logs what it checks; files named `gone…` are not there. + fn logged() -> (Availability, Arc<Mutex<Vec<String>>>, Arc<AtomicUsize>) { + let mut a = Availability::default(); + let log = Arc::new(Mutex::new(Vec::new())); + let l = log.clone(); + a.set_probe(Arc::new(move |p| { + held(&l).push(p.to_string()); + !p.starts_with("gone") + })); + let woke = Arc::new(AtomicUsize::new(0)); + let w = woke.clone(); + a.run_in_background(Arc::new(move || { + w.fetch_add(1, Ordering::SeqCst); + })); + (a, log, woke) + } + + #[test] + fn the_files_a_sweep_finds_gone_are_counted() { + let (a, _, _) = logged(); + assert!(a.sweep(vec!["here".into(), "gone 1".into(), "also here".into(), "gone 2".into()])); + wait_until("the sweep", || a.sweeping() == 0 && a.pending() == 0); + wait_until("the answers", || a.gone_len() == 2); + assert!(a.is_gone("gone 1") && a.is_gone("gone 2") && !a.is_gone("here") && !a.is_gone("also here")); + } + + #[test] + fn files_found_there_at_first_look_change_nothing_for_missing_photos() { + let (a, _, woke) = logged(); + let before = a.gone_generation(); + a.sweep(vec!["a".into(), "b".into(), "c".into()]); + wait_until("the answers", || ["a", "b", "c"].iter().all(|p| lock(&a.state).known.contains_key(*p))); + assert_eq!(a.gone_generation(), before, "nothing went missing"); + assert_eq!(woke.load(Ordering::SeqCst), 0, "a sweep finding files there wakes nobody"); + a.sweep(vec!["gone".into()]); + wait_until("the gone file", || a.gone_generation() != before); + wait_until("the wake", || woke.load(Ordering::SeqCst) == 1); + } + + #[test] + fn what_is_asked_is_checked_before_the_rest_of_a_sweep_and_one_sweep_runs_at_a_time() { + let mut a = Availability::default(); + let log = Arc::new(Mutex::new(Vec::<String>::new())); + // the first file of the sweep holds the worker until the test has asked about another + let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let (l, g) = (log.clone(), gate.clone()); + a.set_probe(Arc::new(move |p| { + if p == "sweep 0" { + let (open, cv) = &*g; + let mut open = held(open); + while !*open { + open = cv.wait(open).unwrap_or_else(PoisonError::into_inner); + } + } + held(&l).push(p.to_string()); + true + })); + a.run_in_background(Arc::new(|| {})); + assert!(a.sweep((0..50).map(|i| format!("sweep {i}")).collect())); + assert!(!a.sweep(vec!["another".into()]), "a sweep under way: the next one waits for its turn"); + assert_eq!(a.exists("asked"), None, "not known yet"); + *held(&gate.0) = true; + gate.1.notify_all(); + wait_until("the log", || held(&log).len() == 51); + let log = held(&log); + // (at most the file the worker was already checking comes first) + assert!(matches!(log.iter().position(|p| p == "asked"), Some(0 | 1)), "asked next, ahead of the sweep: {log:?}"); + assert!(!log.iter().any(|p| p == "another")); + } + + #[test] + fn a_new_sweep_replaces_the_one_under_way_and_a_list_made_for_the_old_one_is_refused() { + let mut a = Availability::default(); + let log = Arc::new(Mutex::new(Vec::<String>::new())); + // the old sweep's first file holds the worker until the new one is in place + let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let (l, g) = (log.clone(), gate.clone()); + a.set_probe(Arc::new(move |p| { + if p == "old 0" { + let (open, cv) = &*g; + let mut open = held(open); + while !*open { + open = cv.wait(open).unwrap_or_else(PoisonError::into_inner); + } + } + held(&l).push(p.to_string()); + true + })); + a.run_in_background(Arc::new(|| {})); + let old = a.restart_sweeps(); + assert!(a.sweep_in(old, (0..20).map(|i| format!("old {i}")).collect())); + wait_until("the worker takes the first file", || a.sweeping() == 19); + // another library is opened: what is left of the old sweep goes, and a list still being made for it too + let new = a.restart_sweeps(); + assert_eq!(a.sweeping(), 0); + assert!(!a.sweep_in(old, vec!["old late".into()]), "a list made for the old library is refused"); + assert!(a.sweep_in(new, (0..3).map(|i| format!("new {i}")).collect())); + *held(&gate.0) = true; + gate.1.notify_all(); + wait_until("the new sweep", || held(&log).len() == 4); + assert_eq!(*held(&log), ["old 0", "new 0", "new 1", "new 2"]); + } + + #[test] + fn files_found_gone_are_told_apart_from_files_never_checked() { + let (a, _, _) = logged(); + assert!(!a.is_gone("gone 1") && a.gone_len() == 0); + assert!(a.sweep(vec!["gone 1".into(), "here".into()])); + wait_until("the sweep", || a.sweeping() == 0 && a.pending() == 0 && a.gone_len() == 1); + assert!(a.is_gone("gone 1") && !a.is_gone("here") && !a.is_gone("never asked")); + } + + fn busy_flag(a: &Availability) -> Arc<std::sync::atomic::AtomicBool> { + let busy = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let b = busy.clone(); + a.sweep_yields_to(Arc::new(move || b.load(Ordering::SeqCst))); + busy + } + + #[test] + fn a_sweep_gives_way_to_file_work_answers_what_is_asked_and_resumes_after() { + let (a, log, _) = logged(); + let busy = busy_flag(&a); + assert!(a.sweep((0..20).map(|i| format!("sweep {i}")).collect())); + std::thread::sleep(YIELD_POLL * 3); + assert!(held(&log).is_empty(), "no sweep check while files are busy"); + assert_eq!(a.sweeping(), 20, "nothing of the sweep is lost"); + assert_eq!(a.exists("asked"), None); + wait_until("the answer", || a.exists("asked") == Some(true)); + assert_eq!(*held(&log), ["asked"], "what is asked is answered, the sweep still waits"); + busy.store(false, Ordering::SeqCst); + wait_until("the sweep", || a.sweeping() == 0); + wait_until("the log", || held(&log).len() == 21); + // it went on from its first file, not from scratch + assert_eq!(held(&log).iter().filter(|p| *p == "sweep 0").count(), 1); + } + + #[test] + fn a_sweep_stopped_part_way_goes_on_from_there() { + let mut a = Availability::default(); + let log = Arc::new(Mutex::new(Vec::<String>::new())); + let l = log.clone(); + // the worker is held inside the fourth check until the sweep is told to give way + let hold = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let h = hold.clone(); + a.set_probe(Arc::new(move |p| { + while p == "sweep 3" && h.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + held(&l).push(p.to_string()); + true + })); + a.run_in_background(Arc::new(|| {})); + let busy = busy_flag(&a); + busy.store(false, Ordering::SeqCst); + assert!(a.sweep((0..100).map(|i| format!("sweep {i}")).collect())); + wait_until("a few checks", || held(&log).len() >= 3); + busy.store(true, Ordering::SeqCst); + hold.store(false, Ordering::SeqCst); + std::thread::sleep(YIELD_POLL * 2); + let stopped = held(&log).len(); + assert_eq!(stopped, 4, "stopped part way, after the check it was in"); + std::thread::sleep(YIELD_POLL * 2); + assert_eq!(held(&log).len(), stopped, "paused"); + assert_eq!(a.sweeping(), 100 - stopped, "what is left is kept"); + busy.store(false, Ordering::SeqCst); + wait_until("the sweep", || a.sweeping() == 0 && held(&log).len() == 100); + let mut all = held(&log).clone(); + all.sort(); + all.dedup(); + assert_eq!(all.len(), 100, "every file checked once, none again from the start"); + } + + #[test] + fn a_sweep_that_yields_to_nothing_runs_as_before() { + let (a, log, _) = logged(); + assert!(a.sweep(vec!["a".into(), "b".into()])); + wait_until("the sweep", || held(&log).len() == 2); + } + + #[test] + fn a_sweep_skips_files_checked_a_moment_ago() { + let (a, log, _) = logged(); + assert_eq!(a.exists("a"), None); + wait_until("the answer", || a.exists("a").is_some()); + a.sweep(vec!["a".into(), "b".into()]); + wait_until("b", || held(&log).iter().any(|p| p == "b")); + wait_until("the sweep", || a.sweeping() == 0); + assert_eq!(held(&log).iter().filter(|p| *p == "a").count(), 1, "`a` was checked a moment ago"); } } diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index d074567a79..1d1d7468eb 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -3066,10 +3066,14 @@ mod tests { let bundled: crate::camera_profiles::CameraProfile = serde_json::from_str(json).unwrap(); let used = crate::camera_profiles::get(model).expect("a profile for the model"); assert_eq!(*used, bundled, "a local {model} profile overrides the built-in one; remove it to run this test"); - let raw = lightcraft_raw::decode(&bytes).unwrap(); + let mut raw = lightcraft_raw::decode(&bytes).unwrap(); assert_eq!(raw.metadata.model.as_deref(), Some(model)); + // as the app does (`files.rs`): the camera's own lens warp pairs the sensor with its JPEG (Nikon's in-file + // distortion for the Z 6II and Z 8), and the lens corrections leave the opcodes before the proxy is binned + let lens = lens_geometry(&raw.opcodes.list3); + raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = fit_preview(&raw, &bytes, &transform, None).0.expect("fit accepted"); + let look = fit_preview(&raw, &bytes, &transform, lens.as_ref()).0.expect("fit accepted"); let expected = bundled.matrix().mul(&transform.matrix.inverse().unwrap()); for (row, want) in look.matrix.0.iter().zip(expected.0) { for (got, want) in row.iter().zip(want) { diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index c7b6c437b1..9e6d2094ee 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -28,6 +28,7 @@ pub const BUNDLED: &[(&str, &str)] = &[ ("ILCA-99M2", include_str!("../../../assets/camera-profiles/ILCA-99M2.json")), ("ILCE-7CR", include_str!("../../../assets/camera-profiles/ILCE-7CR.json")), ("ILCE-7M4", include_str!("../../../assets/camera-profiles/ILCE-7M4.json")), + ("ILCE-7RM5", include_str!("../../../assets/camera-profiles/ILCE-7RM5.json")), ("NIKON D5300", include_str!("../../../assets/camera-profiles/NIKON_D5300.json")), ("NIKON Z 6_2", include_str!("../../../assets/camera-profiles/NIKON_Z_6_2.json")), ("NIKON Z 8", include_str!("../../../assets/camera-profiles/NIKON_Z_8.json")), diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 01c67c2673..6f3f889631 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -482,6 +482,9 @@ pub(crate) fn follow_folder(s: &mut Session, from: &str, to: &str) { // a library folder chosen at or below it follows too, as a source or as a filter follow_library_folder(&mut s.library_folder, from, to); follow_library_folder(&mut s.filter.library_folder, from, to); + if let Some(f) = s.shelved_filter.as_mut() { + follow_library_folder(&mut f.library_folder, from, to); + } if let Some(b) = &mut s.browse && let Ok(rel) = Path::new(&b.path).strip_prefix(from) { diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 142accd5aa..383ed890d9 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -9,10 +9,12 @@ use serde_json::{Value, json}; use super::{CommandSpec, always, cmd}; use crate::{Result, Session}; -/// Seconds between shots of the same burst at most. -const BURST_GAP: i64 = 10; -/// Signature similarity for "the same scene". -const SAME: f32 = 0.93; +/// Seconds between shots of the same burst at most (default of `burstGap`). +const BURST_GAP: f64 = 10.0; +/// Signature similarity for "the same scene" (default of `similarity`). +const SAME: f64 = 0.93; +/// The longest `burstGap` accepted: a day. +const MAX_GAP: f64 = 86_400.0; fn secs(iso: &str) -> Option<i64> { let d = lightcraft_meta::DateTime::parse_iso(iso)?; @@ -26,6 +28,7 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> { let ids: Vec<PhotoId> = ids.into_iter().filter(|id| seen.insert(*id)).collect(); let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32); let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false); + let (gap, same) = burst_params(p)?; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option<i64>, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -45,8 +48,8 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> { let mut next = 1u32; for i in 1..rows.len() { let (a, b) = (&rows[i - 1], &rows[i]); - let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y - x).abs() <= BURST_GAP); - if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= SAME { + let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y.saturating_sub(x)).unsigned_abs() as f64 <= gap); + if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= same { let g = *group_of[i - 1].get_or_insert_with(|| { next += 1; next - 1 @@ -86,6 +89,22 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({"photos": out, "groups": best.len(), "rejected": rejected, "picked": picked, "failed": failed})) } +/// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before +/// anything is measured when they are not numbers in range. +fn burst_params(p: &Value) -> Result<(f64, f32)> { + const C: &str = "photo.analyze"; + let num = |key: &str, d: f64, max: f64| -> Result<f64> { + match p.get(key) { + None | Some(Value::Null) => Ok(d), + Some(v) => match v.as_f64() { + Some(x) if x.is_finite() && (0.0..=max).contains(&x) => Ok(x), + _ => Err(super::bad(C, format!("`{key}` must be a number from 0 to {max}"))), + }, + } + }; + Ok((num("burstGap", BURST_GAP, MAX_GAP)?, num("similarity", SAME, 1.0)? as f32)) +} + /// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by /// content), most similar first; the view is filtered to them. fn find_similar(s: &mut Session, p: &Value) -> Result<Value> { @@ -109,13 +128,16 @@ fn find_similar(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = sig(s, q) { let sim = lightcraft_pipeline::cull::similarity(&me, &v); if sim >= min { - hits.push((q, sim)); + hits.push((q, sim.clamp(0.0, 1.0))); } } } hits.sort_by(|a, b| b.1.total_cmp(&a.1)); if p.get("filter").and_then(Value::as_bool).unwrap_or(true) { + s.shelved_filter = None; s.filter.only = hits.iter().map(|h| h.0).collect(); + // an empty `only` means "no constraint": no hits is its own state that shows no photos + s.filter.only_none = s.filter.only.is_empty(); } Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::<Vec<_>>()})) } @@ -136,7 +158,7 @@ pub fn specs() -> Vec<CommandSpec> { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots taken within 10 s and mark the sharpest of each; optionally reject blurry photos and pick each group's best; one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, rejected, picked}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos and pick each group's best; one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, rejected, picked}", always, analyze ), diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index e66bb56f36..e3b385e2c1 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -176,6 +176,11 @@ fn rename_person(s: &mut Session, p: &Value) -> Result<Value> { if s.filter.person.as_deref().is_some_and(|n| n.trim().to_lowercase() == from_key) { s.filter.person = Some(to.clone()); } + if let Some(f) = s.shelved_filter.as_mut() + && f.person.as_deref().is_some_and(|n| n.trim().to_lowercase() == from_key) + { + f.person = Some(to.clone()); + } Ok(json!({"faces": faces, "photos": photos, "from": from, "to": to, "merged": other})) } diff --git a/crates/engine/src/cmd/filters.rs b/crates/engine/src/cmd/filters.rs index 73bae384ff..afe2011acf 100644 --- a/crates/engine/src/cmd/filters.rs +++ b/crates/engine/src/cmd/filters.rs @@ -38,6 +38,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> { let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?; let f = s.filter_presets.iter().find(|f| f.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(C, format!("no filter preset `{name}`")))?; s.filter = f.filter.clone(); + s.shelved_filter = None; Ok(json!({"photos": s.visible().len()})) } diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index c9ffb6b7e7..feb9b033e9 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -63,6 +63,13 @@ impl PlaceNames { self.lock().running } + /// Whether a place names download has been started in this session (running, or ended). + #[cfg(test)] + pub(crate) fn download_started(&self) -> bool { + let sh = self.lock(); + sh.running || sh.last.is_some() + } + /// The gazetteer in `dir`, parsed once and re-read only when the cities file's size or time changes. fn load(&mut self, dir: &Path) -> std::result::Result<Arc<GeoNames>, lightcraft_geocode::GeocodeError> { let file = dir.join(GEONAMES_FILES[0]); diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index fe09a92f97..ebed426fae 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -32,6 +32,12 @@ fn commit_keywords(s: &mut Session, label: &str, op: lightcraft_catalog::Op, fol if let Some(k) = s.filter.keyword.clone() { s.filter.keyword = follow(&k); } + // a filter put aside by Enable Filters follows the keyword too + if let Some(f) = s.shelved_filter.as_mut() + && let Some(k) = f.keyword.clone() + { + f.keyword = follow(&k); + } Ok(json!({"changed": photos, "listed": listed})) } @@ -148,6 +154,16 @@ pub fn keyword_sets_json(s: &Session) -> Value { json!({"sets": sets, "current": s.keyword_set.clone().unwrap_or_else(|| RECENT.into()), "keywords": current_keywords(s)}) } +/// Make the set `step` places after the current one current, in the Keyword Set menu's order +/// (Recent Keywords, then the saved sets), wrapping around from the last to the first and back. +fn step_set(s: &mut Session, step: isize) -> Result<Value> { + let at = s.keyword_set.as_deref().and_then(|n| s.keyword_sets.iter().position(|x| same_set(&x.name, n))).map_or(0, |i| i + 1); + let next = (at as isize + step).rem_euclid(s.keyword_sets.len() as isize + 1) as usize; + s.keyword_set = next.checked_sub(1).and_then(|i| s.keyword_sets.get(i)).map(|x| x.name.clone()); + s.save_prefs()?; + Ok(keyword_sets_json(s)) +} + pub fn specs() -> Vec<CommandSpec> { vec![ cmd!(query "keyword.sets", "Keyword Sets", [], None, "{} → {sets: [{name, keywords}], current, keywords: the nine ⌥1–⌥9 apply}", always, |s, _| Ok(keyword_sets_json(s))), @@ -168,6 +184,24 @@ pub fn specs() -> Vec<CommandSpec> { s.save_prefs()?; Ok(keyword_sets_json(s)) }), + cmd!( + "keyword.nextSet", + "Next Keyword Set", + [], + Some("Alt+0"), + "{}: the set after the current one (after the last, Recent Keywords)", + always, + |s, _| step_set(s, 1) + ), + cmd!( + "keyword.previousSet", + "Previous Keyword Set", + [], + Some("Alt+Shift+0"), + "{}: the set before the current one (before Recent Keywords, the last)", + always, + |s, _| step_set(s, -1) + ), cmd!( "keyword.saveSet", "Save Keyword Set", @@ -445,7 +479,10 @@ pub fn specs() -> Vec<CommandSpec> { let mut r = json!({"keywords": file.written.len(), "captureOneRefuses": refuses, "unwritable": file.unwritable}); match str_param(p, "path").map(str::trim).filter(|x| !x.is_empty()) { Some(path) => { - std::fs::write(path, &file.text).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?; + s.check_write_target(path).map_err(|e| bad("keyword.export", e))?; + // A folder that isn't there is an error, not created. + lightcraft_catalog::safe_file::write_atomic(std::path::Path::new(path), file.text.as_bytes()) + .map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?; r["path"] = json!(path); } None => r["text"] = json!(file.text), diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index e437dccc23..25a03eab80 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -7,6 +7,9 @@ use serde_json::{Value, json}; use super::{CommandSpec, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, ok, str_param}; use crate::{LibrarySource, Result, Selection, Session}; +/// The selection after photos left the view (deleted, or rated, flagged or labelled out of it). +/// Its callers end an open edit (a slider drag) before their own change, as moving to the next +/// photo does, so it is its own undo step and comes first. fn select_after_deletion(s: &mut Session, before: &[PhotoId]) { let at = before.iter().position(|id| Some(*id) == s.selection.active); let remaining: std::collections::HashSet<_> = s.visible_cloned().into_iter().collect(); @@ -201,7 +204,6 @@ fn change_rating(s: &mut Session, p: &Value, delta: i8, label: &str) -> Result<V if n > 0 { s.commit(label, Op::Batch { ops })?; } - advance_if(s, p); Ok(json!({"changed": n})) } @@ -220,10 +222,36 @@ fn change_flag(s: &mut Session, p: &Value, label: &str, step: impl Fn(Flag) -> F if n > 0 { s.commit(label, Op::Batch { ops })?; } - advance_if(s, p); Ok(json!({"changed": n})) } +/// Rate, flag or label (`edit`), then `advance`. When the edit took the active photo out of the view (the filter bar, +/// Picks or a smart album shows it no more), culling goes on from its place, as after a delete: the photo after it is +/// active, or the one before it at the end (#2312), not the view's first photo. That photo is the next one, so +/// `advance` doesn't step past it. Photos named by `ids` / `id` leave the selection to the caller: Compare and Survey +/// keep showing the photo they rate. +fn cull(s: &mut Session, p: &Value, edit: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> { + let named = [p.get("ids"), p.get("id")].into_iter().any(|t| t.is_some_and(|t| !t.is_null())); + // the view as it was, then an open drag ends first, as its own undo step (the selection may + // move on; the drag itself can take the photo out of the view) + let before = (!named).then(|| s.visible_shared().1); + if !named { + s.end_interaction()?; + } + let active = s.selection.active; + let v = edit(s)?; + if let Some(before) = before + && active.is_some_and(|a| before.contains(&a) && !s.visible().contains(&a)) + { + select_after_deletion(s, &before); + s.active_mask = None; + s.active_spot = None; + } else { + advance_if(s, p); + } + Ok(v) +} + fn advance_if(s: &mut Session, p: &Value) { if bool_or(p, "advance", false) { let _ = step(s, 1); @@ -371,6 +399,9 @@ pub fn specs() -> Vec<CommandSpec> { if s.catalog.album(a).is_none_or(|a| a.folder) { return Err(bad("library.source", "no such album")); } + // one album at a time: `to_filter` makes the album shown replace the filter's, and the + // filter bar has no album chip, so a left-over one would narrow the next source unseen + s.filter.album = None; LibrarySource::Album(a) } "libraryFolder" => { @@ -426,6 +457,7 @@ pub fn specs() -> Vec<CommandSpec> { return Err(bad("library.filter", problems.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))); } s.filter = f; + s.shelved_filter = None; Ok(json!({"count": s.visible().len()})) } ), @@ -469,6 +501,15 @@ pub fn specs() -> Vec<CommandSpec> { if s.filter.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { s.filter.library_folder = None; } + // a filter put aside by Enable Filters must not bring the removed folder back + if let Some(f) = s.shelved_filter.as_mut() + && f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) + { + f.library_folder = None; + } + if s.shelved_filter.as_ref() == Some(&Filter::default()) { + s.shelved_filter = None; + } // the folder being shown is gone: back to everything, as for a deleted album if s.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { s.library_folder = None; @@ -510,8 +551,30 @@ pub fn specs() -> Vec<CommandSpec> { ), cmd!("library.clearFilter", "Clear Filters", ["View"], None, "{}", always, |s, _| { s.filter = Default::default(); + s.shelved_filter = None; Ok(json!({"count": s.visible().len()})) }), + // Classic: Library > Enable Filters (Cmd+L) switches the filter off and on again as it was + cmd!( + "library.toggleFilters", + "Enable Filters", + ["View"], + Some("Cmd+L"), + "{} — with a filter set, puts it aside and shows everything; with one put aside, brings it back as it was (stars, flag, text… together). Setting or clearing a filter while it is off forgets the one put aside → {enabled, count}", + always, + |s, _| { + if s.filter != Filter::default() { + s.shelved_filter = Some(std::mem::take(&mut s.filter)); + } else if let Some(mut f) = s.shelved_filter.take() { + // one folder at a time: the folder shown now wins over the one the filter had + if s.source == LibrarySource::LibraryFolder { + f.library_folder = None; + } + s.filter = f; + } + Ok(json!({"enabled": s.shelved_filter.is_none(), "count": s.visible().len()})) + } + ), cmd!( "library.sort", "Sort", @@ -663,7 +726,7 @@ pub fn specs() -> Vec<CommandSpec> { cmd!(query "library.devices", "Cameras and Cards", [], None, "{} → [{name, path (its DCIM folder), root}] — mounted volumes with a DCIM folder", always, |_, _| { Ok(serde_json::to_value(crate::devices::devices_now()).unwrap_or_default()) }), - cmd!(query "photo.copyMetadata", "Copy Metadata", ["Photo"], None, "{} — title, caption, copyright (notice, status, usage terms, info URL), creator, location and keywords of the active photo", has_active, |s, _| { + cmd!(query "photo.copyMetadata", "Copy Metadata", ["Photo"], Some("Cmd+Alt+Shift+C"), "{} — title, caption, copyright (notice, status, usage terms, info URL), creator, location and keywords of the active photo", has_active, |s, _| { let id = s.active().ok_or_else(|| bad("photo.copyMetadata", "no active photo"))?; let m = &s.catalog.photo(id).ok_or_else(|| bad("photo.copyMetadata", "no photo"))?.meta; let v = json!({"title": m.title, "caption": m.caption, "altText": m.alt_text, "extendedDescription": m.extended_description, @@ -677,7 +740,7 @@ pub fn specs() -> Vec<CommandSpec> { "photo.pasteMetadata", "Paste Metadata", ["Photo"], - None, + Some("Cmd+Alt+Shift+V"), "{ids?, fields?: [title|caption|copyright|copyrightStatus|usageTerms|copyrightUrl|creator|location|keywords] (default: all copied)}", has_selection, |s, p| { @@ -732,40 +795,66 @@ pub fn specs() -> Vec<CommandSpec> { |s, p| { step(s, -row_step(p)) } ), // ---- rating / flags / labels - cmd!("photo.rate", "Set Rating", ["Photo", "Set Rating"], None, "{rating: 0..5, ids?, advance?: bool}", has_selection, |s, p| { - let r = super::f64_req(p, "rating", "photo.rate")? as i64; - if !(0..=5).contains(&r) { - return Err(bad("photo.rate", "rating must be 0..5")); + cmd!( + "photo.rate", + "Set Rating", + ["Photo", "Set Rating"], + None, + "{rating: 0..5, ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", + has_selection, + |s, p| { + let r = super::index_req(p, "rating", "photo.rate") + .ok() + .filter(|r| *r <= 5) + .ok_or_else(|| bad("photo.rate", "rating must be a whole number 0..5"))?; + cull(s, p, |s| for_targets(s, p, "Set Rating", |id| Some(Op::SetRating { id, rating: r as u8 }))) } - let v = for_targets(s, p, "Set Rating", |id| Some(Op::SetRating { id, rating: r as u8 }))?; - advance_if(s, p); - Ok(v) - }), - cmd!("photo.decreaseRating", "Decrease Rating", [], None, "{ids?, advance?: bool}", has_selection, |s, p| { - change_rating(s, p, -1, "Decrease Rating") - }), - cmd!("photo.increaseRating", "Increase Rating", [], None, "{ids?, advance?: bool}", has_selection, |s, p| { - change_rating(s, p, 1, "Increase Rating") - }), - cmd!("photo.flag", "Set Flag", ["Photo", "Set Flag"], None, "{flag: pick|reject|none, ids?, advance?: bool}", has_selection, |s, p| { - let f = str_param(p, "flag").and_then(Flag::parse).ok_or_else(|| bad("photo.flag", "flag must be pick|reject|none"))?; - let v = for_targets(s, p, "Set Flag", |id| Some(Op::SetFlag { id, flag: f }))?; - advance_if(s, p); - Ok(v) - }), + ), + cmd!( + "photo.decreaseRating", + "Decrease Rating", + [], + None, + "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", + has_selection, + |s, p| { cull(s, p, |s| change_rating(s, p, -1, "Decrease Rating")) } + ), + cmd!( + "photo.increaseRating", + "Increase Rating", + [], + None, + "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", + has_selection, + |s, p| { cull(s, p, |s| change_rating(s, p, 1, "Increase Rating")) } + ), + cmd!( + "photo.flag", + "Set Flag", + ["Photo", "Set Flag"], + None, + "{flag: pick|reject|none, ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", + has_selection, + |s, p| { + let f = str_param(p, "flag").and_then(Flag::parse).ok_or_else(|| bad("photo.flag", "flag must be pick|reject|none"))?; + cull(s, p, |s| for_targets(s, p, "Set Flag", |id| Some(Op::SetFlag { id, flag: f }))) + } + ), // Classic: ` cycles the flag; Cmd+Up / Cmd+Down raise / lower it (Ctrl on Windows and Linux) cmd!( "photo.cycleFlag", "Cycle Flag", ["Photo", "Set Flag"], Some("`"), - "{ids?, advance?: bool} — each photo's own flag: unflagged -> pick -> reject -> unflagged", + "{ids?, advance?: bool} — each photo's own flag: unflagged -> pick -> reject -> unflagged; without `ids`, the selection moves on when this takes the active photo out of the view", has_selection, |s, p| { - change_flag(s, p, "Cycle Flag", |f| match f { - Flag::None => Flag::Pick, - Flag::Pick => Flag::Reject, - Flag::Reject => Flag::None, + cull(s, p, |s| { + change_flag(s, p, "Cycle Flag", |f| match f { + Flag::None => Flag::Pick, + Flag::Pick => Flag::Reject, + Flag::Reject => Flag::None, + }) }) } ), @@ -774,34 +863,52 @@ pub fn specs() -> Vec<CommandSpec> { "Increase Flag Status", ["Photo", "Set Flag"], Some("Cmd+Up"), - "{ids?, advance?: bool} — reject -> unflagged -> pick (stops at pick)", + "{ids?, advance?: bool} — reject -> unflagged -> pick (stops at pick); without `ids`, the selection moves on when this takes the active photo out of the view", has_selection, - |s, p| { change_flag(s, p, "Increase Flag Status", |f| if f == Flag::Reject { Flag::None } else { Flag::Pick }) } + |s, p| { cull(s, p, |s| change_flag(s, p, "Increase Flag Status", |f| if f == Flag::Reject { Flag::None } else { Flag::Pick })) } ), cmd!( "photo.decreaseFlag", "Decrease Flag Status", ["Photo", "Set Flag"], Some("Cmd+Down"), - "{ids?, advance?: bool} — pick -> unflagged -> reject (stops at reject)", + "{ids?, advance?: bool} — pick -> unflagged -> reject (stops at reject); without `ids`, the selection moves on when this takes the active photo out of the view", has_selection, - |s, p| { change_flag(s, p, "Decrease Flag Status", |f| if f == Flag::Pick { Flag::None } else { Flag::Reject }) } + |s, p| { cull(s, p, |s| change_flag(s, p, "Decrease Flag Status", |f| if f == Flag::Pick { Flag::None } else { Flag::Reject })) } + ), + cmd!( + "photo.pick", + "Flag as Pick", + ["Photo", "Set Flag"], + Some("P"), + "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", + has_selection, + |s, p| { cull(s, p, |s| for_targets(s, p, "Flag as Pick", |id| Some(Op::SetFlag { id, flag: Flag::Pick }))) } + ), + cmd!( + "photo.reject", + "Flag as Reject", + ["Photo", "Set Flag"], + Some("X"), + "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", + has_selection, + |s, p| { cull(s, p, |s| for_targets(s, p, "Flag as Reject", |id| Some(Op::SetFlag { id, flag: Flag::Reject }))) } + ), + cmd!( + "photo.unflag", + "Unflag", + ["Photo", "Set Flag"], + Some("U"), + "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", + has_selection, + |s, p| { cull(s, p, |s| for_targets(s, p, "Unflag", |id| Some(Op::SetFlag { id, flag: Flag::None }))) } ), - cmd!("photo.pick", "Flag as Pick", ["Photo", "Set Flag"], Some("P"), "{ids?}", has_selection, |s, p| { - for_targets(s, p, "Flag as Pick", |id| Some(Op::SetFlag { id, flag: Flag::Pick })) - }), - cmd!("photo.reject", "Flag as Reject", ["Photo", "Set Flag"], Some("X"), "{ids?}", has_selection, |s, p| { - for_targets(s, p, "Flag as Reject", |id| Some(Op::SetFlag { id, flag: Flag::Reject })) - }), - cmd!("photo.unflag", "Unflag", ["Photo", "Set Flag"], Some("U"), "{ids?}", has_selection, |s, p| { - for_targets(s, p, "Unflag", |id| Some(Op::SetFlag { id, flag: Flag::None })) - }), cmd!( "photo.label", "Set Color Label", ["Photo", "Set Color Label"], None, - "{label: red|yellow|green|blue|purple|none, ids?}", + "{label: red|yellow|green|blue|purple|none, ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view", has_selection, |s, p| { // `none` (or null) clears; a missing label or one that isn't text is an error, not a clear @@ -812,7 +919,7 @@ pub fn specs() -> Vec<CommandSpec> { None => return Err(bad("photo.label", "missing `label` (red|yellow|green|blue|purple|none)")), Some(_) => return Err(bad("photo.label", "label must be red|yellow|green|blue|purple|none")), }; - for_targets(s, p, "Set Color Label", |id| Some(Op::SetLabel { id, label: l })) + cull(s, p, |s| for_targets(s, p, "Set Color Label", |id| Some(Op::SetLabel { id, label: l }))) } ), // ---- orientation @@ -883,6 +990,8 @@ pub fn specs() -> Vec<CommandSpec> { cmd!("photo.delete", "Delete Photo", ["Photo"], Some("Delete"), "{ids?} — moves to Recently Deleted", has_selection, |s, p| { let before = s.visible_cloned(); let targets = s.targets(p)?; + // an open drag ends first, as its own undo step (the selection moves on) + s.end_interaction()?; let n = mark_deleted(s, &targets, "Delete")?; select_after_deletion(s, &before); Ok(json!({"changed": n})) @@ -912,6 +1021,8 @@ pub fn specs() -> Vec<CommandSpec> { cmd!("photo.deletePermanently", "Delete Permanently", ["Photo"], None, "{ids?}", has_selection, |s, p| { let before = s.visible_cloned(); let t = s.targets(p)?; + // before the inverse ops are taken, so undo brings the photo back with its edit + s.end_interaction()?; let op = s.catalog.delete_photos_permanently_ops(&t); s.commit("Delete Permanently", op)?; select_after_deletion(s, &before); @@ -1603,7 +1714,7 @@ pub fn specs() -> Vec<CommandSpec> { s.compact_library()?; ok() }), - cmd!("library.clearPreviews", "Clear Preview Cache", ["File"], None, "{}", always, |s, _| { + cmd!("library.clearPreviews", "Discard Preview Cache", ["File"], None, "{}", always, |s, _| { s.media.rendered.clear(); s.media.clear_sources(); ok() @@ -1771,3 +1882,15 @@ mod relative_rating_tests; #[cfg(test)] #[path = "library/tests_flag_cycle.rs"] mod flag_cycle_tests; + +#[cfg(test)] +#[path = "library/tests_rated_out.rs"] +mod rated_out_tests; + +#[cfg(test)] +#[path = "library/tests_enable_filters.rs"] +mod enable_filters_tests; + +#[cfg(test)] +#[path = "library/tests_source_album_filter.rs"] +mod source_album_filter_tests; diff --git a/crates/engine/src/cmd/library/tests_enable_filters.rs b/crates/engine/src/cmd/library/tests_enable_filters.rs new file mode 100644 index 0000000000..9eb3c1ad03 --- /dev/null +++ b/crates/engine/src/cmd/library/tests_enable_filters.rs @@ -0,0 +1,154 @@ +//! `library.toggleFilters` (Library > Enable Filters, Cmd+L) through the real engine. +use lightcraft_catalog::{Filter, Flag, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::{LibrarySource, Result, Session}; + +fn session() -> Result<Session> { + let mut s = Session::new(); + for (id, rating, flag) in [(1, 5, Flag::Pick), (2, 5, Flag::None), (3, 2, Flag::Pick), (4, 1, Flag::None)] { + let mut photo = Photo::new( + PhotoId(id), + Source::File { path: format!("/lightcraft-enable-filters/{id}.jpg") }, + &format!("{id}.jpg"), + "JPEG", + 40, + 30, + "2026-10-23", + ); + photo.rating = rating; + photo.flag = flag; + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) })?; + } + Ok(s) +} + +fn stars_and_pick(s: &mut Session) { + s.execute("library.filter", &json!({"rating": 4, "flag": "pick"})).unwrap(); +} + +#[test] +fn off_shows_everything_and_on_brings_back_the_same_filter() { + let mut s = session().unwrap(); + stars_and_pick(&mut s); + let set = s.filter.clone(); + assert_eq!(s.visible().len(), 1, "the filter hides photos, or off and on would look alike"); + let r = s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!((r["enabled"].clone(), r["count"].clone()), (json!(false), json!(4))); + assert_eq!(s.filter, Filter::default()); + assert_eq!(s.visible().len(), 4); + let r = s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!((r["enabled"].clone(), r["count"].clone()), (json!(true), json!(1))); + assert_eq!(s.filter, set, "stars and flag come back together"); + assert_eq!(s.visible().len(), 1); +} + +#[test] +fn with_no_filter_it_does_nothing_and_leaves_nothing_to_bring_back() { + let mut s = session().unwrap(); + let r = s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!((r["enabled"].clone(), r["count"].clone()), (json!(true), json!(4))); + let r = s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(r["enabled"], json!(true)); + assert_eq!(s.filter, Filter::default()); + assert!(s.shelved_filter.is_none()); +} + +#[test] +fn setting_a_filter_while_off_turns_filtering_on_and_forgets_the_old_one() { + let mut s = session().unwrap(); + stars_and_pick(&mut s); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.filter", &json!({"rating": 2})).unwrap(); + assert_eq!(s.visible().len(), 3); + // off again, then on: the filter that was set last, not the first one + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter.rating, 2); + assert_eq!(s.filter.flag, None); +} + +#[test] +fn emptying_the_filter_by_hand_while_off_leaves_nothing_to_bring_back() { + let mut s = session().unwrap(); + stars_and_pick(&mut s); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.filter", &json!({"rating": 2})).unwrap(); + s.execute("library.filter", &json!({"rating": 0})).unwrap(); + assert_eq!(s.filter, Filter::default()); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter, Filter::default(), "the filter from before it was switched off is not back"); + assert_eq!(s.visible().len(), 4); +} + +#[test] +fn clearing_the_filter_while_off_leaves_nothing_to_bring_back() { + let mut s = session().unwrap(); + stars_and_pick(&mut s); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.clearFilter", &json!({})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter, Filter::default()); + assert_eq!(s.visible().len(), 4); +} + +#[test] +fn applying_a_preset_while_off_turns_filtering_on_with_the_preset() { + let mut s = session().unwrap(); + s.filter_presets.push(super::super::filters::FilterPreset { name: "Fives".into(), filter: Filter { rating: 5, ..Default::default() } }); + stars_and_pick(&mut s); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("filter.applyPreset", &json!({"name": "Fives"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter.rating, 5); + assert_eq!(s.filter.flag, None); +} + +#[test] +fn a_folder_filter_does_not_come_back_over_the_folder_now_shown() { + let mut s = session().unwrap(); + s.execute("library.filter", &json!({"rating": 4, "libraryFolder": "/lightcraft-enable-filters"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.source = LibrarySource::LibraryFolder; + s.library_folder = Some("/lightcraft-enable-filters".into()); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter.rating, 4); + assert_eq!(s.filter.library_folder, None); +} + +#[test] +fn removing_a_folder_while_off_drops_it_from_the_filter_put_aside() { + let mut s = session().unwrap(); + s.execute("library.filter", &json!({"rating": 4, "libraryFolder": "/lightcraft-enable-filters"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.removeFolder", &json!({"path": "/lightcraft-enable-filters"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter.library_folder, None, "the removed folder is not brought back"); + assert_eq!(s.filter.rating, 4, "the rest of the filter is"); +} + +#[test] +fn removing_the_only_criterion_put_aside_leaves_filtering_on() { + let mut s = session().unwrap(); + s.execute("library.filter", &json!({"libraryFolder": "/lightcraft-enable-filters"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.removeFolder", &json!({"path": "/lightcraft-enable-filters"})).unwrap(); + assert!(s.shelved_filter.is_none(), "an empty filter is not left put aside"); +} + +#[test] +fn a_keyword_renamed_while_off_is_followed_by_the_filter_put_aside() { + let mut s = session().unwrap(); + let mut photo = Photo::new(PhotoId(5), Source::File { path: "/lightcraft-enable-filters/5.jpg".into() }, "5.jpg", "JPEG", 40, 30, "2026-10-23"); + photo.meta.keywords = vec!["cat".into()]; + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + s.filter.keyword = Some("cat".into()); + assert_eq!(s.visible().len(), 1); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("keyword.rename", &json!({"from": "cat", "to": "dog"})).unwrap(); + let r = s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(r["enabled"], json!(true)); + assert_eq!(s.filter.keyword.as_deref(), Some("dog"), "the put-aside filter follows the rename"); + assert_eq!(s.visible().len(), 1); +} diff --git a/crates/engine/src/cmd/library/tests_rated_out.rs b/crates/engine/src/cmd/library/tests_rated_out.rs new file mode 100644 index 0000000000..49c36596bd --- /dev/null +++ b/crates/engine/src/cmd/library/tests_rated_out.rs @@ -0,0 +1,139 @@ +//! A rating, flag or label that takes the active photo out of the view (the filter bar, Picks) goes on from its place: +//! the photo that took it, not the view's first photo (#2312). +use lightcraft_catalog::{ColorLabel, Flag, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::{Result, Selection, Session}; + +/// 100 photos with one star each, in file-name order (photo `n` is the `n`th), the filter showing one-star photos. +fn one_star() -> Result<Session> { + let mut s = Session::new(); + for id in 1..=100 { + let mut photo = Photo::new( + PhotoId(id), + Source::File { path: format!("/lightcraft-rated-out/{id:03}.jpg") }, + &format!("{id:03}.jpg"), + "JPEG", + 40, + 30, + "2026-10-19", + ); + photo.rating = 1; + photo.flag = Flag::Pick; + photo.label = Some(ColorLabel::Red); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) })?; + } + s.execute("library.sort", &json!({"key": "fileName", "ascending": true}))?; + s.execute("library.filter", &json!({"rating": 1, "ratingOp": "exactly"}))?; + Ok(s) +} + +#[test] +fn a_star_taken_off_goes_on_to_the_next_photo() { + // Given photo 82 of 100 one-star photos, the filter showing one-star photos + let mut s = one_star().unwrap(); + s.execute("library.select", &json!({"ids": [82]})).unwrap(); + // When its star is taken off, Then it leaves the view and the photo after it is the one selected + s.execute("photo.rate", &json!({"rating": 0})).unwrap(); + assert!(!s.visible_cloned().contains(&PhotoId(82))); + assert_eq!(s.selection, Selection::single(PhotoId(83))); + // and the next photo is the one after that, not the first one of the view + s.execute("library.next", &json!({})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(84))); + // With `advance`, the photo that took its place is the next one: no photo is skipped + s.execute("photo.rate", &json!({"rating": 0, "advance": true})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(85))); + s.execute("photo.decreaseRating", &json!({"advance": true})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(86))); + // The last photo of the view hands on to the one before it + s.execute("library.select", &json!({"ids": [100]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 0, "advance": true})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(99))); + // A rating that keeps the photo in the view advances as before + s.execute("photo.rate", &json!({"rating": 1, "advance": true})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(99)), "the last photo of the view stays"); + s.execute("library.select", &json!({"ids": [10]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 1, "advance": true})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(11))); +} + +#[test] +fn flags_and_labels_that_leave_the_view_go_on_to_the_next_photo_too() { + for (filter, command, params) in [ + (json!({"flag": "pick"}), "photo.reject", json!({})), + (json!({"flag": "pick"}), "photo.flag", json!({"flag": "none"})), + (json!({"flag": "pick"}), "photo.cycleFlag", json!({})), + (json!({"flag": "pick"}), "photo.decreaseFlag", json!({})), + (json!({"label": "red"}), "photo.label", json!({"label": "none"})), + (json!({}), "photo.increaseRating", json!({})), + ] { + let mut s = one_star().unwrap(); + s.execute("library.filter", &filter).unwrap(); + s.execute("library.select", &json!({"ids": [40]})).unwrap(); + s.execute(command, &params).unwrap(); + assert!(!s.visible_cloned().contains(&PhotoId(40)), "{command} {params}"); + assert_eq!(s.selection, Selection::single(PhotoId(41)), "{command} {params}"); + } +} + +#[test] +fn several_photos_rated_out_go_on_after_the_active_one() { + let mut s = one_star().unwrap(); + // three selected, the middle one active: all leave, the photo after the active one is selected + s.execute("library.select", &json!({"ids": [20, 21, 22], "active": 21})).unwrap(); + s.execute("photo.rate", &json!({"rating": 0})).unwrap(); + assert_eq!(s.selection, Selection::single(PhotoId(23))); + // the active one leaves and another selected photo stays: that one is active + s.execute("photo.rate", &json!({"ids": [30], "rating": 3})).unwrap(); + s.execute("library.filter", &json!({"rating": 1, "ratingOp": "atLeast"})).unwrap(); + s.execute("library.select", &json!({"ids": [29, 30], "active": 29})).unwrap(); + s.execute("photo.decreaseRating", &json!({})).unwrap(); + assert_eq!(s.selection, Selection { ids: vec![PhotoId(30)], active: Some(PhotoId(30)) }); +} + +#[test] +fn named_photos_and_a_held_view_keep_the_selection() { + // Photos named by `ids` leave the selection to the caller (Compare and Survey keep the photo they show) + let mut s = one_star().unwrap(); + s.execute("library.select", &json!({"ids": [5, 6], "active": 6})).unwrap(); + s.execute("photo.rate", &json!({"ids": [6], "rating": 0})).unwrap(); + assert_eq!(s.selection, Selection { ids: vec![PhotoId(5), PhotoId(6)], active: Some(PhotoId(6)) }); + // A held view keeps the photo, so the selection stays with it + let mut s = one_star().unwrap(); + s.execute("library.holdView", &json!({"on": true})).unwrap(); + // (what the grid shows is what is held) + assert_eq!(s.visible_cloned().len(), 100); + s.execute("library.select", &json!({"ids": [7]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 0})).unwrap(); + assert!(s.visible_cloned().contains(&PhotoId(7))); + assert_eq!(s.selection, Selection::single(PhotoId(7))); + s.execute("photo.rate", &json!({"rating": 0, "advance": true})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(8))); +} + +/// A slider drag still open when a rating takes the photo out of the view, or when the photo is +/// deleted, ends as its own undo step before that change, as moving to the next photo does: undo +/// brings the rating or the photo back first, then the edit. Before, the move left the drag open +/// with no undo step (CodeRabbit on #2689). +#[test] +fn an_open_edit_ends_before_the_selection_moves_on() { + let exposure = |s: &Session, id| s.develop_of(PhotoId(id)).map(|d| d.light.exposure); + for (command, params) in [("photo.rate", json!({"rating": 0})), ("photo.delete", json!({})), ("photo.deletePermanently", json!({}))] { + let mut s = one_star().unwrap(); + s.execute("library.select", &json!({"ids": [82]})).unwrap(); + s.execute("develop.beginInteraction", &json!({"label": "Exposure"})).unwrap(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.5})).unwrap(); + s.execute(command, &params).unwrap(); + assert_eq!(s.active(), Some(PhotoId(83)), "{command}"); + assert!(s.interaction.is_none(), "{command}: the drag ended with the move"); + if command != "photo.deletePermanently" { + assert_eq!(exposure(&s, 82), Some(1.5), "{command}"); + } + // undo: the rating or the photo comes back first, with the edit; then the edit goes + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.visible_cloned().contains(&PhotoId(82)), "{command}: back in the view"); + assert_eq!(exposure(&s, 82), Some(1.5), "{command}: with its edit"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(exposure(&s, 82), Some(0.0), "{command}"); + } +} diff --git a/crates/engine/src/cmd/library/tests_source_album_filter.rs b/crates/engine/src/cmd/library/tests_source_album_filter.rs new file mode 100644 index 0000000000..599ffdeb39 --- /dev/null +++ b/crates/engine/src/cmd/library/tests_source_album_filter.rs @@ -0,0 +1,61 @@ +//! `library.source` with an album while the filter holds an album: the album shown wins. +use lightcraft_catalog::{Flag, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::{Result, Selection, Session}; + +/// Photos 1 to 3 (rated 5, 5 and 2). Album X holds photo 1 and album A holds photo 3. +fn session_with_two_albums() -> Result<(Session, u64, u64)> { + let mut s = Session::new(); + for (id, rating) in [(1, 5), (2, 5), (3, 2)] { + let mut photo = Photo::new( + PhotoId(id), + Source::File { path: format!("/lightcraft-source-album/{id}.jpg") }, + &format!("{id}.jpg"), + "JPEG", + 40, + 30, + "2026-10-23", + ); + photo.rating = rating; + photo.flag = Flag::None; + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) })?; + } + let mut make = |name: &str, id: u64| { + s.selection = Selection { ids: vec![PhotoId(id)], active: None }; + s.execute("album.create", &json!({"name": name, "addSelected": true})).unwrap()["id"].as_u64().unwrap() + }; + let (x, a) = (make("X", 1), make("A", 3)); + Ok((s, x, a)) +} + +#[test] +fn showing_an_album_drops_the_album_the_filter_held() { + let (mut s, x, a) = session_with_two_albums().unwrap(); + s.execute("library.filter", &json!({"album": x, "rating": 4})).unwrap(); + assert_eq!(s.visible().len(), 1, "the album narrows the grid, or the hidden album would not matter"); + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + assert_eq!(s.filter.album, None, "one album at a time: the one shown wins, as for a library folder"); + assert_eq!(s.filter.rating, 4, "the rest of the filter stays"); + // the old album must not narrow the next source, with no chip to show it + s.execute("library.source", &json!({"kind": "all"})).unwrap(); + assert_eq!(s.visible().len(), 2, "photos 1 and 2 have four stars or more"); +} + +#[test] +fn the_album_filter_stays_while_the_source_is_not_an_album() { + let (mut s, x, _) = session_with_two_albums().unwrap(); + s.execute("library.filter", &json!({"album": x})).unwrap(); + s.execute("library.source", &json!({"kind": "picks"})).unwrap(); + s.execute("library.source", &json!({"kind": "all"})).unwrap(); + assert_eq!(s.filter.album.map(|a| a.0), Some(x)); + assert_eq!(s.visible().len(), 1); +} + +#[test] +fn a_refused_album_source_leaves_the_filter_alone() { + let (mut s, x, _) = session_with_two_albums().unwrap(); + s.execute("library.filter", &json!({"album": x})).unwrap(); + assert!(s.execute("library.source", &json!({"kind": "album", "id": 9999})).is_err()); + assert_eq!(s.filter.album.map(|a| a.0), Some(x)); +} diff --git a/crates/engine/src/cmd/manage.rs b/crates/engine/src/cmd/manage.rs index 339b20b905..9b1f7e9f74 100644 --- a/crates/engine/src/cmd/manage.rs +++ b/crates/engine/src/cmd/manage.rs @@ -183,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> { "Edit Capture Time", [], None, - "{ids?, time?: `2026-09-30T14:05:00` (the active photo gets it, the others shift by the same amount), each?: bool (every photo gets `time`), shift?: seconds, hours?: time-zone shift in hours} → {changed, captured: [..]}", + "{ids?, time?: `2026-09-30T14:05:00` (the active photo gets it, the others shift by the same amount), each?: bool (every photo gets `time`), shift?: seconds, hours?: time-zone shift in hours} → {changed, captured: [..], unreadable: photos skipped because their capture time can't be read}", has_selection, |s, p| { use lightcraft_catalog::dates::{iso_seconds, normalize_iso, shift_iso}; @@ -213,12 +213,25 @@ pub fn specs() -> Vec<CommandSpec> { let from = normalize_iso(anchor_date.trim().get(..10).unwrap_or("")) .and_then(|_| iso_seconds(&anchor_date)) .ok_or_else(|| bad(c, "the photo's date doesn't parse"))?; - delta += iso_seconds(&t).unwrap_or(from) - from; + // the others move by the anchor's change, so it must read in full, not just + // its leading digits (a Lightroom catalog's capture time is copied verbatim); + // alone, it simply gets the time, which repairs it + if shift_iso(&anchor_date, 0).is_some() { + delta += iso_seconds(&t).unwrap_or(from) - from; + } else if targets.len() == 1 { + each = Some(t); + } else { + return Err(bad( + c, + "the active photo's capture time can't be read, so the other photos can't move by the same amount; set its time with it selected alone", + )); + } } } let mut ops = Vec::new(); let mut out = Vec::new(); let mut out_of_range = 0usize; + let mut unreadable = 0usize; for id in &targets { let from = match &each { Some(t) => t.clone(), @@ -226,9 +239,11 @@ pub fn specs() -> Vec<CommandSpec> { }; let Some(new) = shift_iso(&from, delta) else { // a date that reads but would leave years 0000–9999 is refused below; one - // that doesn't read is skipped, as before - if iso_seconds(&from).is_some() { + // that doesn't read is skipped and counted + if shift_iso(&from, 0).is_some() { out_of_range += 1; + } else { + unreadable += 1; } continue; }; @@ -244,7 +259,7 @@ pub fn specs() -> Vec<CommandSpec> { if n > 0 { s.commit("Edit Capture Time", Op::Batch { ops })?; } - Ok(json!({"changed": n, "captured": out})) + Ok(json!({"changed": n, "captured": out, "unreadable": unreadable})) } ), cmd!( diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index dc403df9b1..2fd44d5665 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -8,6 +8,18 @@ use super::{CommandSpec, bad, bool_or, cmd, f64_or, has_active, ok, point, str_p use crate::segment::{Click, MAX_CLICKS}; use crate::{Result, Session}; +/// A colour-range mask compares every pixel against every sample, so render and export cost is +/// pixels x samples. The interactive sampler stops at 5; automation (`mask.add`/`mask.update`) +/// passed its `samples` array straight through, so a few hundred samples on a large render hung. +const MAX_COLOR_RANGE_SAMPLES: usize = 64; + +/// Caps a colour-range shape's sample list at [`MAX_COLOR_RANGE_SAMPLES`] (render cost is pixels x samples). +fn cap_color_range_samples(shape: &mut MaskShape) { + if let MaskShape::ColorRange { samples, .. } = shape { + samples.truncate(MAX_COLOR_RANGE_SAMPLES); + } +} + fn shape_from(kind: &str, p: &Value, c: &str) -> Result<MaskShape> { Ok(match kind { "brush" => MaskShape::Brush { strokes: vec![] }, @@ -35,7 +47,12 @@ fn shape_from(kind: &str, p: &Value, c: &str) -> Result<MaskShape> { let samples: Vec<[f64; 3]> = p .get("samples") .and_then(Value::as_array) - .map(|a| a.iter().filter_map(|s| Some([s.get(0)?.as_f64()?, s.get(1)?.as_f64()?, s.get(2)?.as_f64()?])).collect()) + .map(|a| { + a.iter() + .filter_map(|s| Some([s.get(0)?.as_f64()?, s.get(1)?.as_f64()?, s.get(2)?.as_f64()?])) + .take(MAX_COLOR_RANGE_SAMPLES) + .collect() + }) .unwrap_or_default(); MaskShape::ColorRange { samples, refine: f64_or(p, "refine", 50.0) } } @@ -381,8 +398,9 @@ pub fn specs() -> Vec<CommandSpec> { } ), cmd!("mask.update", "Update Mask Shape", [], None, "{id?, component?: index (0), shape: MaskShape JSON}", has_active, |s, p| { - let shape: MaskShape = + let mut shape: MaskShape = serde_json::from_value(p.get("shape").cloned().unwrap_or_default()).map_err(|e| bad("mask.update", e.to_string()))?; + cap_color_range_samples(&mut shape); let comp = optional_index(p, "component", "mask.update")?.unwrap_or(0); let mid = mask_id(p, s.active_mask, "mask.update")?; masks_edit(s, "mask.update", "Edit Mask", |masks, _| { @@ -1123,3 +1141,30 @@ fn pressure_list(v: Option<&Value>, points: usize) -> Result<Vec<f32>> { .collect::<Option<Vec<f32>>>() .ok_or_else(|| bad("mask.brushStroke", "pressure must be a list of numbers 0..1")) } + +#[cfg(test)] +mod tests_color_range { + use super::*; + + /// Automation (`mask.add`/`mask.update`) used to take any number of colour-range samples; render + /// cost is pixels x samples, so a few hundred hung a large render. The list is now capped. + #[test] + fn color_range_samples_are_capped() { + let samples: Vec<Value> = (0..1000).map(|i| json!([i as f64 / 1000.0, 0.1, 0.2])).collect(); + let shape = shape_from("colorRange", &json!({ "samples": samples }), "mask.add").unwrap(); + let MaskShape::ColorRange { samples, .. } = shape else { panic!("expected ColorRange") }; + assert_eq!(samples.len(), MAX_COLOR_RANGE_SAMPLES); + // A reasonable request is unchanged. + let few = shape_from("colorRange", &json!({ "samples": [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]] }), "mask.add").unwrap(); + let MaskShape::ColorRange { samples, .. } = few else { panic!() }; + assert_eq!(samples.len(), 2); + // mask.update deserializes the shape directly; it is capped the same way. + let mut shape = shape_from("colorRange", &json!({ "samples": [[0.1, 0.2, 0.3]] }), "mask.add").unwrap(); + if let MaskShape::ColorRange { samples, .. } = &mut shape { + samples.resize(1000, samples[0]); + } + cap_color_range_samples(&mut shape); + let MaskShape::ColorRange { samples, .. } = shape else { panic!() }; + assert_eq!(samples.len(), MAX_COLOR_RANGE_SAMPLES); + } +} diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 1bff30d2b5..c06997eefb 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -90,9 +90,77 @@ fn stored_hash(p: &Photo) -> Option<&str> { p.content_hash.as_deref().map(|h| h.split(':').next().unwrap_or(h)).filter(|h| !h.is_empty()) } -/// The content hash of the file at `path` (as import computes it), if it can be read. +/// The content hash of the file at `path` (as import computes it), if it can be read. Read in +/// pieces: the file is whatever is on the disk, of any size. fn file_hash(path: &str) -> Option<String> { - std::fs::read(path).ok().map(|b| lightcraft_preview::hash_bytes(&b).to_string()) + hash_reader(std::fs::File::open(path).ok()?) +} + +/// The content hash of what `r` gives, read in pieces (the hash import computes of the whole). +fn hash_reader(mut r: impl std::io::Read) -> Option<String> { + let mut hasher = lightcraft_preview::Hasher128::new(); + let mut piece = vec![0u8; 1 << 16]; + loop { + match r.read(&mut piece) { + Ok(0) => return Some(hasher.finish().to_string()), + Ok(n) => { + hasher.update(piece.get(..n)?); + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => return None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A reader that gives its bytes a few at a time, and an interruption in between. + struct Trickle<'a>(&'a [u8], bool); + + impl std::io::Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { + self.1 = !self.1; + if self.1 { + return Err(std::io::ErrorKind::Interrupted.into()); + } + let n = self.0.len().min(buf.len()).min(7); + buf[..n].copy_from_slice(&self.0[..n]); + self.0 = &self.0[n..]; + Ok(n) + } + } + + #[test] + fn a_hash_read_in_pieces_is_the_hash_of_the_whole() { + // longer than one piece, so the read loop runs more than once + let bytes: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect(); + let whole = lightcraft_preview::hash_bytes(&bytes).to_string(); + assert_eq!(hash_reader(bytes.as_slice()).as_deref(), Some(whole.as_str())); + assert_eq!(hash_reader(Trickle(&bytes[..1000], false)).as_deref(), Some(lightcraft_preview::hash_bytes(&bytes[..1000]).to_string().as_str())); + assert_eq!(hash_reader(std::io::empty()).as_deref(), Some(lightcraft_preview::hash_bytes(&[]).to_string().as_str())); + } + + /// A scratch folder that goes away with the test, however it ends. + struct Scratch(std::path::PathBuf); + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn a_file_hash_is_the_import_hash_and_a_missing_file_has_none() { + let dir = Scratch(std::env::temp_dir().join(format!("lc-file-hash-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir_all(&dir.0).unwrap(); + let f = dir.0.join("a.bin"); + std::fs::write(&f, b"pixels").unwrap(); + assert_eq!(file_hash(f.to_str().unwrap()), Some(lightcraft_preview::hash_bytes(b"pixels").to_string())); + assert_eq!(file_hash(dir.0.join("nope").to_str().unwrap()), None); + } } /// An in-scope photo ([`checked_path`]) as Find Missing Photos sees it: its file, the size and @@ -197,13 +265,24 @@ impl FindPlan { } } +/// How Find Missing compares file names: the part after the last `/` or `\`, in lower case. A +/// library made on Windows keeps Windows paths, whose `\` isn't a separator to `Path` on macOS or +/// Linux. Files on disk are named by the same rule, so a macOS or Linux file name that holds a +/// `\` (`a\b.jpg`) still meets its photo, and a `b.jpg` beside it makes that match ambiguous +/// rather than a guess. With no `a\b.jpg` there, such a photo may be found as `b.jpg`, if the +/// size on record agrees. +fn name_key(path: &str) -> String { + path.rsplit(['/', '\\']).next().unwrap_or_default().to_lowercase() +} + /// The file-system half of Find Missing Photos: which `candidates` are gone, and which file in /// `folder` (recursively) is each one's. Touches only the disk — never the session — so the app /// runs it on a worker thread (walking a big folder on a network share and hashing look-alikes /// takes a while) and relinks the result with `library.findMissing {found, missing, ambiguous}`. /// /// Matching, per photo: -/// 1. a file with the same name (any letter case), the same size and the same content hash; +/// 1. a file with the same name ([`name_key`]: any letter case), the same size and the same +/// content hash; /// 2. renamed: a file of the same size with the same content hash (only same-size files are /// read, so this stays cheap); /// 3. without a hash to confirm (or the file was edited in place): the one file with the same @@ -228,8 +307,9 @@ pub fn plan_find_missing(candidates: &[FindCandidate], folder: &str) -> std::res let mut by_name: HashMap<String, Vec<String>> = HashMap::new(); let files: Vec<String> = crate::import::expand(&[folder.to_string()], None).into_iter().filter(|f| !in_use.contains(f.as_str())).collect(); for f in &files { - if let Some(n) = Path::new(f).file_name() { - by_name.entry(n.to_string_lossy().to_lowercase()).or_default().push(f.clone()); + let name = name_key(f); + if !name.is_empty() { + by_name.entry(name).or_default().push(f.clone()); } } let mut by_size: Option<HashMap<u64, Vec<String>>> = None; @@ -239,7 +319,7 @@ pub fn plan_find_missing(candidates: &[FindCandidate], folder: &str) -> std::res let mut used: HashSet<String> = HashSet::new(); let mut plan = FindPlan::default(); for c in &lost { - let name = Path::new(&c.path).file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default(); + let name = name_key(&c.path); let size = c.size; let hash = c.hash.as_deref(); let named: Vec<&String> = by_name diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 26f5d9bc45..1390ca1677 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -8,12 +8,12 @@ //! * `print.get`, `print.set {layout?, image?, page?, guides?, job?}`, `print.reset` //! * `print.cell.add|move|resize|delete|stack|photo|page`, `print.layout.autoLayout|newPage|clear` //! * `print.exportPdf {path, ids?}` -//! * `print.template.list|save|apply|delete` +//! * `print.template.list|save|apply|delete`, `print.template.export|import` (`.lcprint` files) use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, f64_req}; use crate::print::layout::{Layout, MAX_PAGES, Rect, Snap, Stack, paper_names, paper_size}; -use crate::print::template::{MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name}; +use crate::print::template::{FILE_EXT, MAX_FILE, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name, unique_name}; use crate::{Result, Session}; fn rect_json(r: &Rect) -> Value { @@ -277,10 +277,21 @@ fn template_name(p: &Value, id: &str) -> Result<String> { clean_name(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing `name`"))?).map_err(|e| bad(id, e)) } +/// Save the preferences after a change to the templates; if that fails, the templates go back to +/// `before`, so the list matches what is saved and a retry does the same thing. +fn save_templates(s: &mut Session, before: Vec<PrintTemplate>) -> Result<()> { + if let Err(e) = s.save_prefs() { + s.print_templates = before; + return Err(e); + } + Ok(()) +} + fn template_save(s: &mut Session, p: &Value) -> Result<Value> { const ID: &str = "print.template.save"; let name = template_name(p, ID)?; let t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?; + let before = s.print_templates.clone(); match s.print_templates.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) { Some(x) => *x = t, None => { @@ -290,7 +301,7 @@ fn template_save(s: &mut Session, p: &Value) -> Result<Value> { s.print_templates.push(t); } } - s.save_prefs()?; + save_templates(s, before)?; Ok(template_list(s)) } @@ -309,15 +320,66 @@ fn template_apply(s: &mut Session, p: &Value) -> Result<Value> { fn template_delete(s: &mut Session, p: &Value) -> Result<Value> { const ID: &str = "print.template.delete"; let name = template_name(p, ID)?; - let before = s.print_templates.len(); + let before = s.print_templates.clone(); s.print_templates.retain(|x| !x.name.eq_ignore_ascii_case(&name)); - if s.print_templates.len() == before { + if s.print_templates.len() == before.len() { return Err(bad(ID, format!("no print template `{name}`"))); } - s.save_prefs()?; + save_templates(s, before)?; Ok(template_list(s)) } +fn template_path<'a>(p: &'a Value, id: &str) -> Result<&'a str> { + p.get("path").and_then(Value::as_str).map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(id, "missing `path`")) +} + +fn template_export(s: &mut Session, p: &Value) -> Result<Value> { + const ID: &str = "print.template.export"; + let name = template_name(p, ID)?; + let mut path = std::path::PathBuf::from(template_path(p, ID)?); + if path.extension().is_none() { + path.set_extension(FILE_EXT); + } + let t = s + .print_templates + .iter() + .find(|x| x.name.eq_ignore_ascii_case(&name)) + .ok_or_else(|| bad(ID, format!("no print template `{name}` (see print.template.list)")))?; + let bytes = serde_json::to_vec_pretty(&t.to_file()).map_err(|e| crate::EngineError::Other(e.to_string()))?; + let name = t.name.clone(); + let target = path.to_string_lossy(); + s.check_write_target(&target).map_err(|e| bad(ID, e))?; + crate::export::write_file(&target, &bytes).map_err(|e| bad(ID, e))?; + Ok(json!({"name": name, "path": target})) +} + +fn template_import(s: &mut Session, p: &Value) -> Result<Value> { + const ID: &str = "print.template.import"; + let path = std::path::Path::new(template_path(p, ID)?); + let meta = std::fs::metadata(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; + if !meta.is_file() { + return Err(bad(ID, format!("{}: not a file", path.display()))); + } + if meta.len() > MAX_FILE { + return Err(bad(ID, format!("{}: {} bytes is too large for a print template (at most {} KB)", path.display(), meta.len(), MAX_FILE / 1024))); + } + let bytes = std::fs::read(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; + let mut t = PrintTemplate::from_file(&bytes).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; + if s.print_templates.len() >= MAX_TEMPLATES { + return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first"))); + } + let name = unique_name(&t.name, &s.print_templates); + let renamed = name != t.name; + t.name = name.clone(); + let before = s.print_templates.clone(); + s.print_templates.push(t); + save_templates(s, before)?; + let mut out = template_list(s); + out["name"] = json!(name); + out["renamed"] = json!(renamed); + Ok(out) +} + pub fn specs() -> Vec<CommandSpec> { vec![ cmd!(query "print.get", "Print Settings", [], None, @@ -349,5 +411,11 @@ pub fn specs() -> Vec<CommandSpec> { always, template_save), cmd!(query "print.template.apply", "Apply Print Template", [], None, "{name} → print.get", always, template_apply), cmd!(query "print.template.delete", "Delete Print Template", [], None, "{name} → print.template.list", always, template_delete), + cmd!(query "print.template.export", "Export Print Template", [], None, + "{name, path}: writes the template as a .lcprint JSON file ({format, version, name, settings}; `.lcprint` is added when the path has no extension); replaces an existing file, never an original → {name, path}", + always, template_export), + cmd!(query "print.template.import", "Import Print Template", [], None, + "{path: a .lcprint file (at most 256 KB)}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}", + always, template_import), ] } diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index dfbf4bfc55..a3926bc514 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -1,6 +1,8 @@ //! Read-only queries (not journaled): catalog, photos, develop state, controls, presets, albums. -use lightcraft_catalog::{Album, Photo, PhotoId}; +use std::collections::HashMap; + +use lightcraft_catalog::{Album, AlbumId, Photo, PhotoId}; use lightcraft_develop::{CONTROLS, controls}; use serde_json::{Value, json}; @@ -36,9 +38,9 @@ pub fn photo_summary(p: &Photo) -> Value { /// instead of overflowing the stack. const MAX_ALBUM_DEPTH: usize = 64; -fn album_json(a: &Album, all: &[Album], cat: &lightcraft_catalog::Catalog, depth: usize) -> Value { +fn album_json(a: &Album, all: &[Album], counts: &HashMap<AlbumId, usize>, cat: &lightcraft_catalog::Catalog, depth: usize) -> Value { let children: Vec<Value> = if depth < MAX_ALBUM_DEPTH { - all.iter().filter(|c| c.parent == Some(a.id)).map(|c| album_json(c, all, cat, depth + 1)).collect() + all.iter().filter(|c| c.parent == Some(a.id)).map(|c| album_json(c, all, counts, cat, depth + 1)).collect() } else { Vec::new() }; @@ -46,7 +48,7 @@ fn album_json(a: &Album, all: &[Album], cat: &lightcraft_catalog::Catalog, depth "id": a.id.0, "name": a.name, "folder": a.folder, - "count": cat.album_count(a.id), + "count": counts.get(&a.id).copied().unwrap_or(0), "cover": a.cover.map(|c| c.0), "children": children, }); @@ -152,7 +154,9 @@ pub fn specs() -> Vec<CommandSpec> { }), cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| { let all: Vec<Album> = s.catalog.albums().cloned().collect(); - Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, &s.catalog, 0)).collect())) + // every album counted in one pass, so a smart album tested by others is worked out once + let counts = lightcraft_catalog::tally::AlbumTally::of(&s.catalog); + Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, counts.counts(), &s.catalog, 0)).collect())) }), cmd!(query "photo.inspect", "Inspect Photo", [], None, "{id?}", always, |s, p| { let id = photo_arg(s, p, "photo.inspect")?; diff --git a/crates/engine/src/cmd/slideshow.rs b/crates/engine/src/cmd/slideshow.rs index 33ff76ec0f..191cee953f 100644 --- a/crates/engine/src/cmd/slideshow.rs +++ b/crates/engine/src/cmd/slideshow.rs @@ -379,7 +379,7 @@ pub fn specs() -> Vec<CommandSpec> { "Slideshow Playback Settings", [], None, - "{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews}", + "{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due), manual?: bool (manual slideshow: a slide stays up until ← or → changes it)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual}", always, playback ), diff --git a/crates/engine/src/demo.rs b/crates/engine/src/demo.rs index 431eec7630..38a42fe952 100644 --- a/crates/engine/src/demo.rs +++ b/crates/engine/src/demo.rs @@ -31,7 +31,7 @@ pub fn load(s: &mut Session) { ..Default::default() }; // one demo photo carries a camera focus point (as a Sony raw would), on the bloom's centre, so - // View ▸ Show Focus Point and Zoom to Focus Point can be tried without a camera file + // View ▸ Focus Point and Zoom to Focus Point can be tried without a camera file if sc.name == "Cosmos bloom" { p.meta.focus = Some(lightcraft_meta::FocusPoint { rect: lightcraft_geom::Rect { x0: 0.42, y0: 0.433, x1: 0.50, y1: 0.487 }, diff --git a/crates/engine/src/doc_path.rs b/crates/engine/src/doc_path.rs index c2b0e9f690..d3f455b81c 100644 --- a/crates/engine/src/doc_path.rs +++ b/crates/engine/src/doc_path.rs @@ -38,13 +38,13 @@ impl std::error::Error for NotFollowed {} /// was opened from. pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, NotFollowed> { let document = document.map(|d| if d.is_relative() { std::path::absolute(d).unwrap_or_else(|_| d.to_path_buf()) } else { d.to_path_buf() }); - let path = craft_docpath::resolve(stored, document.as_deref()).map_err(NotFollowed::Refused)?; - // A path that is still relative would be taken from the working directory, which the - // document does not choose. - if path.is_relative() { - return Err(NotFollowed::NotHere); + match craft_docpath::resolve_absolute(stored, document.as_deref()) { + Ok(path) => Ok(path), + // A usable path that is not absolute here: a Windows path on macOS or Linux, or a + // relative path with no document folder to take it from. + Err(Refused::Invalid) if craft_docpath::resolve(stored, document.as_deref()).is_ok() => Err(NotFollowed::NotHere), + Err(r) => Err(NotFollowed::Refused(r)), } - Ok(path) } #[cfg(test)] @@ -59,5 +59,12 @@ mod tests { assert_eq!(resolve(r"\\192.0.2.1\share\x.jpg", Some(&doc)), Err(NotFollowed::Refused(Refused::Network))); assert_eq!(resolve("file://192.0.2.1/s/x.jpg", Some(&doc)), Err(NotFollowed::Refused(Refused::Network))); assert_eq!(resolve(r"\\.\COM1", Some(&doc)), Err(NotFollowed::Refused(Refused::Device))); + #[cfg(windows)] + assert_eq!(resolve("Photos/2024:05/a.jpg", Some(&doc)), Err(NotFollowed::Refused(Refused::Invalid))); + #[cfg(not(windows))] + assert_eq!(resolve(r"C:\Photos\a.jpg", Some(&doc)), Err(NotFollowed::NotHere)); + let gvfs = Path::new("/run/user/1000/gvfs/smb-share:server=tokyo,share=photos/catalog.lrcat"); + #[cfg(not(windows))] + assert_eq!(resolve("a.jpg", Some(gvfs)), Ok(gvfs.with_file_name("a.jpg"))); } } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index bfeade59cf..236387b4d3 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -501,11 +501,12 @@ pub(crate) fn watermark_logo(path: &str) -> Option<std::sync::Arc<Rgba8>> { } /// A graphic file (a PNG with transparency, typically) as 8-bit sRGB with its alpha: the -/// watermark logo, the loupe's layout image. The error says why it couldn't be read or decoded. +/// watermark logo, the loupe's layout image. Applies EXIF orientation before either consumer sizes it. +/// The error says why it couldn't be read or decoded. pub fn read_graphic(path: &str) -> Result<Rgba8, String> { let bytes = std::fs::read(path).map_err(|e| format!("can't read {path}: {e}"))?; let decoded = lightcraft_codecs::decode(&bytes, Default::default()).map_err(|e| format!("can't decode {path}: {e}"))?; - Ok(decoded.to_srgb8()) + Ok(decoded.to_srgb8().into_oriented(lightcraft_geom::Orientation::from_exif(decoded.orientation))) } /// The graphic watermark: scaled (premultiplied, so transparent edges stay clean) to @@ -518,20 +519,27 @@ fn logo_coverage(width: usize, height: usize, wm: &Watermark, mut blend_px: impl if width == 0 || height == 0 || logo.width == 0 || logo.height == 0 { return; } - let lw = ((wm.image_width.clamp(0.01, 1.0) * width as f32).round() as usize).clamp(1, width); - let lh = ((lw as f32 * logo.height as f32 / logo.width as f32).round() as usize).clamp(1, height); + let turns = wm.quarter_turns(); + // Reserve the inset on anchored axes before fitting the turned box. Centered axes + // ignore insets, just as placement below does. One scale preserves the graphic's shape. + let short = width.min(height) as f32; + let (ix, iy) = (wm.inset_x.clamp(0.0, 0.4) * short, wm.inset_y.clamp(0.0, 0.4) * short); + use Anchor::*; + let available_w = width as f64 - if matches!(wm.anchor, Top | Center | Bottom) { 0.0 } else { ix as f64 }; + let available_h = height as f64 - if matches!(wm.anchor, Left | Center | Right) { 0.0 } else { iy as f64 }; + let (max_w, max_h) = if turns % 2 == 1 { (available_h, available_w) } else { (available_w, available_h) }; + let scale = + (wm.image_width.clamp(0.01, 1.0) as f64 * width as f64 / logo.width as f64).min(max_w / logo.width as f64).min(max_h / logo.height as f64); + let lw = (logo.width as f64 * scale).round().max(1.0) as usize; + let lh = (logo.height as f64 * scale).round().max(1.0) as usize; let pre: lightcraft_raster::Image<[f32; 4]> = lightcraft_raster::Image::from_fn(logo.width, logo.height, |x, y| { let p = logo.get(x, y); let a = p[3] as f32 / 255.0; [p[0] as f32 * a, p[1] as f32 * a, p[2] as f32 * a, a] }); let scaled = lightcraft_raster::resample::resize(&pre, lw, lh, lightcraft_raster::resample::Filter::Mitchell); - let short = width.min(height) as f32; - let (ix, iy) = (wm.inset_x.clamp(0.0, 0.4) * short, wm.inset_y.clamp(0.0, 0.4) * short); - let turns = wm.quarter_turns(); let (bw, bh) = if turns % 2 == 1 { (lh, lw) } else { (lw, lh) }; let (w, h, lwf, lhf) = (width as f32, height as f32, bw as f32, bh as f32); - use Anchor::*; let ox = match wm.anchor { TopLeft | Left | BottomLeft => ix, Top | Center | Bottom => (w - lwf) / 2.0, @@ -658,8 +666,8 @@ pub struct ExportOptions { /// format's default (TIFF 16, everything else 8). See [`ExportOptions::effective_depth`]. pub bit_depth: Option<u8>, /// HDR output for photos edited in HDR: JPEG as an ISO 21496-1 gain map JPEG (the SDR - /// rendition plus a gain map, so the file looks right everywhere; quality as set, `limit_kb` - /// not applied), AVIF as 10-bit Rec. 2020 PQ, PNG as 16-bit Rec. 2020 PQ (`cICP`; viewers + /// rendition plus a gain map, so the file looks right everywhere; `limit_kb` includes both + /// images and their metadata), AVIF as 10-bit Rec. 2020 PQ, PNG as 16-bit Rec. 2020 PQ (`cICP`; viewers /// without cICP support show it as sRGB, washed out), JPEG XL as 16-bit Rec. 2020 PQ, 32-bit float /// TIFF with the highlights above SDR white kept. Other formats, and photos without an HDR /// edit, are SDR. @@ -1392,29 +1400,7 @@ pub fn encode_with_metadata(img: &Rgba8, o: &ExportOptions, meta: Option<&Metada ExportFormat::Jpeg => { // 4:4:4 normally; 4:2:0 when targeting a file size (much smaller at equal visual quality). let sub = if o.limit_kb.is_some() { ChromaSubsampling::S420 } else { ChromaSubsampling::S444 }; - let jpeg = |q: u8| encode::encode_jpeg(&e, q, sub, &meta); - match o.limit_kb { - Some(kb) => { - let limit = kb as usize * 1024; - // Binary search for the highest quality that fits. - let (mut lo, mut hi) = (1u8, o.quality); - let mut best = None; - while lo <= hi { - let mid = lo + (hi - lo) / 2; - let b = jpeg(mid).map_err(|e| e.to_string())?; - if b.len() <= limit { - best = Some(b); - lo = mid + 1; - } else if mid == 1 { - break; - } else { - hi = mid - 1; - } - } - return best.ok_or_else(|| format!("cannot fit within {kb} KB")); - } - None => jpeg(o.quality), - } + return encode_jpeg_with_limit(o, |q| encode::encode_jpeg(&e, q, sub, &meta)); } ExportFormat::Png => encode::encode_png(&e, &meta), ExportFormat::Tiff => encode::encode_tiff(&e, o.tiff_compression, &meta), @@ -1428,6 +1414,27 @@ pub fn encode_with_metadata(img: &Rgba8, o: &ExportOptions, meta: Option<&Metada r.map_err(|e| e.to_string()) } +/// Apply the same file-size policy to ordinary JPEGs and complete HDR gain map JPEGs. +fn encode_jpeg_with_limit(o: &ExportOptions, jpeg: impl Fn(u8) -> lightcraft_codecs::Result<Vec<u8>>) -> Result<Vec<u8>, String> { + let Some(kb) = o.limit_kb else { return jpeg(o.quality).map_err(|e| e.to_string()) }; + let limit = u64::from(kb) * 1024; + let (mut lo, mut hi) = (1u8, o.quality.min(100)); + let mut best = None; + while lo <= hi { + let mid = lo + (hi - lo) / 2; + let b = jpeg(mid).map_err(|e| e.to_string())?; + if b.len() as u64 <= limit { + best = Some(b); + lo = mid + 1; + } else if mid == 1 { + break; + } else { + hi = mid - 1; + } + } + best.ok_or_else(|| format!("cannot fit within {kb} KB")) +} + /// Output sharpening and the watermark on an 8-bit render in `o.effective_space()`. fn finish_8bit(img: &Rgba8, o: &ExportOptions) -> Rgba8 { let mut img = img.clone(); @@ -1475,7 +1482,7 @@ pub fn encode_gain_map_jpeg(sdr: &Rgba8, hdr: &DeepImage, o: &ExportOptions, met let xmp = meta.map(|m| lightcraft_meta::write_xmp(m, None)); let em = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) }; let sub = if o.limit_kb.is_some() { ChromaSubsampling::S420 } else { ChromaSubsampling::S444 }; - gainmap::encode_jpeg(&EncodeImage::rgba8(&base), &map, &gm, o.quality, sub, &em).map_err(|e| e.to_string()) + encode_jpeg_with_limit(o, |q| gainmap::encode_jpeg(&EncodeImage::rgba8(&base), &map, &gm, q, sub, &em)) } /// The codecs' name of an output space (for its ICC profile). @@ -1827,10 +1834,14 @@ impl PreparedExport { }; let Some(dng) = dng else { // the file is copied byte for byte: refuse rather than leak a location it embeds - if remove_location && lightcraft_meta::extract(&bytes).gps.is_some() { - return Err(format!( - "{label}: can't remove the location from an original file that embeds GPS; export as JPEG, TIFF or DNG instead" - )); + if remove_location { + let metadata = lightcraft_meta::try_extract(&bytes) + .map_err(|e| format!("{label}: can't verify location metadata in this original file: {e}"))?; + if metadata.gps.is_some() { + return Err(format!( + "{label}: can't remove the location from an original file that embeds GPS; export as JPEG, TIFF or DNG instead" + )); + } } return Ok(Exported { file_name, @@ -2015,6 +2026,18 @@ pub fn write_file_durable(path: &str, bytes: &[u8]) -> Result<(), String> { write_with(path, bytes, true) } +/// Write `path` only when nothing exists there: the destination is prepared as a complete temp +/// file and published with create-new semantics, so a file that appears after a caller's check is +/// never replaced. Screenshots of an initially absent path use this instead of the overwriting +/// writer. +pub fn write_file_new(path: &str, bytes: &[u8]) -> Result<(), String> { + let p = std::path::Path::new(path); + if let Some(dir) = p.parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + lightcraft_catalog::safe_file::write_new(p, bytes).map_err(|e| format!("{path}: {e}")) +} + fn write_with(path: &str, bytes: &[u8], durable: bool) -> Result<(), String> { use lightcraft_catalog::safe_file::{write_atomic, write_atomic_nosync}; let p = std::path::Path::new(path); @@ -2425,6 +2448,139 @@ mod tests { assert!(b.len() <= kb as usize * 1024); } + #[test] + fn hdr_jpeg_size_limit_respected() { + let img = Rgba8::from_fn(256, 192, |x, y| { + let n = (x as u32).wrapping_mul(73856093) ^ (y as u32).wrapping_mul(19349663); + [n as u8, (n >> 8) as u8, (n >> 16) as u8, 255] + }); + let hdr = DeepImage { + width: img.width, + height: img.height, + space: OutputSpace::Srgb, + samples: DeepSamples::F32( + img.data.iter().flat_map(|p| p[..3].iter().map(|v| lightcraft_color::transfer::decode_srgb8(*v) * 4.0)).collect(), + ), + }; + let opts = ExportOptions { hdr: true, quality: 100, limit_kb: Some(u32::MAX), ..Default::default() }; + let full = encode_gain_map_jpeg(&img, &hdr, &opts, None).unwrap(); + let kb = (full.len() / 2048) as u32; + let limited = encode_gain_map_jpeg(&img, &hdr, &ExportOptions { limit_kb: Some(kb), ..opts.clone() }, None).unwrap(); + assert!(limited.len() <= kb as usize * 1024, "{} bytes exceeds {kb} KB", limited.len()); + let decoded = lightcraft_codecs::gainmap::read_jpeg(&limited).unwrap(); + assert!(decoded.meta.alternate_headroom > 1.0, "the gain map must survive size limiting"); + let impossible = encode_gain_map_jpeg(&img, &hdr, &ExportOptions { limit_kb: Some(1), ..opts }, None); + assert!(impossible.is_err_and(|e| e.contains("cannot fit within 1 KB"))); + } + + #[test] + fn graphic_watermark_honours_exif_orientation() { + let dir = std::env::temp_dir().join(format!("lc-wm-orientation-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let logo = Rgba8::from_fn(40, 20, |x, _| if x < 20 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }); + for orientation in [2, 6] { + let meta = Metadata { orientation: Some(lightcraft_geom::Orientation::from_exif(orientation)), ..Default::default() }; + let exif = lightcraft_meta::write_exif(&meta); + let bytes = lightcraft_codecs::encode_jpeg( + &EncodeImage::rgba8(&logo), + 100, + ChromaSubsampling::S444, + &EncodeMeta { exif: Some(&exif), ..Default::default() }, + ) + .unwrap(); + let path = dir.join(format!("oriented-{orientation}.jpg")); + std::fs::write(&path, bytes).unwrap(); + let wm = Watermark { + image: path.to_string_lossy().into(), + image_width: if orientation == 6 { 0.25 } else { 0.5 }, + opacity: 1.0, + inset_x: 0.0, + inset_y: 0.0, + ..Default::default() + }; + let mut img = Rgba8::from_fn(80, 80, |_, _| [0, 0, 0, 255]); + draw_watermark(&mut img, &wm); + if orientation == 6 { + assert!(img.get(70, 45)[0] > 240 && img.get(70, 75)[2] > 240, "EXIF 6: red above blue"); + } else { + assert!(img.get(45, 70)[2] > 240 && img.get(75, 70)[0] > 240, "EXIF 2: blue left of red"); + } + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn graphic_watermark_keeps_aspect_when_fitted_and_rotated() { + let dir = std::env::temp_dir().join(format!("lc-wm-aspect-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tall.png"); + let logo = Rgba8::from_fn(40, 160, |_, _| [255, 0, 0, 255]); + std::fs::write(&path, lightcraft_codecs::encode_png(&EncodeImage::rgba8(&logo), &EncodeMeta::default()).unwrap()).unwrap(); + for (rotation, expected) in [(0, (20, 80)), (90, (120, 30)), (180, (20, 80)), (270, (120, 30))] { + let wm = Watermark { + image: path.to_string_lossy().into(), + image_width: 0.5, + opacity: 1.0, + inset_x: 0.0, + inset_y: 0.0, + rotation, + ..Default::default() + }; + let mut img = Rgba8::from_fn(120, 80, |_, _| [0, 0, 0, 255]); + draw_watermark(&mut img, &wm); + let lit: Vec<_> = img.data.iter().enumerate().filter(|(_, p)| p[0] > 200).map(|(i, _)| (i % 120, i / 120)).collect(); + let bounds = ( + lit.iter().map(|p| p.0).max().unwrap() - lit.iter().map(|p| p.0).min().unwrap() + 1, + lit.iter().map(|p| p.1).max().unwrap() - lit.iter().map(|p| p.1).min().unwrap() + 1, + ); + assert_eq!(bounds, expected, "{rotation} degrees: fitting must preserve the logo's aspect ratio"); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn graphic_watermark_fit_preserves_anchor_insets() { + let dir = std::env::temp_dir().join(format!("lc-wm-insets-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tall.png"); + let logo = Rgba8::from_fn(40, 160, |_, _| [255, 0, 0, 255]); + std::fs::write(&path, lightcraft_codecs::encode_png(&EncodeImage::rgba8(&logo), &EncodeMeta::default()).unwrap()).unwrap(); + use Anchor::*; + for (anchor, rotation, expected) in [ + (BottomRight, 90, (0, 44, 111, 71)), + (TopLeft, 270, (8, 8, 119, 35)), + (Right, 90, (0, 26, 111, 53)), + (BottomRight, 0, (94, 0, 111, 71)), + (TopLeft, 180, (8, 8, 25, 79)), + (Bottom, 0, (51, 0, 68, 71)), + // Centered axes ignore their inset rather than shrinking the image unnecessarily. + (Center, 90, (0, 25, 119, 54)), + (Top, 90, (0, 8, 119, 37)), + ] { + let wm = Watermark { + image: path.to_string_lossy().into(), + image_width: 0.5, + opacity: 1.0, + inset_x: 0.1, + inset_y: 0.1, + rotation, + anchor, + ..Default::default() + }; + let mut img = Rgba8::from_fn(120, 80, |_, _| [0, 0, 0, 255]); + draw_watermark(&mut img, &wm); + let lit: Vec<_> = img.data.iter().enumerate().filter(|(_, p)| p[0] > 200).map(|(i, _)| (i % 120, i / 120)).collect(); + let bounds = ( + lit.iter().map(|p| p.0).min().unwrap(), + lit.iter().map(|p| p.1).min().unwrap(), + lit.iter().map(|p| p.0).max().unwrap(), + lit.iter().map(|p| p.1).max().unwrap(), + ); + assert_eq!(bounds, expected, "{anchor:?}, {rotation} degrees"); + } + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn sharpen_increases_edge_contrast() { let mut img = Rgba8::new(8, 8); diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 0670fb7635..82d4c57d60 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -1177,6 +1177,22 @@ pub(crate) mod tests { assert_eq!(super::meta_of(&m).0.keywords, ["travel|Italy|Rome", "beach"]); } + #[test] + fn psd_probe_reads_embedded_capture_time_gps_and_title() { + let capture = lightcraft_meta::DateTime::parse_iso("2023-05-14T14:40:39").unwrap(); + let metadata = lightcraft_meta::Metadata { + capture_time: Some(capture), + gps: Some(lightcraft_meta::Gps { latitude: 45.0, longitude: 7.0, altitude: None }), + title: Some("PSD metadata".into()), + ..Default::default() + }; + let bytes = crate::tests_xmp::synthetic_psd_with_metadata(&metadata); + let probe = probe_bytes("metadata.psd", &bytes).unwrap(); + assert_eq!(probe.captured.as_deref(), Some("2023-05-14T14:40:39")); + assert_eq!(probe.meta.gps, Some((45.0, 7.0))); + assert_eq!(probe.meta.title, "PSD metadata"); + } + use super::*; use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; @@ -2809,7 +2825,7 @@ pub(crate) mod tests { let _ = std::fs::remove_dir_all(&dir); } - /// A Sony ARW of `model`: a 64 × 48 uncompressed 14-bit CFA strip in a SubIFD (as `crates/raw/tests/vendor_robust.rs` + /// A Sony ARW of `model`: a 64 × 48 uncompressed 14-bit CFA strip in a SubIFD (as `crates/raw/tests/it/vendor_robust.rs` /// lays it out) whose IFD carries the full-frame 16–35 mm distortion table (tag 0x7037). fn sony_arw(model: &str) -> Vec<u8> { use lightcraft_tiff::tags::{self as t, photometric}; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index bc8c1c9629..bb81bd2407 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -36,7 +36,7 @@ use crate::media::ProbeInfo; /// This includes preview-only raws; the file probe decides whether sensor decoding is available. pub const EXTENSIONS: &[&str] = &[ "jpg", "jpeg", "png", "tif", "tiff", "webp", "dng", "cr2", "cr3", "nef", "nrw", "arw", "sr2", "srf", "raf", "orf", "rw2", "rwl", "raw", "pef", - "srw", "psd", "jxl", "gif", "bmp", + "srw", "psd", "psb", "jxl", "gif", "bmp", // Decoded when built with the codecs' `heif` feature; otherwise the import reports them as // failed with the reason ("HEIC/HEIF support isn't included in this build"). "heic", "heif", "avif", // no AV1 decoder yet: reported as failed, like a HEIC without the feature @@ -374,6 +374,42 @@ pub fn is_supported(path: &Path) -> bool { path.extension().is_some_and(|e| EXTENSIONS.contains(&e.to_string_lossy().to_lowercase().as_str())) } +/// The web file picker's accept list, derived from [`EXTENSIONS`]. Each extension +/// is listed in both cases: browsers' `accept` matching is case-insensitive per +/// spec, but some implementations (e.g. Windows/Edge) match case-sensitively and +/// rejected uppercase `.NEF` files, so a lowercase-only list silently hid raws +/// such as CR3, NRW, RAF, ORF, RW2, RWL, RAW, PEF and SRW from the picker. +/// +/// The picker only offers files this build can actually import: `.avif` has no +/// AV1 decoder in any build, and `.heic`/`.heif` decode only when the codecs' +/// `heif` feature is enabled ([`lightcraft_codecs::Format::Heif::can_decode`]). +/// [`EXTENSIONS`] itself stays complete — files on disk are still recognised, +/// and import reports them as failed, saying why. +pub fn accept_list() -> String { + let heif_decodable = lightcraft_codecs::Format::Heif.can_decode(); + let mut out = String::new(); + for &ext in EXTENSIONS { + // Skip extensions a web user could pick but this build could not import. + let pickable = match ext { + "avif" => false, + "heic" | "heif" => heif_decodable, + _ => true, + }; + if !pickable { + continue; + } + if !out.is_empty() { + out.push(','); + } + out.push('.'); + out.push_str(ext); + out.push(','); + out.push('.'); + out.push_str(&ext.to_uppercase()); + } + out +} + /// Expand files and folders (recursively) into supported files. `skip` (e.g. the library folder) /// is never descended into. Each folder's walk is bounded ([`crate::walk::Limits::default`]); a /// walk that stops at a bound is logged. @@ -1607,6 +1643,52 @@ mod tests_known; mod prepared_tests { use super::*; + /// Extensions the picker may offer: every one in [`EXTENSIONS`], minus the + /// files this build cannot import (see [`accept_list`]). + fn pickable_extensions() -> Vec<&'static str> { + let heif_decodable = lightcraft_codecs::Format::Heif.can_decode(); + EXTENSIONS + .iter() + .copied() + .filter(|ext| match *ext { + "avif" => false, + "heic" | "heif" => heif_decodable, + _ => true, + }) + .collect() + } + + #[test] + fn accept_list_covers_every_pickable_extension_in_both_cases() { + let list = accept_list(); + for ext in pickable_extensions() { + assert!(list.contains(&format!(".{ext}")), "lowercase .{ext} missing from accept list"); + assert!(list.contains(&format!(".{}", ext.to_uppercase())), "uppercase .{} missing from accept list", ext.to_uppercase()); + } + } + + /// The web picker must not offer files this build cannot import: `.avif` has + /// no AV1 decoder in any build, so it is never listed, in either case. + #[test] + fn accept_list_never_offers_avif() { + let list = accept_list(); + assert!(!list.contains(".avif"), "{list}"); + assert!(!list.contains(".AVIF"), "{list}"); + } + + /// `.heic`/`.heif` follow the codecs' `heif` feature: listed (in both cases) + /// only when this build can decode them; otherwise hidden, so a web user + /// cannot pick a file that would fail to import. + #[test] + fn accept_list_offers_heic_heif_only_when_decodable() { + let list = accept_list(); + let listed = lightcraft_codecs::Format::Heif.can_decode(); + for ext in ["heic", "heif"] { + assert_eq!(list.contains(&format!(".{ext}")), listed, "lowercase .{ext}"); + assert_eq!(list.contains(&format!(".{}", ext.to_uppercase())), listed, "uppercase .{ext}"); + } + } + #[test] fn revalidate_add_only_converts_matching_ready_item() { let mut s = Session::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 323ed90ef4..ff2b972c0a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -195,6 +195,31 @@ pub struct Interaction { /// The most photos an edit may touch for the view to follow it photo by photo; a larger edit is worked out whole. const MAX_FOLLOWED: usize = 256; +/// The established clock precision for relative-date views and sidebar counts. +fn clock_minute(now: &str) -> &str { + now.get(..16).unwrap_or(now) +} + +/// Whether a query can change membership without a catalog edit, including the smart albums it tests. +fn filter_depends_on_clock(filter: &Filter, catalog: &Catalog) -> bool { + if filter.depends_on_now() { + return true; + } + let mut pending = filter.albums_tested(); + let mut seen = std::collections::HashSet::new(); + while let Some(id) = pending.pop() { + if !seen.insert(id) { + continue; + } + let Some(smart) = catalog.album(id).and_then(|album| album.smart.as_deref()) else { continue }; + if smart.depends_on_now() { + return true; + } + pending.extend(smart.albums_tested()); + } + false +} + /// Source of [`Session::visible_shared`] generations (process-wide, so two sessions never share one). static VISIBLE_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); static LIBRARY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -207,12 +232,16 @@ pub struct Session { pub catalog: Catalog, pub source: LibrarySource, pub filter: Filter, + /// The filter `library.toggleFilters` put aside (Library > Enable Filters off); not persisted. + pub(crate) shelved_filter: Option<Filter>, pub sort: Sort, pub selection: Selection, /// The grid order for the current source/filter/sort (cached by catalog revision). /// Shared, so frontends can hold it across frames without copying ([`Session::visible_shared`]). visible: Arc<[PhotoId]>, visible_key: Option<(u64, String)>, + /// The minute used for a cached view whose rules depend on the session clock. + visible_clock_minute: Option<String>, /// A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop /// matching a smart album's rules, Picks or the filter bar leaves it where it is. Off: the photo goes at once. pub hold_view: bool, @@ -232,7 +261,7 @@ pub struct Session { /// is recomputed, so frontends can key their per-view caches on it instead of hashing the ids. visible_gen: u64, /// Photos in the current source with no filter on (cached like `visible`). - total: Option<((u64, String), usize)>, + total: Option<((u64, String), usize, Option<String>)>, pub undo: Vec<UndoEntry>, /// Undo steps committed in this session, ever (the history drops its oldest past 1000, so /// its length can't tell how many steps a command just made; see [`Session::commits`]). @@ -422,10 +451,12 @@ impl Session { catalog: Catalog::new(), source: LibrarySource::All, filter: Filter::default(), + shelved_filter: None, sort: Sort::default(), selection: Selection::default(), visible: Vec::new().into(), visible_key: None, + visible_clock_minute: None, hold_view: false, base: None, view_followed: 0, @@ -1027,6 +1058,11 @@ impl Session { // ---------------------------------------------------------------- library view + /// Library > Enable Filters is off: a filter is put aside (`library.toggleFilters`). + pub fn filters_off(&self) -> bool { + self.shelved_filter.is_some() + } + /// Photos shown in the grid/filmstrip for the current source, filter and sort. pub fn visible(&mut self) -> &[PhotoId] { let mut key = @@ -1042,12 +1078,20 @@ impl Session { }; let view = format!("{}|{rules}", key.1); if self.source == LibrarySource::Missing && self.media.availability.is_background() { - // the view fills in as the background checks find files gone - key.1.push_str(&format!("|{}", self.media.availability.generation())); + // the view fills in as the background checks find files gone (a file found there at + // its first check changes nothing it shows) + key.1.push_str(&format!("|{}", self.media.availability.gone_generation())); } - if self.visible_key.as_ref() != Some(&key) { - // "in the last N days" rules count back from the session's clock - lightcraft_catalog::rules::set_now(Some((self.clock)())); + let key_changed = self.visible_key.as_ref() != Some(&key); + // A time-dependent cache needs one clock read to test its minute stamp. A new view also + // needs one value for the query, even when its previous cached view did not use the clock. + let current_now = (key_changed || self.visible_clock_minute.is_some()).then(|| (self.clock)()); + let current_minute = current_now.as_deref().map(clock_minute); + let clock_changed = self.visible_clock_minute.as_deref().is_some_and(|cached| current_minute != Some(cached)); + if key_changed || clock_changed { + // Use this same value to evaluate relative rules and stamp the result. + let now = current_now.unwrap_or_else(|| (self.clock)()); + lightcraft_catalog::rules::set_now(Some(now.clone())); let f = self.view_filter(self.source, &self.filter); // A held view keeps the photos it shows that stopped matching what is asked of them (a smart album's // rules, a flag, the filter bar), as long as they are still where the view looks: in the library for @@ -1074,8 +1118,7 @@ impl Session { let whole = own_order || matches!(self.source, LibrarySource::RecentlyAdded | LibrarySource::Missing); // A view that asks about "the last N days" (itself, or through a smart album it looks into) changes // with the clock as well as with edits: a photo nobody touched can stop matching. It is asked whole. - let clocked = f.depends_on_now() - || (!f.albums_tested().is_empty() && self.catalog.albums().any(|al| al.smart.as_deref().is_some_and(Filter::depends_on_now))); + let clocked = filter_depends_on_clock(&f, &self.catalog); let base = self.base.take().filter(|(of, _, _)| *of == view); // A small edit to the same view: the photos it touched are taken out, asked about again, and put back // at their place in the order. The others neither stopped matching nor moved. @@ -1149,6 +1192,7 @@ impl Session { self.visible = visible.into(); self.visible_gen = VISIBLE_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); self.visible_key = Some(key); + self.visible_clock_minute = clocked.then(|| clock_minute(&now).to_owned()); } &self.visible } @@ -1181,12 +1225,20 @@ impl Session { /// view, so a list followed many times over is compared, not only one followed once. #[cfg(test)] pub(crate) fn visible_in_full(&mut self) -> Vec<PhotoId> { - let kept = (self.base.clone(), self.visible_key.clone(), self.visible.clone(), self.visible_gen, self.view_followed, self.view_worked_out); + let kept = ( + self.base.clone(), + self.visible_key.clone(), + self.visible_clock_minute.clone(), + self.visible.clone(), + self.visible_gen, + self.view_followed, + self.view_worked_out, + ); self.never_follow = true; self.visible_key = None; let whole = self.visible().to_vec(); self.never_follow = false; - (self.base, self.visible_key, self.visible, self.visible_gen, self.view_followed, self.view_worked_out) = kept; + (self.base, self.visible_key, self.visible_clock_minute, self.visible, self.visible_gen, self.view_followed, self.view_worked_out) = kept; whole } @@ -1214,7 +1266,15 @@ impl Session { } } let key = (self.catalog.revision, format!("{:?}|{:?}|{:?}", self.source, self.browse, self.library_folder)); - if self.total.as_ref().map(|t| &t.0) != Some(&key) { + let key_changed = self.total.as_ref().map(|total| &total.0) != Some(&key); + let cached_minute = self.total.as_ref().and_then(|total| total.2.as_deref()); + let current_now = cached_minute.map(|_| (self.clock)()); + let current_minute = current_now.as_deref().map(clock_minute); + let clock_changed = cached_minute.is_some_and(|cached| current_minute != Some(cached)); + if key_changed || clock_changed { + // The source count can be requested before `visible`; bind it to the session's clock itself. + let now = current_now.unwrap_or_else(|| (self.clock)()); + lightcraft_catalog::rules::set_now(Some(now.clone())); let mut f = self.source.to_filter(&Filter::default(), &self.catalog); if self.source == LibrarySource::Folder { let b = self.browse.clone().unwrap_or_default(); @@ -1226,7 +1286,8 @@ impl Session { } // (how many, not which: nothing to put in order) let n = self.catalog.count(&f); - self.total = Some((key, n)); + let clocked = filter_depends_on_clock(&f, &self.catalog); + self.total = Some((key, n, clocked.then(|| clock_minute(&now).to_owned()))); } self.total.as_ref().map(|t| t.1) } diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 292a9fb1e7..e76ef81691 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 69; +pub const RENDER_CACHE_VERSION: u64 = 70; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/crates/engine/src/originals.rs b/crates/engine/src/originals.rs index b3a140a2b9..890e98f812 100644 --- a/crates/engine/src/originals.rs +++ b/crates/engine/src/originals.rs @@ -6,17 +6,102 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; +#[cfg(not(any(unix, windows)))] +use std::time::SystemTime; use lightcraft_catalog::safe_file::same_file; use lightcraft_catalog::{Catalog, Source}; +/// The directory entry a screenshot is about to write, pinned at request admission. +/// +/// A later write must not replace a path that was absent when the request was admitted (for +/// example a photo imported while the capture was waiting), nor a destination that was replaced by +/// another file in the meantime. [`Session::revalidate_write_target`] checks this immediately +/// before the write, and an absent destination is then published with create-new semantics. +#[derive(Clone, Debug)] +pub struct WriteTarget { + path: String, + state: WriteTargetState, + /// The canonical parent folder at admission, when it existed: a retargeted parent symlink is a + /// different destination even when the file name is unchanged. + parent: Option<PathBuf>, +} + +#[derive(Clone, Debug)] +enum WriteTargetState { + /// The directory entry did not exist at admission. + Absent, + /// The directory entry existed; this is its identity (not its contents). + Existing(FileIdentity), +} + +/// Stable identity of a directory entry, from `symlink_metadata` (so replacing a symlink or a +/// hard link is a different entry). Unix uses device + inode; Windows uses the canonical path, +/// length and creation time; other platforms use a canonical/len/mtime fallback. +#[derive(Clone, Debug, PartialEq, Eq)] +struct FileIdentity { + #[cfg(unix)] + dev: u64, + #[cfg(unix)] + ino: u64, + #[cfg(windows)] + canonical: PathBuf, + #[cfg(windows)] + len: u64, + #[cfg(windows)] + created: u64, + #[cfg(not(any(unix, windows)))] + canonical: PathBuf, + #[cfg(not(any(unix, windows)))] + len: u64, + #[cfg(not(any(unix, windows)))] + modified: Option<SystemTime>, +} + +impl FileIdentity { + fn of(path: &Path, meta: &std::fs::Metadata) -> Self { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let _ = path; + Self { dev: meta.dev(), ino: meta.ino() } + } + #[cfg(windows)] + { + // The volume serial/file index metadata is still unstable; use stable metadata that + // changes when a different file replaces the entry, and keep the same in-place + // content edits (which do not change the creation time or length) overwritable. + use std::os::windows::fs::MetadataExt; + Self { canonical: std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()), len: meta.len(), created: meta.creation_time() } + } + #[cfg(not(any(unix, windows)))] + { + Self { canonical: std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()), len: meta.len(), modified: meta.modified().ok() } + } + } +} + +impl WriteTarget { + /// The destination path as the request named it. + pub fn path(&self) -> &str { + &self.path + } + + /// Was the directory entry absent at admission? Such a destination is published with + /// create-new semantics, never with the overwriting writer. + pub fn was_absent(&self) -> bool { + matches!(&self.state, WriteTargetState::Absent) + } +} + /// The library's originals and their sidecars, looked up by file name. #[derive(Debug, Default)] pub struct OriginalGuard { /// lower-case file name → (path on disk, what it is: "the original of IMG_1.CR3", …) by_name: HashMap<String, Vec<(PathBuf, String)>>, - /// The entries of `by_name` that are symlinks, found on the first check that needs them. - links: std::sync::OnceLock<Vec<(PathBuf, String)>>, + /// Every indexed entry, built on the first check whose target name did not match: a hard + /// link or symlink may name an original differently from the catalogued path. + others: std::sync::OnceLock<Vec<(PathBuf, String)>>, } impl OriginalGuard { @@ -34,7 +119,7 @@ impl OriginalGuard { /// Protect `path` (an original named `label`) and its sidecars (`IMG_1.xmp`, `IMG_1.CR3.xmp`). pub fn add(&mut self, path: &Path, label: &str) { let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; - self.links = std::sync::OnceLock::new(); + self.others = std::sync::OnceLock::new(); let mut put = |file: String, p: PathBuf, what: String| self.by_name.entry(file.to_lowercase()).or_default().push((p, what)); put(name.clone(), path.to_path_buf(), format!("the original of {label}")); let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); @@ -44,6 +129,17 @@ impl OriginalGuard { /// `Err` (a message for the user) when writing `target` would replace a protected file. pub fn check(&self, target: &Path) -> Result<(), String> { + self.check_target(target, false) + } + + /// [`Self::check`] plus hard links: a screenshot target must not replace an original reached + /// through a link with a different name. The per-entry identity scan is limited to this + /// long-lived, user-visible destination check, not every ordinary export overwrite. + pub fn check_identity(&self, target: &Path) -> Result<(), String> { + self.check_target(target, true) + } + + fn check_target(&self, target: &Path, hard_links: bool) -> Result<(), String> { if std::fs::symlink_metadata(target).is_err() { return Ok(()); // nothing there to replace } @@ -61,12 +157,15 @@ impl OriginalGuard { } } } - // An imported symlink can have a different name from its original. A write to - // that original would change what the library reads through the link. Only do - // this fallback for existing targets that the name index did not protect; the links are - // looked up once per guard, not once per target. - let links = self.links.get_or_init(|| self.by_name.values().flatten().filter(|(p, _)| std::fs::read_link(p).is_ok()).cloned().collect()); - for (p, what) in links { + // An imported hard link or symlink can have a different name from its original. A write + // to that entry would change what the library reads. Only do this fallback for existing + // targets that the name index did not protect; the list is built once per guard, not once + // per target. Ordinary exports keep the cheaper symlink-only scan. + let others = self.others.get_or_init(|| self.by_name.values().flatten().cloned().collect()); + for (p, what) in others { + if !hard_links && std::fs::read_link(p).is_err() { + continue; + } if same_file(p, target) { return Err(format!( "{} is {what} in the library: LightCraft never writes over an original (choose another folder or file name)", @@ -93,6 +192,69 @@ impl crate::Session { } self.original_guard().check(path) } + + /// Pin the destination of a long-running write (a screenshot) now. + /// + /// The returned [`WriteTarget`] records whether the directory entry existed and, if so, its + /// identity, plus the canonical parent folder. Pass it to [`Self::revalidate_write_target`] + /// immediately before writing. + pub fn pin_write_target(&self, path: &str) -> Result<WriteTarget, String> { + let p = Path::new(path); + let parent = p.parent().filter(|d| !d.as_os_str().is_empty()).and_then(|d| std::fs::canonicalize(d).ok()); + match std::fs::symlink_metadata(p) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + Ok(WriteTarget { path: path.to_string(), state: WriteTargetState::Absent, parent }) + } + Err(error) => Err(format!("{path}: {error}")), + Ok(meta) => { + // Refuse a catalogued original or sidecar (including a differently named hard + // link) before the request is queued. + self.original_guard().check_identity(p)?; + Ok(WriteTarget { path: path.to_string(), state: WriteTargetState::Existing(FileIdentity::of(p, &meta)), parent }) + } + } + } + + /// Re-check a pinned target immediately before writing. + /// + /// An absent target must still be absent; an existing target must still name the same + /// directory entry and must still pass the current catalog's original guard. A parent folder + /// whose canonical path changed (a retargeted symlink) is refused too. + pub fn revalidate_write_target(&self, target: &WriteTarget) -> Result<(), String> { + if let Some(parent) = &target.parent { + // Resolve the request's parent again: canonicalizing the saved resolved folder + // would miss a directory symlink in the original path being retargeted. + let now = Path::new(&target.path).parent().and_then(|path| std::fs::canonicalize(path).ok()); + match now { + Some(now) if now == *parent => {} + _ => { + return Err(format!( + "{}: the destination folder changed while the screenshot was being captured; refusing to write", + target.path + )); + } + } + } + match std::fs::symlink_metadata(&target.path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => match &target.state { + WriteTargetState::Absent => Ok(()), + WriteTargetState::Existing(_) => { + Err(format!("{}: the file was removed while the screenshot was being captured; refusing to create it again", target.path)) + } + }, + Err(error) => Err(format!("{}: {error}", target.path)), + Ok(meta) => match &target.state { + WriteTargetState::Absent => Err(format!("{} appeared while the screenshot was being captured; refusing to replace it", target.path)), + WriteTargetState::Existing(identity) => { + if FileIdentity::of(Path::new(&target.path), &meta) != *identity { + return Err(format!("{} changed while the screenshot was being captured; refusing to replace the new file", target.path)); + } + // The catalog may have gained this file as an original since admission. + self.original_guard().check_identity(Path::new(&target.path)) + } + }, + } + } } #[cfg(test)] @@ -120,4 +282,61 @@ mod tests { assert!(g.check(&d.join("new.jpg")).is_ok(), "a free name"); let _ = std::fs::remove_dir_all(&d); } + + #[test] + fn write_targets_pin_absent_paths_and_recheck_the_current_library() { + let d = std::env::temp_dir().join(format!("lc-write-targets-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let mut s = crate::Session::new(); + let original = d.join("IMG_1.jpg"); + std::fs::write(&original, b"original").unwrap(); + let photo = Photo::new(PhotoId(1), Source::File { path: original.to_string_lossy().to_string() }, "IMG_1.jpg", "JPEG", 10, 10, "2026-01-01"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + + // A path that was absent at admission is refused when anything appears there. + let free = d.join("new-shot.png"); + let absent = s.pin_write_target(&free.to_string_lossy()).expect("free path"); + assert!(absent.was_absent()); + std::fs::write(&free, b"appeared").unwrap(); + assert!(s.revalidate_write_target(&absent).unwrap_err().contains("appeared")); + std::fs::remove_file(&free).unwrap(); + + // An ordinary existing path can still be overwritten in place (same entry). + let allowed = d.join("old-shot.png"); + std::fs::write(&allowed, b"old").unwrap(); + let existing = s.pin_write_target(&allowed.to_string_lossy()).expect("ordinary file"); + assert!(!existing.was_absent()); + std::fs::write(&allowed, b"new").unwrap(); + assert!(s.revalidate_write_target(&existing).is_ok(), "an allowed screenshot refresh keeps working"); + + // A hard link to an original is refused at admission, and an absent path that becomes + // such a link is refused at write time. + let linked = d.join("linked.png"); + std::fs::hard_link(&original, &linked).unwrap(); + assert!(s.pin_write_target(&linked.to_string_lossy()).unwrap_err().contains("original")); + std::fs::remove_file(&linked).unwrap(); + let appears_as_link = d.join("late-link.png"); + let late = s.pin_write_target(&appears_as_link.to_string_lossy()).expect("free path"); + std::fs::hard_link(&original, &appears_as_link).unwrap(); + assert!(s.revalidate_write_target(&late).unwrap_err().contains("appeared")); + + // A path pinned as an ordinary file becomes an original through a catalog import while + // the capture is queued: the current guard refuses the write. + let imported = d.join("imported.png"); + std::fs::write(&imported, b"not yet imported").unwrap(); + let queued = s.pin_write_target(&imported.to_string_lossy()).expect("ordinary file"); + let p = Photo::new(PhotoId(2), Source::File { path: imported.to_string_lossy().to_string() }, "imported.png", "PNG", 10, 10, "2026-01-01"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + assert!(s.revalidate_write_target(&queued).unwrap_err().contains("original")); + + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + let link = d.join("link-shot.png"); + symlink(&original, &link).unwrap(); + assert!(s.pin_write_target(&link.to_string_lossy()).unwrap_err().contains("original")); + } + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/engine/src/print/layout.rs b/crates/engine/src/print/layout.rs index 26d1818e5e..be44384249 100644 --- a/crates/engine/src/print/layout.rs +++ b/crates/engine/src/print/layout.rs @@ -46,6 +46,41 @@ const PAPER: &[(&str, f64, f64)] = &[ ("5x7", 5.0, 7.0), ("8x10", 8.0, 10.0), ("13x19", 13.0, 19.0), + // Japanese photo printing and postcard sizes, at their exact metric dimensions (the US photo + // sizes above are close but not identical: L is 89 x 127 mm, 5x7 in is 127 x 177.8 mm). + ("l", 89.0 / 25.4, 127.0 / 25.4), + ("2l", 127.0 / 25.4, 178.0 / 25.4), + ("kg", 102.0 / 25.4, 152.0 / 25.4), + ("postcard", 100.0 / 25.4, 148.0 / 25.4), + ("double-postcard", 148.0 / 25.4, 200.0 / 25.4), + ("6cut", 203.0 / 25.4, 254.0 / 25.4), + ("4cut", 254.0 / 25.4, 305.0 / 25.4), + ("business-card", 55.0 / 25.4, 91.0 / 25.4), +]; + +/// Japanese customary names (and a few English spellings) for the papers in [`PAPER`], matched +/// after [`normalize_paper`]: `L判` is `l`, `はがき` is `postcard`, `六切` is `6cut`, and so on. +const PAPER_ALIASES: &[(&str, &str)] = &[ + ("L判", "l"), + ("Lサイズ", "l"), + ("L-size", "l"), + ("2L判", "2l"), + ("2Lサイズ", "2l"), + ("2L-size", "2l"), + ("KG判", "kg"), + ("KGサイズ", "kg"), + ("KG-size", "kg"), + ("はがき", "postcard"), + ("ハガキ", "postcard"), + ("葉書", "postcard"), + ("ポストカード", "postcard"), + ("往復はがき", "double-postcard"), + ("往復ハガキ", "double-postcard"), + ("六切", "6cut"), + ("6切", "6cut"), + ("四切", "4cut"), + ("4切", "4cut"), + ("名刺", "business-card"), ]; /// Names accepted by [`PageSetup::paper`] (besides `custom`). @@ -53,10 +88,39 @@ pub fn paper_names() -> impl Iterator<Item = &'static str> { PAPER.iter().map(|p| p.0) } -/// Portrait size in inches of a named paper (case-insensitive), `None` for unknown names and `custom`. +/// The form [`paper_name`] matches names in: lower case, letters and digits only, and `×`/`*` read +/// as `x`, so `L判`, `L判。`, `l-size` and `(l)` are one name and `4 × 6` is `4x6`. +fn normalize_paper(name: &str) -> String { + name.chars() + .filter_map(|c| match c { + '×' | '*' => Some('x'), + c if c.is_alphanumeric() => Some(c), + _ => None, + }) + .collect::<String>() + .to_lowercase() +} + +/// The canonical name of the paper `name` stands for, `None` for unknown names and `custom`. +/// `L判` is `l`, `はがき` is `postcard`, `六切` is `6cut`, and so on. +pub fn paper_name(name: &str) -> Option<&'static str> { + let n = normalize_paper(name); + if n.is_empty() { + return None; + } + PAPER + .iter() + .find(|p| normalize_paper(p.0) == n) + .map(|p| p.0) + .or_else(|| PAPER_ALIASES.iter().find(|(alias, _)| normalize_paper(alias) == n).map(|(_, name)| *name)) +} + +/// Portrait size in inches of a named paper, `None` for unknown names and `custom`. Case, spaces +/// and punctuation don't matter, and the Japanese customary names (`L判`, `2L判`, `KG判`, `はがき`, +/// `往復はがき`, `六切`, `四切`, `名刺`) are aliases of the papers above. pub fn paper_size(name: &str) -> Option<(f64, f64)> { - let name = name.to_ascii_lowercase(); - PAPER.iter().find(|p| p.0 == name).map(|p| (p.1, p.2)) + let canonical = paper_name(name)?; + PAPER.iter().find(|p| p.0 == canonical).map(|p| (p.1, p.2)) } /// An axis-aligned rectangle in inches. @@ -935,6 +999,65 @@ mod tests { assert!(p.size().is_err()); } + /// Japanese photo and postcard papers: exact metric sizes to 0.1 pt, the customary names as + /// aliases, and the ISO/US papers around them unchanged. + #[test] + fn japanese_photo_and_postcard_papers() { + let pt = |name: &str| { + let p = PageSetup { paper: name.into(), ..Default::default() }; + p.size_points().unwrap_or_else(|e| panic!("{name}: {e}")) + }; + for (name, w_mm, h_mm) in [ + ("L判", 89.0, 127.0), + ("2L判", 127.0, 178.0), + ("KG判", 102.0, 152.0), + ("はがき", 100.0, 148.0), + ("往復はがき", 148.0, 200.0), + ("六切", 203.0, 254.0), + ("四切", 254.0, 305.0), + ("名刺", 55.0, 91.0), + ] { + let (w, h) = pt(name); + let want = (w_mm / 25.4 * 72.0, h_mm / 25.4 * 72.0); + assert!((w - want.0).abs() < 0.1 && (h - want.1).abs() < 0.1, "{name}: {w} x {h} pt, wanted {want:?}"); + assert!((w - h).abs() > 1e-6, "{name} is portrait"); + } + // The customary and English spellings resolve to the same paper, including spaces and case. + for (a, b) in [ + ("L判", "l"), + ("L判", " L "), + ("L判", "L-size"), + ("2L判", "2l"), + ("KG判", "kg"), + ("はがき", "postcard"), + ("はがき", "ハガキ"), + ("往復はがき", "double-postcard"), + ("六切", "6cut"), + ("六切", "6切"), + ("四切", "4cut"), + ("名刺", "business-card"), + ("A4", "a 4"), + ("4 × 6", "4x6"), + ] { + assert_eq!(paper_size(a), paper_size(b), "{a} vs {b}"); + } + // Punctuation is ignored, including the periods and Japanese marks a pasted name may carry. + for (name, canonical) in [("L判。", "l"), ("L判、", "l"), ("(L判)", "l"), ("l-size.", "l"), ("はがき。", "postcard"), ("6切。", "6cut")] + { + assert_eq!(paper_name(name), Some(canonical), "{name}"); + } + assert_eq!(paper_name("custom"), None); + assert!(paper_size("poster").is_none()); + // The papers that were already there keep their sizes. + assert_eq!(pt("letter"), (612.0, 792.0)); + assert_eq!(pt("4x6"), (288.0, 432.0)); + assert_eq!(pt("5x7"), (360.0, 504.0)); + assert_eq!(pt("8x10"), (576.0, 720.0)); + assert_eq!(pt("13x19"), (936.0, 1368.0)); + let (w, h) = pt("A4"); + assert!((w - 595.28).abs() < 0.01 && (h - 841.89).abs() < 0.01, "A4 {w} x {h}"); + } + #[test] fn hostile_numbers_are_rejected() { for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1e9] { diff --git a/crates/engine/src/print/template.rs b/crates/engine/src/print/template.rs index 2465c123ae..7bb5336129 100644 --- a/crates/engine/src/print/template.rs +++ b/crates/engine/src/print/template.rs @@ -30,6 +30,14 @@ impl PrintSettings { pub const MAX_NAME: usize = 80; /// Most templates kept. pub const MAX_TEMPLATES: usize = 200; +/// File extension of an exported print template (JSON). +pub const FILE_EXT: &str = "lcprint"; +/// `format` tag of an exported print template file. +const FILE_FORMAT: &str = "lightcraft.printTemplate"; +/// Version of the template file this build writes and the newest it reads. +const FILE_VERSION: u64 = 1; +/// Largest template file read, bytes. +pub const MAX_FILE: u64 = 256 * 1024; /// A saved print template: the layout, image settings, page and job of a print, without the /// photos assigned to cells and without the guides (a view preference). The settings are kept as @@ -74,6 +82,53 @@ impl PrintTemplate { s.validate().map_err(|e| format!("template `{}`: {e}", self.name))?; Ok(s) } + + /// The document of an exported template: `{format, version, name, settings}`. + pub fn to_file(&self) -> serde_json::Value { + serde_json::json!({"format": FILE_FORMAT, "version": FILE_VERSION, "name": self.name, "settings": self.settings}) + } + + /// A template read from an exported file. Refused: more than [`MAX_FILE`] bytes, not JSON, + /// another format or a newer version, a bad name, and settings that fail the checks a saved + /// template's settings get. Photos assigned to cells and guides in the file are dropped. + pub fn from_file(bytes: &[u8]) -> Result<Self, String> { + if bytes.len() as u64 > MAX_FILE { + return Err(format!("{} bytes is too large for a print template (at most {} KB)", bytes.len(), MAX_FILE / 1024)); + } + let v: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| format!("not a print template file: {e}"))?; + if v.get("format").and_then(serde_json::Value::as_str) != Some(FILE_FORMAT) { + return Err(format!("not a print template file (`format` is not \"{FILE_FORMAT}\")")); + } + match v.get("version").and_then(serde_json::Value::as_u64) { + Some(1..=FILE_VERSION) => {} + Some(n) => return Err(format!("print template file version {n} is not one this version of LightCraft reads (1 to {FILE_VERSION})")), + None => return Err("a print template file needs a `version` number".into()), + } + let name = clean_name(v.get("name").and_then(serde_json::Value::as_str).ok_or("a print template file needs a `name`")?)?; + let settings = v.get("settings").cloned().ok_or("a print template file needs `settings`")?; + let checked = PrintTemplate { name: name.clone(), settings }.settings(&Guides::default())?; + Self::new(&name, &checked) + } +} + +/// `name` if no template in `taken` has it (in any case), else the first free `name (2)`, +/// `name (3)`…, with `name` shortened to keep the result within [`MAX_NAME`] characters. +pub fn unique_name(name: &str, taken: &[PrintTemplate]) -> String { + let free = |n: &str| !taken.iter().any(|t| t.name.eq_ignore_ascii_case(n)); + if free(name) { + return name.to_string(); + } + let mut n = 2usize; + loop { + let suffix = format!(" ({n})"); + let keep = MAX_NAME.saturating_sub(suffix.chars().count()); + let base: String = name.chars().take(keep).collect(); + let candidate = format!("{}{suffix}", base.trim_end()); + if free(&candidate) || n > taken.len() { + return candidate; + } + n += 1; + } } #[cfg(test)] @@ -121,4 +176,64 @@ mod tests { s.job.ppi = f32::NAN; assert!(PrintTemplate::new("t", &s).is_err()); } + + #[test] + fn a_template_file_reads_back_as_the_template() { + let mut s = PrintSettings::default(); + s.layout.style = Style::ContactSheet; + s.page.background = [1, 2, 3]; + let t = PrintTemplate::new("Proofs", &s).unwrap(); + let bytes = serde_json::to_vec(&t.to_file()).unwrap(); + assert_eq!(PrintTemplate::from_file(&bytes).unwrap(), t); + // a hand-written file: photos and guides are not taken in + let doc = json!({"format": FILE_FORMAT, "version": 1, "name": " Hand ", "settings": { + "layout": {"style": "customPackage", "cells": [{"id": 1, "rect": {"x": 1, "y": 1, "w": 2, "h": 2}, "photo": 9}]}, + "guides": {"gridSize": 1.0}}}); + let t = PrintTemplate::from_file(&serde_json::to_vec(&doc).unwrap()).unwrap(); + assert_eq!(t.name, "Hand"); + assert!(t.settings.get("guides").is_none()); + assert!(t.settings.pointer("/layout/cells/0/rect").is_some()); + assert_eq!(t.settings.pointer("/layout/cells/0/photo"), None); + } + + #[test] + fn hostile_template_files_are_refused() { + let file = |v: serde_json::Value| PrintTemplate::from_file(&serde_json::to_vec(&v).unwrap()).unwrap_err(); + let ok = |extra: serde_json::Value| { + let mut v = json!({"format": FILE_FORMAT, "version": 1, "name": "t", "settings": {}}); + if let (Some(o), Some(e)) = (v.as_object_mut(), extra.as_object()) { + o.extend(e.clone()); + } + v + }; + assert!(PrintTemplate::from_file(b"not json").unwrap_err().contains("not a print template file")); + assert!(PrintTemplate::from_file(&vec![b' '; MAX_FILE as usize + 1]).unwrap_err().contains("too large")); + assert!(file(json!([1, 2])).contains("format")); + assert!(file(ok(json!({"format": "lightcraft.slideshowTemplate"}))).contains("format")); + assert!(file(ok(json!({"version": 2}))).contains("version 2")); + assert!(file(ok(json!({"version": 0}))).contains("version 0")); + assert!(file(ok(json!({"version": "1"}))).contains("`version` number")); + assert!(file(json!({"format": FILE_FORMAT, "name": "t", "settings": {}})).contains("`version` number")); + assert!(file(ok(json!({"name": "a\nb"}))).contains("template name")); + assert!(file(ok(json!({"name": 5}))).contains("`name`")); + assert!(file(json!({"format": FILE_FORMAT, "version": 1, "name": "t"})).contains("`settings`")); + assert!(file(ok(json!({"settings": {"job": {"ppi": 1e30}}}))).contains("template `t`")); + assert!(file(ok(json!({"settings": {"surprise": 1}}))).contains("template `t`")); + assert!(PrintTemplate::from_file(&serde_json::to_vec(&ok(json!({}))).unwrap()).is_ok()); + } + + #[test] + fn an_imported_name_never_takes_an_existing_one() { + let t = |n: &str| PrintTemplate::new(n, &PrintSettings::default()).unwrap(); + assert_eq!(unique_name("Proofs", &[]), "Proofs"); + assert_eq!(unique_name("Proofs", &[t("proofs")]), "Proofs (2)"); + assert_eq!(unique_name("Proofs", &[t("Proofs"), t("PROOFS (2)")]), "Proofs (3)"); + let long = "x".repeat(MAX_NAME); + let named = unique_name(&long, &[t(&long)]); + assert_eq!(named.chars().count(), MAX_NAME); + assert!(named.ends_with(" (2)")); + let many: Vec<PrintTemplate> = std::iter::once(t("A")).chain((2..=MAX_TEMPLATES).map(|n| t(&format!("A ({n})")))).collect(); + let named = unique_name("A", &many); + assert!(!many.iter().any(|x| x.name.eq_ignore_ascii_case(&named)), "{named}"); + } } diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index f0d7257936..c569a2e1ff 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -4,7 +4,7 @@ //! Template tokens (shared with import renaming and export file naming): `{name}` (current name //! without extension), `{num}` (the number at the end of the name: `IMG_0042` → `0042`), `{seq}` / //! `{seq:3}` (sequence number, zero-padded to 3 digits), `{date}` / `{date:%Y%m%d}` (capture date; -//! `%Y %y %m %d %H %M %S`), `{folder}` (the original's folder name), `{camera}`, `{lens}`, `{iso}`, +//! `%Y %y %m %B %b %d %H %M %S`), `{folder}` (the original's folder name), `{camera}`, `{lens}`, `{iso}`, //! `{rating}`, `{title}`, `{creator}`, `{ext}` (extension, without the dot). Unknown tokens stay as //! typed. Characters that aren't allowed in file names become `-`. The original extension is always //! kept. @@ -25,6 +25,7 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use lightcraft_catalog::dates::MONTHS; use lightcraft_catalog::{Op, Photo, PhotoId, Source}; use serde::Serialize; @@ -57,9 +58,12 @@ fn sanitize(s: &str) -> String { t.trim().trim_matches('.').trim().to_string() } -/// `%Y%m%d`-style formatting of an ISO local time. +/// `%Y%m%d`-style formatting of an ISO local time. `%B` / `%b` are the English month name +/// (`January` / `Jan`), the same in every interface language so folder names stay put; a month +/// that doesn't parse gives nothing. fn format_date(iso: &str, fmt: &str) -> String { let part = |a: usize, b: usize| iso.get(a..b).unwrap_or("00").to_string(); + let month = iso.get(5..7).and_then(|m| m.parse::<usize>().ok()).and_then(|m| m.checked_sub(1)).and_then(|i| MONTHS.get(i)).copied().unwrap_or(""); let mut out = String::new(); let mut it = fmt.chars(); while let Some(c) = it.next() { @@ -71,6 +75,8 @@ fn format_date(iso: &str, fmt: &str) -> String { Some('Y') => out.push_str(&part(0, 4)), Some('y') => out.push_str(&part(2, 4)), Some('m') => out.push_str(&part(5, 7)), + Some('B') => out.push_str(month), + Some('b') => out.push_str(month.get(..3).unwrap_or(month)), Some('d') => out.push_str(&part(8, 10)), Some('H') => out.push_str(&part(11, 13)), Some('M') => out.push_str(&part(14, 16)), @@ -120,6 +126,8 @@ pub const DATE_DIRECTIVES: &[(&str, &str)] = &[ ("%Y", "year, 4 digits"), ("%y", "year, 2 digits"), ("%m", "month 01–12"), + ("%B", "month name (January)"), + ("%b", "short month name (Jan)"), ("%d", "day 01–31"), ("%H", "hour 00–23"), ("%M", "minute"), @@ -1670,6 +1678,8 @@ pub(crate) mod tests { let mut p = sample_photo(); assert_eq!(expand_folder("{date:%Y}/{date:%Y%m%d}", &p, 1), vec!["2026", "20260114"]); assert_eq!(expand_folder("{date:%Y}\\{date:%Y-%m}", &p, 1), vec!["2026", "2026-01"], "backslash separates too"); + assert_eq!(expand_folder("{date:%Y}/{date:%B}", &p, 1), vec!["2026", "January"]); + assert_eq!(expand_folder("{date:%Y}/{date:%m %b}", &p, 1), vec!["2026", "01 Jan"]); // metadata can't add levels or climb out p.meta.camera = "../../etc/x".into(); p.meta.title = "..".into(); @@ -1711,6 +1721,12 @@ pub(crate) mod tests { let v = format_date("2026-01-14T05:58:48", d); assert!(!v.contains('%') || *d == "%%", "{d} is not a known directive"); } + assert_eq!(format_date("2026-09-30T14:05:00", "%B %b"), "September Sep"); + assert_eq!(format_date("2026-12-01T00:00:00", "%d %B %Y"), "01 December 2026"); + // a month that isn't 01–12 gives no name instead of panicking + for bad in ["2026-00-01", "2026-13-01", "2026-x", "", "2026-é1-01"] { + assert_eq!(format_date(bad, "%B|%b"), "|", "{bad:?}"); + } assert_eq!(unknown_tokens("{date}_{camra}-{seq:2}{x}{camra}"), vec!["{camra}".to_string(), "{x}".to_string()]); assert!(unknown_tokens("{name}{ext}{date:%Y}").is_empty()); let json = token_help_json(); diff --git a/crates/engine/src/slideshow.rs b/crates/engine/src/slideshow.rs index dbee505af0..cb3a6b97db 100644 --- a/crates/engine/src/slideshow.rs +++ b/crates/engine/src/slideshow.rs @@ -1,6 +1,7 @@ //! Slideshow playback: the settings of Lightroom Classic's Playback panel and the timeline that -//! plays the photos in view (durations, fades, random order, repeat, pause, stepping), between an -//! optional intro and ending screen (the Titles panel, [`crate::slide_title`]). +//! plays the photos in view (durations, fades, random order, repeat, pause, stepping, manual +//! advance), between an optional intro and ending screen (the Titles panel, +//! [`crate::slide_title`]). //! //! No UI here: [`Playback`] is a pure state machine driven with injected times (seconds on any //! monotonic clock), so the desktop app, a later Slideshow module and tests run the same timeline. @@ -39,11 +40,22 @@ pub struct PlaybackSettings { pub repeat: bool, /// Render the next slides before they are due. pub prepare_previews: bool, + /// Manual slideshow: a slide stays up until ← / → (or the controls) change it; the slide + /// duration is not used for playback then. + pub manual: bool, } impl Default for PlaybackSettings { fn default() -> Self { - PlaybackSettings { slide_duration: 4.0, fade_duration: 1.0, fade_color: None, random_order: false, repeat: true, prepare_previews: true } + PlaybackSettings { + slide_duration: 4.0, + fade_duration: 1.0, + fade_color: None, + random_order: false, + repeat: true, + prepare_previews: true, + manual: false, + } } } @@ -66,6 +78,7 @@ impl PlaybackSettings { "randomOrder": self.random_order, "repeat": self.repeat, "preparePreviews": self.prepare_previews, + "manual": self.manual, }) } @@ -82,8 +95,11 @@ impl PlaybackSettings { "randomOrder" => s.random_order = boolean(k, v)?, "repeat" => s.repeat = boolean(k, v)?, "preparePreviews" => s.prepare_previews = boolean(k, v)?, + "manual" => s.manual = boolean(k, v)?, other => { - return Err(format!("unknown setting `{other}` (slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews)")); + return Err(format!( + "unknown setting `{other}` (slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual)" + )); } } } @@ -432,8 +448,12 @@ impl Playback { self.started + self.duration(self.current()) } - /// Seconds until the next slide is due (as of `now`; frozen while paused). + /// Seconds until the next slide is due (as of `now`; frozen while paused; infinite in a + /// manual slideshow, where no slide is ever due). pub fn remaining(&self, now: f64) -> f64 { + if self.settings.manual { + return f64::INFINITY; + } (self.due() - self.clock(now)).max(0.0) } @@ -490,7 +510,8 @@ impl Playback { self.started = now; return Tick::Idle; } - if now < self.due() { + // a manual slideshow moves only with `step` (← / →) + if self.settings.manual || now < self.due() { return Tick::Idle; } let Some(next) = self.upcoming(1).first().copied() else { @@ -777,6 +798,30 @@ mod tests { assert!(Playback::new(vec![], None, d, 0, 0.0).is_none()); } + #[test] + fn a_manual_slideshow_moves_only_with_the_arrows() { + let s = PlaybackSettings { manual: true, repeat: false, ..settings(1.0, 0.5) }; + let mut p = titled(3, s, Some(1.0), Some(1.0)); + assert_eq!(p.tick(1000.0, all_ready), Tick::Idle, "the intro stays up past its duration"); + assert_eq!(p.current(), Item::INTRO); + assert_eq!(p.remaining(1000.0), f64::INFINITY, "nothing is ever due"); + assert_eq!(p.upcoming(1), vec![ph(1)], "the next slide is still prepared for →"); + assert_eq!(p.step(1, 1000.0), Tick::Advanced(ph(1))); + assert_eq!(p.tick(5000.0, all_ready), Tick::Idle); + assert_eq!(p.current(), ph(1), "a photo stays up too"); + assert_eq!(p.step(-1, 5000.0), Tick::Advanced(Item::INTRO), "← goes back"); + assert_eq!(p.step(4, 5000.0), Tick::Advanced(Item::ENDING)); + assert_eq!(p.tick(9000.0, all_ready), Tick::Idle, "the ending stays up until → ends the show"); + assert_eq!(p.step(1, 9000.0), Tick::Ended); + // the setting round-trips and is checked like the others + let d = PlaybackSettings::default(); + assert!(!d.manual, "off by default"); + let m = d.merged(&json!({"manual": true})).unwrap(); + assert!(m.manual); + assert_eq!(m.to_json()["manual"], true); + assert!(d.merged(&json!({"manual": "yes"})).is_err()); + } + #[test] fn a_single_photo_repeats_without_changing() { let mut p = Playback::new(ids(1), None, settings(1.0, 0.5), 1, 0.0).unwrap(); diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 713c697a7e..f20ad9c95e 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -845,13 +845,12 @@ impl SyncCommit { } } SyncStep::Remove(gone) => { - let ops: Vec<Op> = gone - .iter() - .filter(|id| s.catalog.photo(**id).is_some_and(|p| p.in_library())) - .map(|id| Op::SetDeleted { id: *id, deleted: true }) - .collect(); + let ids: Vec<PhotoId> = gone.into_iter().filter(|id| s.catalog.photo(*id).is_some_and(|p| p.in_library())).collect(); + let mut ops: Vec<Op> = ids.iter().map(|id| Op::SetDeleted { id: *id, deleted: true }).collect(); let n = ops.len(); if n > 0 { + // Like `photo.delete`, take them out of their stacks. + ops.extend(s.catalog.remove_from_stacks_ops(&ids)); match s.commit("Remove Missing Photos", Op::Batch { ops }) { Ok(()) => report.removed += n, Err(e) => report.failed.push((String::new(), e.to_string())), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1e8f4b7e31..93f4e6adcf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -108,6 +108,20 @@ fn demo_library_loads() { assert!(albums.as_array().unwrap().iter().any(|a| a["folder"] == true)); } +#[test] +fn rating_rejects_fractional_values() { + let mut s = demo(); + let id = s.active().unwrap(); + for bad in [5.9, -0.9, 0.5] { + let err = s.execute("photo.rate", &json!({"rating": bad})).unwrap_err(); + assert!(matches!(&err, crate::EngineError::BadParams { cmd, .. } if cmd == "photo.rate"), "{bad}: {err}"); + assert_eq!(s.catalog.photo(id).unwrap().rating, 0, "{bad} changed the rating"); + } + s.execute("photo.rate", &json!({"rating": 5.0})).unwrap(); + s.execute("photo.rate", &json!({"rating": 3})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().rating, 3); +} + #[test] fn rating_flag_undo_redo() { let mut s = demo(); @@ -452,8 +466,14 @@ fn command_sweep() { for c in command_specs() { assert!(ids.insert(c.id), "duplicate {}", c.id); assert!(!c.label.is_empty() && !c.params.is_empty(), "{}", c.id); + // empty params make this one download from download.geonames.org into the real settings folder; its own tests run it against a loopback server + if c.id == "metadata.downloadPlaceNames" { + continue; + } let _ = s.execute(c.id, &Value::Null); } + // empty params must never start a download from the internet + assert!(!s.place_names.download_started(), "the sweep started a place names download"); assert!(s.commands().len() >= 70, "{}", s.commands().len()); } @@ -1244,6 +1264,43 @@ fn find_similar_filters_to_look_alikes() { assert!(s.visible_cloned().len() > vis.len()); } +#[test] +fn find_similar_with_no_hits_shows_no_photos() { + let mut s = demo(); + let r = s.execute("library.findSimilar", &json!({"similarity": 1.5})).unwrap(); + assert_eq!(r["photos"].as_array().map(Vec::len), Some(0)); + assert_eq!(s.visible_cloned().len(), 0, "an empty Find Similar result must show no photos, not the whole library"); + s.execute("library.clearFilter", &json!({})).unwrap(); + assert_eq!(s.visible_cloned().len(), s.catalog.len(), "Clear Filters brings everything back"); +} + +#[test] +fn find_similar_of_a_flat_photo_shows_an_empty_view_and_counts_zero() { + let mut s = demo(); + let photo = s.catalog.photos().next().unwrap().clone(); + // a flat photo's signature is all zeros: it is not similar even to itself + s.signatures.insert(crate::media::content_key(&photo), [0.0; 64]); + let r = s.execute("library.findSimilar", &json!({"id": photo.id.0})).unwrap(); + assert_eq!(r["photos"].as_array().map(Vec::len), Some(0)); + assert_eq!(s.visible_cloned().len(), 0, "no matches show nothing, not the whole library"); + assert_eq!(s.catalog.count(&s.filter), 0); + let chips = crate::filter_chips(&s.filter, &s.catalog); + assert_eq!(chips.iter().map(|c| c.label.as_str()).collect::<Vec<_>>(), ["Only 0 photos"]); + s.execute("library.filter", &chips[0].clear).unwrap(); + assert_eq!(s.filter, Default::default(), "the chip clears the empty state"); + assert_eq!(s.visible_cloned().len(), s.catalog.len()); +} + +#[test] +fn find_similar_values_stay_within_zero_and_one() { + let mut s = demo(); + let id = s.catalog.photos().next().unwrap().id; + let r = s.execute("library.findSimilar", &json!({"id": id.0, "similarity": -1.0})).unwrap(); + let sims: Vec<f64> = r["photos"].as_array().unwrap().iter().map(|h| h["similarity"].as_f64().unwrap()).collect(); + assert_eq!(sims.len(), s.catalog.len()); + assert!(sims.iter().all(|v| (0.0..=1.0).contains(v)), "{sims:?}"); +} + #[test] fn quick_develop_adds_to_each_photo() { use lightcraft_catalog::PhotoId; diff --git a/crates/engine/src/tests_denoise.rs b/crates/engine/src/tests_denoise.rs index cc9ad2eed4..bf0ae3a713 100644 --- a/crates/engine/src/tests_denoise.rs +++ b/crates/engine/src/tests_denoise.rs @@ -1,7 +1,7 @@ //! AI denoise through the engine: installing a model, making a photo's denoised picture in the background and for an //! export, the Amount slider mixing it in, and the cache. A tiny stand-in model (it halves every sample) takes the //! place of a real one, which is enough to see what the machinery does with its answer; how well real models denoise is -//! measured separately (`crates/denoise/tests/real_model.rs`). +//! measured separately (`crates/denoise/tests/it/real_model.rs`). use std::path::{Path, PathBuf}; use std::sync::Arc; diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 4830490b5c..d0f1742451 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -4,7 +4,7 @@ use serde_json::json; use crate::Session; use crate::export::{ExportFormat, ExportOptions, export_photo}; -use crate::tests_xmp::{synthetic_dng_with, temp_dir}; +use crate::tests_xmp::{synthetic_dng_with, synthetic_psd_with_metadata, temp_dir}; #[test] fn full_size_export_of_a_cropped_photo_is_not_upscaled() { @@ -313,6 +313,30 @@ fn curve_preset_export_never_overwrites_originals_or_sidecars() { preset_export_preserves_originals("curve.exportPresets", json!({"names": ["Linear"]}), "curve-export-guard"); } +/// #1944: Export Keywords went straight to `std::fs::write`, replacing a library original. +#[test] +fn keyword_export_never_overwrites_originals_or_sidecars() { + preset_export_preserves_originals("keyword.export", json!({}), "keyword-export-guard"); +} + +#[test] +fn keyword_export_preserves_the_previous_file_on_write_failure() { + let dir = temp_dir("keyword-export-failure"); + let mut s = Session::with_demo(); + let path = dir.join("keywords.txt"); + let params = json!({"path": path.to_string_lossy()}); + s.execute("keyword.export", &params).unwrap(); + let previous = std::fs::read(&path).unwrap(); + { + let _fault = lightcraft_catalog::safe_file::fail_writes_after(4); + assert!(s.execute("keyword.export", &params).is_err(), "keyword.export must report the failed write"); + } + assert_eq!(std::fs::read(&path).unwrap(), previous, "the prior export is kept"); + s.execute("keyword.export", &params).unwrap(); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "no temporary files remain"); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn preset_exports_preserve_previous_files_on_write_failure() { let dir = temp_dir("preset-export-failure"); @@ -657,6 +681,92 @@ fn remove_location_refuses_a_raw_that_embeds_gps() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn remove_location_refuses_a_psd_that_embeds_gps() { + let dir = temp_dir("export-noloc-psd"); + let gps = lightcraft_meta::Metadata { gps: Some(lightcraft_meta::Gps { latitude: 45.0, longitude: 7.0, altitude: None }), ..Default::default() }; + let path = dir.join("Geo.psd"); + let bytes = synthetic_psd_with_metadata(&gps); + assert_eq!(lightcraft_meta::extract(&bytes).gps, gps.gps, "the fixture embeds EXIF GPS"); + std::fs::write(&path, &bytes).unwrap(); + let mut session = Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let id = session.catalog.photos().next().unwrap().id; + let err = export_photo(&mut session, id, &ExportOptions::from_json(&json!({"format": "original", "removeLocation": true})), 1).err().unwrap(); + assert!(err.contains("can't remove the location") && err.contains("export as JPEG"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn remove_location_refuses_a_psd_with_unreadable_xmp() { + let dir = temp_dir("export-noloc-psd-xmp"); + let path = dir.join("Unreadable.psd"); + let pixels = [40, 80, 120]; + let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U8(&pixels)); + let xmp = "<x:xmpmeta><broken"; + let embedded = lightcraft_codecs::EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = lightcraft_codecs::encode_psd(&image, &embedded).unwrap(); + assert_eq!(lightcraft_meta::extract(&bytes), lightcraft_meta::Metadata::default(), "ordinary extraction stays best-effort"); + std::fs::write(&path, bytes).unwrap(); + + let mut session = Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let id = session.catalog.photos().next().unwrap().id; + let err = export_photo(&mut session, id, &ExportOptions::from_json(&json!({"format": "original", "removeLocation": true})), 1).err().unwrap(); + assert!(err.contains("can't verify location metadata") && err.contains("malformed PSD/PSB"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn remove_location_refuses_a_psd_with_invalid_utf8_xmp() { + let dir = temp_dir("export-noloc-psd-invalid-utf8"); + let path = dir.join("Invalid.psd"); + let gps = lightcraft_meta::Metadata { gps: Some(lightcraft_meta::Gps { latitude: 45.0, longitude: 7.0, altitude: None }), ..Default::default() }; + let xmp = lightcraft_meta::write_xmp(&gps, None); + let pixels = [40, 80, 120]; + let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U8(&pixels)); + let embedded = lightcraft_codecs::EncodeMeta { xmp: Some(&xmp), ..Default::default() }; + let mut bytes = lightcraft_codecs::encode_psd(&image, &embedded).unwrap(); + assert_eq!(lightcraft_meta::extract(&bytes).gps, gps.gps); + let latitude = bytes.windows(2).position(|bytes| bytes == b"45").unwrap(); + bytes[latitude] = 0xff; + assert!(lightcraft_meta::extract(&bytes).gps.is_none()); + std::fs::write(&path, bytes).unwrap(); + + let mut session = Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let id = session.catalog.photos().next().unwrap().id; + let err = export_photo(&mut session, id, &ExportOptions::from_json(&json!({"format": "original", "removeLocation": true})), 1).err().unwrap(); + assert!(err.contains("can't verify location metadata") && err.contains("malformed PSD/PSB"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn remove_location_refuses_a_psd_with_unreadable_resources() { + let dir = temp_dir("export-noloc-psd-malformed"); + let gps = lightcraft_meta::Metadata { gps: Some(lightcraft_meta::Gps { latitude: 45.0, longitude: 7.0, altitude: None }), ..Default::default() }; + let path = dir.join("Geo.psd"); + let valid_bytes = synthetic_psd_with_metadata(&gps); + assert_eq!(lightcraft_meta::extract(&valid_bytes).gps, gps.gps, "the fixture embeds EXIF GPS before corruption"); + let mut bytes = valid_bytes; + let colour_length = usize::try_from(u32::from_be_bytes(bytes[26..30].try_into().unwrap())).unwrap(); + let resource_length_at = 30 + colour_length; + let resource_length = usize::try_from(u32::from_be_bytes(bytes[resource_length_at..resource_length_at + 4].try_into().unwrap())).unwrap(); + let resource_start = resource_length_at + 4; + let resource_end = resource_start + resource_length; + bytes.splice(resource_end..resource_end, *b"BAD!"); + bytes[resource_length_at..resource_length_at + 4].copy_from_slice(&u32::try_from(resource_length + 4).unwrap().to_be_bytes()); + + assert!(lightcraft_meta::extract(&bytes).gps.is_none(), "the malformed trailing resource reproduces the metadata gap"); + std::fs::write(&path, bytes).unwrap(); + let mut session = Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let id = session.catalog.photos().next().unwrap().id; + let err = export_photo(&mut session, id, &ExportOptions::from_json(&json!({"format": "original", "removeLocation": true})), 1).err().unwrap(); + assert!(err.contains("can't verify location metadata") && err.contains("malformed PSD/PSB"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn hdr_png_export_is_16_bit_pq_rec2020() { let mut s = Session::with_demo(); diff --git a/crates/engine/src/tests_hold_view.rs b/crates/engine/src/tests_hold_view.rs index f7082498c9..f30d08c4e0 100644 --- a/crates/engine/src/tests_hold_view.rs +++ b/crates/engine/src/tests_hold_view.rs @@ -1,11 +1,28 @@ //! A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop //! matching a smart album's rules, Picks or the filter bar leaves it where it is, and the others where they are. -use lightcraft_catalog::PhotoId; +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; use serde_json::json; use crate::{LibrarySource, Session}; +fn relative_clock_session(captures: &[&str]) -> (Session, std::sync::Arc<std::sync::Mutex<String>>, Vec<PhotoId>) { + let mut s = Session::new(); + let now = std::sync::Arc::new(std::sync::Mutex::new("2026-10-24T12:00:00".to_string())); + let clock = now.clone(); + s.clock = Box::new(move || clock.lock().unwrap().clone()); + let mut ids = Vec::new(); + for (index, captured) in captures.iter().enumerate() { + let id = PhotoId(index as u64 + 1); + let name = format!("synthetic-{index}.jpg"); + let mut photo = Photo::new(id, Source::Demo { scene: 0 }, &name, "JPEG", 2, 2, "2026-10-01T00:00:00"); + photo.captured = Some((*captured).to_string()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + ids.push(id); + } + (s, now, ids) +} + /// The demo library with no photo keyworded, showing a smart album of the photos without keywords, at random. fn unkeyworded() -> Session { let mut s = Session::with_demo(); @@ -198,3 +215,29 @@ fn asking_for_the_state_it_has_changes_nothing_and_a_word_is_not_a_bool() { assert!(s.execute("library.holdView", &json!({"on": "false"})).is_err()); assert!(s.hold_view, "a refused call changes nothing"); } + +#[test] +fn relative_clock_held_view_keeps_expired_photos_admits_new_matches_and_refreshes() { + let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30", "2026-10-22T12:00:30"]); + let rules = json!({ + "ruleSet": { + "match": "any", + "rules": [ + {"field": "captureDate", "op": "inLast", "value": 1}, + {"field": "captureDate", "op": "notInLast", "value": 2} + ] + } + }); + s.execute("library.filter", &rules).unwrap(); + s.execute("library.holdView", &json!({"on": true})).unwrap(); + assert_eq!(s.visible_cloned(), vec![ids[0]], "only the soon-to-expire photo matches initially"); + + *now.lock().unwrap() = "2026-10-24T12:01:00".to_string(); + let held = s.visible_cloned(); + assert_eq!(held.len(), 2, "the expired photo stays held while the newly matching photo enters: {held:?}"); + assert!(held.contains(&ids[0]), "the expired photo remains held"); + assert!(held.contains(&ids[1]), "the photo crossing the second relative boundary enters"); + + s.execute("library.refresh", &json!({})).unwrap(); + assert_eq!(s.visible_cloned(), vec![ids[1]], "explicit refresh releases the expired photo"); +} diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 191595ebef..6e5585a823 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -263,6 +263,70 @@ fn find_missing_plan_is_rechecked_when_applied() { let _ = std::fs::remove_dir_all(&dir); } +/// A library made on Windows names its originals with Windows paths; opened on macOS or Linux +/// they are missing until Find Missing finds them by name, there as everywhere: the name follows +/// the last `/` or `\`, any letter case, the size checked when one is on record, look-alikes +/// reported rather than guessed, and undo puts back the path exactly as spelled. +#[test] +fn find_missing_finds_the_files_of_a_library_made_on_windows() { + use lightcraft_catalog::{Op, Photo, PhotoId, Source}; + let dir = temp_dir("missing-windows"); + for (rel, bytes) in [("found/a.jpg", &b"x"[..]), ("found/deep/b.jpg", b"xyz"), ("found/one/twin.jpg", b"x"), ("found/two/twin.jpg", b"x")] { + std::fs::create_dir_all(dir.join(rel).parent().unwrap()).unwrap(); + std::fs::write(dir.join(rel), bytes).unwrap(); + } + let mut s = Session::new(); + // as a Windows library may list them: no content hash, and a size only for b + let mut add = |path: &str, size: u64| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + p.file_size = size; + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let (a, b, twin) = (add(r"C:\Users\me\Photos\a.jpg", 0), add(r"D:\Shoot\2019\B.JPG", 3), add(r"C:\Users\me\Photos\twin.jpg", 0)); + let path_of = |s: &Session, id: PhotoId| match &s.catalog.photo(id).unwrap().source { + Source::File { path } => path.clone(), + _ => String::new(), + }; + let r = s.execute("library.findMissing", &json!({"folder": dir.join("found").to_string_lossy()})).unwrap(); + assert_eq!(path_of(&s, a), dir.join("found").join("a.jpg").to_string_lossy(), "found by its name: {r}"); + assert_eq!(path_of(&s, b), dir.join("found").join("deep").join("b.jpg").to_string_lossy(), "found by its name, any case, and size: {r}"); + assert_eq!(path_of(&s, twin), r"C:\Users\me\Photos\twin.jpg", "two files of its name: not guessed: {r}"); + assert_eq!(r["ambiguous"][0]["candidates"].as_array().map(Vec::len), Some(2), "both look-alikes reported: {r}"); + assert_eq!(r["missing"], 1, "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!( + (path_of(&s, a), path_of(&s, b)), + (r"C:\Users\me\Photos\a.jpg".to_string(), r"D:\Shoot\2019\B.JPG".to_string()), + "one undo step puts back the Windows paths as they were spelled" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// On macOS and Linux `\` may be part of a file name. Find Missing names the files it finds by +/// the same rule as the missing photos, so `a\b.jpg` isn't relinked to a `b.jpg` beside it +/// unasked: the two are reported as look-alikes. +#[cfg(unix)] +#[test] +fn find_missing_does_not_take_a_look_alike_for_a_file_name_with_a_backslash() { + use lightcraft_catalog::{Op, Photo, Source}; + let dir = temp_dir("missing-backslash"); + std::fs::create_dir_all(dir.join("found")).unwrap(); + for name in [r"a\b.jpg", "b.jpg"] { + std::fs::write(dir.join("found").join(name), b"x").unwrap(); + } + let mut s = Session::new(); + let gone = dir.join("gone").join(r"a\b.jpg").to_string_lossy().to_string(); + let id = s.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: gone.clone() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let r = s.execute("library.findMissing", &json!({"folder": dir.join("found").to_string_lossy()})).unwrap(); + assert!(matches!(&s.catalog.photo(id).unwrap().source, Source::File { path } if *path == gone), "not relinked to b.jpg: {r}"); + assert_eq!(r["ambiguous"][0]["candidates"].as_array().map(Vec::len), Some(2), "both reported: {r}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn missing_files_are_found_and_relinked() { let dir = std::env::temp_dir().join(format!("lc-missing-{}", std::process::id())); @@ -1004,6 +1068,54 @@ fn assisted_culling_groups_bursts_across_month_end() { let _ = std::fs::remove_dir_all(&dir); } +/// Assisted culling: `burstGap` and `similarity` move the burst limits (#2275), and values out of +/// range are refused before anything is measured or stored. +#[test] +fn assisted_culling_burst_limits_are_adjustable() { + let dir = temp_dir("cull-limits"); + for (name, (w, h)) in [("a.png", (480, 320)), ("b.png", (482, 321))] { + let img = lightcraft_scenes::demo_library()[0].render(w, h); + let data: Vec<[u8; 4]> = img + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(dir.join(name), png).unwrap(); + } + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let ids: Vec<u64> = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).collect(); + let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + let (a, b) = (by_name(&s, "a.png"), by_name(&s, "b.png")); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id: a, captured: Some("2026-05-01T10:00:00".into()) }).unwrap(); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id: b, captured: Some("2026-05-01T10:00:15".into()) }).unwrap(); + // 15 s apart: past the default 10 s, inside a 20 s gap + assert_eq!(s.execute("photo.analyze", &json!({"ids": ids})).unwrap()["groups"], 0); + assert_eq!(s.execute("photo.analyze", &json!({"ids": ids, "burstGap": 20})).unwrap()["groups"], 1); + // the look-alike pair is a burst at the default similarity, not when it must be identical + let strict = s.execute("photo.analyze", &json!({"ids": ids, "burstGap": 20, "similarity": 1.0})).unwrap(); + assert_eq!(strict["groups"], 0, "{strict}"); + // bad values change nothing + let undo_before = s.commits(); + for bad in + [json!({"burstGap": -1}), json!({"burstGap": 86401}), json!({"burstGap": "10"}), json!({"similarity": 1.5}), json!({"similarity": -0.1})] + { + let mut p = bad.clone(); + p["ids"] = json!(ids); + assert!(s.execute("photo.analyze", &p).is_err(), "{bad} must be refused"); + } + assert_eq!(s.commits(), undo_before); + let _ = std::fs::remove_dir_all(&dir); +} + /// Find Dust Spots: soft dark spots on a smooth sky are found and healed (one undo step). #[test] fn dust_spots_are_found_and_healed() { diff --git a/crates/engine/src/tests_keyword_list.rs b/crates/engine/src/tests_keyword_list.rs index b98b45de8d..94ff599887 100644 --- a/crates/engine/src/tests_keyword_list.rs +++ b/crates/engine/src/tests_keyword_list.rs @@ -263,6 +263,29 @@ fn set_names_match_whatever_their_case() { assert!(set_named(&mut s, "ÉTÉ").is_null(), "deleted"); } +/// Next / Previous Keyword Set (⌥0 / ⌥⇧0) step through the sets in the Keyword Set menu's order, +/// Recent Keywords first, and wrap around at either end; with no saved sets they stay on Recent +/// Keywords. +#[test] +fn next_and_previous_keyword_set_wrap_around_the_sets() { + let mut s = Session::with_demo(); + let current = |r: serde_json::Value| r["current"].as_str().unwrap_or_default().to_string(); + assert_eq!(current(s.execute("keyword.nextSet", &json!({})).unwrap()), "Recent Keywords", "no sets: nothing to go to"); + assert_eq!(current(s.execute("keyword.previousSet", &json!({})).unwrap()), "Recent Keywords"); + s.execute("keyword.saveSet", &json!({"name": "Weddings", "keywords": ["ceremony"]})).unwrap(); + s.execute("keyword.saveSet", &json!({"name": "Travel", "keywords": ["harbor"]})).unwrap(); + s.execute("keyword.useSet", &json!({"name": "Recent Keywords"})).unwrap(); + let forward: Vec<String> = (0..3).map(|_| current(s.execute("keyword.nextSet", &json!({})).unwrap())).collect(); + assert_eq!(forward, ["Weddings", "Travel", "Recent Keywords"]); + let back: Vec<String> = (0..3).map(|_| current(s.execute("keyword.previousSet", &json!({})).unwrap())).collect(); + assert_eq!(back, ["Travel", "Weddings", "Recent Keywords"]); + let r = s.execute("keyword.nextSet", &json!({})).unwrap(); + assert_eq!(r["keywords"], json!(["ceremony"]), "⌥1–⌥9 now apply the set's keywords"); + // a current set that is no longer there counts as Recent Keywords + s.keyword_set = Some("Gone".into()); + assert_eq!(current(s.execute("keyword.nextSet", &json!({})).unwrap()), "Weddings"); +} + /// Export Keywords writes the keyword list file, and names the keywords Capture One's importer /// refuses (it allows none of ; , < > in a list); without a path it gives the text. #[test] diff --git a/crates/engine/src/tests_library.rs b/crates/engine/src/tests_library.rs index 5460dc0207..b2eb8cb949 100644 --- a/crates/engine/src/tests_library.rs +++ b/crates/engine/src/tests_library.rs @@ -314,6 +314,29 @@ fn smart_album_rule_sets() { assert!(a.to_string().contains("rating is ≥ 4"), "{a}"); } +/// `label` and `labels` set together (only through `library.filter`, or a filter saved with the +/// single label) AND, and the chip says what they let through, not their union. +#[test] +fn filter_label_and_labels_together_chip() { + use lightcraft_catalog::ColorLabel; + let mut s = crate::Session::with_demo(); + let ids: Vec<u64> = s.catalog.photos().take(3).map(|p| p.id.0).collect(); + for (id, l) in ids.iter().zip(["red", "yellow", "green"]) { + s.execute("photo.label", &json!({"ids": [id], "label": l})).unwrap(); + } + let reds = s.catalog.photos().filter(|p| p.in_library() && p.label == Some(ColorLabel::Red)).count(); + let chip = |s: &Session| crate::filter_chips(&s.filter, &s.catalog).into_iter().find(|c| c.label.starts_with("Label")).expect("a label chip"); + s.execute("library.filter", &json!({"label": "red", "labels": ["yellow", "red"]})).unwrap(); + assert_eq!(s.visible_cloned().len(), reds); + assert_eq!(chip(&s).label, "Label: Red"); + // nothing passes both: the chip names both constraints + s.execute("library.filter", &json!({"label": "red", "labels": ["yellow", "green"]})).unwrap(); + assert_eq!(s.visible_cloned().len(), 0); + assert_eq!(chip(&s).label, "Label: Red and (Yellow or Green)"); + s.execute("library.filter", &chip(&s).clear).unwrap(); + assert_eq!((s.filter.label, s.filter.labels.len()), (None, 0)); +} + /// The filter bar's label multi-select: any of the chosen labels. #[test] fn filter_any_of_several_labels() { @@ -514,6 +537,61 @@ fn capture_time_shift_is_bounded() { assert_eq!(s.catalog.photo(id).unwrap().captured.as_deref(), Some("9999-12-31T12:00:00"), "unchanged"); } +/// A capture time that doesn't fully read (a Lightroom catalog's `captureTime` is copied +/// verbatim) is left as it is and counted, not shifted into a clean-looking wrong time, and it +/// isn't mistaken for one that would leave years 0000–9999. +#[test] +fn capture_time_shift_counts_photos_whose_time_does_not_read() { + let mut s = crate::Session::with_demo(); + let ids: Vec<_> = s.catalog.photos().take(2).map(|p| p.id).collect(); + let (good, bad) = (ids[0], ids[1]); + for (id, t) in [(good, "2026-01-01T10:00:00"), (bad, "2026-01-01T10:00:00 and more")] { + s.catalog.apply(lightcraft_catalog::Op::SetCaptured { id, captured: Some(t.into()) }).unwrap(); + } + let r = s.execute("photo.setCaptureTime", &serde_json::json!({"ids": [good.0, bad.0], "hours": 1})).unwrap(); + assert_eq!(r["unreadable"], 1, "the unreadable photo is counted: {r}"); + assert_eq!(r["changed"], 1, "{r}"); + let captured = |s: &crate::Session, id| s.catalog.photo(id).unwrap().captured.clone(); + assert_eq!(captured(&s, good).as_deref(), Some("2026-01-01T11:00:00")); + assert_eq!(captured(&s, bad).as_deref(), Some("2026-01-01T10:00:00 and more"), "left as it was"); + s.execute("edit.undo", &serde_json::json!({})).unwrap(); + assert_eq!(captured(&s, good).as_deref(), Some("2026-01-01T10:00:00"), "one undo step"); + // a shift past year 9999 for the readable photo is still the out-of-range refusal, and the + // unreadable one alone isn't + let r = s.execute("photo.setCaptureTime", &serde_json::json!({"ids": [bad.0], "hours": 24 * 365 * 9000})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["unreadable"].as_u64()), (Some(0), Some(1)), "{r}"); + let r = s.execute("photo.setCaptureTime", &serde_json::json!({"ids": [good.0, bad.0], "hours": 24 * 365 * 9000})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("1 photo(s) outside")), "{r:?}"); +} + +/// Setting the active photo's time moves the others by its change, so an active photo whose own +/// time doesn't read can't anchor it: refused, nothing changes. Alone, or setting every photo's +/// time, it gets the time, which repairs it. +#[test] +fn capture_time_set_refuses_an_active_photo_whose_time_does_not_read() { + let mut s = crate::Session::with_demo(); + let ids: Vec<_> = s.catalog.photos().take(2).map(|p| p.id).collect(); + let (bad, other) = (ids[0], ids[1]); + let broken = "2026-01-01T10:00:00 and more"; + for (id, t) in [(bad, broken), (other, "2026-01-01T12:00:00")] { + s.catalog.apply(lightcraft_catalog::Op::SetCaptured { id, captured: Some(t.into()) }).unwrap(); + } + s.execute("library.select", &serde_json::json!({"ids": [bad.0, other.0], "active": bad.0})).unwrap(); + assert_eq!(s.active(), Some(bad)); + let captured = |s: &crate::Session, id| s.catalog.photo(id).unwrap().captured.clone(); + let r = s.execute("photo.setCaptureTime", &serde_json::json!({"ids": [bad.0, other.0], "time": "2026-01-01T11:00:00"})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("can't be read")), "{r:?}"); + assert_eq!(captured(&s, bad).as_deref(), Some(broken), "refused: unchanged"); + assert_eq!(captured(&s, other).as_deref(), Some("2026-01-01T12:00:00"), "refused: the others don't move"); + let r = s.execute("photo.setCaptureTime", &serde_json::json!({"ids": [bad.0], "time": "2026-01-01T11:00:00"})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["unreadable"].as_u64()), (Some(1), Some(0)), "{r}"); + assert_eq!(captured(&s, bad).as_deref(), Some("2026-01-01T11:00:00"), "alone, it gets the time"); + s.catalog.apply(lightcraft_catalog::Op::SetCaptured { id: bad, captured: Some(broken.into()) }).unwrap(); + let r = s.execute("photo.setCaptureTime", &serde_json::json!({"ids": [bad.0, other.0], "time": "2026-01-01T11:00:00", "each": true})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["unreadable"].as_u64()), (Some(2), Some(0)), "{r}"); + assert_eq!(captured(&s, bad).as_deref(), Some("2026-01-01T11:00:00"), "each repairs it"); +} + /// Values are checked too: an agent's rule set with a date that isn't one, or a rating of 9, is /// refused with the rule's position, by album.createSmart and library.filter alike. #[test] diff --git a/crates/engine/src/tests_prefs.rs b/crates/engine/src/tests_prefs.rs index 4c9d9582da..c0ded23ddb 100644 --- a/crates/engine/src/tests_prefs.rs +++ b/crates/engine/src/tests_prefs.rs @@ -403,7 +403,7 @@ fn slideshow_playback_settings_persist_with_the_library() { let r = s .execute( "slideshow.playback", - &json!({"slideDuration": 6, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false}), + &json!({"slideDuration": 6, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "manual": true}), ) .unwrap(); assert_eq!(r["fadeColor"], "#000000"); @@ -417,7 +417,7 @@ fn slideshow_playback_settings_persist_with_the_library() { let r = s.execute("slideshow.playback", &json!({})).unwrap(); assert_eq!( r, - json!({"slideDuration": 6.0, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "preparePreviews": true}) + json!({"slideDuration": 6.0, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "preparePreviews": true, "manual": true}) ); drop(s); // out-of-range values written by hand are clamped when the library opens diff --git a/crates/engine/src/tests_print.rs b/crates/engine/src/tests_print.rs index 898faa8899..5a35adb5ba 100644 --- a/crates/engine/src/tests_print.rs +++ b/crates/engine/src/tests_print.rs @@ -14,6 +14,24 @@ fn fails(s: &mut Session, id: &str, p: Value) -> String { s.execute(id, &p).expect_err(&format!("{id} {p} should fail")).to_string() } +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lightcraft-print-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + fn package(s: &mut Session) { run(s, "print.set", json!({"layout": {"style": "customPackage", "page": {"paper": "letter"}}})); } @@ -26,7 +44,13 @@ fn get_set_and_reset() { assert_eq!(g["pageWidth"], 8.5); assert_eq!(g["printable"]["x"], 0.25); assert_eq!(g["settings"]["job"]["ppi"], 240.0); - assert!(g["papers"].as_array().unwrap().iter().any(|p| p["name"] == "a4")); + let papers = g["papers"].as_array().unwrap(); + assert!(papers.iter().any(|p| p["name"] == "a4")); + // The Japanese photo and postcard papers are listed with their metric sizes in inches. + let paper = |name: &str| papers.iter().find(|p| p["name"] == name).cloned().unwrap_or_else(|| panic!("{name}")); + let l = paper("l"); + assert!((l["width"].as_f64().unwrap() - 89.0 / 25.4).abs() < 1e-9 && (l["height"].as_f64().unwrap() - 127.0 / 25.4).abs() < 1e-9); + assert!(papers.iter().any(|p| p["name"] == "postcard") && papers.iter().any(|p| p["name"] == "6cut")); assert_eq!(g["gridCells"].as_array().unwrap().len(), 1); let g = run( @@ -213,6 +237,28 @@ fn export_pdf_prints_the_current_settings() { fails(&mut s, "print.exportPdf", json!({"path": path, "ids": ids})); } +/// The Japanese photo and postcard papers reach the PDF page at their metric sizes: はがき is +/// 100 × 148 mm (283.46 × 419.53 pt) and L is 89 × 127 mm (252.28 × 359.99 pt). 254 ppi is exactly +/// ten pixels per millimetre, so the page pixels are whole millimetres and the MediaBox is exact. +#[test] +fn export_pdf_uses_the_japanese_paper_sizes() { + let mut s = Session::with_demo(); + let id = s.catalog.photos().next().map(|p| p.id.0).unwrap(); + for (paper, w_pt, h_pt) in [("postcard", 283.46, 419.53), ("はがき", 283.46, 419.53), ("l", 252.28, 359.99)] { + run(&mut s, "print.set", json!({"layout": {"style": "singleImage", "page": {"paper": paper}}, "job": {"ppi": 254.0}})); + let path = temp_pdf(paper); + run(&mut s, "print.exportPdf", json!({"path": path, "ids": [id]})); + let bytes = std::fs::read(&path).unwrap(); + let (w, h) = media_box(&bytes); + assert!((w - w_pt).abs() < 0.1 && (h - h_pt).abs() < 0.1, "{paper}: {w} x {h} pt, wanted {w_pt} x {h_pt}"); + } + // The customary names are accepted and the page size follows them; an unknown name is refused. + let g = run(&mut s, "print.set", json!({"layout": {"page": {"paper": "はがき"}}})); + assert!((g["pageWidth"].as_f64().unwrap() - 100.0 / 25.4).abs() < 1e-9); + assert!((g["pageHeight"].as_f64().unwrap() - 148.0 / 25.4).abs() < 1e-9); + fails(&mut s, "print.set", json!({"layout": {"page": {"paper": "poster"}}})); +} + #[test] fn export_pdf_with_a_printer_profile() { let mut s = Session::with_demo(); @@ -295,6 +341,125 @@ fn templates_save_apply_delete_and_persist() { assert!(run(&mut open(&files), "print.template.list", json!({}))["templates"].as_array().unwrap().is_empty()); } +#[test] +fn templates_export_to_a_file_and_import_from_one() { + let files = MemStore::new(); + let open = |files: &MemStore| { + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + s + }; + let scratch = Scratch::new("templates"); + let dir = &scratch.0; + let mut s = open(&files); + run(&mut s, "print.set", json!({"layout": {"style": "contactSheet", "grid": {"columns": 3, "rows": 4}}, "page": {"background": [5, 6, 7]}})); + run(&mut s, "print.template.save", json!({"name": "Proofs"})); + + // the extension is added when the path has none + let r = run(&mut s, "print.template.export", json!({"name": "proofs", "path": dir.join("proofs").to_string_lossy()})); + assert_eq!(r["name"], "Proofs"); + let file = dir.join("proofs.lcprint"); + assert_eq!(r["path"], file.to_string_lossy().as_ref()); + let doc: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!((doc["format"].as_str(), doc["version"].as_u64(), doc["name"].as_str()), (Some("lightcraft.printTemplate"), Some(1), Some("Proofs"))); + + // into the same library: the name is taken, so the copy is renamed + let r = run(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})); + assert_eq!((r["name"].as_str(), r["renamed"].as_bool()), (Some("Proofs (2)"), Some(true)), "{r}"); + assert_eq!(r["templates"].as_array().unwrap().len(), 2); + assert_eq!(r["templates"][1]["settings"], r["templates"][0]["settings"]); + + // into another library, under its own name, and it is kept there + let other = MemStore::new(); + let mut b = open(&other); + let r = run(&mut b, "print.template.import", json!({"path": file.to_string_lossy()})); + assert_eq!((r["name"].as_str(), r["renamed"].as_bool()), (Some("Proofs"), Some(false))); + let g = run(&mut open(&other), "print.template.apply", json!({"name": "Proofs"})); + assert_eq!(g["settings"]["layout"]["grid"]["columns"], 3); + assert_eq!(g["settings"]["page"]["background"], json!([5, 6, 7])); + + // refusals leave the templates as they were + let bad_file = dir.join("bad.lcprint"); + std::fs::write(&bad_file, br#"{"format": "lightcraft.printTemplate", "version": 1, "name": "Bad", "settings": {"layout": {"pages": 0}}}"#) + .unwrap(); + let huge = dir.join("huge.lcprint"); + std::fs::write(&huge, vec![b' '; crate::print::template::MAX_FILE as usize + 1]).unwrap(); + for (p, why) in [ + (json!({}), "missing `path`"), + (json!({"path": " "}), "missing `path`"), + (json!({"path": dir.join("absent.lcprint").to_string_lossy()}), "absent.lcprint"), + (json!({"path": dir.to_string_lossy()}), "not a file"), + (json!({"path": huge.to_string_lossy()}), "too large"), + (json!({"path": bad_file.to_string_lossy()}), "template `Bad`"), + ] { + let e = fails(&mut s, "print.template.import", p.clone()); + assert!(e.contains(why), "{p}: {e}"); + } + assert_eq!(run(&mut s, "print.template.list", json!({}))["templates"].as_array().unwrap().len(), 2); + assert!(fails(&mut s, "print.template.export", json!({"name": "Nope", "path": dir.join("x").to_string_lossy()})).contains("no print template")); + assert!(fails(&mut s, "print.template.export", json!({"name": "Proofs"})).contains("missing `path`")); + assert!(fails(&mut s, "print.template.export", json!({"path": dir.join("x").to_string_lossy()})).contains("missing `name`")); + assert!(!dir.join("x.lcprint").exists()); + + // a full list takes no more + while s.print_templates.len() < crate::print::template::MAX_TEMPLATES { + let n = s.print_templates.len(); + run(&mut s, "print.template.save", json!({"name": format!("T{n}")})); + } + assert!(fails(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})).contains("at most")); +} + +/// A library whose `prefs.json` can't be read, so saving the preferences fails. +#[derive(Clone, Default)] +struct PrefsUnreadable(MemStore); + +impl lightcraft_catalog::Store for PrefsUnreadable { + fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> { + if name == "prefs.json" { + return Err(std::io::Error::other("locked by another process")); + } + self.0.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.0.truncate(name, len) + } + fn describe(&self) -> String { + "prefs unreadable".into() + } +} + +#[test] +fn template_changes_that_cant_be_saved_are_undone() { + let mut s = Session::with_demo(); + let stores = + LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(PrefsUnreadable::default()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + s.print_templates.push(crate::print::template::PrintTemplate::new("Proofs", &s.print).unwrap()); + let names = |s: &Session| s.print_templates.iter().map(|t| (t.name.clone(), t.settings.clone())).collect::<Vec<_>>(); + let kept = names(&s); + let scratch = Scratch::new("unsaved"); + let file = scratch.0.join("proofs.lcprint"); + run(&mut s, "print.template.export", json!({"name": "Proofs", "path": file.to_string_lossy()})); + + run(&mut s, "print.set", json!({"layout": {"style": "contactSheet"}})); + for (id, p) in [ + ("print.template.save", json!({"name": "Other"})), + ("print.template.save", json!({"name": "proofs"})), + ("print.template.delete", json!({"name": "Proofs"})), + ("print.template.import", json!({"path": file.to_string_lossy()})), + ] { + assert!(fails(&mut s, id, p.clone()).contains("prefs.json"), "{id} {p}"); + assert_eq!(names(&s), kept, "{id} {p}"); + } +} + #[test] fn a_hostile_template_in_the_preferences_does_not_break_the_library() { let files = MemStore::new(); @@ -336,6 +501,8 @@ fn every_print_command_is_registered_with_a_description() { "print.template.save", "print.template.apply", "print.template.delete", + "print.template.export", + "print.template.import", ] { let c = crate::find_command(id).unwrap_or_else(|| panic!("{id} missing")); assert!(c.params.len() > 3, "{id}"); diff --git a/crates/engine/src/tests_segment.rs b/crates/engine/src/tests_segment.rs index f4b9f4f484..ceb2365fbe 100644 --- a/crates/engine/src/tests_segment.rs +++ b/crates/engine/src/tests_segment.rs @@ -77,16 +77,23 @@ fn status_and_model_commands_without_the_model() { #[test] fn a_failing_download_ends_with_an_error_and_never_blocks() { use std::io::{BufRead, BufReader, Write}; - // a local mirror that has nothing + // a local mirror that has nothing; its first answer waits until the test has made its second + // request, so the download is still running then however the threads are scheduled (a 404 at + // once could end it before, and the second request would rightly start a new one) let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}/sam3", l.local_addr().unwrap()); + let (release, released) = std::sync::mpsc::channel::<()>(); std::thread::spawn(move || { + let mut first = Some(released); for mut c in l.incoming().flatten() { let mut r = BufReader::new(c.try_clone().unwrap()); let mut line = String::new(); while r.read_line(&mut line).unwrap_or(0) > 2 { line.clear(); } + if let Some(released) = first.take() { + let _ = released.recv_timeout(Duration::from_secs(10)); + } let _ = c.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 13\r\nConnection: close\r\n\r\n<h1>404</h1>\n"); } }); @@ -103,6 +110,7 @@ fn a_failing_download_ends_with_an_error_and_never_blocks() { // a second request while it runs starts nothing let again = s.execute("segment.model.download", &json!({"acknowledged": true})).unwrap(); assert!(again["started"] == false || again["downloading"] == false); + let _ = release.send(()); let t = Instant::now(); while s.segmenter.download_status().running { assert!(t.elapsed() < Duration::from_secs(30), "the download never ended"); diff --git a/crates/engine/src/tests_sync.rs b/crates/engine/src/tests_sync.rs index 88c1843356..8b1ec4f672 100644 --- a/crates/engine/src/tests_sync.rs +++ b/crates/engine/src/tests_sync.rs @@ -739,3 +739,21 @@ fn a_cancelled_scan_does_not_check_the_cached_probes_against_the_disk() { let new = out.candidates.iter().find(|c| c.name == "new.png").expect("new.png is a candidate"); assert!(new.error.is_some(), "the cached probe was used after ✕: {new:?}"); } + +#[test] +fn removing_missing_photos_takes_them_out_of_their_stacks() { + let dir = Scratch::new("remove-stacked"); + let mut s = library(&dir); + let id = |s: &Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().id; + let (a, b) = (id(&s, "a.png"), id(&s, "b.png")); + let group = s.catalog.group_ops(a, &[b], true).unwrap(); + s.catalog.apply(group).unwrap(); + assert!(s.catalog.stack_of(b).is_some()); + std::fs::remove_file(dir.path("trip/day1/b.png")).unwrap(); + let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "removeMissing": true})).unwrap(); + assert_eq!(r["removed"].as_u64(), Some(1), "{r}"); + assert!(s.catalog.photo(b).unwrap().deleted); + assert!(s.catalog.stack_of(b).is_none(), "like photo.delete, a removed photo leaves its stack: {:?}", s.catalog.stack_of(b)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.stack_of(b).is_some(), "one undo step puts b back in its stack"); +} diff --git a/crates/engine/src/tests_view_follow.rs b/crates/engine/src/tests_view_follow.rs index 391e38b3b5..bc47d94c94 100644 --- a/crates/engine/src/tests_view_follow.rs +++ b/crates/engine/src/tests_view_follow.rs @@ -1,7 +1,7 @@ //! The view follows a small edit from the list it had ([`Session::visible`]): whatever the edit, the result has to //! be the list worked out from every photo. -use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use lightcraft_catalog::{Album, Op, Photo, PhotoId, Source}; use serde_json::{Value, json}; use crate::Session; @@ -113,6 +113,23 @@ fn edit(s: &mut Session, dice: &mut Dice, ids: &mut Vec<PhotoId>, album: u64) { }; } +fn relative_clock_session(captures: &[&str]) -> (Session, std::sync::Arc<std::sync::Mutex<String>>, Vec<PhotoId>) { + let mut s = Session::new(); + let now = std::sync::Arc::new(std::sync::Mutex::new("2026-10-24T12:00:00".to_string())); + let clock = now.clone(); + s.clock = Box::new(move || clock.lock().unwrap().clone()); + let mut ids = Vec::new(); + for (index, captured) in captures.iter().enumerate() { + let id = PhotoId(index as u64 + 1); + let name = format!("synthetic-{index}.jpg"); + let mut photo = Photo::new(id, Source::Demo { scene: 0 }, &name, "JPEG", 2, 2, "2026-10-01T00:00:00"); + photo.captured = Some((*captured).to_string()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + ids.push(id); + } + (s, now, ids) +} + #[test] fn following_an_edit_gives_the_list_worked_out_from_every_photo() { let (mut s, mut ids, album, smart) = library(240); @@ -161,6 +178,129 @@ fn following_an_edit_gives_the_list_worked_out_from_every_photo() { assert!(s.view_followed > 400, "followed {} times, worked out {} times", s.view_followed, s.view_worked_out); } +#[test] +fn relative_clock_filter_expires_without_catalog_or_history_mutation() { + let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30"]); + s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}})).unwrap(); + let (before_generation, before) = s.visible_shared(); + assert_eq!(before.as_ref(), ids.as_slice()); + let revision = s.catalog.revision; + let commits = s.commits; + let undo = s.undo.len(); + let redo = s.redo.len(); + + *now.lock().unwrap() = "2026-10-24T12:01:00".to_string(); + let (after_generation, after) = s.visible_shared(); + + assert!(after.is_empty(), "a relative filter must expire when its minute changes"); + assert_ne!(after_generation, before_generation, "the changed list gets a new visible generation"); + assert_eq!(s.catalog.revision, revision, "clock expiry is not a catalog edit"); + assert_eq!(s.commits, commits, "clock expiry adds no undo step"); + assert_eq!(s.undo.len(), undo); + assert_eq!(s.redo.len(), redo); +} + +#[test] +fn relative_clock_direct_and_nested_smart_album_sources_expire() { + for nested in [false, true] { + let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30"]); + let recent = s + .execute( + "album.createSmart", + &json!({"name": "Recent", "rules": {"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + let source = if nested { + s.execute( + "album.createSmart", + &json!({"name": "In Recent", "rules": {"ruleSet": {"rules": [{"field": "album", "op": "is", "value": recent}]}}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap() + } else { + recent + }; + s.execute("library.source", &json!({"kind": "album", "id": source})).unwrap(); + assert_eq!(s.visible_cloned(), ids); + let revision = s.catalog.revision; + + *now.lock().unwrap() = "2026-10-24T12:01:00".to_string(); + assert!(s.visible_cloned().is_empty(), "nested={nested}"); + assert_eq!(s.catalog.revision, revision, "nested={nested}"); + } +} + +#[test] +fn relative_clock_source_total_expires_before_or_after_visible_refresh() { + for refresh_visible in [false, true] { + let (mut s, now, _) = relative_clock_session(&["2026-10-23T12:00:30"]); + let album = s + .execute( + "album.createSmart", + &json!({"name": "Recent", "rules": {"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": album})).unwrap(); + s.execute("library.filter", &json!({"text": "synthetic"})).unwrap(); + assert_eq!(s.source_total(), Some(1), "the initial total is computed without asking for visible photos"); + let revision = s.catalog.revision; + + *now.lock().unwrap() = "2026-10-24T12:01:00".to_string(); + if refresh_visible { + s.execute("library.refresh", &json!({})).unwrap(); + assert!(s.visible_cloned().is_empty()); + } + assert_eq!(s.source_total(), Some(0), "refresh_visible={refresh_visible}"); + assert_eq!(s.catalog.revision, revision, "refresh_visible={refresh_visible}"); + } +} + +#[test] +fn relative_clock_absolute_and_same_minute_views_keep_their_generations() { + let (mut absolute, absolute_now, _) = relative_clock_session(&["2026-10-23T12:00:30"]); + absolute.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "is", "value": "2026-10-23"}]}})).unwrap(); + let (absolute_generation, absolute_ids) = absolute.visible_shared(); + *absolute_now.lock().unwrap() = "2026-10-25T12:10:00".to_string(); + let (after_absolute_generation, after_absolute_ids) = absolute.visible_shared(); + assert_eq!(after_absolute_generation, absolute_generation); + assert_eq!(after_absolute_ids, absolute_ids); + + let (mut relative, relative_now, _) = relative_clock_session(&["2026-10-23T12:00:30"]); + relative.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}})).unwrap(); + let (relative_generation, relative_ids) = relative.visible_shared(); + *relative_now.lock().unwrap() = "2026-10-24T12:00:45".to_string(); + let (same_minute_generation, same_minute_ids) = relative.visible_shared(); + assert_eq!(same_minute_generation, relative_generation); + assert_eq!(same_minute_ids, relative_ids); +} + +#[test] +fn relative_clock_unrelated_smart_album_does_not_expire_album_filter_view() { + let (mut s, now, ids) = relative_clock_session(&["2026-10-23T12:00:30"]); + let manual = s.catalog.alloc_album_id(); + s.catalog.apply(Op::AddAlbum { album: Album::new(manual, "Manual") }).unwrap(); + s.catalog.apply(Op::SetAlbumPhotos { id: manual, photos: vec![ids[0]] }).unwrap(); + s.execute( + "album.createSmart", + &json!({"name": "Unrelated recent", "rules": {"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": 1}]}}}), + ) + .unwrap(); + s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": manual.0}]}})).unwrap(); + let (generation, visible) = s.visible_shared(); + assert_eq!(visible.as_ref(), ids.as_slice()); + + *now.lock().unwrap() = "2026-10-24T12:01:00".to_string(); + let (after_generation, after_visible) = s.visible_shared(); + + assert_eq!(after_generation, generation, "an unrelated relative smart album must not expire this view"); + assert_eq!(after_visible, visible); +} + #[test] fn a_view_that_asks_about_the_last_days_follows_the_clock_too() { let (mut s, ids, _, _) = library(60); diff --git a/crates/engine/src/tests_xmp.rs b/crates/engine/src/tests_xmp.rs index 1a4d86fa3f..129662e4dc 100644 --- a/crates/engine/src/tests_xmp.rs +++ b/crates/engine/src/tests_xmp.rs @@ -43,6 +43,34 @@ fn write_png(path: &Path, seed: u8) { std::fs::write(path, bytes).unwrap(); } +pub(crate) fn synthetic_psd_with_metadata(metadata: &lightcraft_meta::Metadata) -> Vec<u8> { + let exif = lightcraft_meta::write_exif(metadata); + let xmp = lightcraft_meta::write_xmp(metadata, None); + let pixels = [40, 80, 120]; + let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U8(&pixels)); + let embedded = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: Some(&xmp), ..Default::default() }; + lightcraft_codecs::encode_psd(&image, &embedded).unwrap() +} + +pub(crate) fn synthetic_psb_with_metadata(metadata: &lightcraft_meta::Metadata) -> Vec<u8> { + let exif = lightcraft_meta::write_exif(metadata); + let xmp = lightcraft_meta::write_xmp(metadata, None); + let pixels = [1024u16, 2048, 3072]; + let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U16(&pixels)); + let embedded = lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: Some(&xmp), ..Default::default() }; + let psd = lightcraft_codecs::encode_psd(&image, &embedded).unwrap(); + let colour_length = usize::try_from(u32::from_be_bytes(psd[26..30].try_into().unwrap())).unwrap(); + let resource_length_offset = 30 + colour_length; + let resource_length = usize::try_from(u32::from_be_bytes(psd[resource_length_offset..resource_length_offset + 4].try_into().unwrap())).unwrap(); + let resource_end = resource_length_offset + 4 + resource_length; + + let mut psb = psd[..resource_end].to_vec(); + psb[4..6].copy_from_slice(&2u16.to_be_bytes()); + psb.extend_from_slice(&0u64.to_be_bytes()); // PSB layer and mask information length + psb.extend_from_slice(&psd[resource_end + 4..]); // compression and uncompressed 16-bit pixel planes + psb +} + fn only(s: &Session) -> PhotoId { s.catalog.photos().next().unwrap().id } @@ -1036,10 +1064,21 @@ fn external_edit_copies_every_selected_photo() { fn external_edit_copy_as_psd_round_trips() { let dir = temp_dir("extedit-psd"); let src = dir.join("pier.png"); - write_png(&src, 40); + let capture = lightcraft_meta::DateTime::parse_iso("2023-05-14T14:40:39").unwrap(); + let source_meta = lightcraft_meta::Metadata { capture_time: Some(capture), title: Some("Dated original".into()), ..Default::default() }; + let exif = lightcraft_meta::write_exif(&source_meta); + let xmp = lightcraft_meta::write_xmp(&source_meta, None); + let rgba = lightcraft_raster::Rgba8::from_fn(40, 24, |x, y| [(x * 6) as u8, (y * 9) as u8, 40, 255]); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&rgba), + &lightcraft_codecs::EncodeMeta { exif: Some(&exif), xmp: Some(&xmp), ..Default::default() }, + ) + .unwrap(); + std::fs::write(&src, png).unwrap(); let mut s = Session::new().with_fs(); s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); let orig = s.active().unwrap(); + assert_eq!(s.catalog.photo(orig).unwrap().captured.as_deref(), Some("2023-05-14T14:40:39")); s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.5})).unwrap(); let r = s.execute("photo.editExternal", &json!({"format": "psd", "bitDepth": 16})).unwrap(); let path = r["path"].as_str().unwrap().to_string(); @@ -1048,6 +1087,13 @@ fn external_edit_copy_as_psd_round_trips() { assert_eq!(d.bit_depth, 16); assert!(d.icc.is_some(), "the colour space travels with the file"); let new = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap()); + assert_eq!(s.catalog.photo(new).unwrap().captured.as_deref(), Some("2023-05-14T14:40:39")); + let all_metadata = s.execute("photo.allMetadata", &json!({"id": new.0})).unwrap(); + assert!(all_metadata["exif"].as_array().unwrap().iter().any(|row| row["tag"] == json!(0x9003)), "{all_metadata}"); + assert!( + all_metadata["xmp"].as_array().unwrap().iter().any(|row| row["name"] == "dc:title" && row["value"] == "Dated original"), + "{all_metadata}" + ); assert_eq!(s.catalog.stack_of(new).map(|st| (st.top(), st.photos.contains(&orig))), Some((new, true))); // the editor saves the document back over the same file: Reload shows its pixels let before = s.render_now(new, 16, 16).unwrap().image.data; @@ -1069,6 +1115,33 @@ fn external_edit_copy_as_psd_round_trips() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn psb_import_retains_capture_time_and_all_metadata() { + let dir = temp_dir("import-psb-metadata"); + let path = dir.join("dated.psb"); + let capture = lightcraft_meta::DateTime::parse_exif("2023:05:14 14:40:39"); + let metadata = lightcraft_meta::Metadata { + capture_time: capture, + gps: Some(lightcraft_meta::Gps { latitude: 45.0, longitude: 7.0, altitude: None }), + title: Some("PSB original".into()), + ..Default::default() + }; + let bytes = synthetic_psb_with_metadata(&metadata); + assert_eq!(lightcraft_meta::extract(&bytes).capture_time, capture); + assert_eq!(lightcraft_meta::extract(&bytes).gps, metadata.gps); + std::fs::write(&path, bytes).unwrap(); + + let mut session = Session::new().with_fs(); + let imported = session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + assert_eq!(imported["imported"].as_array().map(Vec::len), Some(1), "{imported}"); + let id = session.catalog.photos().next().unwrap().id; + assert_eq!(session.catalog.photo(id).unwrap().captured.as_deref(), Some("2023-05-14T14:40:39")); + let all_metadata = session.execute("photo.allMetadata", &json!({"id": id.0})).unwrap(); + assert!(all_metadata["exif"].as_array().unwrap().iter().any(|row| row["tag"] == json!(0x9003)), "{all_metadata}"); + assert!(all_metadata["xmp"].as_array().unwrap().iter().any(|row| row["name"] == "dc:title" && row["value"] == "PSB original"), "{all_metadata}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// Reload: a file changed on disk (an external editor saved it) gets its new size / hash, the /// cached source is dropped and renders change; unchanged files are left alone. #[test] @@ -1375,6 +1448,38 @@ const OTHER_APP_SIDECAR: &str = r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTc </x:xmpmeta> <?xpacket end="w"?>"#; +/// A foreign namespace may use a familiar prefix without becoming LightCraft-owned metadata. +#[test] +fn saving_preserves_foreign_namespace_prefix_collisions() { + let src = temp_dir("namespace-src"); + let lib = temp_dir("namespace-lib"); + write_png(&src.join("shot.png"), 1); + let foreign = r#"<rdf:Description xmlns:lc="https://example.org/vendor/" xmlns:xmp="https://example.org/vendor/" + lc:Secret="keep-me" xmp:Rating="2"><lc:Other>also keep</lc:Other></rdf:Description>"#; + let packet = format!(r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">{foreign}</rdf:RDF>"#); + let path = src.join("shot.xmp"); + std::fs::write(&path, packet).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + s.execute("library.import", &json!({"paths": [src.join("shot.png")]})).unwrap(); + let id = only(&s); + assert_eq!(s.catalog.photo(id).unwrap().rating, 0, "a foreign rating must not become catalog metadata"); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 5})).unwrap(); + for _ in 0..2 { + let result = s.execute("photo.saveMetadataToFile", &json!({})).unwrap(); + assert_eq!(result["failed"], json!([]), "{result}"); + assert_eq!(result["backups"], json!([]), "a valid packet must merge: {result}"); + assert_eq!(result["merged"], json!([path.to_string_lossy()]), "{result}"); + let saved = std::fs::read_to_string(&path).unwrap(); + assert!(saved.contains(foreign), "lost foreign bytes: {saved}"); + assert_eq!(lightcraft_meta::parse_xmp(&saved).unwrap().metadata.rating, Some(5)); + } + drop(s); + std::fs::remove_dir_all(src).unwrap(); + std::fs::remove_dir_all(lib).unwrap(); +} + /// Issue #92: saving merges into another app's sidecar instead of replacing it. #[test] fn saving_merges_into_another_apps_sidecar() { diff --git a/crates/engine/src/text.rs b/crates/engine/src/text.rs index 12974247f0..0e2e39c1ea 100644 --- a/crates/engine/src/text.rs +++ b/crates/engine/src/text.rs @@ -1,11 +1,12 @@ //! Text drawing in pure Rust, shared by the export watermark and the slideshow overlays: Inter -//! SemiBold (bundled) first, then the craft-fonts CJK faces as fallbacks ([`faces`]); glyph outlines +//! SemiBold (bundled) first, then the craft-fonts CJK and Thai faces as fallbacks ([`faces`]); glyph outlines //! from `ab_glyph`, vertical CJK cells shaped with `harfrust`. [`TextLayout`] lays a string out //! once (lines split at `\n`, kerning within a face) and reports its size, so callers can anchor //! it before drawing; drawing hands out per-pixel coverage, and the caller blends. //! -//! RTL scripts are laid out in logical order without bidi reordering, and scripts no face covers -//! draw as Inter's missing-glyph box: wrong-looking, never a crash. +//! Horizontal text has no contextual shaping or bidi reordering; Thai combining marks use +//! per-character metrics rather than shaped positioning. Arabic faces are not offered. Characters +//! no face covers draw as Inter's missing-glyph box. use ab_glyph::{Font, FontRef, Glyph, PxScale, ScaleFont, point}; @@ -16,13 +17,16 @@ pub static TEXT_FONT: &[u8] = include_bytes!("../../../assets/fonts/Inter-SemiBo pub const MAX_CHARS: usize = 4000; /// The text faces: Inter first, then the craft-fonts CJK faces (Mincho first, the watermark's -/// serif look; then any other CJK face — drawn text has no UI language, so every CJK script is -/// offered). Without craft-fonts that is Inter alone, and CJK characters draw as Inter's -/// missing-glyph box. +/// serif look; then any other CJK face), then Thai faces, preferring Regular. Drawn text has no +/// UI language, so every CJK script is offered. Other script faces stay out until their layout is +/// supported. Without craft-fonts that is Inter alone, with missing-glyph boxes for unsupported text. pub fn faces(craft: &'static [crate::fonts::CraftFont]) -> Vec<FontRef<'static>> { let mut cjk: Vec<_> = crate::fonts::cjk(craft).collect(); cjk.sort_by_key(|f| !f.is_mincho()); - std::iter::once(TEXT_FONT).chain(cjk.into_iter().map(|f| f.bytes)).filter_map(|bytes| FontRef::try_from_slice(bytes).ok()).collect() + let thai = crate::fonts::ui_fallback(craft, "Latn", "Regular") + .into_iter() + .filter(|f| f.covers("Thai") && !f.scripts.iter().any(|s| crate::fonts::is_cjk_script(s))); + std::iter::once(TEXT_FONT).chain(cjk.into_iter().chain(thai).map(|f| f.bytes)).filter_map(|bytes| FontRef::try_from_slice(bytes).ok()).collect() } /// Shape a whole grapheme in one cell. CJK uses vertical origins and forms; Latin stays upright. @@ -223,3 +227,91 @@ impl TextLayout { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::fonts::{CRAFT_FONTS, CraftFont}; + + fn assert_script_glyphs(script: &str, text: &str) { + if !CRAFT_FONTS.iter().any(|font| font.covers(script)) { + lightcraft_testkit::skip!(Fonts, "built without the {script} face from craft-fonts"); + return; + } + let layout = TextLayout::new(text, 40.0, false, CRAFT_FONTS).unwrap(); + assert_eq!(layout.glyphs.len(), text.chars().count()); + for (ch, (face, glyph, _)) in text.chars().zip(&layout.glyphs) { + assert_ne!(glyph.id.0, 0, "missing {script} glyph for {ch}"); + let font = &layout.fonts[*face]; + assert!(CRAFT_FONTS.iter().any(|entry| entry.covers(script) && entry.bytes == font.font_data())); + } + let mut covered = 0; + layout.draw(0.0, 0.0, |_, _, coverage| covered += usize::from(coverage > 0.0)); + assert!(covered > 0, "{script} outlines are rasterized"); + } + + #[test] + fn bundled_arabic_stays_out_of_export_fallback() { + if !CRAFT_FONTS.iter().any(|font| font.covers("Arab")) { + lightcraft_testkit::skip!(Fonts, "built without the Arabic face from craft-fonts"); + return; + } + // UI names still use their existing Arabic face. Export needs joining and bidi first. + assert!(crate::fonts::ui_fallback(CRAFT_FONTS, "Latn", "Regular").iter().any(|font| font.covers("Arab"))); + for vertical in [false, true] { + let layout = TextLayout::new("مرحبا", 40.0, vertical, CRAFT_FONTS).unwrap(); + assert!(layout.glyphs.iter().all(|(face, glyph, _)| *face == 0 && glyph.id.0 == 0)); + } + } + + #[test] + fn bundled_thai_uses_its_glyphs() { + assert_script_glyphs("Thai", "สวัสดีครับ"); + } + + #[test] + fn absent_fonts_keep_inter_and_missing_glyph_boxes() { + assert_eq!(faces(&[]).len(), 1); + let layout = TextLayout::new("Aกم", 40.0, false, &[]).unwrap(); + assert_ne!(layout.glyphs[0].1.id.0, 0); + assert!(layout.glyphs[1..].iter().all(|(face, glyph, _)| *face == 0 && glyph.id.0 == 0)); + let mut covered = 0; + layout.draw(0.0, 0.0, |_, _, coverage| covered += usize::from(coverage > 0.0)); + assert!(covered > 0); + } + + #[test] + fn latin_and_cjk_rendering_keeps_the_existing_preference() { + let mut cjk: Vec<_> = crate::fonts::cjk(CRAFT_FONTS).collect(); + if cjk.is_empty() { + lightcraft_testkit::skip!(Fonts, "built without CJK faces from craft-fonts"); + return; + } + cjk.sort_by_key(|font| !font.is_mincho()); + let previous: &'static [CraftFont] = Box::leak( + cjk.into_iter() + .map(|font| CraftFont { family: font.family, style: font.style, scripts: font.scripts, bytes: font.bytes }) + .collect::<Vec<_>>() + .into_boxed_slice(), + ); + let actual = faces(CRAFT_FONTS); + assert!(actual.len() > previous.len()); + assert!(actual[0].font_data() == TEXT_FONT, "Inter stays first"); + for (font, expected) in actual.iter().skip(1).zip(previous) { + assert!(font.font_data() == expected.bytes, "existing CJK face order: {} {}", expected.family, expected.style); + } + for vertical in [false, true] { + for text in ["LightCraft AV 123", "日本語、。你好世界한국어"] { + let before = TextLayout::new(text, 40.0, vertical, previous).unwrap(); + let after = TextLayout::new(text, 40.0, vertical, CRAFT_FONTS).unwrap(); + assert_eq!((before.width, before.height), (after.width, after.height)); + let pixels = |layout: &TextLayout| { + let mut pixels = Vec::new(); + layout.draw(0.0, 0.0, |x, y, coverage| pixels.push((x, y, coverage))); + pixels + }; + assert!(pixels(&before) == pixels(&after), "{text}, vertical={vertical}"); + } + } + } +} diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 5b32999bb8..dbfb0fade6 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -161,11 +161,17 @@ pub fn filter_chips(f: &Filter, cat: &Catalog) -> Vec<FilterChip> { if let Some(fl) = f.flag { add(format!("Flag: {}", format!("{fl:?}").to_lowercase()), json!({"flag": Null})); } - let mut labels = f.labels.clone(); - labels.extend(f.label.filter(|l| !labels.contains(l))); - if !labels.is_empty() { - let names: Vec<String> = labels.iter().map(|l| cat.label_name(*l)).collect(); - add(format!("Label: {}", names.join(" or ")), json!({"label": Null, "labels": []})); + if let Some(shown) = f.labels_shown() { + let or = |ls: &[lightcraft_catalog::ColorLabel]| ls.iter().map(|l| cat.label_name(*l)).collect::<Vec<_>>().join(" or "); + // empty: `label` and `labels` exclude each other, so name both constraints + let names = if shown.is_empty() { + // parenthesised when plural, so "Red and Yellow or Green" cannot read as "(Red and Yellow) or Green" + let plural = if f.labels.len() > 1 { format!("({})", or(&f.labels)) } else { or(&f.labels) }; + format!("{} and {plural}", f.label.map(|l| cat.label_name(l)).unwrap_or_default()) + } else { + or(&shown) + }; + add(format!("Label: {names}"), json!({"label": Null, "labels": []})); } if let Some(k) = f.kind { let n = match k { @@ -214,8 +220,9 @@ pub fn filter_chips(f: &Filter, cat: &Catalog) -> Vec<FilterChip> { if let Some(rs) = f.rule_set.as_ref().filter(|r| !r.rules.is_empty()) { add(format!("Rules: {}", rs.describe_with(cat)), json!({"ruleSet": Null})); } - if !f.only.is_empty() { - add(format!("Only {} photos", f.only.len()), json!({"only": []})); + if f.only_none || !f.only.is_empty() { + let n = if f.only_none { 0 } else { f.only.len() }; + add(format!("Only {n} photos"), json!({"only": [], "onlyNone": false})); } v } diff --git a/crates/engine/tests/denoise_cpu.rs b/crates/engine/tests/it/denoise_cpu.rs similarity index 97% rename from crates/engine/tests/denoise_cpu.rs rename to crates/engine/tests/it/denoise_cpu.rs index d01b7c5a5d..1da6da78d6 100644 --- a/crates/engine/tests/denoise_cpu.rs +++ b/crates/engine/tests/it/denoise_cpu.rs @@ -1,10 +1,9 @@ //! Opt-in same-machine denoise model-stage benchmark on one public Bayer raw. //! LC_DENOISE_MODEL=<onnx> LC_DENOISE_RAW=<CC0 corpus/raw> cargo test --release -//! -p lightcraft-engine --features denoise --test denoise_cpu -- --ignored --nocapture +//! -p lightcraft-engine --features denoise --test it denoise_cpu:: -- --ignored --nocapture //! LC_DENOISE_ONLY selects a file (default arw-sony-a7m3-compressed.arw). //! The whole model stage includes packing, scale/clip protection, blending and normalization; //! file decode, model loading and GPU setup are outside the timer. It uses the application's tile pool convention. -#![cfg(feature = "denoise")] use lightcraft_denoise::{ TileRunner, diff --git a/crates/engine/tests/denoise_real.rs b/crates/engine/tests/it/denoise_real.rs similarity index 98% rename from crates/engine/tests/denoise_real.rs rename to crates/engine/tests/it/denoise_real.rs index 8d8581753d..cb045cbd5e 100644 --- a/crates/engine/tests/denoise_real.rs +++ b/crates/engine/tests/it/denoise_real.rs @@ -4,12 +4,11 @@ //! //! ```text //! LC_DENOISE_MODEL=<model_bayer.onnx> LC_DENOISE_RAW=<folder with raw files> \ -//! cargo test --release -p lightcraft-engine --features denoise --test denoise_real -- --ignored --nocapture +//! cargo test --release -p lightcraft-engine --features denoise --test it denoise_real:: -- --ignored --nocapture //! ``` //! //! `LC_DENOISE_RAW` is a folder of CC0 raw files (`cargo xtask corpus --download` → `corpus/raw`); every file in it is //! tried. Optional: `LC_DENOISE_ONLY` (a file name to try alone), `LC_DENOISE_RUN_ON=cpu|gpu|auto` (where the model runs; `cpu` to compare with the card). -#![cfg(feature = "denoise")] use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs new file mode 100644 index 0000000000..2c52d87e9d --- /dev/null +++ b/crates/engine/tests/it/main.rs @@ -0,0 +1,7 @@ +//! The integration tests, one module per file, linked into one test binary. + +#[cfg(feature = "denoise")] +mod denoise_cpu; +#[cfg(feature = "denoise")] +mod denoise_real; +mod preview_read; diff --git a/crates/engine/tests/preview_read.rs b/crates/engine/tests/it/preview_read.rs similarity index 95% rename from crates/engine/tests/preview_read.rs rename to crates/engine/tests/it/preview_read.rs index eedebc2c17..98eb64d27a 100644 --- a/crates/engine/tests/preview_read.rs +++ b/crates/engine/tests/it/preview_read.rs @@ -2,7 +2,7 @@ //! network share, which is where reading only the header instead of the whole raw matters: //! //! LC_PREVIEW_RAW="/run/user/1000/gvfs/smb-share:.../DSCF0001.RAF" \ -//! cargo test --release -p lightcraft-engine --test preview_read -- --ignored --nocapture +//! cargo test --release -p lightcraft-engine --test it preview_read:: -- --ignored --nocapture //! //! It reports what the preview cost and fails when the read is not the small part of the file the //! header path promises. Skipped without `LC_PREVIEW_RAW` (there is no committed raw fixture: media diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 0c3ab8f059..33e02fbe4b 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -118,7 +118,9 @@ impl Drop for Buf { let mut b = Some(b); let _ = RETIRED.try_with(|r| r.0.borrow_mut().extend(b.take())); match b { - Some(b) => std::mem::forget(b), + // Leaking is deliberate during thread teardown — dropping a wgpu buffer whose device + // thread-locals have already gone can abort the process. The device owns it. + Some(b) => std::mem::forget(b), // NOSONAR None => { RETIRED_BYTES.fetch_add(size, Ordering::Relaxed); } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 7efae6a576..452e2dd672 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -450,11 +450,12 @@ pub fn render(src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &R } /// Whether the GPU renders requests of this kind at all (a given render can still fall back to -/// the CPU): the kernel writes 8-bit output, so high-bit-depth exports and soft proofs render on -/// the CPU, and so does Visualize HDR, which needs the float HDR render. [`try_render`] follows it, -/// and the loupe sizes its slider-drag drafts by it (issue #330), so the two can't drift apart. -pub fn handles(depth: lightcraft_pipeline::OutputDepth, proofed: bool, overlay: lightcraft_pipeline::Overlay) -> bool { - depth == lightcraft_pipeline::OutputDepth::U8 && !proofed && overlay != lightcraft_pipeline::Overlay::HdrRange +/// the CPU): the kernel writes 8-bit output, so high-bit-depth exports render on the CPU, and so do +/// soft proofs against an output-device profile (`device_proof`: its 3D table is CPU-side) and +/// Visualize HDR, which needs the float HDR render. [`try_render`] follows it, and the loupe sizes +/// its slider-drag drafts by it (issue #330), so the two can't drift apart. +pub fn handles(depth: lightcraft_pipeline::OutputDepth, device_proof: bool, overlay: lightcraft_pipeline::Overlay) -> bool { + depth == lightcraft_pipeline::OutputDepth::U8 && !device_proof && overlay != lightcraft_pipeline::Overlay::HdrRange } /// [`render`], reporting why this render made no GPU image: [`Fallback::NotTried`] when the GPU @@ -473,7 +474,8 @@ pub fn try_render( // sections switched off with their eye render as if at their defaults (issue #316) let effective = s.effective(); let s: &DevelopSettings = &effective; - if !enabled() || !handles(req.depth, req.proof.is_some(), req.overlay) { + let device_proof = req.proof.is_some_and(|p| lightcraft_pipeline::proof_profile(p.profile).is_some()); + if !enabled() || !handles(req.depth, device_proof, req.overlay) { return Err(Fallback::NotTried); } let s = &*lightcraft_pipeline::settings_for(s, req); diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 7f9405492c..b46b7cc1ac 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -73,6 +73,13 @@ const FIELDS: &[(&str, usize)] = &[ ("OUT_Y", 3), ("OUT_TRC", 1), ("OUT_GAMMA", 1), + // soft proofing (matrix proofs; `ProofParams`): working → proof RGB, its luma, proof → output, warnings + ("PROOF", 1), + ("PROOF_M", 9), + ("PROOF_Y", 3), + ("PROOF_OUT", 9), + ("PROOF_DEST_WARN", 1), + ("PROOF_DISP_WARN", 1), // first row of a band dispatch (the kernel runs over rows Y0.., see `render`) ("Y0", 1), ]; @@ -233,6 +240,14 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr let (trc, gamma) = fp.out_trc.code(); p.u("OUT_TRC", trc); p.f("OUT_GAMMA", gamma); + if let Some(pp) = fp.proof.as_ref().filter(|pp| pp.table.is_none()) { + p.b("PROOF", true); + p.fs("PROOF_M", pp.to_proof.as_flattened()); + p.fs("PROOF_Y", &pp.luma); + p.fs("PROOF_OUT", pp.proof_to_out.as_flattened()); + p.b("PROOF_DEST_WARN", pp.dest_warning); + p.b("PROOF_DISP_WARN", pp.display_warning); + } if let Some((amt, cell, rough, seed)) = fp.grain { p.b("GRAIN", true); p.f("GRAIN_AMT", amt); diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 0c5bd19f02..64990db0e1 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -669,8 +669,10 @@ pub fn render( // 5. per-pixel stage let mut fp = FinishParams::new(s, &plan.frame, info, w, h, plan.px_per_long, prep.air, req.space); + // soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`) + fp.proof = req.proof.map(|pr| pr.params(req.space)); if let Some(d) = &req.display { - fp.for_display(d, None); + fp.for_display(d, req.proof); } let present = Present { clarity: prep.clarity.is_some(), diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index d51308ee0e..04115b945a 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -252,6 +252,46 @@ fn out_encode(v: f32) -> f32 { return 1.099 * pow(l, 0.45) - 0.099; } +// The 3×3 matrix stored row by row from field `o`. +fn mat_at(o: u32) -> array<vec3<f32>, 3> { + return array<vec3<f32>, 3>( + vec3<f32>(pf(o), pf(o + 1u), pf(o + 2u)), + vec3<f32>(pf(o + 3u), pf(o + 4u), pf(o + 5u)), + vec3<f32>(pf(o + 6u), pf(o + 7u), pf(o + 8u)), + ); +} + +// `finish::gamut_map` (SDR): the chroma scale that brings `r` into 0..1 towards its luminance (1: in gamut) ... +fn gamut_scale(r: vec3<f32>, luma: vec3<f32>) -> f32 { + let yy = clamp(dot(luma, r), 0.0, 1.0); + var tg = 1.0; + for (var k = 0u; k < 3u; k++) { + let cc = r[k]; + if (cc < 0.0) { + tg = min(tg, yy / max(yy - cc, 1e-9)); + } else if (cc > 1.0) { + tg = min(tg, (1.0 - yy) / max(cc - yy, 1e-9)); + } + } + return tg; +} + +// ... and `r` scaled by it. +fn gamut_apply(r: vec3<f32>, luma: vec3<f32>, tg: f32) -> vec3<f32> { + if (tg < 1.0) { + let yy = clamp(dot(luma, r), 0.0, 1.0); + return yy + (r - yy) * tg; + } + return r; +} + +// `finish::out_of_gamut`: `r` needed desaturating by `t` to fit and isn't just a neutral beyond white or below black. +fn out_of_gamut(r: vec3<f32>, t: f32) -> bool { + let lo = min(r.x, min(r.y, r.z)); + let hi = max(r.x, max(r.y, r.z)); + return t < 0.995 && (hi - lo) > 0.02 * max(abs(hi), 1e-3) && hi - lo > 1e-3 && (lo < -1e-3 || (hi > 1.0 && lo < 1.0)); +} + @compute @workgroup_size(16, 16) fn main(@builtin(global_invocation_id) gid: vec3<u32>) { let w = pu(F_W); @@ -324,8 +364,11 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) { // --- dehaze (scene linear) let dz = pf(F_DEHAZE) + lt[10]; if (dz != 0.0 && pu(F_HAS_DARK) != 0u) { - let d = clamp(dark[i] / pf(F_AIR_PRE), 0.0, 1.0); + // the dark channel is a blur, not a patch minimum: never attribute more veil than the + // pixel's own minimum channel, or dark pixels next to bright ones crush to black (#2504) let air = pf(F_AIR); + let cmin = min(c.x, min(c.y, c.z)); + let d = clamp(min(select(0.0, dark[i] / pf(F_AIR_PRE), pf(F_AIR_PRE) > 0.0), select(0.0, cmin / air, air > 0.0)), 0.0, 1.0); if (dz > 0.0) { let t = max(1.0 - 0.95 * min(dz, 1.0) * d, 0.12); c = max((c - air * (1.0 - t)) / t, vec3<f32>(0.0)); @@ -467,26 +510,27 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) { } } - // --- gamut map to the output space (desaturate towards luminance until in range) - let om = array<vec3<f32>, 3>( - vec3<f32>(pf(F_OUT_M), pf(F_OUT_M + 1u), pf(F_OUT_M + 2u)), - vec3<f32>(pf(F_OUT_M + 3u), pf(F_OUT_M + 4u), pf(F_OUT_M + 5u)), - vec3<f32>(pf(F_OUT_M + 6u), pf(F_OUT_M + 7u), pf(F_OUT_M + 8u)), - ); - var r = mul3(om, d); - let yy = clamp(pf(F_OUT_Y) * r.x + pf(F_OUT_Y + 1u) * r.y + pf(F_OUT_Y + 2u) * r.z, 0.0, 1.0); - var tg = 1.0; - for (var k = 0u; k < 3u; k++) { - let cc = r[k]; - if (cc < 0.0) { - tg = min(tg, yy / max(yy - cc, 1e-9)); - } else if (cc > 1.0) { - tg = min(tg, (1.0 - yy) / max(cc - yy, 1e-9)); + // --- gamut map to the output space (desaturate towards luminance until in range); + // soft proofing maps into the proof space first and shows that in the output space + // (warn: 0 none, 1 destination gamut, 2 display gamut) + var warn = 0u; + var r: vec3<f32>; + if (pu(F_PROOF) != 0u) { + let q0 = mul3(mat_at(F_PROOF_M), d); + let tq = gamut_scale(q0, vec3<f32>(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u))); + if (pu(F_PROOF_DEST_WARN) != 0u && out_of_gamut(q0, tq)) { + warn = 1u; } + r = mul3(mat_at(F_PROOF_OUT), gamut_apply(q0, vec3<f32>(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)), tq)); + } else { + r = mul3(mat_at(F_OUT_M), d); } - if (tg < 1.0) { - r = yy + (r - yy) * tg; + let oy = vec3<f32>(pf(F_OUT_Y), pf(F_OUT_Y + 1u), pf(F_OUT_Y + 2u)); + let tg = gamut_scale(r, oy); + if (pu(F_PROOF) != 0u && pu(F_PROOF_DISP_WARN) != 0u && warn == 0u && out_of_gamut(r, tg)) { + warn = 2u; } + r = gamut_apply(r, oy, tg); // --- encode, curves, grain var e = vec3<f32>(encode_srgb(r.x), encode_srgb(r.y), encode_srgb(r.z)); @@ -512,6 +556,11 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) { let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); e = e + k; } + if (warn == 1u) { + e = vec3<f32>(1.0, 0.0, 0.0); + } else if (warn == 2u) { + e = vec3<f32>(0.0, 0.25, 1.0); + } e = vec3<f32>(out_encode(e.x), out_encode(e.y), out_encode(e.z)); out[i] = enc8(e.x) | (enc8(e.y) << 8u) | (enc8(e.z) << 16u) | (255u << 24u); } diff --git a/crates/gpu/tests/equivalence.rs b/crates/gpu/tests/it/equivalence.rs similarity index 90% rename from crates/gpu/tests/equivalence.rs rename to crates/gpu/tests/it/equivalence.rs index c877e3d9d8..6a8169b301 100644 --- a/crates/gpu/tests/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -79,6 +79,19 @@ fn check(name: &str, src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, (mean, max) } +/// [`check`] for gamut-warning renders: a warning is a hard decision at the gamut boundary, so a +/// pixel sitting exactly on it may be painted by one renderer and not the other (float rounding). +/// Such flips are allowed for at most 0.01 % of the pixels; everything else is held to [`check`]'s bounds. +fn check_warned(name: &str, src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest) { + let cpu = render(src, info, s, req).image; + let gpu = lightcraft_gpu::render(src, info, s, req, None).expect("gpu render"); + let (mean, _, over) = diff(&cpu, &gpu.image); + let flips = cpu.data.iter().zip(&gpu.image.data).filter(|(p, q)| (0..3).any(|c| p[c].abs_diff(q[c]) > MAX_LSB)).count(); + let share = flips as f64 / cpu.data.len() as f64; + eprintln!("{name:<28} {}x{} mean {mean:.4} >1: {:.4}% boundary flips {flips}", cpu.width, cpu.height, over * 100.0); + assert!(mean < MEAN_LSB && share <= 1e-4, "{name}: mean {mean:.4} LSB, {flips} pixels differ by more than {MAX_LSB} LSB"); +} + type Edit = fn(&mut DevelopSettings); fn typical(s: &mut DevelopSettings) { @@ -877,3 +890,54 @@ fn windows_of_a_big_photo_share_one_uploaded_source() { lightcraft_gpu::render(&src, &info, &s, &at(1000), Some(&after)).expect("gpu render"); assert_eq!(lightcraft_gpu::source_uploads() - start, 2); } + +#[test] +fn soft_proofs_match() { + if !gpu() { + return; + } + // Soft proofing against an output space (matrix proofs): into the proof gamut, back to the + // output space, with the destination and display gamut warnings painted alike on both renderers. + // Saturated edits put plenty of colours outside the smaller proof spaces. + use lightcraft_pipeline::{OutputSpace, Proof}; + let src = scene(0, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + for space in [OutputSpace::Srgb, OutputSpace::AdobeRgb, OutputSpace::DisplayP3] { + for (dest_warning, display_warning) in [(false, false), (true, false), (false, true), (true, true)] { + for out in [OutputSpace::Srgb, OutputSpace::Rec2020] { + let mut s = DevelopSettings::default(); + saturated(&mut s); + let proof = Some(Proof { space, dest_warning, display_warning, profile: 0 }); + let req = RenderRequest { space: out, proof, ..RenderRequest::fit(640, 640) }; + let name = format!("proof {space:?} → {out:?} warn {dest_warning}/{display_warning}"); + if dest_warning || display_warning { + check_warned(&name, &src, &raw, &s, &req); + } else { + check(&name, &src, &raw, &s, &req); + } + } + } + } + // the case is meaningful: proofing sRGB from Rec. 2020 output warns on some pixels, and the GPU paints the same ones + let mut s = DevelopSettings::default(); + saturated(&mut s); + let req = RenderRequest { + space: OutputSpace::Rec2020, + proof: Some(Proof { space: OutputSpace::Srgb, dest_warning: true, display_warning: false, profile: 0 }), + ..RenderRequest::fit(640, 640) + }; + let warned = |i: &Rgba8| i.data.iter().filter(|p| p[1] == 0 && p[2] == 0 && p[0] > 200).count(); + let (cpu, gpu) = (render(&src, &raw, &s, &req).image, lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu render").image); + assert!(warned(&cpu) > 100, "{} warned pixels", warned(&cpu)); + let (a, b) = (warned(&cpu), warned(&gpu)); + assert!(a.abs_diff(b) as f64 <= 1e-4 * cpu.data.len() as f64, "warned pixels: CPU {a}, GPU {b}"); + // an output-device profile (a 3D table) stays on the CPU + let n = 2; + let lut = lightcraft_pipeline::ProofLut::new(n, vec![[0.5, 0.5, 0.5, 0.0]; n * n * n]).unwrap(); + let id = lightcraft_pipeline::register_proof_profile(0x5eed_9f00, lut); + let req = RenderRequest { + proof: Some(Proof { space: OutputSpace::Srgb, dest_warning: true, display_warning: false, profile: id }), + ..RenderRequest::fit(64, 64) + }; + assert!(lightcraft_gpu::render(&src, &raw, &DevelopSettings::default(), &req, None).is_none(), "declined: the CPU renders it"); +} diff --git a/crates/gpu/tests/fallback.rs b/crates/gpu/tests/it/fallback.rs similarity index 100% rename from crates/gpu/tests/fallback.rs rename to crates/gpu/tests/it/fallback.rs diff --git a/crates/gpu/tests/gpu_probe.rs b/crates/gpu/tests/it/gpu_probe.rs similarity index 97% rename from crates/gpu/tests/gpu_probe.rs rename to crates/gpu/tests/it/gpu_probe.rs index e006fbc807..4bed20d1bf 100644 --- a/crates/gpu/tests/gpu_probe.rs +++ b/crates/gpu/tests/it/gpu_probe.rs @@ -1,7 +1,7 @@ //! What GPU this machine offers the develop pipeline, as one JSON line: the capability probe of //! `cargo xtask ci`, which is std + serde_json and has no wgpu of its own. Ignored in normal runs; //! xtask runs it after the workspace tests, so it costs no extra build: -//! `cargo test --workspace --test gpu_probe -- --ignored --nocapture`. +//! `cargo test --workspace --test it -- --ignored --exact gpu_probe::gpu_probe --nocapture`. //! //! - `LIGHTCRAFT_GPU_PROBE` unset: the compute device the pipeline picks (`available()`, //! `adapter_name()`, `unavailable_reason()`), the backends it may use and the backends this build @@ -11,7 +11,6 @@ //! a driver that crashes while it is enumerated (issue #136) costs only its own line. //! //! Only reports: which adapters the pipeline accepts is `ctx.rs`'s policy. -#![cfg(not(target_arch = "wasm32"))] use lightcraft_gpu::backend::{self, Backends}; diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs new file mode 100644 index 0000000000..d26d1efc94 --- /dev/null +++ b/crates/gpu/tests/it/main.rs @@ -0,0 +1,9 @@ +//! The integration tests, one module per file, linked into one test binary. +//! Binaries of their own: `tests/shutdown.rs` and `tests/shutdown_first.rs` close the GPU for the whole +//! process, and `tests/memory.rs` checks the process's device-memory counters, which renders on other test +//! threads would change. + +mod equivalence; +mod fallback; +#[cfg(not(target_arch = "wasm32"))] +mod gpu_probe; diff --git a/crates/heif/src/census.rs b/crates/heif/src/census.rs new file mode 100644 index 0000000000..6dbe035fca --- /dev/null +++ b/crates/heif/src/census.rs @@ -0,0 +1,122 @@ +//! Caps on the container's metadata boxes, counted before heic-rs touches the file. +//! +//! heic-rs 0.1.4 (pinned `=0.1.4`) has no aggregate work budget inside its container parsing: +//! every `ipma` association entry rescans the vector of already-seen item ids (quadratic in +//! the number of entries), and an `iloc` extent using construction method 2 reconstructs its +//! source item afresh for every extent that references it, with no shared cache. Legitimate +//! phone-photo metadata never comes near these caps — real corpora keep both well under a few +//! kilobytes — so anything above them is hostile or corrupt and is refused before the +//! countable CPU work happens. +//! +//! [`depth_boxes`] stops silently at structural blips: heic-rs's own parser reports those +//! better than this walk could, and an `ipma` box past the cap is caught wherever it parses. + +use heic_rs::boxes::BoxIter; + +use crate::Error; + +/// The largest `ipma` box (item ↔ property associations) payload accepted, 64 KiB. An entry +/// costs at least 3 bytes, so this bounds heic-rs's per-entry rescan of earlier item ids to +/// ~21 000 entries ≈ 220 million comparisons: long enough to be annoying, never minutes. +const MAX_IPMA_BYTES: usize = 64 << 10; + +/// The largest `iloc` box (item locations) payload accepted, 64 KiB. An extent costs at least +/// 12 bytes, so this bounds both the parse itself and how many extents a +/// construction-method-2 reconstruction chain can visit. +const MAX_ILOC_BYTES: usize = 64 << 10; + +/// Falls through unless the container declares more `ipma` or `iloc` payload than a +/// legitimate phone photo ever does. +pub fn cap(bytes: &[u8]) -> Result<(), Error> { + let mut c = Census::default(); + depth_boxes(&mut c, BoxIter::new(bytes), 0); + if c.ipma > MAX_IPMA_BYTES { + return Err(Error::Limit(format!("the image carries {} bytes of property associations, over the {MAX_IPMA_BYTES}-byte cap", c.ipma))); + } + if c.iloc > MAX_ILOC_BYTES { + return Err(Error::Limit(format!("the image carries {} bytes of item locations, over the {MAX_ILOC_BYTES}-byte cap", c.iloc))); + } + Ok(()) +} + +/// The metadata-box payload sizes seen so far. +#[derive(Default)] +struct Census { + ipma: usize, + iloc: usize, +} + +/// Walks boxes, adding the payload sizes of those named in [`Census`]. +/// +/// Only `meta` and `iprp` (the two nesting boxes the metadata is built from) are descended +/// into, no deeper than that depth, so a nested-box trick can't hide a box from the count. +fn depth_boxes(c: &mut Census, boxes: BoxIter<'_>, depth: u32) { + if depth > 3 { + return; + } + for b in boxes { + // A structural error stops the walk; `heic_rs::probe` reports it properly afterwards. + let Ok(b) = b else { return }; + if b.is(b"ipma") { + c.ipma = c.ipma.saturating_add(b.payload.len()); + } else if b.is(b"iloc") { + c.iloc = c.iloc.saturating_add(b.payload.len()); + } else if b.is(b"meta") { + // `meta` is a FullBox: version and flags sit between its header and its children. + if b.payload.len() >= 4 { + depth_boxes(c, BoxIter::new(&b.payload[4..]), depth + 1); + } + } else if b.is(b"iprp") { + depth_boxes(c, b.children(), depth + 1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Assembles ftyp + meta(version/flags + iprp(ipco, ipma)) by hand; only the structure + /// the census walks matters, no item is ever defined. + fn file_with(ipma_payload: &[u8]) -> Vec<u8> { + let mut out = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic".to_vec(); + let mut iprp = Vec::new(); + iprp.extend(box_of(b"ipco", b"")); + iprp.extend(box_of(b"ipma", ipma_payload)); + let mut meta = vec![0u8, 0, 0, 0]; // version 0, flags 0 + meta.extend(box_of(b"iprp", &iprp)); + out.extend(box_of(b"meta", &meta)); + out + } + + fn box_of(kind: &[u8; 4], body: &[u8]) -> Vec<u8> { + let mut out = Vec::with_capacity(8 + body.len()); + let size = u32::try_from(8 + body.len()).expect("test box fits in u32"); + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(body); + out + } + + #[test] + fn an_oversized_ipma_is_refused() { + // 40 000 entries of 6 bytes: 240 KiB of ipma, far over the cap, and quadratic if + // parsed (each entry rescans the earlier item ids in heic-rs 0.1.4). + let mut ipma = Vec::new(); + for _ in 0..40_000u32 { + ipma.extend_from_slice(&[0u8, 0, 0, 0, 0, 0]); + } + let bytes = file_with(&ipma); + let r = crate::probe(&bytes).map(|_| ()); + assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("associations")), "{r:?}"); + } + + #[test] + fn a_undersized_ipma_is_untouched_by_the_caps() { + // The same shape with a normal ipma (two entries): the caps pass, and whatever error + // follows must not come from them. + let bytes = file_with(&[0, 0, 4, 1, 1, 2, 0, 0]); + let r = crate::probe(&bytes); + assert!(!matches!(r, Err(Error::Limit(ref m)) if m.contains("cap")), "{r:?}"); + } +} diff --git a/crates/heif/src/lib.rs b/crates/heif/src/lib.rs index 21b9cf647f..5b20e31d75 100644 --- a/crates/heif/src/lib.rs +++ b/crates/heif/src/lib.rs @@ -19,6 +19,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod census; mod orient; /// Lossless synthetic HEIF files for tests, here and in the crates above (feature `testdata`). #[cfg(any(test, feature = "testdata"))] @@ -149,20 +150,50 @@ pub fn probe(bytes: &[u8]) -> Result<Info, Error> { } fn probe_unguarded(bytes: &[u8]) -> Result<Info, Error> { - let info = heic_rs::probe(bytes).map_err(|e| match e { - // No `meta` box: no still image, only a `moov` image sequence (a video track). + census::cap(bytes)?; + // No `meta` box: no still image, only a `moov` image sequence (a video track). + let open_error = |e| match e { heic_rs::Error::MissingBox("meta") => Error::Unsupported(SEQUENCE), e => err(e), - })?; - let ctx = Context::open(bytes).map_err(err)?; + }; + let ctx = Context::open(bytes).map_err(open_error)?; let id = ctx.meta.primary; - let coded = match ctx.grid(id).map_err(err)? { + // heic-rs 0.1.4 caps the size of what it assembles, not the work: an item built from other + // items (`iloc` construction method 2) is rebuilt once per extent, so a chain of such items + // multiplies at every level while each result stays small. Count those visits from the + // `iloc` table before reconstructing anything: the primary item first (`heic_rs::probe` and + // `Context::grid` both rebuild its descriptor), then its alpha plane, then every tile + // reference, repeats included. + let mut visits = 0_usize; + item_visits(&ctx, id, 0, &mut visits)?; + let info = heic_rs::probe(bytes).map_err(open_error)?; + if let Some(alpha) = ctx.alpha_item(id).map_err(err)? { + item_visits(&ctx, alpha, 0, &mut visits)?; + } + let mut coded = match ctx.grid(id).map_err(err)? { Some((_, tiles)) => tiles, None => vec![id], }; + for &item in coded.iter().filter(|&&item| item != id) { + item_visits(&ctx, item, 0, &mut visits)?; + } + // A `dimg` listing may name the same tile more than once, and reconstructable items are + // moreover rebuilt for every extent that references them in heic-rs 0.1.4. For the size + // check each unique item counts once: the total reconstruction (all of it assembled from + // `bytes` by heic-rs) is held below one copy of the file, above which a repeat or chain + // wants more bytes than exist. Order doesn't matter here: this only checks that every + // tile's bytes lie in the file. + coded.sort_unstable(); + coded.dedup(); + let mut reconstructed = 0_usize; for item in coded { - // Borrowed from `bytes` unless split across extents: cheap. - ctx.item_data(item).map_err(err)?; + reconstructed = reconstructed.saturating_add(ctx.item_data(item).map_err(err)?.len()); + if reconstructed > bytes.len() { + return Err(Error::Limit(format!( + "the container holds {reconstructed} bytes of item data, over the {} bytes of the file itself", + bytes.len() + ))); + } } Ok(Info { width: info.width, @@ -174,6 +205,36 @@ fn probe_unguarded(bytes: &[u8]) -> Result<Info, Error> { }) } +/// Most extent visits heic-rs may spend reconstructing the primary image's coded items; real +/// files need one per tile (plus a few for the rare derived item). +const MAX_ITEM_VISITS: usize = 4096; +/// Deepest chain of items built from items we follow (heic-rs refuses beyond eight itself). +const MAX_ITEM_CHAIN: u32 = 8; + +/// Adds to `visits` the extents heic-rs would read to reconstruct `id`, following items built +/// from other items, and fails once that passes [`MAX_ITEM_VISITS`] or the chain is too deep. +fn item_visits(ctx: &Context<'_>, id: u32, depth: u32, visits: &mut usize) -> Result<(), Error> { + use heic_rs::meta::iloc::Construction; + if depth > MAX_ITEM_CHAIN { + return Err(Error::Limit(format!("items built from items nest deeper than {MAX_ITEM_CHAIN} levels"))); + } + let Some(loc) = ctx.meta.location(id) else { return Ok(()) }; + *visits = visits.saturating_add(loc.extents.len().max(1)); + if *visits > MAX_ITEM_VISITS { + return Err(Error::Limit(format!("reconstructing the image takes over {MAX_ITEM_VISITS} item extent reads"))); + } + if loc.construction == Construction::Item { + for e in &loc.extents { + if let Ok(source) = u32::try_from(e.index) + && source != id + { + item_visits(ctx, source, depth + 1, visits)?; + } + } + } + Ok(()) +} + /// Decodes the primary image, with its metadata. pub fn decode(bytes: &[u8], options: &Options) -> Result<Decoded, Error> { guarded(|| decode_unguarded(bytes, options)) @@ -188,7 +249,13 @@ pub fn decode_thumbnail(bytes: &[u8], min_edge: u32, options: &Options) -> Resul let ctx = Context::open(bytes).map_err(err)?; let primary = ctx.meta.primary; let mut best: Option<(u32, u32)> = None; + // A thumbnail whose own reconstruction would cost too much is not a candidate; the visits + // of all the candidates share one budget. + let mut candidate_visits = 0_usize; for r in ctx.meta.refs.iter().filter(|r| r.kind == heic_rs::meta::iref::RefKind::Thmb && r.to.contains(&primary)) { + if item_visits(&ctx, r.from, 0, &mut candidate_visits).is_err() { + continue; + } let Ok(p) = ctx.props(r.from) else { continue }; let Ok((w, h)) = ctx.coded_size(r.from, &p) else { continue }; let edge = w.max(h); @@ -197,6 +264,15 @@ pub fn decode_thumbnail(bytes: &[u8], min_edge: u32, options: &Options) -> Resul } } let Some((id, _)) = best else { return Ok(None) }; + // The same pre-scan as `probe`: the thumbnail's own descriptor and every tile reference + // are counted before heic-rs rebuilds any of them. + let mut visits = 0_usize; + item_visits(&ctx, id, 0, &mut visits)?; + if let Some((_, tiles)) = ctx.grid(id).map_err(err)? { + for &tile in &tiles { + item_visits(&ctx, tile, 0, &mut visits)?; + } + } let mut decoded = decode_item(&ctx, id, options, false)?; if decoded.icc.is_none() { decoded.icc = item_icc(&ctx, primary); @@ -232,6 +308,13 @@ fn decode_unguarded(bytes: &[u8], options: &Options) -> Result<Decoded, Error> { /// `with_alpha` and the item has an alpha auxiliary image. fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool) -> Result<Decoded, Error> { let p = ctx.props(id).map_err(err)?; + // heic-rs 0.1.4 keeps every associated transform and its [`orient::apply`] allocates the + // full picture again for each: a file could chain the repetition and multiply decode CPU + // without changing any checked size. Real files carry at most one `clap`, `irot` and + // `imir`, so refuse anything approaching [`MAX_TRANSFORMS`] (CodeRabbit #44). + if p.transforms.len() > MAX_TRANSFORMS { + return Err(Error::Limit(format!("the image carries {} transform properties, over the {MAX_TRANSFORMS}-property cap", p.transforms.len()))); + } let limit = options.max_pixels; // The declared sizes are refused before anything is decoded or allocated. let (cw, ch) = ctx.coded_size(id, &p).map_err(err)?; @@ -245,6 +328,14 @@ fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool) let signal = ycc::Signal { matrix: colour.matrix, full_range: colour.full_range }; let alpha_id = if with_alpha { ctx.alpha_item(id).map_err(err)? } else { None }; let (w, h) = planes.size(); + // A grid's canvas dimensions come from its payload, not the checked `ispe` (CodeRabbit + // #48): check the real one, before [`ycc::to_rgb16`] allocates for it. + match (u32::try_from(w), u32::try_from(h)) { + (Ok(wu), Ok(hu)) => { + heic_rs::image::check_pixels(wu, hu, limit).map_err(err)?; + } + _ => return Err(Error::Limit(format!("the image canvas is {w}x{h}, beyond the {limit}-pixel limit"))), + } let mode = if options.apply_transforms && orient::odd_crop(w, h, &p.transforms)? { ycc::Upsampling::Bilinear } else { ycc::Upsampling::Nearest }; let mut data = ycc::to_rgb16(&planes, signal, alpha_id.is_some(), mode) .ok_or_else(|| Error::Malformed("the decoded pictures don't cover the image".into()))?; @@ -281,6 +372,10 @@ fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool) /// cover its canvas rounded up to whole tiles, so legitimate grids sit near 1. const GRID_BUDGET: u64 = 2; +/// The most transform properties (`clap`/`irot`/`imir`) one item may carry. Real files have at +/// most one of each, so anything approaching this is a reordered or hostile association list. +const MAX_TRANSFORMS: usize = 12; + /// The decoded pictures of an item: one, or a grid's tiles in `dimg` order. struct Coded<'a> { frames: Vec<Frame>, @@ -370,8 +465,12 @@ fn colour(p: &ItemProps<'_>, coded: &ItemProps<'_>) -> Colour { /// metadata item never fails a decode whose pixels came out fine. fn metadata(ctx: &Context<'_>) -> (Option<Vec<u8>>, Option<String>) { let id = ctx.meta.primary; - let exif = ctx.exif(id).ok().flatten().map(<[u8]>::to_vec); - let xmp = ctx.xmp_item(id).and_then(|x| ctx.item_data(x).ok()).and_then(|d| match d { + // Metadata is best effort, so an item that would cost too much to rebuild is skipped, not an error. + let mut visits = 0_usize; + let cheap = |item: Option<u32>, visits: &mut usize| item.is_none_or(|item| item_visits(ctx, item, 0, visits).is_ok()); + let exif = if cheap(ctx.exif_item(id), &mut visits) { ctx.exif(id).ok().flatten().map(<[u8]>::to_vec) } else { None }; + let xmp_item = ctx.xmp_item(id).filter(|&x| cheap(Some(x), &mut visits)); + let xmp = xmp_item.and_then(|x| ctx.item_data(x).ok()).and_then(|d| match d { Cow::Borrowed(b) => String::from_utf8(b.to_vec()).ok(), Cow::Owned(b) => String::from_utf8(b).ok(), }); diff --git a/crates/heif/src/tests_synthetic.rs b/crates/heif/src/tests_synthetic.rs index 3259dc96d6..1286ff82a9 100644 --- a/crates/heif/src/tests_synthetic.rs +++ b/crates/heif/src/tests_synthetic.rs @@ -185,3 +185,16 @@ fn truncated_and_corrupted_files_are_errors_not_panics() { let _ = decode_thumbnail(&b, 1, &Options::default()); } } + +/// CodeRabbit #44: heic-rs keeps every associated transform and each one re-allocates the +/// whole picture, so 13 of them are over the [`crate::MAX_TRANSFORMS`] cap and refused. +#[test] +fn too_many_transform_properties_are_refused() { + let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 13).collect(), ..Spec::new(32, 32, &grey) }); + let r = decode(&bytes, &Options::default()); + assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("transform")), "{r:?}"); + // At the cap they're not: 12 identity rotations decode normally. + let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 12).collect(), ..Spec::new(32, 32, &grey) }); + let d = decode(&bytes, &Options::default()).unwrap(); + assert_eq!((d.width, d.height), (32, 32)); +} diff --git a/crates/heif/src/ycc.rs b/crates/heif/src/ycc.rs index a0429b453d..384d25f2ae 100644 --- a/crates/heif/src/ycc.rs +++ b/crates/heif/src/ycc.rs @@ -161,6 +161,13 @@ pub fn to_rgb16(planes: &Planes<'_>, signal: Signal, alpha: bool, mode: Upsampli if !(8..=16).contains(&bd) || w == 0 || h == 0 { return None; } + // The default caller limit is 2²8 pixels, at most four channels per pixel, so the largest + // legitimate `w·h·ch` is 2²30 samples. Anything more is a malformed or hostile canvas the + // decode path would have refused before calling here (CodeRabbit #48): refuse rather than + // ask for a multi-gigabuffer (or worse, over usize). + if w.checked_mul(h)?.checked_mul(ch)? > 1 << 30 { + return None; + } let max = ((1u32 << bd) - 1) as f32; let half = (1u32 << (bd - 1)) as f32; let scale = (1u32 << (bd - 8)) as f32; @@ -323,4 +330,23 @@ mod tests { .is_none() ); } + + /// CodeRabbit #48: a plane claiming 500 000 × 500 000 pixels must be refused without ever + /// allocating for it (before the cap this vec was never built; upper-bounding allocation + /// would have been a 7.5-gibabuffer or a panic instead of an error). + #[test] + fn an_oversized_canvas_is_refused_without_allocation() { + let f = Frame { + width: 500_000, + height: 500_000, + bit_depth: 8, + chroma: ChromaFormat::Yuv420, + y: vec![128], + cb: vec![128; 4], + cr: vec![128; 4], + y_stride: 0, + c_stride: 0, + }; + assert!(to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, false, Upsampling::Nearest).is_none()); + } } diff --git a/crates/mcp/tests/e2e.rs b/crates/mcp/tests/it/e2e.rs similarity index 100% rename from crates/mcp/tests/e2e.rs rename to crates/mcp/tests/it/e2e.rs diff --git a/crates/mcp/tests/it/main.rs b/crates/mcp/tests/it/main.rs new file mode 100644 index 0000000000..7fce2464b6 --- /dev/null +++ b/crates/mcp/tests/it/main.rs @@ -0,0 +1,3 @@ +//! The integration tests, one module per file, linked into one test binary. + +mod e2e; diff --git a/crates/merge/src/align.rs b/crates/merge/src/align.rs index 34a6061550..be103c4e58 100644 --- a/crates/merge/src/align.rs +++ b/crates/merge/src/align.rs @@ -5,7 +5,6 @@ use lightcraft_geom::{Homography, Point}; use lightcraft_raster::resample::{Filter, fit}; use lightcraft_raster::{Plane, Rgb32f}; -use rayon::prelude::*; use crate::features::{self, Features}; use crate::ransac::{self, Model}; @@ -129,23 +128,10 @@ pub fn align_pair(ref_feat: &Features, feat: &Features, scale: f64, full_w: usiz /// Resample `img` into the reference geometry: `out(p) = img(h(p))` (Lanczos-3). Returns the warped /// image and a validity mask (false where `h(p)` falls outside `img`). pub fn warp(img: &Rgb32f, h: &Homography) -> (Rgb32f, Vec<bool>) { - let (w, ht) = (img.width, img.height); if *h == Homography::IDENTITY { - return (img.clone(), vec![true; w * ht]); + return (img.clone(), vec![true; img.width * img.height]); } - let mut out = Rgb32f::new(w, ht); - let mut valid = vec![false; w * ht]; - out.data.par_chunks_mut(w).zip(valid.par_chunks_mut(w)).enumerate().for_each(|(y, (row, vrow))| { - for x in 0..w { - let p = h.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); - let (sx, sy) = (p.x as f32, p.y as f32); - if sx >= 0.0 && sy >= 0.0 && sx <= w as f32 && sy <= ht as f32 { - row[x] = img.sample_lanczos3(sx, sy); - vrow[x] = true; - } - } - }); - (out, valid) + crate::flow::warp(img, h, &crate::flow::Flow::default()) } #[cfg(test)] diff --git a/crates/merge/src/flow.rs b/crates/merge/src/flow.rs new file mode 100644 index 0000000000..a8a9a6bf91 --- /dev/null +++ b/crates/merge/src/flow.rs @@ -0,0 +1,239 @@ +//! Local alignment: what one motion model for the whole frame leaves. +//! +//! A homography is exact only for a camera that turned about its lens. Handheld, the camera also +//! moves, and things at different distances shift differently (parallax): on a real bracket (Sony, +//! 33 MP, gravel a few metres away and a building a kilometre off) the fit, dominated by the +//! foreground's texture, left the building 2.3 px off, and the merge doubled its inscription. Lens +//! distortion and rolling shutter leave local shifts too. +//! +//! After the global fit ([`crate::align`], [`crate::refine`]) the frame is compared with the +//! reference tile by tile: +//! +//! 1. **Measure.** On a grid of about [`GRID`] tiles along the long edge, the reference's patch at +//! the tile's centre is found in the frame, through the global fit, within [`RADIUS`] pixels +//! ([`crate::refine::match_patch`]: masked correlation, sub-pixel peak, ambiguous and textureless +//! patches dropped). +//! 2. **Clean.** A shift more than [`OUTLIER`] px from the median of its measured neighbours is +//! dropped (a person walking, a mismatch), as is one with no measured neighbour to check it by. Tiles without a measurement take the mean of their +//! measured neighbours, spreading outwards until every tile has one. +//! 3. **Smooth** with two 3 × 3 box passes, so the field bends gently. +//! 4. **Warp.** Each output pixel `p` samples the frame at `h(p + flow(p))` (the flow interpolated +//! bilinearly between tile centres): one Lanczos-3 resampling for both corrections. + +use lightcraft_geom::{Homography, Point}; +use lightcraft_raster::{Plane, Rgb32f}; +use rayon::prelude::*; + +use crate::refine::{self, PATCH}; + +/// Tiles along the long edge. +pub const GRID: usize = 96; +/// Largest local shift measured (pixels); farther ones are filled from neighbours. +pub const RADIUS: usize = 5; +/// A tile this far (pixels) from the median of its neighbours is an outlier. +pub const OUTLIER: f32 = 0.75; + +/// A smooth field of local shifts in reference pixels: one value per tile, tile `(i, j)`'s at +/// `((i + ½)·step, (j + ½)·step)`, so pixel centres of `dx` / `dy` line up with the tiles'. +#[derive(Clone, Debug, PartialEq)] +pub struct Flow { + pub step: usize, + pub dx: Plane, + pub dy: Plane, + /// Tiles that were measured (before filling). + pub measured: usize, +} + +impl Default for Flow { + /// No shift anywhere. + fn default() -> Self { + Flow { step: 0, dx: Plane::new(0, 0), dy: Plane::new(0, 0), measured: 0 } + } +} + +impl Flow { + /// The shift at reference coordinates (pixel centres at +0.5), bilinear between tile centres; + /// zero for an empty flow. + pub fn at(&self, x: f64, y: f64) -> (f64, f64) { + let (fx, fy) = ((x / self.step as f64) as f32, (y / self.step as f64) as f32); + if self.dx.data.is_empty() || !fx.is_finite() || !fy.is_finite() { + return (0.0, 0.0); + } + (crate::features::bilinear(&self.dx, fx, fy) as f64, crate::features::bilinear(&self.dy, fx, fy) as f64) + } + + /// The largest shift in the field (pixels). + pub fn max(&self) -> f32 { + self.dx.data.iter().zip(&self.dy.data).map(|(x, y)| x.hypot(*y)).fold(0.0, f32::max) + } +} + +/// The local shifts between `reference` and `frame` (both from [`refine::luma`]) once `h` (reference +/// → frame pixels) is applied, within `radius` pixels. +pub fn estimate(reference: &Plane, frame: &Plane, h: &Homography, radius: usize) -> Flow { + let (w, ht) = (reference.width, reference.height); + // an even step, so a patch centred on a tile has a whole-pixel corner + let step = ((w.max(ht) / GRID).max(PATCH) + 1) & !1; + let (gw, gh) = (w / step, ht / step); + if gw == 0 || gh == 0 || frame.data.is_empty() { + return Flow::default(); + } + let r = radius.max(1); + let raw: Vec<Option<[f32; 2]>> = (0..gw * gh) + .into_par_iter() + .map(|t| { + let (i, j) = (t % gw, t / gw); + let (sx, sy) = (i * step + (step - PATCH) / 2, j * step + (step - PATCH) / 2); + if sx < r + 1 || sy < r + 1 || sx + PATCH + r + 1 > w || sy + PATCH + r + 1 > ht { + return None; + } + refine::match_patch(reference, (sx, sy), frame, h, r).map(|m| [m.offset.x as f32, m.offset.y as f32]) + }) + .collect(); + let measured = raw.iter().filter(|v| v.is_some()).count(); + let at = |d: &[Option<[f32; 2]>], k: usize| d.get(k).copied().flatten(); + // 2. outliers against the median of their measured neighbours + let mut d: Vec<Option<[f32; 2]>> = (0..gw * gh) + .map(|t| { + let v = at(&raw, t)?; + let n = neighbours(|k| at(&raw, k), gw, gh, t); + let med = [median(n.iter().map(|v| v[0]).collect()), median(n.iter().map(|v| v[1]).collect())]; + // a tile with no measured neighbour can't be checked, and the fill would spread it: dropped + (!n.is_empty() && (v[0] - med[0]).hypot(v[1] - med[1]) <= OUTLIER).then_some(v) + }) + .collect(); + // fill outwards from measured tiles + for _ in 0..gw + gh { + if d.iter().all(Option::is_some) || d.iter().all(Option::is_none) { + break; + } + let prev = d.clone(); + for (t, slot) in d.iter_mut().enumerate().filter(|(_, s)| s.is_none()) { + *slot = mean(&neighbours(|k| at(&prev, k), gw, gh, t)); + } + } + let mut f: Vec<[f32; 2]> = d.into_iter().map(|v| v.unwrap_or([0.0; 2])).collect(); + // 3. smooth (each tile with its neighbours) + for _ in 0..2 { + let prev = f.clone(); + for (t, v) in f.iter_mut().enumerate() { + let mut n = neighbours(|k| prev.get(k).copied(), gw, gh, t); + n.push(*v); + *v = mean(&n).unwrap_or(*v); + } + } + let plane = |c: usize| Plane::from_fn(gw, gh, |i, j| f.get(j * gw + i).map_or(0.0, |v| v[c])); + Flow { step, dx: plane(0), dy: plane(1), measured } +} + +/// The values `get` has among the 8 neighbours of tile `t`. +fn neighbours(get: impl Fn(usize) -> Option<[f32; 2]>, gw: usize, gh: usize, t: usize) -> Vec<[f32; 2]> { + let (i, j) = (t % gw, t / gw); + let mut out = Vec::with_capacity(8); + for b in j.saturating_sub(1)..=(j + 1).min(gh - 1) { + for a in i.saturating_sub(1)..=(i + 1).min(gw - 1) { + if (a, b) != (i, j) + && let Some(v) = get(b * gw + a) + { + out.push(v); + } + } + } + out +} + +fn mean(n: &[[f32; 2]]) -> Option<[f32; 2]> { + let k = n.len() as f32; + (!n.is_empty()).then(|| [n.iter().map(|v| v[0]).sum::<f32>() / k, n.iter().map(|v| v[1]).sum::<f32>() / k]) +} + +fn median(mut v: Vec<f32>) -> f32 { + v.sort_by(|a, b| a.total_cmp(b)); + v.get(v.len() / 2).copied().unwrap_or(0.0) +} + +/// `img` resampled into the reference's geometry through `h` after the local shifts: +/// `out(p) = img(h(p + flow(p)))` (Lanczos-3), and where that falls inside `img`. +pub fn warp(img: &Rgb32f, h: &Homography, flow: &Flow) -> (Rgb32f, Vec<bool>) { + let (w, ht) = (img.width, img.height); + let mut out = Rgb32f::new(w, ht); + let mut valid = vec![false; w * ht]; + if w == 0 || ht == 0 { + return (out, valid); + } + out.data.par_chunks_mut(w).zip(valid.par_chunks_mut(w)).enumerate().for_each(|(y, (row, vrow))| { + for x in 0..w { + let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); + let (dx, dy) = flow.at(px, py); + let q = h.apply(Point::new(px + dx, py + dy)); + let (sx, sy) = (q.x as f32, q.y as f32); + if sx >= 0.0 && sy >= 0.0 && sx <= w as f32 && sy <= ht as f32 { + row[x] = img.sample_lanczos3(sx, sy); + vrow[x] = true; + } + } + }); + (out, valid) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::refine::tests::tex; + + /// Parallax: the top of the frame (far) shifted 2.2 px against the bottom (near), with a + /// smooth band between. The flow finds both, and the warp lines the frame up everywhere. + #[test] + fn finds_and_undoes_a_local_shift() { + let (w, h) = (1200usize, 800usize); + let shift = |y: f64| { + let t = ((y - 300.0) / 200.0).clamp(0.0, 1.0); + let s = t * t * (3.0 - 2.0 * t); + ((1.0 - s) * 2.2, (1.0 - s) * -1.1) + }; + let reference = Plane::from_fn(w, h, |x, y| tex(x as f64 + 0.5, y as f64 + 0.5)); + // the frame's pixel q shows the scene at q + shift(q.y) + let frame = Rgb32f::from_fn(w, h, |x, y| { + let (sx, sy) = shift(y as f64 + 0.5); + [tex(x as f64 + 0.5 + sx, y as f64 + 0.5 + sy); 3] + }); + let fl = refine::luma(&frame, 1.0, 10.0); + let flow = estimate(&reference, &fl, &Homography::IDENTITY, RADIUS); + let tiles = flow.dx.width * flow.dx.height; + assert!(flow.measured > tiles / 2, "{} of {tiles}", flow.measured); + // reference p matches frame p + d with d = −shift + let (tx, ty) = flow.at(600.0, 100.0); + assert!((tx + 2.2).abs() < 0.15 && (ty - 1.1).abs() < 0.15, "top {tx} {ty}"); + let (bx, by) = flow.at(600.0, 700.0); + assert!(bx.abs() < 0.15 && by.abs() < 0.15, "bottom {bx} {by}"); + let (out, valid) = warp(&frame, &Homography::IDENTITY, &flow); + let error = |img: &Rgb32f| { + let (mut e, mut n) = (0f64, 0usize); + for y in (40..h - 40).step_by(3) { + for x in (40..w - 40).step_by(3) { + if valid[y * w + x] { + e += (img.get(x, y)[0] - reference.get(x, y)).abs() as f64; + n += 1; + } + } + } + e / n as f64 + }; + let (before, after) = (error(&frame), error(&out)); + assert!(after < before / 6.0, "mean error {before} unwarped, {after} warped"); + } + + #[test] + fn empty_and_flat_inputs_give_no_shift() { + let flat = Plane::from_fn(400, 300, |_, _| 0.5); + let f = estimate(&flat, &flat, &Homography::IDENTITY, RADIUS); + assert_eq!(f.measured, 0); + assert_eq!(f.max(), 0.0); + assert_eq!(estimate(&Plane::new(0, 0), &Plane::new(0, 0), &Homography::IDENTITY, 3), Flow::default()); + assert_eq!(estimate(&flat, &Plane::new(0, 0), &Homography::IDENTITY, 3), Flow::default()); + assert_eq!(Flow::default().at(5.0, f64::NAN), (0.0, 0.0)); + assert_eq!(f.at(f64::INFINITY, 3.0), (0.0, 0.0)); + let (img, v) = warp(&Rgb32f::new(0, 0), &Homography::IDENTITY, &Flow::default()); + assert!(img.data.is_empty() && v.is_empty()); + } +} diff --git a/crates/merge/src/lib.rs b/crates/merge/src/lib.rs index 4b4e206e63..ca7f918215 100644 --- a/crates/merge/src/lib.rs +++ b/crates/merge/src/lib.rs @@ -15,12 +15,14 @@ pub mod align; pub mod features; +pub mod flow; pub mod frame; pub mod hdr; pub mod linalg; pub mod output; pub mod pano; pub mod ransac; +pub mod refine; pub mod synth; pub use frame::{Frame, FrameColor, RawColour, load_frame, load_frame_with}; @@ -32,6 +34,8 @@ pub use pano::{PanoOptions, PanoResult, Projection, stitch}; pub enum MergeError { #[error("{0} photo(s) selected; at least {1} are needed")] TooFew(usize, usize), + #[error("{0} photo(s) selected; a stitch of more than {1} is refused: matching every pair would take far too long")] + TooMany(usize, usize), #[error("{0}")] Mismatch(String), #[error("could not read a photo: {0}")] diff --git a/crates/merge/src/pano/camera.rs b/crates/merge/src/pano/camera.rs index 7625170c3f..4589f88db3 100644 --- a/crates/merge/src/pano/camera.rs +++ b/crates/merge/src/pano/camera.rs @@ -61,10 +61,12 @@ pub struct PairMatch { /// Match every pair of images. `feats[k]` are in work coordinates scaled by `scales[k]`. pub fn match_pairs(feats: &[Features], scales: &[f64]) -> Vec<PairMatch> { let n = feats.len(); - let pairs: Vec<(usize, usize)> = (0..n).flat_map(|i| (i + 1..n).map(move |j| (i, j))).collect(); - let mut out: Vec<PairMatch> = pairs - .par_iter() - .filter_map(|&(i, j)| { + // the pairs are generated lazily: materialising all n(n−1)/2 up front is quadratic memory, including + // when every comparison comes up empty (no usable features) + let mut out: Vec<PairMatch> = (0..n) + .into_par_iter() + .flat_map_iter(|i| ((i + 1)..n).map(move |j| (i, j))) + .filter_map(|(i, j)| { let m = features::match_features(&feats[i], &feats[j], 0.8); if m.len() < 12 { return None; diff --git a/crates/merge/src/pano/mod.rs b/crates/merge/src/pano/mod.rs index 5ce4396811..ba7e1c63f4 100644 --- a/crates/merge/src/pano/mod.rs +++ b/crates/merge/src/pano/mod.rs @@ -53,6 +53,11 @@ impl Default for PanoOptions { /// The largest panorama, in megapixels (Lightroom's limit too); a bigger one is scaled down. pub const MAX_MEGAPIXELS: f64 = 512.0; +/// Most frames one stitch accepts: pair matching compares every pair of frames (n(n−1)/2 runs), so an +/// unbounded frame count is quadratic CPU as well as quadratic memory while the frames load. A panorama +/// with more than [`MAX_FRAMES`] shots is refused with an error, not attempted. +pub const MAX_FRAMES: usize = 256; + /// The longest edge of a panorama, in pixels (Lightroom's limit too); a longer one is scaled down. pub const MAX_EDGE: f64 = 65_000.0; @@ -224,6 +229,9 @@ pub fn stitch(mut frames: Vec<Frame>, opts: &PanoOptions, progress: &Progress) - if n < 2 { return Err(MergeError::TooFew(n, 2)); } + if n > MAX_FRAMES { + return Err(MergeError::TooMany(n, MAX_FRAMES)); + } check(progress, 0.01, "Finding features")?; let (cams, rms_before, rms) = register(&frames, progress)?; let used: Vec<usize> = (0..n).filter(|&i| cams[i].is_some()).collect(); diff --git a/crates/merge/src/refine.rs b/crates/merge/src/refine.rs new file mode 100644 index 0000000000..e9044bc8bb --- /dev/null +++ b/crates/merge/src/refine.rs @@ -0,0 +1,359 @@ +//! Full-resolution refinement of an alignment found on small versions of the frames. +//! +//! [`crate::align`] registers frames on versions of at most [`crate::align::WORK_EDGE`] pixels. +//! For a 24–60 MP photo that is 5–8× smaller, and a tenth of a work pixel off is most of a full +//! pixel off: merged frames that far apart blur the result. Here the motion is fitted again at +//! full size: +//! +//! 1. **Sites.** The reference is cut into a grid of cells (≈ [`CELLS`] along the long edge); in +//! each, the [`PATCH`]-pixel square with the most two-dimensional texture (the smaller +//! eigenvalue of its gradient structure tensor, so a straight edge, which only fixes one +//! direction, doesn't count) is a site. +//! 2. **Matching.** Each site's patch is compared with the frame resampled through the current +//! alignment, by normalised cross-correlation (immune to the frames' different brightness and +//! contrast) over integer offsets within a search radius, counting only pixels usable in both +//! (clipped ones aren't); the peak is refined to a fraction of a pixel by a parabola through its +//! neighbours on each axis. Patches less than half usable, with too little texture, a weak peak, a peak on the search border or a second peak almost +//! as strong (repeating texture) are dropped. +//! 3. **Fit.** The matches are fitted with RANSAC at [`THRESH`] pixels, choosing the simplest of +//! translation / similarity / homography that explains (nearly) as many as the most general +//! one, as [`crate::align::align_pair`] does. A second, narrower pass starts from that fit. +//! +//! When too few patches match, or the fit isn't a plausible handheld motion, the alignment found +//! on the small versions stays: refining never makes an alignment worse than not refining. + +use lightcraft_geom::{Homography, Point}; +use lightcraft_raster::{Plane, Rgb32f}; +use rayon::prelude::*; + +use crate::align::{Alignment, Models, choose_model, luma as lum}; +use crate::ransac::Model; + +/// Side of a matched patch (pixels). +pub const PATCH: usize = 48; +/// Cells along the long edge (sites are picked one per cell). +pub const CELLS: usize = 24; +/// RANSAC inlier threshold at full resolution (pixels). +pub const THRESH: f64 = 0.75; +/// Weakest correlation peak a match may have. +const MIN_SCORE: f32 = 0.8; +/// The best peak away from the best one must be at least this much weaker. +const UNIQUE: f32 = 0.03; +/// Least standard deviation (of the gamma-encoded luminance) a patch needs to be matched. +const MIN_STD: f32 = 0.01; +/// Fewest matches a fit is made from. +const MIN_MATCHES: usize = 12; +/// Share of the matches the fit must explain. +const MIN_SHARE: f64 = 0.4; + +/// A frame's luminance for matching: `(luminance · gain)^(1/2.2)` at full size, NaN where the +/// frame is clipped (any channel at or above 95 % of `clip`) or `gain` takes it past 1, so such +/// pixels never take part. `gain` brings frames of a bracket to the same brightness. +pub fn luma(img: &Rgb32f, gain: f32, clip: f32) -> Plane { + let g = if gain.is_finite() && gain > 0.0 { gain } else { 1.0 }; + img.map(|c| { + if c[0].max(c[1]).max(c[2]) >= 0.95 * clip { + return f32::NAN; + } + let y = lum(c) * g; + if y.is_finite() && y < 1.0 { y.max(0.0).powf(1.0 / 2.2) } else { f32::NAN } + }) +} + +/// The search radius (full-resolution pixels) for an alignment found at `scale` (work pixels per +/// full pixel): about two work pixels. +pub fn radius_for(scale: f64) -> usize { + if scale.is_finite() && scale > 0.0 { ((2.0 / scale).ceil() as usize + 1).clamp(3, 16) } else { 3 } +} + +/// A patch of the reference found in a frame. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Match { + /// Centre of the patch in the reference (pixel centres at +0.5). + pub reference: Point, + /// Where it is in the frame. + pub frame: Point, + /// The offset from where the alignment put it, in reference pixels. + pub offset: Point, + /// Correlation at the peak (−1..1). + pub score: f32, +} + +/// Top-left corners of the patches to match: one per cell, where the reference has the most +/// two-dimensional texture, `margin` pixels clear of the edges. +pub fn sites(reference: &Plane, margin: usize) -> Vec<(usize, usize)> { + let (w, h) = (reference.width, reference.height); + let need = PATCH + 2 * margin; + if w < need || h < need { + return Vec::new(); + } + let long = w.max(h); + let cell = long.div_ceil(CELLS).max(PATCH); + let (nx, ny) = ((w - 2 * margin) / cell, (h - 2 * margin) / cell); + let (nx, ny) = (nx.max(1), ny.max(1)); + let (cw, chh) = ((w - 2 * margin) / nx, (h - 2 * margin) / ny); + (0..nx * ny) + .into_par_iter() + .filter_map(|c| { + let (cx, cy) = (margin + (c % nx) * cw, margin + (c / nx) * chh); + let span_x = cw.saturating_sub(PATCH); + let span_y = chh.saturating_sub(PATCH); + let mut best: Option<((usize, usize), f32)> = None; + for j in 0..3 { + for i in 0..3 { + let (x, y) = (cx + span_x * i / 2, cy + span_y * j / 2); + if x + PATCH > w - margin || y + PATCH > h - margin { + continue; + } + if let Some(t) = texture(reference, x, y) + && best.is_none_or(|(_, b)| t > b) + { + best = Some(((x, y), t)); + } + } + } + best.filter(|(_, t)| *t > 1e-6).map(|(p, _)| p) + }) + .collect() +} + +/// The smaller eigenvalue of the patch's mean gradient structure tensor, over its usable pixels; +/// `None` when fewer than half of them are. +fn texture(p: &Plane, x0: usize, y0: usize) -> Option<f32> { + let w = p.width; + let at = |x: usize, y: usize| p.data.get(y * w + x).copied().unwrap_or(f32::NAN); + let (mut sxx, mut syy, mut sxy, mut n) = (0f64, 0f64, 0f64, 0usize); + for y in y0 + 1..y0 + PATCH - 1 { + for x in x0 + 1..x0 + PATCH - 1 { + let gx = (at(x + 1, y) - at(x - 1, y)) as f64; + let gy = (at(x, y + 1) - at(x, y - 1)) as f64; + if gx.is_finite() && gy.is_finite() { + sxx += gx * gx; + syy += gy * gy; + sxy += gx * gy; + n += 1; + } + } + } + if n * 2 < (PATCH - 2) * (PATCH - 2) { + return None; + } + let n = n as f64; + let (a, b, c) = (sxx / n, syy / n, sxy / n); + let tr = a + b; + let det = a * b - c * c; + Some((tr / 2.0 - ((tr * tr / 4.0 - det).max(0.0)).sqrt()) as f32) +} + +/// Find the reference patch at `site` (top-left) in `frame`, which `h` maps reference pixels into, +/// searching offsets up to `radius` pixels. +pub fn match_patch(reference: &Plane, site: (usize, usize), frame: &Plane, h: &Homography, radius: usize) -> Option<Match> { + let (sx, sy) = site; + let (rw, rh) = (reference.width, reference.height); + if sx + PATCH > rw || sy + PATCH > rh || frame.width == 0 || frame.height == 0 { + return None; + } + let r = radius.max(1); + let s = PATCH + 2 * r; + let mut pr: Vec<f32> = Vec::with_capacity(PATCH * PATCH); + for y in sy..sy + PATCH { + for x in sx..sx + PATCH { + pr.push(reference.data.get(y * rw + x).copied().unwrap_or(f32::NAN)); + } + } + // the frame around the patch, through `h`; NaN where it can't be used + let (fw, fh) = (frame.width as f64, frame.height as f64); + let mut win = vec![f32::NAN; s * s]; + for j in 0..s { + for i in 0..s { + let q = h.apply(Point::new((sx + i) as f64 - r as f64 + 0.5, (sy + j) as f64 - r as f64 + 0.5)); + if !(q.x >= 0.5 && q.y >= 0.5 && q.x <= fw - 0.5 && q.y <= fh - 0.5) { + return None; + } + win[j * s + i] = crate::features::bilinear(frame, q.x as f32, q.y as f32); + } + } + let d = 2 * r + 1; + // offsets that can't be scored (too few usable pixels) stay at −∞ + let mut score = vec![f32::NEG_INFINITY; d * d]; + for dy in 0..d { + for dx in 0..d { + if let Some(c) = correlation(&pr, |u, v| win.get((v + dy) * s + dx + u).copied().unwrap_or(f32::NAN)) { + score[dy * d + dx] = c; + } + } + } + let (bi, &best) = score.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1))?; + let (bx, by) = (bi % d, bi / d); + if best < MIN_SCORE || bx == 0 || by == 0 || bx == d - 1 || by == d - 1 { + return None; + } + // a second peak nearly as strong: repeating texture, the match is ambiguous + let second = + score.iter().enumerate().filter(|(k, _)| (k % d).abs_diff(bx) > 1 || (k / d).abs_diff(by) > 1).map(|(_, v)| *v).fold(-1f32, f32::max); + if second > best - UNIQUE { + return None; + } + let at = |x: usize, y: usize| score[y * d + x]; + // the sub-pixel parabola needs the peak's four neighbours: one that couldn't be scored would pull it away + if [at(bx - 1, by), at(bx + 1, by), at(bx, by - 1), at(bx, by + 1)].iter().any(|v| !v.is_finite()) { + return None; + } + let sub = |m: f32, c: f32, p: f32| { + let den = m - 2.0 * c + p; + if den < -1e-9 { (0.5 * (m - p) / den).clamp(-0.5, 0.5) } else { 0.0 } + }; + let ox = bx as f64 - r as f64 + sub(at(bx - 1, by), best, at(bx + 1, by)) as f64; + let oy = by as f64 - r as f64 + sub(at(bx, by - 1), best, at(bx, by + 1)) as f64; + let c = Point::new(sx as f64 + PATCH as f64 / 2.0, sy as f64 + PATCH as f64 / 2.0); + Some(Match { reference: c, frame: h.apply(Point::new(c.x + ox, c.y + oy)), offset: Point::new(ox, oy), score: best }) +} + +/// Correlation of the reference patch `a` (row-major, [`PATCH`] wide) with `b(u, v)` over the +/// pixels usable in both; `None` with fewer than half of the patch usable, or too little texture in +/// either. +fn correlation(a: &[f32], b: impl Fn(usize, usize) -> f32) -> Option<f32> { + let (mut n, mut sa, mut sb, mut saa, mut sbb, mut sab) = (0usize, 0f64, 0f64, 0f64, 0f64, 0f64); + for v in 0..PATCH { + for u in 0..PATCH { + let (x, y) = (a.get(v * PATCH + u).copied().unwrap_or(f32::NAN), b(u, v)); + if x.is_finite() && y.is_finite() { + let (x, y) = (x as f64, y as f64); + n += 1; + sa += x; + sb += y; + saa += x * x; + sbb += y * y; + sab += x * y; + } + } + } + if n * 2 < PATCH * PATCH { + return None; + } + let nf = n as f64; + let (ma, mb) = (sa / nf, sb / nf); + let (va, vb) = (saa / nf - ma * ma, sbb / nf - mb * mb); + let min = (MIN_STD as f64).powi(2); + if !(va >= min && vb >= min * 0.25) { + return None; + } + let c = (sab / nf - ma * mb) / (va * vb).sqrt(); + c.is_finite().then_some(c as f32) +} + +/// Translation, similarity and homography: what a handheld frame may need. +pub const ALL_MODELS: [(Model, &str, usize); 3] = + [(Model::Translation, "translation", 6), (Model::Similarity, "similarity", 8), (Model::Homography, "homography", 12)]; + +/// Search radius (pixels) for a frame with no alignment to start from (the small versions found +/// none: a bright frame mostly clipped, too little texture left for features). +pub const RECOVER_RADIUS: usize = 16; + +/// Fit `models` (reference → frame, full resolution) to patches of `reference` matched in `frame` +/// around `start` within `radius` pixels, then again within 2 px of that fit; both planes from +/// [`luma`]. `start` is an alignment found on small versions (`radius` from [`radius_for`]), or the +/// identity with [`RECOVER_RADIUS`]. `None` when too few patches match or no fit is a plausible +/// handheld motion: the caller keeps what it had. +pub fn fit(reference: &Plane, frame: &Plane, start: &Homography, radius: usize, seed: u64, models: &Models) -> Option<Alignment> { + let (w, ht) = (reference.width as f64, reference.height as f64); + let r0 = radius.max(2); + // the sites for the widest search fit the narrower one too + let s = sites(reference, r0 + 2); + let mut cur: Option<Alignment> = None; + for r in [r0, 2] { + let h = cur.as_ref().map_or(*start, |a| a.h); + let m: Vec<Match> = s.par_iter().filter_map(|&p| match_patch(reference, p, frame, &h, r)).collect(); + if m.len() < MIN_MATCHES { + break; + } + let pa: Vec<Point> = m.iter().map(|m| m.reference).collect(); + let pb: Vec<Point> = m.iter().map(|m| m.frame).collect(); + let Some((name, f)) = choose_model(models, &pa, &pb, THRESH, MIN_SHARE, (w, ht), seed) else { break }; + cur = Some(Alignment { h: f.h, model: name, inliers: f.inliers.len(), rms: f.rms }); + } + cur +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// A smooth random texture, sampled anywhere. + pub(crate) fn tex(x: f64, y: f64) -> f32 { + let mut v = 0.45; + for k in 0..9 { + let a = k as f64 * 2.399; + let f = 0.02 + 0.025 * k as f64; + v += 0.05 * ((x * a.cos() + y * a.sin()) * f * std::f64::consts::TAU + k as f64).sin(); + } + v as f32 + } + + fn plane(w: usize, h: usize, map: &Homography) -> Plane { + Plane::from_fn(w, h, |x, y| { + let p = map.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); + tex(p.x, p.y) + }) + } + + fn corner_error(a: &Homography, b: &Homography, w: f64, h: f64) -> f64 { + [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].iter().map(|&(x, y)| a.apply(Point::new(x, y)).dist(b.apply(Point::new(x, y)))).fold(0.0, f64::max) + } + + /// A frame rotated 0.2° and moved 1.37 px, given an alignment 2 px off: refined to a tenth of + /// a pixel at the corners. + #[test] + fn refines_a_rough_alignment_to_a_fraction_of_a_pixel() { + let (w, h) = (900usize, 600usize); + let reference = plane(w, h, &Homography::IDENTITY); + // the frame's pixel q shows the scene at s(q); reference → frame is s⁻¹ + let (c, sn) = (0.2f64.to_radians().cos(), 0.2f64.to_radians().sin()); + let s = Homography([c, -sn, 1.37, sn, c, -0.83, 0.0, 0.0, 1.0]); + let truth = s.inverse().unwrap(); + let frame = plane(w, h, &s); + let rough = Homography([truth.0[0], truth.0[1], truth.0[2] + 1.6, truth.0[3], truth.0[4], truth.0[5] - 1.2, 0.0, 0.0, 1.0]); + assert!(corner_error(&rough, &truth, w as f64, h as f64) > 1.5); + let r = fit(&reference, &frame, &rough, 4, 1, &ALL_MODELS).unwrap(); + let e = corner_error(&r.h, &truth, w as f64, h as f64); + assert!(e < 0.1, "corner error {e} px, model {}", r.model); + assert!(r.inliers >= MIN_MATCHES); + } + + /// A frame the small versions couldn't align, 5 px and 0.1° off: found from nothing. + #[test] + fn recovers_a_frame_with_no_alignment() { + let (w, h) = (900usize, 600usize); + let reference = plane(w, h, &Homography::IDENTITY); + let (c, sn) = (0.1f64.to_radians().cos(), 0.1f64.to_radians().sin()); + let s = Homography([c, -sn, -4.6, sn, c, 2.1, 0.0, 0.0, 1.0]); + let r = fit(&reference, &plane(w, h, &s), &Homography::IDENTITY, RECOVER_RADIUS, 1, &ALL_MODELS).unwrap(); + let e = corner_error(&r.h, &s.inverse().unwrap(), w as f64, h as f64); + assert!(e < 0.1, "corner error {e} px, model {}", r.model); + assert!(fit(&reference, &Plane::from_fn(w, h, |_, _| 0.5), &Homography::IDENTITY, RECOVER_RADIUS, 1, &ALL_MODELS).is_none()); + } + + /// Nothing to match (a flat frame, planes too small for a patch, empty ones): no fit. + #[test] + fn no_fit_when_nothing_matches() { + let h = Homography([1.0, 0.0, 0.7, 0.0, 1.0, 0.2, 0.0, 0.0, 1.0]); + let flat = Plane::from_fn(400, 300, |_, _| 0.5); + assert!(fit(&flat, &flat, &h, 4, 1, &ALL_MODELS).is_none()); + let tiny = Plane::from_fn(20, 20, |x, _| x as f32); + assert!(fit(&tiny, &tiny, &h, 4, 1, &ALL_MODELS).is_none()); + assert!(fit(&Plane::new(0, 0), &Plane::new(0, 0), &h, 4, 1, &ALL_MODELS).is_none()); + } + + #[test] + fn clipped_pixels_and_odd_gains_are_left_out() { + let img = Rgb32f::from_fn(4, 1, |x, _| [x as f32 * 0.33; 3]); + let l = luma(&img, 1.0, 1.0); + assert!(l.data[0] == 0.0 && l.data[3].is_nan(), "{:?}", l.data); + let l = luma(&img, 4.0, 1.0); + assert!(l.data[1].is_nan(), "0.33 × 4 is past 1: {:?}", l.data); + assert!(luma(&img, f32::NAN, 1.0).data[1].is_finite()); + assert_eq!(radius_for(0.125), 16); + assert_eq!(radius_for(1.0), 3); + assert_eq!(radius_for(f64::NAN), 3); + } +} diff --git a/crates/merge/tests/hdr.rs b/crates/merge/tests/it/hdr.rs similarity index 100% rename from crates/merge/tests/hdr.rs rename to crates/merge/tests/it/hdr.rs diff --git a/crates/merge/tests/it/main.rs b/crates/merge/tests/it/main.rs new file mode 100644 index 0000000000..0859919cd6 --- /dev/null +++ b/crates/merge/tests/it/main.rs @@ -0,0 +1,5 @@ +//! The integration tests, one module per file, linked into one test binary. + +mod hdr; +mod pano; +mod white_balance; diff --git a/crates/merge/tests/pano.rs b/crates/merge/tests/it/pano.rs similarity index 94% rename from crates/merge/tests/pano.rs rename to crates/merge/tests/it/pano.rs index fdb736524f..aeecde64cf 100644 --- a/crates/merge/tests/pano.rs +++ b/crates/merge/tests/it/pano.rs @@ -246,6 +246,18 @@ fn unrelated_photos_do_not_stitch() { assert!(stitch(frames, &PanoOptions::default(), &no_progress).is_err()); } +/// Pair matching compares every pair of frames before anything is known about them: an unbounded +/// photo count is quadratic CPU and memory (issue #1519). More than `MAX_FRAMES` is refused at once, +/// before any frame is worked on. +#[test] +fn a_stitch_of_more_than_the_frame_cap_is_refused_up_front() { + let frames: Vec<Frame> = (0..lightcraft_merge::pano::MAX_FRAMES + 1) + .map(|i| Frame::from_linear_rec2020(Rgb32f::from_fn(8, 8, |_, _| [(i % 255) as f32 / 255.0, 0.0, 0.0]), None)) + .collect(); + let err = stitch(frames, &PanoOptions::default(), &no_progress).unwrap_err(); + assert!(err.to_string().contains("refused"), "the frame cap errors, it does not begin the quadratic match: {err}"); +} + /// Issue #1455: a panorama came out at 40 MP whatever its photos' resolution. It now keeps their /// own resolution unless a size is asked for (up to Lightroom's 512 MP); a size scales it down, /// and a NaN one (from an agent) is no size at all, not a 0.1 MP thumbnail. diff --git a/crates/merge/tests/white_balance.rs b/crates/merge/tests/it/white_balance.rs similarity index 100% rename from crates/merge/tests/white_balance.rs rename to crates/merge/tests/it/white_balance.rs diff --git a/crates/meta/README.md b/crates/meta/README.md index 83ee9e6016..519426784a 100644 --- a/crates/meta/README.md +++ b/crates/meta/README.md @@ -8,11 +8,12 @@ Photo metadata: EXIF, XMP (read + write), IPTC-IIM, and the containers that carr |---|---| | `read_exif(&[u8]) -> Metadata` | TIFF-structured Exif block (whole TIFF/DNG/raw file, or JPEG APP1 payload with/without `Exif\0\0`). `try_read_exif` reports header errors. | | `from_tiff(&Tiff) -> Metadata` | Same, from an already parsed stream (used by `lightcraft-raw`). | -| `embedded(&[u8]) -> Embedded` | Sniffs JPEG / PNG / WebP / TIFF and returns the Exif, XMP (+ extended XMP), ICC and IPTC blocks. `jpeg_segments`, `png_chunks`, `webp_chunks` are the per-container walkers. | +| `embedded(&[u8]) -> Embedded` | Sniffs JPEG / PNG / WebP / TIFF / PSD / PSB and returns the Exif, XMP (+ extended XMP), ICC and IPTC blocks. PSD/PSB EXIF resource 1058 and XMP resource 1060 are read from the bounded image-resource section without decoding pixels. `jpeg_segments`, `png_chunks`, `webp_chunks` are the per-container walkers. | | `parse_xmp(&str) -> Result<XmpData>` | Metadata + the opaque `lc:settings` JSON + every property (`prefix:name`, structs flattened as `a:b/c:d`). | | `write_xmp(&Metadata, Option<&str>) -> String` | Complete `<?xpacket?>` packet; the second argument is LightCraft's full develop settings JSON. | | `parse_iptc(&[u8]) -> Metadata` | IIM record 2: title (2:5), keywords (2:25), by-line (2:80), copyright (2:116), caption (2:120), date/time created (2:55/2:60). | | `extract(&[u8]) -> Metadata` | Everything for a whole file. Precedence: EXIF → IPTC fills gaps → XMP overrides user fields (rating, label, title, caption, artist, copyright, keywords, GPS) and fills the rest. | +| `try_extract(&[u8]) -> Result<Metadata, ExtractError>` | Like `extract`, but reports malformed PSD/PSB headers, image-resource sections, or embedded EXIF/XMP structure (including duplicate EXIF/XMP resources) so callers can fail closed when location absence cannot be established. Other formats remain best-effort. | `Metadata` carries camera (make, model, serial, software), lens (make, model, serial, specification), capture (date-time with UTC offset and milliseconds, exposure time, f-number, ISO incl. extended ISO, focal length and @@ -27,10 +28,19 @@ prefixes by namespace URI, handles attribute and element forms, `rdf:Seq`/`Bag`/ `rdf:parseType="Resource"` and nested-description structs, predefined and numeric entities. Nesting depth and node count are limited. +An explicitly foreign namespace using a recognized prefix (for example `lc` or `xmp`) cannot supply +recognized properties. Its keys use `Q{hex-encoded namespace URI}local` in `properties` and `values`; +hex encoding keeps `/` reserved for struct paths. Other unknown prefixes keep their existing QName keys. +Merging preserves the original foreign XML rather than writing these opaque keys into the packet. +The parser and merge scanner each cap generated opaque names at 8 MiB per packet, returning `TooComplex` +if repeated use of a long namespace URI would exceed that budget. + ## Robustness No panics on malformed input: proptests feed random bytes to every container walker and random text to the -XMP parser; truncation tests cut a sample JPEG at every byte. +XMP parser; truncation tests cut a sample JPEG at every byte and exercise truncated PSD/PSB headers and +image-resource records with hostile declared lengths. +PSD/PSB XMP resources require valid UTF-8; trailing NUL padding is trimmed after validation. ## Sources diff --git a/crates/meta/src/container.rs b/crates/meta/src/container.rs index 3ac60907fe..3cfb7e287f 100644 --- a/crates/meta/src/container.rs +++ b/crates/meta/src/container.rs @@ -7,6 +7,7 @@ //! - WebP (RIFF container spec): `EXIF`, `XMP `, `ICCP` chunks. //! - TIFF-based files (TIFF, DNG and most raws): the whole file is the Exif block; XMP (700), ICC (34675) and //! IPTC (33723) from IFD0. +//! - Photoshop PSD/PSB: EXIF (image resource 1058) and XMP (image resource 1060) from the bounded image-resource section. //! - Minolta MRW (see [`crate::mrw`]): the `TTW` block is the Exif block. //! - Canon CR3 (ISO base media file, see [`crate::cr3`]): `CMT1`/`CMT2`/`CMT4` merged into one Exif block; the //! XMP `uuid` box. @@ -29,6 +30,9 @@ pub struct Embedded { /// Sniff the container and collect its metadata blocks. Unknown containers yield an empty result. pub fn embedded(bytes: &[u8]) -> Embedded { + if bytes.starts_with(b"8BPS") { + return crate::psd::embedded(bytes); + } if bytes.starts_with(b"FUJIFILMCCD-RAW") { // Fujifilm RAF: metadata lives in the embedded JPEG whose (offset, length) are big-endian u32s at byte 84 let be = |i: usize| bytes.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); @@ -71,6 +75,12 @@ pub fn embedded(bytes: &[u8]) -> Embedded { } } +/// Locate metadata blocks while preserving PSD/PSB resource-structure errors for callers that +/// must establish whether embedded GPS is absent. Other containers keep their best-effort walk. +pub(crate) fn try_embedded(bytes: &[u8]) -> Result<Embedded, crate::ExtractError> { + if bytes.starts_with(b"8BPS") { crate::psd::parse(bytes).ok_or(crate::ExtractError::MalformedPsd) } else { Ok(embedded(bytes)) } +} + const XMP_SIG: &[u8] = b"http://ns.adobe.com/xap/1.0/\0"; const XMP_EXT_SIG: &[u8] = b"http://ns.adobe.com/xmp/extension/\0"; diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index cb45274d1d..adcba0f807 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -1,7 +1,7 @@ //! Exif / TIFF tags → [`Metadata`] (CIPA DC-008 Exif 2.32, TIFF 6.0, DNG 1.7 tag semantics). use crate::{DateTime, Flash, Gps, Metadata, Orientation}; -use lightcraft_tiff::{Ifd, Tiff, TiffError, tags as t}; +use lightcraft_tiff::{Ifd, ParseOptions, Tiff, TiffError, tags as t}; /// Strip an `Exif\0\0` (or `Exif\0\xff`) prefix as found in JPEG APP1 and some WebP `EXIF` chunks. pub fn strip_exif_header(b: &[u8]) -> &[u8] { @@ -16,8 +16,16 @@ pub fn read_exif(bytes: &[u8]) -> Metadata { /// Like [`read_exif`] but reports a structurally invalid TIFF header / IFD0. pub fn try_read_exif(bytes: &[u8]) -> Result<Metadata, TiffError> { + try_read_exif_with(bytes, &ParseOptions::default()) +} + +/// [`try_read_exif`] with the caller's parser options (its value allocation budget in particular). +/// A decoder working from a sparse buffer — only selected ranges of the logical file are actually +/// loaded, the rest is zeros — must not size its allocations by the logical file length, which +/// unrelated bytes of the file can inflate at no cost to the attacker. +pub fn try_read_exif_with(bytes: &[u8], opts: &ParseOptions) -> Result<Metadata, TiffError> { let data = strip_exif_header(bytes); - let tiff = Tiff::parse(data)?; + let tiff = Tiff::parse_with(data, opts)?; let mut m = from_tiff(&tiff); // Panasonic writes no LensModel, only the name in its maker note (and in a RW2 that note is not in the raw's own Exif) if m.lens_model.is_none() { @@ -456,6 +464,14 @@ pub(crate) mod tests { } } +/// An exact `1/N` rational for a sub-second value whose reciprocal is a whole number (shutter speeds such as +/// 1/12800 s, which [`lightcraft_tiff::writer::rational`]'s decimal denominators cannot represent). +fn reciprocal(v: Option<f64>) -> Option<lightcraft_tiff::Value> { + let v = v.filter(|v| v.is_finite() && *v > 0.0 && *v < 1.0)?; + let inv = 1.0 / v; + ((inv - inv.round()).abs() < 1e-6 && inv.round() <= u32::MAX as f64).then(|| lightcraft_tiff::Value::Rational(vec![(1, inv.round() as u32)])) +} + /// Serialise the interchange subset of `meta` as a TIFF-structured Exif block (little-endian, no /// `Exif\0\0` prefix): IFD0 (make, model, software, artist, copyright, description, orientation, /// date), the Exif IFD (capture settings, lens) and, when present, the GPS IFD. @@ -483,7 +499,7 @@ pub fn write_exif(meta: &Metadata) -> Vec<u8> { let r = |v: Option<f64>| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| Value::Rational(vec![rational(v)])); for (tag, v) in [ (t::DATE_TIME_ORIGINAL, meta.capture_time.map(|d| Value::Ascii(d.to_exif()))), - (t::EXPOSURE_TIME, r(meta.exposure_time)), + (t::EXPOSURE_TIME, reciprocal(meta.exposure_time).or_else(|| r(meta.exposure_time))), (t::F_NUMBER, r(meta.f_number)), (t::FOCAL_LENGTH, r(meta.focal_length)), (t::ISO_SPEED, meta.iso.map(|i| Value::Short(vec![i.min(65_535) as u16]))), @@ -561,4 +577,13 @@ mod write_tests { assert_eq!(back.iso, Some(iso)); } } + + #[test] + fn fast_shutter_speeds_round_trip_exactly() { + for den in [8000.0, 12_800.0, 16_000.0, 32_000.0] { + let back = read_exif(&write_exif(&Metadata { exposure_time: Some(1.0 / den), ..Default::default() })); + let got = back.exposure_time.unwrap(); + assert!((1.0 / got - den).abs() < 0.5, "1/{den} s came back as 1/{}", 1.0 / got); + } + } } diff --git a/crates/meta/src/focus_read.rs b/crates/meta/src/focus_read.rs index 5a5d349d11..65adbee754 100644 --- a/crates/meta/src/focus_read.rs +++ b/crates/meta/src/focus_read.rs @@ -171,7 +171,15 @@ fn tiff(r: &mut Reader, head: Vec<u8>) -> io::Result<Option<FocusPoint>> { loaded.insert(0, head.len() as u64); for _ in 0..MAX_ROUNDS { match plan(&buf, &loaded) { - Step::Ready => return Ok(crate::try_read_exif(&buf).ok().and_then(|m| m.focus)), + Step::Ready => { + // The decoder's allocation budget follows the bytes actually fetched, not the logical + // file length: only the loaded ranges are data, and an unrelated entry that claims a + // huge value must be cut by what leaving it cost, not by what the buffer claims to hold. + // The same 8 × / + 1 MiB shape the general TIFF reader uses, over `reader.bytes` instead. + let opts = + lightcraft_tiff::ParseOptions { value_budget: Some(r.bytes.saturating_mul(8).saturating_add(1 << 20)), ..Default::default() }; + return Ok(crate::try_read_exif_with(&buf, &opts).ok().and_then(|m| m.focus)); + } Step::Nothing => return Ok(None), Step::Need(ranges) => { for (a, b) in ranges { diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 59062dfda9..46c7a10432 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -7,7 +7,7 @@ //! - [`parse_xmp`] / [`write_xmp`] — XMP packets (interchange fields + the opaque `lc:settings` JSON). //! - [`parse_iptc`] — IPTC-IIM record 2 datasets. //! - [`parse_gpx`] — GPS track logs (GPX) for geotagging by capture time. -//! - [`extract`] — all of the above for a whole file (JPEG, PNG, WebP, TIFF/DNG/raw, Canon CR3). +//! - [`extract`] — all of the above for a whole file (JPEG, PNG, WebP, TIFF/DNG/raw, PSD/PSB, Canon CR3). //! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks). #![forbid(unsafe_code)] @@ -20,13 +20,14 @@ mod focus_read; mod gpx; mod iptc; pub mod mrw; +mod psd; pub mod tags; mod xmp; mod xmp_merge; pub use container::{Embedded, embedded, jpeg_segments, png_chunks, webp_chunks}; pub use datetime::DateTime; -pub use exif::{from_tiff, read_exif, strip_exif_header, try_read_exif, write_exif}; +pub use exif::{from_tiff, read_exif, strip_exif_header, try_read_exif, try_read_exif_with, write_exif}; pub use focus::FocusPoint; pub use gpx::{GpxError, Match, TrackPoint, Tracklog, parse_gpx}; pub use iptc::parse_iptc; @@ -282,17 +283,57 @@ impl Metadata { /// Precedence: EXIF, then IPTC fills gaps, then XMP overrides user fields and fills the rest. pub fn extract(bytes: &[u8]) -> Metadata { let e = embedded(bytes); - let mut m = e.exif.as_deref().map(read_exif).unwrap_or_default(); + let exif = e.exif.as_deref().map(read_exif).unwrap_or_default(); + let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok()).map(|xmp| xmp.metadata); + extract_embedded(e, exif, xmp) +} + +/// Read metadata while reporting malformed PSD/PSB containers, embedded EXIF, or embedded XMP instead of treating +/// them as empty. Other container formats retain [`extract`]'s best-effort behavior. +pub fn try_extract(bytes: &[u8]) -> Result<Metadata, ExtractError> { + let e = container::try_embedded(bytes)?; + let is_psd = bytes.starts_with(b"8BPS"); + let exif = match e.exif.as_deref() { + Some(exif) if is_psd => try_read_exif(exif).map_err(|_| ExtractError::MalformedPsd)?, + Some(exif) => read_exif(exif), + None => Metadata::default(), + }; + let xmp = match e.xmp.as_deref() { + Some(xmp) if is_psd => Some(parse_xmp(xmp).map_err(|_| ExtractError::MalformedPsd)?.metadata), + Some(xmp) => parse_xmp(xmp).ok().map(|xmp| xmp.metadata), + None => None, + }; + Ok(extract_embedded(e, exif, xmp)) +} + +fn extract_embedded(e: Embedded, mut m: Metadata, xmp: Option<Metadata>) -> Metadata { if let Some(i) = e.iptc.as_deref() { m.fill_missing(&parse_iptc(i)); } - if let Some(x) = e.xmp.as_deref().and_then(|x| parse_xmp(x).ok()) { - m.overlay_user_fields(&x.metadata); - m.fill_missing(&x.metadata); + if let Some(xmp) = xmp { + m.overlay_user_fields(&xmp); + m.fill_missing(&xmp); } m } +/// A container-level error reported by [`try_extract`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExtractError { + /// The PSD/PSB header, image-resource section, or embedded EXIF/XMP structure is malformed. + MalformedPsd, +} + +impl std::fmt::Display for ExtractError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::MalformedPsd => f.write_str("malformed PSD/PSB header, image-resource section, or embedded EXIF/XMP structure"), + } + } +} + +impl std::error::Error for ExtractError {} + /// A lens name from its focal and aperture range (Exif LensSpecification, or a Nikon maker note's Lens), written the /// way Lightroom shows a lens it has no name for: `50.0 mm f/1.8`, `18.0-135.0 mm f/3.5-5.6`. pub fn lens_spec_name(spec: [f64; 4]) -> Option<String> { @@ -351,6 +392,17 @@ mod tests { assert_eq!(m.exposure_display(), None); } + #[test] + fn try_extract_keeps_non_psd_exif_best_effort() { + let payload = b"Exif\0\0not a TIFF stream"; + let mut jpeg = vec![0xff, 0xd8, 0xff, 0xe1]; + jpeg.extend_from_slice(&u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + jpeg.extend_from_slice(payload); + jpeg.extend_from_slice(&[0xff, 0xd9]); + + assert!(matches!(try_extract(&jpeg), Ok(metadata) if metadata == Metadata::default())); + } + #[test] fn merge_rules() { let mut a = Metadata { make: Some("A".into()), rating: Some(1), ..Default::default() }; diff --git a/crates/meta/src/psd.rs b/crates/meta/src/psd.rs new file mode 100644 index 0000000000..bda16d9602 --- /dev/null +++ b/crates/meta/src/psd.rs @@ -0,0 +1,285 @@ +//! EXIF and XMP image resources in Photoshop PSD and PSB files. + +use crate::container::Embedded; + +struct Reader<'a> { + bytes: &'a [u8], + offset: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, length: usize) -> Option<&'a [u8]> { + let end = self.offset.checked_add(length)?; + let bytes = self.bytes.get(self.offset..end)?; + self.offset = end; + Some(bytes) + } + + fn u16(&mut self) -> Option<u16> { + let bytes = self.take(2)?; + Some(u16::from_be_bytes([*bytes.first()?, *bytes.get(1)?])) + } + + fn u32(&mut self) -> Option<u32> { + let bytes = self.take(4)?; + Some(u32::from_be_bytes([*bytes.first()?, *bytes.get(1)?, *bytes.get(2)?, *bytes.get(3)?])) + } +} + +pub(crate) fn embedded(bytes: &[u8]) -> Embedded { + parse(bytes).unwrap_or_default() +} + +pub(crate) fn parse(bytes: &[u8]) -> Option<Embedded> { + let mut reader = Reader { bytes, offset: 0 }; + if reader.take(4)? != b"8BPS" || !matches!(reader.u16()?, 1 | 2) { + return None; + } + // The fixed header after the version is reserved bytes, channels, dimensions, depth and colour mode. + reader.take(6 + 2 + 4 + 4 + 2 + 2)?; + let colour_mode_length = usize::try_from(reader.u32()?).ok()?; + reader.take(colour_mode_length)?; + let resource_length = usize::try_from(reader.u32()?).ok()?; + let resources = reader.take(resource_length)?; + parse_resources(resources) +} + +fn parse_resources(bytes: &[u8]) -> Option<Embedded> { + let mut reader = Reader { bytes, offset: 0 }; + let (mut exif, mut xmp) = (None, None); + while reader.offset < bytes.len() { + if reader.take(4)? != b"8BIM" { + return None; + } + let id = reader.u16()?; + let name_length = usize::from(*reader.take(1)?.first()?); + let pascal_length = 1usize.checked_add(name_length)?.checked_add(1)? & !1; + reader.take(pascal_length.checked_sub(1)?)?; + let data_length = usize::try_from(reader.u32()?).ok()?; + let data = reader.take(data_length)?; + if !data_length.is_multiple_of(2) { + reader.take(1)?; + } + match id { + 1058 if exif.is_some() => return None, + 1058 => exif = Some(data), + 1060 if xmp.is_some() => return None, + 1060 => xmp = Some(std::str::from_utf8(data).ok()?), + _ => {} + } + } + + Some(Embedded { + exif: exif.map(crate::strip_exif_header).map(<[u8]>::to_vec), + xmp: xmp.map(|text| text.trim_end_matches('\0').to_string()), + ..Default::default() + }) +} + +#[cfg(test)] +mod tests { + use super::embedded; + use crate::container::Embedded; + use crate::{DateTime, Gps, Metadata}; + + fn resource(id: u16, name: &[u8], data: &[u8]) -> Vec<u8> { + let mut out = b"8BIM".to_vec(); + out.extend_from_slice(&id.to_be_bytes()); + out.push(u8::try_from(name.len()).unwrap()); + out.extend_from_slice(name); + if !(name.len() + 1).is_multiple_of(2) { + out.push(0); + } + out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes()); + out.extend_from_slice(data); + if !data.len().is_multiple_of(2) { + out.push(0); + } + out + } + + fn image(version: u16, colour_data: &[u8], resources: &[u8]) -> Vec<u8> { + let mut out = b"8BPS".to_vec(); + out.extend_from_slice(&version.to_be_bytes()); + out.extend_from_slice(&[0; 6]); + out.extend_from_slice(&3u16.to_be_bytes()); // channels + out.extend_from_slice(&1u32.to_be_bytes()); // height + out.extend_from_slice(&1u32.to_be_bytes()); // width + out.extend_from_slice(&8u16.to_be_bytes()); // depth + out.extend_from_slice(&3u16.to_be_bytes()); // RGB + out.extend_from_slice(&u32::try_from(colour_data.len()).unwrap().to_be_bytes()); + out.extend_from_slice(colour_data); + out.extend_from_slice(&u32::try_from(resources.len()).unwrap().to_be_bytes()); + out.extend_from_slice(resources); + out + } + + fn dated_metadata() -> Metadata { + Metadata { + capture_time: DateTime::parse_exif("2023:05:14 14:40:39"), + gps: Some(Gps { latitude: 45.0, longitude: 7.0, altitude: None }), + ..Default::default() + } + } + + fn dated_image(version: u16) -> Vec<u8> { + let exif = crate::write_exif(&dated_metadata()); + image(version, &[], &resource(1058, b"", &exif)) + } + + #[test] + fn psd_capture_time_is_extracted() { + let expected = dated_metadata().capture_time; + let actual = crate::extract(&dated_image(1)); + assert_eq!(actual.capture_time, expected); + assert_eq!(actual.gps, dated_metadata().gps); + } + + #[test] + fn psb_capture_time_is_extracted() { + let expected = dated_metadata().capture_time; + let actual = crate::extract(&dated_image(2)); + assert_eq!(actual.capture_time, expected); + assert_eq!(actual.gps, dated_metadata().gps); + } + + #[test] + fn psd_extracts_xmp_without_exif() { + let metadata = Metadata { + capture_time: DateTime::parse_iso("2024-02-03T04:05:06Z"), + gps: Some(Gps { latitude: -33.9, longitude: 151.2, altitude: Some(25.0) }), + title: Some("Embedded XMP".into()), + ..Default::default() + }; + let xmp = crate::write_xmp(&metadata, None); + let file = image(1, &[], &resource(1060, b"", xmp.as_bytes())); + let actual = crate::extract(&file); + assert_eq!(actual.capture_time, metadata.capture_time); + assert_eq!(actual.gps, metadata.gps); + assert_eq!(actual.title, metadata.title); + } + + #[test] + fn psd_normalizes_the_optional_exif_resource_prefix() { + let mut exif = b"Exif\0\0".to_vec(); + exif.extend(crate::write_exif(&dated_metadata())); + let file = image(1, &[], &resource(1058, b"", &exif)); + assert_eq!(crate::extract(&file).capture_time, dated_metadata().capture_time); + } + + #[test] + fn try_extract_rejects_structurally_malformed_psd_exif() { + for version in [1, 2] { + let file = image(version, &[], &resource(1058, b"", b"not a TIFF stream")); + assert!(matches!(crate::try_extract(&file), Err(crate::ExtractError::MalformedPsd))); + } + } + + #[test] + fn try_extract_accepts_unknown_exif_tags_in_psd() { + let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); + ifd0.set(0xc001, lightcraft_tiff::Value::Ascii("vendor metadata".into())); + let exif = lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap(); + let file = image(1, &[], &resource(1058, b"", &exif)); + assert!(crate::try_extract(&file).is_ok()); + } + + #[test] + fn try_extract_rejects_malformed_psd_xmp_but_extract_remains_best_effort() { + let file = image(1, &[], &resource(1060, b"", b"<x:xmpmeta><broken")); + + assert_eq!(crate::extract(&file), Metadata::default()); + assert!(matches!(crate::try_extract(&file), Err(crate::ExtractError::MalformedPsd))); + } + + #[test] + fn try_extract_rejects_invalid_utf8_psd_xmp() { + let mut xmp = crate::write_xmp(&dated_metadata(), None).into_bytes(); + let latitude = xmp.windows(2).position(|bytes| bytes == b"45").unwrap(); + xmp[latitude] = 0xff; + let lossy = crate::parse_xmp(&String::from_utf8_lossy(&xmp)).unwrap(); + assert!(lossy.metadata.gps.is_none(), "lossy decoding hides the corrupted GPS value without an XML error"); + + for version in [1, 2] { + let file = image(version, &[], &resource(1060, b"", &xmp)); + assert!(matches!(crate::try_extract(&file), Err(crate::ExtractError::MalformedPsd))); + assert_eq!(embedded(&file), Embedded::default()); + assert_eq!(crate::extract(&file), Metadata::default()); + } + } + + #[test] + fn psd_xmp_preserves_valid_utf8_and_trailing_nul_trimming() { + let metadata = Metadata { title: Some("Café 山".into()), ..dated_metadata() }; + let xmp = crate::write_xmp(&metadata, None); + let mut padded = xmp.as_bytes().to_vec(); + padded.extend_from_slice(b"\0\0"); + + for version in [1, 2] { + let file = image(version, &[], &resource(1060, b"", &padded)); + assert_eq!(embedded(&file).xmp.as_deref(), Some(xmp.as_str())); + let actual = crate::try_extract(&file).unwrap(); + assert_eq!(actual.gps, metadata.gps); + assert_eq!(actual.title, metadata.title); + } + } + + #[test] + fn try_extract_rejects_duplicate_psd_exif_and_xmp_resources() { + let gps = dated_metadata(); + let no_gps = Metadata::default(); + let gps_exif = crate::write_exif(&gps); + let no_gps_exif = crate::write_exif(&no_gps); + let gps_xmp = crate::write_xmp(&gps, None); + let no_gps_xmp = crate::write_xmp(&no_gps, None); + + let duplicate_exif = [resource(1058, b"", &gps_exif), resource(1058, b"", &no_gps_exif)].concat(); + let duplicate_xmp = [resource(1060, b"", gps_xmp.as_bytes()), resource(1060, b"", no_gps_xmp.as_bytes())].concat(); + + for (id, resources) in [(1058, duplicate_exif), (1060, duplicate_xmp)] { + let file = image(1, &[], &resources); + assert!(matches!(crate::try_extract(&file), Err(crate::ExtractError::MalformedPsd)), "duplicate resource {id} must be rejected"); + } + } + + #[test] + fn psd_skips_unknown_resources_with_pascal_name_and_payload_padding() { + let exif = crate::write_exif(&dated_metadata()); + let mut resources = resource(4000, b"xy", &[1, 2, 3]); + resources.extend(resource(1058, b"", &exif)); + let file = image(1, &[8, 7, 6], &resources); + assert_eq!(crate::extract(&file).capture_time, dated_metadata().capture_time); + } + + #[test] + fn psd_truncation_and_hostile_lengths_return_no_embedded_metadata() { + let file = dated_image(1); + for end in 0..file.len() { + assert_eq!(embedded(&file[..end]), Embedded::default(), "truncated at {end}"); + } + + let mut hostile_colour_length = file.clone(); + hostile_colour_length[26..30].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(embedded(&hostile_colour_length), Embedded::default()); + + let mut hostile_resource_length = file.clone(); + hostile_resource_length[30..34].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(embedded(&hostile_resource_length), Embedded::default()); + + let mut hostile_payload_length = file; + hostile_payload_length[42..46].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(embedded(&hostile_payload_length), Embedded::default()); + } + + #[test] + fn psd_rejects_unknown_versions_and_incomplete_resource_records() { + let file = dated_image(1); + let mut unknown_version = file.clone(); + unknown_version[4..6].copy_from_slice(&3u16.to_be_bytes()); + assert_eq!(embedded(&unknown_version), Embedded::default()); + + let mut truncated_record = file; + truncated_record.pop(); + assert_eq!(embedded(&truncated_record), Embedded::default()); + } +} diff --git a/crates/meta/src/tags.rs b/crates/meta/src/tags.rs index 526348b159..30069dea1a 100644 --- a/crates/meta/src/tags.rs +++ b/crates/meta/src/tags.rs @@ -351,7 +351,7 @@ pub fn tag_rows(tiff: &Tiff) -> Vec<TagRow> { } /// [`tag_rows`] of a file's bytes: a TIFF-based file directly, else its embedded EXIF block -/// (JPEG, PNG, WebP, HEIF…). Empty when there is none. +/// (JPEG, PNG, WebP, HEIF, PSD/PSB…). Empty when there is none. pub fn file_tag_rows(bytes: &[u8]) -> Vec<TagRow> { if Tiff::sniff(bytes).is_some() && let Ok(t) = Tiff::parse(bytes) diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 1fb7891640..ac0a8808a8 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -69,7 +69,8 @@ pub struct XmpData { /// The opaque `lc:settings` JSON string, if present. pub lc_settings: Option<String>, /// Every property found, keyed `prefix:name` (struct fields as `prefix:name/prefix:field`); arrays keep - /// item order, language alternatives put `x-default` first. + /// item order, language alternatives put `x-default` first. Foreign namespaces that reuse a recognized + /// prefix use `Q{hex-encoded namespace URI}local` instead, so they cannot impersonate known properties. pub properties: BTreeMap<String, Vec<String>>, /// Every top-level property with its full structure (arrays of structs such as local /// corrections, which [`XmpData::properties`] flattens). @@ -150,26 +151,51 @@ impl Node { const MAX_DEPTH: usize = 64; const MAX_NODES: usize = 200_000; +// Expanding a long namespace URI on many short names must not amplify a small packet without bound. +pub(crate) const MAX_OPAQUE_NAME_BYTES: usize = 8 * 1024 * 1024; -/// `prefix:local` with the prefix canonicalised by namespace URI (see [`NAMESPACES`]). -pub(crate) fn canonical_name(qname: &str, scopes: &[Vec<(String, String)>]) -> String { - canonical(qname, scopes) +/// Most text a converter's flattened property keys may add up to. Keys repeat their whole ancestor +/// path (`parent/field`), so a document with a long nested name and a wide child fan-out otherwise +/// retains its prefix once per property: node limits alone cannot bound that duplication. +const MAX_KEY_BYTES: usize = 1 << 20; + +/// Names canonicalised by namespace URI (see [`NAMESPACES`]); conflicting foreign prefixes are opaque. +pub(crate) fn canonical_name(qname: &str, scopes: &[Vec<(String, String)>], opaque_budget: &mut usize) -> Result<String, XmpError> { + canonical(qname, scopes, opaque_budget) } -fn canonical(qname: &str, scopes: &[Vec<(String, String)>]) -> String { +fn canonical(qname: &str, scopes: &[Vec<(String, String)>], opaque_budget: &mut usize) -> Result<String, XmpError> { let (prefix, local) = qname.split_once(':').unwrap_or(("", qname)); if prefix == "xml" || prefix == "xmlns" { - return qname.to_string(); + return Ok(qname.to_string()); } let uri = scopes.iter().rev().flat_map(|s| s.iter().rev()).find(|(p, _)| p == prefix).map(|(_, u)| u.as_str()); - match uri { + Ok(match uri { Some(u) => match NAMESPACES.iter().find(|(_, nu)| *nu == u) { Some((p, _)) => format!("{p}:{local}"), + None if NAMESPACES.iter().any(|(p, _)| *p == prefix) => { + // A foreign `lc:settings` must never match our `lc:*` ownership rule (nor may a + // foreign `xmp:Rating` become a rating). Braces cannot occur in an XML QName; + // hex keeps URI slashes out of the flattened property's `/` path separators. + let size = + u.len().checked_mul(2).and_then(|n| n.checked_add(3)).and_then(|n| n.checked_add(local.len())).ok_or(XmpError::TooComplex)?; + *opaque_budget = opaque_budget.checked_sub(size).ok_or(XmpError::TooComplex)?; + let mut key = String::with_capacity(size); + key.push_str("Q{"); + for byte in u.bytes() { + for nibble in [byte >> 4, byte & 15] { + key.push(char::from(if nibble < 10 { b'0' + nibble } else { b'a' + (nibble - 10) })); + } + } + key.push('}'); + key.push_str(local); + key + } None if prefix.is_empty() => local.to_string(), None => qname.to_string(), }, None => qname.to_string(), - } + }) } fn entity(name: &str) -> Option<char> { @@ -202,7 +228,7 @@ fn xml_safe(s: &str) -> String { } /// Unescape attribute values (predefined + numeric references; unknown references kept verbatim). -fn unescape_attr(s: &str) -> String { +pub(crate) fn unescape_attr(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut rest = s; while let Some(i) = rest.find('&') { @@ -229,6 +255,7 @@ fn parse_tree(s: &str) -> Result<Node, XmpError> { let mut stack: Vec<Node> = vec![Node { name: "#root".into(), ..Default::default() }]; let mut scopes: Vec<Vec<(String, String)>> = vec![vec![("xml".into(), "http://www.w3.org/XML/1998/namespace".into())]]; let mut count = 0usize; + let mut opaque_budget = MAX_OPAQUE_NAME_BYTES; loop { let ev = reader.read_event().map_err(|e| XmpError::Xml(e.to_string()))?; match ev { @@ -251,8 +278,9 @@ fn parse_tree(s: &str) -> Result<Node, XmpError> { } } scopes.push(scope); - let name = canonical(&String::from_utf8_lossy(e.name().as_ref()), &scopes); - let attrs = raw_attrs.into_iter().map(|(k, v)| (canonical(&k, &scopes), v)).collect(); + let name = canonical(&String::from_utf8_lossy(e.name().as_ref()), &scopes, &mut opaque_budget)?; + let attrs = + raw_attrs.into_iter().map(|(k, v)| Ok((canonical(&k, &scopes, &mut opaque_budget)?, v))).collect::<Result<_, XmpError>>()?; let node = Node { name, attrs, ..Default::default() }; if matches!(ev, Event::Empty(_)) { scopes.pop(); @@ -309,18 +337,29 @@ fn is_rdf_meta_attr(k: &str) -> bool { matches!(k, "rdf:about" | "rdf:ID" | "rdf:nodeID" | "xml:lang" | "rdf:parseType" | "rdf:resource" | "rdf:datatype") || k.starts_with("xmlns") } -fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>) { +fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>, budget: &mut usize) { for (k, v) in &d.attrs { - if !is_rdf_meta_attr(k) { + if !is_rdf_meta_attr(k) && take_key_bytes(&format!("{prefix}{k}"), budget) { props.entry(format!("{prefix}{k}")).or_default().push(v.clone()); } } for c in &d.children { - collect_property(c, prefix, props); + collect_property(c, prefix, props, budget); } } -fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>) { +/// Charge one flattened key's length to the key budget; `false` when the budget is spent (the +/// property is then left out, like other elements a limit has cut). +fn take_key_bytes(key: &str, budget: &mut usize) -> bool { + let n = key.len(); + if *budget < n { + return false; + } + *budget -= n; + true +} + +fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>, budget: &mut usize) { let key = format!("{prefix}{}", p.name); if let Some(arr) = p.children.iter().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")) { let mut items: Vec<(bool, String)> = arr @@ -334,29 +373,36 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<Str if arr.name == "rdf:Alt" { items.sort_by_key(|(default, _)| !*default); } - props.entry(key).or_default().extend(items.into_iter().map(|(_, v)| v)); + if take_key_bytes(&key, budget) { + props.entry(key).or_default().extend(items.into_iter().map(|(_, v)| v)); + } return; } let struct_prefix = format!("{key}/"); if p.attr("rdf:parseType") == Some("Resource") { for c in &p.children { - collect_property(c, &struct_prefix, props); + collect_property(c, &struct_prefix, props, budget); } return; } if let Some(d) = p.children.iter().find(|c| c.name == "rdf:Description") { - collect_description(d, &struct_prefix, props); + collect_description(d, &struct_prefix, props, budget); return; } let field_attrs: Vec<&(String, String)> = p.attrs.iter().filter(|(k, _)| !is_rdf_meta_attr(k)).collect(); if !field_attrs.is_empty() && p.children.is_empty() && p.text.trim().is_empty() { for (k, v) in field_attrs { - props.entry(format!("{struct_prefix}{k}")).or_default().push(v.clone()); + let full = format!("{struct_prefix}{k}"); + if take_key_bytes(&full, budget) { + props.entry(full).or_default().push(v.clone()); + } } return; } let v = p.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| p.text.trim().to_string()); - props.entry(key).or_default().push(v); + if take_key_bytes(&key, budget) { + props.entry(key).or_default().push(v); + } } fn find_descriptions<'a>(n: &'a Node, out: &mut Vec<&'a Node>) { @@ -474,8 +520,10 @@ pub fn parse_xmp(s: &str) -> Result<XmpData, XmpError> { find_descriptions(&tree, &mut descs); let mut props = BTreeMap::new(); let mut values = BTreeMap::new(); + // One budget for the whole document: several descriptions cannot each spend a fresh one. + let mut key_budget = MAX_KEY_BYTES; for d in descs { - collect_description(d, "", &mut props); + collect_description(d, "", &mut props, &mut key_budget); if let XmpValue::Struct(m) = node_struct(d) { values.extend(m); } @@ -767,6 +815,43 @@ mod tests { assert_eq!(d.lc_settings, None); } + #[test] + fn foreign_namespace_cannot_impersonate_known_metadata() { + for body in [ + r#"xmp:Rating="2" lc:settings="foreign settings"/>"#, + r#"><xmp:Rating>2</xmp:Rating><lc:settings>foreign settings</lc:settings></rdf:Description>"#, + ] { + let packet = format!( + r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description + xmlns:xmp="https://example.org/vendor/" xmlns:lc="https://example.org/vendor/" {body}</rdf:RDF>"# + ); + let d = parse_xmp(&packet).unwrap(); + assert_eq!(d.metadata.rating, None, "foreign rating: {packet}"); + assert_eq!(d.lc_settings, None, "foreign settings: {packet}"); + assert!(!d.properties.contains_key("xmp:Rating")); + assert!(!d.values.contains_key("lc:settings")); + assert!(d.properties.values().any(|v| v == &["foreign settings"])); + assert!(d.properties.keys().all(|key| !key.contains('/')), "opaque names must not create struct paths"); + } + } + + #[test] + fn foreign_namespace_names_are_distinct_and_scoped() { + let packet = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> + <rdf:Description xmlns:xmp="http://ns.adobe.com/xap/1.0/"> + <xmp:Rating xmlns:xmp="https://example.org/one/">1</xmp:Rating> + <xmp:Rating xmlns:xmp="https://example.org/two/">2</xmp:Rating> + <xmp:Rating>4</xmp:Rating> + </rdf:Description></rdf:RDF>"#; + let d = parse_xmp(packet).unwrap(); + assert_eq!(d.metadata.rating, Some(4), "a local rebinding must not escape its scope"); + assert_eq!(d.properties.len(), 3, "different foreign URIs must not collide"); + assert_eq!(d.values.len(), 3); + assert_eq!(d.properties["xmp:Rating"], vec!["4"]); + assert!(d.properties.values().any(|v| v == &["1"])); + assert!(d.properties.values().any(|v| v == &["2"])); + } + #[test] fn attribute_form_foreign_prefixes_and_structs() { let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> @@ -1111,4 +1196,32 @@ mod tests { assert_eq!(entity("#x41"), Some('A')); assert_eq!(entity("#9"), Some('\t')); } + + /// Flattened keys repeat their whole ancestor path, so a long nested name with a wide child + /// fan-out would otherwise retain its prefix once per leaf: the cumulative key budget stops it + /// (a 65 KB document with 3000 leaves must not retain ~2.4 MB of key text). + #[test] + fn flattened_keys_stay_within_the_cumulative_budget() { + let level = "n".repeat(200); + let mut doc = String::from( + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:lc=\"https://lightcraft.example/lc/\"><rdf:RDF><rdf:Description><lc:root rdf:parseType=\"Resource\">", + ); + for _ in 0..4 { + doc.push_str(&format!("<lc:{level} rdf:parseType=\"Resource\">")); + } + // each leaf has a name of its own, so each one adds a key + for i in 0..3000 { + doc.push_str(&format!("<lc:leaf{i} lc:att=\"v\"/>")); + } + doc.push_str("</lc:root>"); + for _ in 0..4 { + doc.push_str(&format!("</lc:{level}>")); + } + doc.push_str("</rdf:Description></rdf:RDF></x:xmpmeta>"); + let d = parse_xmp(&doc).unwrap(); + let total: usize = d.properties.keys().map(String::len).sum(); + assert!(total <= MAX_KEY_BYTES, "flattened-key text {total} is over the {MAX_KEY_BYTES} budget"); + assert!(d.properties.len() < 3000, "keys stop being added once the budget is spent"); + assert!(!d.properties.is_empty(), "properties parsed before the budget are kept"); + } } diff --git a/crates/meta/src/xmp_merge.rs b/crates/meta/src/xmp_merge.rs index 022f962ec8..e1e4bca5e5 100644 --- a/crates/meta/src/xmp_merge.rs +++ b/crates/meta/src/xmp_merge.rs @@ -23,7 +23,7 @@ use std::collections::{BTreeSet, HashSet}; use quick_xml::events::Event; -use crate::xmp::{XmpError, canonical_name, parse_xmp}; +use crate::xmp::{MAX_OPAQUE_NAME_BYTES, XmpError, canonical_name, parse_xmp, unescape_attr}; /// Which properties [`merge_xmp`] takes from the fresh packet. Names are canonical /// `prefix:name` (prefixes as [`crate::parse_xmp`] reports them); `prefix:*` is a whole namespace. @@ -101,6 +101,7 @@ fn scan(s: &str) -> Result<Scan, XmpError> { let mut stack: Vec<Kind> = Vec::new(); let mut scopes: Vec<Vec<(String, String)>> = vec![vec![("xml".into(), "http://www.w3.org/XML/1998/namespace".into())]]; let mut count = 0usize; + let mut opaque_budget = MAX_OPAQUE_NAME_BYTES; loop { let before = pos(&reader); let ev = reader.read_event().map_err(|e| XmpError::Xml(e.to_string()))?; @@ -124,18 +125,21 @@ fn scan(s: &str) -> Result<Scan, XmpError> { } let v = String::from_utf8_lossy(&a.value).into_owned(); if k == "xmlns" { - scope.push((String::new(), v.clone())); + scope.push((String::new(), unescape_attr(&v))); } else if let Some(p) = k.strip_prefix("xmlns:") { - scope.push((p.to_string(), v.clone())); + scope.push((p.to_string(), unescape_attr(&v))); } raw_attrs.push((k, v)); } scopes.push(scope); let raw_name = String::from_utf8_lossy(e.name().as_ref()).into_owned(); - let name = canonical_name(&raw_name, &scopes); + let name = canonical_name(&raw_name, &scopes, &mut opaque_budget)?; let kind = match stack.last() { Some(Kind::Rdf) if name == "rdf:Description" => { - let attrs = raw_attrs.into_iter().map(|(raw, value)| Attr { name: canonical_name(&raw, &scopes), raw, value }).collect(); + let attrs = raw_attrs + .into_iter() + .map(|(raw, value)| Ok(Attr { name: canonical_name(&raw, &scopes, &mut opaque_budget)?, raw, value })) + .collect::<Result<_, XmpError>>()?; out.descs.push(Desc { tag_start: before, tag_end: after, raw_name, empty, attrs, props: Vec::new(), end: after }); Kind::Desc(out.descs.len() - 1) } @@ -399,6 +403,47 @@ mod tests { assert_eq!(d.properties.get("exif:DateTimeOriginal"), Some(&vec!["2024-05-06T07:08:09".to_string()])); } + #[test] + fn preserves_foreign_properties_using_known_prefixes() { + for property in [r#"lc:Secret="keep-me"/>"#, r#"><lc:Secret>keep-me</lc:Secret></rdf:Description>"#] { + let desc = format!(r#"<rdf:Description rdf:about="" xmlns:lc="https://example.org/vendor/" {property}"#); + let old = format!(r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">{desc}</rdf:RDF>"#); + let out = merge_xmp(&old, &fresh(4, &[]), RULES).unwrap(); + assert!(out.contains(&desc), "lost foreign description: {out}"); + assert_eq!(parse_xmp(&out).unwrap().metadata.rating, Some(4)); + assert_eq!(merge_xmp(&out, &fresh(4, &[]), RULES).unwrap(), out); + } + } + + #[test] + fn namespace_aliases_remain_distinct_during_merge() { + // The alias URI includes a character reference: scanning and parsing must resolve it identically. + let foreign = r#"<rdf:Description xmlns:xmp="https://example.org/vendor/" xmp:Rating="2"/>"#; + let old = format!( + r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">{foreign} + <rdf:Description xmlns:a="http://ns.adobe.com/xap/1.0&#47;" a:Rating="3"/> + </rdf:RDF>"# + ); + let out = merge_xmp(&old, &fresh(5, &[]), RULES).unwrap(); + assert!(out.contains(foreign), "lost foreign rating: {out}"); + assert!(!out.contains("a:Rating="), "genuine alias must be replaced: {out}"); + assert_eq!(parse_xmp(&out).unwrap().metadata.rating, Some(5)); + assert_eq!(merge_xmp(&out, &fresh(5, &[]), RULES).unwrap(), out); + } + + #[test] + fn opaque_namespace_expansion_is_bounded() { + // A roughly 40 KiB packet must not expand the same long URI into every property name indefinitely. + let packet = format!( + r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description + xmlns:lc="https://example.org/{}">{}</rdf:Description></rdf:RDF>"#, + "a".repeat(1024), + "<lc:p/>".repeat(5000) + ); + assert_eq!(parse_xmp(&packet).unwrap_err(), XmpError::TooComplex); + assert!(matches!(scan(&packet), Err(XmpError::TooComplex))); + } + #[test] fn many_attributes_scan_in_linear_time() { // quick-xml's duplicate-name check compares each attribute with all earlier ones: 200 000 attributes on diff --git a/crates/meta/tests/it/main.rs b/crates/meta/tests/it/main.rs new file mode 100644 index 0000000000..f56fd47f0f --- /dev/null +++ b/crates/meta/tests/it/main.rs @@ -0,0 +1,3 @@ +//! The integration tests, one module per file, linked into one test binary. + +mod robust; diff --git a/crates/meta/tests/robust.rs b/crates/meta/tests/it/robust.rs similarity index 100% rename from crates/meta/tests/robust.rs rename to crates/meta/tests/it/robust.rs diff --git a/crates/pipeline/Cargo.toml b/crates/pipeline/Cargo.toml index 197020e458..b62588b6d8 100644 --- a/crates/pipeline/Cargo.toml +++ b/crates/pipeline/Cargo.toml @@ -19,6 +19,7 @@ rayon = { workspace = true } serde = { workspace = true } [dev-dependencies] +dhat = { workspace = true } lightcraft-scenes = { workspace = true } proptest = { workspace = true } image = { workspace = true } diff --git a/crates/pipeline/examples/guided_memory.rs b/crates/pipeline/examples/guided_memory.rs new file mode 100644 index 0000000000..9f6beaa2aa --- /dev/null +++ b/crates/pipeline/examples/guided_memory.rs @@ -0,0 +1,84 @@ +//! Isolated fast-guided-filter benchmark (procedural log luminance; no decoded RGB or tone median). +//! `RAYON_NUM_THREADS=1 cargo run --release -p lightcraft-pipeline --example guided_memory -- new` +//! Replace `new` with `old` for the materialized-coefficient reference. Optional positional arguments: +//! width height sigma iterations (defaults: 6000 4000 120 5). Append `--heap` for one dhat-counted run. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use lightcraft_pipeline::local::{BASE_EPS, guided, guided_fast, guided_fast_step}; +use lightcraft_raster::blur::gaussian; +use lightcraft_raster::resample::{Filter, resize}; +use lightcraft_raster::{Plane, par_join, par_rows}; +use std::hint::black_box; +use std::time::Instant; + +#[global_allocator] +static ALLOC: dhat::Alloc = dhat::Alloc; + +/// Previous algorithm; kept here only to make before/after measurements reproducible. +fn materialized(p: &Plane, sigma: f32) -> Plane { + let s = guided_fast_step(sigma); + if s <= 1 { + return guided(p, sigma, BASE_EPS); + } + let lo = resize(p, p.width.div_ceil(s).max(1), p.height.div_ceil(s).max(1), Filter::Box); + let (a, b) = coefficients(&lo, sigma / s as f32); + let (a, b) = (resize(&a, p.width, p.height, Filter::Bilinear), resize(&b, p.width, p.height, Filter::Bilinear)); + let mut q = Plane::new(p.width, p.height); + par_rows(&mut q.data, p.width, |y, row| { + for ((v, pv), (av, bv)) in row.iter_mut().zip(p.row(y)).zip(a.row(y).iter().zip(b.row(y))) { + *v = av * pv + bv; + } + }); + q +} + +fn coefficients(lo: &Plane, sg: f32) -> (Plane, Plane) { + let (mean, corr) = par_join(|| gaussian(lo, sg), || gaussian(&lo.map(|v| v * v), sg)); + let a = corr.zip_map(&mean, |c, m| { + let v = (c - m * m).max(0.0); + v / (v + BASE_EPS) + }); + let b = mean.zip_map(&a, |m, a| m - a * m); + par_join(|| gaussian(&a, sg), || gaussian(&b, sg)) +} + +fn main() -> Result<(), Box<dyn std::error::Error>> { + let args: Vec<_> = std::env::args().skip(1).collect(); + let mode = args.first().map(String::as_str).unwrap_or("new"); + if !matches!(mode, "old" | "new") { + return Err("mode must be old or new".into()); + } + let parse = |i: usize, default: usize| -> Result<usize, Box<dyn std::error::Error>> { + Ok(args.get(i).filter(|v| !v.starts_with("--")).map(|v| v.parse()).transpose()?.unwrap_or(default)) + }; + let (w, h, sigma, n) = (parse(1, 6000)?, parse(2, 4000)?, parse(3, 120)? as f32, parse(4, 5)?.max(1)); + if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|pixels| pixels > 100_000_000) { + return Err("dimensions must be positive and at most 100 MP".into()); + } + let heap = args.iter().any(|a| a == "--heap"); + let p = Plane::from_fn(w, h, |x, y| ((x * 7919 + y * 104729) % 97) as f32 / 97.0 - 4.0 + if x > w / 2 { 2.0 } else { 0.0 }); + let filter = || if mode == "old" { materialized(&p, sigma) } else { guided_fast(&p, sigma, BASE_EPS) }; + // Initialize Rayon and warm code paths before counting. The source is excluded from heap stats. + black_box(filter()); + let profiler = heap.then(|| dhat::Profiler::builder().testing().build()); + let mut best = f64::MAX; + for _ in 0..if heap { 1 } else { n } { + let t = Instant::now(); + let q = black_box(filter()); + best = best.min(t.elapsed().as_secs_f64() * 1000.0); + if heap { + let stats = dhat::HeapStats::get(); + println!( + "peak_bytes={} total_bytes={} total_blocks={} retained_output_bytes={}", + stats.max_bytes, + stats.total_bytes, + stats.total_blocks, + q.data.len() * size_of::<f32>() + ); + } + } + drop(profiler); + println!("{mode} {w}x{h} sigma={sigma} step={} heap={heap} min_wall_ms={best:.3}", guided_fast_step(sigma)); + Ok(()) +} diff --git a/crates/pipeline/src/curve.rs b/crates/pipeline/src/curve.rs new file mode 100644 index 0000000000..b2c2b0b141 --- /dev/null +++ b/crates/pipeline/src/curve.rs @@ -0,0 +1,238 @@ +//! The parametric tone curve model shared by the pipeline renderer and the UI curve editor. +//! +//! Lightroom-style tone curve parametric model: four regions (shadows, darks, lights, highlights) +//! separated by three split points. Each region contributes a cosine-windowed bump, summed and +//! forced monotone. + +use lightcraft_color::spline::Lut1; +use lightcraft_develop::ToneCurve; + +/// The four shape controls of the parametric curve, in graph order: region 0 is the darkest. +pub const PARAM_AMOUNTS: [&str; 4] = ["curve.shadows", "curve.darks", "curve.lights", "curve.highlights"]; + +/// Resolution the parametric curve is sampled at, matching the renderer's LUT. +pub const PARAM_LUT: usize = 1024; + +/// The parametric (region) curve of a [`ToneCurve`]: the four region amounts, each a cosine bump +/// over its window between two splits, summed and then forced monotone. +/// +/// This is the renderer's curve, not an approximation of it — both `curve_luts` in the pipeline +/// and the curve editor in the UI use this struct so they can never disagree. +#[derive(Clone, Debug)] +pub struct ParametricCurve { + /// The curve, sampled and already forced monotone. + lut: [f32; PARAM_LUT], + /// The three region boundaries as fractions of the graph (0..1). + pub splits: [f64; 3], + /// The four region amounts, in graph order (0 = shadows, 3 = highlights). + pub amounts: [f64; 4], +} + +impl ParametricCurve { + pub fn new(c: &ToneCurve) -> ParametricCurve { + let s0 = if c.split_shadows.is_nan() { 0.25 } else { (c.split_shadows / 100.0).clamp(0.0, 1.0) as f32 }; + let s1 = if c.split_mid.is_nan() { 0.50_f32.max(s0) } else { (c.split_mid / 100.0).clamp(s0 as f64, 1.0) as f32 }; + let s2 = if c.split_highlights.is_nan() { 0.75_f32.max(s1) } else { (c.split_highlights / 100.0).clamp(s1 as f64, 1.0) as f32 }; + let clean_amt = |a: f64| if a.is_nan() { 0.0 } else { a.clamp(-100.0, 100.0) }; + let (a0, a1, a2, a3) = (clean_amt(c.shadows), clean_amt(c.darks), clean_amt(c.lights), clean_amt(c.highlights)); + let splits = [s0 as f64, s1 as f64, s2 as f64]; + let amounts = [a0, a1, a2, a3]; + let regions = [(0.0, s0, a0), (s0, s1, a1), (s1, s2, a2), (s2, 1.0, a3)]; + let mut lut = [0.0_f32; PARAM_LUT]; + let mut prev = 0.0_f32; + for (i, entry) in lut.iter_mut().enumerate() { + let x = i as f32 / (PARAM_LUT - 1) as f32; + let mut d = 0.0_f32; + for (a, b, amt) in regions { + if amt == 0.0 { + continue; + } + let (ctr, half) = ((a + b) / 2.0, (b - a) * 0.75 + 0.05); + if half <= f32::EPSILON { + continue; + } + let t = ((x - ctr) / half).clamp(-1.0, 1.0); + d += (amt / 100.0) as f32 * 0.22 * (0.5 + 0.5 * (t * std::f32::consts::PI).cos()); + } + let y = (x + d * 4.0 * x * (1.0 - x)).clamp(0.0, 1.0); + prev = prev.max(y); + *entry = prev; + } + ParametricCurve { lut, splits, amounts } + } + + /// Convert the evaluated parametric curve into a 1024-entry [`Lut1`]. + pub fn to_lut(&self) -> Lut1 { + Lut1 { v: self.lut.to_vec() } + } + + /// The curve at `x` (0 = black, 1 = white), read off the table (so it never overshoots the ends). + pub fn at(&self, x: f64) -> f64 { + let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) as f32 }; + let at = x * (PARAM_LUT - 1) as f32; + let i = at.floor().clamp(0.0, (PARAM_LUT - 1) as f32) as usize; + let cur = self.lut.get(i).copied().unwrap_or(0.0); + let next = self.lut.get(i + 1).copied().unwrap_or(cur); + let f = at - i as f32; + (cur + (next - cur) * f) as f64 + } + + /// Where region `region`'s handle sits on the input axis: the middle of its own window, so a + /// handle never has to cross a split to be grabbed. + pub fn region_x(&self, region: usize) -> f64 { + let (a, b) = self.region_window(region); + (a + b) / 2.0 + } + + /// The window (two splits, as fractions of the graph) region `region` owns. + pub fn region_window(&self, region: usize) -> (f64, f64) { + let s0 = self.split_x(0); + let s1 = self.split_x(1); + let s2 = self.split_x(2); + match region { + 0 => (0.0, s0), + 1 => (s0, s1), + 2 => (s1, s2), + _ => (s2, 1.0), + } + } + + /// The half-width of region `region`'s own bump, as fraction of the graph. + pub fn region_half(&self, region: usize) -> f64 { + let (a, b) = self.region_window(region); + (b - a) * 0.75 + 0.05 + } + + /// The cosine window region `region` applies at `x` (1 at its centre, 0 at the window edges). + pub fn region_window_at(&self, region: usize, x: f64) -> f64 { + let ctr = self.region_x(region); + let half = self.region_half(region); + if half <= f64::EPSILON { + return 0.0; + } + let t = ((x - ctr) / half).clamp(-1.0, 1.0); + 0.5 + 0.5 * (t * std::f64::consts::PI).cos() + } + + /// The region that owns graph position `x`: the one whose own window contains it. The four + /// windows tile 0..1, so this is always defined and a drag anywhere on the curve moves exactly + /// one slider — the region under the pointer. + pub fn region_at(&self, x: f64) -> usize { + let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; + let s0 = self.split_x(0); + let s1 = self.split_x(1); + let s2 = self.split_x(2); + if x <= s0 { + 0 + } else if x <= s1 { + 1 + } else if x <= s2 { + 2 + } else { + 3 + } + } + + /// How much output level region `region`'s bump gains at `x` per unit of its slider: the bump is + /// linear in the amount, so this is a constant for a given `x`. A drag converts the pointer's + /// vertical motion into a slider change through it. + pub fn level_per_unit(&self, region: usize, x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + 0.22 / 100.0 * self.region_window_at(region, x) * 4.0 * x * (1.0 - x) + } + + /// The baseline level at `x` from the identity diagonal plus the contributions of all regions + /// *except* `region`. Used when inverting the model for `region` while holding the other three + /// regions fixed. + pub fn base_level_without(&self, region: usize, x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + let mut d = 0.0; + for i in 0..4 { + if i == region { + continue; + } + let amt = self.amounts.get(i).copied().unwrap_or(0.0); + if amt == 0.0 { + continue; + } + d += (amt / 100.0) * 0.22 * self.region_window_at(i, x); + } + x + d * 4.0 * x * (1.0 - x) + } + + /// The curve level region `region` sits at when its slider holds `amount`, at graph position `x`, + /// holding the other regions fixed at their current settings. + pub fn handle_level_at(&self, region: usize, amount: f64, x: f64) -> f64 { + (self.base_level_without(region, x) + amount * self.level_per_unit(region, x)).clamp(0.0, 1.0) + } + + /// The amount that puts region `region`'s curve at `level` at `x`, with the other three + /// regions held fixed — the inverse of [`Self::handle_level_at`]. A level the region cannot + /// reach saturates rather than jumping. + pub fn amount_at_level(&self, region: usize, level: f64, x: f64) -> f64 { + let per_unit = self.level_per_unit(region, x); + if per_unit.abs() <= f64::EPSILON { + return self.amounts.get(region).copied().unwrap_or(0.0); + } + let base = self.base_level_without(region, x); + ((level.clamp(0.0, 1.0) - base) / per_unit).clamp(-100.0, 100.0).round() + } + + /// The graph position split `split` (0..=2) sits at, 0..1. + pub fn split_x(&self, split: usize) -> f64 { + self.splits.get(split).copied().unwrap_or(0.5) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn non_finite_or_inverted_splits_do_not_panic_or_poison_curve() { + let c = ToneCurve { + split_shadows: 80.0, + split_mid: 20.0, + split_highlights: f64::NAN, + shadows: f64::NAN, + lights: f64::INFINITY, + ..Default::default() + }; + let model = ParametricCurve::new(&c); + assert!(model.at(0.5).is_finite()); + assert!(model.at(f64::NAN).is_finite()); + assert!(model.region_at(f64::NAN) < 4); + assert!((model.splits[0] - 0.8).abs() < 1e-6); + assert!((model.splits[1] - 0.8).abs() < 1e-6); + assert!((model.splits[2] - 0.8).abs() < 1e-6); + } + + #[test] + fn horizontal_inversion_at_x_0_51_with_darks_60_preserves_zero_lights() { + let c = ToneCurve { darks: 60.0, lights: 0.0, ..Default::default() }; + let model = ParametricCurve::new(&c); + assert_eq!(model.region_at(0.51), 2, "x=0.51 is inside the Lights region"); + let level = model.at(0.51); + assert!((level - 0.5619).abs() < 0.001, "extracted model at 0.51 is ~0.5619: {level}"); + // With other regions held fixed, inverting at level ~0.5619 must return Lights = 0, NOT 45! + let lights = model.amount_at_level(2, level, 0.51); + assert_eq!(lights, 0.0, "zero vertical delta preserves Lights=0: {lights}"); + } + + #[test] + fn a_curve_level_and_its_amount_are_inverses_with_other_regions_present() { + let c = ToneCurve { shadows: 20.0, darks: -30.0, lights: 40.0, highlights: -10.0, ..Default::default() }; + let model = ParametricCurve::new(&c); + for region in 0..4 { + let centre = model.region_x(region); + let (_, upper) = model.region_window(region); + for x in [centre, centre + (upper - centre) * 0.5] { + for amount in [-100.0, -40.0, 0.0, 30.0, 100.0] { + let level = model.handle_level_at(region, amount, x); + let back = model.amount_at_level(region, level, x); + assert!((back - amount).abs() <= 1.0, "region {region} at {x}: {amount} -> {level} -> {back}"); + } + } + } + } +} diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index eb65d51a2b..c1e6a9bc20 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -29,31 +29,20 @@ fn curve_luts(c: &ToneCurve) -> Option<[Lut1; 3]> { return None; } const N: usize = 1024; - let (s1, s2, s3) = ((c.split_shadows / 100.0) as f32, (c.split_mid / 100.0) as f32, (c.split_highlights / 100.0) as f32); - let regions = [(0.0, s1, c.shadows), (s1, s2, c.darks), (s2, s3, c.lights), (s3, 1.0, c.highlights)]; - let mut base = Lut1::from_fn(N, |x| { - let mut d = 0.0; - for (a, b, amt) in regions { - if amt == 0.0 { - continue; - } - let (ctr, half) = ((a + b) / 2.0, (b - a) * 0.75 + 0.05); - let t = ((x - ctr) / half).clamp(-1.0, 1.0); - let win = 0.5 + 0.5 * (t * std::f32::consts::PI).cos(); - d += (amt / 100.0) as f32 * 0.22 * win; - } - (x + d * 4.0 * x * (1.0 - x)).clamp(0.0, 1.0) - }); - // keep monotone - for i in 1..N { - base.v[i] = base.v[i].max(base.v[i - 1]); - } + let mut base = crate::curve::ParametricCurve::new(c).to_lut(); let to_pts = |p: &[Point]| p.iter().map(|q| (q.x, q.y)).collect::<Vec<_>>(); if master { base = MonotoneCurve::new(&to_pts(&c.master)).to_lut(N).compose(&base); } let per = [&c.red, &c.green, &c.blue]; - Some(std::array::from_fn(|i| if chans[i] { MonotoneCurve::new(&to_pts(per[i])).to_lut(N).compose(&base) } else { base.clone() })) + Some(std::array::from_fn(|i| { + if chans.get(i).copied().unwrap_or(false) { + let pts = per.get(i).map(|&p| to_pts(p)).unwrap_or_default(); + MonotoneCurve::new(&pts).to_lut(N).compose(&base) + } else { + base.clone() + } + })) } /// Vignette (post-crop) parameters. @@ -450,7 +439,12 @@ pub(crate) fn finish_with<T: Copy + Default + Send>( if dz != 0.0 && let Some(dark) = &p.dark { - let d = (dark.data[i] / air_pre).clamp(0.0, 1.0); + // The dark channel is a blur, not a patch minimum: near bright neighbours it credits + // dark pixels with veil they don't hold (and a windowed render borrows the whole + // frame's airlight), so the subtraction went past zero and crushed them to black + // (#2504). Never attribute more veil than the pixel's own minimum channel. + let c_min = c[0].min(c[1]).min(c[2]); + let d = (if air_pre > 0.0 { dark.data[i] / air_pre } else { 0.0 }).min(if air > 0.0 { c_min / air } else { 0.0 }).clamp(0.0, 1.0); if dz > 0.0 { let t = (1.0 - 0.95 * dz.min(1.0) * d).max(0.12); c = c.map(|v| ((v - air * (1.0 - t)) / t).max(0.0)); diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 34df1f8a91..8f2702760d 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -27,6 +27,7 @@ pub mod auto; pub mod blemish; pub mod colorops; pub mod cull; +pub mod curve; pub mod dust; pub mod finish; pub mod geometry; @@ -44,6 +45,7 @@ pub mod transform; pub mod upright; pub mod visualize; +pub use curve::{PARAM_AMOUNTS, PARAM_LUT, ParametricCurve}; pub use output::{DeepImage, DeepSamples, DisplaySpace, OutputDepth, OutputSpace, OutputTrc, Proof, ProofLut, proof_profile, register_proof_profile}; pub use visualize::{MaskView, Overlay}; @@ -139,7 +141,7 @@ pub struct RenderRequest { pub space: OutputSpace, /// Sample format: 8-bit only, or also a 16-bit / linear float [`Rendered::deep`] (exports). pub depth: OutputDepth, - /// Soft proofing (CPU only; see [`Proof`]). + /// Soft proofing (a proof against an output-device profile renders on the CPU; see [`Proof`]). pub proof: Option<Proof>, /// Render only this window of the output that `max_w × max_h` describes (a zoomed view): /// the result is that window's pixels, as in the whole render. See [`PixelWindow`]. diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index ba02982260..c91872d388 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -178,10 +178,55 @@ fn guided_coeffs(p: &Plane, sigma: f32, eps: f32) -> (Plane, Plane) { par_join(|| gaussian(&a, sigma), || gaussian(&b, sigma)) } -/// `q = a·p + b` per pixel. +/// `q = a·p + b` per pixel. Reduced coefficients are sampled with the same separable +/// weights and accumulation order as a bilinear resize, without full-size coefficient planes. fn guided_apply(p: &Plane, a: &Plane, b: &Plane) -> Plane { let mut q = Plane::new(p.width, p.height); let w = p.width; + if (a.width, a.height) != (p.width, p.height) { + use lightcraft_raster::resample::{Filter, weights}; + let wx = weights(a.width, w, Filter::Bilinear); + let wy = weights(a.height, p.height, Filter::Bilinear); + // Bilinear upsampling has at most four taps (including zero-weight boundary taps). + // Keep only those horizontally sampled rows per band, reusing them for neighbouring + // output rows. Scratch scales with width and active bands, not image area. + const BAND: usize = 32; + for_rows(&mut q.data, w.saturating_mul(BAND), |band, rows| { + let mut cache: [(usize, Vec<f32>, Vec<f32>); 4] = std::array::from_fn(|_| (usize::MAX, vec![0.0; w], vec![0.0; w])); + let mut bias = vec![0.0; w]; + for (dy, row) in rows.chunks_mut(w).enumerate() { + let y = band * BAND + dy; + let (top, ys) = &wy[y]; + bias.fill(0.0); + for (dy, yw) in ys.iter().enumerate() { + let cy = top + dy; + let (cached_y, aa, bb) = &mut cache[cy % 4]; + if *cached_y != cy { + let (ar, br) = (a.row(cy), b.row(cy)); + for ((av, bv), (left, xs)) in aa.iter_mut().zip(bb.iter_mut()).zip(&wx) { + *av = 0.0; + *bv = 0.0; + for (dx, xw) in xs.iter().enumerate() { + *av += ar[left + dx] * xw; + *bv += br[left + dx] * xw; + } + } + *cached_y = cy; + } + for (av, ax) in row.iter_mut().zip(aa) { + *av += *ax * yw; + } + for (bv, bx) in bias.iter_mut().zip(bb) { + *bv += *bx * yw; + } + } + for ((v, pv), bv) in row.iter_mut().zip(p.row(y)).zip(&bias) { + *v = *v * pv + bv; + } + } + }); + return q; + } for_rows(&mut q.data, w, |y, row| { for ((v, pv), (av, bv)) in row.iter_mut().zip(p.row(y)).zip(a.row(y).iter().zip(b.row(y))) { *v = av * pv + bv; @@ -191,7 +236,7 @@ fn guided_apply(p: &Plane, a: &Plane, b: &Plane) -> Plane { } /// Fast guided filter (He & Sun 2015): coefficients computed on a `s×` subsampled plane and -/// bilinearly upsampled; the output keeps full-resolution edges. Equivalent to [`guided`] for +/// sampled bilinearly at full resolution; the output keeps full-resolution edges. Equivalent to [`guided`] for /// large windows at a fraction of the cost. pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane { use lightcraft_raster::resample::{Filter, resize}; @@ -202,8 +247,7 @@ pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane { let (lw, lh) = (p.width.div_ceil(s).max(1), p.height.div_ceil(s).max(1)); let lo = resize(p, lw, lh, Filter::Box); let (ma, mb) = guided_coeffs(&lo, sigma / s as f32, eps); - let up = |c: &Plane| resize(c, p.width, p.height, Filter::Bilinear); - guided_apply(p, &up(&ma), &up(&mb)) + guided_apply(p, &ma, &mb) } /// Separable median (`2r+1` px along each row, then each column; clamped edges). It keeps the @@ -227,22 +271,47 @@ fn median_row(src: &[f32], out: &mut [f32], r: usize) { if n == 0 { return; } - let at = |i: isize| src[i.clamp(0, n as isize - 1) as usize]; + let at = |i: isize| total_key(src[i.clamp(0, n as isize - 1) as usize]); let r_ = r as isize; - let mut win: Vec<f32> = (-r_..=r_).map(at).collect(); - win.sort_unstable_by(f32::total_cmp); + let mut win: Vec<i32> = (-r_..=r_).map(at).collect(); + win.sort_unstable(); for (x, o) in out.iter_mut().enumerate() { - *o = win[r]; + *o = f32::from_bits(total_key_inv(win[r])); let (old, new) = (at(x as isize - r_), at(x as isize + r_ + 1)); - if old.to_bits() != new.to_bits() { - let i = win.binary_search_by(|v| v.total_cmp(&old)).unwrap_or_else(|i| i.min(win.len() - 1)); - win.remove(i); - let j = win.binary_search_by(|v| v.total_cmp(&new)).unwrap_or_else(|j| j); - win.insert(j, new); + if old != new { + // Ranks by counting the smaller keys in one branch-free pass the compiler vectorizes. + // Binary searches here mispredicted on most steps and, with `remove` + `insert`, cost + // 2.4 s per 24 MP at r = 9 on one core. + let (mut i, mut j) = (0u32, 0u32); + for &v in &win { + i += u32::from(v < old); + j += u32::from(v < new); + } + let (i, j) = (i as usize, j as usize); + // `old` sits at `i`; shift the keys between the two ranks by one over it + if j > i { + win.copy_within(i + 1..j, i); + win[j - 1] = new; + } else { + win.copy_within(j..i, j + 1); + win[j] = new; + } } } } +/// `v`'s bits as an `i32` that orders like [`f32::total_cmp`] (the same transform it applies), so +/// equal keys are equal bits. +fn total_key(v: f32) -> i32 { + let b = v.to_bits() as i32; + b ^ (((b >> 31) as u32) >> 1) as i32 +} + +/// The bits [`total_key`] came from (the transform is its own inverse: it keeps the sign bit). +fn total_key_inv(k: i32) -> u32 { + (k ^ (((k >> 31) as u32) >> 1) as i32) as u32 +} + fn transpose(p: &Plane) -> Plane { let (w, h) = (p.width, p.height); let mut t = Plane::new(h, w); @@ -733,6 +802,60 @@ mod tests { mod fast_tests { use super::*; + /// The previous fast path, including its two materialized coefficient resizes. + fn resized_reference(p: &Plane, sigma: f32, eps: f32) -> Plane { + use lightcraft_raster::resample::{Filter, resize}; + let s = guided_fast_step(sigma); + if s <= 1 { + return guided(p, sigma, eps); + } + let lo = resize(p, p.width.div_ceil(s).max(1), p.height.div_ceil(s).max(1), Filter::Box); + let (a, b) = guided_coeffs(&lo, sigma / s as f32, eps); + let (a, b) = (resize(&a, p.width, p.height, Filter::Bilinear), resize(&b, p.width, p.height, Filter::Bilinear)); + Plane::from_fn(p.width, p.height, |x, y| a.get(x, y) * p.get(x, y) + b.get(x, y)) + } + + #[test] + fn sampled_coefficients_match_materialized_resizes() { + for (w, h) in [(0, 0), (1, 1), (1, 19), (23, 1), (2, 3), (17, 13), (64, 48), (161, 119)] { + let planes = [ + Plane::filled(w, h, -3.25), + Plane::from_fn(w, h, |x, y| ((x * 7919 + y * 104729) % 97) as f32 / 7.0 - 8.0), + Plane::from_fn(w, h, |x, y| { + if x == w / 2 && y == h / 2 { + 9.0 + } else if x < w / 2 { + -5.0 + } else { + 2.0 + } + }), + ]; + // Step 1 fallback, every small step, Draft's cap, and the maximum step (16). + for sigma in [0.0, 2.99, 5.99, 6.0, 9.0, 12.0, 24.0, 48.0, 200.0] { + for eps in [BASE_EPS, CLARITY_EPS, 0.0001] { + for p in &planes { + let expected = resized_reference(p, sigma, eps); + let actual = guided_fast(p, sigma, eps); + assert_eq!((actual.width, actual.height), (w, h)); + assert_eq!(actual.data, expected.data, "{w}x{h}, sigma {sigma}, eps {eps}"); + } + } + } + } + } + + #[test] + fn sampled_tone_base_keeps_the_median_before_the_guided_filter() { + let p = Plane::from_fn(73, 51, |x, y| if x % 9 == 0 { 3.0 } else { -4.0 + ((x + y) % 7) as f32 * 0.03 }); + for sigma in [6.0, 24.0, 120.0] { + for detail in [0, 1, 3, BASE_DETAIL_MAX] { + let median = median_hv(&p, detail); + assert_eq!(tone_base(&p, sigma, detail).data, resized_reference(&median, sigma, BASE_EPS).data, "{sigma}, {detail}"); + } + } + } + #[test] fn fast_guided_close_to_reference() { let p = Plane::from_fn(160, 120, |x, y| ((x as f32 * 0.13).sin() + (y as f32 * 0.07).cos()) * 2.0 + if x > 80 { 1.5 } else { 0.0 }); diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index d7949315e0..23eca0ba74 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -75,6 +75,38 @@ fn directional_sliders() { assert!(at("effects.dehaze", -100.0) != base); } +/// Dehaze crushed dark regions next to bright ones to black: the dark channel is a blur, not a +/// patch minimum, so near the boundary it credited the dark pixels with the bright side's veil and +/// the subtraction went past zero (#2504). The veil credited to a pixel is now bounded by its own +/// minimum channel, so a uniform dark region renders uniformly under dehaze. +#[test] +fn dehaze_does_not_crush_dark_regions_next_to_bright_ones() { + // a dark field against a bright hazy sky; the blur bleeds the sky's dark channel ~10 px into + // the field, which is where the blotches formed + let src = Rgb32f::from_fn(240, 160, |x, _| if x < 120 { [0.02, 0.03, 0.012] } else { [0.45, 0.5, 0.55] }); + let mut s = DevelopSettings::default(); + s.effects.dehaze = 80.0; + let r = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(240, 160)).image; + for ch in 0..3 { + let mut v: Vec<u8> = Vec::with_capacity(160 * 100); + for y in 0..160 { + for x in 0..100 { + v.push(r.get(x, y)[ch]); + } + } + v.sort_unstable(); + let mid = v[v.len() / 2] as i32; + // a field rendered all black would pass the comparison below vacuously + assert!(mid > 2, "the dark field itself is crushed in ch {ch}: level {mid}"); + for y in 0..160 { + for x in 0..120 { + let p = r.get(x, y)[ch] as i32; + assert!(p >= mid - 2, "crushed at {x},{y} ch {ch}: {p} vs field level {mid}"); + } + } + } +} + #[test] fn resolution_independence_of_local_contrast() { // Clarity at two preview sizes should give similar results after downscaling. diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index d7105acfce..ac244cb0dc 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -488,3 +488,39 @@ fn level_degrees_sign_matches_crop_angle() { let deg = crate::upright::level_degrees(&src, &SourceInfo::default(), &DevelopSettings::default()).expect("lines found"); assert!((deg + 6.0).abs() < 0.5, "{deg}"); } + +/// A "horizon" of `deg` degrees: sky above, below it bands of `band` px (0: one edge only). +fn tilted_scene(deg: f32, band: f32) -> Rgb32f { + let (w, h) = (900usize, 600usize); + let t = deg.to_radians().tan(); + Rgb32f::from_fn(w, h, |x, y| { + let yh = h as f32 / 2.0 + (x as f32 - w as f32 / 2.0) * t; + if (y as f32) < yh { + [0.6, 0.7, 0.9] + } else if band > 0.0 && (((y as f32 - yh) / band) as i32) % 2 == 1 { + [0.1, 0.2, 0.3] + } else { + [0.05, 0.1, 0.2] + } + }) +} + +/// Auto straighten acts on several agreeing lines only: one edge (the frame of a window, a branch) +/// turned straight photos in a measurement on real ones, so it is left alone. +#[test] +fn auto_straighten_needs_more_than_one_line() { + let level = |src: &Rgb32f| crate::upright::level_degrees(src, &SourceInfo::default(), &DevelopSettings::default()); + assert_eq!(level(&tilted_scene(4.0, 0.0)), None, "one edge"); + let deg = level(&tilted_scene(4.0, 30.0)).expect("a horizon and the bands below it"); + assert!((deg + 4.0).abs() < 0.5, "{deg}"); +} + +/// Auto straighten turns by at most `STRAIGHTEN_MAX_DEGREES`: larger "levels" came from texture +/// (planks, a bird's wing) on photos that were straight. +#[test] +fn auto_straighten_leaves_steep_lines_alone() { + let level = |src: &Rgb32f| crate::upright::level_degrees(src, &SourceInfo::default(), &DevelopSettings::default()); + assert_eq!(level(&tilted_scene(20.0, 30.0)), None, "20° is not a horizon to level"); + let deg = level(&tilted_scene(8.0, 30.0)).expect("8° is"); + assert!((deg + 8.0).abs() < 0.5, "{deg}"); +} diff --git a/crates/pipeline/src/tests_tone.rs b/crates/pipeline/src/tests_tone.rs index a6ec70eb58..87e1b659ac 100644 --- a/crates/pipeline/src/tests_tone.rs +++ b/crates/pipeline/src/tests_tone.rs @@ -187,6 +187,27 @@ fn median_matches_a_plain_per_pixel_median() { } } +#[test] +fn median_orders_special_values_and_ties_like_total_cmp() { + // the running window keeps keys in `f32::total_cmp` order: NaNs of either sign, signed zeros, + // infinities and long runs of equal values come out bit for bit as a sorted per-pixel window + // does, also on planes narrower or shorter than the window + let special = [f32::NAN, -f32::NAN, 0.0, -0.0, f32::INFINITY, f32::NEG_INFINITY, f32::MIN_POSITIVE, -1.0, 1.0, 1.0, 1.0]; + let bits = |p: &Plane| p.data.iter().map(|v| v.to_bits()).collect::<Vec<_>>(); + for (w, h) in [(1, 1), (2, 3), (5, 1), (19, 7), (61, 9)] { + let p = Plane::from_fn(w, h, |x, y| special[(x * 7 + y * 3 + (x * y) % 5) % special.len()]); + for r in [1, 2, 9, 24] { + let med = |v: &mut Vec<f32>| { + v.sort_by(f32::total_cmp); + v[r] + }; + let rows = Plane::from_fn(w, h, |x, y| med(&mut (0..=2 * r).map(|k| p.get((x + k).saturating_sub(r).min(w - 1), y)).collect())); + let want = Plane::from_fn(w, h, |x, y| med(&mut (0..=2 * r).map(|k| rows.get(x, (y + k).saturating_sub(r).min(h - 1))).collect())); + assert_eq!(bits(&local::median_hv(&p, r)), bits(&want), "{w}x{h} r {r}"); + } + } +} + #[test] fn v1_keeps_the_base_it_always_had() { // V1's base is the edge-aware filter of log luminance itself, as before process V2: no median diff --git a/crates/pipeline/src/tests_window.rs b/crates/pipeline/src/tests_window.rs index b0fc3de8f3..b82a19f459 100644 --- a/crates/pipeline/src/tests_window.rs +++ b/crates/pipeline/src/tests_window.rs @@ -407,3 +407,42 @@ fn auto_mask_strokes_match_the_whole_render() { }; check_noisy("auto mask", &s, PixelWindow { x: 400, y: 300, w: 300, h: 250 }, 2, 0.1); } + +/// The margin the loupe's windows carry around what they show at this size (`region::margin_for`: +/// 4.5 % of the long edge). +const OVERLAY_INSET: usize = W * 45 / 1000; + +/// [`check`] for a diagnostic overlay, with the photo as a raw (Visualize HDR needs one), keeping the +/// loupe's margin in from the window's edges. +fn check_overlay(name: &str, s: &DevelopSettings, overlay: crate::Overlay, win: PixelWindow, max_ok: u8, mean_ok: f64) { + let info = SourceInfo { raw: true, ..Default::default() }; + let full_req = RenderRequest { overlay, ..RenderRequest::fit(W, H) }; + let f = render(&scene(), &info, s, &full_req).image; + let w = render(&scene(), &info, s, &RenderRequest { window: Some(win), ..full_req }).image; + assert_eq!((w.width, w.height), (win.w, win.h), "{name}: the window's own size"); + assert_ne!(f.data, render(&scene(), &info, s, &RenderRequest::fit(W, H)).image.data, "{name}: the overlay draws something"); + let (max, mean) = compare_inset(&f, &w, win, OVERLAY_INSET); + assert!(max <= max_ok && mean <= mean_ok, "{name}: max {max} (≤ {max_ok}), mean {mean:.3} (≤ {mean_ok})"); +} + +// Given a diagnostic overlay (Visualize Spots, a Point Color range, Visualize HDR), a window shows +// the same pixels as the whole-frame render, so the loupe can draw them as a zoom window +#[test] +fn diagnostic_overlays_in_a_window_match_the_full_render() { + use crate::Overlay; + let mut spots = DevelopSettings::default(); + spots.detail.sharpen_amount = 60.0; + // a binary threshold: a pixel at the threshold may flip on a one-level difference underneath + check_overlay("spots", &spots, Overlay::Spots(70), MID, 255, 0.05); + for (x, y) in [(0, 0), (W - 400, H - 300)] { + check_overlay("spots at a corner", &spots, Overlay::Spots(70), PixelWindow { x, y, w: 400, h: 300 }, 255, 0.05); + } + let mut pc = DevelopSettings::default(); + pc.point_colors.push(lightcraft_develop::PointColor { lum: 0.6, chroma: 0.08, hue: 60.0, hue_shift: 40.0, ..Default::default() }); + check_overlay("point colour range", &pc, Overlay::PointColorRange(0), MID, 1, 0.1); + let mut hdr = DevelopSettings::default(); + hdr.hdr.enabled = true; + hdr.hdr.max_ev = 3.0; + hdr.light.exposure = 1.5; + check_overlay("hdr range", &hdr, Overlay::HdrRange, MID, 1, 0.1); +} diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 93dffad0c9..58a61adbe2 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -375,6 +375,12 @@ fn focal_from_vps(v: [f64; 3], h: [f64; 3]) -> Option<f64> { /// Pure rotation (degrees, clockwise +) that levels the dominant lines. fn level_angle(vert: &[Segment], horiz: &[Segment]) -> Option<f64> { + level_angle_within(vert, horiz, 90.0, 1) +} + +/// [`level_angle`] that only answers for at most `max` degrees, backed by at least `min_lines` +/// agreeing segments. +fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, min_lines: usize) -> Option<f64> { let dev = |s: &Segment, vertical: bool| { let (dx, dy) = (s.b.x - s.a.x, s.b.y - s.a.y); // signed deviation in degrees of the segment from the axis @@ -406,8 +412,9 @@ fn level_angle(vert: &[Segment], horiz: &[Segment]) -> Option<f64> { })?; // consensus: most of the line length must agree with the median within 2°, otherwise the "lines" are scene // texture (tree flanks, ridges) rather than a horizon or plumb lines - let agree: f64 = v.iter().filter(|(d, _)| (d - median.0).abs() <= 2.0).map(|x| x.1).sum(); - (agree >= 0.5 * total).then_some(-median.0) + let agreeing: Vec<_> = v.iter().filter(|(d, _)| (d - median.0).abs() <= 2.0).collect(); + let agree: f64 = agreeing.iter().map(|x| x.1).sum(); + (agree >= 0.5 * total && agreeing.len() >= min_lines && median.0.abs() <= max).then_some(-median.0) } fn rot_z_h(deg: f64) -> Homography { @@ -569,11 +576,27 @@ pub fn analyze_source(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> A a } +/// The most Auto straighten turns a photo (degrees). Measured on 68 photos straightened by hand +/// in Lightroom Classic and 300 left as shot: none was turned by more than 6°, while a larger +/// "level" came from texture (wooden planks, a branch, a bird's wing) and turned photos that were +/// straight. +pub const STRAIGHTEN_MAX_DEGREES: f64 = 10.0; + +/// The fewest agreeing lines Auto straighten acts on: one line (the frame's edge, a branch) said +/// nothing about the horizon in that measurement. +pub const STRAIGHTEN_MIN_LINES: usize = 3; + /// The rotation (degrees, clockwise +) that levels `src`'s dominant horizon/plumb lines, if they agree -/// (the consensus rule of Upright Level). Used by the crop panel's Auto straighten. +/// (the consensus rule of Upright Level), within [`STRAIGHTEN_MAX_DEGREES`] and backed by at least +/// [`STRAIGHTEN_MIN_LINES`] lines. Used by the crop panel's Auto straighten. pub fn level_degrees(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Option<f64> { let a = analyze_source(src, info, s); - level_angle(&a.vertical, &a.horizontal) + straighten_angle(&a) +} + +/// [`level_degrees`] of an analysis. +pub fn straighten_angle(a: &Analysis) -> Option<f64> { + level_angle_within(&a.vertical, &a.horizontal, STRAIGHTEN_MAX_DEGREES, STRAIGHTEN_MIN_LINES) } /// The automatic Upright correction for `mode` on `src` (identity for Off and Guided). diff --git a/crates/pipeline/tests/it/main.rs b/crates/pipeline/tests/it/main.rs new file mode 100644 index 0000000000..95fc179bfa --- /dev/null +++ b/crates/pipeline/tests/it/main.rs @@ -0,0 +1,3 @@ +//! The integration tests, one module per file, linked into one test binary. + +mod preview_save; diff --git a/crates/pipeline/tests/preview_save.rs b/crates/pipeline/tests/it/preview_save.rs similarity index 100% rename from crates/pipeline/tests/preview_save.rs rename to crates/pipeline/tests/it/preview_save.rs diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 76d48872da..be2ba8d445 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -268,6 +268,27 @@ impl Rgba8 { } Some(Self { width, height, data: bytes.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2], c[3]]).collect() }) } + + /// Build an image from exactly `width * height` RGBA pixels. + /// + /// This copies each pixel once, straight into the image's own buffer, so a caller that already + /// holds a pixel array (an egui `ColorImage`, say) does not need a second full byte vector. + /// `None` for a zero or overflowing size, or a pixel count that is not exactly `width * height`. + pub fn from_pixels(width: usize, height: usize, pixels: impl IntoIterator<Item = [u8; 4]>) -> Option<Self> { + if width == 0 || height == 0 { + return None; + } + let expected = width.checked_mul(height)?; + let mut data = Vec::new(); + data.try_reserve_exact(expected).ok()?; + for (i, pixel) in pixels.into_iter().enumerate() { + if i == expected { + return None; + } + data.push(pixel); + } + (data.len() == expected).then_some(Self { width, height, data }) + } /// Linear Rec.709/sRGB primaries float image from 8-bit sRGB. pub fn to_linear(&self) -> Rgb32f { use lightcraft_color::transfer::decode_srgb8; @@ -356,4 +377,15 @@ mod tests { assert_eq!(img.to_linear().to_srgb8(), img); assert_eq!(Rgba8::from_bytes(16, 16, &img.as_bytes()).unwrap(), img); } + + #[test] + fn from_pixels_requires_exactly_the_stated_pixels() { + let img = Rgba8::from_fn(4, 3, |x, y| [x as u8, y as u8, 9, 255]); + let rebuilt = Rgba8::from_pixels(4, 3, img.as_bytes().as_chunks::<4>().0.iter().map(|p| [p[0], p[1], p[2], p[3]])).unwrap(); + assert_eq!(rebuilt, img); + assert!(Rgba8::from_pixels(4, 3, vec![[0, 0, 0, 0]; 11]).is_none(), "too few pixels"); + assert!(Rgba8::from_pixels(4, 3, vec![[0, 0, 0, 0]; 13]).is_none(), "too many pixels"); + assert!(Rgba8::from_pixels(0, 3, std::iter::empty()).is_none()); + assert!(Rgba8::from_pixels(usize::MAX, 2, std::iter::empty()).is_none()); + } } diff --git a/crates/raw/src/dngwrite.rs b/crates/raw/src/dngwrite.rs index d7ba427766..fae6015b6d 100644 --- a/crates/raw/src/dngwrite.rs +++ b/crates/raw/src/dngwrite.rs @@ -94,6 +94,17 @@ pub const SOFTWARE: &str = "LightCraft DNG 2"; /// (3.9 s vs 0.55 s on 4 cores) to save 3 % of the file (266 vs 275 MB); 5–12 % on raw and rendered DNGs. const DEFLATE_LEVEL: u8 = 1; +/// Largest Deflate tile edge the writer pads to (`tile` is caller-supplied in [`DngCompression::Deflate`]): +/// square-tile buffers grow with the square, so an unclamped edge lets a request pad a tiny valid image into +/// a multi-gigabyte buffer and billions of edge-replicate iterations. 2048² samples (≤ 24 MB of f32) is far +/// above the 256 default and every real tile this writer makes. +const MAX_DEFLATE_TILE: u32 = 2048; + +/// `tile` aligned down to a multiple of 16 and clamped to [`MAX_DEFLATE_TILE`]. +fn deflate_tile(tile: u32) -> usize { + (tile.max(16) & !15).min(MAX_DEFLATE_TILE) as usize +} + /// IEEE 754 binary32 → binary16 (round to nearest even; overflow → ±inf, NaN kept). pub fn f32_to_f16(v: f32) -> u16 { let b = v.to_bits(); @@ -318,7 +329,7 @@ pub fn write_dng(raw: &RawImage, opts: &DngWriteOptions) -> Result<Vec<u8>> { match (&raw.data, opts.compression) { (RawData::F32(v), DngCompression::Deflate { tile, half }) => { - let tile = (tile.max(16) & !15) as usize; + let tile = deflate_tile(tile); let bp = if half { 2 } else { 4 }; ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![(bp * 8) as u16; cpp])); ifd.set(t::SAMPLE_FORMAT, Value::Short(vec![3; cpp])); @@ -417,7 +428,7 @@ pub fn write_dng(raw: &RawImage, opts: &DngWriteOptions) -> Result<Vec<u8>> { ifd.set_image(ImageData::Strips { rows_per_strip: rows as u32, strips }); } DngCompression::Deflate { tile, .. } => { - let tile = (tile.max(16) & !15) as usize; + let tile = deflate_tile(tile); ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16; cpp])); ifd.set(t::COMPRESSION, Value::Short(vec![compression::ADOBE_DEFLATE])); ifd.set(t::PREDICTOR, Value::Short(vec![2])); @@ -546,3 +557,45 @@ pub fn write_rendered_dng( let order = ByteOrder::Little; write_dng(&raw, &DngWriteOptions { compression: DngCompression::Deflate { tile: 256, half: true }, order, xmp }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{BlackLevel, OpcodeLists, RawData, RawFormat, RawImage, Rect}; + + /// Deflate tiles of `tile × tile` pad into a square buffer that grows with the square: a + /// caller-supplied edge of `u32::MAX` would make the writer pad an 8 × 8 image into billions of + /// edge-replicate iterations and a multi-gigabyte buffer. The clamp keeps the bounded shape — same + /// file as requesting the cap exactly, and a DNG either way. + #[test] + fn a_hostile_deflate_tile_edge_is_clamped() { + let (w, h) = (8usize, 8usize); + let full = Rect::new(0, 0, w, h); + let raw = RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::U16((0..64).map(|i| i as u16 * 129).collect()), + cfa: None, + bits: 12, + black: BlackLevel::uniform(0.0), + white: vec![4095.0], + active_area: full, + crop: full, + orientation: lightcraft_geom::Orientation::Normal, + color: crate::ColorData::default(), + wb_multipliers: None, + linearized: false, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + metadata: Default::default(), + lens_metadata: Default::default(), + }; + let opts = |tile: u32| DngWriteOptions { compression: DngCompression::Deflate { tile, half: false }, ..DngWriteOptions::default() }; + let hostile = write_dng(&raw, &opts(u32::MAX)).expect("the clamped tile writes"); + assert_eq!(hostile, write_dng(&raw, &opts(2048)).expect("the cap itself writes"), "u32::MAX is clamped to the cap"); + assert_ne!(hostile, write_dng(&raw, &opts(256)).expect("a normal tile writes"), "the clamp is not a no-op"); + assert_eq!(crate::probe(&hostile), Some(RawFormat::Dng), "the clamped output is still a DNG"); + } +} diff --git a/crates/raw/src/opcodes.rs b/crates/raw/src/opcodes.rs index 6cf224984b..d5a3ffd1e1 100644 --- a/crates/raw/src/opcodes.rs +++ b/crates/raw/src/opcodes.rs @@ -656,18 +656,38 @@ fn fix_pixels(buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa> } } +/// Most full-image passes of one `OpcodeList3`: every warp record is a full-image allocation and resample +/// pass and every bad-pixel record a full flatten-and-rebuild, and a hostile record may repeat either +/// thousands of times. Real DNGs carry at most a couple; passes past the cap are skipped. +const MAX_LIST3_PASSES: usize = 8; + /// Apply `OpcodeList3` (on the demosaiced RGB image, values normalised to [0, 1]). pub fn apply_list3(list: &[Opcode], img: &mut Rgb32f) { if list.is_empty() { return; } let (w, h) = (img.width, img.height); + let mut passes = 0usize; for op in applied_ops(list) { match op { - Opcode::WarpRectilinear { planes, center } => *img = warp_rectilinear(img, planes, *center), - Opcode::WarpRectilinear2 { planes, center, reciprocal, .. } => *img = warp_rectilinear2(img, planes, *center, *reciprocal), + Opcode::WarpRectilinear { planes, center } => { + if passes < MAX_LIST3_PASSES { + passes += 1; + *img = warp_rectilinear(img, planes, *center); + } + } + Opcode::WarpRectilinear2 { planes, center, reciprocal, .. } => { + if passes < MAX_LIST3_PASSES { + passes += 1; + *img = warp_rectilinear2(img, planes, *center, *reciprocal); + } + } Opcode::WarpFisheye { .. } | Opcode::TrimBounds { .. } | Opcode::Unknown { .. } => {} other => { + if passes >= MAX_LIST3_PASSES { + continue; + } + passes += 1; let mut flat: Vec<f32> = img.data.iter().flat_map(|p| *p).collect(); apply_list(std::slice::from_ref(other), &mut flat, w, h, 3, None, 1.0); for (d, c) in img.data.iter_mut().zip(flat.as_chunks::<3>().0) { @@ -765,6 +785,27 @@ pub(crate) mod tests { a.iter().flat_map(|v| v.to_be_bytes()).collect() } + /// Warp and bad-pixel records each cost a full-image pass, and a hostile `OpcodeList3` repeats them + /// thousands of times ([`MAX_LIST3_PASSES`] bounds the multiplier); identity warps below the cap must + /// still apply, exactly, so the same image comes out. + #[test] + fn list3_pass_cap_skips_repeated_records() { + let mut img = Rgb32f::new(8, 6); + for (i, px) in img.data.iter_mut().enumerate() { + *px = [i as f32 / 2.0, (i % 8) as f32, (i / 8) as f32]; + } + let orig: Vec<[f32; 3]> = img.data.clone(); + let list: Vec<Opcode> = + (0..MAX_LIST3_PASSES * 5).map(|_| Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }).collect(); + apply_list3(&list, &mut img); + assert_eq!(img.data, orig, "identity warps change nothing, and the cap skips the repeated rest"); + + // a real warp below the cap is still applied + let one = [Opcode::WarpRectilinear { planes: vec![[2.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }]; + apply_list3(&one, &mut img); + assert_ne!(img.data, orig, "a genuine warp record is not skipped"); + } + #[test] fn parse_and_apply_area_ops() { let (w, h) = (4usize, 3usize); diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 95f9bdcaa9..4bcf6963e5 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -103,8 +103,6 @@ fn jpeg_frame(b: &[u8]) -> Option<(u32, u32, u8)> { let be16 = |k: usize| Some(u32::from(u16::from_be_bytes([at(k)?, at(k + 1)?]))); Some((be16(7)?, be16(5)?, at(9)?)) } - -/// Whether `b` is a JPEG XL file: a bare codestream or the ISO-BMFF container's signature box. fn is_jxl(b: &[u8]) -> bool { b.starts_with(&[0xff, 0x0a]) || b.starts_with(&[0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a]) } @@ -128,20 +126,17 @@ fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>) } if matches!(ifd.u16(t::COMPRESSION), Some(6) | Some(7) | Some(34892)) && let Ok(info) = ifd.image() + && let Some(chunk) = info.single_chunk(data.len() as u64) + && let Some(s) = chunk_bytes(data, &chunk) { - let chunks = info.chunks(data.len() as u64); - if chunks.len() == 1 - && let Some(s) = chunk_bytes(data, &chunks[0]) - { - out.push(s); - } + out.push(s); } // a rendered (RGB or grey, never CFA/LinearRaw/mask) JPEG XL preview in one chunk if ifd.u16(t::COMPRESSION) == Some(t::compression::JPEG_XL) && matches!(ifd.u16(t::PHOTOMETRIC), Some(t::photometric::BLACK_IS_ZERO | t::photometric::RGB)) && let Ok(info) = ifd.image() - && let [chunk] = info.chunks(data.len() as u64).as_slice() - && let Some(s) = chunk_bytes(data, chunk) + && let Some(chunk) = info.single_chunk(data.len() as u64) + && let Some(s) = chunk_bytes(data, &chunk) && is_jxl(s) { out.push(s); @@ -397,8 +392,14 @@ fn cr3_preview(bytes: &[u8]) -> Option<&[u8]> { /// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0 /// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller /// `THMB` box has the same shape. Returns the larger valid one. +/// Marker-walk budget of the CR3 fallback: candidates can overlap (each claiming the rest of the file) and +/// [`is_dct_jpeg`] walks each marker by marker, so walking every candidate would be quadratic in file size. +/// The `THMB`/`PRVW` previews this finds are far below the cap together; once it is spent the scan stops. +const CR3_MAX_WALK: usize = 8 << 20; + fn cr3_preview_boxes(bytes: &[u8]) -> Option<&[u8]> { let mut best: Option<&[u8]> = None; + let mut walked = 0usize; for tag in [b"PRVW", b"THMB"] { let mut from = 0; while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) { @@ -411,6 +412,11 @@ fn cr3_preview_boxes(bytes: &[u8]) -> Option<&[u8]> { continue; } let jpeg = &bytes[j..j + len]; + // One that doesn't fit the budget left is skipped; a smaller one later may still fit. + if walked + jpeg.len() > CR3_MAX_WALK { + continue; + } + walked += jpeg.len(); if is_dct_jpeg(jpeg) { if best.is_none_or(|b| b.len() < jpeg.len()) { best = Some(jpeg); @@ -440,6 +446,52 @@ mod tests { j } + /// Preview extraction only serves single-chunk JPEG-compressed IFDs and asks the `single_chunk` first: + /// a TIFF whose strip array declares 100 000 one-row strips and no StripByteCounts must not build their + /// descriptor vector, and of course finds no preview in it. + #[test] + fn a_multi_strip_jpeg_ifd_costs_no_descriptor_vector() { + let mut ifd = IfdBuilder::new(); + ifd.set(t::COMPRESSION, Value::Short(vec![7])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![16])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![100_000])); + ifd.set(t::ROWS_PER_STRIP, Value::Short(vec![1])); + ifd.set(t::STRIP_OFFSETS, Value::Byte((0..100_000).map(|i| (i % 255 + 1) as u8).collect())); + let file = TiffWriter::default().write(&[ifd]).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(embedded_preview(&file))); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(2)), Ok(None)); + } + + /// CR3 candidates claim overlapping extents: each block's first bytes double as a 40-byte jump marker so + /// a walk jogs past the next header and reaches the end of the file, making every one of the 9000 + /// candidates walk its whole suffix before the marker-walk budget — quadratic without it. Nothing here + /// is a JPEG (no frame header), so the answer is `None` either way. + #[test] + fn cr3_preview_boxes_stop_walking_when_the_budget_is_spent() { + // one 256-byte block per candidate, all marker-aligned so walks chain through later blocks: + // 0..4, size (itself a jump marker of 40 bytes); 4..8, "PRVW"; 20..24, the claimed length + // (to the file end); 24..28, an SOI plus a marker jumping to the fill at 40; 64..256, a fill of + // 4-byte markers (`ff 01 00 02`). + let blocks = 9000usize; + let total = blocks * 256; + let mut f = Vec::with_capacity(total); + for k in 0..blocks { + let base = k * 256; + f.extend_from_slice(&[0xff, 0x01, 0x00, 0x26, b'P', b'R', b'V', b'W', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + f.extend_from_slice(&u32::try_from(total - base - 24).unwrap().to_be_bytes()); + f.extend_from_slice(&[0xff, 0xd8, 0x00, 0x24, 0xff, 0x01, 0x00, 0x26, 0, 0, 0, 0, 0, 0, 0, 0]); + f.resize(base + 64, 0); // 40..64 filler: walks jump over it, so its bytes are free + for _ in 0..48 { + f.extend_from_slice(&[0xff, 0x01, 0x00, 0x02]); + } + } + assert_eq!(f.len(), total); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(cr3_preview_boxes(&f).map(|s| s.len()))); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(2)), Ok(None), "no PRVW candidate is a JPEG"); + } + /// A minimal RAF: the fixed header (JPEG offset/length at 84/88), the JPEG, then a raw tail the /// caller must not have to read. `jpeg_len` is written as declared, so a test can claim more than /// the JPEG holds the way a padded container does. diff --git a/crates/raw/src/sparse.rs b/crates/raw/src/sparse.rs index d67a92b407..8a404a25ea 100644 --- a/crates/raw/src/sparse.rs +++ b/crates/raw/src/sparse.rs @@ -35,6 +35,12 @@ const MAX_ENTRIES: u64 = 8192; const MAX_BOXES: usize = 4096; /// Child IFDs listed by one `SubIFDs` entry. const MAX_CHILDREN: u64 = 4096; +/// Pending child-IFD offsets the walker may queue at once: no more than it can ever visit +/// (the same [`MAX_IFDS`] the seen set is held to, deduplicated as they are popped), so an alley +/// of hostile `SubIFDs` entries can't grow the queue into the tens of millions of pointers. +/// The plan never guesses: the walk refuses and the plan reports the whole file when it would go +/// past the cap. +const MAX_PENDING: usize = MAX_IFDS; /// The RAF raw container's pointer to its raw IFD. const RAF_RAW_IFD: u16 = 0xf000; @@ -308,6 +314,13 @@ fn walk_tiff(w: &mut Want, origin: u64, data: &[u8], extra: &[u16]) -> Result<Ra }; let mut stack = vec![first]; let mut seen = HashSet::new(); + // Every offset ever queued: the pending cap counts distinct IFDs, so a thousand references to + // one child cost one visit, not a thousand. + let mut queued = HashSet::from([first]); + // Every IFD table and out-of-line value, collected and merged once at the end: an insert + // per entry would scan the ranges of every entry before it — quadratic in the metadata + // this walker collects. + let mut spans: Vec<(u64, u64)> = Vec::new(); while let Some(off) = stack.pop() { if off == 0 || off >= len || seen.len() >= MAX_IFDS || !seen.insert(off) { continue; @@ -329,7 +342,7 @@ fn walk_tiff(w: &mut Want, origin: u64, data: &[u8], extra: &[u16]) -> Result<Ra if !w.want(at(off), at(end)) { continue; } - meta.insert(at(off), at(end)); + spans.push((at(off), at(end))); for i in 0..n_read { let p = table + i * entry; let Ok(pu) = usize::try_from(p) else { continue }; @@ -348,7 +361,7 @@ fn walk_tiff(w: &mut Want, origin: u64, data: &[u8], extra: &[u16]) -> Result<Ra }; let Some(value_end) = start.checked_add(total).filter(|&e| e <= len) else { continue }; if total > inline { - meta.insert(at(start), at(value_end)); + spans.push((at(start), at(value_end))); } let child = matches!(tag, t::SUB_IFDS | t::EXIF_IFD | t::GPS_IFD | t::INTEROP_IFD) || extra.contains(&tag); let locates = child || matches!(tag, t::STRIP_OFFSETS | t::STRIP_BYTE_COUNTS | t::TILE_OFFSETS | t::TILE_BYTE_COUNTS); @@ -359,14 +372,24 @@ fn walk_tiff(w: &mut Want, origin: u64, data: &[u8], extra: &[u16]) -> Result<Ra let take = if tag == t::SUB_IFDS { count.min(MAX_CHILDREN) } else { count.min(1) }; for k in 0..take { if let Some(v) = unsigned(data, order, typ, start + k * typ.size() as u64) { + if v == 0 || v >= len || !queued.insert(v) { + continue; + } + if stack.len() >= MAX_PENDING { + return Err("too many child IFDs queued to visit"); + } stack.push(v); } } } - if complete && let Some(next) = offset_at(table_end) { + if complete && let Some(next) = offset_at(table_end).filter(|&next| next != 0 && next < len && queued.insert(next)) { + if stack.len() >= MAX_PENDING { + return Err("too many child IFDs queued to visit"); + } stack.push(next); } } + meta.extend(spans); Ok(meta) } @@ -585,8 +608,74 @@ mod tests { assert_eq!(run(&file, 16, 0).0, HeaderPlan::Whole("an ARW6 header probe reads its tiles")); } - /// A TIFF with a million one-byte strips listed in descending order and all byte counts 0: the plan is - /// built in one sort and merge, not one pass over all strips (or all holes) per strip. + /// An IFD whose `SubIFDs` entries would queue 33 million child pointers (8192 entries of + /// 4096 values apiece, all pointing at the same array) is refused at the walker's pending + /// cap instead of growing the queue — and the plan reports the whole file, never guessing. + #[test] + fn a_subifds_alley_is_refused_at_the_pending_cap() { + // First read everything, so the walk reaches the directory table itself. + let n = 8192u32; + let len = 8 + 2 + (n * 12 + 4 + 4 * 4096) as usize; + let mut tiff = b"II*\0\x08\0\0\0".to_vec(); + tiff.extend_from_slice(&(n as u16).to_le_bytes()); + let mut entry = |tag: u16, typ: u16, count: u32, value: u32| { + tiff.extend_from_slice(&tag.to_le_bytes()); + tiff.extend_from_slice(&typ.to_le_bytes()); + tiff.extend_from_slice(&count.to_le_bytes()); + tiff.extend_from_slice(&value.to_le_bytes()); + }; + // header (8) + count field (2) + the {n} numbers and pointer (4), then the value array + let values_at = (8 + 2u64 + u64::from(n) * 12 + 4) as u32; + for _ in 0..n { + entry(t::SUB_IFDS, 4, MAX_CHILDREN as u32, values_at); + } + tiff.extend_from_slice(&0u32.to_le_bytes()); + tiff.extend((1..=4096u32).flat_map(u32::to_le_bytes)); + let mut loaded = Ranges::new(); + loaded.insert(0, len as u64); + let mut w = Want::new(&tiff, &loaded); + assert_eq!(walk_tiff(&mut w, 0, &tiff, &[]), Err("too many child IFDs queued to visit")); + } + + /// A TIFF with many out-of-line values across 512 directories is planned in one sort and + /// merge, not one pass over all accumulated ranges per value (CodeRabbit #52: before, each + /// `Ranges::insert` copied every range found before it — the ~million disjoint values of the + /// fixture below ask for more copying than the timeout allows). + #[test] + fn many_out_of_line_values_plan_fast() { + let (ifds, values) = (512usize, 2048usize); + let ifd_len = 2 + values * 12 + 4; + let values_at = 8 + ifds * ifd_len; + let len = values_at + values * 8; + let mut tiff = vec![0u8; len]; + tiff[..8].copy_from_slice(b"II*\0\x08\0\0\0"); + for i in 0..ifds { + let at = 8 + i * ifd_len; + // {values} out-of-line strings (count 8 > the 4 inline bytes), then the next-IFD + // pointer; every value is a disjoint 8-byte range for the merge to handle. + tiff[at..at + 2].copy_from_slice(&(values as u16).to_le_bytes()); + for k in 0..values { + let e = at + 2 + k * 12; + tiff[e..e + 2].copy_from_slice(&t::MAKE.to_le_bytes()); + tiff[e + 2..e + 4].copy_from_slice(&2u16.to_le_bytes()); // ASCII: 8 bytes > inline — a span per entry + tiff[e + 4..e + 8].copy_from_slice(&8u32.to_le_bytes()); + tiff[e + 8..e + 12].copy_from_slice(&(values_at as u32 + (k * 8) as u32).to_le_bytes()); + } + let next = if i == ifds - 1 { 0u32 } else { (at + ifd_len) as u32 }; + tiff[at + ifd_len - 4..at + ifd_len].copy_from_slice(&next.to_le_bytes()); + } + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut loaded = Ranges::new(); + loaded.insert(0, len as u64); + let _ = tx.send(header_plan(&tiff, &loaded)); + }); + rx.recv_timeout(std::time::Duration::from_secs(20)).expect("header_plan took longer than 20 s"); + } + + /// A TIFF with a million one-byte strips listed in descending order and all byte counts 0: + /// the plan is built in one sort and merge, not one pass over all strips (or all holes) per + /// strip. #[test] fn many_strips_without_byte_counts_plan_fast() { let n = 1_000_000u32; diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index a781151b44..57878b881c 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -105,48 +105,93 @@ pub fn read_image(data: &[u8], info: &ImageInfo, order: ByteOrder, packing: Pack let chunks = info.chunks(data.len() as u64); let planar = info.planar == 2 && cpp > 1; let ccpp = if planar { 1 } else { cpp }; - let decoded: Vec<Result<(Chunk, ChunkPx)>> = - chunks.par_iter().map(|c| decode_chunk(data, info, c, order, packing, ccpp, bits, float).map(|p| (*c, p))).collect(); + // The chunks are decoded and copied into the output in groups whose combined nominal size stays within + // a few times the output buffer's: everything decoded at once would retain the whole image twice, and + // a hostile tile table's chosen padding could stretch that much further (issue #1517). One group + // still decodes in parallel; the grid order groups make, the copies stay disjoint. + // The tile grid decides how much is decoded, whatever the file's bytes: the nominal sizes of all + // the chunks stay within a few times the image (edge tiles pad it) before any is decoded. + let nominal = chunks.iter().fold(0usize, |sum, c| sum.saturating_add(chunk_samples(c, ccpp))); + if nominal > total.saturating_mul(4).saturating_add(1 << 24) { + return Err(RawError::Corrupt("the tile grid is much larger than the image".into())); + } + let group_samples = (total / 4).max(1 << 20); let mut out_u16 = if float { Vec::new() } else { vec![0u16; total] }; let mut out_f32 = if float { vec![0f32; total] } else { Vec::new() }; - for r in decoded { - // a chunk that cannot be decoded is not a partial image: the file stays preview-only - let (c, px) = r?; - let (cw, ch) = (c.width as usize, c.height as usize); - let (x0, y0) = (c.x as usize, c.y as usize); - if x0 >= w || y0 >= h { - continue; + let mut decode_from = 0usize; + while decode_from < chunks.len() { + let mut to = decode_from; + let mut taken = 0usize; + for (k, c) in chunks[decode_from..].iter().enumerate() { + let n = chunk_samples(c, ccpp); + if taken > 0 && taken.saturating_add(n) > group_samples { + break; + } + taken = taken.saturating_add(n); + to = decode_from + k + 1; } - let copy_w = cw.min(w - x0); - let copy_h = ch.min(h - y0); - for y in 0..copy_h { - for x in 0..copy_w { - for s in 0..ccpp { - let src = (y * cw + x) * ccpp + s; - let dst_s = if planar { c.plane as usize } else { s }; - if dst_s >= cpp { - continue; - } - let dst = ((y0 + y) * w + x0 + x) * cpp + dst_s; - match &px { - ChunkPx::U16(v) => { - if let (Some(o), Some(&s)) = (out_u16.get_mut(dst), v.get(src)) { - *o = s; - } + let decoded: Vec<Result<(Chunk, ChunkPx)>> = + chunks[decode_from..to].par_iter().map(|c| decode_chunk(data, info, c, order, packing, ccpp, bits, float).map(|p| (*c, p))).collect(); + for r in decoded { + // a chunk that cannot be decoded is not a partial image: the file stays preview-only + let (c, px) = r?; + let (cw, ch) = (c.width as usize, c.height as usize); + let (x0, y0) = (c.x as usize, c.y as usize); + if x0 >= w || y0 >= h { + continue; + } + let copy_w = cw.min(w - x0); + let copy_h = ch.min(h - y0); + for y in 0..copy_h { + for x in 0..copy_w { + for s in 0..ccpp { + let src = (y * cw + x) * ccpp + s; + let dst_s = if planar { c.plane as usize } else { s }; + if dst_s >= cpp { + continue; } - ChunkPx::F32(v) => { - if let (Some(o), Some(&s)) = (out_f32.get_mut(dst), v.get(src)) { - *o = s; + let dst = ((y0 + y) * w + x0 + x) * cpp + dst_s; + match &px { + ChunkPx::U16(v) => { + if let (Some(o), Some(&s)) = (out_u16.get_mut(dst), v.get(src)) { + *o = s; + } + } + ChunkPx::F32(v) => { + if let (Some(o), Some(&s)) = (out_f32.get_mut(dst), v.get(src)) { + *o = s; + } } } } } } } + decode_from = to; } Ok(if float { RawData::F32(out_f32) } else { RawData::U16(out_u16) }) } +/// Bytes that `n` samples take in a row of an uncompressed or inflated chunk, laid out as +/// [`unpack_chunk`] reads them: whole bytes or 16-bit words, or 32-bit words for `Words32Msb`. +fn packed_row_bytes(n: u64, bits: u32, packing: Packing, float: bool) -> u64 { + if float { + return n.saturating_mul(u64::from(bits.div_ceil(8))); + } + let bit_len = n.saturating_mul(u64::from(bits)); + match (bits, packing) { + (8, _) => n, + (16, _) | (_, Packing::Word16) => n.saturating_mul(2), + (_, Packing::Msb | Packing::Lsb) => bit_len.div_ceil(8), + (_, Packing::Words32Msb) => bit_len.div_ceil(32).saturating_mul(4), + } +} + +/// A chunk's nominal decoded size in samples (per plane, as the decoder builds it). +fn chunk_samples(c: &Chunk, ccpp: usize) -> usize { + (c.width as usize).saturating_mul(c.height as usize).saturating_mul(ccpp) +} + #[allow(clippy::too_many_arguments)] fn decode_chunk(data: &[u8], info: &ImageInfo, c: &Chunk, order: ByteOrder, packing: Packing, cpp: usize, bits: u32, float: bool) -> Result<ChunkPx> { let src = chunk_bytes(data, c).ok_or_else(|| RawError::Corrupt("chunk offset past end of file".into()))?; @@ -179,9 +224,13 @@ fn decode_chunk(data: &[u8], info: &ImageInfo, c: &Chunk, order: ByteOrder, pack } comp::LOSSY_JPEG => { // lossy DNG: each chunk is a baseline (DCT) JPEG of 8-bit samples - let (px, jw, jh, jc) = lossy_jpeg(src, cpp)?; - let mut v = vec![0u16; n]; - for y in 0..ch.min(jh) { + let (px, jw, jh, jc) = lossy_jpeg(src, cpp, MAX_JPEG_SAMPLES)?; + // the buffer holds the rows the decoded JPEG covers (the caller zero-fills the tile's + // remainder and reads only rows it fills): a tile-many-larger decoded JPEG does not + // get the nominal tile's full buffer (issue #1517) + let rows = ch.min(jh); + let mut v = vec![0u16; rows.max(1).saturating_mul(cw).saturating_mul(cpp)]; + for y in 0..rows { for x in 0..cw.min(jw) { for k in 0..cpp { v[(y * cw + x) * cpp + k] = px[(y * jw + x) * jc + k.min(jc - 1)] as u16; @@ -191,13 +240,28 @@ fn decode_chunk(data: &[u8], info: &ImageInfo, c: &Chunk, order: ByteOrder, pack Ok(ChunkPx::U16(v)) } comp::ADOBE_DEFLATE | comp::DEFLATE => { - let bytes_per = if float { bits.div_ceil(8) as usize } else { 0 }; // row bytes in u64: a wrapping `cw · cpp · …` in usize could come out small on 32-bit targets and slip past the gate - let row_bytes = if float { cw as u64 * cpp as u64 * bytes_per as u64 } else { (cw as u64 * cpp as u64 * bits as u64).div_ceil(8) }; + let row_bytes = packed_row_bytes(cw as u64 * cpp as u64, bits, packing, float); // the gate caps at MAX_SAMPLES (≤ 2^30), so the `usize` cast below is lossless on 32-bit targets too let inflate_len = crate::checked_pixel_count(row_bytes, ch as u64).ok_or_else(|| RawError::Corrupt("bad TIFF chunk dimensions".into()))?; + // Deflate compresses at most about 1:1032, so a source this far under half of its + // nominal length cannot reconstruct the chunk: refused before the nominal buffer is + // inflated and predicted, which padding-only work would make gigabytes. + if (src.len() as u64).saturating_mul(2048) < inflate_len { + return Err(RawError::Corrupt(format!("a deflated chunk of {inflate_len} bytes is packed into only {} bytes", src.len()))); + } let raw = inflate(src, inflate_len as usize)?; + // The stream has to reach the last row inside the image (edge strips may stop there); + // it is laid out in nominal rows, so shorter is a truncated chunk, not a picture. + let last = packed_row_bytes(vw as u64 * cpp as u64, bits, packing, float); + let visible = row_bytes.saturating_mul(vh.saturating_sub(1) as u64).saturating_add(last); + if (raw.len() as u64) < visible { + return Err(RawError::Corrupt(format!( + "a deflated chunk holds {} bytes, fewer than the {visible} bytes its in-image samples span", + raw.len() + ))); + } unpack_chunk(&raw, order, packing, cw, ch, cpp, bits, float, info.predictor) } comp::JPEG_XL => jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float), @@ -228,19 +292,31 @@ fn jxl_chunk_check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ()) } +/// The most samples a tiled JPEG chunk or a white-balance preview may decode to: far more than +/// any real lossy tile or preview carries, and small enough that a JPEG header alone cannot size +/// a multi-gigabyte allocation. +pub(crate) const MAX_JPEG_SAMPLES: usize = 1 << 26; + /// Decode one baseline JPEG chunk to 8-bit samples: (samples, width, height, channels). -pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize) -> Result<(Vec<u8>, usize, usize, usize)> { +pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max_samples: usize) -> Result<(Vec<u8>, usize, usize, usize)> { use zune_core::bytestream::ZCursor; use zune_core::colorspace::ColorSpace; use zune_core::options::DecoderOptions; let cs = if cpp == 1 { ColorSpace::Luma } else { ColorSpace::RGB }; let opts = DecoderOptions::default().set_max_width(1 << 16).set_max_height(1 << 16).set_strict_mode(false).jpeg_set_out_colorspace(cs); let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(src), opts); - let px = d.decode().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; + // The header is read first: the JPEG's own dimensions, not the enclosing tile's, size every + // allocation `decode` makes, and they may claim billions of pixels. + d.decode_headers().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; let info = d.info().ok_or_else(|| RawError::Corrupt("lossy JPEG tile without a header".into()))?; let (w, h) = (info.width as usize, info.height as usize); let c = if cpp == 1 { 1 } else { 3 }; - if w == 0 || h == 0 || px.len() < w * h * c { + let out = w as u64 * h as u64 * c as u64; + if w == 0 || h == 0 || out > max_samples as u64 { + return Err(RawError::Corrupt(format!("a lossy JPEG of {w} × {h} × {c} would exceed the {max_samples} output samples allowed"))); + } + let px = d.decode().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; + if px.len() < w * h * c { return Err(RawError::Corrupt("lossy JPEG tile: short output".into())); } Ok((px, w, h, c)) @@ -471,4 +547,97 @@ mod lossy_tests { // half of the visible rows are missing assert!(decode(8, 4).is_err()); } + + /// A lossy JPEG whose header alone claims more samples than any real tile or preview (here + /// 40000 × 40000 × 3) is refused from the header, before the decoder allocates its output + /// from the JPEG's own dimensions. + #[test] + fn an_oversized_lossy_jpeg_header_is_refused_before_decoding() { + // A real 8 × 8 baseline JPEG, whose frame header then claims other dimensions: the decoder + // parses the header, and the size check is what refuses it. + let px = vec![128u8; 8 * 8 * 3]; + let mut j = Vec::new(); + jpeg_encoder::Encoder::new(&mut j, 90).encode(&px, 8, 8, jpeg_encoder::ColorType::Rgb).unwrap(); + // SOF0: marker, length, precision, then the height and the width + let sof = j.windows(2).position(|w| w == [0xff, 0xc0]).expect("a baseline frame header"); + let claim = |j: &mut Vec<u8>, size: u16| { + j[sof + 5..sof + 7].copy_from_slice(&size.to_be_bytes()); + j[sof + 7..sof + 9].copy_from_slice(&size.to_be_bytes()); + }; + claim(&mut j, 40_000); + let RawError::Corrupt(refused) = lossy_jpeg(&j, 3, MAX_JPEG_SAMPLES).unwrap_err() else { panic!("a corrupt-data error") }; + assert!(refused.contains("would exceed"), "{refused}"); + // a header inside the budget passes the size check (and then fails to decode only for lack of data) + claim(&mut j, 1024); + match lossy_jpeg(&j, 3, MAX_JPEG_SAMPLES) { + Ok(_) => {} + Err(RawError::Corrupt(m)) => assert!(!m.contains("would exceed"), "the smaller header was refused for its size: {m}"), + Err(other) => panic!("unexpected error: {other:?}"), + } + } + + /// A lossy tile whose JPEG decodes far less than the nominal tile is fine: the rows the JPEG + /// covers hold its pixels, the rest of the output stays zero (and the tile's intermediate buffer + /// is sized by the JPEG, not by the nominal tile). + #[test] + fn a_small_lossy_jpeg_in_a_large_nominal_tile_decodes_with_zeros_below() { + let px: Vec<u8> = (0..8 * 8).flat_map(|_| [30u8, 90, 150]).collect(); + let mut j = Vec::new(); + jpeg_encoder::Encoder::new(&mut j, 100).encode(&px, 8, 8, jpeg_encoder::ColorType::Rgb).unwrap(); + let info = ImageInfo { + width: 16, + height: 16, + bits_per_sample: vec![8, 8, 8], + samples_per_pixel: 3, + compression: comp::LOSSY_JPEG, + photometric: 34892, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Tiles { tile_width: 16, tile_height: 16 }, + offsets: vec![0], + byte_counts: vec![j.len() as u64], + }; + let RawData::U16(v) = read_image(&j, &info, ByteOrder::Little, Packing::Msb).unwrap() else { panic!("integer samples") }; + assert_eq!(v.len(), 16 * 16 * 3, "the output is the full nominal image"); + let px = |x: usize, y: usize| &v[(y * 16 + x) * 3..(y * 16 + x) * 3 + 3]; + assert!((px(3, 3)[0] as i32 - 30).abs() <= 3 && (px(3, 3)[2] as i32 - 150).abs() <= 3, "covered rows: {:?}", px(3, 3)); + assert!(px(3, 12).iter().all(|&s| s == 0), "rows below the JPEG stay zero: {:?}", px(3, 12)); + } + + /// A deflated tile is refused when its packed bytes are too few for deflate to have produced + /// the nominal chunk, or when the stream stops short of the rows inside the image; a fully + /// covered flat tile still decodes. + #[test] + fn a_short_or_undercovering_deflated_tile_is_refused() { + let info = |byte_counts: u64| ImageInfo { + width: 512, + height: 512, + bits_per_sample: vec![16], + samples_per_pixel: 1, + compression: comp::ADOBE_DEFLATE, + photometric: 32803, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Tiles { tile_width: 512, tile_height: 512 }, + offsets: vec![0], + byte_counts: vec![byte_counts], + }; + // a complete flat tile: 512 KiB of zeros compresses to a few hundred bytes (well within + // deflate's packing bound) and inflates to every nominal byte the tile claims + let zlib = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 512 * 512 * 2], 6); + assert_eq!(read_image(&zlib, &info(zlib.len() as u64), ByteOrder::Little, Packing::Msb), Ok(RawData::U16(vec![0; 512 * 512]))); + // the same 1 KiB packed, but the stream claims a whole tile: a few hundred bytes cannot + // reconstruct 512 KiB from a decoder that compresses no further than about 1:1032 + let zlib = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 1024], 6); + assert!(matches!(read_image(&zlib, &info(512 * 512 * 2), ByteOrder::Little, Packing::Msb), Err(RawError::Corrupt(_))), "{zlib:?}"); + // 500 KiB of zeros compress to a stream within the packing bound and inflating to more + // bytes than the in-image samples span, but 24 KiB short of the whole nominal tile: + // refused as truncated rather than filled with the predictor's padding + let zlib = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 500 * 1000], 6); + assert!(matches!(read_image(&zlib, &info(zlib.len() as u64), ByteOrder::Little, Packing::Msb), Err(RawError::Corrupt(_)))); + } } diff --git a/crates/raw/src/vendor/crx.rs b/crates/raw/src/vendor/crx.rs index 13f63a4a32..5d69bf2d40 100644 --- a/crates/raw/src/vendor/crx.rs +++ b/crates/raw/src/vendor/crx.rs @@ -373,7 +373,7 @@ fn split_dimension(length: usize, before: bool, after: bool) -> (usize, usize) { /// low-pass columns (bands 8 and 5, whose low-pass columns the next level transforms again) at an odd /// width: an even synthesis width gains one column, which synthesis does not use. Every other band, /// including band 2 of the last level, is coded at its synthesis width. Measured on every C-RAW plane -/// that `tests/cr3_corpus.rs` decodes (CC0 raw.pixls.us files): two-tile files with tile widths 2816, +/// that `tests/it/cr3_corpus.rs` decodes (CC0 raw.pixls.us files): two-tile files with tile widths 2816, /// 3144, 3192, 3444 and 3564 (G5 X Mark II, M50, R100, 250D, RP, R, 90D, M6 Mark II), where bands 5 /// and 8 gain a column in left tiles exactly when the rule says so, and single-tile `0x100` and /// `0x200` files, which never extend a band. In every one of those planes, each band's entropy stream diff --git a/crates/raw/src/vendor/mef.rs b/crates/raw/src/vendor/mef.rs index 207bc8871e..d5c5d83b41 100644 --- a/crates/raw/src/vendor/mef.rs +++ b/crates/raw/src/vendor/mef.rs @@ -89,6 +89,13 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> { // the white balance is measured from the samples, so the header probe reads them too let chunks = info.chunks(bytes.len() as u64); let src = chunks.first().and_then(|c| chunk_bytes(bytes, c)).ok_or_else(|| RawError::Corrupt("Mef strip outside file".into()))?; + // 12-bit MSB packing takes 3 bytes per 2 samples; a strip that cannot hold the declared + // samples is a truncated file, not a picture — unpacking it would run past the real bytes + // through every output sample (a short strip asks for the whole allocation and more). + let need = n.div_ceil(2).saturating_mul(3); + if src.len() < need { + return Err(RawError::Corrupt(format!("a Mef strip of {} bytes cannot hold the declared {n} samples", src.len()))); + } let mut d = vec![0u16; n]; crate::unpack::unpack_msb(src, 12, &mut d); let white = super::white_from_data(&d, 12); @@ -138,6 +145,10 @@ mod tests { } fn sample(w: u32, h: u32, px: &[u16]) -> Vec<u8> { + sample_strip(w, h, &pack(px)) + } + + fn sample_strip(w: u32, h: u32, strip: &[u8]) -> Vec<u8> { let mut raw = IfdBuilder::new(); raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); @@ -148,7 +159,7 @@ mod tests { raw.set(t::ORIENTATION, Value::Short(vec![6])); raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![pack(px)] }); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![strip.to_vec()] }); let mut ifd0 = IfdBuilder::new(); ifd0.set(t::MAKE, Value::Ascii("Mamiya-OP Co.,Ltd.".into())); ifd0.set(t::MODEL, Value::Ascii("MAMIYA ZD".into())); @@ -156,6 +167,52 @@ mod tests { TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap() } + /// A strip that cannot hold the declared samples is a truncated file, refused as corrupt + /// instead of unpacked: `unpack_msb` would otherwise run `n` samples through the few real + /// bytes, filling the rest from nothing. + #[test] + fn a_strip_too_short_for_the_declared_samples_is_refused() { + let px: Vec<u16> = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); + let f = sample(16, 6, &px); + assert!(crate::decode(&f).is_ok()); + // A truncated file shaped like a real one: IFD tables first, strip last — only its first + // 20 packed bytes remain, while the IFD still declares the full 1.5 B/sample length. The + // probe accepts the file on the declared length; before the byte gate below, `unpack_msb` + // ran the dimension-sized allocation through those 20 bytes, filling it from nothing. + let u32be = |b: &[u8], a: usize| u32::from_be_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]); + let full = pack(&px); + let at = f.windows(full.len()).position(|w| w == full).expect("strip bytes in the file"); + let after_strip = at + full.len(); + let moved = after_strip - (at + 20); + let mut g = f[..8].to_vec(); + g.extend(std::iter::repeat_n(0u8, at + 20 - 8)); + g.extend_from_slice(&f[after_strip..]); + // repoint the first-IFD pointer and ifd0's MAKE / MODEL / SubIfds offsets (the tables now + // sit `moved` earlier); the raw sub-IFD's strip offset and byte count are patched below + let poke = |b: &mut [u8], a: usize| { + let v = u32::from_be_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]); + if v as usize >= after_strip { + b[a..a + 4].copy_from_slice(&(v - moved as u32).to_be_bytes()); + } + }; + let ifd0_at = u32be(&g, 4) as usize - moved; + g[4..8].copy_from_slice(&(ifd0_at as u32).to_be_bytes()); + let n = u16::from_be_bytes([g[ifd0_at], g[ifd0_at + 1]]) as usize; + for i in 0..n { + poke(&mut g, ifd0_at + 2 + i * 12 + 8); + } + // the raw sub-IFD: entries follow its count; tag 273 (StripOffsets) is the seventh, held + // inline — repoint it at the strip's new home, and append the truncated strip for real + let sub_at = u32be(&g, ifd0_at + 2 + 2 * 12 + 8) as usize; + let e_offsets = sub_at + 2 + 6 * 12 + 8; + let strip_at = g.len() as u32; + g[e_offsets..e_offsets + 4].copy_from_slice(&strip_at.to_be_bytes()); + g.extend_from_slice(&full[..20]); + assert_eq!(crate::probe(&g), Some(RawFormat::Mef)); + let r = crate::decode(&g); + assert!(matches!(r, Err(RawError::Corrupt(_))), "{r:?}"); + } + #[test] fn decodes_packed_12_bit() { let px: Vec<u16> = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); diff --git a/crates/raw/src/vendor/nef.rs b/crates/raw/src/vendor/nef.rs index 62c9a2505e..10bb24d501 100644 --- a/crates/raw/src/vendor/nef.rs +++ b/crates/raw/src/vendor/nef.rs @@ -8,8 +8,9 @@ //! (HE / HE★, Z 8, Z 9, Z 6III, Z f): they keep compression 34713 but carry a wavelet codestream that starts with //! the JPEG XS markers SOC + CAP (ISO/IEC 21122-1, `FF10 FF50`) and have no `0x0096` table (issue #193). //! Strips labelled 34713 without a `0x0096` -//! linearization table are packed uncompressed data in several measured layouts ([`PackedLayout`]); Nikon small raw -//! (sRAW) and the D1X's genuinely Huffman-coded strip stay refused. +//! linearization table are packed uncompressed data in several measured layouts ([`PackedLayout`]) or, when the strip +//! is exactly three bytes per pixel, Nikon small raw ([`small_raw`]); the D1X's genuinely Huffman-coded strip stays +//! refused. use super::{nefc, white_from_data}; use crate::tiffraw::{Packing, check_image, read_image}; @@ -233,6 +234,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> { let make = ifd0.string(t::MAKE).unwrap_or_default(); let mn = tiff.exif().and_then(|e| e.get(t::MAKER_NOTE)).and_then(|e| makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)); + if let Some(strip) = small_raw_strip(&info, bytes.len(), mn.as_ref()) { + return small_raw(bytes, &tiff, &info, strip, mode); + } // the header probe reads only the rows the masked-column test needs let rows = match mode { Mode::Full => h, @@ -494,14 +498,7 @@ fn packed(bytes: &[u8], info: &ImageInfo, rows: usize) -> Result<RawData> { _ => None, }; let (Some(layout), [c]) = (layout, chunks.as_slice()) else { - let small = bits == 12 - && chunks.len() == 1 - && w.checked_mul(h).and_then(|n| n.checked_mul(3)).is_some_and(|n| u64::try_from(n).ok() == Some(chunks[0].len)); - return Err(RawError::Unsupported(if small { - "Nikon small raw (sRAW) not decoded yet".into() - } else { - "Nikon compressed NEF without a linearization table (maker note 0x96)".into() - })); + return Err(RawError::Unsupported("Nikon compressed NEF without a linearization table (maker note 0x96)".into())); }; let src = lightcraft_tiff::image::chunk_bytes(bytes, c) .filter(|src| u64::try_from(src.len()).ok() == Some(c.len)) @@ -512,6 +509,128 @@ fn packed(bytes: &[u8], info: &ImageInfo, rows: usize) -> Result<RawData> { Ok(RawData::U16(unpack_packed(src, w, rows.min(h), bits, layout))) } +/// Nikon small raw (sRAW), measured clean-room from the CC0 raw.pixls.us D810 (2036) and D4S (2227) samples. The raw SubIFD is labelled compression 34713, +/// 12 bits, one CFA sample per pixel, but it carries no linearization table (maker note `0x0096`) and its single strip +/// is exactly `3 * width * height` bytes. It holds a YCbCr 4:2:2 image of the IFD size, not a CFA mosaic (the CFA +/// tags are dummies): +/// +/// - the strip is an LSB-first 12-bit stream (`s0 = b0 | (b1 & 0x0f) << 8`, `s1 = b1 >> 4 | b2 << 4`), a row is `3 * width` +/// bytes with no padding, i.e. `2 * width` samples; +/// - the samples come in groups of four, `[Y_left, Y_right, Cb, Cr]`, for the pixel pair `(2k, 2k + 1)`: chroma is +/// halved horizontally and not vertically; +/// - luma is linear and already black-subtracted (the darkest samples are near 0) and never uses the top two bits +/// (maxima 873 and 1004 of 4095), so the white level is 1023; chroma is centred on 2048 (fitted neutral 2045-2049). +/// +/// The chroma is a camera colour-difference scale, not JFIF Cb/Cr. In linear terms the stored values behave as +/// `R - Y = R_GAIN * (Cr - 2048)` and `B - Y = B_GAIN * (Cb - 2048)` on the luma scale: regressing the camera JPEG's +/// linear `(R - Y) / Y` and `(B - Y) / Y` on `(Cr - 2048) / Y` and `(Cb - 2048) / Y` over mid-tone pixels gave slopes +/// 4.92 / 5.09 (D810, correlation 0.94 / 0.88) and 3.52 / 3.73 (D4S, 0.98 / 0.97); the gains below are the rounded +/// means. They are approximate (the two bodies differ by about 30 %), the luma is not tone-mapped, and the data is +/// treated as already white balanced (neutral D4S areas have `Cb`, `Cr` within 2 of 2048 and equal JPEG R, G, B). G +/// follows from the luma equation with the BT.601 weights. The chroma is upsampled horizontally with linear +/// interpolation, centred between the two pixels of a pair. Output is linear RGB scaled by 16 (to a 14-bit range), +/// like Sony's downsized ARWs. +const SMALL_RAW_WHITE: f32 = 1023.0; +const SMALL_RAW_SCALE: f32 = 16.0; +const SMALL_RAW_CHROMA_ZERO: f32 = 2048.0; +const SMALL_RAW_R_GAIN: f32 = 4.2; +const SMALL_RAW_B_GAIN: f32 = 4.4; + +/// The strip of a small raw: compression 34713, 12 bits, no maker note `0x0096`, one strip of exactly +/// `3 * width * height` bytes (even width). +fn small_raw_strip(info: &ImageInfo, file_len: usize, mn: Option<&makernote::MakerNote>) -> Option<lightcraft_tiff::image::Chunk> { + if info.compression != t::compression::NIKON || info.bits() != 12 || info.samples_per_pixel != 1 { + return None; + } + if mn.is_some_and(|m| m.ifd.bytes(LINEARIZATION_TABLE).is_some()) { + return None; + } + let (w, h) = (info.width as u64, info.height as u64); + let chunks = info.chunks(file_len as u64); + match chunks.as_slice() { + [c] if w.is_multiple_of(2) && w > 0 && h > 0 && w.checked_mul(h).and_then(|n| n.checked_mul(3)) == Some(c.len) => Some(*c), + _ => None, + } +} + +/// Decode one row of a small raw (`3 * width` bytes) into `3 * width` linear RGB values on the 14-bit scale. +/// Short input reads as zero bytes. +fn small_raw_row(src: &[u8], w: usize, out: &mut [u16]) { + let Some(n) = w.checked_mul(3).filter(|n| *n <= out.len() && *n <= crate::MAX_SAMPLES) else { return }; + if w == 0 || !w.is_multiple_of(2) { + return; + } + let mut s = vec![0u16; 2 * w]; + crate::unpack::unpack_lsb(&src[..src.len().min(n)], 12, &mut s); + let pairs = w / 2; + let chroma = |k: usize| { + let g = &s[4 * k + 2..4 * k + 4]; + (f32::from(g[0]) - SMALL_RAW_CHROMA_ZERO, f32::from(g[1]) - SMALL_RAW_CHROMA_ZERO) + }; + for k in 0..pairs { + let (cb, cr) = chroma(k); + for side in 0..2 { + let (nb, nr) = if side == 0 { chroma(k.saturating_sub(1)) } else { chroma((k + 1).min(pairs - 1)) }; + let (u, v) = (0.75 * cb + 0.25 * nb, 0.75 * cr + 0.25 * nr); + let y = f32::from(s[4 * k + side]); + let r = y + SMALL_RAW_R_GAIN * v; + let b = y + SMALL_RAW_B_GAIN * u; + let g = (y - 0.299 * r - 0.114 * b) / 0.587; + let dst = (2 * k + side) * 3; + for (i, value) in [r, g, b].into_iter().enumerate() { + out[dst + i] = (value * SMALL_RAW_SCALE).round().clamp(0.0, 65535.0) as u16; + } + } + } +} + +fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: lightcraft_tiff::image::Chunk, mode: Mode) -> Result<RawImage> { + use rayon::prelude::*; + let (w, h) = (info.width as usize, info.height as usize); + let stride = w.checked_mul(3).ok_or(RawError::Limit("image too large"))?; + let count = stride.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; + let src = lightcraft_tiff::image::chunk_bytes(bytes, &strip) + .filter(|src| u64::try_from(src.len()).ok() == Some(strip.len)) + .ok_or_else(|| RawError::Corrupt("NEF: incomplete image strip".into()))?; + let data = match mode { + Mode::Full => { + let mut data = vec![0u16; count]; + data.par_chunks_mut(stride).enumerate().for_each(|(y, out)| { + small_raw_row(src.get(y * stride..).unwrap_or(&[]), w, out); + }); + data + } + Mode::Header => Vec::new(), + }; + let mut metadata = lightcraft_meta::from_tiff(tiff); + metadata.width = Some(w as u32); + metadata.height = Some(h as u32); + let img = RawImage { + format: RawFormat::Nef, + width: w, + height: h, + cpp: 3, + data: RawData::U16(data), + cfa: None, + bits: 14, + black: BlackLevel::uniform(0.0), + white: vec![SMALL_RAW_WHITE * SMALL_RAW_SCALE], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::from_exif(tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION)).unwrap_or(1)), + color: ColorData::default(), + // the stored colour is already white balanced (see above) + wb_multipliers: Some([1.0; 3]), + linearized: false, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + metadata, + lens_metadata: Default::default(), + }; + img.validate_for(mode)?; + Ok(img) +} + #[cfg(test)] mod tests { use super::*; @@ -1089,9 +1208,119 @@ mod tests { // 14-bit rows must be padded to 16 bytes let d14 = samples(40 * 6, 14); assert!(matches!(decoded(strip(&d14, 40, 0, |r| pack_lsb(r, 14)), 14, 40, 6), Err(RawError::Unsupported(_)))); - // 3 bytes per IFD-width pixel is a Nikon small raw: still refused, with its own reason - let Err(RawError::Unsupported(why)) = decoded(vec![0; 3 * 40 * 6], 12, 40, 6) else { panic!("small raw decoded") }; - assert!(why.contains("sRAW"), "{why}"); + } + + /// A small raw strip of `[Y0 Y1 Cb Cr]` groups, rows of `3 * w` bytes, LSB-first 12-bit. + fn small_strip(groups: &[[u16; 4]], w: usize) -> Vec<u8> { + let flat: Vec<u16> = groups.iter().flatten().copied().collect(); + assert_eq!(flat.len() % (2 * w), 0); + flat.chunks(2 * w).flat_map(|r| pack_lsb(r, 12)).collect() + } + + fn small(strip: Vec<u8>, bits: u16, w: u32, h: u32) -> Result<RawImage> { + crate::decode(&nef(34713, bits, vec![strip], w, h, h)) + } + + #[test] + fn small_raw_422_round_trips() { + let (w, h) = (8usize, 3usize); + // flat chroma per row so the interpolation is exact; distinct luma everywhere + let mut groups = Vec::new(); + for y in 0..h { + for k in 0..w / 2 { + let (cb, cr) = (2048 + 10 * y as u16, 2048 - 5 * y as u16); + groups.push([100 + (y * w + 2 * k) as u16, 100 + (y * w + 2 * k + 1) as u16, cb, cr]); + } + } + let raw = small(small_strip(&groups, w), 12, w as u32, h as u32).unwrap(); + assert_eq!((raw.width, raw.height, raw.cpp, raw.cfa.is_none()), (w, h, 3, true)); + assert_eq!(raw.wb_multipliers, Some([1.0; 3])); + let RawData::U16(d) = &raw.data else { panic!() }; + for y in 0..h { + for x in 0..w { + let luma = (100 + y * w + x) as f32; + let (u, v) = (10.0 * y as f32, -5.0 * y as f32); + let (r, b) = (luma + SMALL_RAW_R_GAIN * v, luma + SMALL_RAW_B_GAIN * u); + let g = (luma - 0.299 * r - 0.114 * b) / 0.587; + for (i, want) in [r, g, b].into_iter().enumerate() { + let got = f32::from(d[(y * w + x) * 3 + i]) / SMALL_RAW_SCALE; + assert!((got - want).abs() < 0.1, "({x},{y}) channel {i}: {got} vs {want}"); + } + } + } + } + + #[test] + fn small_raw_neutral_chroma_is_grey_and_chroma_is_interpolated() { + let w = 8usize; + let groups: Vec<[u16; 4]> = (0..w / 2).map(|k| [200 + 40 * k as u16, 200 + 40 * k as u16, 2048, 2048]).collect(); + let raw = small(small_strip(&groups, w), 12, w as u32, 1).unwrap(); + let RawData::U16(d) = &raw.data else { panic!() }; + for x in 0..w { + let px = &d[x * 3..x * 3 + 3]; + assert!(px.iter().all(|&v| v == px[0]), "{px:?}"); + assert_eq!(f32::from(px[0]), (200 + 40 * (x / 2)) as f32 * SMALL_RAW_SCALE); + } + // a step in Cb between the first two pairs is shared 3:1 by the pixels next to the boundary + let mut groups = groups; + groups[1][2] = 2048 + 100; + let raw = small(small_strip(&groups, w), 12, w as u32, 1).unwrap(); + let RawData::U16(d) = &raw.data else { panic!() }; + let blue_minus_luma = |x: usize, luma: f32| f32::from(d[x * 3 + 2]) / SMALL_RAW_SCALE - luma; + assert!((blue_minus_luma(1, 200.0) - SMALL_RAW_B_GAIN * 25.0).abs() < 0.1); + assert!((blue_minus_luma(2, 240.0) - SMALL_RAW_B_GAIN * 75.0).abs() < 0.1); + } + + #[test] + fn small_raw_wrong_sizes_and_depths_are_refused() { + let (w, h) = (8usize, 3usize); + let good = small_strip(&vec![[100, 100, 2048, 2048]; w / 2 * h], w); + assert!(small(good.clone(), 12, w as u32, h as u32).is_ok()); + for len in [good.len() - 1, good.len() + 1] { + let mut s = good.clone(); + s.resize(len, 0); + assert!(matches!(small(s, 12, w as u32, h as u32), Err(RawError::Unsupported(_))), "len {len}"); + } + assert!(matches!(small(good.clone(), 14, w as u32, h as u32), Err(RawError::Unsupported(_)))); + // odd width: 3 bytes per pixel does not split into pixel pairs + assert!(matches!(small(vec![0; 3 * 7 * 3], 12, 7, 3), Err(RawError::Unsupported(_)))); + } + + #[test] + fn small_raw_short_input_does_not_panic() { + for len in [0, 1, 2, 3, 5, 11, 12, 13] { + let mut out = vec![0u16; 12]; + small_raw_row(&vec![0xFF; len], 4, &mut out); + } + let mut bytes = nef(34713, 12, vec![vec![0x55; 3 * 8 * 3]], 8, 3, 3); + bytes.truncate(bytes.len() - 40); + assert!(crate::decode(&bytes).is_err(), "a truncated small-raw strip is corrupt"); + } + + #[test] + fn small_raw_header_has_full_geometry_without_allocating_pixels() { + let (w, h) = (8usize, 3usize); + let bytes = nef(34713, 12, vec![small_strip(&vec![[100, 110, 2048, 2048]; w / 2 * h], w)], w as u32, h as u32, h as u32); + let header = decode(&bytes, Mode::Header).unwrap(); + let full = decode(&bytes, Mode::Full).unwrap(); + assert_eq!(header.info(), full.info()); + assert!(matches!(header.data, RawData::U16(ref samples) if samples.is_empty())); + assert!(matches!(full.data, RawData::U16(ref samples) if samples.len() == 3 * w * h)); + } + + #[test] + fn small_raw_rejects_excessive_dimensions_before_allocation() { + let bytes = nef(34713, 12, vec![vec![0; 72]], 8, 3, 3); + let tiff = Tiff::parse(&bytes).unwrap(); + let mut info = raw_ifd(&tiff).unwrap().image().unwrap(); + let strip = info.chunks(bytes.len() as u64)[0]; + info.width = u32::MAX - 1; + info.height = u32::MAX; + assert!(matches!(small_raw(&bytes, &tiff, &info, strip, Mode::Header), Err(RawError::Limit(_)))); + let mut out = [0; 12]; + small_raw_row(&[], usize::MAX, &mut out); + small_raw_row(&[], 3, &mut out); + assert_eq!(out, [0; 12]); } /// Big-endian 16-bit words holding the 12-bit samples in their upper bits. @@ -1186,4 +1415,15 @@ mod tests { } } } + + #[test] + fn small_raw_rejects_tail_truncation_with_intact_directories() { + let bytes = nef(34713, 12, vec![vec![0x55; 72]], 8, 3, 3); + for keep in [0, 24, 71] { + let short = truncated_tail_strip(bytes.clone(), keep); + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&short, mode), Err(RawError::Corrupt(_)))); + } + } + } } diff --git a/crates/raw/src/wb_estimate.rs b/crates/raw/src/wb_estimate.rs index 17a86a2a5b..13cb9f8daf 100644 --- a/crates/raw/src/wb_estimate.rs +++ b/crates/raw/src/wb_estimate.rs @@ -66,7 +66,7 @@ fn median(v: &mut [f64]) -> Option<f64> { fn from_preview(bytes: &[u8], f: &Frame) -> Option<[f32; 3]> { let jpeg = crate::preview::embedded_preview(bytes)?; - let (px, pw, ph, ch) = crate::tiffraw::lossy_jpeg(&jpeg, 3).ok()?; + let (px, pw, ph, ch) = crate::tiffraw::lossy_jpeg(&jpeg, 3, crate::tiffraw::MAX_JPEG_SAMPLES).ok()?; if ch != 3 { return None; } diff --git a/crates/raw/tests/body_corpus.rs b/crates/raw/tests/it/body_corpus.rs similarity index 100% rename from crates/raw/tests/body_corpus.rs rename to crates/raw/tests/it/body_corpus.rs diff --git a/crates/raw/tests/canon_pentax_corpus.rs b/crates/raw/tests/it/canon_pentax_corpus.rs similarity index 100% rename from crates/raw/tests/canon_pentax_corpus.rs rename to crates/raw/tests/it/canon_pentax_corpus.rs diff --git a/crates/raw/tests/corpus.rs b/crates/raw/tests/it/corpus.rs similarity index 99% rename from crates/raw/tests/corpus.rs rename to crates/raw/tests/it/corpus.rs index c9a48fb690..94d4647d6b 100644 --- a/crates/raw/tests/corpus.rs +++ b/crates/raw/tests/it/corpus.rs @@ -4,7 +4,8 @@ //! Every file must be recognised, carry an embedded JPEG preview (optional for DNG, generic CFA TIFF, //! older Panasonic RAW and HEVC-preview CR3), and either decode to a valid image or report //! `Unsupported` for one of the variants we know we don't decode yet. Prints decode times -//! (`cargo test -p lightcraft-raw --release --test corpus -- --nocapture`). +//! (`cargo test -p lightcraft-raw --release --test it corpus:: -- --nocapture --skip _corpus::`; the +//! `--skip` leaves out the other `*_corpus` modules). use lightcraft_raw::{RawError, RawFormat, decode, embedded_preview, probe, probe_info}; use std::path::{Path, PathBuf}; @@ -44,10 +45,12 @@ fn corpus_raw_decodes() { let tp = t0.elapsed().as_secs_f64() * 1e3; // DNG and generic CFA TIFF previews can be absent or uncompressed RGB; other vendor raws embed a JPEG, // except the Panasonic `.RAW` files of 2005–2007, Canon's explicit HEVC preview tracks and Mamiya MEF. + // A Hasselblad 3FR / FFF without a JPEG hands its 8-bit RGB image on as a baseline TIFF (`rgb_preview`). if let Some(p) = &preview { let jpeg = p.starts_with(&[0xff, 0xd8]) && p.ends_with(&[0xff, 0xd9]); let jxl = p.starts_with(&[0xff, 0x0a]) || p.starts_with(b"\0\0\0\x0cJXL "); - assert!(jpeg || jxl, "{name}: preview is neither a JPEG nor a JPEG XL file"); + let tiff = fmt == RawFormat::CfaTiff && p.starts_with(b"II*\0"); + assert!(jpeg || jxl || tiff, "{name}: preview is neither a JPEG, a JPEG XL nor (Hasselblad) a TIFF file"); } else { let hevc_preview = fmt == RawFormat::Cr3 && lightcraft_meta::cr3::parse_cr3(&bytes) @@ -946,7 +949,7 @@ fn corpus_samsung_srw() { #[test] fn corpus_fujifilm_compressed_samples() { use sha2::{Digest, Sha256}; - let checksums = include_str!("../../../docs/raf-corpus.sha256"); + let checksums = include_str!("../../../../docs/raf-corpus.sha256"); let cases: &[(&str, usize, usize, u64, u64)] = &[ ("raf-fuji-gfx100-3773.raf", 11808, 8754, 483668733090, 6453395759968151080), ("raf-fuji-gfx100-3775.raf", 11808, 8754, 120434414850, 6144091676930008551), @@ -1200,7 +1203,7 @@ fn sony_pins_match_the_corpus_manifest() { lines.sort(); let digest: String = Sha256::digest(lines.concat()).iter().map(|b| format!("{b:02x}")).collect(); assert_eq!(digest, SONY_PINS_SHA256, "the pinned Sony SHA-256 table changed: check every changed pin against its file, then update the anchor"); - let manifest = include_str!("../../../xtask/src/main.rs"); + let manifest = include_str!("../../../../xtask/src/main.rs"); for (name, sha) in SONY_SAMPLES { let entry = manifest.find(&format!("\"{name}\"")).unwrap_or_else(|| panic!("{name} is not in the manifest")); assert!(manifest[entry..].split_once("),").is_some_and(|(e, _)| e.contains(sha)), "{name}: pinned SHA-256 differs from the manifest"); diff --git a/crates/raw/tests/coverage_sweep_corpus.rs b/crates/raw/tests/it/coverage_sweep_corpus.rs similarity index 97% rename from crates/raw/tests/coverage_sweep_corpus.rs rename to crates/raw/tests/it/coverage_sweep_corpus.rs index 78f3846514..5aabe53650 100644 --- a/crates/raw/tests/coverage_sweep_corpus.rs +++ b/crates/raw/tests/it/coverage_sweep_corpus.rs @@ -10,7 +10,7 @@ use lightcraft_raw::{RawData, decode, probe_info}; use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; -const RECORDS: &str = include_str!("../../../docs/raw/coverage-sweep.tsv"); +const RECORDS: &str = include_str!("../../../../docs/raw/coverage-sweep.tsv"); #[test] fn coverage_sweep_sensor_decodes_are_pinned() { diff --git a/crates/raw/tests/cr3_corpus.rs b/crates/raw/tests/it/cr3_corpus.rs similarity index 100% rename from crates/raw/tests/cr3_corpus.rs rename to crates/raw/tests/it/cr3_corpus.rs diff --git a/crates/raw/tests/cr3_variants.rs b/crates/raw/tests/it/cr3_variants.rs similarity index 100% rename from crates/raw/tests/cr3_variants.rs rename to crates/raw/tests/it/cr3_variants.rs diff --git a/crates/raw/tests/crx_properties.rs b/crates/raw/tests/it/crx_properties.rs similarity index 100% rename from crates/raw/tests/crx_properties.rs rename to crates/raw/tests/it/crx_properties.rs diff --git a/crates/raw/tests/dng.rs b/crates/raw/tests/it/dng.rs similarity index 100% rename from crates/raw/tests/dng.rs rename to crates/raw/tests/it/dng.rs diff --git a/crates/raw/tests/lossy_dng.rs b/crates/raw/tests/it/lossy_dng.rs similarity index 100% rename from crates/raw/tests/lossy_dng.rs rename to crates/raw/tests/it/lossy_dng.rs diff --git a/crates/raw/tests/it/main.rs b/crates/raw/tests/it/main.rs new file mode 100644 index 0000000000..8834ed0f0c --- /dev/null +++ b/crates/raw/tests/it/main.rs @@ -0,0 +1,20 @@ +//! The integration tests, one module per file, linked into one test binary. +//! `tests/sr2_heap.rs` stays a binary of its own: it installs dhat as the global allocator. + +mod body_corpus; +mod canon_pentax_corpus; +mod corpus; +mod coverage_sweep_corpus; +mod cr3_corpus; +mod cr3_variants; +mod crx_properties; +mod dng; +mod lossy_dng; +mod nrw_be16; +mod olympus_samsung_corpus; +mod rendered_dng; +mod robust; +mod sony_leica_corpus; +mod sony_lens_inventory; +mod sparse_corpus; +mod vendor_robust; diff --git a/crates/raw/tests/nrw_be16.rs b/crates/raw/tests/it/nrw_be16.rs similarity index 100% rename from crates/raw/tests/nrw_be16.rs rename to crates/raw/tests/it/nrw_be16.rs diff --git a/crates/raw/tests/olympus_samsung_corpus.rs b/crates/raw/tests/it/olympus_samsung_corpus.rs similarity index 100% rename from crates/raw/tests/olympus_samsung_corpus.rs rename to crates/raw/tests/it/olympus_samsung_corpus.rs diff --git a/crates/raw/tests/rendered_dng.rs b/crates/raw/tests/it/rendered_dng.rs similarity index 100% rename from crates/raw/tests/rendered_dng.rs rename to crates/raw/tests/it/rendered_dng.rs diff --git a/crates/raw/tests/robust.proptest-regressions b/crates/raw/tests/it/robust.proptest-regressions similarity index 100% rename from crates/raw/tests/robust.proptest-regressions rename to crates/raw/tests/it/robust.proptest-regressions diff --git a/crates/raw/tests/robust.rs b/crates/raw/tests/it/robust.rs similarity index 100% rename from crates/raw/tests/robust.rs rename to crates/raw/tests/it/robust.rs diff --git a/crates/raw/tests/sony_leica_corpus.rs b/crates/raw/tests/it/sony_leica_corpus.rs similarity index 100% rename from crates/raw/tests/sony_leica_corpus.rs rename to crates/raw/tests/it/sony_leica_corpus.rs diff --git a/crates/raw/tests/sony_lens_inventory.rs b/crates/raw/tests/it/sony_lens_inventory.rs similarity index 100% rename from crates/raw/tests/sony_lens_inventory.rs rename to crates/raw/tests/it/sony_lens_inventory.rs diff --git a/crates/raw/tests/sparse_corpus.rs b/crates/raw/tests/it/sparse_corpus.rs similarity index 99% rename from crates/raw/tests/sparse_corpus.rs rename to crates/raw/tests/it/sparse_corpus.rs index a602dd1489..7f50d935df 100644 --- a/crates/raw/tests/sparse_corpus.rs +++ b/crates/raw/tests/it/sparse_corpus.rs @@ -5,7 +5,7 @@ //! For every file the plan reaches `Ready` on, probing the partly loaded buffer must give exactly //! what probing the whole file gives — with the skipped bytes zero and again with them 0xFF, so a //! reader that looked at skipped data would be caught. CR3 and DNG files must be described from a -//! small part of the file (`cargo test -p lightcraft-raw --release --test sparse_corpus -- --nocapture` +//! small part of the file (`cargo test -p lightcraft-raw --release --test it sparse_corpus:: -- --nocapture` //! prints what each format reads). use lightcraft_raw::sparse::{HeaderPlan, Ranges, header_plan, preview_plan}; diff --git a/crates/raw/tests/vendor_robust.rs b/crates/raw/tests/it/vendor_robust.rs similarity index 100% rename from crates/raw/tests/vendor_robust.rs rename to crates/raw/tests/it/vendor_robust.rs diff --git a/crates/segment/tests/it/main.rs b/crates/segment/tests/it/main.rs new file mode 100644 index 0000000000..4dcb685916 --- /dev/null +++ b/crates/segment/tests/it/main.rs @@ -0,0 +1,4 @@ +//! The integration tests, one module per file, linked into one test binary. + +mod reference; +mod remote; diff --git a/crates/segment/tests/reference.rs b/crates/segment/tests/it/reference.rs similarity index 100% rename from crates/segment/tests/reference.rs rename to crates/segment/tests/it/reference.rs diff --git a/crates/segment/tests/remote.rs b/crates/segment/tests/it/remote.rs similarity index 100% rename from crates/segment/tests/remote.rs rename to crates/segment/tests/it/remote.rs diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 7a2322245f..1715dee943 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -16,7 +16,7 @@ //! //! It prints the note to stderr as before and, when the [`SKIP_LOG_ENV`] variable names a file //! (`cargo xtask ci` sets it), appends one JSON line there: -//! `{"need":"gpu","reason":"no GPU adapter","test":"camera_tone","binary":"equivalence","location":"crates/gpu/tests/equivalence.rs:22"}`. +//! `{"need":"gpu","reason":"no GPU adapter","test":"equivalence::camera_tone","binary":"it","location":"crates/gpu/tests/it/equivalence.rs:22"}`. //! `cargo xtask ci` lists the skips by need and reason in its summary and in //! `target/ci/report.json`. A test that runs part of its checks (e.g. only the CPU half) records //! the part it could not run the same way. @@ -142,13 +142,13 @@ mod tests { #[test] fn an_entry_is_one_json_line_with_its_text_escaped() { - let line = entry(Need::Corpus, "skip: C:\\corpus\\raw \"absent\"\n\u{1}", "corpus::decodes", "corpus", "crates\\raw\\tests\\corpus.rs", 28); + let line = entry(Need::Corpus, "skip: C:\\corpus\\raw \"absent\"\n\u{1}", "corpus::decodes", "it", "crates\\raw\\tests\\it\\corpus.rs", 28); assert!(line.ends_with('\n')); assert_eq!(line.matches('\n').count(), 1, "{line}"); assert_eq!( line, "{\"need\":\"corpus\",\"reason\":\"skip: C:\\\\corpus\\\\raw \\\"absent\\\"\\n\\u0001\",\"test\":\"corpus::decodes\",\ - \"binary\":\"corpus\",\"location\":\"crates/raw/tests/corpus.rs:28\"}\n" + \"binary\":\"it\",\"location\":\"crates/raw/tests/it/corpus.rs:28\"}\n" ); } @@ -164,10 +164,14 @@ mod tests { #[test] fn appended_lines_accumulate() { + // Exclusive, private: the pid-derived name in a shared /tmp can be planted by another account + // (CWE-59), so an existing directory fails the test instead of it symlinking inside. let dir = std::env::temp_dir().join(format!("lightcraft-testkit-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir(&dir).unwrap(); let log = dir.join("skips.jsonl"); - let _ = std::fs::remove_file(&log); + if std::fs::symlink_metadata(&log).is_ok() { + std::fs::remove_file(&log).unwrap(); + } let threads: Vec<_> = (0..8) .map(|i| { let log = log.clone(); diff --git a/crates/tiff/src/image.rs b/crates/tiff/src/image.rs index ca3ff8b690..16e24f3676 100644 --- a/crates/tiff/src/image.rs +++ b/crates/tiff/src/image.rs @@ -118,14 +118,34 @@ impl ImageInfo { } } - /// All chunks that have an offset. Missing byte counts are inferred as "to the next offset / end of data" - /// using `data_len`. - pub fn chunks(&self, data_len: u64) -> Vec<Chunk> { + /// The chunk count the image declares (offsets present, cut to the layout's plane capacity) with the + /// geometry `chunks` needs to place each one. No descriptors are built, so a pathological strip array + /// costs it a length check. + fn chunk_grid(&self) -> (usize, u32, usize) { let (across, down) = self.grid(); let per_plane = across as usize * down as usize; let planes = if self.planar == 2 { self.samples_per_pixel as usize } else { 1 }; + (self.offsets.len().min(per_plane.saturating_mul(planes)), across, per_plane) + } + + fn declared_chunk_count(&self) -> usize { + self.chunk_grid().0 + } + + /// The one chunk when the image has exactly one, else `None` — and no descriptor vector beyond it. Preview + /// extraction only serves single-chunk images, so it asks here before serving a hostile multi-strip layout. + pub fn single_chunk(&self, data_len: u64) -> Option<Chunk> { + if self.declared_chunk_count() != 1 { + return None; + } + self.chunks(data_len).into_iter().next() + } + + /// All chunks that have an offset. Missing byte counts are inferred as "to the next offset / end of data" + /// using `data_len`. + pub fn chunks(&self, data_len: u64) -> Vec<Chunk> { + let (n, across, per_plane) = self.chunk_grid(); let (cw, ch) = self.chunk_size(); - let n = self.offsets.len().min(per_plane.saturating_mul(planes)); let mut out = Vec::with_capacity(n); // the distinct offsets in order, for chunks without a byte count (sorted once, not scanned per chunk) let mut sorted: Vec<u64> = Vec::new(); @@ -192,6 +212,18 @@ mod tests { } } + /// One offset is one chunk, and `single_chunk` refuses to build descriptors when the image declares more. + #[test] + fn single_chunk_is_the_only_chunk() { + let one = strips(vec![50], vec![10]); + assert_eq!(one.single_chunk(100).map(|c| (c.index, c.offset, c.len)), one.chunks(100).first().map(|c| (c.index, c.offset, c.len))); + // the inferred length matches too, and never falls back past the data + let inferred = strips(vec![70], vec![]); + assert_eq!(inferred.single_chunk(100).map(|c| c.len), Some(30)); + assert!(strips(vec![50, 10], vec![10, 5]).single_chunk(100).is_none(), "a multi-chunk image has no single chunk"); + assert!(strips(Vec::new(), Vec::new()).single_chunk(100).is_none()); + } + #[test] fn missing_byte_counts_run_to_the_next_larger_offset() { let info = strips(vec![50, 10, 30, 10, 70], vec![0, 0, 5]); diff --git a/crates/tiff/src/makernote.rs b/crates/tiff/src/makernote.rs index 7ed5e1997c..288b366f64 100644 --- a/crates/tiff/src/makernote.rs +++ b/crates/tiff/src/makernote.rs @@ -55,7 +55,11 @@ pub fn parse_makernote(data: &[u8], offset: u64, len: u64, order: ByteOrder, mak Some(b"MM") => Some(ByteOrder::Big), _ => None, }; - let opts = ParseOptions { max_ifds: 64, max_depth: 3, ..Default::default() }; + // A fixed value budget: a maker note is at most tens of kilobytes of values in any honest file, and + // computing the budget from the buffer's length multiplies the file length (a hostile entry in a + // sparse header-read buffer, where the buffer holds the file's logical size but only a few + // kilobytes are loaded, would decode allocations no actual data backs). + let opts = ParseOptions { max_ifds: 64, max_depth: 3, value_budget: Some(1 << 20), ..Default::default() }; let try_parse = |kind: MakerNoteKind, ifd_at: u64, base: u64, ord: ByteOrder| -> Option<MakerNote> { let (ifd, _) = parse_ifd_at(data, ifd_at, ord, base, false, &opts).ok()?; (!ifd.entries.is_empty()).then_some(MakerNote { kind, order: ord, base, ifd }) @@ -192,6 +196,35 @@ mod tests { assert_eq!(m.ifd.u64s(2).unwrap(), vec![9, 0]); } + /// A maker note's value budget is fixed, not computed from the length of the buffer it sits in: + /// an entry claiming more than the note budget (here 2 MB) is dropped, a fitting one is read. In a + /// sparse header read the buffer holds the file's logical size while only kilobytes were loaded, + /// so a length-scaled budget would let an unrelated entry decode megabytes of zeros (see the focus + /// reader, try_read_exif_with). + #[test] + fn a_note_entry_past_the_fixed_value_budget_is_dropped() { + let order = ByteOrder::Little; + let mut note = b"SONY DSC \0\0\0".to_vec(); + // the Sony IFD directly after the 12-byte header, one fitting BYTE entry and a decoy + // BYTE[2 MB] entry pointing into the file's own (zero-filled) body + order.put_u16(&mut note, 2); + order.put_u16(&mut note, 0x201b); + order.put_u16(&mut note, 1); + order.put_u32(&mut note, 1); + note.extend([3, 0, 0, 0]); + order.put_u16(&mut note, 0x9900); + order.put_u16(&mut note, 1); + order.put_u32(&mut note, 2 << 20); + order.put_u32(&mut note, 200); + order.put_u32(&mut note, 0); + let mut bytes = note.clone(); + bytes.resize(200 + (2 << 20), 0); // the decoy's value range is inside the real bytes + let m = parse_makernote(&bytes, 0, note.len() as u64, order, "SONY").unwrap(); + assert_eq!(m.kind, MakerNoteKind::Sony); + assert!(m.ifd.get(0x201b).is_some(), "the fitting entry is read"); + assert!(m.ifd.get(0x9900).is_none(), "the decoy is dropped by the value budget"); + } + #[test] fn garbage_note_is_none() { let (bytes, off, len) = with_note(ByteOrder::Little, vec![0xff; 40]); diff --git a/crates/tiff/src/reader.rs b/crates/tiff/src/reader.rs index bd728ca9c8..70c66c5a74 100644 --- a/crates/tiff/src/reader.rs +++ b/crates/tiff/src/reader.rs @@ -338,6 +338,25 @@ pub fn decode(o: ByteOrder, typ: FieldType, b: &[u8]) -> Value { #[cfg(test)] mod tests { use super::*; + use crate::Value; + use crate::tags as t; + use crate::writer::{IfdBuilder, TiffWriter}; + + /// A value budget the caller sets bounds what is decoded: an entry claiming more value bytes than + /// the budget allows is dropped, entries that fit are read (the sparse header-read path, where the + /// buffer holds the file's logical size but only a few kilobytes were ever loaded, sizes its + /// budget from what was fetched, not from whatever length the file claims). + #[test] + fn the_value_budget_drops_over_budget_entries_and_keeps_the_rest() { + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Keep".into())); + ifd0.set(0x9000, Value::Byte(vec![0; 2 << 20])); + let file = TiffWriter { order: ByteOrder::Little, bigtiff: false }.write(&[ifd0]).unwrap(); + let opts = ParseOptions { value_budget: Some(1 << 20), ..Default::default() }; + let tiff = Tiff::parse_with(&file, &opts).unwrap(); + assert_eq!(tiff.ifds[0].string(t::MAKE), Some("Keep".to_string()), "a fitting entry is read"); + assert!(tiff.ifds[0].get(0x9000).is_none(), "the over-budget entry is dropped"); + } /// A BigTIFF whose first IFD, at 80, declares `declared` entries but holds one, followed by a next-IFD pointer /// `next`; a valid one-entry IFD sits at 16. diff --git a/crates/tiff/tests/it/main.rs b/crates/tiff/tests/it/main.rs new file mode 100644 index 0000000000..e415ed5377 --- /dev/null +++ b/crates/tiff/tests/it/main.rs @@ -0,0 +1,3 @@ +//! The integration tests, one module per file, linked into one test binary. + +mod roundtrip; diff --git a/crates/tiff/tests/roundtrip.rs b/crates/tiff/tests/it/roundtrip.rs similarity index 100% rename from crates/tiff/tests/roundtrip.rs rename to crates/tiff/tests/it/roundtrip.rs diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 1ae33a03d7..8dab2b9676 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -2,7 +2,7 @@ name = "lightcraft-ui-egui" version.workspace = true edition.workspace = true -rust-version = "1.95" +rust-version.workspace = true license.workspace = true description = "LightCraft egui frontend (Lightroom-style UI); swappable — nothing below depends on it (L5)" @@ -30,6 +30,11 @@ log = { workspace = true } [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } +# The model-setup tests install and resume a real denoise model. Without this the engine's +# `default_loader` is the "this build cannot run denoise models" stub when the package is tested +# on its own (`cargo test -p lightcraft-ui-egui`); a workspace test only passed by feature +# unification with the desktop app's default `denoise` feature. +lightcraft-engine = { workspace = true, features = ["denoise"] } egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } lightcraft-denoise = { workspace = true, features = ["runtime"] } lightcraft-codecs = { workspace = true } @@ -39,3 +44,6 @@ lightcraft-merge = { workspace = true } [build-dependencies] serde_json = { workspace = true } toml = "1" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft-update = { workspace = true } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 0d0f9a3a41..9d8300e8e9 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -7,9 +7,9 @@ //! `{:+}`… keep their meaning). The English source is the fallback arm. Adding a language means //! adding its file (and its `language_table!` entry); this script picks the file up by name. //! -//! Every catalog must carry the same messages: a `tr_format!` call whose message is in no catalog -//! does not compile, so a message missing from one language would otherwise go unnoticed until it -//! shows English. +//! A message a language lacks (or translates as an empty string) shows the English source: that +//! language has no arm for it, and a message no catalog has formats the English source through the +//! macro's last arm. `i18n::tests::translation_gaps_report` lists the gaps per language. //! //! It also bakes the contributor credits into the binary as static Rust tables (`$OUT_DIR/credits.rs`, //! included by `src/credits.rs`; craftrules `standards/contributors.md`): commit stats from @@ -61,25 +61,14 @@ fn generate() -> Result<String, Box<dyn std::error::Error>> { let Some(code) = name.strip_suffix("-formats.json").filter(|code| *code != "en") else { continue }; println!("cargo:rerun-if-changed=locales/{name}"); let variant = variant_for(code)?; - let messages: BTreeMap<String, String> = + let mut messages: BTreeMap<String, String> = serde_json::from_str(&fs::read_to_string(&path)?).map_err(|error| format!("locales/{name}: {error}"))?; + messages.retain(|_, translated| !translated.is_empty()); catalogs.push((code.to_string(), variant, messages)); } catalogs.sort_by(|a, b| a.0.cmp(&b.0)); - // Every catalog translates the same messages. let all: BTreeSet<&String> = catalogs.iter().flat_map(|(_, _, messages)| messages.keys()).collect(); - let mut problems = Vec::new(); - for (code, _, messages) in &catalogs { - for key in &all { - if !messages.contains_key(*key) { - problems.push(format!("locales/{code}-formats.json is missing {key:?}")); - } - } - } - if !problems.is_empty() { - return Err(problems.join("\n").into()); - } let mut source = String::from(concat!( "/// Translate a format string, checked by `format!` in every language.\n", @@ -98,6 +87,9 @@ fn generate() -> Result<String, Box<dyn std::error::Error>> { source.push_str(&format!(" _ => format!({en} $(, $($args)*)?),\n }}\n }};\n")); } source.push_str(concat!( + " ($english:literal $(, $($args:tt)*)?) => {\n", + " format!($english $(, $($args)*)?)\n", + " };\n", "}\n", "\n", "// `macro_rules!` is textual: the module re-export is what lets call sites say\n", diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 675c920d52..166c0e9b62 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -283,6 +283,7 @@ fn real() { unit: egui::MouseWheelUnit::Point, delta: egui::vec2(0.0, if (i / 45) % 2 == 0 { -12.0 } else { 12.0 }), phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, modifiers: Default::default(), }); let t = Instant::now(); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 8a50d38f10..1eb882f09d 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -253,6 +253,7 @@ "new, inside {parent}": "nové, pod {parent}", "Keywords of {n} selected photos": "Klíčová slova vybraných fotografií (počet: {n})", "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Klíčové slovo „{name}“ bylo odebráno z fotografií v počtu {n}. Úpravy → Zpět jej vrátí.", + "Inside: {names}": "Uvnitř: {names}", " in {g} group{}": " ve skupinách: {g}{:.0}", " · kept, not applied: {}": " · zachováno, nepoužito: {}", " — kept but not applied: {}": " — zachováno, ale nepoužito: {}", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Procházení složek – složky: {folders}, soubory: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí.", + "Drop to review {n} item{} for import": "Pusťte pro kontrolu před importem (položek: {n}){:.0}", + "Drop to import {n} item{}": "Pusťte pro import (položek: {n}){:.0}", + "Drop to import {n} preset{}": "Pusťte pro import přednastavení: {n}{:.0}", + "Could not read {name}: {e}": "Soubor {name} se nepodařilo přečíst: {e}", + "Added {n} photo{}": "Přidáno fotografií: {n}{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", + "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index e3a98569fd..52ca94a524 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -47,6 +47,7 @@ "Add in place": "Přidat ze současného umístění", "Add in place: the library references the files where they are; nothing is copied or moved.": "Přidat ze současného umístění: knihovna odkazuje na soubory tam, kde jsou; nic se nekopíruje ani nepřesouvá.", "Add keyword": "Přidat klíčové slovo", + "Add Keywords": "Přidat klíčová slova", "Add number": "Přidat číslo", "Add to": "Přidat do", "Add to Album": "Přidat do alba", @@ -374,7 +375,6 @@ "Clear Filters": "Zrušit filtry", "Clear Guides": "Vymazat vodítka", "Clear History": "Vymazat historii", - "Clear Preview Cache": "Vymazat mezipaměť náhledů", "Clear Quick Collection": "Vyprázdnit rychlou kolekci", "Clear Recent Libraries": "Vymazat nedávné knihovny", "Clear Reference": "Zrušit referenční fotografii", @@ -425,7 +425,6 @@ "Company": "Společnost", "Compare": "Porovnat", "Compare (Shift+C)": "Porovnat (Shift+C)", - "Compare Before and After": "Porovnat před a po", "Compare needs at least two photos": "Porovnání vyžaduje alespoň dvě fotografie", "Component options": "Možnosti součásti", "Compression": "Komprese", @@ -1195,6 +1194,7 @@ "New time": "Nový čas", "New…": "Nový…", "Next Appearance Mode": "Další režim vzhledu", + "Next Keyword Set": "Další sada klíčových slov", "Next Photo": "Další fotografie", "Next up for AI Denoise…": "Další na řadě pro redukci šumu pomocí AI…", "Night Blue": "Noční modř", @@ -1404,6 +1404,7 @@ "Preview size": "Velikost náhledu", "Preview unavailable": "Náhled není dostupný", "Previews": "Náhledy", + "Previous Keyword Set": "Předchozí sada klíčových slov", "Previous Photo": "Předchozí fotografie", "Primaries (x, y)": "Primární barvy (x, y)", "Print": "Tisk", @@ -1585,7 +1586,6 @@ "Reset all edits (Cmd+Shift+R)": "Obnovit všechny úpravy (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Inteligentní alba se aktualizují automaticky: změňte jejich pravidla nebo použijte Fotografie → Odstranit fotografii", "LightCraft stopped": "LightCraft se neočekávaně ukončil", - "Show Focus Point": "Zobrazit zaostřovací bod", "Zoom to Focus Point": "Přiblížit na zaostřovací bod", "Focus": "Zaostření", "Focus point": "Zaostřovací bod", @@ -1754,18 +1754,13 @@ "Short Edge": "Kratší hrana", "Show": "Zobrazit", "Show All": "Zobrazit vše", - "Show Clipping": "Zobrazit ořezání tónů", "Show Deghost Overlay": "Zobrazit překrytí odstranění duchů", "Show Hidden Local Locations": "Zobrazit skrytá místní umístění", "Show Luminance Map": "Zobrazit mapu jasu", "Show Mask": "Zobrazit masku", - "Show Mask Overlay": "Zobrazit překrytí masky", - "Show All Mask Overlays": "Zobrazit všechna překrytí masek", "Show all overlays": "Zobrazit všechna překrytí", - "Show Mask Pins": "Zobrazit body masek", "Show Original": "Zobrazit originál", "Show Person": "Zobrazit osobu", - "Show Photo Counts": "Zobrazit počty fotografií", "Show Photos with Keyword": "Zobrazit fotografie s klíčovým slovem", "Show Pins": "Zobrazit body", "Show Sidebar Section": "Zobrazit sekci postranního panelu", @@ -2394,5 +2389,24 @@ "End Slideshow": "Ukončit prezentaci", "Save Current Settings as New Effect Preset…": "Uložit aktuální nastavení jako nové přednastavení efektu…", "Manage Effect Presets…": "Spravovat přednastavení efektů…", - "Export Effect Presets…": "Exportovat přednastavení efektů…" + "Export Effect Presets…": "Exportovat přednastavení efektů…", + "Before/After Side by Side": "Před/Po vedle sebe", + "Clipping": "Ořezání tónů", + "Mask Overlay": "Překrytí masky", + "All Mask Overlays": "Všechna překrytí masek", + "Mask Pins": "Body masek", + "Photo Counts": "Počty fotografií", + "Focus Point": "Bod zaostření", + "Layout Image": "Obrázek rozvržení", + "Detail View": "Zobrazení detailu", + "Edit Panel": "Panel Úpravy", + "Close the open dialog, then drop the files again": "Zavřete otevřené okno, pak soubory pusťte znovu", + "Close the open dialog to drop files here": "Zavřete otevřené okno, aby sem šlo soubory pustit", + "Drop to open the face model": "Pusťte pro otevření modelu obličejů", + "Drop to import": "Pusťte pro import", + "Dropped Files": "Přetažené soubory", + "Import dropped files without review": "Importovat přetažené soubory bez kontroly", + "An import is running": "Import už běží", + "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", + "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index af29f7134e..79390f1364 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -10,7 +10,7 @@ " · {} not readable": " · {} nicht lesbar", " · {} original{} left at the source": " · Originale an der Quelle verblieben: {}{:.0}", " · {} restored from Recently Deleted": " · {} aus „Zuletzt gelöscht“ wiederhergestellt", - " — not carried over: {}{}": " — nicht übernommen: {}{}", + " — not carried over: {}{}": " – nicht übernommen: {}{}", "+{} more": "+{} weitere", ", {failed} file{} not readable": ", nicht lesbare Dateien: {failed}{:.0}", "; {kept} already had a location": "; bereits verortet: {kept}", @@ -54,7 +54,7 @@ "Exported {} point curve preset{}": "Exportierte Punktkurvenvorgaben: {}{:.0}", "Exported {} preset{}": "Exportierte Vorgaben: {}{:.0}", "Exporting {} of {total}": "{} von {total} wird exportiert", - "Filter bar — {active} active filter{}": "Filterleiste — aktive Filter: {active}{:.0}", + "Filter bar — {active} active filter{}": "Filterleiste – aktive Filter: {active}{:.0}", "Focus {:.0}": "Schärfe {:.0}", "Folder “{}” (and its subfolders)": "Ordner „{}“ (und seine Unterordner)", "Found {n} missing photo{}; {left} still missing{unsure}": "Gefundene fehlende Fotos: {n}{:.0}; weiterhin fehlend: {left}{unsure}", @@ -63,11 +63,11 @@ "Import failed: {e}": "Import fehlgeschlagen: {e}", "Import warnings ({n}):\n{warnings}": "Importwarnungen ({n}):\n{warnings}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Die XMP-Begleitdateien von {n} Fotos konnten nicht geschrieben werden (ist ihr Ordner offline?). LightCraft versucht es weiter.", - "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "XMP-Profil \"{profile}\" wurde für {path} nicht angewendet; Farben können von Lightroom abweichen.", + "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "XMP-Profil „{profile}“ wurde für {path} nicht angewendet; Farben können von Lightroom abweichen.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Lightroom-Geometrie wurde für {path} nicht beibehalten; {mode} wird neu berechnet.", - "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "Lightroom-Geometrie für {path} wurde nicht beibehalten; gespeicherte Transformation wird ignoriert, weil Upright deaktiviert ist.", - "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "Lightroom-Geometrie für {path} wurde nicht beibehalten; gespeicherte Guided-Upright-Transformation wird nicht unterstützt.", - "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "Lightroom-Geometrie für {path} wurde nicht beibehalten; gespeicherte Upright-Transformation wird nicht unterstützt.", + "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "Lightroom-Geometrie für {path} wurde nicht beibehalten; gespeicherte Transformation wird ignoriert, weil die Perspektivkorrektur aus ist.", + "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "Lightroom-Geometrie für {path} wurde nicht beibehalten; gespeicherte Perspektivkorrektur mit Hilfslinien wird nicht unterstützt.", + "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "Lightroom-Geometrie für {path} wurde nicht beibehalten; gespeicherte Perspektivkorrektur wird nicht unterstützt.", "XMP adjustments were not imported for {path}: {fields}.": "XMP-Anpassungen wurden für {path} nicht importiert: {fields}.", "Imported {n} point curve preset{}": "Importierte Punktkurvenvorgaben: {n}{:.0}", "Imported {n} preset{}": "Importierte Vorgaben: {n}{:.0}", @@ -90,10 +90,10 @@ "Move {what} to Recently Deleted?": "{what} nach „Zuletzt gelöscht“ verschieben?", "Named ({named_n})": "Benannt ({named_n})", "Painting “{k}”: click photos to add or remove it · Esc stops": "„{k}“ auftragen: Fotos anklicken, um es hinzuzufügen oder zu entfernen · Esc beendet", - "Paste into {n} photo{} — only settings that were copied are pasted": "In {n} Foto{} einfügen — nur kopierte Einstellungen werden eingefügt", + "Paste into {n} photo{} — only settings that were copied are pasted": "In {n} Foto{} einfügen – nur kopierte Einstellungen werden eingefügt", "Preset: {name}": "Vorgabe: {name}", - "Preview only — editing the camera's embedded JPEG ({})": "Nur Vorschau — das eingebettete Kamera-JPEG wird bearbeitet ({})", - "Preview only — {}": "Nur Vorschau — {}", + "Preview only — editing the camera's embedded JPEG ({})": "Nur Vorschau – das eingebettete Kamera-JPEG wird bearbeitet ({})", + "Preview only — {}": "Nur Vorschau – {}", "Previews ready for {done} photo{plural}": "Vorschauen für {done} Foto{plural} fertig", "Profile: {}": "Profil: {}", "Proof Copy ({})": "Softproof-Kopie ({})", @@ -101,7 +101,7 @@ "Quick Develop · {n} photos": "Schnellentwicklung · {n} Fotos", "Quick Develop: {name}": "Schnellentwicklung: {name}", "Rated {}": "Bewertet mit {}", - "Reading Lightroom catalog… {done} of {total}": "Lightroom-Katalog wird gelesen … {done} von {total}", + "Reading Lightroom catalog… {done} of {total}": "Lightroom-Katalog wird gelesen… {done} von {total}", "Reading photos… {done} of {total}": "Fotos werden gelesen… {done} von {total}", "Reading photos… {} of {}": "Fotos werden gelesen… {} von {}", "Redo {}": "Wiederholen: {}", @@ -129,7 +129,7 @@ "Undo {}": "Rückgängig: {}", "Unknown tag{s} {} stay{} as typed (see Tags)": "Unbekannte Platzhalter{s:.0} {} bleiben unverändert{:.0} (siehe „Platzhalter“)", "Updated “{name}”": "„{name}“ aktualisiert", - "Version {} — a clean-room, pure-Rust photo library and raw developer.": "Version {} — eine unabhängig entwickelte Fotobibliothek und RAW-Entwicklung in reinem Rust.", + "Version {} — a clean-room, pure-Rust photo library and raw developer.": "Version {} – eine unabhängig entwickelte Fotobibliothek und RAW-Entwicklung in reinem Rust.", "Version: {}": "Version: {}", "Virtual copy “{name}” of {of}": "Virtuelle Kopie „{name}“ von {of}", "Working on {what} for {} photos…": "{what} für {} Fotos wird verarbeitet…", @@ -153,16 +153,16 @@ "{name} Off": "{name} aus", "{name} On": "{name} ein", "{name} opened for editing; it is stacked with the original": "{name} zum Bearbeiten geöffnet; mit dem Original gestapelt", - "{name} — double-click to reset it": "{name} — zum Zurücksetzen doppelklicken", - "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Nicht auf den Datenträger geschriebene Änderungen: {n}{0:.0}: {e}\nWenn du jetzt beendest, gehen diese Änderungen verloren.{1:.0}", - "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Ungespeicherte Änderungen: {n}{0:.0} im Arbeitsspeicher, aber nicht auf dem Datenträger: {e}\nLightCraft versucht es automatisch erneut; beim Beenden gingen diese Änderungen verloren.{1:.0}", - "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Änderungen nur im Arbeitsspeicher gespeichert: {n}{:.0}: {e} — LightCraft versucht es erneut", + "{name} — double-click to reset it": "{name} – zum Zurücksetzen doppelklicken", + "{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "{n} Änderung(en) konnten nicht auf den Datenträger geschrieben werden{0:.0}: {e}\nWenn du jetzt beendest, gehen sie verloren.{1:.0}", + "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} Änderung(en) nur im Arbeitsspeicher, nicht auf dem Datenträger gespeichert{0:.0}: {e}\nLightCraft versucht es automatisch erneut; wenn du jetzt beendest, gehen sie verloren.{1:.0}", + "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "{n} Änderung(en) nur im Arbeitsspeicher gespeichert{:.0}: {e} – LightCraft versucht es erneut", "{n} found · {sel} selected": "{n} gefunden · {sel} ausgewählt", "{n} photos": "Fotos: {n}", - "{n} photos in {} are hidden by the filters above": "Ausgeblendete Fotos in {}: {n} (durch die obigen Filter)", + "{n} photos in {} are hidden by the filters above": "{n} Fotos in {} werden durch die obigen Filter ausgeblendet", "{n} photo{}": "{n} Foto{}", "{n} photo{} match · updates automatically as photos change": "Passende Fotos: {n}{:.0} · wird bei Änderungen an Fotos automatisch aktualisiert", - "{n} photo{} now · updates automatically as photos change": "Aktuelle Fotos: {n}{:.0} · wird bei Änderungen an Fotos automatisch aktualisiert", + "{n} photo{} now · updates automatically as photos change": "Derzeit {n} Foto{} · wird bei Änderungen an Fotos automatisch aktualisiert", "{n} selected photos · {pages} pages": "{n} ausgewählte Fotos · {pages} Seiten", "{pid} (missing)": "{pid} (fehlt)", "{sel_n} selected · {counted}": "{sel_n} ausgewählt · {counted}", @@ -180,7 +180,7 @@ "{} files": "{} Dateien", "{} files and {f} folder{}": "{} Dateien und {f} Ordner{:.0}", "{} item{}": "Elemente: {}{:.0}", - "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} von 4 Hilfslinien — entlang von Linien ziehen, die senkrecht oder waagerecht sein sollen.", + "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} von 4 Hilfslinien – entlang von Linien ziehen, die senkrecht oder waagerecht sein sollen.", "{} photos": "Fotos: {}", "{} photos · exposures {} EV": "{} Fotos · Belichtungen {} EV", "{} photos · {} · {:.0}° × {:.0}°": "{} Fotos · {} · {:.0}° × {:.0}°", @@ -188,7 +188,7 @@ "{} sample{}": "Farbproben: {}{:.0}", "{} sec": "{} s", "{} spot(s) on this photo": "{} Retuschierstelle(n) in diesem Foto", - "{} — show their photos": "{} — Fotos dieser Person anzeigen", + "{} — show their photos": "{} – Fotos dieser Person anzeigen", "· {dups} already in the library": "· {dups} bereits in der Bibliothek", "· {n} photo{}": "· {n} Foto{}", "· {trashed} in Recently Deleted": "· {trashed} in „Zuletzt gelöscht“", @@ -196,17 +196,17 @@ "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft kann diese RAW-Variante noch nicht dekodieren ({}). Du bearbeitest die eingebettete JPEG-Vorschau der Kamera. Sie enthält bereits deren Bildstil (z. B. Monochrom) und Weißabgleich.", "Filtered: {label}": "Gefiltert: {label}", "{n} similar photo{} · View ▸ Clear Filters to see all": "Ähnliche Fotos: {n}{:.0} · Ansicht → Filter löschen zeigt alle Fotos", - "Moved; {} photo(s) relinked": "Verschoben; {} Fotos neu verknüpft", - "{} label (click more labels to show any of them)": "Markierung {} (weitere Markierungen auswählen, um alle passenden Fotos zu zeigen)", + "Moved; {} photo(s) relinked": "Verschoben; {} Foto(s) neu verknüpft", + "{} label (click more labels to show any of them)": "Farbmarkierung {} (weitere Farbmarkierungen auswählen, um alle passenden Fotos zu zeigen)", ", {} star{}": ", Sterne: {}{:.0}", - ", {} label": ", Markierung: {}", + ", {} label": ", Farbmarkierung: {}", "Downloads from {host}. Once it has arrived and checked out, LightCraft installs it, {after}.": "Lädt von {host} herunter. Sobald es angekommen und geprüft ist, installiert LightCraft es und {after}.", "{:.1} MB": "{:.1} MB", "Running on the processor: {}.": "Läuft auf dem Prozessor: {}.", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Im Ordner „denoise“ der Bibliothek gespeichert; bei Erreichen der Grenze werden zuerst die ältesten entfernt, die kein Foto verwendet.", "Denoising {name}: {done} of {total} tiles{}": "{name} wird entrauscht: {done} von {total} Kacheln{}", "{size} GB": "{size} GB", - "{} of {} from {host}": "{} von {} von {host}", + "{} of {} from {host}": "{} von {} (Quelle: {host})", "{} KB": "{} KB", "{} MB": "{} MB", "Making the denoised picture… {}%": "Entrauschtes Bild wird berechnet… {}%", @@ -223,17 +223,18 @@ "Delete the keyword “{name}”?": "Das Stichwort „{name}“ löschen?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Es wird von {count} Foto{} entfernt, mit den Stichwörtern darunter. Rückgängig stellt es wieder her.", "Create Keyword Tag Inside “{name}”…": "Stichwort in „{name}“ erstellen…", + "Inside: {names}": "Darin: {names}", "“{parent}” has a “{name}” already. Merge the two?": "„{parent}“ enthält bereits „{name}“. Beide zusammenführen?", "There is a “{name}” at the top level already. Merge the two?": "Auf der obersten Ebene gibt es bereits „{name}“. Beide zusammenführen?", "Added “{keyword}” to {n} photo{}": "„{keyword}“ zu {n} Foto{} hinzugefügt", - "On {have} of {of} selected photos": "Auf {have} von {of} ausgewählten Fotos", + "On {have} of {of} selected photos": "Bei {have} von {of} ausgewählten Fotos", "Remove “{name}”": "„{name}“ entfernen", "There is a keyword set “{name}” already": "Es gibt bereits einen Stichwortsatz „{name}“", "Added {n} keyword{}": "Stichwörter hinzugefügt: {n}{:.0}", "; {n} gained synonyms": "; mit neuen Synonymen: {n}", "Exported {n} keyword{}": "Stichwörter exportiert: {n}{:.0}", - " — Capture One won't import a list with ; , < or > in a keyword: {names}": " — Capture One importiert keine Liste mit ; , < oder > in einem Stichwort: {names}", - " — left out, as a keyword list can't hold them: {names}": " — ausgelassen, weil eine Stichwortliste sie nicht aufnehmen kann: {names}", + " — Capture One won't import a list with ; , < or > in a keyword: {names}": " – Capture One importiert keine Liste mit ; , < oder > in einem Stichwort: {names}", + " — left out, as a keyword list can't hold them: {names}": " – ausgelassen, weil eine Stichwortliste sie nicht aufnehmen kann: {names}", "{done} of {total}": "{done} von {total}", "{done} of {total} MB": "{done} von {total} MB", "{pct} %": "{pct} %", @@ -254,7 +255,7 @@ "{n} photos opened for editing; each is stacked with its original": "{n} Fotos zur Bearbeitung geöffnet; jedes ist mit seinem Original gestapelt", " in {g} group{}": " in {g} Gruppe(n){:.0}", " · kept, not applied: {}": " · behalten, nicht angewendet: {}", - " — kept but not applied: {}": " — behalten, aber nicht angewendet: {}", + " — kept but not applied: {}": " – behalten, aber nicht angewendet: {}", "Apply to “{mask}” on Selected Photos": "Auf „{mask}“ in den ausgewählten Fotos anwenden", "Delete the effect preset “{name}”?": "Effektvorgabe „{name}“ löschen?", "Delete these {n} effect presets?": "Diese {n} Effektvorgaben löschen?", @@ -280,7 +281,7 @@ "Skipped {problem}": "Übersprungen: {problem}", "…and {more} more": "…und {more} weitere", "Template preview: {name}": "Vorlagenvorschau: {name}", - "{n} photos in view · {slides} slides · {time}": "{n} Fotos in der Ansicht · {slides} Folien · {time}", + "{n} photos in view · {slides} slides · {time}": "{n} Fotos in der Ansicht · {slides} Dias · {time}", "{n} pages": "{n} Seiten", "{n} JPEG files": "{n} JPEG-Dateien", "{s} s of AV1 video": "{s} s AV1-Video", @@ -289,7 +290,7 @@ "{n} raws can now be developed from their raw data": "{n} RAW-Dateien können jetzt aus ihren Rohdaten entwickelt werden", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft wurde unerwartet beendet: {e}\n\nEinzelheiten stehen in der Protokolldatei: {path}", "LightCraft stopped unexpectedly: {e}": "LightCraft wurde unerwartet beendet: {e}", - "Renames {n} face{} across the library. The files are not changed.": "Benennt {n} Gesichter in der Bibliothek um. Die Dateien werden nicht geändert.{:.0}", + "Renames {n} face{} across the library. The files are not changed.": "Benennt {n} Gesicht(er) in der Bibliothek um. Die Dateien werden nicht geändert.{:.0}", "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "„{to}“ ist bereits eine Person. Zusammenführen ergibt eine Person; Rückgängig trennt sie wieder.", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}-Zusammenfügung mit {mp} hinzugefügt: die volle Größe, {full}, braucht mehr Arbeitsspeicher, als dieser Computer hat", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}-Zusammenfügung mit {mp} hinzugefügt, der größten möglichen Panoramagröße (volle Größe: {full})", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "{n} Foto{0} nach „{1}“ verschieben", "Move {n} photo{} to “{}”?": "{n} Foto{0} nach „{1}“ verschieben?", "Listing folders — folders: {folders}, files: {files}": "Ordner werden aufgelistet – Ordner: {folders}, Dateien: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück.", + "Drop to review {n} item{} for import": "Ablegen, um vor dem Import zu prüfen (Objekte: {n}){:.0}", + "Drop to import {n} item{}": "Ablegen zum Importieren (Objekte: {n}){:.0}", + "Drop to import {n} preset{}": "Ablegen zum Importieren von Vorgaben: {n}{:.0}", + "Could not read {name}: {e}": "{name} konnte nicht gelesen werden: {e}", + "Added {n} photo{}": "{n} Foto{} hinzugefügt", + "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", + "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 67a305ddf5..e2205db782 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -14,7 +14,7 @@ "0: nothing is rejected.": "0: Nichts wird abgelehnt.", "1 day": "1 Tag", "123 on studio-mac)\") instead of letting both write and silently drop each other's edits. A crash never leaves the": "123 auf studio-mac. Beide Programme können nicht gleichzeitig schreiben und gegenseitig Bearbeitungen verlieren. Ein Absturz lässt die", - "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · aktuelle Bearbeitungen · eingepasst ohne Beschnitt", + "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · aktuelle Bearbeitungen · eingepasst ohne Zuschnitt", "1620 × 1080 preview, and import with their metadata: capture time, camera, lens, exposure, GPS and XMP. Their raw": "1620 × 1080 großen Vorschau. Metadaten werden importiert: Aufnahmezeit, Kamera, Objektiv, Belichtung, GPS und XMP. Die RAW-Daten", "2026-04 or 2026-04-12": "2026-04 oder 2026-04-12", "23 new built-in presets: Portrait, Landscape, Urban, Food, Seasons, Vintage and B&W toners.": "23 neue eingebaute Vorgaben: Porträt, Landschaft, Stadt, Essen, Jahreszeiten, Vintage und Schwarzweißtonungen.", @@ -49,6 +49,7 @@ "Add in place": "Am Speicherort hinzufügen", "Add in place: the library references the files where they are; nothing is copied or moved.": "Am Speicherort hinzufügen: Die Bibliothek verweist auf die Dateien an ihrem aktuellen Speicherort; nichts wird kopiert oder verschoben.", "Add keyword": "Stichwort hinzufügen", + "Add Keywords": "Stichwörter hinzufügen", "Add number": "Nummer hinzufügen", "Add to": "Hinzufügen zu", "Add to Album": "Zu Album hinzufügen", @@ -64,7 +65,7 @@ "Add/Subtract/Intersect Mask": "Maske hinzufügen/subtrahieren/schneiden", "Added to photos you import that don't already have it.": "Wird importierten Fotos hinzugefügt, die diese Angabe noch nicht enthalten.", "Adding": "Wird hinzugefügt", - "Adding Lightroom photos…": "Lightroom-Fotos werden hinzugefügt …", + "Adding Lightroom photos…": "Lightroom-Fotos werden hinzugefügt…", "Advanced search…": "Erweiterte Suche…", "After": "Nachher", "After 30 days": "Nach 30 Tagen", @@ -99,9 +100,9 @@ "Aqua Hue": "Aquamarin – Farbton", "Aqua Luminance": "Aquamarin – Luminanz", "Aqua Saturation": "Aquamarin – Sättigung", - "Arrange Panel": "Bereich anordnen", + "Arrange Panel": "Bedienfeld anordnen", "ArtCraft Website": "ArtCraft-Website", - "ArtCraft — more creative apps": "ArtCraft — weitere Kreativ-Apps", + "ArtCraft — more creative apps": "ArtCraft – weitere Kreativ-Apps", "As Shot": "Wie Aufnahme", "As shot": "Wie Aufnahme", "Ascending": "Aufsteigend", @@ -235,7 +236,6 @@ "Clear Filters": "Filter löschen", "Clear Guides": "Hilfslinien löschen", "Clear History": "Verlauf löschen", - "Clear Preview Cache": "Vorschau-Cache leeren", "Clear Quick Collection": "Schnellsammlung leeren", "Clear Reference": "Referenz entfernen", "Clear all": "Alles löschen", @@ -258,7 +258,7 @@ "Close Window": "Fenster schließen", "Close all": "Alle schließen", "Close file": "Datei schließen", - "Close panel": "Bereich schließen", + "Close panel": "Bedienfeld schließen", "Cloudy": "Bewölkt", "Cmd+Shift+R, keeps the photo and clears its edits.)": "mit ⌘⇧R die Bearbeitungen zurück und behält das Foto.", "Collapse": "Einklappen", @@ -289,7 +289,6 @@ "Company": "Unternehmen", "Compare": "Vergleichen", "Compare (Shift+C)": "Vergleichen (Umschalt+C)", - "Compare Before and After": "Vorher und Nachher vergleichen", "Compare needs at least two photos": "Zum Vergleichen sind mindestens zwei Fotos erforderlich", "Component options": "Komponentenoptionen", "Compressed Nikon NEFs (lossless and lossy compressed, 12- and 14-bit — e.g. D3200, D5100, D7000, D750, D850, Z 50)": "Komprimierte Nikon-NEFs, verlustfrei oder verlustbehaftet mit 12 oder 14 Bit, etwa D3200, D5100, D7000, D750, D850 und Z 50,", @@ -298,10 +297,10 @@ "Confirm before deleting": "Vor dem Löschen bestätigen", "Confirm before moving photos to Recently Deleted": "Vor dem Verschieben nach „Zuletzt gelöscht“ bestätigen", "Move Photos": "Fotos verschieben", - "Their files and XMP sidecars move on disk. Edit → Undo moves them back.": "Ihre Dateien und XMP-Filialdateien werden auf dem Datenträger verschoben. Bearbeiten → Rückgängig holt sie zurück.", + "Their files and XMP sidecars move on disk. Edit → Undo moves them back.": "Die Dateien der Fotos und ihre XMP-Begleitdateien werden auf dem Datenträger verschoben. Bearbeiten → Rückgängig holt sie zurück.", "Don't ask again": "Nicht mehr fragen", "Another library was opened since the photos were dropped: nothing was moved": "Seit dem Ablegen der Fotos wurde eine andere Bibliothek geöffnet: Es wurde nichts verschoben", - "Settings → Confirm before moving photos to another folder on disk turns it back on": "Einstellungen → „Vor dem Verschieben in einen anderen Ordner auf dem Datenträger bestätigen“ schaltet es wieder ein", + "Settings → Confirm before moving photos to another folder on disk turns it back on": "Einstellungen → „Vor dem Verschieben in einen anderen Ordner auf dem Datenträger bestätigen“ schaltet die Abfrage wieder ein", "Confirm before moving photos to another folder on disk": "Vor dem Verschieben in einen anderen Ordner auf dem Datenträger bestätigen", "Constrain Crop": "Zuschnitt beschränken", "Contact Sheet PDF": "Kontaktabzug-PDF", @@ -445,6 +444,7 @@ "Download the SAM 3 Model?": "SAM-3-Modell herunterladen?", "Downloads": "Downloads", "Drag along the horizon; double-click for Auto": "Entlang des Horizonts ziehen; Doppelklick für Automatik", + "No horizon or vertical lines to level by": "Kein Horizont und keine senkrechten Linien zum Ausrichten gefunden", "Drag over an eye on the photo; the pupil inside is found automatically.": "Ziehe über ein Auge im Foto; die Pupille darin wird automatisch gefunden.", "Draw Guides": "Hilfslinien zeichnen", "Duplicate": "Duplizieren", @@ -464,7 +464,7 @@ "Edit Date": "Bearbeitungsdatum", "Edit Info": "Informationen bearbeiten", "Edit Label Names": "Namen der Farbmarkierungen bearbeiten", - "Edit Label Names…": "Markierungsnamen bearbeiten…", + "Edit Label Names…": "Namen der Farbmarkierungen bearbeiten…", "Edit Mask": "Maske bearbeiten", "Edit Mask Component": "Maskenkomponente bearbeiten", "Edit Sections": "Bearbeitungsbereiche", @@ -506,7 +506,7 @@ "Export Presets…": "Vorgaben exportieren…", "Export User Presets…": "Benutzervorgaben exportieren…", "Export file names use the Rename Photos tokens ({title}, {seq:2}, {date:%Y-%m-%d}…), plus new {num}, {folder}, {lens}, {iso}, {rating}, {creator}.": "Exportdateinamen verwenden die Platzhalter der Fotoumbenennung ({title}, {seq:2}, {date:%Y-%m-%d}…) sowie {num}, {folder}, {lens}, {iso}, {rating}, {creator}.", - "Export stopped unexpectedly": "Export unerwartet angehalten", + "Export stopped unexpectedly": "Export unerwartet abgebrochen", "Export with Preset": "Mit Vorgabe exportieren", "Export with Previous": "Mit vorherigen Einstellungen exportieren", "Exported files are written to a temp file and then renamed into place, so a full disk or an unplugged drive": "Exportdateien werden zunächst temporär geschrieben und anschließend umbenannt. Ein voller Datenträger oder getrenntes Laufwerk", @@ -576,7 +576,7 @@ "Flip Overlay (⇧O)": "Überlagerung spiegeln (⇧O)", "Flip V": "V spiegeln", "Flip Vertical": "Vertikal spiegeln", - "Float panel": "Bereich frei platzieren", + "Float panel": "Bedienfeld frei platzieren", "Flow": "Fluss", "Fluorescent": "Leuchtstofflicht", "Focal Length": "Brennweite", @@ -592,7 +592,7 @@ "Form fields panel": "Formularfeldbereich", "Format": "Format", "Forward": "Vorwärts", - "Frame time": "Bilddauer", + "Frame time": "Frame-Zeit", "Frame update": "Bildaktualisierung", "Free": "Frei", "Fresh & Bright": "Frisch und hell", @@ -697,7 +697,7 @@ "Import": "Importieren", "Import Date": "Importdatum", "Import Lightroom Catalog": "Lightroom-Katalog importieren", - "Import Lightroom Catalog…": "Lightroom-Katalog importieren …", + "Import Lightroom Catalog…": "Lightroom-Katalog importieren…", "Import Photos": "Fotos importieren", "Import Photos…": "Fotos importieren…", "Import Point Curve Presets": "Punktkurvenvorgaben importieren", @@ -723,7 +723,7 @@ "In Photo Grid and Square Grid: expand or collapse the stack": "In Fotoraster und quadratischem Raster: Stapel auf- oder zuklappen", "In Recently Deleted": "In „Zuletzt gelöscht“", "In library": "In Bibliothek", - "In memory — nothing is saved": "Im Arbeitsspeicher — nichts wird gespeichert", + "In memory — nothing is saved": "Im Arbeitsspeicher – nichts wird gespeichert", "In use": "In Verwendung", "In-memory session: these settings last until LightCraft quits.": "Sitzung im Arbeitsspeicher: Diese Einstellungen gelten bis zum Beenden von LightCraft.", "Include selected photos": "Ausgewählte Fotos einschließen", @@ -804,7 +804,7 @@ "LightCraft no longer crashes at launch on Windows PCs whose Vulkan driver is broken (issue #136, e.g. some Intel UHD": "LightCraft stürzt beim Start auf Windows-PCs mit defektem Vulkan-Treiber nicht mehr ab (Issue #136, etwa bestimmte Intel-UHD-630-Treiber).", "LightCraft on GitHub": "LightCraft auf GitHub", "LightCraft website": "LightCraft-Website", - "LightCraft — Second Window": "LightCraft — zweites Fenster", + "LightCraft — Second Window": "LightCraft – zweites Fenster", "Lightroom Classic Catalog": "Lightroom Classic-Katalog", "Lightroom import cancelled": "Lightroom-Import abgebrochen", "Lightroom inspection cancelled": "Lightroom-Prüfung abgebrochen", @@ -825,7 +825,7 @@ "Loading preview…": "Vorschau wird geladen…", "Local": "Lokal", "Local folders": "Lokale Ordner", - "Local library — no cloud account needed": "Lokale Bibliothek — kein Cloud-Konto erforderlich", + "Local library — no cloud account needed": "Lokale Bibliothek – kein Cloud-Konto erforderlich", "Locate Missing File…": "Fehlende Datei suchen…", "Locate Missing Files…": "Fehlende Dateien suchen…", "Locate Photo": "Foto suchen", @@ -881,7 +881,7 @@ "Midtones Hue": "Mitteltöne – Farbton", "Midtones Luminance": "Mitteltöne – Luminanz", "Midtones Saturation": "Mitteltöne – Sättigung", - "Midtones split": "Mitteltontrennung", + "Midtones split": "Mitteltongrenze", "Minimize": "Minimieren", "Missing Photos": "Fehlende Fotos", "Missing metadata ({camera}, {title}…) leaves an empty gap; a name that comes out empty keeps the original name.": "Fehlende Metadaten ({camera}, {title}…) hinterlassen eine Lücke; bei einem leeren Ergebnis bleibt der Originalname erhalten.", @@ -923,7 +923,7 @@ "Muted": "Gedämpft", "Muted Film": "Gedämpfter Film", "My Photos": "Meine Fotos", - "My Photos Panel": "Bereich „Meine Fotos“", + "My Photos Panel": "Bedienfeld „Meine Fotos“", "Name": "Name", "Name (A–Z)": "Name (A–Z)", "Name of the folder the original is in": "Name des Ordners mit dem Original", @@ -951,6 +951,7 @@ "New name": "Neuer Name", "New time": "Neue Zeit", "New…": "Neu…", + "Next Keyword Set": "Nächster Stichwortsatz", "Next Photo": "Nächstes Foto", "Night Blue": "Nachtblau", "Nikon NEFs start from a colour and tone look fitted to the camera's own JPEG, as Sony ARWs do, instead of a muted,": "Nikon-NEFs beginnen mit einem Farb- und Tonwertbild, das wie bei Sony-ARWs an das Kamera-JPEG angepasst ist, statt mit einem gedämpften,", @@ -980,7 +981,7 @@ "No photo selected": "Kein Foto ausgewählt", "No photos": "Keine Fotos", "Your library is empty": "Deine Bibliothek ist leer", - "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Importierte Fotos erscheinen hier. Nichts wird kopiert oder verschoben, außer du wählst es.", + "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Importierte Fotos erscheinen hier. Kopiert oder verschoben wird nur, wenn du dich dafür entscheidest.", "or drop photos and folders into this window": "oder ziehe Fotos und Ordner in dieses Fenster", "Import photos to get started": "Importiere Fotos, um loszulegen", "or drop photos into this window": "oder ziehe Fotos in dieses Fenster", @@ -994,7 +995,7 @@ "No versions yet. Create one to keep this look.": "Noch keine Versionen. Erstelle eine, um diesen Look zu bewahren.", "Noise": "Rauschen", "Noise Reduction": "Rauschreduzierung", - "Non-raw photos": "Andere Fotos als RAW", + "Non-raw photos": "Nicht-RAW-Fotos", "None": "Keine", "Not Now": "Nicht jetzt", "Nothing to compare": "Nichts zum Vergleichen", @@ -1038,11 +1039,11 @@ "Overwrite": "Überschreiben", "Pages": "Seiten", "Paint": "Auftragen", - "Paint only areas like the one under the brush": "Nur Bereiche wie den unter dem Pinsel bearbeiten", + "Paint only areas like the one under the brush": "Nur Bereiche bemalen, die dem Bereich unter dem Pinsel ähneln", "Paint over a distraction on the photo to remove it.": "Übermale ein störendes Element im Foto, um es zu entfernen.", "Paint overlay": "Überlagerung auftragen", "Panasonic and Leica raws (RW2, RWL and the older RAW files, DMC-LX1 to DC-S1R II) develop from the raw data in": "RAW-Dateien von Panasonic und Leica, RW2, RWL und ältere RAW-Dateien von DMC-LX1 bis DC-S1R II, werden in", - "Panels": "Bereiche", + "Panels": "Bedienfelder", "Panorama": "Panorama", "Panorama Merge": "Zu Panorama zusammenfügen", "Panorama Merge Preview": "Panoramavorschau", @@ -1106,13 +1107,14 @@ "Presets (Shift+P)": "Vorgaben (Umschalt+P)", "Presets and profiles": "Vorgaben und Profile", "Presets ▾": "Vorgaben ⌄", - "Press keys…": "Tasten drücken …", + "Press keys…": "Tasten drücken…", "Preview": "Vorschau", "Preview Build Progress": "Fortschritt der Vorschauerstellung", "Preview only": "Nur Vorschau", "Preview size": "Vorschaugröße", "Preview unavailable": "Vorschau nicht verfügbar", "Previews": "Vorschauen", + "Previous Keyword Set": "Vorheriger Stichwortsatz", "Previous Photo": "Vorheriges Foto", "Print": "Drucken", "Print…": "Drucken…", @@ -1175,7 +1177,7 @@ "Read mode": "Lesemodus", "Read the SAM License": "SAM-Lizenz lesen", "Reading": "Wird gelesen", - "Reading Lightroom catalog…": "Lightroom-Katalog wird gelesen …", + "Reading Lightroom catalog…": "Lightroom-Katalog wird gelesen…", "Reading folder…": "Ordner wird gelesen…", "Real name": "Echter Name", "Recent": "Zuletzt verwendet", @@ -1206,6 +1208,9 @@ "Refresh View": "Ansicht aktualisieren", "Reject": "Ablehnen", "Reject below focus": "Unter Schärfegrenzwert ablehnen", + "Burst: shots at most this far apart": "Serie: Aufnahmen höchstens so weit auseinander", + "Burst: how alike (loose … strict)": "Serie: wie ähnlich (locker … streng)", + "Lower it when a panning or moving burst splits into several groups.": "Senken, wenn eine Mitzieher- oder Bewegungsserie in mehrere Gruppen zerfällt.", "Rejected": "Abgelehnt", "Rejects": "Abgelehnte Fotos", "Reliability": "Zuverlässigkeit", @@ -1217,7 +1222,7 @@ "Remove CA": "Chromatische Aberration entfernen", "Remove Chromatic Aberration": "Chromatische Aberration entfernen", "Camera local tone mapping": "Lokale Tonwertzuordnung der Kamera", - "Apply the local tone mapping stored in the raw (Apple ProRAW), as the camera renders it": "Die in der Raw-Datei gespeicherte lokale Tonwertzuordnung (Apple ProRAW) anwenden, wie die Kamera sie rendert", + "Apply the local tone mapping stored in the raw (Apple ProRAW), as the camera renders it": "Die in der RAW-Datei gespeicherte lokale Tonwertzuordnung (Apple ProRAW) anwenden, wie die Kamera sie rendert", "Remove Disk from Library": "Datenträger aus Bibliothek entfernen", "Remove Disk from Library…": "Datenträger aus Bibliothek entfernen…", "Remove Face Box": "Gesichtsrahmen entfernen", @@ -1267,7 +1272,7 @@ "Reset Control": "Regler zurücksetzen", "Reset Crop": "Zuschnitt zurücksetzen", "Reset Edits": "Bearbeitungen zurücksetzen", - "Reset Panel Layout": "Bereichsanordnung zurücksetzen", + "Reset Panel Layout": "Bedienfeldanordnung zurücksetzen", "Reset Parametric Curve": "Parametrische Kurve zurücksetzen", "Reset Section": "Bereich zurücksetzen", "Reset Tone Curve": "Gradationskurve zurücksetzen", @@ -1275,8 +1280,8 @@ "Reset all edits": "Alle Bearbeitungen zurücksetzen", "Reshuffle": "Neu mischen", "Resize Face Box": "Gesichtsrahmengröße ändern", - "Resize panel window": "Größe des Bereichsfensters ändern", - "Resize panels": "Bereichsgrößen ändern", + "Resize panel window": "Größe des Bedienfeldfensters ändern", + "Resize panels": "Bedienfeldgrößen ändern", "Resize to": "Größe ändern auf", "Resolution (ppi)": "Auflösung (ppi)", "Restore": "Wiederherstellen", @@ -1327,7 +1332,7 @@ "Save as set": "Als Satz speichern", "Save as…": "Speichern unter…", "Save preset": "Vorgabe speichern", - "Saving Lightroom import index…": "Lightroom-Importindex wird gespeichert …", + "Saving Lightroom import index…": "Lightroom-Importindex wird gespeichert…", "Saving metadata to an XMP sidecar another application wrote no longer replaces it (issue #92): LightCraft merges its": "Beim Speichern von Metadaten in einer XMP-Begleitdatei einer anderen Anwendung wird diese nicht mehr ersetzt (Issue #92): LightCraft führt seine", "Scale": "Skalierung", "Scan failed": "Durchsuchen fehlgeschlagen", @@ -1382,7 +1387,7 @@ "Set as Target Album (B adds to it)": "Als Zielalbum festlegen (B fügt Fotos hinzu)", "Set as Top of Stack": "Als oberstes Foto im Stapel festlegen", "Set date & time": "Datum und Uhrzeit festlegen", - "Set name": "Satzname", + "Set name": "Name des Satzes", "Set the mix from the photo's colours": "Mischung anhand der Farben des Fotos festlegen", "Settings": "Einstellungen", "Settings file problem": "Problem mit Einstellungsdatei", @@ -1397,7 +1402,7 @@ "Shadows Hue": "Tiefen – Farbton", "Shadows Luminance": "Tiefen – Luminanz", "Shadows Saturation": "Tiefen – Sättigung", - "Shadows Tint": "Tiefen – Tonung", + "Shadows Tint": "Tiefen – Tönung", "Shadows split": "Tiefengrenze", "Sharpen": "Schärfen", "Sharpening": "Schärfen", @@ -1407,17 +1412,12 @@ "Short Edge": "Kurze Kante", "Show": "Anzeigen", "Show All": "Alle einblenden", - "Show Clipping": "Beschnitt anzeigen", "Show Deghost Overlay": "Geisterbildüberlagerung anzeigen", "Show Hidden Local Locations": "Ausgeblendete lokale Orte anzeigen", "Show Luminance Map": "Luminanzkarte anzeigen", "Show Mask": "Maske anzeigen", - "Show Mask Overlay": "Maskenüberlagerung anzeigen", - "Show All Mask Overlays": "Alle Maskenüberlagerungen anzeigen", "Show all overlays": "Alle Überlagerungen anzeigen", - "Show Mask Pins": "Maskenpins anzeigen", "Show Original": "Original anzeigen", - "Show Photo Counts": "Fotoanzahl anzeigen", "Show Photos with Keyword": "Fotos mit Stichwort anzeigen", "Show Pins": "Pins anzeigen", "Show Source": "Quelle anzeigen", @@ -1437,7 +1437,7 @@ "Show the import review when a camera or card is connected": "Importfenster öffnen, wenn eine Kamera oder Karte angeschlossen wird", "Show the template tags; click one to insert it": "Vorlagenplatzhalter anzeigen; zum Einfügen anklicken", "Show/Hide Mask": "Maske ein-/ausblenden", - "Show/hide My Photos panel": "Bereich „Meine Fotos“ ein-/ausblenden", + "Show/hide My Photos panel": "Bedienfeld „Meine Fotos“ ein-/ausblenden", "Shutter speed": "Verschlusszeit", "Side panels": "Seitliche Bedienfelder", "Sidecar names": "Namen der Begleitdateien", @@ -1531,13 +1531,13 @@ "Temp": "Temp.", "Temperature": "Temperatur", "Template": "Vorlage", - "Temporary session — your library isn't open, and nothing you do here is saved.": "Vorübergehende Sitzung — deine Bibliothek ist nicht geöffnet; hier vorgenommene Änderungen werden nicht gespeichert.", + "Temporary session — your library isn't open, and nothing you do here is saved.": "Vorübergehende Sitzung – deine Bibliothek ist nicht geöffnet; hier vorgenommene Änderungen werden nicht gespeichert.", "Text": "Text", "Text direction": "Textrichtung", "Texture": "Struktur", "That includes the photos in the folders inside it.": "Das schließt die Fotos in den enthaltenen Unterordnern ein.", "That key can't be used as a shortcut": "Diese Taste kann nicht als Tastenkürzel verwendet werden", - "The SAM 3 model is installed: Object and Describe masks are ready.": "Das SAM-3-Modell ist installiert: Objekt- und Beschreibungsmaske sind verfügbar.", + "The SAM 3 model is installed: Object and Describe masks are ready.": "Das SAM-3-Modell ist installiert: Objekt- und Beschreibungsmasken sind verfügbar.", "The catalog has a format version (issue #102). Opening a library from an older LightCraft upgrades it; a library": "Der Katalog hat eine Formatversion (Issue #102). Bibliotheken älterer LightCraft-Versionen werden beim Öffnen aktualisiert; eine Bibliothek", "The control port (`--control`) closes a connection as soon as it receives anything that isn't a JSON request": "Der Steuerport (`--control`) schließt eine Verbindung, sobald er etwas anderes als eine JSON-Anfrage erhält", "The download didn't work:": "Der Download ist fehlgeschlagen:", @@ -1557,7 +1557,7 @@ "Thumbnail cache": "Miniaturbild-Cache", "Thursday": "Donnerstag", "Time zone": "Zeitzone", - "Tint": "Tonung", + "Tint": "Tönung", "Title": "Titel", "Title metadata": "Titel aus Metadaten", "Toggle Keyword from Set": "Stichwort aus Satz umschalten", @@ -1586,7 +1586,7 @@ "Unflagged": "Unmarkiert", "Ungroup Stack": "Stapel auflösen", "Unknown Date": "Unbekanntes Datum", - "Unknown tags stay as typed — check the preview for a {typo}.": "Unbekannte Platzhalter bleiben unverändert — prüfe die Vorschau auf einen {typo}.", + "Unknown tags stay as typed — check the preview for a {typo}.": "Unbekannte Platzhalter bleiben unverändert – prüfe die Vorschau auf einen {typo}.", "Unrated": "Unbewertet", "Unreadable": "Nicht lesbar", "Update": "Aktualisieren", @@ -1638,7 +1638,7 @@ "Watermark": "Wasserzeichen", "Wednesday": "Mittwoch", "What's New": "Neuigkeiten", - "When rated or hovered": "Bei Bewertung oder Mauszeigerkontakt", + "When rated or hovered": "Bei Bewertung oder unter dem Mauszeiger", "White Balance": "Weißabgleich", "White Balance Selector": "Weißabgleich-Pipette", "White Balance Selector (W)": "Weißabgleich-Pipette (W)", @@ -1646,7 +1646,7 @@ "Width": "Breite", "Width (% of photo)": "Breite (% des Fotos)", "Width (px)": "Breite (px)", - "Width & Height": "Breite & Höhe", + "Width & Height": "Breite und Höhe", "Will be replaced": "Wird ersetzt", "Will be restored": "Wird wiederhergestellt", "Window": "Fenster", @@ -1674,7 +1674,7 @@ "`Photos/2026/20260114/20260114_001.jpg`) together with their XMP sidecars; each original leaves the card only after its": "`Photos/2026/20260114/20260114_001.jpg`, zusammen mit ihren XMP-Begleitdateien. Jedes Original verlässt die Karte erst nach", "`img_1-1.JPG`; on case-insensitive volumes the case change still goes through.": "`img_1-1.JPG`. Auf Laufwerken ohne diese Unterscheidung wird die Schreibweise weiterhin geändert.", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "oder vollen Laufwerk gilt nicht mehr als fertig und wird beim Erstellen der Smart-Vorschauen ersetzt.", - "a literal %": "ein wörtliches %", + "a literal %": "ein %-Zeichen", "a removed photo": "einem entfernten Foto", "afterwards (issue #101): the partial write is cut off before LightCraft retries, so the next launch replays every": "(Issue #101). Vor einem erneuten Versuch wird das Schreibfragment entfernt; beim nächsten Start werden alle Änderungen wiederhergestellt.", "again. Change the period (or turn it off) in Settings → Performance.": "wieder. Der Zeitraum lässt sich unter Einstellungen → Leistung ändern oder deaktivieren.", @@ -1752,7 +1752,7 @@ "isn't in the last": "liegt nicht in den letzten", "it away from the other (issue #92). Find Missing Photos also finds renamed files by their content, prefers a content match": "statt sie der anderen Datei wegzunehmen (Issue #92). Die Suche fehlender Fotos findet umbenannte Dateien anhand ihres Inhalts und bevorzugt passende Inhalte", "its photos and XMP sidecars, and the photos point at it again. If something now occupies the old place, the undo": "mit Fotos und XMP-Begleitdateien zurückverschoben; die Fotos verweisen wieder darauf. Ist der alte Speicherort inzwischen belegt,", - "keep names — or e.g. {date}_{seq:3}": "Namen beibehalten — oder z. B. {date}_{seq:3}", + "keep names — or e.g. {date}_{seq:3}": "Namen beibehalten – oder z. B. {date}_{seq:3}", "latitude, longitude": "Breitengrad, Längengrad", "layout is read from each file instead of assumed.": "wird aus jeder Datei gelesen, statt vorausgesetzt zu werden.", "leaves no DNG and keeps the raw. Smart previews are written the same way; a damaged one (cut short by a crash or": "hinterlässt kein DNG und behält die RAW-Datei. Smart-Vorschauen verwenden denselben Schreibweg; eine beschädigte Vorschau nach einem Absturz", @@ -1842,7 +1842,7 @@ "Any camera": "Jede Kamera", "Any lens": "Jedes Objektiv", "Any keyword": "Jedes Stichwort", - "Label Set": "Markierungssatz", + "Label Set": "Farbmarkierungssatz", ", picked": ", ausgewählt", ", rejected": ", abgelehnt", "Preview only: editing the camera's embedded JPEG": "Nur Vorschau: Bearbeitung des eingebetteten JPEGs der Kamera", @@ -1885,7 +1885,7 @@ "Make the denoised picture of the photos I am looking at": "Entrauschtes Bild der angezeigten Fotos berechnen", "Next up for AI Denoise…": "Als Nächstes beim KI-Entrauschen…", "Nothing is fetched until you accept. The model is kept on this computer only; LightCraft never uploads or shares it.": "Nichts wird geladen, bevor du zustimmst. Das Modell bleibt nur auf diesem Computer; LightCraft lädt es nie hoch und gibt es nie weiter.", - "Only photos whose AI Denoise amount is above 0 are made. Exports always make theirs if it is missing.": "Nur Fotos mit einer KI-Entrauschungsstärke über 0 werden berechnet. Exporte berechnen ihres immer, wenn es fehlt.", + "Only photos whose AI Denoise amount is above 0 are made. Exports always make theirs if it is missing.": "Nur Fotos mit einer KI-Entrauschungsstärke über 0 werden berechnet. Beim Export wird ein fehlendes Bild immer berechnet.", "Open page": "Seite öffnen", "Open the model's page": "Seite des Modells öffnen", "Opens the model's own page in your browser, to read about it or get the file yourself.": "Öffnet die Seite des Modells im Browser, um mehr darüber zu lesen oder die Datei selbst herunterzuladen.", @@ -1909,7 +1909,7 @@ "Unknown licence": "Unbekannte Lizenz", "Use": "Verwenden", "Waiting to start…": "Wartet auf Start…", - "Works on raw files from cameras with a standard (Bayer) sensor. Other files keep their normal noise reduction.": "Funktioniert mit Raw-Dateien von Kameras mit Standardsensor (Bayer). Andere Dateien behalten ihre normale Rauschreduzierung.", + "Works on raw files from cameras with a standard (Bayer) sensor. Other files keep their normal noise reduction.": "Funktioniert mit RAW-Dateien von Kameras mit Standardsensor (Bayer). Andere Dateien behalten ihre normale Rauschreduzierung.", "cached picture": "zwischengespeichertes Bild", "cached pictures": "zwischengespeicherte Bilder", "commercial use allowed": "kommerzielle Nutzung erlaubt", @@ -1991,20 +1991,20 @@ "Sa": "Sa", "Su": "So", "Pick a date": "Datum wählen", - "would make this album include itself through other smart albums": "würde dieses Album über andere Smart-Alben sich selbst enthalten lassen", + "would make this album include itself through other smart albums": "würde dazu führen, dass dieses Album sich über andere Smart-Alben selbst enthält", "Search albums": "Alben suchen", "No albums match": "Kein Album passt", "This is the album you're editing": "Das ist das Album, das du bearbeitest", - "It tests this album, so testing it back would loop": "Es prüft dieses Album; es zurückzuprüfen wäre ein Kreis", - "Copy Name": "Kopiename", + "It tests this album, so testing it back would loop": "Es prüft bereits dieses Album; eine Prüfung in Gegenrichtung ergäbe eine Endlosschleife", + "Copy Name": "Name der Kopie", "In a Stack": "In einem Stapel", "File Extension": "Dateiendung", "Video Duration": "Videodauer", "Keyword Count": "Anzahl Stichwörter", "People Count": "Anzahl Personen", - "Shutter Speed": "Belichtungszeit", + "Shutter Speed": "Verschlusszeit", "Cropped": "Zugeschnitten", - "Keywords & People": "Stichwörter & Personen", + "Keywords & People": "Stichwörter und Personen", "Description": "Beschreibung", "Camera Info": "Kamera-Info", "Develop": "Bearbeitung", @@ -2015,7 +2015,7 @@ "Whole names": "Vollständige Namen", "Grouped by parent": "Nach übergeordnetem Stichwort gruppiert", "Keywords of the selection": "Stichwörter der Auswahl", - "Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened.": "Gruppiert: Stichwörter im selben Stichwort teilen sich eine Zeile mit dessen Namen; lange Listen und die Vorschläge werden gekürzt.", + "Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened.": "Gruppiert: Stichwörter mit demselben übergeordneten Stichwort teilen sich eine Zeile mit dessen Namen; lange Listen und die Vorschläge werden gekürzt.", "Show every keyword of the selected photos": "Alle Stichwörter der ausgewählten Fotos anzeigen", "new keyword": "neues Stichwort", "Return creates this keyword and gives it to the selected photos": "Die Eingabetaste erstellt dieses Stichwort und weist es den ausgewählten Fotos zu", @@ -2031,14 +2031,14 @@ "Create Keyword Tag": "Stichwort erstellen", "Edit Keyword Tag": "Stichwort bearbeiten", "Create": "Erstellen", - "No photo has it; the keywords below it go too.": "Kein Foto hat es; die Stichwörter darunter werden ebenfalls gelöscht.", + "No photo has it; the keywords below it go too.": "Kein Foto verwendet es; die Stichwörter darunter werden ebenfalls gelöscht.", "Edit Keyword Tag…": "Stichwort bearbeiten…", "Put New Keywords Inside This Keyword": "Neue Stichwörter in dieses Stichwort einfügen", "Purge Unused Keywords": "Nicht verwendete Stichwörter löschen", "Delete Keyword…": "Stichwort löschen…", "Drop here for the top level": "Hier ablegen für die oberste Ebene", - "Their photos and the keywords below them come together under one keyword.": "Ihre Fotos und die Stichwörter darunter kommen unter einem Stichwort zusammen.", - "Select photos to give them keywords.": "Wähle Fotos aus, um ihnen Stichwörter zu geben.", + "Their photos and the keywords below them come together under one keyword.": "Die Fotos und die untergeordneten Stichwörter werden unter einem Stichwort zusammengeführt.", + "Select photos to give them keywords.": "Wähle Fotos aus, um ihnen Stichwörter zuzuweisen.", "Add to All Selected Photos": "Allen ausgewählten Fotos hinzufügen", "Will Export": "Wird exportiert", "No keywords are exported": "Es werden keine Stichwörter exportiert", @@ -2058,14 +2058,14 @@ "Synchronize Folder": "Ordner synchronisieren", "Synchronize": "Synchronisieren", "Scanning…": "Wird durchsucht…", - "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "Fotos finden, die in diesem Ordner auf dem Datenträger hinzugekommen sind oder fehlen, und von anderen Apps geänderte XMP-Filialdateien", + "Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps": "Fotos finden, die in diesem Ordner auf dem Datenträger hinzugekommen sind oder fehlen, und von anderen Apps geänderte XMP-Begleitdateien", "Bring the library up to date with this folder and the folders inside it:": "Die Bibliothek mit diesem Ordner und den Ordnern darin abgleichen:", "Import new photos": "Neue Fotos importieren", "Remove missing photos from the library": "Fehlende Fotos aus der Bibliothek entfernen", - "Read metadata updates from XMP sidecars": "Metadaten-Änderungen aus XMP-Filialdateien lesen", + "Read metadata updates from XMP sidecars": "Metadaten-Änderungen aus XMP-Begleitdateien lesen", "The library is up to date with this folder.": "Die Bibliothek ist mit diesem Ordner auf dem neuesten Stand.", "Missing photos move to Recently Deleted and can be restored; no file on disk is touched.": "Fehlende Fotos werden nach „Zuletzt gelöscht“ verschoben und können wiederhergestellt werden; keine Datei auf dem Datenträger wird verändert.", - "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "Beim Lesen einer Filialdatei werden Bewertung, Markierungen, Metadaten und Bearbeitungen des Fotos durch ihren Inhalt ersetzt.", + "Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.": "Beim Lesen einer Begleitdatei werden Bewertung, Markierungen, Metadaten und Bearbeitungen des Fotos durch ihren Inhalt ersetzt.", "Skipped: files already in the library elsewhere": "Übersprungen: Dateien, die bereits an anderer Stelle in der Bibliothek sind", "Skipped: files that can't be read": "Übersprungen: Dateien, die nicht gelesen werden können", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Dieser Ordner ist nicht vorhanden: Er wurde verschoben oder umbenannt, oder sein Datenträger ist nicht verbunden.", @@ -2104,7 +2104,7 @@ "Discarding smart previews": "Smart-Vorschauen werden verworfen", "Importing Lightroom catalog": "Lightroom-Katalog wird importiert", "Reading Lightroom catalog": "Lightroom-Katalog wird gelesen", - "Merging": "Zusammenfügen", + "Merging": "Wird zusammengefügt", "Downloading model": "Modell wird heruntergeladen", "Finding faces": "Gesichter werden gesucht", "Synchronizing folder": "Ordner wird synchronisiert", @@ -2152,7 +2152,7 @@ "Move to Folder": "In Ordner verschieben", "Move to Folder…": "In Ordner verschieben…", "Move Selected Photos Here": "Ausgewählte Fotos hierher verschieben", - "Moves the files and their XMP sidecars into this folder; never overwrites": "Verschiebt die Dateien samt XMP-Filialdateien in diesen Ordner; nichts wird überschrieben", + "Moves the files and their XMP sidecars into this folder; never overwrites": "Verschiebt die Dateien samt XMP-Begleitdateien in diesen Ordner; nichts wird überschrieben", "Appearance Settings…": "Erscheinungsbild-Einstellungen…", "Add to favorites": "Zu Favoriten hinzufügen", "Remove from favorites": "Aus Favoriten entfernen", @@ -2169,7 +2169,7 @@ "Detect Faces": "Gesichter erkennen", "Detect Faces (Photo menu) needs it: a small one-time download.": "„Gesichter erkennen“ (Menü „Foto“) benötigt es: ein kleiner, einmaliger Download.", "Download Face Model": "Gesichtsmodell herunterladen", - "Drag Crop Handle": "Freistellungsgriff ziehen", + "Drag Crop Handle": "Zuschnittgriff ziehen", "Evaluate Face Recognition": "Gesichtserkennung bewerten", "Face Model Downloads": "Downloads von Gesichtsmodellen", "Face Models": "Gesichtsmodelle", @@ -2218,7 +2218,7 @@ "Right": "Rechts", "Top": "Oben", "Bottom": "Unten", - "Margins are a share of the slide's shorter side, so slides look the same on any screen.": "Ränder sind ein Anteil der kürzeren Seite der Folie, damit Folien auf jedem Bildschirm gleich aussehen.", + "Margins are a share of the slide's shorter side, so slides look the same on any screen.": "Ränder sind ein Anteil der kürzeren Seite des Dias, damit Dias auf jedem Bildschirm gleich aussehen.", "Show guides": "Hilfslinien anzeigen", "Aspect preview": "Seitenverhältnis-Vorschau", "Zoom to fill frame": "Zoomen, um Rahmen zu füllen", @@ -2232,15 +2232,15 @@ "Background image": "Hintergrundbild", "(not in the library)": "(nicht in der Bibliothek)", "Use selected photo": "Ausgewähltes Foto verwenden", - "Select a photo, then turn this on to fill the slide behind every photo with it.": "Wähle ein Foto aus und schalte dies ein, um die Folie hinter jedem Foto damit zu füllen.", + "Select a photo, then turn this on to fill the slide behind every photo with it.": "Wähle ein Foto aus und schalte dies ein, um das Dia hinter jedem Foto damit zu füllen.", "Reset layout": "Layout zurücksetzen", - "Select a photo to preview its slide": "Wähle ein Foto, um seine Folie in der Vorschau zu sehen", - "The selected photo as a slide. Playback fills the screen; the aspect preview only changes this preview.": "Das ausgewählte Foto als Folie. Die Wiedergabe füllt den Bildschirm; die Seitenverhältnis-Vorschau ändert nur diese Vorschau.", + "Select a photo to preview its slide": "Wähle ein Foto, um sein Dia in der Vorschau zu sehen", + "The selected photo as a slide. Playback fills the screen; the aspect preview only changes this preview.": "Das ausgewählte Foto als Dia. Die Wiedergabe füllt den Bildschirm; die Seitenverhältnis-Vorschau ändert nur diese Vorschau.", "Overlays": "Überlagerungen", "Identity plate": "Erkennungstafel", "Your name or studio": "Dein Name oder Studio", "Anchored to": "Verankert an", - "Slide": "Folie", + "Slide": "Dia", "Render behind image": "Hinter dem Bild rendern", "Rating stars": "Sternebewertung", "Text overlays": "Textüberlagerungen", @@ -2285,7 +2285,7 @@ "Shooting Data": "Aufnahmedaten", "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Jedes Foto so groß wie möglich auf Schwarz, mit kurzer Überblendung. Nichts darüber gezeichnet.", "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Eine hellgraue Wand mit weißem Passepartout und weichem Schatten; Bildunterschrift und Bewertung unter dem Foto.", - "Every photo cropped to fill the whole screen, with slow crossfades.": "Jedes Foto auf den ganzen Bildschirm beschnitten, mit langsamen Überblendungen.", + "Every photo cropped to fill the whole screen, with slow crossfades.": "Jedes Foto auf den ganzen Bildschirm zugeschnitten, mit langsamen Überblendungen.", "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Ein 16:9-Bild mit schwarzen Balken oben und unten, dem Titel in der Ecke, Blenden über Schwarz und einer Abschlusstafel.", "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Ein dunkler Schieferhintergrund mit Belichtung, ISO und Brennweite, darunter Kamera und Objektiv, unter jedem Foto.", "Exporting slideshow": "Diashow wird exportiert", @@ -2298,11 +2298,11 @@ "Export JPEG…": "JPEG exportieren…", "Export Video…": "Video exportieren…", "Automatically show full screen": "Automatisch im Vollbild anzeigen", - "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode.": "Eine Seite pro Folie (lange Seite in Pixeln = Punkte), mit Foliendauer und Überblendung für den Präsentationsmodus des Betrachters.", + "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode.": "Eine Seite pro Dia (lange Seite in Pixeln = Punkte), mit Dia-Dauer und Überblendung für den Präsentationsmodus des Betrachters.", "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.": "Nummerierte JPEG-Dateien (name-001.jpg…) in einem neuen Ordner, der im nächsten Schritt benannt wird.", - "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.": "AV1-Video, jede Folie für ihre Dauer mit ihren Überblendungen. Kein Ton: Musik wird noch nicht exportiert.", - "Slides use the slideshow's layout, overlays and intro and ending screens, in view order.": "Die Folien verwenden Layout, Überlagerungen sowie Intro- und Abspannbild der Diashow, in der Reihenfolge der Ansicht.", - "The photos in view as slides, with the settings above. Progress shows in the activity stack.": "Die Fotos in der Ansicht als Folien, mit den Einstellungen oben. Der Fortschritt erscheint in der Aktivitätsliste.", + "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.": "AV1-Video, jedes Dia für seine Dauer mit seinen Überblendungen. Kein Ton: Musik wird noch nicht exportiert.", + "Slides use the slideshow's layout, overlays and intro and ending screens, in view order.": "Die Dias verwenden Layout, Überlagerungen sowie Intro- und Abschlussbildschirm der Diashow, in der Reihenfolge der Ansicht.", + "The photos in view as slides, with the settings above. Progress shows in the activity stack.": "Die Fotos in der Ansicht als Dias, mit den Einstellungen oben. Der Fortschritt erscheint im Aktivitätsstapel.", "Checking raw files": "RAW-Dateien werden geprüft", "1 raw can now be developed from its raw data": "1 RAW-Datei kann jetzt aus ihren Rohdaten entwickelt werden", "This raw is now developed from its raw data": "Diese RAW-Datei wird jetzt aus ihren Rohdaten entwickelt", @@ -2313,9 +2313,8 @@ "Same folder as original photo": "Im selben Ordner wie das Originalfoto", "Tidying the thumbnail cache": "Miniaturcache wird aufgeräumt", "Reset all edits (Cmd+Shift+R)": "Alle Bearbeitungen zurücksetzen (⌘⇧R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Intelligente Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", + "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", "LightCraft stopped": "LightCraft wurde beendet", - "Show Focus Point": "Fokuspunkt anzeigen", "Zoom to Focus Point": "Auf Fokuspunkt zoomen", "Focus": "Fokus", "Focus point": "Fokuspunkt", @@ -2340,7 +2339,7 @@ "Detection": "Erkennung", "Recognition": "Wiedererkennung", "Not loaded yet": "Noch nicht geladen", - "Checking the GPU…": "GPU wird geprüft …", + "Checking the GPU…": "GPU wird geprüft…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Ein Gesichtsmodell nutzt die GPU nur, wenn eine Prüfung zeigt, dass sie dieselben Ergebnisse schneller liefert.", "Checking the GPU for faces": "GPU für Gesichter wird geprüft", @@ -2466,8 +2465,8 @@ "Edit in HDR: highlights above SDR white, for HDR exports and displays": "In HDR bearbeiten: Lichter über SDR-Weiß, für HDR-Exporte und -Bildschirme", "SDR": "SDR", "Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.": "Links: der Standardbereich (SDR) bis SDR-Weiß. Rechts: der HDR-Bereich, ein Band pro Blendenstufe über SDR-Weiß (die orange Linie: der HDR-Spielraum). Mit eingeschaltetem „HDR visualisieren“ übernehmen die Bänder dessen Farben.", - "Click to hide clipping warnings for shadows and highlights.": "Klicken, um die Beschnittwarnungen für Tiefen und Lichter auszublenden.", - "Click to show clipping warnings for shadows and highlights.": "Klicken, um die Beschnittwarnungen für Tiefen und Lichter einzublenden.", + "Click to hide clipping warnings for shadows and highlights.": "Klicken, um die Beschneidungswarnungen für Tiefen und Lichter auszublenden.", + "Click to show clipping warnings for shadows and highlights.": "Klicken, um die Beschneidungswarnungen für Tiefen und Lichter einzublenden.", "Curve channel": "Kurvenkanal", "Targeted adjustment on: drag up or down on the photo · Esc to stop": "Gezielte Anpassung aktiv: auf dem Foto nach oben oder unten ziehen · Esc beendet", "Color wheel": "Farbrad", @@ -2508,7 +2507,7 @@ "Show mask": "Maske anzeigen", "Overlay color": "Überlagerungsfarbe", "Rename Person…": "Person umbenennen…", - "Their photos in the grid": "Ihre Fotos im Raster", + "Their photos in the grid": "Fotos dieser Person im Raster", "Tool Overlay": "Werkzeugüberlagerung", "When pins show on the photo (Shift+H cycles)": "Wann Pins auf dem Foto erscheinen (Umschalt+H wechselt)", "External Editing": "Externe Bearbeitung", @@ -2530,7 +2529,7 @@ "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Die in den Farbeinstellungen deines Desktops zugewiesenen Profile liegen meist in ~/.local/share/icc.", "Slide duration": "Dia-Dauer", "Fade duration": "Überblendungsdauer", - "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "Ein Dia bleibt für seine Dauer stehen, die Überblendung eingeschlossen. Eine Überblendung von 0 schneidet hart.", + "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "Ein Dia bleibt für seine Dauer stehen, die Überblendung eingeschlossen. Bei 0 wird hart geschnitten.", "Fade": "Überblendung", "Renders the next slides while the current one is up, so fades never wait. Off: each slide renders when it is due (less memory and work).": "Berechnet die nächsten Dias, während das aktuelle zu sehen ist, sodass Überblendungen nie warten. Aus: Jedes Dia wird berechnet, wenn es an der Reihe ist (weniger Speicher und Rechenarbeit).", "Slideshow in the View menu plays the photos in view from the selected one. These settings are saved with the library.": "„Diashow“ im Menü „Ansicht“ spielt die Fotos der Ansicht ab dem ausgewählten ab. Diese Einstellungen werden mit der Bibliothek gespeichert.", @@ -2832,7 +2831,7 @@ "\"LightCraft stopped unexpectedly\" and why, instead of \"could not open its window\", and the next start renders": "„LightCraft wurde unerwartet beendet“ und den Grund statt „konnte sein Fenster nicht öffnen“, und der nächste Start rendert", "on the CPU and explains how to turn the GPU back on.": "auf der CPU und erklärt, wie man die GPU wieder einschaltet.", "Resetting a slider": "Einen Regler zurücksetzen", - "Resting the pointer on a slider's name or its thumb now says that a double-click resets it (\"Exposure — double-click": "Ruht der Mauszeiger auf dem Namen oder dem Griff eines Reglers, wird jetzt angezeigt, dass ein Doppelklick ihn zurücksetzt („Belichtung — zum Zurücksetzen", + "Resting the pointer on a slider's name or its thumb now says that a double-click resets it (\"Exposure — double-click": "Ruht der Mauszeiger auf dem Namen oder dem Griff eines Reglers, wird jetzt angezeigt, dass ein Doppelklick ihn zurücksetzt („Belichtung – zum Zurücksetzen", "to reset it\"), in every language (issue #1436).": "doppelklicken“), in jeder Sprache (Issue #1436).", "A double-click on the thumb is a single step in History and Undo. Its first click no longer nudges the value to": "Ein Doppelklick auf den Griff ist ein einziger Schritt in Verlauf und Rückgängig. Sein erster Klick verschiebt den Wert nicht mehr dorthin,", "where the pointer landed, and a single click on the thumb leaves the value alone.": "wo der Zeiger landete, und ein einfacher Klick auf den Griff lässt den Wert unverändert.", @@ -2982,7 +2981,7 @@ "Choosing a Lightroom Classic catalog folder in File → Open Library… (or one of its `Previews.lrdata` /": "Die Wahl eines Lightroom-Classic-Katalogordners unter Datei → Bibliothek öffnen… (oder eines seiner Ordner `Previews.lrdata` /", "`.lrcat-data` folders, or the `.lrcat`) no longer makes an empty LightCraft library inside it (issue #891). The": "`.lrcat-data` oder der `.lrcat`) legt darin keine leere LightCraft-Bibliothek mehr an (Issue #891). Die", "library open now stays, and LightCraft says \"This is a Lightroom catalog, not a LightCraft library\" and offers": "geöffnete Bibliothek bleibt jetzt, und LightCraft meldet „Dies ist ein Lightroom-Katalog, keine LightCraft-Bibliothek“ und bietet", - "**Import Lightroom Catalog…** with that catalog, or Cancel. `lightcraft-cli --library` refuses those folders too.": "**Lightroom-Katalog importieren …** mit diesem Katalog an, oder Abbrechen. `lightcraft-cli --library` lehnt diese Ordner ebenfalls ab.", + "**Import Lightroom Catalog…** with that catalog, or Cancel. `lightcraft-cli --library` refuses those folders too.": "**Lightroom-Katalog importieren…** mit diesem Katalog an, oder Abbrechen. `lightcraft-cli --library` lehnt diese Ordner ebenfalls ab.", "Canon EOS R5 Mark II": "Canon EOS R5 Mark II", "Switching libraries": "Bibliotheken wechseln", "out. Clear Recent Libraries empties the list.": "ausgegraut. „Liste leeren“ leert die Liste.", @@ -3305,8 +3304,8 @@ "the container instead of decoding it; small previews use the file's embedded thumbnail. The release packages": "dem Container, statt es zu dekodieren; kleine Vorschauen verwenden die eingebettete Miniatur der Datei. Die Release-Pakete", "(macOS, Windows, Linux, FreeBSD, Nix) now really are built with HEIC support; a build without it reports": "(macOS, Windows, Linux, FreeBSD, Nix) werden jetzt wirklich mit HEIC-Unterstützung gebaut; ein Build ohne sie meldet", "\"HEIC/HEIF support isn't included in this build\" for each `.heic`/`.heif` at import.": "„HEIC/HEIF support isn't included in this build“ für jede `.heic`/`.heif`-Datei beim Import.", - "The Tint slider works the right way round (issues #188, #321): left adds green, right adds magenta, as its track": "Der Tonungsregler arbeitet in die richtige Richtung (Issues #188, #321): links mehr Grün, rechts mehr Magenta, wie seine Skala", - "shows and as in Lightroom, and Tint values in Lightroom XMP sidecars now render as they do there. A custom Tint": "zeigt und wie in Lightroom, und Tonungswerte in Lightroom-XMP-Begleitdateien rendern jetzt wie dort. Eine benutzerdefinierte Tonung,", + "The Tint slider works the right way round (issues #188, #321): left adds green, right adds magenta, as its track": "Der Tönungsregler arbeitet in die richtige Richtung (Issues #188, #321): links mehr Grün, rechts mehr Magenta, wie seine Skala", + "shows and as in Lightroom, and Tint values in Lightroom XMP sidecars now render as they do there. A custom Tint": "zeigt und wie in Lightroom, und Tönungswerte in Lightroom-XMP-Begleitdateien rendern jetzt wie dort. Eine benutzerdefinierte Tönung,", "saved in an earlier version now shifts the other way; set it again (or re-run Auto / the white-balance picker).": "die in einer früheren Version gespeichert wurde, verschiebt jetzt in die andere Richtung; stelle sie neu ein (oder führe Auto / die Weißabgleichpipette erneut aus).", "White balance on DNGs (and other raws with a colour matrix) re-develops the photo for the new white through the": "Der Weißabgleich bei DNGs (und anderen RAW-Dateien mit Farbmatrix) entwickelt das Foto für das neue Weiß über die", "camera's own colour matrices, as Lightroom does, instead of shifting the colours of the as-shot rendering: a grey": "eigenen Farbmatrizen der Kamera neu, wie Lightroom es tut, statt die Farben des Renderings „Wie Aufnahme“ zu verschieben: Ein Grau,", @@ -3378,7 +3377,7 @@ "Sony A7R II (and other) raws whose camera JPEG is lens-corrected no longer open grey and too dark (issue #232): the": "RAW-Dateien der Sony A7R II (und anderer), deren Kamera-JPEG objektivkorrigiert ist, öffnen nicht mehr grau und zu dunkel (Issue #232): Der", "starting look is fitted to the camera JPEG away from edges when the misaligned edges spoil the fit on all pixels.": "Ausgangslook wird abseits der Ränder an das Kamera-JPEG angepasst, wenn die verschobenen Ränder die Anpassung über alle Pixel verderben.", "Lightroom Classic catalogs": "Lightroom-Classic-Kataloge", - "File → Import Lightroom Catalog… opens `.lrcat` directly, with originals referenced in place.": "Datei → Lightroom-Katalog importieren … öffnet `.lrcat` direkt, wobei die Originale an ihrem Ort referenziert werden.", + "File → Import Lightroom Catalog… opens `.lrcat` directly, with originals referenced in place.": "Datei → Lightroom-Katalog importieren… öffnet `.lrcat` direkt, wobei die Originale an ihrem Ort referenziert werden.", "Ratings, flags, labels, keywords, collections/sets, virtual copies and supported edits migrate;": "Bewertungen, Markierungen, Farbmarkierungen, Stichwörter, Sammlungen/Sätze, virtuelle Kopien und unterstützte Bearbeitungen werden übernommen;", "existing LightCraft edits are preserved by default. Source settings/history are archived, unsupported": "vorhandene LightCraft-Bearbeitungen bleiben standardmäßig erhalten. Quelleinstellungen und -verlauf werden archiviert, nicht unterstützte", "fields are reported, and the original Lightroom database stays read-only. Rendering is approximate.": "Felder werden gemeldet, und die ursprüngliche Lightroom-Datenbank bleibt schreibgeschützt. Das Rendering ist eine Annäherung.", @@ -3422,5 +3421,24 @@ "favourites across restarts (issue #328).": "über Neustarts hinweg Favoriten (Issue #328).", "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Optionales entferntes SAM 3: Der native Editor bleibt lokal, und Objekt-, Beschreibungs- und Detail-", "inference on a Mac through SSH. Saved masks still render and export offline.": "Inferenz laufen über SSH auf einem Mac. Gespeicherte Masken werden weiterhin offline gerendert und exportiert.", - "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference)." + "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference).", + "Before/After Side by Side": "Vorher/Nachher nebeneinander", + "Clipping": "Beschneidung", + "Mask Overlay": "Maskenüberlagerung", + "All Mask Overlays": "Alle Maskenüberlagerungen", + "Mask Pins": "Maskenpins", + "Photo Counts": "Fotoanzahl", + "Focus Point": "Fokuspunkt", + "Layout Image": "Layoutbild", + "Detail View": "Detailansicht", + "Edit Panel": "Bedienfeld „Bearbeiten“", + "Close the open dialog, then drop the files again": "Schließe den geöffneten Dialog und lege die Dateien dann erneut ab", + "Close the open dialog to drop files here": "Schließe den geöffneten Dialog, um hier Dateien abzulegen", + "Drop to open the face model": "Ablegen, um das Gesichtsmodell zu öffnen", + "Drop to import": "Ablegen zum Importieren", + "Dropped Files": "Abgelegte Dateien", + "Import dropped files without review": "Abgelegte Dateien ohne Prüfung importieren", + "An import is running": "Ein Import läuft", + "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", + "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index fd15401693..33e5f52fc6 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -223,6 +223,7 @@ "Delete the keyword “{name}”?": "¿Eliminar la palabra clave “{name}”?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Se quita de {count} foto{}, con las palabras clave que contiene. Deshacer la recupera.", "Create Keyword Tag Inside “{name}”…": "Crear palabra clave dentro de “{name}”…", + "Inside: {names}": "Dentro: {names}", "“{parent}” has a “{name}” already. Merge the two?": "“{parent}” ya tiene “{name}”. ¿Combinar las dos?", "There is a “{name}” at the top level already. Merge the two?": "Ya hay “{name}” en el nivel superior. ¿Combinar las dos?", "Added “{keyword}” to {n} photo{}": "Se añadió “{keyword}” a {n} foto{}", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "Mover {n} foto{0} a “{1}”", "Move {n} photo{} to “{}”?": "¿Mover {n} foto{0} a “{1}”?", "Listing folders — folders: {folders}, files: {files}": "Listando carpetas — carpetas: {folders}, archivos: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve.", + "Drop to review {n} item{} for import": "Suelta para revisar {n} elemento{} antes de importar", + "Drop to import {n} item{}": "Suelta para importar {n} elemento{}", + "Drop to import {n} preset{}": "Suelta para importar {n} ajuste{0} preestablecido{0}", + "Could not read {name}: {e}": "No se pudo leer {name}: {e}", + "Added {n} photo{}": "{n} foto{0} añadida{0}", + "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", + "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 46965c7782..888af077ff 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -34,6 +34,7 @@ "Add in place": "Añadir sin mover", "Add in place: the library references the files where they are; nothing is copied or moved.": "Añadir sin mover: la biblioteca hace referencia a los archivos donde están; no se copia ni se mueve nada.", "Add keyword": "Añadir palabra clave", + "Add Keywords": "Añadir palabras clave", "Add number": "Añadir número", "Add to": "Añadir a", "Add to Album": "Añadir al álbum", @@ -228,7 +229,6 @@ "Clear Filters": "Borrar filtros", "Clear Guides": "Borrar guías", "Clear History": "Borrar historial", - "Clear Preview Cache": "Vaciar caché de vistas previas", "Clear Quick Collection": "Borrar colección rápida", "Clear Reference": "Borrar referencia", "Clear all": "Borrar todo", @@ -279,7 +279,7 @@ "Company": "Empresa", "Compare": "Comparar", "Compare (Shift+C)": "Comparar (Mayús+C)", - "Compare Before and After": "Comparar antes y después", + "Before/After Side by Side": "Antes/Después lado a lado", "Compare needs at least two photos": "Comparar requiere al menos dos fotos", "Component options": "Opciones del componente", "Compression": "Compresión", @@ -292,6 +292,8 @@ "Another library was opened since the photos were dropped: nothing was moved": "Se abrió otra biblioteca después de soltar las fotos: no se movió nada", "Settings → Confirm before moving photos to another folder on disk turns it back on": "Ajustes → Confirmar antes de mover fotos a otra carpeta del disco lo vuelve a activar", "Confirm before moving photos to another folder on disk": "Confirmar antes de mover fotos a otra carpeta del disco", + "Dialogs": "Diálogos", + "Close a dialog by clicking outside it": "Cerrar un diálogo al hacer clic fuera de él", "Constrain Crop": "Restringir recorte", "Contact Sheet PDF": "PDF de hoja de contactos", "Continue": "Continuar", @@ -960,6 +962,7 @@ "New name": "Nuevo nombre", "New time": "Nueva hora", "New…": "Nuevo…", + "Next Keyword Set": "Conjunto de palabras clave siguiente", "Next Photo": "Foto siguiente", "Night Blue": "Azul nocturno", "No": "No", @@ -1116,6 +1119,7 @@ "Preview size": "Tamaño de la vista previa", "Preview unavailable": "Vista previa no disponible", "Previews": "Vistas previas", + "Previous Keyword Set": "Conjunto de palabras clave anterior", "Previous Photo": "Foto anterior", "Print": "Imprimir", "Print…": "Imprimir…", @@ -1413,15 +1417,15 @@ "Short Edge": "Lado corto", "Show": "Mostrar", "Show All": "Mostrar todo", - "Show Clipping": "Mostrar recorte de tonos", + "Clipping": "Recorte de tonos", "Show Deghost Overlay": "Mostrar superposición de eliminación de fantasmas", "Show Hidden Local Locations": "Mostrar ubicaciones ocultas de Local", "Show Luminance Map": "Mostrar mapa de luminancia", "Show Mask": "Mostrar máscara", - "Show Mask Overlay": "Mostrar superposición de máscara", - "Show All Mask Overlays": "Mostrar todas las superposiciones de máscara", + "Mask Overlay": "Superposición de máscara", + "All Mask Overlays": "Todas las superposiciones de máscara", "Show all overlays": "Mostrar todas las superposiciones", - "Show Mask Pins": "Mostrar chinchetas de máscara", + "Mask Pins": "Chinchetas de máscara", "Show Original": "Mostrar original", "Show Person": "Mostrar persona", "Slideshow, second window, All Metadata, System Info.": "Presentación, segunda ventana, Todos los metadatos, Información del sistema.", @@ -1430,7 +1434,7 @@ "Sony ARWs from before about 2017 (RX100, RX100 II–V, RX10, NEX, SLT, ILCE-6000, A7 / A7 II / A7R II and their": "Los ARW de Sony de antes de 2017 aproximadamente (RX100, RX100 II–V, RX10, NEX, SLT, ILCE-6000, A7 / A7 II / A7R II y sus", "Sony ILCE-7M4 downsized lossless ARWs now decode subsampled YCbCr tiles into linear RGB,": "Los ARW sin pérdida reducidos de la Sony ILCE-7M4 ahora descodifican los mosaicos YCbCr submuestreados a RGB lineal,", "Sort Albums A–Z": "Ordenar álbumes A–Z", - "Show Photo Counts": "Mostrar recuento de fotos", + "Photo Counts": "Recuento de fotos", "Show Photos with Keyword": "Mostrar fotos con la palabra clave", "Show Pins": "Mostrar chinchetas", "Show Source": "Mostrar origen", @@ -2314,7 +2318,7 @@ "Reset all edits (Cmd+Shift+R)": "Restablecer todas las ediciones (Cmd+Mayús+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", "LightCraft stopped": "LightCraft se detuvo", - "Show Focus Point": "Mostrar punto de enfoque", + "Focus Point": "Punto de enfoque", "Zoom to Focus Point": "Zoom al punto de enfoque", "Focus": "Enfoque", "Focus point": "Punto de enfoque", @@ -2342,5 +2346,17 @@ "Checking the GPU…": "Comprobando la GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modelo de caras usa la GPU solo cuando una comprobación muestra que da los mismos resultados más rápido.", - "Checking the GPU for faces": "Comprobando la GPU para las caras" + "Checking the GPU for faces": "Comprobando la GPU para las caras", + "Layout Image": "Imagen de diseño", + "Detail View": "Vista de detalle", + "Edit Panel": "Panel Editar", + "Close the open dialog, then drop the files again": "Cierra el cuadro de diálogo abierto y vuelve a soltar los archivos", + "Close the open dialog to drop files here": "Cierra el cuadro de diálogo abierto para soltar archivos aquí", + "Drop to open the face model": "Suelta para abrir el modelo de caras", + "Drop to import": "Suelta para importar", + "Dropped Files": "Archivos soltados", + "Import dropped files without review": "Importar los archivos soltados sin revisión", + "An import is running": "Hay una importación en curso", + "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", + "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 698080e10d..1daab3dab9 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -102,6 +102,7 @@ "Imported {} photo{}": "Tuotuja kuvia: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Jonossa tekoälykohinanpoistoon ({ahead} edellä)…", "Insert at the cursor (also written {})": "Lisää kohdistimen kohtaan (kirjoitetaan myös {})", + "Inside: {names}": "Sisällä: {names}", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Se poistetaan {count} kuvalta{:.0}, alla olevat avainsanat mukaan lukien. Kumoa palauttaa sen.", "Keywords of {n} selected photos": "Valittujen kuvien ({n}) avainsanat", "Label Set: {name}": "Merkintäjoukko: {name}", @@ -297,5 +298,12 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "”{to}” on jo henkilö. Yhdistäminen tekee kahdesta yhden henkilön; Kumoa erottaa ne uudelleen.", "• {assumption}": "• {assumption}", "… and {more} more": "… ja {more} lisää", - "…and {more} more": "…ja {more} lisää" + "…and {more} more": "…ja {more} lisää", + "Added {n} photo{}": "Lisättyjä kuvia: {n}{:.0}", + "Could not read {name}: {e}": "Tiedostoa {name} ei voitu lukea: {e}", + "Drop to import {n} item{}": "Pudota tuodaksesi (kohteita: {n}){:.0}", + "Drop to import {n} preset{}": "Pudota tuodaksesi esiasetuksia: {n}{:.0}", + "Drop to review {n} item{} for import": "Pudota tarkistaaksesi ennen tuontia (kohteita: {n}){:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Minne Lightroom-luettelo ”{catalog}” tuodaan?", + "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff1707ac7a..e0a8c622a3 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -58,6 +58,7 @@ "Add in place": "Lisää paikalleen", "Add in place: the library references the files where they are; nothing is copied or moved.": "Lisää paikalleen: kirjasto viittaa tiedostoihin niiden nykyisessä sijainnissa; mitään ei kopioida tai siirretä.", "Add keyword": "Lisää avainsana", + "Add Keywords": "Lisää avainsanoja", "Add number": "Lisää numero", "Add text overlay": "Lisää tekstipeittokuva", "Add to": "Lisää kohteeseen", @@ -306,7 +307,6 @@ "Clear Filters": "Tyhjennä suodattimet", "Clear Guides": "Tyhjennä apuviivat", "Clear History": "Tyhjennä historia", - "Clear Preview Cache": "Tyhjennä esikatselun välimuisti", "Clear Quick Collection": "Tyhjennä pikakokoelma", "Clear Recent Libraries": "Tyhjennä viimeisimmät kirjastot", "Clear Reference": "Tyhjennä vertailukuva", @@ -372,7 +372,6 @@ "Company": "Yritys", "Compare": "Vertaa", "Compare (Shift+C)": "Vertaa (Shift+C)", - "Compare Before and After": "Vertaa ennen ja jälkeen", "Compare needs at least two photos": "Vertailu vaatii vähintään kaksi kuvaa", "Component options": "Komponentin asetukset", "Compression": "Pakkaus", @@ -1238,6 +1237,7 @@ "New…": "Uusi…", "Next Appearance Mode": "Seuraava ulkoasutila", "Next History Step": "Seuraava historiavaihe", + "Next Keyword Set": "Seuraava avainsanajoukko", "Next Photo": "Seuraava kuva", "Next Slide": "Seuraava dia", "Next page": "Seuraava sivu", @@ -1463,6 +1463,7 @@ "Preview unavailable": "Esikatselu ei käytettävissä", "Previews": "Esikatselut", "Previous History Step": "Edellinen historiavaihe", + "Previous Keyword Set": "Edellinen avainsanajoukko", "Previous Photo": "Edellinen kuva", "Previous Slide": "Edellinen dia", "Previous page": "Edellinen sivu", @@ -1822,19 +1823,13 @@ "Show": "Näytä", "Show / hide": "Näytä / piilota", "Show All": "Näytä kaikki", - "Show All Mask Overlays": "Näytä kaikki maskien peittokuvat", - "Show Clipping": "Näytä leikkautuminen", "Show Deghost Overlay": "Näytä haamukuvien poiston peittokuva", - "Show Focus Point": "Näytä tarkennuspiste", "Show Hidden Local Locations": "Näytä piilotetut paikalliset sijainnit", "Show Layout Image": "Näytä asettelukuva", "Show Luminance Map": "Näytä kirkkauskartta", "Show Mask": "Näytä maski", - "Show Mask Overlay": "Näytä maskin peittokuva", - "Show Mask Pins": "Näytä maskin nastat", "Show Original": "Näytä alkuperäinen", "Show Person": "Näytä henkilö", - "Show Photo Counts": "Näytä kuvamäärät", "Show Photos with Keyword": "Näytä kuvat, joilla on avainsana", "Show Pins": "Näytä nastat", "Show Sidebar Section": "Näytä sivupalkin osio", @@ -2284,10 +2279,12 @@ "or drop a .onnx file on the window": "tai pudota .onnx-tiedosto ikkunaan", "or drop photos and folders into this window": "tai pudota kuvia ja kansioita tähän ikkunaan", "or drop photos into this window": "tai pudota kuvia tähän ikkunaan", + "pick": "valittu kuva", "photo has its denoised picture.": "kuvalla on kohinanpoistettu kuvansa.", "photo waiting": "kuva odottaa", "photos have their denoised picture.": "kuvilla on kohinanpoistetut kuvansa.", "photos waiting": "kuvaa odottaa", + "reject": "hylätty", "saved in": "tallennettu kohteeseen", "second": "sekunti", "starts using it for AI Denoise": "alkaa käyttää sitä tekoälykohinanpoistoon", @@ -2311,5 +2308,24 @@ "− harder border · + softer border": "− terävämpi reuna · + pehmeämpi reuna", "≤ at most": "≤ enintään", "≥ at least": "≥ vähintään", - "★ Favorites": "★ Suosikit" + "★ Favorites": "★ Suosikit", + "All Mask Overlays": "Kaikki maskien peittokuvat", + "Before/After Side by Side": "Ennen/jälkeen vierekkäin", + "Clipping": "Leikkautuminen", + "Detail View": "Tarkastelunäkymä", + "Edit Panel": "Muokkauspaneeli", + "Focus Point": "Tarkennuspiste", + "Layout Image": "Asettelukuva", + "Mask Overlay": "Maskin peittokuva", + "Mask Pins": "Maskin nastat", + "Photo Counts": "Kuvamäärät", + "An import is running": "Tuonti on käynnissä", + "An import is running. Drop photos when it has finished": "Tuonti on käynnissä. Pudota kuvat, kun se on valmis", + "Close the open dialog to drop files here": "Sulje avoin valintaikkuna pudottaaksesi tiedostot tähän", + "Close the open dialog, then drop the files again": "Sulje avoin valintaikkuna ja pudota tiedostot sitten uudelleen", + "Drop to import": "Pudota tuodaksesi", + "Drop to open the face model": "Pudota avataksesi kasvomallin", + "Dropped Files": "Pudotetut tiedostot", + "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", + "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index ae2b778725..294273781e 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -51,7 +51,7 @@ "Example: {example}": "Exemple : {example}", "Exported {n} photo{}": "{n} photo{} exportée(s)", "Exported {ok} of {total} photo{}": "{ok} photo{} exportée(s) sur {total}", - "Exported {} point curve preset{}": "{} préréglage{} de courbe de points exporté(s)", + "Exported {} point curve preset{}": "{} préréglage{} de courbe à points exporté(s)", "Exported {} preset{}": "{} préréglage{} exporté(s)", "Exporting {} of {total}": "Exportation : {} sur {total}", "Filter bar — {active} active filter{}": "Barre de filtres — {active} filtre{} actif(s)", @@ -62,7 +62,7 @@ "Import cancelled · {} photo{} added": "Importation annulée · {} photo{} ajoutée(s)", "Import failed: {e}": "Échec de l’importation : {e}", "Import warnings ({n}):\n{warnings}": "Avertissements d’importation ({n}) :\n{warnings}", - "Imported {n} point curve preset{}": "{n} préréglage{} de courbe de points importé(s)", + "Imported {n} point curve preset{}": "{n} préréglage{} de courbe à points importé(s)", "Imported {n} preset{}": "{n} préréglage{} importé(s)", "Imported {n} preset{}, {f} file{} not readable": "{n} préréglage{} importé(s), {f} fichier{} illisible(s)", "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", @@ -223,6 +223,7 @@ "Delete the keyword “{name}”?": "Supprimer le mot-clé « {name} » ?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Il est retiré de {count} photo{}, avec les mots-clés qu’il contient. Annuler le rétablit.", "Create Keyword Tag Inside “{name}”…": "Créer un mot-clé dans « {name} »…", + "Inside: {names}": "À l’intérieur : {names}", "“{parent}” has a “{name}” already. Merge the two?": "« {parent} » contient déjà « {name} ». Fusionner les deux ?", "There is a “{name}” at the top level already. Merge the two?": "Il existe déjà « {name} » au premier niveau. Fusionner les deux ?", "Added “{keyword}” to {n} photo{}": "« {keyword} » ajouté à {n} photo{}", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "Déplacer {n} photo{} vers « {} »", "Move {n} photo{} to “{}”?": "Déplacer {n} photo{} vers « {} » ?", "Listing folders — folders: {folders}, files: {files}": "Liste des dossiers — dossiers : {folders}, fichiers : {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{} déplacée(s) vers « {} ». Modifier → Annuler les remet en place." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{0} déplacée{0} vers « {1} ». Modifier → Annuler les remet en place.", + "Drop to review {n} item{} for import": "Déposez pour vérifier {n} élément{} avant l'import", + "Drop to import {n} item{}": "Déposez pour importer {n} élément{}", + "Drop to import {n} preset{}": "Déposez pour importer {n} préréglage{}", + "Could not read {name}: {e}": "Impossible de lire {name} : {e}", + "Added {n} photo{}": "{n} photo{} ajoutée(s)", + "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", + "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 2f22a70c1c..3278d6ccda 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -26,7 +26,7 @@ "Add Folder to Local": "Ajouter le dossier à Local", "Add Mask": "Ajouter un masque", "Add Object Click": "Ajouter un clic sur l'objet", - "Add Point Color Sample": "Ajouter un échantillon de couleur ponctuelle", + "Add Point Color Sample": "Ajouter un échantillon de point de couleur", "Add Red Eye Correction": "Ajouter une correction des yeux rouges", "Add Remove Spot": "Ajouter une suppression de tache", "Add Selected Photos": "Ajouter les photos sélectionnées", @@ -34,6 +34,7 @@ "Add in place": "Ajouter sur place", "Add in place: the library references the files where they are; nothing is copied or moved.": "Ajouter sur place : la bibliothèque référence les fichiers là où ils se trouvent ; rien n'est copié ni déplacé.", "Add keyword": "Ajouter un mot-clé", + "Add Keywords": "Ajouter des mots-clés", "Add number": "Ajouter un numéro", "Add to": "Ajouter à", "Add to Album": "Ajouter à l'album", @@ -76,21 +77,21 @@ "Apply Color Label Set": "Appliquer un jeu d'étiquettes de couleur", "Apply Filter Preset": "Appliquer un préréglage de filtre", "Apply Metadata Preset": "Appliquer un préréglage de métadonnées", - "Apply Point Curve Preset": "Appliquer un préréglage de courbe de points", + "Apply Point Curve Preset": "Appliquer un préréglage de courbe à points", "Apply Preset": "Appliquer un préréglage", "Apply Settings JSON": "Appliquer des réglages JSON", "Approved": "Approuvée", - "Aqua": "Aigue-marine", - "Aqua Hue": "Teinte aigue-marine", - "Aqua Luminance": "Luminance aigue-marine", - "Aqua Saturation": "Saturation aigue-marine", + "Aqua": "Turquoise", + "Aqua Hue": "Teinte turquoise", + "Aqua Luminance": "Luminance turquoise", + "Aqua Saturation": "Saturation turquoise", "ArtCraft Website": "Site web d'ArtCraft", "ArtCraft — more creative apps": "ArtCraft : d'autres applications créatives", "As Shot": "Tel quel", "As shot": "Tel quel", "Ascending": "Croissant", "Aspect": "Format", - "Aspect Ratio": "Rapport d'aspect", + "Aspect Ratio": "Ratio de format", "Assisted Culling": "Tri assisté", "Assisted Culling…": "Tri assisté…", "Auto": "Auto", @@ -142,7 +143,7 @@ "Best of Similar Shots": "Meilleure des prises similaires", "Binary assets added": "Ressources binaires ajoutées", "Binary assets removed": "Ressources binaires supprimées", - "Bit depth": "Profondeur de bits", + "Bit depth": "Profondeur de couleur", "Black & White": "Noir et blanc", "Blacks": "Noirs", "Bleach Bypass": "Bleach bypass", @@ -214,7 +215,6 @@ "Clear Filters": "Effacer les filtres", "Clear Guides": "Effacer les repères", "Clear History": "Effacer l'historique", - "Clear Preview Cache": "Vider le cache des aperçus", "Clear Quick Collection": "Vider la collection rapide", "Clear Reference": "Effacer la référence", "Clear all": "Tout effacer", @@ -264,7 +264,7 @@ "Company": "Société", "Compare": "Comparer", "Compare (Shift+C)": "Comparer (Maj+C)", - "Compare Before and After": "Comparer avant et après", + "Before/After Side by Side": "Avant/Après côte à côte", "Compare needs at least two photos": "Comparer nécessite au moins deux photos", "Component options": "Options du composant", "Compression": "Compression", @@ -374,9 +374,9 @@ "Delete Permanently": "Supprimer définitivement", "Delete Photo": "Supprimer la photo", "Delete Photos": "Supprimer les photos", - "Delete Point Color": "Supprimer la couleur ponctuelle", - "Delete Point Color Sample": "Supprimer l'échantillon de couleur ponctuelle", - "Delete Point Curve Preset": "Supprimer le préréglage de courbe de points", + "Delete Point Color": "Supprimer le point de couleur", + "Delete Point Color Sample": "Supprimer l'échantillon de point de couleur", + "Delete Point Curve Preset": "Supprimer le préréglage de courbe à points", "Delete Preset": "Supprimer le préréglage", "Delete Red Eye": "Supprimer les yeux rouges", "Delete Red Eye Correction": "Supprimer la correction des yeux rouges", @@ -470,8 +470,8 @@ "Export As…": "Exporter sous…", "Export Group…": "Exporter le groupe…", "Export Now": "Exporter maintenant", - "Export Point Curve Presets": "Exporter les préréglages de courbe de points", - "Export Point Curve Presets…": "Exporter les préréglages de courbe de points…", + "Export Point Curve Presets": "Exporter les préréglages de courbe à points", + "Export Point Curve Presets…": "Exporter les préréglages de courbe à points…", "Export Presets": "Exporter les préréglages", "Export Presets…": "Exporter les préréglages…", "Export User Presets…": "Exporter les préréglages utilisateur…", @@ -602,12 +602,12 @@ "Grid Info": "Informations de la grille", "Gritty Street": "Rue brute", "Group": "Groupe", - "Group by Date: Automatic": "Regrouper par date : automatique", - "Group by Day": "Regrouper par jour", - "Group by Month": "Regrouper par mois", - "Group by Year": "Regrouper par année", - "Group by date": "Regrouper par date", - "Group into Stack": "Regrouper en pile", + "Group by Date: Automatic": "Grouper par date : automatique", + "Group by Day": "Grouper par jour", + "Group by Month": "Grouper par mois", + "Group by Year": "Grouper par année", + "Group by date": "Grouper par date", + "Group into Stack": "Grouper en pile", "Group name": "Nom du groupe", "Guided": "Guidé", "Guided Upright": "Upright guidé", @@ -664,8 +664,8 @@ "Import Lightroom Catalog…": "Importer un catalogue Lightroom…", "Import Photos": "Importer des photos", "Import Photos…": "Importer des photos…", - "Import Point Curve Presets": "Importer des préréglages de courbe de points", - "Import Point Curve Presets…": "Importer des préréglages de courbe de points…", + "Import Point Curve Presets": "Importer des préréglages de courbe à points", + "Import Point Curve Presets…": "Importer des préréglages de courbe à points…", "Import Presets": "Importer des préréglages", "Import Presets…": "Importer des préréglages…", "Import Profiles": "Importer des profils", @@ -905,6 +905,7 @@ "New name": "Nouveau nom", "New time": "Nouvelle heure", "New…": "Nouveau…", + "Next Keyword Set": "Jeu de mots-clés suivant", "Next Photo": "Photo suivante", "Night Blue": "Bleu nuit", "No": "Non", @@ -1037,10 +1038,10 @@ "Picks": "Sélectionnées", "Pictures": "Images", "Pixels": "Pixels", - "Point Color": "Couleur ponctuelle", - "Point Curve": "Courbe de points", - "Point Curve Presets": "Préréglages de courbe de points", - "Point curve": "Courbe de points", + "Point Color": "Point de couleur", + "Point Curve": "Courbe à points", + "Point Curve Presets": "Préréglages de courbe à points", + "Point curve": "Courbe à points", "Portrait": "Portrait", "Position": "Position", "Preferences": "Préférences", @@ -1060,6 +1061,7 @@ "Preview size": "Taille de l'aperçu", "Preview unavailable": "Aperçu indisponible", "Previews": "Aperçus", + "Previous Keyword Set": "Jeu de mots-clés précédent", "Previous Photo": "Photo précédente", "Print": "Imprimer", "Print…": "Imprimer…", @@ -1257,8 +1259,8 @@ "Save Metadata Preset": "Enregistrer le préréglage de métadonnées", "Save Metadata Preset…": "Enregistrer le préréglage de métadonnées…", "Save Metadata to File": "Enregistrer les métadonnées dans le fichier", - "Save Point Curve Preset": "Enregistrer le préréglage de courbe de points", - "Save Point Curve…": "Enregistrer la courbe de points…", + "Save Point Curve Preset": "Enregistrer le préréglage de courbe à points", + "Save Point Curve…": "Enregistrer la courbe à points…", "Save as Preset": "Enregistrer comme préréglage", "Save as Set…": "Enregistrer comme jeu…", "Save as Smart Album…": "Enregistrer comme album intelligent…", @@ -1308,7 +1310,7 @@ "Set Image Zoom and Pan": "Définir le zoom et le déplacement de l'image", "Set Keyboard Shortcut": "Définir le raccourci clavier", "Set Mask Adjustments": "Définir les réglages du masque", - "Set Point Curve": "Définir la courbe de points", + "Set Point Curve": "Définir la courbe à points", "Set Profile": "Définir le profil", "Set Rating": "Définir la note", "Set Top of Stack": "Définir le haut de la pile", @@ -1343,17 +1345,17 @@ "Short Edge": "Petit côté", "Show": "Afficher", "Show All": "Tout afficher", - "Show Clipping": "Afficher l'écrêtage", + "Clipping": "Écrêtage", "Show Deghost Overlay": "Afficher l'incrustation de suppression des images fantômes", "Show Hidden Local Locations": "Afficher les emplacements Local masqués", "Show Luminance Map": "Afficher la carte de luminance", "Show Mask": "Afficher le masque", - "Show Mask Overlay": "Afficher l'incrustation du masque", - "Show All Mask Overlays": "Afficher toutes les superpositions de masque", + "Mask Overlay": "Incrustation du masque", + "All Mask Overlays": "Toutes les incrustations de masque", "Show all overlays": "Afficher toutes les superpositions", - "Show Mask Pins": "Afficher les épingles de masque", + "Mask Pins": "Épingles de masque", "Show Original": "Afficher l'original", - "Show Photo Counts": "Afficher le nombre de photos", + "Photo Counts": "Nombre de photos", "Show Photos with Keyword": "Afficher les photos avec le mot-clé", "Show Pins": "Afficher les épingles", "Show Source": "Afficher la source", @@ -1458,7 +1460,7 @@ "Targeted adjustment: drag up/down on the photo to adjust the curve there": "Réglage ciblé : faites glisser vers le haut/bas sur la photo pour ajuster la courbe à cet endroit", "Teal & Amber": "Bleu-vert et ambre", "Teal & Orange": "Bleu-vert et orange", - "Temp": "Temp.", + "Temp": "Température", "Temperature": "Température", "Template": "Modèle", "Temporary session — your library isn't open, and nothing you do here is saved.": "Session temporaire : votre bibliothèque n'est pas ouverte et rien de ce que vous faites ici n'est enregistré.", @@ -1930,7 +1932,7 @@ "Finding faces": "Recherche des visages", "Synchronizing folder": "Synchronisation du dossier", "Looking for changes": "Recherche des modifications", - "Arrange Panel": "Disposer le panneau", + "Arrange Panel": "Modifier le panneau", "Close panel": "Fermer le panneau", "Float panel": "Panneau flottant", "Move to group": "Déplacer vers le groupe", @@ -1956,7 +1958,7 @@ "Perceptual": "Perceptif", "Relative": "Relatif", "Simulate Paper & Ink": "Simuler le papier et l'encre", - "Content-Aware": "Contenu pris en compte", + "Content-Aware": "Selon le contenu", "Sidebar Sections": "Sections de la barre latérale", "Reset Sidebar Sections": "Réinitialiser les sections de la barre latérale", "Hide This Section": "Masquer cette section", @@ -2249,7 +2251,7 @@ "Intro screen": "Écran d'introduction", "Ending screen": "Écran de fin", "Shows": "Affiche", - "Colour only": "Couleur seule", + "Colour only": "Couleur unie", "Override colour": "Remplacer la couleur", "Own duration (off: the slide duration)": "Durée propre (désactivée : celle des diapositives)", "Duration": "Durée", @@ -2312,7 +2314,7 @@ "Reset all edits (Cmd+Shift+R)": "Réinitialiser toutes les retouches (Cmd+Maj+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", "LightCraft stopped": "LightCraft s’est arrêté", - "Show Focus Point": "Afficher le point de mise au point", + "Focus Point": "Point de mise au point", "Zoom to Focus Point": "Zoomer sur le point de mise au point", "Focus": "Mise au point", "Focus point": "Point de mise au point", @@ -2340,5 +2342,53 @@ "Checking the GPU…": "Vérification du GPU…", "CPU": "Processeur", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modèle de visages n’utilise le GPU que si une vérification montre qu’il donne les mêmes résultats plus vite.", - "Checking the GPU for faces": "Vérification du GPU pour les visages" + "Checking the GPU for faces": "Vérification du GPU pour les visages", + "Layout Image": "Image de mise en page", + "Detail View": "Vue de détail", + "Edit Panel": "Panneau Modifier", + "Close the open dialog, then drop the files again": "Fermez la boîte de dialogue ouverte, puis déposez à nouveau les fichiers", + "Close the open dialog to drop files here": "Fermez la boîte de dialogue ouverte pour déposer des fichiers ici", + "Drop to open the face model": "Déposez pour ouvrir le modèle de visages", + "Drop to import": "Déposez pour importer", + "Dropped Files": "Fichiers déposés", + "Import dropped files without review": "Importer les fichiers déposés sans vérification", + "An import is running": "Une importation est en cours", + "An import is running. Drop photos when it has finished": "Une importation est en cours. Déposez les photos quand elle sera terminée", + "Finish Lightroom catalog import before adding photos": "Terminez l'importation du catalogue Lightroom avant d'ajouter des photos", + "The library is empty: the catalog's photos, collections and edits become its first.": "La bibliothèque est vide : les photos, collections et retouches du catalogue seront les premières.", + "The catalog's photos, collections and edits join the ones already in this library.": "Les photos, collections et retouches du catalogue rejoignent celles déjà présentes dans cette bibliothèque.", + "Create a new library": "Créer une nouvelle bibliothèque", + "LightCraft opens the new library, then imports the catalog into it. Its folder must be new or empty.": "LightCraft ouvre la nouvelle bibliothèque, puis y importe le catalogue. Son dossier doit être nouveau ou vide.", + "Don't ask again (always merge into the open library)": "Ne plus demander (toujours fusionner avec la bibliothèque ouverte)", + "To be asked again: Settings → General → When importing a Lightroom catalog.": "Pour que la question revienne : Réglages → Général → À l’importation d’un catalogue Lightroom.", + "Create Library and Import": "Créer la bibliothèque et importer", + "Another library was opened since this window appeared: nothing was imported": "Une autre bibliothèque a été ouverte depuis l’apparition de cette fenêtre : rien n’a été importé", + "When importing a Lightroom catalog": "À l’importation d’un catalogue Lightroom", + "Ask where to import it": "Demander où l’importer", + "Always merge into the open library": "Toujours fusionner avec la bibliothèque ouverte", + "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library.": "L’importation lit le catalogue sans le modifier. Ensuite, choisissez si ses photos, retouches, mots-clés et collections rejoignent la bibliothèque ouverte ou une nouvelle bibliothèque.", + "At launch": "Au lancement", + "Open the last library": "Ouvrir la dernière bibliothèque", + "Ask me": "Me demander", + "Ask me lists your recent libraries at launch. Holding Alt (Option on a Mac) as the window appears asks once.": "« Me demander » affiche vos bibliothèques récentes au lancement. Maintenir Alt (Option sur Mac) pendant que la fenêtre apparaît le demande une fois.", + "Open a Library": "Ouvrir une bibliothèque", + "Choose the library to open.": "Choisissez la bibliothèque à ouvrir.", + "No recent libraries. Open one from a folder, or make a new one.": "Aucune bibliothèque récente. Ouvrez-en une depuis un dossier, ou créez-en une nouvelle.", + "Remove from List": "Retirer de la liste", + "The library itself stays where it is.": "La bibliothèque elle-même reste où elle est.", + "Open": "Ouvrir", + "Open Another…": "Ouvrir une autre…", + "Open now": "Ouverte en ce moment", + "Last opened": "Ouverte le", + "Not found: moved, renamed or on a disconnected drive": "Introuvable : déplacée, renommée ou sur un disque déconnecté", + "There is no LightCraft library in this folder any more": "Ce dossier ne contient plus de bibliothèque LightCraft", + "This is a file, not a library folder": "C’est un fichier, pas un dossier de bibliothèque", + "This folder can't be read:": "Ce dossier ne peut pas être lu :", + "The library's catalog can't be read:": "Le catalogue de la bibliothèque ne peut pas être lu :", + "Not answering yet: the drive may be asleep or offline": "Pas encore de réponse : le disque est peut-être en veille ou hors ligne", + "This library couldn't be checked": "Impossible de vérifier cette bibliothèque", + "Checking recent libraries": "Vérification des bibliothèques récentes", + "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", + "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", + "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index b3887f9174..7fc3255221 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -297,5 +297,13 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}: resolusi penuhnya ({full}) memerlukan memori melebihi kapasitas komputer ini", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}, resolusi maksimum untuk panorama (resolusi penuhnya {full})", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "Added {n} photo{}": "{n} foto ditambahkan{:.0}", + "Could not read {name}: {e}": "Tidak dapat membaca {name}: {e}", + "Drop to import {n} item{}": "Jatuhkan untuk mengimpor {n} item{:.0}", + "Drop to import {n} preset{}": "Jatuhkan untuk mengimpor {n} preset{:.0}", + "Drop to review {n} item{} for import": "Jatuhkan untuk meninjau {n} item sebelum impor{:.0}", + "Inside: {names}": "Di dalam: {names}", + "Where should the Lightroom catalog “{catalog}” go?": "Ke mana katalog Lightroom “{catalog}” diimpor?", + "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index aefe04417a..0d6da9b8fb 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -58,6 +58,7 @@ "Add in place": "Tambahkan di lokasi asli", "Add in place: the library references the files where they are; nothing is copied or moved.": "Tambahkan di lokasi asli: pustaka merujuk file di lokasinya saat ini; tidak ada yang disalin atau dipindahkan.", "Add keyword": "Tambahkan kata kunci", + "Add Keywords": "Tambahkan kata kunci", "Add number": "Tambahkan nomor", "Add text overlay": "Tambahkan overlay teks", "Add to": "Tambahkan ke", @@ -308,7 +309,6 @@ "Clear Filters": "Hapus filter", "Clear Guides": "Hapus garis panduan", "Clear History": "Hapus riwayat", - "Clear Preview Cache": "Kosongkan cache pratinjau", "Clear Print Layout": "Kosongkan tata letak cetak", "Clear Quick Collection": "Kosongkan koleksi cepat", "Clear Recent Libraries": "Hapus daftar pustaka terbaru", @@ -372,7 +372,6 @@ "Company": "Perusahaan", "Compare": "Bandingkan", "Compare (Shift+C)": "Bandingkan (Shift+C)", - "Compare Before and After": "Bandingkan Sebelum dan Sesudah", "Compare needs at least two photos": "Perlu minimal dua foto untuk dibandingkan", "Component options": "Opsi komponen", "Compression": "Kompresi", @@ -1235,6 +1234,7 @@ "New…": "Baru…", "Next Appearance Mode": "Mode tampilan berikutnya", "Next History Step": "Langkah riwayat berikutnya", + "Next Keyword Set": "Set kata kunci berikutnya", "Next Photo": "Foto berikutnya", "Next Slide": "Slide berikutnya", "Next up for AI Denoise…": "Berikutnya dalam antrean pengurangan noise AI…", @@ -1447,6 +1447,7 @@ "Preview unavailable": "Pratinjau tidak tersedia", "Previews": "Pratinjau", "Previous History Step": "Langkah riwayat sebelumnya", + "Previous Keyword Set": "Set kata kunci sebelumnya", "Previous Photo": "Foto sebelumnya", "Previous Slide": "Slide sebelumnya", "Previous settings": "Pengaturan sebelumnya", @@ -1817,19 +1818,13 @@ "Short Edge": "Sisi pendek", "Show": "Tampilkan", "Show All": "Tampilkan semua", - "Show All Mask Overlays": "Tampilkan semua overlay masker", - "Show Clipping": "Tampilkan clipping", "Show Deghost Overlay": "Tampilkan overlay deghost", - "Show Focus Point": "Tampilkan titik fokus", "Show Hidden Local Locations": "Tampilkan lokasi Lokal yang disembunyikan", "Show Layout Image": "Tampilkan gambar tata letak", "Show Luminance Map": "Tampilkan peta luminans", "Show Mask": "Tampilkan masker", - "Show Mask Overlay": "Tampilkan overlay masker", - "Show Mask Pins": "Tampilkan pin masker", "Show Original": "Tampilkan yang asli", "Show Person": "Tampilkan orang", - "Show Photo Counts": "Tampilkan jumlah foto", "Show Photos with Keyword": "Tampilkan foto dengan kata kunci ini", "Show Pins": "Tampilkan pin", "Show Sidebar Section": "Tampilkan bagian bilah samping", @@ -2325,5 +2320,24 @@ "≤ at most": "≤ maksimal", "≥ at least": "≥ minimal", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "All Mask Overlays": "Semua overlay masker", + "Before/After Side by Side": "Sebelum/Sesudah berdampingan", + "Clipping": "Clipping", + "Detail View": "Tampilan Detail", + "Edit Panel": "Panel Edit", + "Focus Point": "Titik fokus", + "Layout Image": "Gambar tata letak", + "Mask Overlay": "Overlay masker", + "Mask Pins": "Pin masker", + "Photo Counts": "Jumlah foto", + "An import is running": "Impor sedang berjalan", + "An import is running. Drop photos when it has finished": "Impor sedang berjalan. Jatuhkan foto setelah selesai", + "Close the open dialog to drop files here": "Tutup dialog yang terbuka untuk menjatuhkan file di sini", + "Close the open dialog, then drop the files again": "Tutup dialog yang terbuka, lalu jatuhkan file lagi", + "Drop to import": "Jatuhkan untuk mengimpor", + "Drop to open the face model": "Jatuhkan untuk membuka model wajah", + "Dropped Files": "File yang dijatuhkan", + "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", + "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index ccd01e6a71..7efae90e94 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -283,6 +283,7 @@ "Delete the effect preset “{name}”?": "Eliminare il preset effetto “{name}”?", "{n} raws can now be developed from their raw data": "Raw che ora si possono sviluppare dai loro dati raw: {n}", "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Inside: {names}": "Al suo interno: {names}", "Template preview: {name}": "Anteprima del modello: {name}", "{n} photos in view · {slides} slides · {time}": "Foto nella vista: {n} · diapositive: {slides} · {time}", "Applied {name}": "{name} applicato", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "Sposta foto in “{1}” ({n}){0:.0}", "Move {n} photo{} to “{}”?": "Spostare le foto in “{1}” ({n})?{0:.0}", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Foto spostate in “{1}”: {n}{0:.0}. Modifica → Annulla le riporta indietro.", - "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}" + "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}", + "Drop to review {n} item{} for import": "Rilascia per rivedere prima dell'importazione (elementi: {n}){:.0}", + "Drop to import {n} item{}": "Rilascia per importare (elementi: {n}){:.0}", + "Drop to import {n} preset{}": "Rilascia per importare predefiniti: {n}{:.0}", + "Could not read {name}: {e}": "Impossibile leggere {name}: {e}", + "Added {n} photo{}": "Foto aggiunte: {n}{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", + "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a638c14820..e159fd47d1 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -34,6 +34,7 @@ "Add in place": "Aggiungi sul posto", "Add in place: the library references the files where they are; nothing is copied or moved.": "Aggiungi sul posto: la libreria usa i file dove si trovano; niente viene copiato o spostato.", "Add keyword": "Aggiungi parola chiave", + "Add Keywords": "Aggiungi parole chiave", "Add number": "Aggiungi numero", "Add to": "Aggiungi a", "Add to Album": "Aggiungi all'album", @@ -215,7 +216,6 @@ "Clear Filters": "Cancella filtri", "Clear Guides": "Cancella guide", "Clear History": "Cancella cronologia", - "Clear Preview Cache": "Svuota cache delle anteprime", "Clear Quick Collection": "Svuota la raccolta rapida", "Clear Reference": "Cancella riferimento", "Clear all": "Cancella tutto", @@ -266,7 +266,6 @@ "Company": "Azienda", "Compare": "Confronta", "Compare (Shift+C)": "Confronta (Maiusc+C)", - "Compare Before and After": "Confronta prima e dopo", "Compare needs at least two photos": "Per confrontare servono almeno due foto", "Component options": "Opzioni del componente", "Compression": "Compressione", @@ -909,6 +908,7 @@ "New name": "Nuovo nome", "New time": "Nuova ora", "New…": "Nuovo…", + "Next Keyword Set": "Set di parole chiave successivo", "Next Photo": "Foto successiva", "Night Blue": "Blu notte", "No": "No", @@ -1070,6 +1070,7 @@ "Preview size": "Dimensione dell'anteprima", "Preview unavailable": "Anteprima non disponibile", "Previews": "Anteprime", + "Previous Keyword Set": "Set di parole chiave precedente", "Previous Photo": "Foto precedente", "Print": "Stampa", "Print…": "Stampa…", @@ -1229,7 +1230,6 @@ "Reset all edits (Cmd+Shift+R)": "Reimposta tutte le modifiche (Cmd+Maiusc+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Gli album smart si aggiornano da soli: cambia le loro regole, oppure usa Foto → Elimina foto", "LightCraft stopped": "LightCraft si è chiuso", - "Show Focus Point": "Mostra punto di messa a fuoco", "Zoom to Focus Point": "Zoom sul punto di messa a fuoco", "Focus": "Messa a fuoco", "Focus point": "Punto di messa a fuoco", @@ -1381,17 +1381,12 @@ "Short Edge": "Lato corto", "Show": "Mostra", "Show All": "Mostra tutto", - "Show Clipping": "Mostra tagli", "Show Deghost Overlay": "Mostra sovrapposizione della rimozione fantasmi", "Show Hidden Local Locations": "Mostra le posizioni locali nascoste", "Show Luminance Map": "Mostra mappa di luminanza", "Show Mask": "Mostra maschera", - "Show Mask Overlay": "Mostra sovrapposizione maschera", - "Show All Mask Overlays": "Mostra tutte le sovrapposizioni maschera", "Show all overlays": "Mostra tutte le sovrapposizioni", - "Show Mask Pins": "Mostra i punti delle maschere", "Show Original": "Mostra originale", - "Show Photo Counts": "Mostra il numero di foto", "Show Photos with Keyword": "Mostra le foto con la parola chiave", "Show Pins": "Mostra i punti", "Show Source": "Mostra origine", @@ -2341,10 +2336,30 @@ "View Options": "Opzioni di visualizzazione", "Loupe View": "Vista lente", "Show Info Overlay": "Mostra sovrapposizione informazioni", + "Show message when loading or rendering photos": "Mostra un messaggio durante il caricamento o il rendering delle foto", "Loupe Info 1": "Info lente 1", "Loupe Info 2": "Info lente 2", "Use Defaults": "Usa predefiniti", - "Dimensions": "Dimensioni", + "Show briefly when photo changes": "Mostra brevemente al cambio di foto", "Camera & Lens": "Fotocamera e obiettivo", - "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2." + "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.", + "Before/After Side by Side": "Prima/Dopo affiancati", + "Clipping": "Tagli tonali", + "Mask Overlay": "Sovrapposizione maschera", + "Mask Pins": "Punti delle maschere", + "Photo Counts": "Numero di foto", + "Focus Point": "Punto di messa a fuoco", + "All Mask Overlays": "Tutte le sovrapposizioni maschera", + "Layout Image": "Immagine di layout", + "Detail View": "Vista dettaglio", + "Edit Panel": "Pannello Modifica", + "Close the open dialog, then drop the files again": "Chiudi la finestra di dialogo aperta, poi rilascia di nuovo i file", + "Close the open dialog to drop files here": "Chiudi la finestra di dialogo aperta per rilasciare qui i file", + "Drop to open the face model": "Rilascia per aprire il modello dei volti", + "Drop to import": "Rilascia per importare", + "Dropped Files": "File rilasciati", + "Import dropped files without review": "Importa i file rilasciati senza revisione", + "An import is running": "Un'importazione è in corso", + "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", + "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index ce56500b5e..99c14bf16d 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -227,6 +227,7 @@ "Delete the keyword “{name}”?": "キーワード「{name}」を削除しますか?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "写真{count}枚から下位のキーワードとともに削除されます。取り消すと元に戻ります。{:.0}", "Create Keyword Tag Inside “{name}”…": "「{name}」の中にキーワードタグを作成…", + "Inside: {names}": "この中: {names}", "“{parent}” has a “{name}” already. Merge the two?": "「{parent}」にはすでに「{name}」があります。統合しますか?", "There is a “{name}” at the top level already. Merge the two?": "最上位にはすでに「{name}」があります。統合しますか?", "Added “{keyword}” to {n} photo{}": "写真{n}枚に「{keyword}」を追加しました{:.0}", @@ -297,5 +298,12 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」はすでに別の人物です。まとめると1人になり、元に戻すと再び分かれます。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}合成を{mp}で追加しました:フルサイズ({full})にはこのコンピューターのメモリが足りません", "Listing folders — folders: {folders}, files: {files}": "フォルダーを一覧中 — フォルダー:{folders}、ファイル:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})", + "Drop to review {n} item{} for import": "ドロップして {n} 件を確認してから読み込み{:.0}", + "Drop to import {n} item{}": "ドロップして {n} 件を読み込み{:.0}", + "Drop to import {n} preset{}": "ドロップして {n} 件のプリセットを読み込み{:.0}", + "Could not read {name}: {e}": "{name} を読み取れませんでした: {e}", + "Added {n} photo{}": "{n}枚を追加しました{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", + "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 4c55ee4947..e1834555bd 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -35,6 +35,7 @@ "Add in place": "現在の場所から追加", "Add in place: the library references the files where they are; nothing is copied or moved.": "現在の場所のファイルを参照します。コピーや移動はしません", "Add keyword": "キーワードを追加", + "Add Keywords": "キーワードを追加", "Add number": "番号を付ける", "Add to": "追加先", "Add to Album": "アルバムに追加", @@ -215,7 +216,6 @@ "Clear Filters": "フィルターを解除", "Clear Guides": "ガイドを消去", "Clear History": "履歴を消去", - "Clear Preview Cache": "プレビューキャッシュを消去", "Clear Quick Collection": "クイックコレクションを空にする", "Clear Reference": "参照写真を解除", "Clear all": "すべて解除", @@ -260,7 +260,7 @@ "Company": "企業", "Compare": "比較", "Compare (Shift+C)": "比較(⇧C)", - "Compare Before and After": "編集前と編集後を比較", + "Before/After Side by Side": "編集前/編集後の左右表示", "Compare needs at least two photos": "比較には2枚以上の写真が必要です", "Component options": "構成要素の設定", "Compression": "圧縮", @@ -633,6 +633,7 @@ "Nested group": "入れ子のグループ", "New Album": "新しいアルバム", "New time": "新しい日時", + "Next Keyword Set": "次のキーワードセット", "Next Photo": "次の写真", "Night Blue": "ナイトブルー", "No contributor data was built into this copy.": "このビルドにはコントリビューターのデータが含まれていません", @@ -673,6 +674,7 @@ "Preview Build Progress": "プレビュー作成の進行状況", "Preview only: editing the camera's embedded JPEG": "プレビューのみ:カメラの埋め込みJPEGを編集中", "Preview unavailable": "プレビューを表示できません", + "Previous Keyword Set": "前のキーワードセット", "Previous Photo": "前の写真", "Profile Browser": "プロファイルブラウザー", "Profile Menu": "プロファイルメニュー", @@ -1289,17 +1291,17 @@ "Short Edge": "短辺", "Show": "表示", "Show All": "すべて表示", - "Show Clipping": "白飛び・黒つぶれを表示", + "Clipping": "白飛び・黒つぶれ", "Show Deghost Overlay": "ゴースト除去範囲を表示", "Show Hidden Local Locations": "非表示にしたローカルの場所を表示", "Show Luminance Map": "輝度マップを表示", "Show Mask": "マスクを表示", - "Show Mask Overlay": "マスクの重ね表示", - "Show All Mask Overlays": "すべてのマスクオーバーレイを表示", + "Mask Overlay": "マスクの重ね表示", + "All Mask Overlays": "すべてのマスクの重ね表示", "Show all overlays": "すべてのオーバーレイを表示", - "Show Mask Pins": "マスクのピンを表示", + "Mask Pins": "マスクのピン", "Show Original": "元の写真を表示", - "Show Photo Counts": "写真の枚数を表示", + "Photo Counts": "写真の枚数", "Show Photos with Keyword": "このキーワードの写真を表示", "Show Pins": "ピンを表示", "Show Source": "コピー元を表示", @@ -2314,7 +2316,7 @@ "Reset all edits (Cmd+Shift+R)": "すべての編集をリセット(⌘⇧R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", "LightCraft stopped": "LightCraftが終了しました", - "Show Focus Point": "フォーカスポイントを表示", + "Focus Point": "フォーカスポイント", "Zoom to Focus Point": "フォーカスポイントにズーム", "Focus": "フォーカス", "Focus point": "フォーカスポイント", @@ -2342,5 +2344,17 @@ "Checking the GPU…": "GPU を確認中…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "顔モデルが GPU を使うのは、同じ結果をより速く出せると確認できた場合だけです。", - "Checking the GPU for faces": "顔用の GPU を確認中" + "Checking the GPU for faces": "顔用の GPU を確認中", + "Layout Image": "レイアウト画像", + "Detail View": "詳細表示", + "Edit Panel": "編集パネル", + "Close the open dialog, then drop the files again": "開いているダイアログを閉じてから、もう一度ファイルをドロップしてください", + "Close the open dialog to drop files here": "ファイルをここにドロップするには、開いているダイアログを閉じてください", + "Drop to open the face model": "ドロップして顔モデルを開く", + "Drop to import": "ドロップして読み込み", + "Dropped Files": "ドロップしたファイル", + "Import dropped files without review": "ドロップしたファイルを確認せずに読み込む", + "An import is running": "読み込み中です", + "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", + "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index c3b48ef626..4603682618 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -268,6 +268,7 @@ "LightCraft stopped unexpectedly: {e}": "LightCraft stopped unexpectedly: {e}", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}", "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Inside: {names}": "შიგნით: {names}", "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", "Saved template {name}": "Saved template {name}", "Skipped {problem}": "Skipped {problem}", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", "Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "Drop to review {n} item{} for import": "ჩააგდეთ იმპორტამდე გადასახედად (ელემენტები: {n}){:.0}", + "Drop to import {n} item{}": "ჩააგდეთ იმპორტისთვის (ელემენტები: {n}){:.0}", + "Drop to import {n} preset{}": "ჩააგდეთ პრესეტების იმპორტისთვის: {n}{:.0}", + "Could not read {name}: {e}": "ვერ წაიკითხა {name}: {e}", + "Added {n} photo{}": "დაემატა ფოტო: {n}{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", + "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 066f2ecd25..32c4077001 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -110,6 +110,7 @@ "Add in place": "ადგილზე დამატება", "Add in place: the library references the files where they are; nothing is copied or moved.": "ადგილზე დამატება: ბიბლიოთეკა ფაილებს მათ ამჟამინდელ ადგილას მიმართავს; არაფერი კოპირდება ან გადაიტანება.", "Add keyword": "საკვანძო სიტყვის დამატება", + "Add Keywords": "საკვანძო სიტყვების დამატება", "Add number": "რიცხვის დამატება", "Add to": "დამატება:", "Add to Album": "ალბომში დამატება", @@ -373,7 +374,6 @@ "Clear Filters": "ფილტრების გასუფთავება", "Clear Guides": "დამხმარე ხაზების გასუფთავება", "Clear History": "ისტორიის გასუფთავება", - "Clear Preview Cache": "წინასწარი ხედების ქეშის გასუფთავება", "Clear Quick Collection": "სწრაფი კოლექციის გასუფთავება", "Clear Recent Libraries": "ბოლოს გახსნილი ბიბლიოთეკების სიის გასუფთავება", "Clear Reference": "ეტალონის გასუფთავება", @@ -429,7 +429,7 @@ "Company": "კომპანია", "Compare": "შედარება", "Compare (Shift+C)": "შედარება (Shift+C)", - "Compare Before and After": "მანამდე და შემდეგ შედარება", + "Before/After Side by Side": "მანამდე/შემდეგ გვერდიგვერდ", "Compare and Reference View panes say \"Rendering…\" (or that the photo can't be opened) the same way, so a": "შედარებისა და ეტალონური ხედის პანელები ასევე წერს „რენდერდება…“ (ან რომ ფოტოს გახსნა შეუძლებელია), ასე რომ", "Compare needs at least two photos": "შედარებას სულ მცირე ორი ფოტო სჭირდება", "Component options": "კომპონენტის პარამეტრები", @@ -1311,6 +1311,7 @@ "New…": "ახალი…", "Next Appearance Mode": "შემდეგი იერსახის რეჟიმი", "Next History Step": "ისტორიის შემდეგი ნაბიჯი", + "Next Keyword Set": "საკვანძო სიტყვების შემდეგი ნაკრები", "Next Photo": "შემდეგი ფოტო", "Next up for AI Denoise…": "შემდეგია AI ხმაურის მოცილების რიგში…", "Night Blue": "ღამის ლურჯი", @@ -1535,6 +1536,7 @@ "Previews": "წინასწარი ხედები", "Previews match exports on Mac screens": "წინასწარი ხედები ემთხვევა ექსპორტს Mac-ის ეკრანებზე", "Previous History Step": "ისტორიის წინა ნაბიჯი", + "Previous Keyword Set": "საკვანძო სიტყვების წინა ნაკრები", "Previous Photo": "წინა ფოტო", "Primaries (x, y)": "ძირითადი ფერები (x, y)", "Print": "ბეჭდვა", @@ -1902,17 +1904,17 @@ "Shortcuts are editable: Help ▸ Keyboard Shortcuts (⌘/) lists every command with a search box; click a shortcut and": "მალსახმობები რედაქტირებადია: დახმარება → კლავიატურის მალსახმობები (⌘/) ყველა ბრძანებას საძიებო ველით ჩამოთვლის; დაწკაპეთ მალსახმობზე და", "Show": "ჩვენება", "Show All": "ყველას ჩვენება", - "Show All Mask Overlays": "ნიღბების ყველა ზედდების ჩვენება", - "Show Clipping": "ჩამოჭრილი ტონების ჩვენება", + "All Mask Overlays": "ნიღბების ყველა ზედდება", + "Clipping": "ჩამოჭრილი ტონები", "Show Deghost Overlay": "აჩრდილების მოცილების ზედდების ჩვენება", "Show Hidden Local Locations": "დამალული ლოკალური მდებარეობების ჩვენება", "Show Luminance Map": "სიკაშკაშის რუკის ჩვენება", "Show Mask": "ნიღბის ჩვენება", - "Show Mask Overlay": "ნიღბის ზედდების ჩვენება", - "Show Mask Pins": "ნიღბის მარკერების ჩვენება", + "Mask Overlay": "ნიღბის ზედდება", + "Mask Pins": "ნიღბის მარკერები", "Show Original": "ორიგინალის ჩვენება", "Show Person": "ადამიანის ჩვენება", - "Show Photo Counts": "ფოტოების რაოდენობის ჩვენება", + "Photo Counts": "ფოტოების რაოდენობა", "Show Photos with Keyword": "საკვანძო სიტყვის მქონე ფოტოების ჩვენება", "Show Pins": "მარკერების ჩვენება", "Show Sidebar Section": "გვერდითი ზოლის სექციის ჩვენება", @@ -2719,5 +2721,18 @@ "≥ at least": "≥ არანაკლებ", "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-გადათრევა გასასწორებლად, ⇧G მართვადი Upright, ბადე გარდაქმნისას.", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "Focus Point": "ფოკუსის წერტილი", + "Layout Image": "განლაგების სურათი", + "Detail View": "დეტალური ხედი", + "Edit Panel": "რედაქტირების პანელი", + "Close the open dialog, then drop the files again": "დახურეთ გახსნილი დიალოგი და ფაილები ხელახლა ჩააგდეთ", + "Close the open dialog to drop files here": "ფაილების აქ ჩასაგდებად დახურეთ გახსნილი დიალოგი", + "Drop to open the face model": "ჩააგდეთ სახეების მოდელის გასახსნელად", + "Drop to import": "ჩააგდეთ იმპორტისთვის", + "Dropped Files": "ჩაგდებული ფაილები", + "Import dropped files without review": "ჩაგდებული ფაილების იმპორტი გადახედვის გარეშე", + "An import is running": "იმპორტი მიმდინარეობს", + "An import is running. Drop photos when it has finished": "იმპორტი მიმდინარეობს. ფოტოები ჩააგდეთ, როცა დასრულდება", + "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index e3ce316a0d..20c7f840d6 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -5,17 +5,17 @@ " · {failed} couldn't be rendered": " · nie udało się wyświetlić: {failed}", " · {skipped} skipped (file exists)": " · pominięto {skipped} (plik istnieje)", " · {} duplicate{} skipped": " · pominięte duplikaty: {}{:.0}", - " · {} failed: {}": " · {} nieudanych: {}", - " · {} moved": " · {} przeniesionych", + " · {} failed: {}": " · nieudane ({}): {}", + " · {} moved": " · przeniesione: {}", " · {} not readable": " · {} nie można odczytać", " · {} original{} left at the source": " · oryginały pozostawione w źródle: {}{:.0}", - " · {} restored from Recently Deleted": " · {} przywróconych z Ostatnio usuniętych", + " · {} restored from Recently Deleted": " · przywrócone z Ostatnio usuniętych: {}", " — not carried over: {}{}": " — nie przeniesiono: {}{}", "+{} more": "+{} więcej", ", {failed} file{} not readable": ", nieczytelne pliki: {failed}{:.0}", "; {kept} already had a location": "; {kept} miało już przypisaną lokalizację", "; {outside} outside its time range": "; {outside} poza zakresem dat", - "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}: {} PR, {} zatwierdzeń, +{} / −{} wierszy (Δ {}), +{} / −{} zasobów binarnych, {} – {}", + "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}: PR: {}, zatwierdzenia: {}, wiersze: +{} / −{} (Δ {}), zasoby binarne: +{} / −{}, {} – {}", "Add {local_n} to My Photos": "Dodaj {local_n} do Moich zdjęć", "Add {} Photo{}": "Dodaj zdjęcia: {}{:.0}", "Add {} Photo{}, restore {}": "Dodaj zdjęcia: {}{:.0}, przywróć: {}", @@ -29,12 +29,12 @@ "Already in the library: {} photo{} selected in All Photos": "Już w bibliotece — zaznaczone zdjęcia we Wszystkich zdjęciach: {}{:.0}", "Auto ({})": "Automatycznie ({})", "Auto Import: added {} photo{}": "Automatyczny import — dodane zdjęcia: {}{:.0}", - "Auto Sync: edits apply to {n} photos": "Automatyczna synchronizacja: zmiany dotyczą {n} zdjęć", + "Auto Sync: edits apply to {n} photos": "Automatyczna synchronizacja: zmiany obejmują zdjęcia ({n})", "Automatic ({} MB)": "Automatycznie ({} MB)", "Build 1:1 Previews ({scope})": "Utwórz podglądy 1:1 ({scope})", "Build Smart Previews ({scope})": "Utwórz podglądy inteligentne ({scope})", "Build Standard-Sized Previews ({scope})": "Utwórz podglądy o standardowym rozmiarze ({scope})", - "Building previews for {} photos…": "Tworzenie podglądów dla {} zdjęć…", + "Building previews for {} photos…": "Tworzenie podglądów (zdjęcia: {})…", "Click {}:1": "Kliknij {}:1", "Couldn't open the editor: {e}": "Nie można otworzyć edytora: {e}", "Create {n} Virtual Copies": "Utwórz {n} kopii wirtualnych", @@ -42,7 +42,7 @@ "Decoder: {reason}": "Dekoder: {reason}", "Delete \"{label}\"": "Usuń „{label}”", "Delete \"{label}\" (and the mask)": "Usuń „{label}” (wraz z maską)", - "Delete {n} Photos": "Usuń {n} zdjęć", + "Delete {n} Photos": "Usuń zdjęcia ({n})", "Delete “{current}”": "Usuń „{current}”", "Discard Smart Previews ({scope})": "Odrzuć podglądy inteligentne ({scope})", "Done ({what}): {done} photo{plural}": "Gotowe ({what}) — zdjęcia: {done}{plural:.0}", @@ -69,10 +69,10 @@ "Label Set: {name}": "Zestaw etykiet: {name}", "LightCraft could not open its window: {e}": "LightCraft nie mógł otworzyć okna: {e}", "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft nie mógł otworzyć okna: {e}\n\nSzczegóły znajdują się w pliku dziennika: {path}", - "Lightroom catalog inspected: {photos} photos, {collections} collections, {missing} missing": "Sprawdzono katalog Lightroom: {photos} zdjęć, {collections} kolekcji, {missing} brakujących", - "Lightroom import complete: {imported} photos added": "Import z Lightroom zakończony: dodano {imported} zdjęć", - "Lightroom import complete: {imported} photos added, {failed} failed": "Import z Lightroom zakończony: dodano {imported} zdjęć, błędów: {failed}", - "Lightroom import complete: {imported} photos added; index warning: {warning}": "Import z Lightroom zakończony: dodano {imported} zdjęć; ostrzeżenie indeksu: {warning}", + "Lightroom catalog inspected: {photos} photos, {collections} collections, {missing} missing": "Sprawdzono katalog Lightroom — zdjęcia: {photos}, kolekcje: {collections}, brakujące: {missing}", + "Lightroom import complete: {imported} photos added": "Import z Lightroom zakończony — dodane zdjęcia: {imported}", + "Lightroom import complete: {imported} photos added, {failed} failed": "Import z Lightroom zakończony — dodane zdjęcia: {imported}, błędy: {failed}", + "Lightroom import complete: {imported} photos added; index warning: {warning}": "Import z Lightroom zakończony — dodane zdjęcia: {imported}; ostrzeżenie indeksu: {warning}", "Lightroom import failed: {e}{warning}": "Import z Lightroom nieudany: {e}{warning}", "Lightroom inspection failed: {e}{warning}": "Sprawdzanie katalogu Lightroom nieudane: {e}{warning}", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT lub Apache-2.0. Czcionki: {} (OFL). Ikony: oryginalne.", @@ -89,7 +89,7 @@ "Profile: {}": "Profil: {}", "Proof Copy ({})": "Kopia próbna ({})", "Proof Preview · {}": "Podgląd próbny · {}", - "Quick Develop · {n} photos": "Szybka obróbka · {n} zdjęć", + "Quick Develop · {n} photos": "Szybka obróbka · zdjęcia: {n}", "Quick Develop: {name}": "Szybka obróbka: {name}", "Rated {}": "Ocena: {}", "Reading Lightroom catalog… {done} of {total}": "Odczytywanie katalogu Lightroom… {done} z {total}", @@ -100,7 +100,7 @@ "Remove “{}” from Favorites": "Usuń „{}” z ulubionych", "Removed from {}": "Usunięto z {}", "Removed {what} from {name}": "Usunięto {what} z {name}", - "Rename {n} Photos…": "Zmień nazwy {n} zdjęć…", + "Rename {n} Photos…": "Zmień nazwy zdjęć ({n})…", "Rename “{name}”": "Zmień nazwę „{name}”", "Renames “{from}” on {n} photo{} (keywords below it too). Use | for levels, e.g. Travel|Italy. An existing name merges the two.": "Zmienia nazwę „{from}” na zdjęciach ({n}){:.0} (także podrzędne słowa kluczowe). Rozdzielaj poziomy znakiem |, np. Podróże|Włochy. Istniejąca nazwa spowoduje scalenie.", "Rendering on the CPU: {why}": "Renderowanie na procesorze: {why}", @@ -122,7 +122,7 @@ "Version {} — a clean-room, pure-Rust photo library and raw developer.": "Wersja {} — niezależnie opracowana biblioteka zdjęć i wywoływarka RAW napisana wyłącznie w Rust.", "Version: {}": "Wersja: {}", "Virtual copy “{name}” of {of}": "Kopia wirtualna „{name}” zdjęcia {of}", - "Working on {what} for {} photos…": "Przetwarzanie {what} dla {} zdjęć…", + "Working on {what} for {} photos…": "Przetwarzanie: {what} (zdjęcia: {})…", "none (CPU rendering): {why}": "brak (renderowanie na CPU): {why}", "the {n} selected photos": "{n} zaznaczonych zdjęć", "the {} photos in view": "{} zdjęć w bieżącym widoku", @@ -132,12 +132,12 @@ "{label} Grading": "Gradacja: {label}", "{label} {d:+} on every selected photo": "{label}: {d:+} na każdym zaznaczonym zdjęciu", "{label} {index} of {n}": "{label} {index} z {n}", - "{label}, {n} photos": "{label}, {n} zdjęć", + "{label}, {n} photos": "{label}, zdjęcia: {n}", "{matching} of {t} photos": "{matching} z {t} zdjęć", - "{matching} photos": "{matching} pasujących zdjęć", + "{matching} photos": "Pasujące zdjęcia: {matching}", "{mode} spot {} of {}": "{mode}: plamka {} z {}", - "{month}": "{month}", - "{month} {year}": "{month} {year}", + "{month}": "{month:02}", + "{month} {year}": "{month:02}.{year}", "{msg} ({failed} failed)": "{msg} (nieudanych: {failed})", "{name} Label": "Etykieta {name}", "{name} Off": "{name}: wyłączone", @@ -148,8 +148,8 @@ "{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Zmiany zapisane w pamięci, ale nie na dysku ({n}){0:.0}: {e}\nLightCraft ponawia zapis automatycznie; zamknięcie programu teraz oznacza ich utratę.{1:.0}", "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Zmiany zapisane w pamięci, ale nie na dysku ({n}){:.0}: {e} — LightCraft ponowi próbę", "{n} found · {sel} selected": "Znaleziono {n} · zaznaczono {sel}", - "{n} photos": "{n} zdjęć", - "{n} photos in {} are hidden by the filters above": "{n} zdjęć w {} jest ukrytych przez powyższe filtry", + "{n} photos": "zdjęcia ({n})", + "{n} photos in {} are hidden by the filters above": "Zdjęcia w {} ukryte przez powyższe filtry: {n}", "{n} photo{}": "Zdjęcia: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "Pasujące zdjęcia: {n}{:.0} · aktualizacja automatyczna po zmianach zdjęć", "{n} photo{} now · updates automatically as photos change": "Zdjęcia teraz: {n}{:.0} · aktualizacja automatyczna po zmianach zdjęć", @@ -158,25 +158,25 @@ "{stage}… {:.0}%": "{stage}… {:.0}%", "{verb} {n} Photo{}": "{verb} (zdjęcia: {n}){:.0}", "{weekday}, {day}": "{weekday}, {day}", - "{weekday}, {day} {month} {year}": "{weekday}, {day} {month} {year}", + "{weekday}, {day} {month} {year}": "{weekday}, {day}.{month:02}.{year}", "{what} merge added": "Dodano po scaleniu: {what}", "{what} merge failed: {e}": "Scalanie nieudane: {what}: {e}", "{year}": "{year}", "{{date:…}} directives: {}": "Dyrektywy {{date:…}}: {}", "{} and higher": "{} i nowsze", - "{} contributors · {} commits": "{} współtwórców · {} zatwierdzeń", - "{} failed": "{} nieudanych", - "{} files": "{} plików", + "{} contributors · {} commits": "Współtwórcy: {} · zatwierdzenia: {}", + "{} failed": "{}: niepowodzenie", + "{} files": "Pliki: {}", "{} files and {f} folder{}": "Pliki: {}, foldery: {f}{:.0}", "{} item{}": "Elementy: {}{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} z 4 prowadnic — przeciągnij wzdłuż linii, które powinny być pionowe lub poziome.", - "{} photos": "{} zdjęć", - "{} photos · exposures {} EV": "{} zdjęć · ekspozycje {} EV", - "{} photos · {} · {:.0}° × {:.0}°": "{} zdjęć · {} · {:.0}° × {:.0}°", + "{} photos": "Zdjęcia: {}", + "{} photos · exposures {} EV": "Zdjęcia: {} · ekspozycje {} EV", + "{} photos · {} · {:.0}° × {:.0}°": "Zdjęcia: {} · {} · {:.0}° × {:.0}°", "{} photo{} not readable": "Nieczytelne zdjęcia: {}{:.0}", "{} sample{}": "Próbki: {}{:.0}", "{} sec": "{} s", - "{} spot(s) on this photo": "{} plamek na tym zdjęciu", + "{} spot(s) on this photo": "Plamki na tym zdjęciu: {}", "{} — show their photos": "{} — pokaż ich zdjęcia", "· {dups} already in the library": "· {dups} już w bibliotece", "· {n} photo{}": "· zdjęcia: {n}{:.0}", @@ -184,7 +184,7 @@ "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft nie obsługuje jeszcze tego wariantu RAW ({}). Edytujesz podgląd JPEG osadzony przez aparat, zawierający już styl obrazu aparatu (np. monochromatyczny) i balans bieli.", "Filtered: {label}": "Filtrowanie: {label}", "{n} similar photo{} · View ▸ Clear Filters to see all": "Podobne zdjęcia: {n}{:.0} · Widok → Wyczyść filtry, aby zobaczyć wszystkie", - "Moved; {} photo(s) relinked": "Przeniesiono; ponownie powiązano {} zdjęć", + "Moved; {} photo(s) relinked": "Przeniesiono; ponownie powiązane zdjęcia: {}", "{} label (click more labels to show any of them)": "{} etykieta (kliknij kolejne etykiety, aby wyświetlić dowolną z nich)", ", {} star{}": ", gwiazdki: {}{:.0}", ", {} label": ", {} etykieta", @@ -199,7 +199,7 @@ "{} MB": "{} MB", "Making the denoised picture… {}%": "Tworzenie odszumionego obrazu… {}%", "{name} · {terms}": "{name} · {terms}", - "{n} {noun}": "{n} {noun}", + "{n} {noun}": "{noun}: {n}", "Trained on: {provenance}": "Wytrenowano na: {provenance}", " · {queued} waiting": " · {queued} oczekuje", "Shows the model's terms, then downloads {} from {host}, installs it and starts using it. Nothing else is sent.": "Wyświetla warunki modelu, następnie pobiera {} z {host}, instaluje go i zaczyna używać. Żadne inne dane nie są wysyłane.", @@ -252,50 +252,58 @@ " · kept, not applied: {}": " · zachowane, niezastosowane: {}", " — kept but not applied: {}": " — zachowane, ale niezastosowane: {}", "Apply to “{mask}” on Selected Photos": "Zastosuj do „{mask}” na zaznaczonych zdjęciach", - "Delete the effect preset “{name}”?": "Usunąć ustawienie wstępne efektu „{name}”?", - "Delete these {n} effect presets?": "Usunąć te ustawienia wstępne efektów ({n})?", - "Delete {n} effect preset{}? This can't be undone.": "Usunąć ustawienia wstępne efektów ({n})?{:.0} Tej operacji nie można cofnąć.", + "Delete the effect preset “{name}”?": "Usunąć ustawienie efektu „{name}”?", + "Delete these {n} effect presets?": "Usunąć zaznaczone ustawienia efektów ({n})?", + "Delete {n} effect preset{}? This can't be undone.": "Usunąć ustawienia efektów ({n})?{:.0} Tej operacji nie można cofnąć.", "Effect: {name}": "Efekt: {name}", - "Exported {} effect preset{}": "Wyeksportowane ustawienia wstępne efektów: {}{:.0}", + "Exported {} effect preset{}": "Wyeksportowane ustawienia efektów: {}{:.0}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Zaimportowane efekty masek: {e}{:.0} (Maskowanie → Efekt)", - "Update “{name}” with Current Settings": "Aktualizuj „{name}” bieżącymi ustawieniami", - "{n} preset{}": "Ustawienia wstępne: {n}{:.0}", + "Update “{name}” with Current Settings": "Zaktualizuj „{name}” bieżącymi ustawieniami", + "{n} preset{}": "Ustawienia: {n}{:.0}", "{count} more warnings.": "Pozostałe ostrzeżenia: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Nie zaimportowano obrazów z katalogu: {skipped}. Ich rekordy w katalogu są niekompletne.", "{photos} catalog records processed; {collections} collections.": "Przetworzone rekordy katalogu: {photos}; kolekcje: {collections}.", - "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Brakujące oryginały: {missing}. Ich rekordy w katalogu są dostępne; użyj polecenia „Znajdź brakujące zdjęcia”, aby ponownie je połączyć.", - "Applied {name}": "Zastosowano: {name}", + "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Brakujące oryginały: {missing}. Ich rekordy w katalogu są dostępne; użyj polecenia Znajdź brakujące zdjęcia, aby je ponownie powiązać.", + "Applied {name}": "Zastosowano {name}", "Delete “{name}”?": "Usunąć „{name}”?", - "Updated {name}": "Zaktualizowano: {name}", + "Updated {name}": "Zaktualizowano {name}", "Exported to {path}": "Wyeksportowano do {path}", "Saved template {name}": "Zapisano szablon {name}", - "Imported {name}": "Zaimportowano: {name}", + "Imported {name}": "Zaimportowano {name}", "Skipped {problem}": "Pominięto: {problem}", "…and {more} more": "…i jeszcze {more}", "Template preview: {name}": "Podgląd szablonu: {name}", "{n} photos in view · {slides} slides · {time}": "Zdjęcia w widoku: {n} · slajdy: {slides} · {time}", "{n} pages": "Strony: {n}", "{n} JPEG files": "Pliki JPEG: {n}", - "{s} s of AV1 video": "{s} s wideo AV1", + "{s} s of AV1 video": "Wideo AV1: {s} s", "Slideshow exported: {what}": "Wyeksportowano pokaz slajdów: {what}", " · {n} skipped (could not be rendered)": " · pominięte (nie udało się wyrenderować): {n}", - "{n} raws can now be developed from their raw data": "Pliki RAW, które można teraz wywołać z danych surowych: {n}", - "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Nie udało się zapisać plików pomocniczych XMP zdjęć ({n}). Czy ich folder jest offline? LightCraft ponawia próby.", + "{n} raws can now be developed from their raw data": "Pliki RAW, które można już wywołać z danych surowych: {n}", + "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Nie udało się zapisać plików XMP dla zdjęć ({n}) — czy ich folder jest niedostępny? LightCraft ponawia próby.", "Create the keyword “{name}”": "Utwórz słowo kluczowe „{name}”", - "new, inside {parent}": "nowe, wewnątrz {parent}", + "new, inside {parent}": "nowe, w {parent}", "Keywords of {n} selected photos": "Słowa kluczowe zaznaczonych zdjęć ({n})", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Usunięto „{name}” z {n} zdjęć. Edytuj → Cofnij przywraca je.", + "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Usunięto „{name}” ze zdjęć ({n}). Edytuj → Cofnij przywraca.", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft nieoczekiwanie zakończył działanie: {e}\n\nSzczegóły są w pliku dziennika: {path}", "LightCraft stopped unexpectedly: {e}": "LightCraft nieoczekiwanie zakończył działanie: {e}", - "Renames {n} face{} across the library. The files are not changed.": "Zmienia nazwę twarzy w całej bibliotece (liczba twarzy: {n}).{:.0} Pliki nie są zmieniane.", - "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "„{to}” to już istniejąca osoba. Połączenie utworzy jedną osobę; Cofnij ponownie je rozdzieli.", - "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Dodano połączenie {what} w rozdzielczości {mp}: pełny rozmiar, {full}, wymaga więcej pamięci, niż ma ten komputer", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Dodano połączenie {what} w rozdzielczości {mp}, największej możliwej dla panoramy (pełny rozmiar to {full})", + "Renames {n} face{} across the library. The files are not changed.": "Zmienia nazwę twarzy w całej bibliotece (twarze: {n}).{:.0} Pliki nie są zmieniane.", + "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "„{to}” to już istniejąca osoba. Połączenie utworzy jedną osobę; Cofnij rozdzieli je z powrotem.", + "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Dodano scalenie {what} w rozdzielczości {mp}: pełny rozmiar, {full}, wymaga więcej pamięci, niż ma ten komputer", + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Dodano scalenie {what} w rozdzielczości {mp}, największej możliwej dla panoramy (pełny rozmiar: {full})", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Przestrzeń kolorów: Rec. 2020 {curve} (HDR AVIF)", "{n} selected photos · {pages} pages": "Zaznaczone zdjęcia: {n} · strony: {pages}", "Already in “{}”": "Już w „{}”", "Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Przeglądanie folderów — foldery: {folders}, pliki: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je.", + "Drop to review {n} item{} for import": "Upuść, aby przejrzeć przed importem (elementy: {n}){:.0}", + "Drop to import {n} item{}": "Upuść, aby zaimportować (elementy: {n}){:.0}", + "Drop to import {n} preset{}": "Upuść, aby zaimportować ustawienia wstępne: {n}{:.0}", + "Could not read {name}: {e}": "Nie można odczytać {name}: {e}", + "Added {n} photo{}": "Dodano zdjęcia: {n}{:.0}", + "Inside: {names}": "Wewnątrz: {names}", + "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", + "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index aba88ef445..adac22e62a 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -31,6 +31,7 @@ "Add in place": "Dodaj bez kopiowania plików", "Add in place: the library references the files where they are; nothing is copied or moved.": "Dodaj w miejscu: biblioteka odwołuje się do plików w ich obecnej lokalizacji; nic nie jest kopiowane ani przenoszone.", "Add keyword": "Dodaj słowo kluczowe", + "Add Keywords": "Dodaj słowa kluczowe", "Add number": "Dodaj numer", "Add to": "Dodaj do", "Add to Album": "Dodaj do albumu", @@ -210,7 +211,6 @@ "Clear Filters": "Wyczyść filtry", "Clear Guides": "Wyczyść prowadnice", "Clear History": "Wyczyść historię", - "Clear Preview Cache": "Wyczyść pamięć podręczną podglądów", "Clear Quick Collection": "Wyczyść szybką kolekcję", "Clear Reference": "Wyczyść zdjęcie referencyjne", "Clear all": "Wyczyść wszystko", @@ -260,7 +260,6 @@ "Company": "Firma", "Compare": "Porównaj", "Compare (Shift+C)": "Porównaj (Shift+C)", - "Compare Before and After": "Porównaj przed i po", "Compare needs at least two photos": "Porównanie wymaga co najmniej dwóch zdjęć", "Component options": "Opcje składnika", "Compression": "Kompresja", @@ -888,6 +887,7 @@ "New name": "Nowa nazwa", "New time": "Nowy czas", "New…": "Nowy…", + "Next Keyword Set": "Następny zestaw słów kluczowych", "Next Photo": "Następne zdjęcie", "Night Blue": "Nocny błękit", "No": "Nie", @@ -1032,6 +1032,7 @@ "Preview only": "Tylko podgląd", "Preview size": "Rozmiar podglądu", "Previews": "Podglądy", + "Previous Keyword Set": "Poprzedni zestaw słów kluczowych", "Previous Photo": "Poprzednie zdjęcie", "Print": "Drukuj", "Print…": "Drukuj…", @@ -1319,15 +1320,11 @@ "Short Edge": "Krótsza krawędź", "Show": "Pokaż", "Show All": "Pokaż wszystko", - "Show Clipping": "Pokaż prześwietlenia i niedoświetlenia", "Show Deghost Overlay": "Pokaż nakładkę usuwania duchów", "Show Hidden Local Locations": "Pokaż ukryte lokalizacje lokalne", "Show Luminance Map": "Pokaż mapę luminancji", "Show Mask": "Pokaż maskę", - "Show Mask Overlay": "Pokaż nakładkę maski", - "Show Mask Pins": "Pokaż znaczniki masek", "Show Original": "Pokaż oryginał", - "Show Photo Counts": "Pokaż liczbę zdjęć", "Show Photos with Keyword": "Pokaż zdjęcia ze słowem kluczowym", "Show Pins": "Pokaż znaczniki", "Show Source": "Pokaż źródło", @@ -1711,17 +1708,17 @@ "Use": "Użyj", "Waiting to start…": "Oczekiwanie na uruchomienie…", "Works on raw files from cameras with a standard (Bayer) sensor. Other files keep their normal noise reduction.": "Działa na plikach RAW z aparatów z typową matrycą Bayera. Pozostałe pliki zachowują zwykłe odszumianie.", - "cached picture": "obraz w pamięci podręcznej", - "cached pictures": "obrazy w pamięci podręcznej", + "cached picture": "Obrazy w pamięci podręcznej", + "cached pictures": "Obrazy w pamięci podręcznej", "commercial use allowed": "dozwolony użytek komercyjny", "in use": "w użyciu", "installed": "zainstalowano", "makes AI Denoise available": "włącza odszumianie AI", "non-commercial use only": "wyłącznie do użytku niekomercyjnego", - "photo has its denoised picture.": "zdjęcie ma już odszumioną wersję.", - "photo waiting": "zdjęcie oczekuje", - "photos have their denoised picture.": "zdjęcia mają już odszumione wersje.", - "photos waiting": "zdjęć oczekuje", + "photo has its denoised picture.": "Zdjęcia z odszumioną wersją", + "photo waiting": "Oczekujące zdjęcia", + "photos have their denoised picture.": "Zdjęcia z odszumioną wersją", + "photos waiting": "Oczekujące zdjęcia", "starts using it for AI Denoise": "rozpoczyna używanie modelu do odszumiania AI", "terms unclear": "niejasne warunki", "the graphics card": "karta graficzna", @@ -2138,7 +2135,6 @@ "Remove from favorites": "Usuń z ulubionych", "Reorder Album": "Zmień kolejność w albumie", "Reset Sidebar Sections": "Przywróć sekcje paska bocznego", - "Show All Mask Overlays": "Pokaż wszystkie nakładki masek", "Show Person": "Pokaż osobę", "Show Sidebar Section": "Pokaż sekcję paska bocznego", "Show all overlays": "Pokaż wszystkie nakładki", @@ -2236,7 +2232,6 @@ "Background Tasks": "Zadania w tle", "Cancel Background Task": "Anuluj zadanie w tle", "Select Only Active Photo": "Zaznacz tylko aktywne zdjęcie", - "Show Focus Point": "Pokaż punkt ostrości", "Zoom to Focus Point": "Powiększ do punktu ostrości", "Show in Compare": "Pokaż w porównaniu", "Increase Grid Thumbnail Size": "Zwiększ rozmiar miniatur w siatce", @@ -2269,5 +2264,24 @@ "SDR Shadows": "Cienie SDR", "SDR Whites": "Biele SDR", "SDR Clarity": "Przejrzystość SDR", - "Face Models on the GPU": "Modele twarzy przetwarzane na GPU" + "Face Models on the GPU": "Modele twarzy przetwarzane na GPU", + "Before/After Side by Side": "Przed/Po obok siebie", + "Clipping": "Prześwietlenia i niedoświetlenia", + "Mask Overlay": "Nakładka maski", + "Mask Pins": "Znaczniki masek", + "Photo Counts": "Liczba zdjęć", + "All Mask Overlays": "Wszystkie nakładki masek", + "Focus Point": "Punkt ostrości", + "Layout Image": "Obraz układu", + "Detail View": "Widok szczegółów", + "Edit Panel": "Panel Edytuj", + "Close the open dialog, then drop the files again": "Zamknij otwarte okno dialogowe, a potem upuść pliki ponownie", + "Close the open dialog to drop files here": "Zamknij otwarte okno dialogowe, aby upuścić tu pliki", + "Drop to open the face model": "Upuść, aby otworzyć model twarzy", + "Drop to import": "Upuść, aby zaimportować", + "Dropped Files": "Upuszczone pliki", + "Import dropped files without review": "Importuj upuszczone pliki bez przeglądu", + "An import is running": "Import jest w toku", + "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", + "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index bab81a3688..f17f2c0fd4 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -227,6 +227,7 @@ "Delete the keyword “{name}”?": "Excluir a palavra-chave “{name}”?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Ela é removida de {count} foto{}, com as palavras-chave abaixo dela. Desfazer a traz de volta.", "Create Keyword Tag Inside “{name}”…": "Criar palavra-chave dentro de “{name}”…", + "Inside: {names}": "Dentro: {names}", "“{parent}” has a “{name}” already. Merge the two?": "“{parent}” já tem “{name}”. Mesclar as duas?", "There is a “{name}” at the top level already. Merge the two?": "Já existe “{name}” no nível superior. Mesclar as duas?", "Added “{keyword}” to {n} photo{}": "“{keyword}” adicionada a {n} foto{}", @@ -297,5 +298,12 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” já é uma pessoa. Combiná-las deixa uma só; Desfazer as separa de novo.", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what} mesclagem adicionada em {mp}: o tamanho completo, {full}, precisa de mais memória do que este computador tem", "Listing folders — folders: {folders}, files: {files}": "Listando pastas — pastas: {folders}, arquivos: {files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})", + "Drop to review {n} item{} for import": "Solte para revisar antes de importar (itens: {n}){:.0}", + "Drop to import {n} item{}": "Solte para importar (itens: {n}){:.0}", + "Drop to import {n} preset{}": "Solte para importar predefinições: {n}{:.0}", + "Could not read {name}: {e}": "Não foi possível ler {name}: {e}", + "Added {n} photo{}": "{n} foto{0} adicionada{0}", + "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", + "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 5b4ae44096..e84fb7615b 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -36,6 +36,7 @@ "Add in place": "Adicionar no local", "Add in place: the library references the files where they are; nothing is copied or moved.": "Adicionar no local: a biblioteca referencia os arquivos onde eles estão; nada é copiado nem movido.", "Add keyword": "Adicionar palavra-chave", + "Add Keywords": "Adicionar palavras-chave", "Add number": "Adicionar número", "Add to": "Adicionar a", "Add to Album": "Adicionar ao álbum", @@ -221,7 +222,6 @@ "Clear Filters": "Limpar filtros", "Clear Guides": "Limpar guias", "Clear History": "Limpar histórico", - "Clear Preview Cache": "Limpar cache de prévias", "Clear Quick Collection": "Limpar coleção rápida", "Clear Reference": "Limpar referência", "Clear all": "Limpar tudo", @@ -272,7 +272,7 @@ "Company": "Empresa", "Compare": "Comparar", "Compare (Shift+C)": "Comparar (Shift+C)", - "Compare Before and After": "Comparar antes e depois", + "Before/After Side by Side": "Antes/Depois lado a lado", "Compare needs at least two photos": "A comparação requer pelo menos duas fotos", "Component options": "Opções do componente", "Compression": "Compressão", @@ -917,6 +917,7 @@ "New name": "Novo nome", "New time": "Novo horário", "New…": "Novo…", + "Next Keyword Set": "Próximo conjunto de palavras-chave", "Next Photo": "Próxima foto", "Night Blue": "Azul noturno", "No": "Não", @@ -1078,6 +1079,7 @@ "Preview size": "Tamanho da pré-visualização", "Preview unavailable": "Prévia indisponível", "Previews": "Pré-visualizações", + "Previous Keyword Set": "Conjunto de palavras-chave anterior", "Previous Photo": "Foto anterior", "Print": "Imprimir", "Print…": "Imprimir…", @@ -1366,17 +1368,17 @@ "Short Edge": "Aresta curta", "Show": "Mostrar", "Show All": "Mostrar tudo", - "Show Clipping": "Mostrar recorte de tons", + "Clipping": "Recorte de tons", "Show Deghost Overlay": "Mostrar sobreposição de remoção de fantasma", "Show Hidden Local Locations": "Mostrar locais ocultos de Local", "Show Luminance Map": "Mostrar mapa de luminância", "Show Mask": "Mostrar máscara", - "Show Mask Overlay": "Mostrar sobreposição da máscara", - "Show All Mask Overlays": "Mostrar todas as sobreposições de máscara", + "Mask Overlay": "Sobreposição da máscara", + "All Mask Overlays": "Todas as sobreposições de máscara", "Show all overlays": "Mostrar todas as sobreposições", - "Show Mask Pins": "Mostrar pinos da máscara", + "Mask Pins": "Pinos da máscara", "Show Original": "Mostrar original", - "Show Photo Counts": "Mostrar contagem de fotos", + "Photo Counts": "Contagem de fotos", "Show Photos with Keyword": "Mostrar fotos com a palavra-chave", "Show Pins": "Mostrar pinos", "Show Source": "Mostrar origem", @@ -2154,7 +2156,7 @@ "Reset all edits (Cmd+Shift+R)": "Redefinir todas as edições (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", "LightCraft stopped": "O LightCraft parou", - "Show Focus Point": "Mostrar ponto de foco", + "Focus Point": "Ponto de foco", "Zoom to Focus Point": "Zoom no ponto de foco", "Focus": "Foco", "Focus point": "Ponto de foco", @@ -2188,5 +2190,17 @@ "Color Overlay on B&W": "Sobreposição de cor em P&B", "Image on Black": "Imagem sobre preto", "Image on White": "Imagem sobre branco", - "White on Black": "Branco sobre preto" + "White on Black": "Branco sobre preto", + "Layout Image": "Imagem de layout", + "Detail View": "Exibição de detalhe", + "Edit Panel": "Painel Editar", + "Close the open dialog, then drop the files again": "Feche a caixa de diálogo aberta e solte os arquivos novamente", + "Close the open dialog to drop files here": "Feche a caixa de diálogo aberta para soltar arquivos aqui", + "Drop to open the face model": "Solte para abrir o modelo de rostos", + "Drop to import": "Solte para importar", + "Dropped Files": "Arquivos soltos", + "Import dropped files without review": "Importar arquivos soltos sem revisão", + "An import is running": "Uma importação está em andamento", + "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", + "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 1efc30268e..76b7af4276 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -223,6 +223,7 @@ "Delete the keyword “{name}”?": "Удалить ключевое слово «{name}»?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Оно будет снято с фото ({count}){:.0} вместе с вложенными ключевыми словами. Отмена вернёт его.", "Create Keyword Tag Inside “{name}”…": "Создать ключевое слово в «{name}»…", + "Inside: {names}": "Внутри: {names}", "“{parent}” has a “{name}” already. Merge the two?": "В «{parent}» уже есть «{name}». Объединить их?", "There is a “{name}” at the top level already. Merge the two?": "На верхнем уровне уже есть «{name}». Объединить их?", "Added “{keyword}” to {n} photo{}": "«{keyword}» добавлено к фото ({n}){:.0}", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "Переместить в «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Переместить в «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Просмотр папок — папок: {folders}, файлов: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их.", + "Drop to review {n} item{} for import": "Отпустите для проверки перед импортом (элементов: {n}){:.0}", + "Drop to import {n} item{}": "Отпустите для импорта (элементов: {n}){:.0}", + "Drop to import {n} preset{}": "Отпустите для импорта пресетов: {n}{:.0}", + "Could not read {name}: {e}": "Не удалось прочитать {name}: {e}", + "Added {n} photo{}": "Добавлено фото: {n}{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", + "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index bf191bb515..306804df04 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -20,6 +20,7 @@ "Add in place": "Добавить на месте", "Add in place: the library references the files where they are; nothing is copied or moved.": "Добавить на месте: библиотека ссылается на файлы там, где они лежат; ничего не копируется и не перемещается.", "Add keyword": "Добавить ключевое слово", + "Add Keywords": "Добавить ключевые слова", "Add number": "Добавить номер", "Add to": "Добавить в", "Add to Album": "Добавить в альбом", @@ -181,7 +182,6 @@ "Clear Filters": "Сбросить фильтры", "Clear Guides": "Убрать направляющие", "Clear History": "Очистить историю", - "Clear Preview Cache": "Очистить кэш просмотров", "Clear Quick Collection": "Очистить быструю коллекцию", "Clear Reference": "Убрать эталон", "Clear all": "Очистить всё", @@ -223,7 +223,7 @@ "Comments panel": "Панель комментариев", "Compare": "Сравнение", "Compare (Shift+C)": "Сравнение (Shift+C)", - "Compare Before and After": "Сравнить «до» и «после»", + "Before/After Side by Side": "До/после рядом", "Compare needs at least two photos": "Для сравнения нужно минимум два фото", "Component options": "Параметры компонента", "Compression": "Сжатие", @@ -761,6 +761,7 @@ "New blank PDF": "Новый пустой PDF", "New name": "Новое имя", "New…": "Новый…", + "Next Keyword Set": "Следующий набор ключевых слов", "Next Photo": "Следующее фото", "Night Blue": "Ночной синий", "No": "Нет", @@ -898,6 +899,7 @@ "Preview size": "Размер просмотра", "Preview unavailable": "Просмотр недоступен", "Previews": "Просмотры", + "Previous Keyword Set": "Предыдущий набор ключевых слов", "Previous Photo": "Предыдущее фото", "Print": "Печать", "Print…": "Печать…", @@ -1134,17 +1136,17 @@ "Sharpness": "Резкость", "Short Edge": "Короткая сторона", "Show All": "Показать все", - "Show Clipping": "Показать отсечение", + "Clipping": "Отсечение", "Show Deghost Overlay": "Показать наложение удаления артефактов", "Show Hidden Local Locations": "Показать скрытые места в «Локальном»", "Show Luminance Map": "Показать карту яркости", "Show Mask": "Показать маску", - "Show Mask Overlay": "Показать наложение маски", - "Show All Mask Overlays": "Показать все наложения масок", + "Mask Overlay": "Наложение маски", + "All Mask Overlays": "Все наложения масок", "Show all overlays": "Показать все наложения", - "Show Mask Pins": "Показать булавки масок", + "Mask Pins": "Булавки масок", "Show Original": "Показать оригинал", - "Show Photo Counts": "Показывать количество фото", + "Photo Counts": "Количество фото", "Show Photos with Keyword": "Показать фото с ключевым словом", "Show Pins": "Показать булавки", "Show Source": "Показать источник", @@ -2307,7 +2309,7 @@ "Reset all edits (Cmd+Shift+R)": "Сбросить все правки (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", "LightCraft stopped": "LightCraft остановился", - "Show Focus Point": "Показать точку фокусировки", + "Focus Point": "Точка фокусировки", "Zoom to Focus Point": "Увеличить по точке фокусировки", "Focus": "Фокус", "Focus point": "Точка фокусировки", @@ -2335,5 +2337,17 @@ "Checking the GPU…": "Проверка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель лиц использует ГП, только если проверка показала, что он даёт те же результаты быстрее.", - "Checking the GPU for faces": "Проверка ГП для лиц" + "Checking the GPU for faces": "Проверка ГП для лиц", + "Layout Image": "Изображение макета", + "Detail View": "Режим детализации", + "Edit Panel": "Панель «Правка»", + "Close the open dialog, then drop the files again": "Закройте открытое окно и перетащите файлы ещё раз", + "Close the open dialog to drop files here": "Закройте открытое окно, чтобы перетащить сюда файлы", + "Drop to open the face model": "Отпустите, чтобы открыть модель лиц", + "Drop to import": "Отпустите для импорта", + "Dropped Files": "Перетащенные файлы", + "Import dropped files without review": "Импортировать перетащенные файлы без проверки", + "An import is running": "Импорт уже выполняется", + "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", + "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 50e3fa4be0..9a71a0288c 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -297,5 +297,13 @@ "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "Added {n} photo{}": "{n} foto tillagda{:.0}", + "Could not read {name}: {e}": "Kunde inte läsa {name}: {e}", + "Drop to import {n} item{}": "Släpp för att importera {n} objekt{:.0}", + "Drop to import {n} preset{}": "Släpp för att importera {n} förinställningar{:.0}", + "Drop to review {n} item{} for import": "Släpp för att granska {n} objekt före import{:.0}", + "Inside: {names}": "Inuti: {names}", + "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", + "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 76f08c2d38..66e69b7ba5 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -60,6 +60,7 @@ "Add in place": "Lägg till på plats", "Add in place: the library references the files where they are; nothing is copied or moved.": "Lägg till på plats: biblioteket refererar till filerna där de ligger; ingenting kopieras eller flyttas.", "Add keyword": "Lägg till nyckelord", + "Add Keywords": "Lägg till nyckelord", "Add Mask": "Lägg till mask", "Add number": "Lägg till nummer", "Add Object Click": "Lägg till objektklick", @@ -350,7 +351,6 @@ "Clear form": "Rensa formulär", "Clear Guides": "Rensa stödlinjer", "Clear History": "Rensa historiken", - "Clear Preview Cache": "Rensa förhandsgranskningscache", "Clear Quick Collection": "Rensa snabbsamling", "Clear rating": "Rensa betyg", "Clear rating and advance": "Rensa betyg och gå vidare", @@ -416,7 +416,6 @@ "Company": "Företag", "Compare": "Jämför", "Compare (Shift+C)": "Jämför (Shift+C)", - "Compare Before and After": "Jämför före och efter", "Compare needs at least two photos": "Jämförelse kräver minst två foton", "Component options": "Komponentalternativ", "Compressed Nikon NEFs (lossless and lossy compressed, 12- and 14-bit — e.g. D3200, D5100, D7000, D750, D850, Z 50)": "Komprimerade Nikon-NEF (förlustfritt och förstörande komprimerade, 12 och 14 bitar – t.ex. D3200, D5100, D7000, D750, D850, Z 50)", @@ -1364,6 +1363,7 @@ "New…": "Ny…", "Next Appearance Mode": "Nästa utseendeläge", "Next page": "Nästa sida", + "Next Keyword Set": "Nästa nyckelordsuppsättning", "Next Photo": "Nästa foto", "Next up for AI Denoise…": "Näst i tur för AI-brusreducering…", "Night Blue": "Nattblå", @@ -1601,6 +1601,7 @@ "Previews": "Förhandsgranskningar", "previews": "förhandsgranskningar", "Previous page": "Föregående sida", + "Previous Keyword Set": "Föregående nyckelordsuppsättning", "Previous Photo": "Föregående foto", "Previous settings": "Föregående inställningar", "Primaries (x, y)": "Primärfärger (x, y)", @@ -1975,9 +1976,7 @@ "Show": "Visa", "Show / hide": "Visa/dölj", "Show All": "Visa alla", - "Show All Mask Overlays": "Visa alla masköverlägg", "Show all overlays": "Visa alla överlägg", - "Show Clipping": "Visa klippning", "Show commands without a shortcut": "Visa kommandon utan kortkommando", "Show Deghost Overlay": "Visa överlägg för spökborttagning", "Show destination gamut warning": "Visa färgomfångsvarning för målet", @@ -1996,13 +1995,10 @@ "Show Luminance Map": "Visa luminanskarta", "Show Mask": "Visa mask", "Show mask": "Visa mask", - "Show Mask Overlay": "Visa masköverlägg", - "Show Mask Pins": "Visa masknålar", "Show on Map": "Visa på kartan", "Show Original": "Visa original", "Show overlay (O)": "Visa överlägg (O)", "Show Person": "Visa person", - "Show Photo Counts": "Visa antal foton", "Show photos": "Visa foton", "Show Photos with Keyword": "Visa foton med nyckelordet", "Show Pins": "Visa nålar", @@ -2414,5 +2410,24 @@ "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-dra för att räta upp, ⇧G guidad upprätning, ett rutnät under transformering.", "★ Favorites": "★ Favoriter", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "All Mask Overlays": "Alla masköverlägg", + "Before/After Side by Side": "Före/efter sida vid sida", + "Clipping": "Klippning", + "Detail View": "Detaljvy", + "Edit Panel": "Redigeringspanel", + "Focus Point": "Fokuspunkt", + "Layout Image": "Layoutbild", + "Mask Overlay": "Masköverlägg", + "Mask Pins": "Masknålar", + "Photo Counts": "Antal foton", + "An import is running": "En import pågår", + "An import is running. Drop photos when it has finished": "En import pågår. Släpp fotona när den är klar", + "Close the open dialog to drop files here": "Stäng den öppna dialogrutan för att släppa filer här", + "Close the open dialog, then drop the files again": "Stäng den öppna dialogrutan och släpp sedan filerna igen", + "Drop to import": "Släpp för att importera", + "Drop to open the face model": "Släpp för att öppna ansiktsmodellen", + "Dropped Files": "Släppta filer", + "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", + "Import dropped files without review": "Importera släppta filer utan granskning" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 0ada44e080..36022ac1a2 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -223,6 +223,7 @@ "Delete the keyword “{name}”?": "Видалити ключове слово «{name}»?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Його буде знято з фото (кількість: {count}{:.0}) разом із вкладеними ключовими словами. Скасування поверне його.", "Create Keyword Tag Inside “{name}”…": "Створити ключове слово в «{name}»…", + "Inside: {names}": "Усередині: {names}", "“{parent}” has a “{name}” already. Merge the two?": "«{parent}» уже містить «{name}». Об’єднати їх?", "There is a “{name}” at the top level already. Merge the two?": "На верхньому рівні вже є «{name}». Об’єднати їх?", "Added “{keyword}” to {n} photo{}": "«{keyword}» додано до фото: {n}{:.0}", @@ -297,5 +298,12 @@ "Move {n} photo{} to “{}”": "Перемістити до «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Перемістити до «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Перегляд тек — тек: {folders}, файлів: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх.", + "Drop to review {n} item{} for import": "Відпустіть для перегляду перед імпортом (елементів: {n}){:.0}", + "Drop to import {n} item{}": "Відпустіть для імпорту (елементів: {n}){:.0}", + "Drop to import {n} preset{}": "Відпустіть для імпорту наборів налаштувань: {n}{:.0}", + "Could not read {name}: {e}": "Не вдалося прочитати {name}: {e}", + "Added {n} photo{}": "Додано фото: {n}{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", + "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 4dff39f784..ee694ed4fe 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -389,6 +389,7 @@ "Add in place": "Додати на місці", "Add in place: the library references the files where they are; nothing is copied or moved.": "Додати на місці: бібліотека посилається на файли в їхньому розташуванні; нічого не копіюється й не переміщується.", "Add keyword": "Додати ключове слово", + "Add Keywords": "Додати ключові слова", "Add number": "Додати число", "Add to Album": "Додати до альбому", "Add to Favorites": "Додати до улюблених", @@ -533,7 +534,6 @@ "Clean Studio": "Чиста студія", "Clear Cache": "Очистити кеш", "Clear Filters": "Скинути фільтри", - "Clear Preview Cache": "Очистити кеш переглядів", "Clear Quick Collection": "Очистити швидку колекцію", "Clear Reference": "Очистити еталон", "Clear all": "Очистити все", @@ -562,7 +562,7 @@ "Command Journal": "Журнал команд", "Compare": "Порівняти", "Compare (Shift+C)": "Порівняти (Shift+C)", - "Compare Before and After": "Порівняти до й після", + "Before/After Side by Side": "До/після поруч", "Compare needs at least two photos": "Для порівняння потрібно щонайменше два фото", "Component options": "Параметри компонента", "Concrete Cool": "Холодний бетон", @@ -856,6 +856,7 @@ "Nested group": "Вкладена група", "New Album": "Новий альбом", "New time": "Новий час", + "Next Keyword Set": "Наступний набір ключових слів", "Next Photo": "Наступне фото", "Night Blue": "Нічна синява", "No named people in these photos": "На цих фото немає людей з іменами", @@ -888,6 +889,7 @@ "Presets and profiles": "Набори налаштувань і профілі", "Preview Build Progress": "Перебіг створення переглядів", "Preview only: editing the camera's embedded JPEG": "Лише перегляд: редагування вбудованого JPEG камери", + "Previous Keyword Set": "Попередній набір ключових слів", "Previous Photo": "Попереднє фото", "Profile Browser": "Оглядач профілів", "Profile Menu": "Меню профілів", @@ -1360,16 +1362,16 @@ "Shadows split": "Розділення тіней", "Shift by": "Зсунути на", "Short Edge": "Короткий край", - "Show Clipping": "Показати відсікання", + "Clipping": "Відсікання", "Show Deghost Overlay": "Показати накладання усунення двоїння", "Show Hidden Local Locations": "Показати приховані локальні розташування", "Show Luminance Map": "Показати карту яскравості", - "Show Mask Overlay": "Показати накладання маски", - "Show All Mask Overlays": "Показати всі накладення масок", + "Mask Overlay": "Накладання маски", + "All Mask Overlays": "Усі накладання масок", "Show all overlays": "Показати всі накладення", - "Show Mask Pins": "Показати маркери масок", + "Mask Pins": "Маркери масок", "Show Original": "Показати оригінал", - "Show Photo Counts": "Показати кількість фото", + "Photo Counts": "Кількість фото", "Show Photos with Keyword": "Показати фото з ключовим словом", "Show Pins": "Показати маркери", "Show Source": "Показати джерело", @@ -2312,7 +2314,7 @@ "Reset all edits (Cmd+Shift+R)": "Скинути всі зміни (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", "LightCraft stopped": "LightCraft зупинився", - "Show Focus Point": "Показати точку фокусування", + "Focus Point": "Точка фокусування", "Zoom to Focus Point": "Збільшити до точки фокусування", "Focus": "Фокус", "Focus point": "Точка фокусування", @@ -2340,5 +2342,17 @@ "Checking the GPU…": "Перевірка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель облич використовує ГП, лише якщо перевірка показала, що він дає ті самі результати швидше.", - "Checking the GPU for faces": "Перевірка ГП для облич" + "Checking the GPU for faces": "Перевірка ГП для облич", + "Layout Image": "Зображення макета", + "Detail View": "Детальне подання", + "Edit Panel": "Панель «Редагування»", + "Close the open dialog, then drop the files again": "Закрийте відкрите вікно та перетягніть файли ще раз", + "Close the open dialog to drop files here": "Закрийте відкрите вікно, щоб перетягнути сюди файли", + "Drop to open the face model": "Відпустіть, щоб відкрити модель облич", + "Drop to import": "Відпустіть для імпорту", + "Dropped Files": "Перетягнуті файли", + "Import dropped files without review": "Імпортувати перетягнуті файли без перегляду", + "An import is running": "Імпорт уже виконується", + "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", + "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 9ff8ed6b99..d5e28bff06 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -102,6 +102,7 @@ "Imported {} photo{}": "Đã nhập {} ảnh{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Đang xếp hàng Khử nhiễu AI (trước bạn: {ahead})…", "Insert at the cursor (also written {})": "Chèn tại con trỏ (cũng ghi là {})", + "Inside: {names}": "Bên trong: {names}", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "Sẽ gỡ khỏi {count} ảnh{:.0}, kèm từ khóa con. Hoàn tác sẽ khôi phục.", "Keywords of {n} selected photos": "Keywords of {n} selected photos", "Label Set: {name}": "Bộ nhãn: {name}", @@ -297,5 +298,12 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” is already a person. Combining them makes one person; Undo separates them again.", "• {assumption}": "• {assumption}", "… and {more} more": "… và {more} nữa", - "…and {more} more": "…and {more} more" + "…and {more} more": "…and {more} more", + "Added {n} photo{}": "Đã thêm {n} ảnh{:.0}", + "Could not read {name}: {e}": "Không thể đọc {name}: {e}", + "Drop to import {n} item{}": "Thả để nhập {n} mục{:.0}", + "Drop to import {n} preset{}": "Thả để nhập {n} thiết lập sẵn{:.0}", + "Drop to review {n} item{} for import": "Thả để xem lại {n} mục trước khi nhập{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Nhập danh mục Lightroom «{catalog}» vào đâu?", + "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 6908be70e1..e4fb8feb81 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -60,6 +60,7 @@ "Add in place": "Thêm tại chỗ", "Add in place: the library references the files where they are; nothing is copied or moved.": "Thêm tại chỗ: thư viện tham chiếu tệp ở vị trí hiện tại; không sao chép hay di chuyển gì.", "Add keyword": "Thêm từ khóa", + "Add Keywords": "Thêm từ khóa", "Add number": "Thêm số", "Add to": "Thêm vào", "Add to Album": "Thêm vào album", @@ -288,7 +289,6 @@ "Clear Filters": "Xóa bộ lọc", "Clear Guides": "Xóa đường dẫn", "Clear History": "Xóa lịch sử", - "Clear Preview Cache": "Xóa bộ nhớ đệm xem trước", "Clear Quick Collection": "Xóa Bộ sưu tập nhanh", "Clear Recent Libraries": "Xóa thư viện gần đây", "Clear Reference": "Xóa tham chiếu", @@ -342,7 +342,6 @@ "Company": "Công ty", "Compare": "So sánh", "Compare (Shift+C)": "So sánh (Shift+C)", - "Compare Before and After": "So sánh Trước và Sau", "Compare needs at least two photos": "So sánh cần ít nhất hai ảnh", "Component options": "Tùy chọn thành phần", "Compressed Nikon NEFs (lossless and lossy compressed, 12- and 14-bit — e.g. D3200, D5100, D7000, D750, D850, Z 50)": "Nikon NEF nén (nén không mất và có mất, 12 và 14 bit — ví dụ D3200, D5100, D7000, D750, D850, Z 50)", @@ -1138,6 +1137,7 @@ "New…": "Mới…", "Next Appearance Mode": "Chế độ giao diện tiếp theo", "Next History Step": "Bước lịch sử sau", + "Next Keyword Set": "Bộ từ khóa tiếp theo", "Next Photo": "Ảnh tiếp theo", "Next up for AI Denoise…": "Tiếp theo cho AI Khử nhiễu…", "Night Blue": "Xanh đêm", @@ -1340,6 +1340,7 @@ "Preview unavailable": "Không có xem trước", "Previews": "Xem trước", "Previous History Step": "Bước lịch sử trước", + "Previous Keyword Set": "Bộ từ khóa trước", "Previous Photo": "Ảnh trước", "Primaries (x, y)": "Màu gốc (x, y)", "Print": "In", @@ -1676,17 +1677,12 @@ "Short Edge": "Cạnh ngắn", "Show": "Hiện", "Show All": "Hiện tất cả", - "Show All Mask Overlays": "Hiện mọi lớp phủ mặt nạ", - "Show Clipping": "Hiện vùng cắt tông", "Show Deghost Overlay": "Hiện lớp phủ deghost", "Show Hidden Local Locations": "Hiện vị trí Local đã ẩn", "Show Luminance Map": "Hiện bản đồ độ sáng", "Show Mask": "Hiện mặt nạ", - "Show Mask Overlay": "Hiện lớp phủ mặt nạ", - "Show Mask Pins": "Hiện ghim mặt nạ", "Show Original": "Hiện bản gốc", "Show Person": "Hiện người", - "Show Photo Counts": "Hiện số lượng ảnh", "Show Photos with Keyword": "Hiện ảnh có từ khóa", "Show Pins": "Hiện ghim", "Show Sidebar Section": "Hiện mục thanh bên", @@ -2220,5 +2216,24 @@ "≥ at least": "≥ tối thiểu", "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Chỉnh thẳng có hướng dẫn, lưới khi biến đổi.", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "All Mask Overlays": "Mọi lớp phủ mặt nạ", + "Before/After Side by Side": "Trước/Sau cạnh nhau", + "Clipping": "Vùng cắt tông", + "Detail View": "Chế độ xem chi tiết", + "Edit Panel": "Bảng Chỉnh sửa", + "Focus Point": "Điểm lấy nét", + "Layout Image": "Ảnh bố cục", + "Mask Overlay": "Lớp phủ mặt nạ", + "Mask Pins": "Ghim mặt nạ", + "Photo Counts": "Số lượng ảnh", + "An import is running": "Đang có một lần nhập chạy", + "An import is running. Drop photos when it has finished": "Đang có một lần nhập chạy. Hãy thả ảnh khi nó hoàn tất", + "Close the open dialog to drop files here": "Hãy đóng hộp thoại đang mở để thả tệp vào đây", + "Close the open dialog, then drop the files again": "Hãy đóng hộp thoại đang mở, rồi thả lại các tệp", + "Drop to import": "Thả để nhập", + "Drop to open the face model": "Thả để mở mô hình khuôn mặt", + "Dropped Files": "Tệp đã thả", + "Finish Lightroom catalog import before adding photos": "Hoàn tất nhập danh mục Lightroom trước khi thêm ảnh", + "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index a28b07d2c8..7406c39b86 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -227,6 +227,7 @@ "Delete the keyword “{name}”?": "要删除关键字“{name}”吗?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "将从 {count} 张照片中移除,其下的关键字也一并移除。撤销可恢复。{:.0}", "Create Keyword Tag Inside “{name}”…": "在“{name}”中创建关键字标记…", + "Inside: {names}": "其中:{names}", "“{parent}” has a “{name}” already. Merge the two?": "“{parent}”中已有“{name}”。要合并两者吗?", "There is a “{name}” at the top level already. Merge the two?": "顶层已有“{name}”。要合并两者吗?", "Added “{keyword}” to {n} photo{}": "已将“{keyword}”添加到 {n} 张照片{:.0}", @@ -297,5 +298,12 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}”已经是另一个人。合并后成为一个人;撤销会再把他们分开。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已添加 {what} 合并({mp}):完整尺寸({full})所需的内存超出了这台电脑的内存", "Listing folders — folders: {folders}, files: {files}": "正在列出文件夹 — 文件夹:{folders},文件:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})", + "Drop to review {n} item{} for import": "松开鼠标以在导入前检查 {n} 个项目{:.0}", + "Drop to import {n} item{}": "松开鼠标以导入 {n} 个项目{:.0}", + "Drop to import {n} preset{}": "松开鼠标以导入 {n} 个预设{:.0}", + "Could not read {name}: {e}": "无法读取 {name}:{e}", + "Added {n} photo{}": "已添加 {n} 张照片{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", + "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 4a2ebaa7b1..270af8a625 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -36,6 +36,7 @@ "Add in place": "在原位置添加", "Add in place: the library references the files where they are; nothing is copied or moved.": "在原位置添加:图库直接引用文件所在位置;不会复制或移动任何内容。", "Add keyword": "添加关键字", + "Add Keywords": "添加关键字", "Add number": "添加编号", "Add to": "添加到", "Add to Album": "添加到相册", @@ -220,7 +221,6 @@ "Clear Filters": "清除过滤器", "Clear Guides": "清除参考线", "Clear History": "清除历史记录", - "Clear Preview Cache": "清除预览缓存", "Clear Quick Collection": "清空快速集合", "Clear Reference": "清除参考照片", "Clear all": "全部清除", @@ -270,7 +270,6 @@ "Company": "公司", "Compare": "比较", "Compare (Shift+C)": "比较(Shift+C)", - "Compare Before and After": "比较修改前和修改后", "Compare needs at least two photos": "比较至少需要两张照片", "Component options": "组件选项", "Compression": "压缩", @@ -983,6 +982,7 @@ "New blank PDF": "新建空白 PDF", "New name": "新名称", "New…": "新建…", + "Next Keyword Set": "下一个关键字集", "Next Photo": "下一张照片", "Night Blue": "夜色蓝调", "No": "否", @@ -1111,6 +1111,7 @@ "Preview only": "仅预览", "Preview size": "预览大小", "Previews": "预览", + "Previous Keyword Set": "上一个关键字集", "Previous Photo": "上一张照片", "Print": "打印", "Print…": "打印…", @@ -1351,17 +1352,12 @@ "Short Edge": "短边", "Show": "显示", "Show All": "显示全部", - "Show Clipping": "显示溢出警告", "Show Deghost Overlay": "显示去重影叠加", "Show Hidden Local Locations": "显示隐藏的本地位置", "Show Luminance Map": "显示明亮度图", "Show Mask": "显示蒙版", - "Show Mask Overlay": "显示蒙版叠加", - "Show All Mask Overlays": "显示所有蒙版叠加", "Show all overlays": "显示所有叠加", - "Show Mask Pins": "显示蒙版图钉", "Show Original": "显示原图", - "Show Photo Counts": "显示照片数量", "Show Photos with Keyword": "显示包含该关键字的照片", "Show Pins": "显示图钉", "Show Source": "显示来源", @@ -2153,7 +2149,6 @@ "Reset all edits (Cmd+Shift+R)": "重置所有编辑 (Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", "LightCraft stopped": "LightCraft 已停止", - "Show Focus Point": "显示对焦点", "Zoom to Focus Point": "缩放至对焦点", "Focus": "对焦", "Focus point": "对焦点", @@ -2186,5 +2181,24 @@ "Suggests who is in a photo from the faces you have named. Everything stays on your computer.": "根据你已命名的人脸,推测照片中的人物。所有数据仅保存在本机。", "This build cannot run recognition models: they can be added and chosen, not used.": "此版本无法运行识别模型:可以添加和选择,但无法使用。", "Detect Faces (Photo menu) needs it: a small one-time download.": "“检测人脸”(照片菜单)依赖它:一次性小文件下载。", - "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)" + "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)", + "Before/After Side by Side": "修改前/修改后左右排列", + "Clipping": "溢出警告", + "Mask Overlay": "蒙版叠加", + "All Mask Overlays": "所有蒙版叠加", + "Mask Pins": "蒙版图钉", + "Photo Counts": "照片数量", + "Focus Point": "对焦点", + "Layout Image": "版面图像", + "Detail View": "详细视图", + "Edit Panel": "编辑面板", + "Close the open dialog, then drop the files again": "请先关闭打开的对话框,然后重新拖入文件", + "Close the open dialog to drop files here": "请先关闭打开的对话框,才能在此拖入文件", + "Drop to open the face model": "松开鼠标以打开人脸模型", + "Drop to import": "松开鼠标以导入", + "Dropped Files": "拖入的文件", + "Import dropped files without review": "不经检查直接导入拖入的文件", + "An import is running": "正在导入", + "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", + "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 1192722251..d5c4eb279a 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -227,6 +227,7 @@ "Delete the keyword “{name}”?": "要刪除關鍵字「{name}」嗎?", "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.": "將從 {count} 張照片移除,其下的關鍵字也一併移除。還原可復原。{:.0}", "Create Keyword Tag Inside “{name}”…": "在「{name}」中建立關鍵字標記…", + "Inside: {names}": "其中:{names}", "“{parent}” has a “{name}” already. Merge the two?": "「{parent}」中已有「{name}」。要合併兩者嗎?", "There is a “{name}” at the top level already. Merge the two?": "最上層已有「{name}」。要合併兩者嗎?", "Added “{keyword}” to {n} photo{}": "已將「{keyword}」加入 {n} 張照片{:.0}", @@ -297,5 +298,12 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」已經是另一個人。合併後成為一個人;還原會再把他們分開。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已新增{what}合併照片({mp}):完整尺寸({full})所需的記憶體超過這台電腦的記憶體", "Listing folders — folders: {folders}, files: {files}": "正在列出資料夾 — 資料夾:{folders},檔案:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})", + "Drop to review {n} item{} for import": "放開滑鼠以在匯入前檢查 {n} 個項目{:.0}", + "Drop to import {n} item{}": "放開滑鼠以匯入 {n} 個項目{:.0}", + "Drop to import {n} preset{}": "放開滑鼠以匯入 {n} 個預設集{:.0}", + "Could not read {name}: {e}": "無法讀取 {name}:{e}", + "Added {n} photo{}": "已加入 {n} 張照片{:.0}", + "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目錄「{catalog}」要匯入到哪裡?", + "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 78d8851285..0408e23ec8 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -36,6 +36,7 @@ "Add in place": "原地加入", "Add in place: the library references the files where they are; nothing is copied or moved.": "原地加入:照片庫參照檔案目前的位置,不會複製或移動檔案。", "Add keyword": "新增關鍵字", + "Add Keywords": "新增關鍵字", "Add number": "加上編號", "Add to": "加入至", "Add to Album": "加入相簿", @@ -220,7 +221,6 @@ "Clear Filters": "清除篩選條件", "Clear Guides": "清除參考線", "Clear History": "清除歷史紀錄", - "Clear Preview Cache": "清除預覽快取", "Clear Quick Collection": "清除快速集合", "Clear Reference": "清除參考照片", "Clear all": "全部清除", @@ -270,7 +270,7 @@ "Company": "公司", "Compare": "比較", "Compare (Shift+C)": "比較(Shift+C)", - "Compare Before and After": "比較編輯前與編輯後", + "Before/After Side by Side": "編輯前/後左右檢視", "Compare needs at least two photos": "比較需要至少兩張照片", "Component options": "元件選項", "Compression": "壓縮", @@ -405,7 +405,7 @@ "Desert Heat": "沙漠熱浪", "Desert Warmth": "沙漠暖色", "Desktop": "桌面", - "Detail": "詳細檢視", + "Detail": "細節", "Detail (D)": "詳細檢視(D)", "Details": "詳細資訊", "Diagonal": "對角線", @@ -983,6 +983,7 @@ "New blank PDF": "新增空白 PDF", "New name": "新名稱", "New…": "新增…", + "Next Keyword Set": "下一個關鍵字集", "Next Photo": "下一張照片", "Night Blue": "夜色藍調", "No": "否", @@ -1111,6 +1112,7 @@ "Preview only": "僅供預覽", "Preview size": "預覽尺寸", "Previews": "預覽", + "Previous Keyword Set": "上一個關鍵字集", "Previous Photo": "上一張照片", "Print": "列印", "Print…": "列印…", @@ -1351,17 +1353,17 @@ "Short Edge": "短邊", "Show": "顯示", "Show All": "全部顯示", - "Show Clipping": "顯示溢色", + "Clipping": "溢色", "Show Deghost Overlay": "顯示去除鬼影疊加", "Show Hidden Local Locations": "顯示隱藏的本機位置", "Show Luminance Map": "顯示明度圖", "Show Mask": "顯示遮色片", - "Show Mask Overlay": "顯示遮色片疊加", - "Show All Mask Overlays": "顯示所有蒙版疊加", + "Mask Overlay": "遮色片疊加", + "All Mask Overlays": "所有遮色片疊加", "Show all overlays": "顯示所有疊加", - "Show Mask Pins": "顯示遮色片控制點", + "Mask Pins": "遮色片控制點", "Show Original": "顯示原始照片", - "Show Photo Counts": "顯示照片數量", + "Photo Counts": "照片數量", "Show Photos with Keyword": "顯示含此關鍵字的照片", "Show Pins": "顯示控制點", "Show Source": "顯示來源", @@ -2115,7 +2117,7 @@ "Reset all edits (Cmd+Shift+R)": "重設所有編輯(Cmd+Shift+R)", "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", "LightCraft stopped": "LightCraft 已停止", - "Show Focus Point": "顯示對焦點", + "Focus Point": "對焦點", "Zoom to Focus Point": "縮放至對焦點", "Focus": "對焦", "Focus point": "對焦點", @@ -2143,5 +2145,17 @@ "Checking the GPU…": "正在檢查 GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "只有在檢查顯示 GPU 能更快得出相同結果時,臉孔模型才會使用 GPU。", - "Checking the GPU for faces": "正在檢查用於臉孔的 GPU" + "Checking the GPU for faces": "正在檢查用於臉孔的 GPU", + "Layout Image": "版面圖像", + "Detail View": "詳細檢視", + "Edit Panel": "編輯面板", + "Close the open dialog, then drop the files again": "請先關閉開啟的對話框,然後重新拖放檔案", + "Close the open dialog to drop files here": "請先關閉開啟的對話框,才能在此拖放檔案", + "Drop to open the face model": "放開滑鼠以開啟人臉模型", + "Drop to import": "放開滑鼠以匯入", + "Dropped Files": "拖放的檔案", + "Import dropped files without review": "不經檢查直接匯入拖放的檔案", + "An import is running": "正在匯入", + "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", + "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入" } diff --git a/crates/ui-egui/src/album_picker.rs b/crates/ui-egui/src/album_picker.rs index 835dbcce82..1c59bcae8e 100644 --- a/crates/ui-egui/src/album_picker.rs +++ b/crates/ui-egui/src/album_picker.rs @@ -211,8 +211,8 @@ impl<'a> AlbumPicker<'a> { ui.add_sized(vec2(width, ui.spacing().interact_size.y), egui::Button::new(text.as_str()).truncate().right_text(" ")).on_hover_text(text); let arrow_color = crate::theme::Tokens::get(ui.ctx()).icon; disclosure(ui.painter(), egui::pos2(button.rect.right() - 10.0, button.rect.center().y), true, arrow_color); - register(ui.ctx(), format!("albumPicker:{id}"), button.rect); - let key = egui::Id::new(("albumPicker", id.as_str())); + register(ui, format!("albumPicker:{id}"), button.rect); + let key = egui::Id::unique(("albumPicker", id.as_str())); if button.clicked() { // open on the chosen album's folders, with the search empty and ready for typing let open = chosen.map(|c| ancestors(entries, c)).unwrap_or_default(); @@ -232,7 +232,7 @@ impl<'a> AlbumPicker<'a> { } let search_box = ui.add(egui::TextEdit::singleline(&mut state.query).hint_text(crate::i18n::tr("Search albums")).desired_width(f32::INFINITY)); - register(ui.ctx(), format!("albumPickerSearch:{id}"), search_box.rect); + register(ui, format!("albumPickerSearch:{id}"), search_box.rect); if state.focus { search_box.request_focus(); state.focus = false; @@ -252,7 +252,7 @@ impl<'a> AlbumPicker<'a> { let resp = ui .add_enabled(e.blocked.is_none(), egui::Button::selectable(Some(e.id) == chosen || highlighted, label).truncate()) .on_hover_text(label); - register(ui.ctx(), format!("albumPickerItem:{}:{id}", e.id), resp.rect); + register(ui, format!("albumPickerItem:{}:{id}", e.id), resp.rect); let resp = match &e.blocked { Some(why) => resp.on_disabled_hover_text(why.as_str()), None => resp, @@ -289,10 +289,10 @@ impl<'a> AlbumPicker<'a> { egui::TextStyle::Button.resolve(ui.style()), t.text_label, ); - register(ui.ctx(), format!("albumPickerFolder:{}:{id}", e.id), r.rect); + register(ui, format!("albumPickerFolder:{}:{id}", e.id), r.rect); // what assistive tools announce: the folder, and whether it is open let name = e.name.clone(); - r.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, &name)); + crate::widgets::announce_disclosure(&r, true, open, &name); if r.clicked() { // the click took the keyboard from the search box: give it back state.focus = true; diff --git a/crates/ui-egui/src/button.rs b/crates/ui-egui/src/button.rs index f46156ed94..d3fa988219 100644 --- a/crates/ui-egui/src/button.rs +++ b/crates/ui-egui/src/button.rs @@ -188,6 +188,7 @@ pub struct Button<'a> { kind: Kind, size: Size, enabled: bool, + busy: bool, widget: Option<String>, tooltip: Option<&'a str>, min_width: f32, @@ -204,6 +205,7 @@ impl<'a> Button<'a> { kind: Kind::default(), size: Size::default(), enabled: true, + busy: false, widget: None, tooltip: None, min_width: 0.0, @@ -256,6 +258,14 @@ impl<'a> Button<'a> { self } + /// Working on what it was pressed for: a spinner takes the icon's place (or sits before the + /// text, inside the button's own padding, so the button keeps its width), a click does nothing, + /// and screen readers hear it is busy. + pub fn busy(mut self, busy: bool) -> Self { + self.busy = busy; + self + } + /// Registered under this id (`button:…`) for scripts, tests and `ui.clickWidget`; unique on /// screen, as every registered id is. pub fn widget(mut self, id: impl Into<String>) -> Self { @@ -322,7 +332,7 @@ impl<'a> Button<'a> { // stable across frames and moves: its widget id (with its salt) when it has one, else its // place in the ui (moved on, so the next button in the same ui gets another) let id = match &self.widget { - Some(w) => ui.id().with(("lc-button", w.as_str(), self.id_salt)), + Some(w) => ui.scope_id().with(("lc-button", w.as_str(), self.id_salt)), None => { let id = ui.auto_id_with(("lc-button", self.text.or(self.name), self.id_salt)); ui.skip_ahead_auto_ids(1); @@ -331,14 +341,30 @@ impl<'a> Button<'a> { }; // a button in a disabled part of the window is disabled too let enabled = self.enabled && ui.is_enabled(); - let resp = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() }); + let resp = ui.interact( + rect, + id, + if !enabled { + Sense::hover() + } else if self.busy { + // still reachable by the keyboard, but nothing to press + Sense::focusable_noninteractive() + } else { + Sense::click() + }, + ); let words = crate::i18n::tr(self.name.or(self.text).unwrap_or_default()).to_string(); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, words.clone())); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, words.clone())); + if self.busy { + ui.ctx().accesskit_node_builder(resp.id, |node| node.set_busy()); + } if let Some(w) = &self.widget { - crate::widgets::register(ui.ctx(), w.clone(), rect); + crate::widgets::register(ui, w.clone(), rect); } let state = if !enabled { State::Disabled + } else if self.busy { + State::Idle } else if resp.is_pointer_button_down_on() { State::Pressed } else if resp.hovered() { @@ -362,16 +388,29 @@ impl<'a> Button<'a> { } let galley = self.galley(ui); let icon_s = self.size.icon(); - let content_w = match (&galley, self.icon) { - (Some(g), Some(_)) => icon_s + self.size.gap() + g.size().x, - (Some(g), None) => g.size().x, - (None, Some(_)) => icon_s, - (None, None) => 0.0, + // busy: the spinner is the icon's slot; with text alone it is a smaller one in the button's + // own padding (a little tighter), so the button never grows + let spinner_only = self.busy && self.icon.is_none() && galley.is_some(); + let (slot, gap) = if spinner_only { ((self.size.padding() * 2.0 - 12.0).clamp(8.0, icon_s), 4.0) } else { (icon_s, self.size.gap()) }; + let has_slot = self.icon.is_some() || spinner_only; + let content_w = match (&galley, has_slot) { + (Some(g), true) => slot + gap + g.size().x, + (Some(g), false) => g.size().x, + (None, true) => slot, + (None, false) => 0.0, }; let mut x = rect.center().x - content_w / 2.0; - if let Some(icon) = self.icon { - paint(p, Rect::from_center_size(pos2(x + icon_s / 2.0, rect.center().y), vec2(icon_s, icon_s)), icon, lk.content); - x += icon_s + self.size.gap(); + if has_slot { + let slot_rect = Rect::from_center_size(pos2(x + slot / 2.0, rect.center().y), vec2(slot, slot)); + if self.busy { + if ui.is_rect_visible(rect) { + crate::progress::paint_spinner(p, slot_rect, lk.content, ui.input(|i| i.time)); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(33)); + } + } else if let Some(icon) = self.icon { + paint(p, slot_rect, icon, lk.content); + } + x += slot + gap; } if let Some(g) = galley { let at = pos2(x, rect.center().y - g.size().y / 2.0); diff --git a/crates/ui-egui/src/canvas_keys.rs b/crates/ui-egui/src/canvas_keys.rs index dadbb1577d..d0c9ee3adf 100644 --- a/crates/ui-egui/src/canvas_keys.rs +++ b/crates/ui-egui/src/canvas_keys.rs @@ -12,12 +12,12 @@ pub const STEP: f64 = 0.005; pub const BIG_STEP: f64 = 0.05; fn focused_key() -> Id { - Id::new("lc-canvas-handle-focused") + Id::unique("lc-canvas-handle-focused") } /// The egui id of the stand-in registered as `key` (to focus it, or find it in tests). pub fn id(key: &str) -> Id { - Id::new("lc-canvas-handle").with(key) + Id::unique("lc-canvas-handle").with(key) } /// Whether a canvas handle holds the keyboard focus: it keeps the arrow keys and Return from the @@ -49,11 +49,11 @@ pub fn handle(ui: &mut Ui, key: &str, name: &str, value: String, at: Pos2) -> Ha let rect = Rect::from_center_size(at, vec2(14.0, 14.0)); let resp = ui.interact(rect, id, egui::Sense::focusable_noninteractive()); let label = name.to_string(); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label.clone())); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.clone())); ui.ctx().accesskit_node_builder(id, |node| { node.set_value(value); }); - crate::widgets::register(ui.ctx(), format!("canvasHandle:{key}"), rect); + crate::widgets::register(ui, format!("canvasHandle:{key}"), rect); let mut out = HandleKeys::default(); if !resp.has_focus() { return out; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index efb3ea3ac5..caacbc5908 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -10,7 +10,7 @@ //! - `ui.move/click/drag {x, y, …}`: raw pointer input in screen points //! - `ui.pointer {events: [{kind: down|drag|up, x, y}], space: "image"}`: gestures in normalized //! image coordinates (brush strokes, crop handles…) — mapped to screen and injected as real input -//! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}` / `ui.scroll {dx, dy}` +//! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}` / `ui.scroll {dx, dy, source?, unit?, phase?}` //! - `ui.set {view?, panel?, filmstrip?, leftPanel?, zoom?, …}` / `ui.dialog.confirm|cancel` //! - `ui.screenshot {path?, headless?}` (headless: CPU-rendered, no compositor needed), `ui.resize {width, height}`, `ui.render {id?, size?, path?}`, `app.quit` @@ -59,7 +59,17 @@ impl ControlRequest { pub enum Outcome { Done(Value), - Screenshot { path: Option<String>, headless: bool }, + /// A capture was admitted: `target` pins the destination identity until the write. + Screenshot { + target: Option<lightcraft_engine::originals::WriteTarget>, + headless: bool, + }, + /// A synthetic-input request that must wait for a fresh layout and for its last event to be + /// consumed before it is answered (see `LightcraftApp::admit_gesture`). + Gesture { + method: String, + params: Value, + }, } fn ok(v: Value) -> Outcome { @@ -160,6 +170,9 @@ fn modifiers(p: &Value) -> egui::Modifiers { egui::Modifiers { alt: b("alt"), ctrl: b("ctrl"), shift: b("shift"), mac_cmd: b("cmd") && cfg!(target_os = "macos"), command: b("cmd") } } +/// Parse a control-protocol key name into an egui key. `egui::Key::from_name` is tried first; +/// then lowercase aliases cover `return`/`enter`, `esc`/`escape`, `delete`/`backspace` (both +/// Backspace), arrow names, space/tab, and backslash, slash and square brackets. fn key_from(name: &str) -> Option<egui::Key> { egui::Key::from_name(name).or(match name.to_ascii_lowercase().as_str() { "enter" | "return" => Some(egui::Key::Enter), @@ -179,6 +192,50 @@ fn key_from(name: &str) -> Option<egui::Key> { }) } +/// Most clicks one `ui.click`/`ui.clickWidget` request may inject. The control server is a +/// local automation surface, but a request must not be able to fill memory with synthetic events. +pub(crate) const MAX_CLICKS: u64 = 16; +/// Most pointer-move steps one `ui.drag`/`ui.dragWidget` request may inject. +pub(crate) const MAX_DRAG_STEPS: u64 = 1000; + +/// What a widget gesture's synthetic events were aimed at when they were resolved. Delivery +/// rechecks this against the latest completed layout before the first event and again before every +/// press: a moved widget cancels the request instead of being retargeted. +#[derive(Clone, Debug)] +pub(crate) struct GestureTarget { + pub id: String, + /// The rect the request resolved against. An explicit `fx`/`fy` may place `at` outside it; + /// delivery accepts that only while egui's actual clipped interaction rectangle still + /// contains the point. + pub rect: egui::Rect, + /// The point the pointer events aim at. + pub at: egui::Pos2, + /// Whether the release must still find this widget. egui attributes a click on release while a + /// drag may legitimately end outside the widget it started on, so only `ui.clickWidget` sets + /// this. + pub check_release: bool, + /// Whether the first event must find the widget visible and topmost. A hover is not harmless + /// when its point is clipped out of the widget or covered by a non-modal overlay: the + /// documented contract refuses it rather than moving the pointer at a stale place. + pub check_visible: bool, +} + +/// The events queued for a resolved gesture, plus the widget target whose geometry must still hold +/// when the first event and each press are injected. +#[derive(Debug)] +pub(crate) struct GestureOutcome { + pub result: Value, + pub target: Option<GestureTarget>, +} + +impl GestureOutcome { + /// A gesture outcome that injected no widget-targeted events, so delivery has no geometry to + /// re-check. + fn done(result: Value) -> Self { + Self { result, target: None } + } +} + fn push_drag(app: &mut LightcraftApp, a: egui::Pos2, b: egui::Pos2, steps: u64, m: egui::Modifiers) { app.synthetic.push(egui::Event::PointerMoved(a)); app.synthetic.push(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: m }); @@ -189,10 +246,81 @@ fn push_drag(app: &mut LightcraftApp, a: egui::Pos2, b: egui::Pos2, steps: u64, app.synthetic.push(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: m }); } -fn widget_rect(app: &LightcraftApp, id: &str) -> Option<egui::Rect> { +/// The rectangle registered for automation id `id` in the latest completed pass. The last +/// registration wins, so a redrawn widget's current geometry is returned. +pub(crate) fn widget_rect(app: &LightcraftApp, id: &str) -> Option<egui::Rect> { app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r) } +/// The real egui widget that owns automation id `id` in the latest completed pass (the last +/// registration wins, as [`widget_rect`] does). +pub(crate) fn widget_hit(app: &LightcraftApp, id: &str) -> Option<crate::widgets::WidgetHit> { + app.widget_hits.iter().rev().find(|(w, _)| w == id).map(|(_, hit)| *hit) +} + +/// Whether the registered automation rectangle still owns egui's pointer hit at `at`. +/// +/// A registration records the egui id and layer of a hover probe (or of the widget's own +/// response), plus that response's clipped `interact_rect` in the same completed pass. This asks +/// egui for the current areas at the point and checks: +/// +/// - the recorded clipped rectangle still contains the point (a widget scrolled out of its panel +/// has an empty interact rect even though its unclipped rect still contains the old point); +/// - the top-most interactable area at the point is the recorded layer; or +/// - the top-most area is the current modal layer and the recorded layer is below it. egui routes +/// every point below a modal to that modal, even outside the dialog window, so leaving the press +/// to egui is safe: the dialog consumes it or `clicked_backdrop` closes the dialog, and a +/// background widget cannot receive it. A non-modal overlay is not the modal layer, so it must +/// still match the target and is refused otherwise. The one exception is the explicitly +/// blocking library-problem/launch-list window: its dim also owns the modal layer, but a +/// background target is refused here rather than reported `ok:true` after the dim swallows the +/// press; only controls drawn in that window's own layer pass. Same-layer overlaps are invisible +/// to this area check; egui still delivers the press to whichever widget is top-most in that +/// layer. +/// +/// `interact_rect` comes from the latest completed registry, not `Context::read_response`: +/// `raw_input_hook` runs before `begin_pass`, where `read_response` checks `this_pass` before +/// `prev_pass` and can therefore return the pass before the one that just published the registry. +/// This matters when clipping, scrolling or a viewport change alters the target without changing +/// its layer. +/// +/// In pinned egui `6d518fc`, `Response::hovered` is deliberately false while any button is down +/// unless this is the clicked widget (`context.rs:1884-1886`, `interaction.rs:257-300`). A +/// hover-only probe cannot use it for a click release. `Response::contains_pointer` would survive +/// the press, but its hit-test snapshot is one frame behind the pointer move that precedes the +/// press (`context.rs:517-548` reads `prev_pass.widgets` at `begin_pass`). The recorded clipped rect +/// plus the current layer has no such lag. +/// +/// This also avoids the old centre-of-an-interactive-rect heuristic: a registration may be a +/// sub-rect of its widget's interactive response (rating stars, date cells, a checkbox's box, a +/// profile card's star), so the interactive rect's centre need not lie in the registered rect. +/// Disabled controls keep working as a no-op: their own probe is enabled and the injected click +/// is ignored by egui, which is the documented `ui.clickWidget` semantics. +pub(crate) fn widget_target_visible(ctx: &egui::Context, hit: Option<crate::widgets::WidgetHit>, at: egui::Pos2) -> bool { + let Some(hit) = hit else { + // A hand-built registry entry (tests) or painted geometry has no egui widget to own a + // press. Production widget registrations always record a probe or a real response. + return false; + }; + let interact_rect = ctx.layer_transform_to_global(hit.layer_id).map_or(hit.interact_rect, |to_global| to_global * hit.interact_rect); + if !interact_rect.is_finite() || !interact_rect.contains(at) { + return false; + } + let (top_modal, allows_interaction, above_modal) = + ctx.memory(|memory| (memory.top_modal_layer(), memory.allows_interaction(hit.layer_id), memory.is_above_modal_layer(hit.layer_id))); + if crate::panels::library_problem::refuses_control_target(top_modal, hit.layer_id) { + return false; + } + let at_layer = ctx.layer_id_at(at); + if at_layer == Some(hit.layer_id) { + return allows_interaction; + } + top_modal == at_layer && !above_modal +} + +/// Dispatch one control request: run engine commands, list menus/widgets, inspect state, queue +/// file drops and synthetic input, capture screenshots, or return an error for an unknown or +/// invalid request. Requests that need fresh widget geometry are queued as `Outcome` values. pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; let s = |k: &str| p.get(k).and_then(Value::as_str); @@ -217,128 +345,30 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest app.widgets.iter().filter(|(id, _)| id.contains(filter)).map(|(id, r)| json!({"id": id, "rect": rect_json(*r)})).collect(), )) } - "ui.clickWidget" | "ui.dragWidget" | "ui.hoverWidget" => { - let Some(id) = s("id") else { return err("missing `id`") }; - let Some(r) = widget_rect(app, id) else { return err(format!("no widget `{id}` on screen (see ui.widgets)")) }; - let m = modifiers(p); - // optional relative position inside the widget (0..1) - let at = egui::pos2(r.left() + r.width() * f("fx").unwrap_or(0.5) as f32, r.top() + r.height() * f("fy").unwrap_or(0.5) as f32); - if req.method == "ui.hoverWidget" { - app.synthetic.push(egui::Event::PointerMoved(at)); - } else if req.method == "ui.clickWidget" { - let n = p.get("count").and_then(Value::as_u64).unwrap_or(1); - let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary }; - app.synthetic.push(egui::Event::PointerMoved(at)); - for _ in 0..n { - app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: true, modifiers: m }); - app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: false, modifiers: m }); - } - } else { - let to = egui::pos2( - f("toX").map(|v| v as f32).unwrap_or(at.x + f("dx").unwrap_or(0.0) as f32), - f("toY").map(|v| v as f32).unwrap_or(at.y + f("dy").unwrap_or(0.0) as f32), - ); - push_drag(app, at, to, p.get("steps").and_then(Value::as_u64).unwrap_or(10), m); - } - ctx.request_repaint(); - ok(json!({"rect": rect_json(r)})) - } - "ui.move" => { - app.synthetic.push(egui::Event::PointerMoved(egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32))); - ctx.request_repaint(); - ok(Value::Null) - } - "ui.click" | "ui.drag" => { - let a = egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32); - let m = modifiers(p); - let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary }; - if req.method == "ui.drag" { - let b = egui::pos2(f("toX").unwrap_or(0.0) as f32, f("toY").unwrap_or(0.0) as f32); - push_drag(app, a, b, p.get("steps").and_then(Value::as_u64).unwrap_or(10), m); - } else { - app.synthetic.push(egui::Event::PointerMoved(a)); - for _ in 0..p.get("count").and_then(Value::as_u64).unwrap_or(1) { - app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers: m }); - app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: false, modifiers: m }); - } - } - ctx.request_repaint(); - ok(Value::Null) - } - "ui.pointer" => { - // events in normalized image coordinates of the displayed photo frame - let Some(img) = app.image_rect else { return err("no image on screen (switch to Detail view)") }; - let Some(events) = p.get("events").and_then(Value::as_array) else { return err("missing `events`") }; - let m = modifiers(p); - for e in events { - let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.5) as f32; - let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.5) as f32; - let pos = egui::pos2(img.left() + x * img.width(), img.top() + y * img.height()); - match e.get("kind").and_then(Value::as_str).unwrap_or("move") { - "down" => { - app.synthetic.push(egui::Event::PointerMoved(pos)); - app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: m }); - } - "up" => { - app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: m }) - } - _ => app.synthetic.push(egui::Event::PointerMoved(pos)), - } - } - ctx.request_repaint(); - ok(json!({"events": events.len()})) - } - "ui.key" => { - let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") }; - let m = modifiers(p); - app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m }); - app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: m }); - ctx.request_repaint(); - ok(Value::Null) - } - "ui.text" => { - app.synthetic.push(egui::Event::Text(s("text").unwrap_or("").to_string())); - ctx.request_repaint(); - ok(Value::Null) - } - // what the system does for ⌘X / ⌘C / ⌘V in a text field: paste `text`, or (without it) - // what the system clipboard holds - "ui.clipboard" => { - // outside a text field ⌘C / ⌘V are the app's shortcuts (and the macOS menu bar's): - // agents run those as commands (`develop.copy`, `develop.paste`) - if !ctx.text_edit_focused() { - return err("ui.clipboard: no text field has the focus (click one first)"); - } - match s("action") { - Some("cut") => app.synthetic.push(egui::Event::Cut), - Some("copy") => app.synthetic.push(egui::Event::Copy), - Some("paste") => match s("text") { - Some(text) => app.synthetic.push(egui::Event::Paste(text.to_string())), - None => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste), - }, - _ => return err("ui.clipboard: `action` is cut, copy or paste"), - } - ctx.request_repaint(); - ok(Value::Null) - } - "ui.scroll" => { - app.synthetic.push(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(f("dx").unwrap_or(0.0) as f32, f("dy").unwrap_or(0.0) as f32), - phase: egui::TouchPhase::Move, - modifiers: modifiers(p), - }); - ctx.request_repaint(); - ok(Value::Null) - } - "ui.zoom" => { - let Some(factor) = f("factor").map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0) else { - return err("ui.zoom: factor must be a finite positive number (1 = unchanged)"); + "ui.dropFiles" => { + // every entry must be a string: a script is not told `ok` for a part of what it sent + let Some(paths) = + p.get("paths").and_then(Value::as_array).and_then(|a| a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<Vec<_>>>()) + else { + return err("ui.dropFiles: paths must be an array of strings"); }; - app.synthetic.push(egui::Event::Zoom(factor)); + if p.get("hover").and_then(Value::as_bool).unwrap_or(false) { + app.drop_hover = paths; + } else { + // the drag ends with the drop, as it does for the OS + app.drop_hover.clear(); + app.drop_pending = paths; + } ctx.request_repaint(); ok(Value::Null) } + "ui.clickWidget" | "ui.dragWidget" | "ui.hoverWidget" | "ui.move" | "ui.click" | "ui.drag" | "ui.pointer" | "ui.key" | "ui.text" + | "ui.clipboard" | "ui.scroll" => { + // Geometry and input events are resolved only after a fresh completed layout; the + // reply waits until the UI has consumed the last event (plan §4.5). + Outcome::Gesture { method: req.method.clone(), params: req.params.clone() } + } + "ui.zoom" => Outcome::Gesture { method: req.method.clone(), params: req.params.clone() }, "ui.set" => { // an arrangement of the sidebar is checked, not made whole as a settings file's is let sidebar = match p.get("sidebar").map(crate::sidebar::SidebarLayout::parse).transpose() { @@ -392,8 +422,10 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest | crate::state::Dialog::SamModel { .. } | crate::state::Dialog::SmartRules { .. } | crate::state::Dialog::SaveEffect { .. } + | crate::state::Dialog::CaptureTime { .. } )) || (r.is_ok() && crate::panels::dialogs::keeps_open(app, &d)) + || (r.is_err() && crate::lightroom_destination::keeps_open_on_error(app, &d)) { app.ui.dialog = Some(d); } @@ -430,12 +462,18 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest _ => err("ui.zoomFactor: factor must be a number from 0.5 to 3"), }, "ui.screenshot" => { - // never over a photo's original - if let Some(Err(e)) = s("path").map(|path| app.session.check_write_target(path)) { - return err(e); - } + // Never over a photo's original, and pin the destination identity now: the write + // revalidates it after the (possibly lengthy) capture and never replaces a path that + // was absent at admission but appeared meanwhile. + let target = match s("path") { + Some(path) => match app.session.pin_write_target(path) { + Ok(t) => Some(t), + Err(e) => return err(e), + }, + None => None, + }; ctx.request_repaint(); - Outcome::Screenshot { path: s("path").map(str::to_string), headless: p.get("headless").and_then(Value::as_bool).unwrap_or(false) } + Outcome::Screenshot { target, headless: p.get("headless").and_then(Value::as_bool).unwrap_or(false) } } "ui.render" => { let id = match p.get("id").filter(|v| !v.is_null()) { @@ -562,22 +600,230 @@ pub fn export_active(app: &mut LightcraftApp, p: &Value) -> Result<Value, String Ok(out) } -pub fn save_screenshot(app: &mut LightcraftApp, image: &egui::ColorImage, path: Option<&str>) -> Value { +/// Resolve one queued synthetic-input control request against the **current** layout. +/// +/// Called by the app only after a completed UI pass newer than admission (plan §4.5). Widget rects +/// and the image rect therefore come from that pass; nothing is retargeted. A successful return +/// has pushed the events onto `app.synthetic`; the app answers the request once the UI consumed +/// them. +pub(crate) fn gesture_events(app: &mut LightcraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Result<GestureOutcome, String> { + let s = |k: &str| p.get(k).and_then(Value::as_str); + let f = |k: &str| p.get(k).and_then(Value::as_f64); + match method { + "ui.clickWidget" | "ui.dragWidget" | "ui.hoverWidget" => { + let Some(id) = s("id") else { return Err("missing `id`".into()) }; + let Some(r) = widget_rect(app, id) else { return Err(format!("no widget `{id}` on screen (see ui.widgets)")) }; + let m = modifiers(p); + let (fx, fy) = (f("fx").unwrap_or(0.5), f("fy").unwrap_or(0.5)); + let at = egui::pos2(r.left() + r.width() * fx as f32, r.top() + r.height() * fy as f32); + if !fx.is_finite() || !fy.is_finite() || !at.is_finite() { + return Err(format!("{method}: fx and fy must resolve to a finite point")); + } + let hover = method == "ui.hoverWidget"; + if hover && !widget_target_visible(ctx, widget_hit(app, id), at) { + return Err(format!("ui.hoverWidget: widget `{id}` has no visible interaction area at the requested point")); + } + if hover { + app.synthetic.push(egui::Event::PointerMoved(at)); + } else if method == "ui.clickWidget" { + let n = p.get("count").and_then(Value::as_u64).unwrap_or(1).min(MAX_CLICKS); + let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary }; + app.synthetic.push(egui::Event::PointerMoved(at)); + for _ in 0..n { + app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: true, modifiers: m }); + app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed: false, modifiers: m }); + } + } else { + let to = egui::pos2( + f("toX").map(|v| v as f32).unwrap_or(at.x + f("dx").unwrap_or(0.0) as f32), + f("toY").map(|v| v as f32).unwrap_or(at.y + f("dy").unwrap_or(0.0) as f32), + ); + push_drag(app, at, to, p.get("steps").and_then(Value::as_u64).unwrap_or(10).min(MAX_DRAG_STEPS), m); + } + ctx.request_repaint(); + Ok(GestureOutcome { + result: json!({"rect": rect_json(r)}), + target: Some(GestureTarget { id: id.to_string(), rect: r, at, check_release: method == "ui.clickWidget", check_visible: hover }), + }) + } + "ui.move" => { + app.synthetic.push(egui::Event::PointerMoved(egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32))); + ctx.request_repaint(); + Ok(GestureOutcome::done(Value::Null)) + } + "ui.click" | "ui.drag" => { + let a = egui::pos2(f("x").unwrap_or(0.0) as f32, f("y").unwrap_or(0.0) as f32); + let m = modifiers(p); + let button = if s("button") == Some("right") { egui::PointerButton::Secondary } else { egui::PointerButton::Primary }; + if method == "ui.drag" { + let b = egui::pos2(f("toX").unwrap_or(0.0) as f32, f("toY").unwrap_or(0.0) as f32); + push_drag(app, a, b, p.get("steps").and_then(Value::as_u64).unwrap_or(10).min(MAX_DRAG_STEPS), m); + } else { + app.synthetic.push(egui::Event::PointerMoved(a)); + for _ in 0..p.get("count").and_then(Value::as_u64).unwrap_or(1).min(MAX_CLICKS) { + app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers: m }); + app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: false, modifiers: m }); + } + } + ctx.request_repaint(); + Ok(GestureOutcome::done(Value::Null)) + } + "ui.pointer" => { + let Some(img) = app.image_rect else { return Err("no image on screen (switch to Detail view)".into()) }; + let Some(events) = p.get("events").and_then(Value::as_array) else { return Err("missing `events`".into()) }; + let m = modifiers(p); + for e in events { + let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.5) as f32; + let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.5) as f32; + let pos = egui::pos2(img.left() + x * img.width(), img.top() + y * img.height()); + match e.get("kind").and_then(Value::as_str).unwrap_or("move") { + "down" => { + app.synthetic.push(egui::Event::PointerMoved(pos)); + app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: m }); + } + "up" => { + app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: m }) + } + _ => app.synthetic.push(egui::Event::PointerMoved(pos)), + } + } + ctx.request_repaint(); + Ok(GestureOutcome::done(json!({"events": events.len()}))) + } + "ui.key" => { + let Some(k) = s("key").and_then(key_from) else { return Err("unknown or missing `key`".into()) }; + let m = modifiers(p); + app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m }); + app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: m }); + ctx.request_repaint(); + Ok(GestureOutcome::done(Value::Null)) + } + "ui.text" => { + app.synthetic.push(egui::Event::Text(s("text").unwrap_or("").to_string())); + ctx.request_repaint(); + Ok(GestureOutcome::done(Value::Null)) + } + "ui.clipboard" => { + // RequestPaste is a viewport command, not an event: the prompt/library input barrier + // cannot inspect it after the fact. Refuse the command while either barrier owns input, + // including a window created after this pass began resolving the gesture. Without + // `text` this only queues RequestPaste in egui; it is not a host-dispatch or delivery + // acknowledgement. egui 0.37 documents RequestPaste as asking the host to paste into + // the focused text edit, with no completion or correlation id. egui-winit emits a later + // Event::Paste only for non-empty text (or a PasteImage fallback; Wayland reads finish + // later), so a barrier created after the request can drop that later event; the reply + // below cannot promise dispatch or delivery. With `text`, the synthetic + // Event::Paste is filtered and canceled like other injected input. + let barrier = if crate::panels::notices::blocks_input(app) { + Some("a modal prompt") + } else if crate::panels::library_problem::blocks_dialog_input(app) { + Some("the blocking library window") + } else { + None + }; + if let Some(barrier) = barrier { + return Err(format!("ui.clipboard: {barrier} is blocking background input")); + } + if !ctx.text_edit_focused() { + return Err("ui.clipboard: no text field has the focus (click one first)".into()); + } + match s("action") { + Some("cut") => app.synthetic.push(egui::Event::Cut), + Some("copy") => app.synthetic.push(egui::Event::Copy), + Some("paste") => match s("text") { + Some(text) => app.synthetic.push(egui::Event::Paste(text.to_string())), + None => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste), + }, + _ => return Err("ui.clipboard: `action` is cut, copy or paste".into()), + } + ctx.request_repaint(); + Ok(GestureOutcome::done(Value::Null)) + } + "ui.scroll" => { + // Omitted keys keep the pre-0.37 request meaning; all other values are validated + // before anything is queued. + let source = match s("source") { + None | Some("unknown") => egui::MouseWheelSource::Unknown, + Some("wheel") => egui::MouseWheelSource::Wheel, + Some("trackpad") => egui::MouseWheelSource::Trackpad, + Some("momentum") => egui::MouseWheelSource::Momentum, + Some(other) => return Err(format!("ui.scroll: `source` is wheel, trackpad, momentum or unknown, not {other:?}")), + }; + let unit = match s("unit") { + None | Some("point") => egui::MouseWheelUnit::Point, + Some("line") => egui::MouseWheelUnit::Line, + Some("page") => egui::MouseWheelUnit::Page, + Some(other) => return Err(format!("ui.scroll: `unit` is point, line or page, not {other:?}")), + }; + let phase = match s("phase") { + None | Some("move") => egui::TouchPhase::Move, + Some("start") => egui::TouchPhase::Start, + Some("end") => egui::TouchPhase::End, + Some("cancel") => egui::TouchPhase::Cancel, + Some(other) => return Err(format!("ui.scroll: `phase` is start, move, end or cancel, not {other:?}")), + }; + app.synthetic.push(egui::Event::MouseWheel { + unit, + delta: egui::vec2(f("dx").unwrap_or(0.0) as f32, f("dy").unwrap_or(0.0) as f32), + phase, + source, + modifiers: modifiers(p), + }); + ctx.request_repaint(); + Ok(GestureOutcome::done(Value::Null)) + } + "ui.zoom" => { + let Some(factor) = f("factor").map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0) else { + return Err("ui.zoom: factor must be a finite positive number (1 = unchanged)".into()); + }; + app.synthetic.push(egui::Event::Zoom(factor)); + ctx.request_repaint(); + Ok(GestureOutcome::done(Value::Null)) + } + other => Err(format!("not a synthetic-input gesture: `{other}`")), + } +} + +/// Encode `image` as PNG and write it to the capture's pinned target, returning the control +/// protocol's JSON result. The destination is revalidated before encoding; a new path is written +/// with create-new semantics (never replacing a file that appeared), and a missing encoder or +/// writer is an error. `None` only reports the image size without writing. +pub fn save_screenshot(app: &mut LightcraftApp, image: &egui::ColorImage, target: Option<&lightcraft_engine::originals::WriteTarget>) -> Value { let [w, h] = image.size; - let Some(path) = path else { + let Some(target) = target else { return json!({"ok": true, "result": {"width": w, "height": h}}); }; - let rgba: Vec<u8> = image.pixels.iter().flat_map(|c| c.to_array()).collect(); - let Some(img) = lightcraft_raster::Rgba8::from_bytes(w, h, &rgba) else { + // Re-check the pinned destination immediately before encoding/writing. This is the point the + // asynchronous renderer callback and the CPU fallback share. + if let Err(error) = app.session.revalidate_write_target(target) { + return json!({"ok": false, "error": error}); + } + // Rgba8's buffer is the only extra full-image allocation while encoding (the PNG bytes are + // the second transient; see MAX_SHOT_WORKING_SET_BYTES in `lib.rs`). Building it straight from + // the `Color32` pixels avoids the former flat `Vec<u8>` copy of the same image. + let Some(img) = lightcraft_raster::Rgba8::from_pixels(w, h, image.pixels.iter().map(|c| c.to_array())) else { return json!({"ok": false, "error": "bad screenshot buffer"}); }; let Some(png) = app.services.png.as_ref() else { return json!({"ok": false, "error": "no encoder"}) }; let bytes = png(&img); - match app.services.write.as_mut() { - Some(wr) => match wr(path, &bytes) { + let path = target.path(); + if target.was_absent() { + // Publish a complete temp file with create-new semantics: a file that appeared after the + // revalidation above is never replaced. Without this writer the capture fails closed. + let Some(writer) = app.services.write_new.as_mut() else { + return json!({"ok": false, "error": format!("{path}: no create-new writer configured for a new screenshot path")}); + }; + match writer(path, &bytes) { Ok(()) => json!({"ok": true, "result": {"path": path, "width": w, "height": h}}), Err(e) => json!({"ok": false, "error": e}), - }, - None => json!({"ok": false, "error": "no writer configured"}), + } + } else { + match app.services.write.as_mut() { + Some(wr) => match wr(path, &bytes) { + Ok(()) => json!({"ok": true, "result": {"path": path, "width": w, "height": h}}), + Err(e) => json!({"ok": false, "error": e}), + }, + None => json!({"ok": false, "error": "no writer configured"}), + } } } diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index d451aa79d0..5786160685 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -229,7 +229,7 @@ fn name_link(app: &mut LightcraftApp, ui: &mut egui::Ui, c: &Contributor, names: /// About ▸ Contributors: a name toggle, a sort, and the list as a grab bag or a table. pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let id = egui::Id::new("credits_view"); + let id = egui::Id::unique("credits_view"); let mut v = ui.data_mut(|d| d.get_temp::<View>(id)).unwrap_or_default(); ui.horizontal_wrapped(|ui| { ui.label(crate::i18n::tr("Show")); @@ -240,7 +240,7 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) { } ui.separator(); ui.label(crate::i18n::tr("Sort")); - crate::widgets::combo_box("credits_sort").selected_text(crate::i18n::tr(v.key.label().0)).show_ui(ui, |ui| { + let sort = crate::widgets::combo_box("credits_sort").selected_text(crate::i18n::tr(v.key.label().0)).show_ui(ui, |ui| { for k in SortKey::ALL { if ui.selectable_label(v.key == k, crate::i18n::tr(k.label().0)).clicked() { v.key = k; @@ -248,20 +248,21 @@ pub fn contributors_ui(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } }); + crate::widgets::name_combo(&sort.response, crate::i18n::tr("Sort")); let reverse = crate::widgets::arrow_button(ui, "", if v.ascending { crate::icons::Icon::ChevronUp } else { crate::icons::Icon::ChevronDown }, false); - reverse.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("Reverse the order"))); + reverse.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), crate::i18n::tr("Reverse the order"))); if reverse.on_hover_text(crate::i18n::tr("Reverse the order")).clicked() { v.ascending = !v.ascending; } ui.separator(); let r = ui.selectable_label(!v.table, crate::i18n::tr("Grab bag")); - crate::widgets::register(ui.ctx(), "button:creditsGrabBag", r.rect); + crate::widgets::register(ui, "button:creditsGrabBag", r.rect); if r.clicked() { v.table = false; } let r = ui.selectable_label(v.table, crate::i18n::tr("Table")); - crate::widgets::register(ui.ctx(), "button:creditsTable", r.rect); + crate::widgets::register(ui, "button:creditsTable", r.rect); if r.clicked() { v.table = true; } diff --git a/crates/ui-egui/src/date_picker.rs b/crates/ui-egui/src/date_picker.rs index c84df98c4c..eda461eb72 100644 --- a/crates/ui-egui/src/date_picker.rs +++ b/crates/ui-egui/src/date_picker.rs @@ -238,8 +238,8 @@ impl<'a> DatePicker<'a> { pub fn show(self, ui: &mut Ui) -> Response { let DatePicker { id, value, precisions, min, max, today } = self; let mut button = crate::widgets::icon_button(ui, &format!("datePicker:{id}"), Icon::Calendar, vec2(24.0, 22.0), false, true, "Pick a date"); - register(ui.ctx(), format!("datePicker:{id}"), button.rect); - let state = egui::Id::new(("datePicker", id.as_str())); + register(ui, format!("datePicker:{id}"), button.rect); + let state = egui::Id::unique(("datePicker", id.as_str())); if button.clicked() { // open on the value (or today), at its precision when it is one of those offered let at = value.or(today).unwrap_or(PickedDate::year(2026)); @@ -257,7 +257,7 @@ impl<'a> DatePicker<'a> { ui.horizontal(|ui| { for p in precisions { let r = ui.selectable_label(view.precision == *p, crate::i18n::tr(p.label())); - register(ui.ctx(), format!("datePickerPrecision:{}:{id}", p.id()), r.rect); + register(ui, format!("datePickerPrecision:{}:{id}", p.id()), r.rect); if r.clicked() { view.precision = *p; } @@ -267,8 +267,8 @@ impl<'a> DatePicker<'a> { } ui.horizontal(|ui| { let prev = crate::widgets::arrow_button(ui, "", Icon::ChevronLeft, true); - prev.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("Previous page"))); - register(ui.ctx(), format!("datePickerPrev:{id}"), prev.rect); + prev.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), crate::i18n::tr("Previous page"))); + register(ui, format!("datePickerPrev:{id}"), prev.rect); let title = match view.precision { Precision::Day => crate::i18n::date_group_label(&format!("{:04}-{:02}", view.year, view.month), false), Precision::Month => format!("{:04}", view.year), @@ -280,8 +280,8 @@ impl<'a> DatePicker<'a> { ui.label(RichText::new(title).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let next = crate::widgets::arrow_button(ui, "", Icon::ChevronRight, false); - next.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr("Next page"))); - register(ui.ctx(), format!("datePickerNext:{id}"), next.rect); + next.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), crate::i18n::tr("Next page"))); + register(ui, format!("datePickerNext:{id}"), next.rect); if next.clicked() { view = step(view, true); } @@ -294,7 +294,7 @@ impl<'a> DatePicker<'a> { let allowed = in_bounds(&date, min.as_ref(), max.as_ref()); let text = if holds_today(&date, today) { RichText::new(text).strong().underline() } else { RichText::new(text) }; let r = ui.add_enabled(allowed, egui::Button::selectable(*value == Some(date), text).min_size(vec2(26.0, 0.0))); - register(ui.ctx(), format!("datePickerCell:{}:{id}", date.iso()), r.rect); + register(ui, format!("datePickerCell:{}:{id}", date.iso()), r.rect); if r.clicked() { *picked = Some(date); } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index e9f51a56fe..a8ef56f398 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -370,7 +370,7 @@ pub(crate) fn cancel_replaced_gesture(app: &crate::LightcraftApp, workspace: Opt _ => true, }; if replaced && let Some(ctx) = &app.tasks.repaint { - craft_ui::docking::cancel_drag::<Panel>(ctx, egui::Id::new("lightcraft-docking")); + craft_ui::docking::cancel_drag::<Panel>(ctx, egui::Id::unique("lightcraft-docking")); } } @@ -397,11 +397,15 @@ fn command_impl(app: &mut crate::LightcraftApp, reset: bool, params: &Value, ren Ok(json!({"docking": app.ui.docking})) } +/// Draw the docked workspace: restore or fall back from an invalid layout, sync panel +/// visibility, render the panels and the current view in the canvas, then apply the docking +/// actions. If the layout changed during the pass, any in-flight dock drag is cancelled and the +/// docking actions it produced are not applied. pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { let t = crate::theme::Tokens::get(ui.ctx()); let mut workspace = app.ui.docking.clone().unwrap_or_else(|| from_ui(app)); if let Err(error) = workspace.validate().and_then(|()| sync(&mut workspace, app)) { - app.ui.toast = Some((format!("Panel layout could not be restored: {error}"), ui.input(|input| input.time) + 8.0, None)); + app.ui.toast = Some((format!("Panel layout could not be restored: {error}"), app.tick_now() + 8.0, None)); workspace = from_ui(app); let _ = sync(&mut workspace, app); } @@ -427,7 +431,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { style.font = t.font(12.0); // Tool and preset panels publish hover previews before the photo consumes them. let mut canvas = None; - let output = DockArea::new(egui::Id::new("lightcraft-docking")).show_with_limits( + let output = DockArea::new(egui::Id::unique("lightcraft-docking")).show_with_limits( ui, &workspace.layout, &style, @@ -439,11 +443,11 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { canvas = Some(ui.new_child(egui::UiBuilder::new().id_salt("photo-view").max_rect(ui.max_rect()))); } Panel::Library => { - crate::widgets::register(ui.ctx(), "panel:left_panel", ui.max_rect()); + crate::widgets::register(ui, "panel:left_panel", ui.max_rect()); crate::panels::left::show(app, ui); } Panel::Tools => { - crate::widgets::register(ui.ctx(), "panel:right_panel", ui.max_rect()); + crate::widgets::register(ui, "panel:right_panel", ui.max_rect()); crate::panels::right::show(app, ui); } Panel::Presets => crate::panels::presets::show(app, ui), @@ -476,7 +480,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { let _ = sync(&mut workspace, app); let stale = workspace.layout != rendered.layout || workspace.hidden != rendered.hidden; if stale { - craft_ui::docking::cancel_drag::<Panel>(ui.ctx(), egui::Id::new("lightcraft-docking")); + craft_ui::docking::cancel_drag::<Panel>(ui.ctx(), egui::Id::unique("lightcraft-docking")); } publish_visibility(app, &workspace); app.ui.docking = Some(workspace); @@ -488,7 +492,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { .map_err(|error| error.to_string()) .and_then(|action| command_impl(app, false, &json!({"action": action}), true)) { - app.ui.toast = Some((format!("Panel move was not applied: {error}"), ui.input(|input| input.time) + 8.0, None)); + app.ui.toast = Some((format!("Panel move was not applied: {error}"), app.tick_now() + 8.0, None)); } } } diff --git a/crates/ui-egui/src/drop_overlay.rs b/crates/ui-egui/src/drop_overlay.rs new file mode 100644 index 0000000000..8be75ee888 --- /dev/null +++ b/crates/ui-egui/src/drop_overlay.rs @@ -0,0 +1,104 @@ +//! What dropping the files dragged over the window will do: the same sorting the drop applies, +//! shown on a veil over the whole window while the drag lasts. + +use egui::{Align2, Color32, Context, Order, Rect, Stroke, StrokeKind, vec2}; + +use crate::LightcraftApp; +use crate::theme::Tokens; + +/// Dropped paths by what becomes of them. +#[derive(Default, Debug, PartialEq)] +pub struct Sorted { + /// Face models (`.onnx`): the first opens the licence dialog. + pub models: Vec<String>, + /// Preset files: imported as presets. + pub presets: Vec<String>, + /// Everything else: photos and folders, for the import. + pub photos: Vec<String>, +} + +/// Sort `paths` as a drop does. +pub fn classify(paths: Vec<String>) -> Sorted { + let (models, rest): (Vec<String>, Vec<String>) = paths.into_iter().partition(|p| crate::is_model_file(p)); + let (presets, photos) = crate::split_presets(rest); + Sorted { models, presets, photos } +} + +/// The lines the card shows for files hovering over the window (`unknown`: how many have no path +/// to look at, as on some platforms and in browsers), for the current settings. +fn lines(app: &LightcraftApp, paths: Vec<String>, unknown: bool) -> Vec<String> { + if app.ui.dialog.is_some() { + return vec![crate::i18n::tr("Close the open dialog to drop files here").to_string()]; + } + let drop = classify(paths); + let mut out = Vec::new(); + if !drop.models.is_empty() { + out.push(crate::i18n::tr("Drop to open the face model").to_string()); + } + let plural = |n: usize| if n == 1 { "" } else { "s" }; + // no library open yet (desktop: the web build's drops import into its session as before): + // photos wait for the library chosen, presets are refused (the drop handler does the same) + let waiting = crate::panels::library_problem::holds_drops(app) && !cfg!(target_arch = "wasm32"); + if !drop.presets.is_empty() && waiting { + out.push(crate::i18n::tr("Open a library first, then drop the presets again").to_string()); + } else if !drop.presets.is_empty() { + let n = drop.presets.len(); + out.push(crate::i18n::tr_format!("Drop to import {n} preset{}", plural(n), n = n)); + } + if !drop.photos.is_empty() && waiting { + out.push(crate::i18n::tr("The photos are imported once a library is open").to_string()); + } else if !drop.photos.is_empty() && app.lightroom.is_some() && !cfg!(target_arch = "wasm32") { + // the drop is refused while a Lightroom catalog import owns the catalog + out.push(crate::i18n::tr("Finish Lightroom catalog import before adding photos").to_string()); + } else if !drop.photos.is_empty() && crate::import::running(app) && !cfg!(target_arch = "wasm32") { + out.push(crate::i18n::tr("An import is running. Drop photos when it has finished").to_string()); + } else if !drop.photos.is_empty() { + let n = drop.photos.len(); + // the web build has no review to open: its drops import at once + if app.ui.settings.import_dropped_directly || cfg!(target_arch = "wasm32") { + out.push(crate::i18n::tr_format!("Drop to import {n} item{}", plural(n), n = n)); + } else { + out.push(crate::i18n::tr_format!("Drop to review {n} item{} for import", plural(n), n = n)); + } + } + if out.is_empty() || unknown { + out.push(crate::i18n::tr("Drop to import").to_string()); + } + out +} + +/// Veil and card while files are dragged over the window. +pub fn show(app: &LightcraftApp, ctx: &Context) { + // This card is an `Order::Tooltip` layer, above the prompt's Foreground window. While a prompt + // owns input the drag can only be background noise: do not paint over or register it. + if crate::panels::notices::blocks_input(app) { + return; + } + let count = ctx.input(|i| i.raw.hovered_files.len()); + if count == 0 { + return; + } + let known: Vec<String> = ctx.input(|i| { + i.raw.hovered_files.iter().filter_map(|f| f.path.as_ref()).map(|p| p.to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect() + }); + let lines = lines(app, known.clone(), known.len() < count); + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let painter = ctx.layer_painter(egui::LayerId::new(Order::Tooltip, egui::Id::unique("drop-overlay"))); + painter.rect_filled(screen, 0.0, Color32::from_black_alpha(150)); + painter.rect_stroke(screen.shrink(10.0), 12.0, Stroke::new(2.0, t.accent), StrokeKind::Inside); + let galleys: Vec<_> = lines.into_iter().map(|l| painter.layout(l, t.semibold(18.0), t.text, (screen.width() - 120.0).max(200.0))).collect(); + let (w, h) = galleys.iter().fold((0.0f32, 0.0f32), |(w, h), g| (w.max(g.size().x), h + g.size().y + 8.0)); + let card = Rect::from_center_size(screen.center(), vec2(w + 64.0, h + 40.0)); + painter.rect_filled(card, 10.0, t.chrome); + painter.rect_stroke(card, 10.0, Stroke::new(1.0, t.accent), StrokeKind::Inside); + let mut y = card.top() + 24.0; + for g in galleys { + let at = egui::pos2(card.center().x, y); + let height = g.size().y; + painter.galley(Align2::CENTER_TOP.anchor_size(at, g.size()).min, g, t.text); + y += height + 8.0; + } + crate::widgets::register_geometry(ctx, "dropOverlay", card); + ctx.request_repaint(); +} diff --git a/crates/ui-egui/src/focus_scan.rs b/crates/ui-egui/src/focus_scan.rs index de6e292dc3..66e8174e3f 100644 --- a/crates/ui-egui/src/focus_scan.rs +++ b/crates/ui-egui/src/focus_scan.rs @@ -10,8 +10,7 @@ use crate::LightcraftApp; const BUSY_SECS: f64 = 0.25; /// Called every frame. Idle, it costs a comparison and wakes nothing; reading, it asks again every [`BUSY_SECS`]. -pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { - let now = ctx.input(|i| i.time); +pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { if now < app.caches.focus_next_pump { return; } diff --git a/crates/ui-egui/src/frame_rate.rs b/crates/ui-egui/src/frame_rate.rs new file mode 100644 index 0000000000..b213963afd --- /dev/null +++ b/crates/ui-egui/src/frame_rate.rs @@ -0,0 +1,313 @@ +//! Help ▸ Debug ▸ Frame Rate (`view.frameRate`; `LIGHTCRAFT_FPS=1` starts with it on): a +//! frame-rate display in the window's top-right corner, to watch how a slider drag or a zoom holds +//! up. It shows where a frame's time goes: the UI +//! thread's CPU time (layout, painting, texture uploads) and the rest of the frame interval, which +//! is waiting — for vsync, or for the GPU when render work is ahead of the window's frame. A +//! tick over the graph marks each frame in which a render arrived, so spikes can be put next to +//! renders. While it shows, the window repaints continuously, so the rate is the one a drag gets. + +use std::collections::VecDeque; + +use crate::LightcraftApp; +use crate::render::Slot; + +/// Frames kept for the graph (about two seconds at 120 Hz). +const KEEP: usize = 240; + +/// A gap between frames longer than this is a pause (window hidden or occluded, the machine +/// asleep), not a frame: the display starts counting again instead of showing it as a spike. +const PAUSE: f64 = 2.0; + +#[derive(Clone, Copy)] +pub(crate) struct Frame { + at: f64, + /// Seconds since the previous frame. + pub(crate) dt: f64, + /// The previous frame's CPU time on the UI thread, seconds. + cpu: f64, + /// Renders that arrived this frame. + renders: u64, + /// Of those, thrown away (superseded by a newer request). + discarded: u64, +} + +/// The display's state, kept in the context's temp data (one per window or headless view) and +/// dropped while the display is off, so turning it back on starts a fresh count. +#[derive(Clone, Default)] +struct Hud { + last: Option<f64>, + completed: u64, + discarded: u64, + frames: VecDeque<Frame>, + /// When the numbers were last logged. + logged: Option<f64>, +} + +/// Stable egui data id under which the FPS HUD's per-frame state is stored. +fn hud_id() -> egui::Id { + egui::Id::unique("fps-hud-state") +} + +/// The display is off: drop its state, so the time it was off never shows as one long frame. +pub(crate) fn forget(ctx: &egui::Context) { + ctx.data_mut(|d| d.remove::<Hud>(hud_id())); +} + +/// Record a frame at `now` (`completed`/`discarded`: the renderer's running totals; `cpu`: the +/// previous frame's UI CPU time, seconds). Returns the frames kept for the display, and whether +/// the numbers are due in the log (once a second; A/B runs read them). +fn record(ctx: &egui::Context, now: f64, completed: u64, discarded: u64, cpu: f64) -> (Vec<Frame>, bool) { + ctx.data_mut(|d| { + let hud = d.get_temp_mut_or_default::<Hud>(hud_id()); + match hud.last { + Some(prev) if now - prev > PAUSE || now < prev => hud.frames.clear(), + Some(prev) => { + let renders = completed.saturating_sub(hud.completed); + let thrown = discarded.saturating_sub(hud.discarded); + hud.frames.push_back(Frame { at: now, dt: (now - prev).max(1e-6), cpu, renders, discarded: thrown }); + while hud.frames.len() > KEEP { + hud.frames.pop_front(); + } + } + None => {} + } + hud.last = Some(now); + hud.completed = completed; + hud.discarded = discarded; + let log = hud.logged.is_none_or(|t| now - t >= 1.0 || now < t); + if log { + hud.logged = Some(now); + } + (hud.frames.iter().copied().collect(), log) + }) +} + +/// The frames the display holds now (tests). +#[cfg(test)] +pub(crate) fn frames(ctx: &egui::Context) -> Vec<Frame> { + ctx.data_mut(|d| d.get_temp::<Hud>(hud_id())).map(|h| h.frames.into_iter().collect()).unwrap_or_default() +} + +fn mb(bytes: u64) -> f64 { + bytes as f64 / (1 << 20) as f64 +} + +/// Count this frame and draw the display over everything. +pub fn show(ctx: &egui::Context, app: &LightcraftApp) { + let now = ctx.input(|i| i.time); + let cpu = app.perf.host_frame_ms.unwrap_or(0.0) / 1e3; + let (frames, log) = record(ctx, now, app.renderer.completed, app.renderer.discarded, cpu); + + let recent: Vec<&Frame> = frames.iter().filter(|f| now - f.at <= 1.0).collect(); + let fps_now = frames.last().map_or(0.0, |f| 1.0 / f.dt); + let worst = recent.iter().copied().max_by(|a, b| a.dt.total_cmp(&b.dt)); + let avg_fps = if recent.is_empty() { 0.0 } else { recent.len() as f64 / recent.iter().map(|f| f.dt).sum::<f64>().max(1e-6) }; + let slow = recent.iter().filter(|f| f.dt > 1.0 / 50.0).count(); + let renders_s: u64 = recent.iter().map(|f| f.renders).sum(); + let discarded_s: u64 = recent.iter().map(|f| f.discarded).sum(); + let window = app.renderer.textures.get(&Slot::Region); + let mem = lightcraft_engine::gpu::memory(); + // (`ready` first: `available` would wait for a device still being created) + let device = match lightcraft_engine::gpu::unavailable_reason() { + Some(why) => format!("off ({why})"), + None if lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available() => { + lightcraft_engine::gpu::adapter_name().unwrap_or_else(|| "on".into()) + } + None => "starting…".into(), + }; + if log { + let (wdt, wcpu) = worst.map_or((0.0, 0.0), |w| (w.dt * 1e3, w.cpu * 1e3)); + let p95 = { + let mut d: Vec<f64> = recent.iter().map(|f| f.dt * 1e3).collect(); + d.sort_by(f64::total_cmp); + d.get(d.len().saturating_sub(1) * 95 / 100).copied().unwrap_or(0.0) + }; + log::info!( + "fps-hud: frames {} slow>20ms {slow} p95 {p95:.1} worst {wdt:.1} (cpu {wcpu:.1}) renders {renders_s} discarded {discarded_s} window {:.1} gpu {device}", + recent.len(), + window.map_or(0.0, |t| t.ms) + ); + } + let lines = [ + format!("{fps_now:>4.0} fps avg {avg_fps:.0} {slow} frames > 20 ms in 1 s"), + match worst { + Some(w) => format!("worst {:.1} ms = CPU {:.1} + wait {:.1}", w.dt * 1e3, w.cpu * 1e3, (w.dt - w.cpu).max(0.0) * 1e3), + None => "worst –".to_string(), + }, + format!("UI CPU {:.1} ms (update {:.1})", app.perf.host_frame_ms.unwrap_or(0.0), app.perf.update_ms), + format!("render frame {:.1} ms", app.renderer.last_main_ms), + match window { + Some(t) => format!("render window {:.1} ms", t.ms), + None => "render window –".to_string(), + }, + format!("renders: {} queued, {} running, {renders_s}/s ({discarded_s} thrown away)", app.renderer.queued(), app.renderer.in_flight()), + format!("GPU: {device}"), + format!("GPU mem {:.0} MB (+{:.0} pooled)", mb(mem.allocated), mb(mem.pooled)), + ]; + + let screen = ctx.content_rect(); + let width = 300.0; + egui::Area::new(egui::Id::unique("fps-hud")) + .order(egui::Order::Tooltip) + .fixed_pos(egui::pos2(screen.right() - width - 24.0, screen.top() + 56.0)) + .interactable(false) + .show(ctx, |ui| { + egui::Frame::new().fill(egui::Color32::from_black_alpha(210)).corner_radius(6.0).inner_margin(8.0).show(ui, |ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing.y = 1.0; + for l in &lines { + ui.label(egui::RichText::new(l).monospace().size(11.0).color(egui::Color32::from_gray(230))); + } + ui.add_space(4.0); + graph(ui, &frames, width); + ui.label( + egui::RichText::new("bars: blue = UI CPU, orange/red = waiting · ticks = a render arrived · line = 60 fps") + .size(9.0) + .color(egui::Color32::from_gray(160)), + ); + }); + }); + // a rate the drag gets, not the idle one + ctx.request_repaint(); +} + +/// Frame intervals, 0 at the bottom and 50 ms at the top: the UI thread's CPU part in blue and +/// the waiting part above it (green within 60 fps, orange within 30, red beyond), with a tick +/// over each frame in which a render arrived. +fn graph(ui: &mut egui::Ui, frames: &[Frame], width: f32) { + let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 70.0), egui::Sense::hover()); + let p = ui.painter_at(rect); + let plot = egui::Rect::from_min_max(egui::pos2(rect.left(), rect.top() + 6.0), rect.max); + let y = |ms: f64| plot.bottom() - (ms / 50.0).clamp(0.0, 1.0) as f32 * plot.height(); + let w = rect.width() / KEEP as f32; + let start = KEEP.saturating_sub(frames.len()); + for (i, f) in frames.iter().enumerate() { + let (ms, cpu) = (f.dt * 1e3, (f.cpu * 1e3).min(f.dt * 1e3)); + let x = rect.left() + (start + i) as f32 * w; + let bar = |from: f64, to: f64, c: egui::Color32| { + p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, y(to)), egui::pos2(x + w.max(1.0), y(from))), 0.0, c); + }; + let wait = if ms > 33.4 { + egui::Color32::from_rgb(230, 80, 70) + } else if ms > 17.5 { + egui::Color32::from_rgb(235, 160, 60) + } else { + egui::Color32::from_rgb(110, 190, 110) + }; + bar(cpu, ms, wait); + bar(0.0, cpu, egui::Color32::from_rgb(90, 150, 240)); + if f.renders > 0 { + p.rect_filled( + egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(x + w.max(1.0), rect.top() + 4.0)), + 0.0, + egui::Color32::WHITE, + ); + } + } + p.hline(rect.x_range(), y(1000.0 / 60.0), egui::Stroke::new(1.0, egui::Color32::from_rgb(90, 200, 90))); + p.hline(rect.x_range(), y(1000.0 / 30.0), egui::Stroke::new(1.0, egui::Color32::from_rgb(200, 90, 80).gamma_multiply(0.6))); +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use serde_json::json; + + use crate::headless::Headless; + use crate::menubar::{MenuNode, menu_bar}; + use crate::{LightcraftApp, Services}; + + const T: Duration = Duration::from_secs(20); + + fn set(h: &mut Headless, params: serde_json::Value) -> Option<bool> { + let r = h.request("engine.execute", json!({"command": "view.frameRate", "params": params}), T); + assert_eq!(r["ok"], true, "{r}"); + r["result"]["show"].as_bool() + } + + /// The Help ▸ Debug item for it, and its checkmark. + fn debug_item(app: &LightcraftApp) -> Option<Option<bool>> { + let help = menu_bar(app).into_iter().find(|(t, _)| t == "Help").map(|(_, items)| items).unwrap_or_default(); + help.into_iter().find_map(|n| match n { + MenuNode::Submenu { label, children } if label == "Debug" => children.into_iter().find_map(|c| match c { + MenuNode::Item { id, checked, .. } if id == "view.frameRate" => Some(checked), + _ => None, + }), + _ => None, + }) + } + + /// Help ▸ Debug ▸ Frame Rate toggles the display (a checked menu item), `{show}` sets it, + /// and frames draw with it on. + #[test] + fn show_frame_rate_is_a_debug_toggle() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + let was = h.app.ui.frame_rate; + assert_eq!(debug_item(&h.app), Some(Some(was)), "Help ▸ Debug lists it, checked as it is"); + assert_eq!(set(&mut h, json!({})), Some(!was)); + assert_eq!(debug_item(&h.app), Some(Some(!was))); + // frames with the display on draw (and keep the window repainting) + assert_eq!(set(&mut h, json!({"show": true})), Some(true)); + for _ in 0..3 { + h.step(); + } + assert_eq!(set(&mut h, json!({"show": false})), Some(false)); + assert!(!h.app.ui.frame_rate); + } + + fn worst_ms(h: &Headless) -> f64 { + super::frames(&h.view.ctx).iter().map(|f| f.dt * 1e3).fold(0.0, f64::max) + } + + /// Turned off and on again later, the display starts a fresh count: the time it was off is not + /// one long frame (a red spike and a "worst" of the whole time off). + #[test] + fn turning_it_back_on_shows_no_spike_for_the_time_it_was_off() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + set(&mut h, json!({"show": true})); + for _ in 0..3 { + h.step(); + } + assert!(!super::frames(&h.view.ctx).is_empty(), "frames are counted while it shows"); + set(&mut h, json!({"show": false})); + h.step(); + h.time += 1.5; + set(&mut h, json!({"show": true})); + for _ in 0..3 { + h.step(); + } + assert!(worst_ms(&h) < 1000.0, "worst frame {} ms after turning it back on", worst_ms(&h)); + } + + /// A pause while it shows (window hidden, machine asleep) starts a fresh count too. + #[test] + fn a_long_pause_while_it_shows_is_not_a_frame() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + set(&mut h, json!({"show": true})); + for _ in 0..3 { + h.step(); + } + h.time += 30.0; + for _ in 0..3 { + h.step(); + } + assert!(worst_ms(&h) < 1000.0, "worst frame {} ms after a pause", worst_ms(&h)); + } + + /// Each window (egui context) keeps its own count. + #[test] + fn each_context_keeps_its_own_count() { + let (a, b) = (egui::Context::default(), egui::Context::default()); + for t in [0.0, 0.016, 0.033] { + super::record(&a, t, 0, 0, 0.0); + } + assert_eq!(super::frames(&a).len(), 2); + assert!(super::frames(&b).is_empty()); + let (frames, _) = super::record(&b, 100.0, 0, 0, 0.0); + assert!(frames.is_empty(), "a new context's first frame has no interval: {}", frames.len()); + } +} diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index acd513e98b..c47bd27737 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -13,7 +13,6 @@ //! is occluded. use std::collections::HashMap; -use std::sync::Arc; use std::sync::mpsc::Sender; use std::time::{Duration, Instant}; @@ -36,6 +35,10 @@ pub fn viewport_pixels(size: [f32; 2], pixels_per_point: f32) -> Result<[usize; native_viewport_pixels(size, pixels_per_point) } +/// Turn a logical viewport size into native pixels for the headless renderer. Both edges and +/// the scale must be finite and positive; each scaled edge is rounded like egui's scissor and +/// must be within `1..=MAX_IMAGE_EDGE`, and the product must fit both the raster and screenshot +/// pixel budgets. Returns a user-facing error instead of clamping. fn native_viewport_pixels(size: [f32; 2], pixels_per_point: f32) -> Result<[usize; 2], String> { let [width, height] = size; if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 || !pixels_per_point.is_finite() || pixels_per_point <= 0.0 { @@ -50,8 +53,11 @@ fn native_viewport_pixels(size: [f32; 2], pixels_per_point: f32) -> Result<[usiz Ok(pixels as usize) }; let (w, h) = (axis(width)?, axis(height)?); - if w.checked_mul(h).is_none_or(|pixels| pixels > softpaint::MAX_IMAGE_PIXELS) { - return Err(format!("scaled viewport exceeds {} pixels", softpaint::MAX_IMAGE_PIXELS)); + // The rasterizer's limit is not enough: a screenshot is also bounded by the RGBA budget it is + // admitted against, so reject a size `ui.screenshot` would only refuse later. + let max_pixels = softpaint::MAX_IMAGE_PIXELS.min(crate::MAX_SHOT_PIXELS); + if w.checked_mul(h).is_none_or(|pixels| pixels > max_pixels) { + return Err(format!("scaled viewport exceeds {max_pixels} pixels")); } Ok([w, h]) } @@ -156,7 +162,20 @@ impl HeadlessView { self.clipboard.clone_from(text); } } - let commands = out.viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(); + let mut commands = out.viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(); + // 0.37: `ViewportCommand::Screenshot` carries a one-shot callback. A headless host answers + // it here, after the pass it was issued in, exactly once. + let mut shots = Vec::new(); + commands.retain(|command| match command { + ViewportCommand::Screenshot(callback) => { + shots.push(callback.clone()); + false + } + _ => true, + }); + for callback in shots { + callback.complete(std::sync::Arc::new(self.paint(&std::collections::HashMap::new()))); + } // what a desktop host does with a cut, copy or paste request (egui-winit): the event, next frame for c in &commands { match c { @@ -234,17 +253,22 @@ pub struct Headless { /// Logical size (points) and scale. pub size: egui::Vec2, pub pixels_per_point: f32, - time: f64, + pub(crate) time: f64, frames: u64, pub(crate) events: Vec<egui::Event>, control: Sender<ControlRequest>, quit: bool, /// The simulated window is zoomed (`Maximized(true)` seen, reported back to the app like a real host). pub window_maximized: bool, - /// Window-management commands the app sent (`StartDrag`, `Maximized`, …), oldest first. + /// Window-management and pointer commands the app sent (`StartDrag`, `Maximized`, + /// `CursorPosition`, …), oldest first. pub window_commands: Vec<ViewportCommand>, /// The pointer cursor the last frame asked for (what a real host would show). pub last_cursor: egui::CursorIcon, + /// Test-only hook run after `raw_input_hook` and before `logic`/`ui`, as eframe does: it can + /// create a prompt after the host input was already filtered for the previous frame. + #[cfg(test)] + after_raw_input_hook: Option<Box<dyn FnMut(&mut LightcraftApp)>>, } /// A headless run (`lightcraft-cli snapshot`, tests) is a one-shot process: however it ends, it @@ -285,9 +309,19 @@ impl Headless { window_maximized: false, window_commands: vec![], last_cursor: egui::CursorIcon::Default, + #[cfg(test)] + after_raw_input_hook: None, } } + /// Run `hook` once, between the next frame's [`LightcraftApp::raw_input_hook`] and its + /// `logic`/`ui` call. This is the production order in eframe: a prompt can be created there + /// after the host input was already accepted for the frame. + #[cfg(test)] + pub(crate) fn set_after_raw_input_hook(&mut self, hook: impl FnMut(&mut LightcraftApp) + 'static) { + self.after_raw_input_hook = Some(Box::new(hook)); + } + pub fn frames(&self) -> u64 { self.frames } @@ -314,7 +348,13 @@ impl Headless { raw.viewports.entry(ViewportId::ROOT).or_default().maximized = Some(self.window_maximized); raw.max_texture_side = (self.reported_texture_side != Some(self.max_texture_side)).then_some(self.max_texture_side); self.reported_texture_side = Some(self.max_texture_side); - self.app.raw_input_hook(&mut raw); + // A headless run's timers follow its simulated clock, not the host's wall clock. + self.app.set_simulated_clock(Some(self.time)); + self.app.raw_input_hook(&self.view.ctx, &mut raw); + #[cfg(test)] + if let Some(mut hook) = self.after_raw_input_hook.take() { + hook(&mut self.app); + } let app = &mut self.app; let mut cursor = egui::CursorIcon::Default; let commands = self.view.run(raw, |ui| { @@ -326,11 +366,10 @@ impl Headless { self.time += FRAME_DT; self.frames += 1; for c in commands { + // `ViewportCommand::Screenshot` never reaches here: `HeadlessView::run` answers the + // one-shot callback after the pass it was issued in, so there is exactly one reply. match c { - ViewportCommand::Screenshot(user_data) => { - let image = Arc::new(self.paint()); - self.events.push(egui::Event::Screenshot { viewport_id: ViewportId::ROOT, user_data, image }); - } + ViewportCommand::Screenshot(_) => {} ViewportCommand::InnerSize(size) => { // Viewport commands use current egui points, which include UI zoom. if let Ok(native_size) = resized_viewport([size.x, size.y], self.pixels_per_point, self.view.ctx.zoom_factor()) { @@ -342,7 +381,8 @@ impl Headless { self.window_maximized = on; self.window_commands.push(c); } - ViewportCommand::StartDrag => self.window_commands.push(c), + // recorded, not carried out: the simulated pointer moves only when a test moves it + ViewportCommand::StartDrag | ViewportCommand::CursorPosition(_) | ViewportCommand::CursorGrab(_) => self.window_commands.push(c), _ => {} } } @@ -362,6 +402,7 @@ impl Headless { || self.app.session.denoise_busy() || !self.app.tasks.is_empty() || !self.app.synthetic.is_empty() + || !self.app.pending_gestures.is_empty() || !self.events.is_empty() } @@ -597,6 +638,7 @@ mod tests { } use super::*; + use std::sync::Arc; /// The pretend host has a clipboard, as a desktop does: text the UI copies lands in it, and a /// cut, copy or paste request (from a context menu) comes back as that event on the next frame. @@ -628,7 +670,9 @@ mod tests { fn screenshot_dimensions_are_checked_before_layout() { assert_eq!(viewport_pixels([1600.0, 1000.0], 2.0).unwrap(), [3200, 2000]); assert_eq!(viewport_pixels([345.0, 200.0], 0.9).unwrap(), [311, 180]); - assert_eq!(viewport_pixels([8000.0, 8000.0], 1.0).unwrap(), [8000, 8000]); + // The largest accepted surface is exactly the 128 MiB screenshot budget (32 Mi pixels). + assert_eq!(viewport_pixels([16384.0, 2048.0], 1.0).unwrap(), [16384, 2048]); + assert_eq!(viewport_pixels([5792.0, 5792.0], 1.0).unwrap(), [5792, 5792]); for (size, scale) in [ ([f32::NAN, 10.0], 1.0), ([10.0, f32::INFINITY], 1.0), @@ -637,6 +681,9 @@ mod tests { ([10.0, 10.0], 0.0), ([0.0, 10.0], 1.0), ([10.0, 10.0], 0.01), + ([16384.0, 2049.0], 1.0), + ([8000.0, 8000.0], 1.0), + ([5793.0, 5793.0], 1.0), ([9000.0, 9000.0], 1.0), ([9000.0, 100.0], 2.0), ] { @@ -849,7 +896,7 @@ mod tests { let (Some(a), Some(b)) = (thumbs.first().cloned(), thumbs.get(1).cloned()) else { panic!("two grid photos: {thumbs:?}") }; let popup = |w: &str| { let id: u64 = w.trim_start_matches("thumb:").parse().expect("a photo id"); - egui::Id::new(("cell", id)).with("popup") + egui::Id::unique(("cell", id)).with("popup") }; assert!(!egui::Popup::is_any_open(&h.view.ctx)); let r = h.request("ui.clickWidget", json!({"id": a, "button": "right"}), t); @@ -1522,7 +1569,7 @@ mod tests { assert_eq!(names(&h), vec![Some("Jane Doe".into()), None, None, None, None, None, Some("John Roe".into())]); // With no target A cannot name a face, even on this page. h.request("ui.move", json!({"x": 1, "y": 1}), t); - h.view.ctx.memory_mut(|m| m.surrender_focus(egui::Id::new(("more-face-above", ids[2].0, 0_usize)))); + h.view.ctx.memory_mut(|m| m.surrender_focus(egui::Id::unique(("more-face-above", ids[2].0, 0_usize)))); set_page(&mut h); h.request("ui.key", json!({"key": "a"}), t); h.step(); @@ -1550,7 +1597,7 @@ mod tests { h.request("ui.move", json!({"x": 1, "y": 1}), t); set_page(&mut h); // Keyboard focus on the candidate makes the same batch action available without hovering it. - h.view.ctx.memory_mut(|m| m.request_focus(egui::Id::new(("more-face", ids[2].0, 0_usize)))); + h.view.ctx.memory_mut(|m| m.request_focus(egui::Id::unique(("more-face", ids[2].0, 0_usize)))); h.request("ui.key", json!({"key": "a"}), t); h.step(); assert_eq!( @@ -2018,6 +2065,30 @@ mod tests { assert!(deep.is_some_and(|n| n > 500), "scrolled rows: {later:?}"); } + /// With `label` and `labels` both set (a saved single-label filter, or an agent), the filter + /// bar lights only the labels that pass both, and a click starts from those, not their union. + #[test] + fn filter_bar_labels_from_label_and_labels() { + use lightcraft_catalog::ColorLabel; + let mut h = demo([1400.0, 800.0]); + let t = Duration::from_secs(10); + h.request("engine.execute", json!({"command": "view.filterBar"}), t); + h.app.session.execute("library.filter", &json!({"label": "red", "labels": ["red", "yellow"]})).unwrap(); + // a frame so the bar is laid out for the new filter before the click + h.step(); + let r = h.request("ui.clickWidget", json!({"id": "filter:label-green"}), t); + assert_eq!(r["ok"], true, "{r}"); + let f = h.app.session.filter.clone(); + assert_eq!((f.label, f.labels), (None, vec![ColorLabel::Red, ColorLabel::Green])); + // nothing passes both: nothing is lit, so a click shows just that label + h.app.session.execute("library.filter", &json!({"label": "red", "labels": ["yellow"]})).unwrap(); + h.step(); + h.request("ui.clickWidget", json!({"id": "filter:label-green"}), t); + let f = h.app.session.filter.clone(); + assert_eq!((f.label, f.labels), (None, vec![ColorLabel::Green])); + h.settle(SETTLE); + } + /// The filter bar drives `library.filter` and saves the view as a smart album. #[test] fn filter_bar_filters_and_saves_a_smart_album() { @@ -2495,7 +2566,7 @@ mod tests { assert!(!row.cancellable, "{row:?}"); assert!(h.app.session.activity.cancel(row.id).is_err(), "Photos can't be stopped once asked"); let current = h.app.export.as_ref().map(|e| e.progress.lock().unwrap().1.clone()).unwrap_or_default(); - assert_eq!(current, "Wird zu Apple Fotos hinzugefügt…"); + assert_eq!(current, crate::i18n::Locale::De.tr("Adding to Apple Photos…")); // the row says so on the next frame (issue #345) h.step(); let row = h.app.session.activity.list().into_iter().find(|r| r.kind == "export").expect("the export's row"); @@ -2830,6 +2901,25 @@ mod tests { assert!(!h.app.ui.visualize_spots); } + /// Bring a right-panel field into the visible panel before clicking it. The Info panel is a + /// scroll area: 0.37's roomier text rows push the place fields below a 1000-point window, and a + /// click at an off-screen rect would leave the previous field focused. + fn click_field_in_view(h: &mut Headless, key: &str, timeout: Duration) { + let id = format!("field:{key}"); + let panel = h.app.widgets.iter().find(|(w, _)| w == "panel:right_panel").map(|(_, r)| *r).expect("the right panel is laid out"); + let rect = h.app.widgets.iter().find(|(w, _)| *w == id).map(|(_, r)| *r).expect("the field is laid out"); + if !panel.contains(rect.center()) { + let dy = (panel.center().y - rect.center().y).clamp(-4000.0, 4000.0); + assert_eq!(h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), timeout)["ok"], true); + assert_eq!(h.request("ui.scroll", json!({"dy": dy}), timeout)["ok"], true); + h.settle(timeout); + } + let rect = h.app.widgets.iter().find(|(w, _)| *w == id).map(|(_, r)| *r).expect("the field is laid out"); + assert!(panel.contains(rect.center()), "the field must be scrolled into view before clicking: {rect:?} in {panel:?}"); + let r = h.request("ui.clickWidget", json!({"id": id}), timeout); + assert_eq!(r["ok"], true, "{r}"); + } + /// Info panel: typing into a field survives frames and is saved when it loses focus; the new /// accessibility and place fields reach the photo. #[test] @@ -2839,8 +2929,7 @@ mod tests { h.request("ui.set", json!({"view": "detail", "right": "info"}), t); h.settle(SETTLE); for (key, text) in [("altText", "A lake at dawn"), ("usageTerms", "Editorial use only"), ("city", "Zermatt")] { - let r = h.request("ui.clickWidget", json!({"id": format!("field:{key}")}), t); - assert_eq!(r["ok"], true, "{r}"); + click_field_in_view(&mut h, key, t); h.request("ui.key", json!({"key": "A", "cmd": true}), t); h.request("ui.text", json!({"text": text}), t); h.step(); @@ -2900,6 +2989,291 @@ mod tests { assert_eq!(meta(&h).title, "Wedding in Sintra"); } + /// With several photos selected the Info panel offers Target Photo / Selected Photos. Target + /// Photo (the default) shows the active photo's values. Selected Photos leaves a field whose + /// values differ empty, so what is typed there is what every selected photo gets, and keeps + /// the value of a field they share; leaving a mixed field untouched saves nothing. + #[test] + fn info_shows_metadata_for_the_selected_photos() { + let mut h = demo([1300.0, 1000.0]); + let t = Duration::from_secs(10); + let ask = |h: &mut Headless, method: &str, params: serde_json::Value| { + let r = h.request(method, params.clone(), t); + assert_eq!(r["ok"], true, "{method} {params}: {r}"); + h.step(); + h.step(); + r + }; + let exec = |h: &mut Headless, command: &str, params: serde_json::Value| { + ask(h, "engine.execute", json!({"command": command, "params": params}))["result"].clone() + }; + let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let (a, b) = (lightcraft_catalog::PhotoId(ids[0]), lightcraft_catalog::PhotoId(ids[1])); + let meta = |h: &Headless, id| h.app.session.catalog.photo(id).unwrap().meta.clone(); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "title": "Dawn", "copyrightStatus": "copyrighted"})); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "title": "Dusk"})); + exec(&mut h, "photo.setMeta", json!({"ids": ids, "creator": "Ana"})); + h.request("ui.set", json!({"view": "detail", "right": "info"}), t); + exec(&mut h, "library.select", json!({"ids": ids, "active": ids[0]})); + h.settle(SETTLE); + let buttons = |h: &mut Headless| h.request("ui.widgets", json!({"filter": "infoFor"}), t)["result"].to_string(); + assert!(buttons(&mut h).contains("button:infoFor-selected"), "the choice shows with two photos selected"); + assert!(h.app.ui.settings.info_selected_photos, "Selected Photos by default"); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "title": "Dawn!"})); + // Target Photo and back to Selected Photos, from their buttons + ask(&mut h, "ui.clickWidget", json!({"id": "button:infoFor-target"})); + assert!(!h.app.ui.settings.info_selected_photos); + ask(&mut h, "ui.clickWidget", json!({"id": "button:infoFor-selected"})); + assert!(h.app.ui.settings.info_selected_photos); + // a mixed field left untouched saves nothing + let undo = h.app.session.undo.len(); + click_field_in_view(&mut h, "title", t); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((meta(&h, a).title, meta(&h, b).title, h.app.session.undo.len()), ("Dawn!".into(), "Dusk".into(), undo)); + // neither does switching the choice while a field is being edited, either way + for on in [false, true] { + click_field_in_view(&mut h, "title", t); + exec(&mut h, "view.infoSelectedPhotos", json!({"on": on})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((meta(&h, a).title, meta(&h, b).title, h.app.session.undo.len()), ("Dawn!".into(), "Dusk".into(), undo), "{on}"); + } + // the mixed title starts empty; the shared creator keeps its value + for (key, typed, want) in [("title", "Harbor", "Harbor"), ("creator", " Silva", "Ana Silva")] { + click_field_in_view(&mut h, key, t); + ask(&mut h, "ui.key", json!({"key": "End"})); + ask(&mut h, "ui.text", json!({"text": typed})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + let got = |h: &Headless, id| if key == "title" { meta(h, id).title } else { meta(h, id).creator }; + assert_eq!((got(&h, a), got(&h, b)), (want.to_string(), want.to_string()), "{key}"); + } + // a mixed field typed in and left empty clears it on every selected photo + exec(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "caption": "Old"})); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "caption": "Other"})); + h.settle(SETTLE); + click_field_in_view(&mut h, "caption", t); + ask(&mut h, "ui.text", json!({"text": "x"})); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((meta(&h, a).caption, meta(&h, b).caption), (String::new(), String::new())); + // GPS: one photo's place and Show on Map only while the selected photos share it + let map = |h: &mut Headless| h.request("ui.widgets", json!({"filter": "showOnMap"}), t)["result"].to_string().contains("showOnMap"); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "gps": [41.15, -8.61]})); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "gps": [38.72, -9.14]})); + h.settle(SETTLE); + assert!(!map(&mut h), "places differ"); + exec(&mut h, "photo.setMeta", json!({"ids": ids, "gps": [41.15, -8.61]})); + h.settle(SETTLE); + assert!(map(&mut h), "a shared place"); + // the command: refuses a value that isn't true or false, and turns Target Photo back on + let r = h.request("engine.execute", json!({"command": "view.infoSelectedPhotos", "params": {"on": "yes"}}), t); + assert_ne!(r["ok"], true, "{r}"); + assert!(h.app.ui.settings.info_selected_photos); + assert_eq!(exec(&mut h, "view.infoSelectedPhotos", json!({"on": false}))["on"], false); + assert!(!h.app.ui.settings.info_selected_photos); + assert_eq!(exec(&mut h, "view.infoSelectedPhotos", json!({}))["on"], true, "no params toggles"); + // the choice is saved with the app settings; settings saved before it read as Selected Photos + exec(&mut h, "view.infoSelectedPhotos", json!({"on": false})); + let saved = serde_json::to_value(&h.app.ui.settings).unwrap(); + assert_eq!(saved["infoSelectedPhotos"], false); + let read: crate::state::AppSettings = serde_json::from_value(saved).unwrap(); + assert!(!read.info_selected_photos); + let old: crate::state::AppSettings = serde_json::from_value(json!({"filmNames": false})).unwrap(); + assert!(old.info_selected_photos); + // one photo selected: no choice to make + exec(&mut h, "library.select", json!({"ids": [ids[0]]})); + h.settle(SETTLE); + assert!(!buttons(&mut h).contains("infoFor-"), "{}", buttons(&mut h)); + } + + /// With several photos selected and the settings as they come, an edit to a field where the + /// photos differ starts from an empty field: the photos get what was typed, not the active + /// photo's value with the typing added. + #[test] + fn info_edits_of_a_multi_selection_start_from_mixed_fields_by_default() { + let mut h = demo([1300.0, 1000.0]); + let t = Duration::from_secs(10); + let ask = |h: &mut Headless, method: &str, params: serde_json::Value| { + let r = h.request(method, params.clone(), t); + assert_eq!(r["ok"], true, "{method} {params}: {r}"); + h.step(); + h.step(); + }; + let exec = |h: &mut Headless, command: &str, params: serde_json::Value| { + ask(h, "engine.execute", json!({"command": command, "params": params})); + }; + let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let caption = |h: &Headless, i: usize| h.app.session.catalog.photo(lightcraft_catalog::PhotoId(ids[i])).unwrap().meta.caption.clone(); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "caption": "Dawn"})); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "caption": "Dusk"})); + h.request("ui.set", json!({"view": "detail", "right": "info"}), t); + exec(&mut h, "library.select", json!({"ids": ids, "active": ids[0]})); + h.settle(SETTLE); + click_field_in_view(&mut h, "caption", t); + ask(&mut h, "ui.key", json!({"key": "End"})); + ask(&mut h, "ui.text", json!({"text": "Harbor"})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((caption(&h, 0), caption(&h, 1)), ("Harbor".into(), "Harbor".into())); + } + + /// Target Photo edits the photo it shows: with several photos selected, a field's edit is + /// saved to the active photo alone. + #[test] + fn info_target_photo_edits_only_the_photo_it_shows() { + let mut h = demo([1300.0, 1000.0]); + let t = Duration::from_secs(10); + let ask = |h: &mut Headless, method: &str, params: serde_json::Value| { + let r = h.request(method, params.clone(), t); + assert_eq!(r["ok"], true, "{method} {params}: {r}"); + h.step(); + h.step(); + }; + let exec = |h: &mut Headless, command: &str, params: serde_json::Value| { + ask(h, "engine.execute", json!({"command": command, "params": params})); + }; + let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(2).map(|p| p.0).collect(); + let caption = |h: &Headless, i: usize| h.app.session.catalog.photo(lightcraft_catalog::PhotoId(ids[i])).unwrap().meta.caption.clone(); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "caption": "Dawn"})); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "caption": "Dusk"})); + h.request("ui.set", json!({"view": "detail", "right": "info"}), t); + exec(&mut h, "library.select", json!({"ids": ids, "active": ids[0]})); + exec(&mut h, "view.infoSelectedPhotos", json!({"on": false})); + h.settle(SETTLE); + click_field_in_view(&mut h, "caption", t); + ask(&mut h, "ui.key", json!({"key": "End"})); + ask(&mut h, "ui.text", json!({"text": "!"})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((caption(&h, 0), caption(&h, 1)), ("Dawn!".into(), "Dusk".into())); + } + + /// The fields the Info panel marks as mixed: each text field, the copyright status and GPS + /// where a selected photo differs from the photo the panel shows, and none for one photo. + #[test] + fn info_mixed_fields_are_the_ones_that_differ() { + let mut s = lightcraft_engine::Session::with_demo(); + let ids: Vec<u64> = s.visible_cloned().iter().take(3).map(|p| p.0).collect(); + let all = |key: &str, v: serde_json::Value| json!({"ids": ids, key: v}); + // (every field the panel compares starts the same on the three photos) + let fields = [ + "title", + "caption", + "altText", + "extendedDescription", + "copyright", + "usageTerms", + "copyrightUrl", + "creator", + "location", + "state", + "country", + ]; + for key in fields { + s.execute("photo.setMeta", &all(key, json!(""))).unwrap(); + } + for (key, v) in + [("title", json!("Same")), ("city", json!("Porto")), ("copyrightStatus", json!("copyrighted")), ("gps", json!([41.15, -8.61]))] + { + s.execute("photo.setMeta", &all(key, v)).unwrap(); + } + let photos: Vec<lightcraft_catalog::PhotoId> = ids.iter().map(|&i| lightcraft_catalog::PhotoId(i)).collect(); + let shown = s.catalog.photo(photos[0]).unwrap().meta.clone(); + assert!(crate::panels::right::mixed_meta(&s.catalog, &photos, &shown).is_empty()); + assert!(crate::panels::right::mixed_meta(&s.catalog, &photos[..1], &shown).is_empty()); + s.execute("photo.setMeta", &json!({"ids": [ids[2]], "city": "Lisbon", "caption": "x", "gps": [38.72, -9.14]})).unwrap(); + s.execute("photo.setMeta", &json!({"ids": [ids[1]], "copyrightStatus": "publicDomain"})).unwrap(); + let mut mixed = crate::panels::right::mixed_meta(&s.catalog, &photos, &shown); + mixed.sort_unstable(); + assert_eq!(mixed, ["caption", "city", "copyrightStatus", "gps"]); + } + + /// Selected Photos with the active photo outside the selection: the fields show what the + /// selected photos share, not the active photo's values. + #[test] + fn info_selected_photos_ignore_an_active_photo_outside_the_selection() { + let mut h = demo([1300.0, 1000.0]); + let t = Duration::from_secs(10); + let ask = |h: &mut Headless, method: &str, params: serde_json::Value| { + let r = h.request(method, params.clone(), t); + assert_eq!(r["ok"], true, "{method} {params}: {r}"); + h.step(); + h.step(); + }; + let exec = |h: &mut Headless, command: &str, params: serde_json::Value| { + ask(h, "engine.execute", json!({"command": command, "params": params})); + }; + let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + let title = |h: &Headless, i: usize| h.app.session.catalog.photo(lightcraft_catalog::PhotoId(ids[i])).unwrap().meta.title.clone(); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[0], ids[1]], "title": "Same"})); + exec(&mut h, "photo.setMeta", json!({"ids": [ids[2]], "title": "Other"})); + h.request("ui.set", json!({"view": "detail", "right": "info"}), t); + exec(&mut h, "library.select", json!({"ids": [ids[0], ids[1]], "active": ids[2]})); + exec(&mut h, "view.infoSelectedPhotos", json!({"on": true})); + h.settle(SETTLE); + click_field_in_view(&mut h, "title", t); + ask(&mut h, "ui.key", json!({"key": "End"})); + ask(&mut h, "ui.text", json!({"text": "!"})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((title(&h, 0), title(&h, 1), title(&h, 2)), ("Same!".into(), "Same!".into(), "Other".into())); + } + + /// An Info field saves to the photos selected when its edit started, also when the selection + /// changes while the field is being edited. + #[test] + fn info_field_saves_to_the_photos_selected_when_the_edit_started() { + // (tall enough for the GPS field to show without scrolling) + let mut h = demo([1300.0, 1800.0]); + let t = Duration::from_secs(10); + let ask = |h: &mut Headless, method: &str, params: serde_json::Value| { + let r = h.request(method, params.clone(), t); + assert_eq!(r["ok"], true, "{method} {params}: {r}"); + h.step(); + h.step(); + }; + let exec = |h: &mut Headless, command: &str, params: serde_json::Value| { + ask(h, "engine.execute", json!({"command": command, "params": params})); + }; + let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(4).map(|p| p.0).collect(); + let meta = |h: &Headless, i: usize| h.app.session.catalog.photo(lightcraft_catalog::PhotoId(ids[i])).unwrap().meta.clone(); + exec(&mut h, "photo.setMeta", json!({"ids": ids, "title": "Same", "gps": ""})); + h.request("ui.set", json!({"view": "detail", "right": "info"}), t); + exec(&mut h, "library.select", json!({"ids": [ids[0], ids[1]], "active": ids[0]})); + h.settle(SETTLE); + click_field_in_view(&mut h, "title", t); + ask(&mut h, "ui.key", json!({"key": "End"})); + ask(&mut h, "ui.text", json!({"text": "!"})); + exec(&mut h, "library.select", json!({"ids": [ids[2]]})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((meta(&h, 0).title, meta(&h, 1).title, meta(&h, 2).title), ("Same!".into(), "Same!".into(), "Same".into())); + // GPS too (the new selection is two photos as well, so the panel keeps its layout) + exec(&mut h, "library.select", json!({"ids": [ids[0], ids[1]], "active": ids[0]})); + h.settle(SETTLE); + click_field_in_view(&mut h, "gps", t); + ask(&mut h, "ui.text", json!({"text": "41.15, -8.61"})); + exec(&mut h, "library.select", json!({"ids": [ids[2], ids[3]], "active": ids[2]})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + let gps: Vec<bool> = (0..4).map(|i| meta(&h, i).gps.is_some()).collect(); + assert_eq!(gps, [true, true, false, false]); + // Esc gives a GPS edit up + exec(&mut h, "library.select", json!({"ids": [ids[0], ids[1]], "active": ids[0]})); + h.settle(SETTLE); + let before = meta(&h, 0).gps; + click_field_in_view(&mut h, "gps", t); + ask(&mut h, "ui.key", json!({"key": "End"})); + ask(&mut h, "ui.text", json!({"text": "5"})); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + h.settle(SETTLE); + assert_eq!((meta(&h, 0).gps, meta(&h, 1).gps), (before, before)); + } + /// Local: a folder's photos show without joining the library; the breadcrumb, Include /// subfolders and Add to My Photos work from the grid header. #[test] @@ -3362,7 +3736,7 @@ mod tests { } /// Switching Settings tabs keeps the window's top edge (and its tab row) where it is and never makes it - /// narrower, though the tabs are of different heights and widths. + /// narrower or taller, though the tabs hold different amounts: the window is one size on every tab. #[test] fn settings_tabs_keep_the_window_in_place() { let mut h = demo([1300.0, 820.0]); @@ -3381,7 +3755,7 @@ mod tests { assert!(now.width() >= first.width() - 1.0, "{tab}: width {} → {}", first.width(), now.width()); heights.push(now.height()); } - assert!(heights.iter().any(|h| (h - first.height()).abs() > 20.0), "the tabs differ in height: {heights:?}"); + assert!(heights.iter().all(|h| (h - first.height()).abs() < 1.0), "the tabs keep the height of {}: {heights:?}", first.height()); } /// Settings → Import → "Show the import review when a camera or card is connected": a card that @@ -4247,7 +4621,7 @@ mod tests { // Paint the edited template before locating the Tags button in the resized dialog. assert!(h.settle(SETTLE), "Copy dialog layout should settle before locating Tags"); // the cursor sits after "Trip-" - let id = egui::Id::new("import-rename"); + let id = egui::Id::unique("import-rename"); let mut st = egui::text_edit::TextEditState::default(); st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(5)))); st.store(&h.view.ctx, id); @@ -4284,7 +4658,7 @@ mod tests { let r = h.request("ui.clickWidget", json!({"id": format!("button:aboutTab-{tab}")}), t); assert_eq!(r["ok"], true, "{tab}: {r}"); h.step(); - let shown = h.view.ctx.data_mut(|d| d.get_temp::<u8>(egui::Id::new("about_tab"))); + let shown = h.view.ctx.data_mut(|d| d.get_temp::<u8>(egui::Id::unique("about_tab"))); assert_eq!(shown.map(usize::from), Some(i), "{tab}"); } h.request("ui.clickWidget", json!({"id": "button:aboutTab-contributors"}), t); @@ -4570,9 +4944,6 @@ mod tests { assert_eq!(crate::i18n::language(), locale); for (mode, key) in [("basic", "Info Overlay: File"), ("exposure", "Info Overlay: Exposure"), ("off", "Info Overlay Off")] { let expected = locale.tr(key); - if locale != Locale::En { - assert_ne!(expected, key, "this locale must translate the tested message"); - } assert_eq!(h.request("ui.key", json!({"key": "i", "cmd": true}), t)["ok"], true); assert_eq!(serde_json::to_value(h.app.ui.info_overlay).unwrap(), json!(mode)); assert_eq!(h.app.ui.toast.as_ref().expect("overlay toast").0, expected); @@ -4611,6 +4982,53 @@ mod tests { assert_eq!(h.app.ui.settings.loupe_info.info2, [F::Camera, F::None, F::FileName], "a refused change changes nothing"); } + /// View Options' Show Briefly When Photo Changes: a tick box under each Info (ticking one + /// unticks the other) and `view.viewOptions {briefly}`; with the overlay off, the loupe shows + /// the chosen Info after → changes the photo, and hides it again a few seconds later. + #[test] + fn show_briefly_when_photo_changes_in_view_options() { + use crate::state::{BRIEF_INFO_SECS, InfoOverlay}; + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + h.request("ui.set", json!({"view": "detail"}), t); + assert_eq!(h.request("ui.key", json!({"key": "j", "cmd": true}), t)["ok"], true); + h.step(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "check:viewOptions.briefly2"}), t)["ok"], true); + h.step(); + assert_eq!(h.app.ui.settings.loupe_info.briefly, InfoOverlay::Exposure); + assert_eq!(h.request("ui.clickWidget", json!({"id": "check:viewOptions.briefly1"}), t)["ok"], true); + h.step(); + assert_eq!(h.app.ui.settings.loupe_info.briefly, InfoOverlay::Basic, "one Info at most"); + h.app.ui.dialog = None; + h.step(); + + let overlay = |h: &Headless| h.app.widgets.iter().any(|(w, _)| w == "canvas:infoOverlay"); + assert_eq!(h.app.ui.info_overlay, InfoOverlay::Off); + h.time += BRIEF_INFO_SECS + 1.0; + h.step(); + h.step(); + assert!(!overlay(&h), "hidden once the time has passed"); + let before = h.app.session.active(); + h.request("ui.key", json!({"key": "right"}), t); + assert_ne!(h.app.session.active(), before); + h.step(); + assert!(overlay(&h), "shown after → changes the photo"); + h.time += BRIEF_INFO_SECS + 1.0; + h.step(); + h.step(); + assert!(!overlay(&h), "and hidden again"); + + let r = h.request("engine.execute", json!({"command": "view.viewOptions", "params": {"briefly": "off"}}), t); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["loupeInfo"]["briefly"], "off", "{r}"); + h.request("ui.key", json!({"key": "right"}), t); + h.step(); + assert!(!overlay(&h), "off: nothing shows when the photo changes"); + let r = h.request("engine.execute", json!({"command": "view.viewOptions", "params": {"briefly": "info3"}}), t); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(h.app.ui.settings.loupe_info.briefly, InfoOverlay::Off, "a refused change changes nothing"); + } + /// A click on the image zooms to the chosen click-zoom ratio (1:1 by default), animating the /// loupe while rendering once at the final size; Z uses the same ratio; a second click returns to Fit. #[test] @@ -4716,6 +5134,7 @@ mod tests { unit: egui::MouseWheelUnit::Point, delta: egui::vec2(10.0, -10.0), phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, modifiers: egui::Modifiers::NONE, }), None, @@ -4794,7 +5213,13 @@ mod tests { ] { h.request("ui.set", json!({"zoom": "fit", "pan": [0.5, 0.5]}), t); h.request("ui.hoverWidget", json!({"id": "canvas:image"}), t); - h.app.synthetic.push(egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers }); + h.app.synthetic.push(egui::Event::MouseWheel { + unit, + delta: egui::vec2(0.0, y), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers, + }); for _ in 0..10 { h.step(); } @@ -4947,6 +5372,69 @@ mod tests { assert!(!h.app.renderer.is_pending(Slot::Main)); } + /// View Options' Show message when loading or rendering photos (on by default): turned off in + /// the window, the loupe does not say "Rendering…" while an edit renders; `view.viewOptions + /// {loupeMessages}` turns it back on for an agent (refusing a value that is not true or false). + #[test] + fn view_options_turn_the_rendering_message_off() { + use crate::render::Slot; + use std::{cell::Cell, rc::Rc}; + let pill = |h: &Headless| h.app.widgets.iter().any(|(w, _)| w == "loupe:rendering"); + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + h.settle(SETTLE); + assert!(h.app.ui.settings.loupe_messages, "on by default"); + assert_eq!(h.request("ui.key", json!({"key": "j", "cmd": true}), t)["ok"], true); + h.step(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "check:viewOptions.loupeMessages"}), t)["ok"], true); + h.step(); + assert!(!h.app.ui.settings.loupe_messages, "the tick box turns it off"); + h.app.ui.dialog = None; + let open = Rc::new(Cell::new(false)); + h.app.renderer.set_offload(Box::new(super::RenderGate::new(open.clone()))); + h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.exposure", "value": 0.5}}), t); + for _ in 0..45 { + h.step(); + } + assert!(h.app.renderer.is_pending(Slot::Main), "the edit's render is held"); + assert!(!pill(&h), "no message while it is off"); + + let r = h.request("engine.execute", json!({"command": "view.viewOptions", "params": {"loupeMessages": "yes"}}), t); + assert_eq!(r["ok"], false, "{r}"); + assert!(!h.app.ui.settings.loupe_messages, "a refused change changes nothing"); + let r = h.request("engine.execute", json!({"command": "view.viewOptions", "params": {"loupeMessages": true}}), t); + assert_eq!(r["result"]["loupeMessages"], true, "{r}"); + assert_eq!(h.app.ui.dialog, None, "a value sets it without opening the window"); + assert!(h.step_until(SETTLE, pill), "the message shows again while the render is held"); + open.set(true); + assert!(h.step_until(SETTLE, |h| !pill(h)), "gone once the render lands"); + } + + /// With nothing to show yet, the loupe says "Rendering…" in its middle only while View Options' + /// Show message when loading or rendering photos is on. + #[test] + fn an_empty_loupe_says_rendering_only_with_the_message_on() { + use std::{cell::Cell, rc::Rc}; + for on in [true, false] { + let mut h = demo([1000.0, 700.0]); + let t = Duration::from_secs(10); + h.app.ui.settings.loupe_messages = on; + h.app.renderer.set_offload(Box::new(super::RenderGate::new(Rc::new(Cell::new(false))))); + h.request("ui.set", json!({"view": "detail", "right": "none"}), t); + // drop every texture (quick previews and thumbnails land outside the gate) until a + // frame has nothing to show + let empty = (0..60).any(|_| { + h.app.renderer.textures.clear(); + h.step(); + h.app.loupe_shown.map(|l| l.1) == Some("none") + }); + assert!(empty, "a frame with nothing rendered"); + let said = h.painted_text().iter().any(|text| text == "Rendering…"); + assert_eq!(said, on, "message on: {on}"); + } + } + /// A render that fails while the loupe shows a stand-in (the embedded JPEG, a thumbnail) left /// the stand-in up as if it were the photo: the loupe says the photo can't be opened, with the /// error on hover, and keeps saying so while a library change retries it. diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 158a006641..9ba1cd5afb 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -51,10 +51,13 @@ macro_rules! language_table { static CATALOGS: OnceLock<BTreeMap<Locale, BTreeMap<String, String>>> = OnceLock::new(); static EMPTY: OnceLock<BTreeMap<String, String>> = OnceLock::new(); // A malformed catalog logs and comes back empty: a broken translation degrades to - // English text, it never takes the app down. + // English text, it never takes the app down. An empty translation is a missing one. let parse = |catalog: Option<&'static str>| match catalog { - Some(json) => match serde_json::from_str(json) { - Ok(messages) => messages, + Some(json) => match serde_json::from_str::<BTreeMap<String, String>>(json) { + Ok(mut messages) => { + messages.retain(|_, text| !text.is_empty()); + messages + } Err(error) => { log::error!("Invalid message catalog for {}: {error}", self.code()); BTreeMap::new() @@ -263,8 +266,48 @@ fn catalog_verbatim(language: Locale) -> BTreeMap<String, &'static str> { // `locales/*-formats.json`. include!(concat!(env!("OUT_DIR"), "/tr-formats.rs")); -/// A stock preset's or profile's name in the UI language; an imported or user-edited name stays -/// exactly as its owner wrote it. +/// The web build's notice for a dropped file the browser could not read. +pub fn dropped_file_unreadable(name: &str, error: &str) -> String { + tr_format!("Could not read {name}: {e}", name = name, e = error) +} + +/// The web build's notice for dropped files the library refused. +pub fn dropped_import_failed(error: &str) -> String { + tr_format!("Import failed: {e}", e = error) +} + +/// The web build's notice for `n` dropped photos that joined the library. +pub fn dropped_photos_added(n: usize) -> String { + tr_format!("Added {n} photo{}", if n == 1 { "" } else { "s" }, n = n) +} + +/// The web build's notice for `n` dropped photos that came back from Recently Deleted. +pub fn dropped_photos_restored(n: usize) -> String { + tr_format!("Restored {} photo{} from Recently Deleted", n, if n == 1 { "" } else { "s" }) +} + +/// The web build's notice for what a drop of photos came to, from the `library.import` report: every outcome that +/// happened (added, restored from Recently Deleted, not readable), joined with " · " as the desktop import's notice +/// joins its parts, or `None` when none did (duplicates only). +pub fn dropped_photos_outcome(report: &serde_json::Value) -> Option<String> { + let count = |k: &str| report[k].as_array().map_or(0, Vec::len); + let parts: Vec<String> = [ + (count("imported"), dropped_photos_added as fn(usize) -> String), + (count("restored"), dropped_photos_restored), + (count("failed"), dropped_photos_unreadable), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, say)| say(n)) + .collect(); + (!parts.is_empty()).then(|| parts.join(" · ")) +} + +/// The web build's notice for `n` dropped photos that could not be read. +pub fn dropped_photos_unreadable(n: usize) -> String { + tr_format!("{} photo{} not readable", n, if n == 1 { "" } else { "s" }) +} + /// The title and text of the message box shown when the desktop app's window can't start /// (issue #260), in the UI language: the error and, when there is one, the log file to look in. pub fn startup_failed_message(error: &str, log_file: Option<&str>) -> (String, String) { @@ -302,6 +345,8 @@ pub fn upper_first(text: &str) -> String { } } +/// A stock preset's or profile's name in the UI language; an imported or user-edited name stays +/// exactly as its owner wrote it. pub fn builtin_label(source: &str, builtin: bool) -> &str { if builtin { tr(source) } else { source } } @@ -522,112 +567,55 @@ pub fn rules_label(rules: &lightcraft_catalog::RuleSet, catalog: &lightcraft_cat mod tests { use super::*; + /// Each language through its menu command and the control channel's locale tags, saved by its + /// code: built-in labels follow it, user values and ids don't, the window paints its text and + /// the bundled fonts have its letters. #[test] - fn czech_coverage_of_catalogs_commands_controls_and_rules_is_reported() { - let catalog = Locale::Cs.catalog(); - let keys: std::collections::BTreeSet<&String> = Locale::ALL.iter().flat_map(|language| language.catalog().keys()).collect(); - let lacking: Vec<_> = keys.into_iter().filter(|key| !catalog.contains_key(key.as_str())).collect(); - if !lacking.is_empty() { - eprintln!("cs lacks {} catalog message(s) (shown in English): {lacking:?}", lacking.len()); - } - let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); - labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); - labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); - labels.extend(crate::panels::settings::TABS.iter().map(|(_, label)| *label)); - labels.extend(lightcraft_catalog::rules::FIELD_GROUPS.iter().map(|group| group.0)); - labels.extend(lightcraft_engine::rename::TOKENS.iter().map(|token| token.meaning)); - labels.extend(lightcraft_engine::rename::TEMPLATE_NOTES); - let missing: Vec<_> = labels.into_iter().filter(|label| !catalog.contains_key(*label)).collect(); - if !missing.is_empty() { - eprintln!("cs lacks {} display label(s) (shown in English): {missing:?}", missing.len()); - } - } - - #[test] - fn czech_switches_persists_and_formats_without_changing_user_values() { + fn languages_switch_persist_and_keep_user_values() { use crate::control::{ControlRequest, Outcome}; - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.czech", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::Cs); - assert_eq!(Locale::Cs.name(), "Čeština"); - assert_eq!(Locale::Cs.script(), "Latn"); - assert_eq!(crate::menubar::checked(&app, "app.language.czech"), Some(true)); - assert_eq!(tr("File"), "Soubor"); - assert_eq!(tr("Develop"), "Vyvolat"); - assert_eq!(date_group_label("2026-09-20", false), "Neděle, 20. 9. 2026"); - assert_eq!(date_group_label("2026-09-20", true), "Neděle, 20."); - assert_eq!(date_group_label("2026-09", false), "9. 2026"); - assert_eq!(date_group_label("2026", false), "2026"); - assert_eq!(display_time("2026-09-20T16:04:05"), "Neděle, 20. 9. 2026 16:04:05"); - for n in [0, 1, 2, 4, 5, 11, 21, 22, 25] { - assert_eq!(tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }), format!("Importováno fotografií: {n}")); - assert_eq!( - tr_format!("{n} {noun}", n = n, noun = tr(if n == 1 { "photo waiting" } else { "photos waiting" })), - format!("Čekající fotografie: {n}") - ); - } - let name = String::from("Color 1234.56 {title} 日本語"); - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22), format!("Do „{name}“ přidáno fotografií: 22")); - assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::Cs); - let ctx = egui::Context::default(); - for tag in ["cs", "cs-CZ", "cs_CZ.UTF-8", "cs-Latn-CZ"] { - assert_eq!(Locale::parse_tag(tag), Some(Locale::Cs)); - let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": tag})); - let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; - assert_eq!(reply["ok"], true); - assert_eq!(language(), Locale::Cs); - } - let text = painted_text(&ctx, &mut app, Locale::Cs); - assert!(text.contains("Soubor") && text.contains("Expozice"), "{text}"); - ctx.fonts_mut(|fonts| { - for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { - let font = egui::FontId::new(13.0, family); - for ch in "áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ„“".chars() { - assert!(fonts.has_glyph(&font, ch), "missing Czech glyph {ch}"); - } + let languages: [(Locale, &str, &[&str], &str); 8] = [ + (Locale::Cs, "czech", &["cs", "cs-CZ", "cs_CZ.UTF-8", "cs-Latn-CZ"], "áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ„“"), + (Locale::Id, "indonesian", &["id", "id-ID", "id_ID.UTF-8", "id-Latn-ID"], ""), + (Locale::Sv, "swedish", &["sv", "sv-SE", "sv_SE.UTF-8", "sv-FI"], "åäöÅÄÖé”’"), + (Locale::Uk, "ukrainian", &["uk", "uk-UA", "uk_UA.UTF-8", "uk-Cyrl-UA"], ""), + (Locale::Ka, "georgian", &["ka", "ka-GE", "ka_GE.UTF-8"], ""), + (Locale::It, "italian", &["it", "it-IT", "it_IT.UTF-8", "it-Latn-IT", "it-CH"], ""), + (Locale::Fi, "finnish", &["fi", "fi-FI", "fi_FI.UTF-8", "fi-Latn-FI"], ""), + (Locale::Vi, "vietnamese", &["vi", "vi-VN", "vi_VN", "vi_VN.UTF-8"], ""), + ]; + for (locale, command, tags, letters) in languages { + let command = format!("app.language.{command}"); + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + app.run(&command, serde_json::json!({})).unwrap(); + assert_eq!(app.ui.language, locale); + assert_eq!(language(), locale); + assert_eq!(crate::menubar::checked(&app, &command), Some(true)); + assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); + assert_eq!(builtin_label("Warm Glow", true), locale.tr("Warm Glow")); + assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); + assert_eq!(tr("develop.set"), "develop.set"); + let saved = serde_json::to_string(&app.ui).unwrap(); + assert!(saved.contains(&format!(r#""language":"{}""#, locale.code())), "{saved}"); + assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, locale); + let ctx = egui::Context::default(); + for tag in tags { + assert_eq!(Locale::parse_tag(tag), Some(locale), "{tag}"); + let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": tag})); + let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; + assert_eq!(reply["ok"], true); + assert_eq!(language(), locale); } - }); - set_language(Locale::En); - } - - #[test] - fn indonesian_switches_persists_formats_dates_and_preserves_values() { - use crate::control::{ControlRequest, Outcome}; - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.indonesian", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::Id); - assert_eq!(Locale::Id.name(), "Bahasa Indonesia"); - assert_eq!(Locale::Id.script(), "Latn"); - assert_eq!(crate::menubar::checked(&app, "app.language.indonesian"), Some(true)); - assert_eq!(tr("Exposure"), "Eksposur"); - assert_eq!(tr("My Photos"), "Foto saya"); - assert_eq!(date_group_label("2026-09-20", false), "Minggu, 20/09/2026"); - assert_eq!(date_group_label("2026-09-20", true), "Minggu, 20"); - assert_eq!(date_group_label("2026-09", false), "09/2026"); - assert_eq!(date_group_label("2026", false), "2026"); - assert_eq!(display_time("2026-09-20T16:04:05"), "Minggu, 20/09/2026 16:04:05"); - // Indonesian keeps a noun unchanged after a count ("1 foto", "22 foto"), so the English - // plural suffix is consumed and never shows. - for n in [0, 1, 2, 5, 11, 22] { - assert_eq!(tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }), format!("{n} foto diimpor")); - } - let name = String::from("Color 1234.56 {title} 日本語"); - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22), format!("22 foto ditambahkan ke “{name}”")); - assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert!(saved.contains(r#""language":"id""#)); - assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::Id); - let ctx = egui::Context::default(); - for tag in ["id", "id-ID", "id_ID.UTF-8", "id-Latn-ID"] { - assert_eq!(Locale::parse_tag(tag), Some(Locale::Id)); - let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": tag})); - let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; - assert_eq!(reply["ok"], true); - assert_eq!(language(), Locale::Id); + let text = painted_text(&ctx, &mut app, locale); + // (not the menu titles: a language whose titles don't fit shows one Menu button) + assert!(text.contains(locale.tr("Exposure")), "{locale:?}: {text}"); + ctx.fonts_mut(|fonts| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { + let font = egui::FontId::new(13.0, family); + for ch in letters.chars() { + assert!(fonts.has_glyph(&font, ch), "{locale:?}: missing glyph {ch}"); + } + } + }); } set_language(Locale::En); } @@ -642,68 +630,64 @@ mod tests { } #[test] - fn swedish_switches_persists_and_formats_without_changing_user_values() { - use crate::control::{ControlRequest, Outcome}; - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.swedish", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::Sv); - assert_eq!(Locale::Sv.name(), "Svenska"); - assert_eq!(Locale::Sv.script(), "Latn"); - assert_eq!(crate::menubar::checked(&app, "app.language.swedish"), Some(true)); - assert_eq!(tr("File"), "Fil"); - assert_eq!(tr("Develop"), "Framkalla"); - assert_eq!(tr("Exposure"), "Exponering"); - assert_eq!(date_group_label("2026", false), "2026"); - assert!(date_group_label("2026-09-20", false).starts_with("Söndag 20 "), "{}", date_group_label("2026-09-20", false)); - assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert!(saved.contains("\"sv\""), "{saved}"); - assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::Sv); - let ctx = egui::Context::default(); - for tag in ["sv", "sv-SE", "sv_SE.UTF-8", "sv-FI"] { - assert_eq!(Locale::parse_tag(tag), Some(Locale::Sv), "{tag}"); - let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": tag})); - let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; - assert_eq!(reply["ok"], true); - assert_eq!(language(), Locale::Sv); - } - let text = painted_text(&ctx, &mut app, Locale::Sv); - assert!(text.contains("Fil") && text.contains("Exponering"), "{text}"); - ctx.fonts_mut(|fonts| { - for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { - let font = egui::FontId::new(13.0, family); - for ch in "åäöÅÄÖé”’".chars() { - assert!(fonts.has_glyph(&font, ch), "missing Swedish glyph {ch}"); - } - } - }); - set_language(Locale::En); - } - - #[test] - fn every_language_has_a_catalog_covering_the_source() { + fn every_language_has_a_name_a_script_and_its_own_code() { assert!(crate::i18n::Locale::En.catalog().is_empty(), "the source language needs no catalog"); for language in Locale::ALL { assert!(!language.name().is_empty(), "{language:?} has a name"); assert!(!language.script().is_empty(), "{language:?} has a script"); assert_eq!(Locale::parse(language.code()), Some(*language), "{language:?} parses its own code"); - if *language == Locale::En { - continue; - } - let messages = language.catalog(); - assert!(!messages.is_empty(), "{language:?}: {} has no messages", language.code()); - for (key, value) in messages { - assert!(!value.is_empty(), "{language:?}: empty translation for {key:?}"); - } } } - /// Where two catalogs translate the same text they agree on its placeholders. Catalogs may cover - /// different sets of messages (a message a language lacks shows in English): the gaps are - /// reported, not failed, so a translation can grow at its own pace. + /// Every catalog file is a JSON object of strings, each key once: a malformed file would load as + /// no catalog, and a repeated key silently drops one of its translations. #[test] - fn catalogs_agree_on_placeholders_and_report_gaps() { + fn catalogs_load() { + let files = catalog_files(); + assert_eq!(files.len(), 2 * (Locale::ALL.len() - 1), "a plain and a formats catalog per translation"); + for path in files { + let repeated = repeated_keys(&path); + assert_eq!(repeated, Ok(Vec::new()), "{}", path.display()); + } + } + + /// `locales/*.json`, sorted. + fn catalog_files() -> Vec<std::path::PathBuf> { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("locales"); + let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "json")) + .collect(); + files.sort(); + files + } + + /// The keys a catalog file names more than once, or why it isn't an object of strings. + fn repeated_keys(path: &std::path::Path) -> Result<Vec<String>, String> { + struct Repeated; + impl<'de> serde::de::Visitor<'de> for Repeated { + type Value = Vec<String>; + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("an object of strings") + } + fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Vec<String>, A::Error> { + let (mut seen, mut repeated) = (std::collections::BTreeSet::new(), Vec::new()); + while let Some((key, _)) = map.next_entry::<String, String>()? { + if !seen.insert(key.clone()) { + repeated.push(key); + } + } + Ok(repeated) + } + } + let text = std::fs::read_to_string(path).map_err(|error| error.to_string())?; + serde::Deserializer::deserialize_map(&mut serde_json::Deserializer::from_str(&text), Repeated).map_err(|error| error.to_string()) + } + + /// A translation carries the placeholders of the message it translates. + #[test] + fn catalogs_agree_on_placeholders() { let fields = |text: &str| { let mut out: Vec<String> = Vec::new(); let mut rest = text; @@ -715,17 +699,10 @@ mod tests { out.sort(); out }; - let translated: Vec<Locale> = Locale::ALL.iter().copied().filter(|language| *language != Locale::En).collect(); - let all: std::collections::BTreeSet<&String> = translated.iter().flat_map(|language| language.catalog().keys()).collect(); - for language in &translated { - let catalog = language.catalog(); - for (key, value) in catalog { + for language in Locale::ALL { + for (key, value) in language.catalog() { assert_eq!(fields(key), fields(value), "{language:?}: {key:?} -> {value:?}"); } - let missing: Vec<&&String> = all.iter().filter(|key| !catalog.contains_key(key.as_str())).collect(); - if !missing.is_empty() { - eprintln!("{} lacks {} message(s) another language translates (shown in English): {missing:?}", language.code(), missing.len()); - } } } @@ -793,18 +770,16 @@ mod tests { #[test] fn switching_language_translates_and_restores() { - set_language(Locale::ZhHans); - assert_eq!(tr("Exposure"), "曝光"); - assert_eq!(tr("Settings"), "设置"); - // Untranslated and data-like text passes through untouched. - assert_eq!(tr("my-photo.jpg"), "my-photo.jpg"); - assert_eq!(tr("develop.set"), "develop.set"); - assert_eq!(tr("A string no catalog has"), "A string no catalog has"); - set_language(Locale::Ja); - assert_eq!(tr("Exposure"), "露出"); - set_language(Locale::PtBr); - assert_eq!(tr("Exposure"), "Exposição"); - assert_eq!(tr("Settings"), "Configurações"); + for language in Locale::ALL { + set_language(*language); + for source in ["Exposure", "Settings"] { + assert_eq!(tr(source), language.catalog().get(source).map_or(source, String::as_str), "{language:?}"); + } + // Untranslated and data-like text passes through untouched. + assert_eq!(tr("my-photo.jpg"), "my-photo.jpg"); + assert_eq!(tr("develop.set"), "develop.set"); + assert_eq!(tr("A string no catalog has"), "A string no catalog has"); + } set_language(Locale::En); assert_eq!(tr("Exposure"), "Exposure"); } @@ -817,16 +792,10 @@ mod tests { set_language(Locale::En); assert_eq!(tr_format!("Imported {} photo{}", 12, "s"), "Imported 12 photos"); assert_eq!(tr_format!("Exported {ok} of {total} photo{}", "s", ok = 4, total = 12), "Exported 4 of 12 photos"); - set_language(Locale::ZhHans); - assert_eq!(tr_format!("Imported {} photo{}", 12, "s"), "已导入 12 张照片"); - assert_eq!(tr_format!("Exported {ok} of {total} photo{}", "s", ok = 4, total = 12), "已导出 12 张中的 4 张照片"); - set_language(Locale::Ja); - assert_eq!(tr_format!("Imported {} photo{}", 12, "s"), "12枚を読み込みました"); - assert_eq!(tr_format!("Exported {ok} of {total} photo{}", "s", ok = 4, total = 12), "12枚中4枚を書き出しました"); - set_language(Locale::Fr); - assert_eq!(tr_format!("Imported {} photo{}", 12, "s"), "12 photos importée(s)"); - assert_eq!(tr_format!("Imported {} photo{}", 1, ""), "1 photo importée(s)"); - // Format specs survive translation: precision, sign, and values a language reorders. + // A message no catalog has formats its English source. + assert_eq!(tr_format!("{} of {} (no catalog has this)", 1, 2), "1 of 2 (no catalog has this)"); + // Format specs survive translation: precision, sign, and values a language reorders; user + // text (an album name with braces and CJK) and counts are never dropped. for language in Locale::ALL { set_language(*language); let text = tr_format!("{count} smart preview{} · {:.1} MB", "s", 12.345, count = 3); @@ -838,6 +807,17 @@ mod tests { let reading = tr_format!("Reading photos… {} of {}", 3, 10); let (three, ten) = (reading.find('3'), reading.find("10")); assert!(three.is_some() && ten.is_some(), "{language:?}: {reading}"); + let name = "Color 1234.56 {title} 日本語"; + let added = tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22); + assert!(added.contains(name) && added.contains("22"), "{language:?}: {added}"); + for n in [0, 1, 2, 5, 22] { + let imported = tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }); + assert!(imported.contains(&n.to_string()), "{language:?}: {imported}"); + } + // The trailing argument is queue progress, not an English plural suffix. + let queued = tr_format!(" · {queued} waiting", queued = 5); + let denoising = tr_format!("Denoising {name}: {done} of {total} tiles{}", queued, name = "IMG.CR3", done = 1, total = 4); + assert!(denoising.contains("IMG.CR3") && denoising.contains('5'), "{language:?}: {denoising}"); } set_language(Locale::En); assert_eq!(tr_format!("Reading photos… {} of {}", 3, 10), "Reading photos… 3 of 10"); @@ -973,48 +953,31 @@ mod tests { assert_eq!(restored.language, Locale::ZhHans); } - #[test] - fn catalogs_contain_core_workflows() { - for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { - for key in ["Import Photos…", "Export…", "Exposure", "White Balance", "Settings", "Language"] { - let value = language.tr(key); - assert!(!value.is_empty() && value != key, "{language:?}: {key}"); - } - } - } - - /// Smart-album choice values read as words in every language (English "Public Domain", German - /// "Gemeinfrei"), never as rule ids like `publicDomain`; an id the field doesn't know shows as - /// written. Unlike other labels these must be translated: an untranslated one would be English - /// in the middle of a translated rule. + /// Smart-album choice values read as words in every language (English "Public Domain"), never as + /// rule ids like `publicDomain`; an id the field doesn't know shows as written. A yes/no value + /// reads Yes / No, or the language's contextual entry for it where it has one. #[test] fn choice_values_read_as_words_in_every_language() { - use lightcraft_catalog::rules::{FIELDS, Kind}; + use lightcraft_catalog::rules::{FIELDS, Kind, bool_label}; assert_eq!(choice_text_in(Locale::En, "copyrightStatus", "publicDomain"), "Public Domain"); - assert_eq!(choice_text_in(Locale::De, "copyrightStatus", "publicDomain"), "Gemeinfrei"); - assert_eq!(choice_text_in(Locale::De, "copyrightStatus", "someday"), "someday"); - assert_eq!(choice_text_in(Locale::ZhHans, "treatment", "color"), "彩色", "in colour, not the colour noun"); - assert_eq!(choice_text_in(Locale::Ru, "treatment", "color"), "Цветное"); - assert_eq!(choice_text_in(Locale::Es, "label", "none"), "Sin etiqueta"); - // yes/no fields read Yes / No, never true / false assert_eq!((bool_text_in(Locale::En, true), bool_text_in(Locale::En, false)), ("Yes", "No")); - assert_eq!(bool_text_in(Locale::De, false), "Nein"); - // Japanese answers はい / いいえ don't read as a rule's value: its own wording, あり / なし, - // through a context, while the shared Yes / No keep their meaning everywhere else - assert_eq!((bool_text_in(Locale::Ja, true), bool_text_in(Locale::Ja, false)), ("あり", "なし")); - assert_eq!((Locale::Ja.tr("Yes"), Locale::Ja.tr("No")), ("はい", "いいえ")); - assert_eq!(tr_ctx_in(Locale::Ja, "nope", "Yes"), "はい", "no contextual entry: the plain message"); assert_eq!(tr_ctx_in(Locale::En, BOOL_CONTEXT, "Yes"), "Yes"); - // and the yes/no fields are named by plain nouns, so "編集 … なし" doesn't read "edits: yes … none" - for (field, label, kind) in FIELDS { - if *kind != Kind::Bool { - continue; + for language in Locale::ALL { + assert_eq!(choice_text_in(*language, "copyrightStatus", "someday"), "someday"); + assert_eq!(tr_ctx_in(*language, "nope", "Yes"), language.tr("Yes"), "no contextual entry: the plain message"); + for b in [true, false] { + let contextual = language.catalog().get(&format!("{BOOL_CONTEXT}|{}", bool_label(b))); + assert_eq!(bool_text_in(*language, b), contextual.map_or(language.tr(bool_label(b)), String::as_str)); + } + for (field, _, kind) in FIELDS { + let Kind::Choice(choices) = kind else { continue }; + for (id, _) in *choices { + assert_ne!(choice_text_in(*language, field, id), *id, "{}: {field} {id}", language.code()); + } } - let ja = Locale::Ja.catalog().get(*label).unwrap_or_else(|| panic!("ja lacks the {field} label {label:?}")); - assert!(!ja.contains("あり") && !ja.contains("なし"), "{field}: {ja}"); } - // a contextual entry names a real value (a typo would silently fall back to はい / いいえ) - let values = [lightcraft_catalog::rules::bool_label(true), lightcraft_catalog::rules::bool_label(false)]; + // a contextual entry names a real value (a typo would silently fall back to the plain Yes / No) + let values = [bool_label(true), bool_label(false)]; for language in Locale::ALL { for key in language.catalog().keys() { if let Some(value) = key.strip_prefix(BOOL_CONTEXT).and_then(|k| k.strip_prefix('|')) { @@ -1022,28 +985,10 @@ mod tests { } } } - for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { - for label in [lightcraft_catalog::rules::bool_label(true), lightcraft_catalog::rules::bool_label(false)] { - assert!(language.catalog().contains_key(label), "{} lacks {label:?}", language.code()); - } - } - for language in Locale::ALL { - for (field, _, kind) in FIELDS { - let Kind::Choice(choices) = kind else { continue }; - for (id, label) in *choices { - let text = choice_text_in(*language, field, id); - assert_ne!(text, *id, "{}: {field} {id}", language.code()); - if *language != Locale::En { - assert!(language.catalog().contains_key(*label), "{} lacks {label:?}", language.code()); - } - } - } - } } - /// A rule's problem reads as the field's name and the issue, in the editor's language ("Titel: - /// braucht einen Suchbegriff …"); the sidebar's list puts the rule's position first. Every issue - /// is translated in every language: an English one would stand out in a translated editor. + /// A rule's problem reads as the field's name and the issue, in the editor's language, joined by + /// a full-width colon in Japanese and Chinese; the sidebar's list puts the rule's position first. #[test] fn problems_read_in_every_language() { use lightcraft_catalog::rules::Issue; @@ -1053,151 +998,19 @@ mod tests { }; let p = problems(serde_json::json!([{"field": "rating", "op": "gte", "value": 3}, {"field": "title", "op": "contains", "value": ""}])); assert_eq!(problem_text_in(Locale::En, &p[0]), "Title: needs something to look for (or use “is empty”)"); - assert_eq!(problem_text_in(Locale::De, &p[0]), "Titel: braucht einen Suchbegriff (oder „ist leer“)"); assert_eq!(problem_line_in(Locale::En, &p[0]), "#2 Title: needs something to look for (or use “is empty”)"); - // Japanese and Chinese join with a full-width colon, as their catalogs do - assert_eq!(problem_text_in(Locale::Ja, &p[0]), "タイトル:検索する語句が必要です(または「が空」を使用)"); + for language in Locale::ALL { + let colon = if matches!(language.script(), "Jpan" | "Hans" | "Hant") { ":" } else { ": " }; + let text = format!("{}{colon}{}", language.tr("Title"), language.tr(p[0].issue.text())); + assert_eq!(problem_text_in(*language, &p[0]), text); + assert_eq!(problem_line_in(*language, &p[0]), format!("#2 {text}")); + } // a problem with the album filter itself has no rule position to show let filter_loop = lightcraft_catalog::rules::Problem { path: Vec::new(), field: Some("album".into()), issue: Issue::AlbumLoop, message: String::new() }; assert!(problem_line_in(Locale::En, &filter_loop).starts_with("Album: "), "{}", problem_line_in(Locale::En, &filter_loop)); let g = problems(serde_json::json!([{"group": {"rules": []}}])); assert_eq!(problem_text_in(Locale::En, &g[0]), "This group is empty: add a rule or remove it."); - // the issues, the operators their hints name and the album picker's words, in every language - for language in Locale::ALL.iter().filter(|l| **l != Locale::En) { - // the field menu: every field and every group, so it never mixes languages - for label in lightcraft_catalog::rules::FIELDS.iter().map(|f| f.1).chain(lightcraft_catalog::rules::FIELD_GROUPS.iter().map(|g| g.0)) { - assert!(language.catalog().contains_key(label), "{} lacks the rule label {label:?}", language.code()); - } - for word in [ - "Choose an album…", - "No albums yet", - "Search albums", - "No albums match", - "This is the album you're editing", - "It tests this album, so testing it back would loop", - "Fix the marked rules to save this album.", - ] { - assert!(language.catalog().contains_key(word), "{} lacks {word:?}", language.code()); - } - for issue in Issue::ALL { - assert!(language.catalog().contains_key(issue.text()), "{} lacks {:?}", language.code(), issue.text()); - } - for (_, _, kind) in lightcraft_catalog::rules::FIELDS { - for (_, op) in lightcraft_catalog::rules::ops_for(*kind) { - assert!(language.catalog().contains_key(*op), "{} lacks the operator {op:?}", language.code()); - } - } - } - } - - /// The date picker's own words (its tooltip, the weekday headers) are in every language, as the - /// month and day labels it borrows from the date headings are. - #[test] - fn date_picker_words_are_translated() { - for language in Locale::ALL.iter().filter(|l| **l != Locale::En) { - for word in crate::date_picker::WEEKDAY_SHORT.iter().chain(&["Pick a date", "Year", "Month", "Day"]) { - assert!(language.catalog().contains_key(*word), "{} lacks {word:?}", language.code()); - } - } - } - - /// Ukrainian's coverage of every catalog message and display label. Gaps are reported, not failed - /// (like `catalogs_agree_on_placeholders_and_report_gaps`): a feature PR that adds a label doesn't - /// have to ship its Ukrainian text, which shows in English until the translation catches up. - #[test] - fn ukrainian_coverage_of_catalogs_commands_controls_and_rules_is_reported() { - let catalog = Locale::Uk.catalog(); - let keys: std::collections::BTreeSet<&String> = Locale::ALL.iter().flat_map(|language| language.catalog().keys()).collect(); - let lacking: Vec<_> = keys.into_iter().filter(|key| !catalog.contains_key(key.as_str())).collect(); - if !lacking.is_empty() { - eprintln!("uk lacks {} catalog message(s) (shown in English): {lacking:?}", lacking.len()); - } - let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); - labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); - labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); - labels.extend(crate::panels::settings::TABS.iter().map(|(_, label)| *label)); - for (_, label, kind) in lightcraft_catalog::rules::FIELDS { - labels.push(label); - labels.extend(lightcraft_catalog::rules::ops_for(*kind).iter().map(|(_, label)| *label)); - } - labels.extend(lightcraft_engine::rename::TOKENS.iter().map(|token| token.meaning)); - labels.extend(lightcraft_engine::rename::TEMPLATE_NOTES); - let missing: Vec<_> = labels.into_iter().filter(|label| !catalog.contains_key(*label)).collect(); - if !missing.is_empty() { - eprintln!("uk lacks {} display label(s) (shown in English): {missing:?}", missing.len()); - } - } - - #[test] - fn ukrainian_switches_persists_formats_dates_and_preserves_values() { - use crate::control::{ControlRequest, Outcome}; - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.ukrainian", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::Uk); - assert_eq!(crate::menubar::checked(&app, "app.language.ukrainian"), Some(true)); - assert_eq!(tr("Light"), "Світло"); - assert_eq!(tr("Landscape"), "Пейзаж"); - assert_eq!(tr("Home"), "Домашня тека"); - assert_eq!(date_group_label("2026-09-20", false), "Неділя, 20.09.2026"); - assert_eq!(date_group_label("2026-09", false), "09.2026"); - assert_eq!(display_time("2026-09-20T16:04:05"), "Неділя, 20.09.2026 16:04:05"); - // Count-neutral labels work for every Ukrainian integer category, with no English suffix. - for n in [0, 1, 2, 5, 11, 21, 22, 25, 111] { - assert_eq!(tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }), format!("Імпортовано фото: {n}")); - assert_eq!(tr_format!("{} files and {f} folder{}", n, "s", f = n), format!("Файлів: {n}, тек: {n}")); - let noun = tr(if n == 1 { "cached picture" } else { "cached pictures" }); - assert_eq!(tr_format!("{n} {noun}", n = n, noun = noun), format!("Кешовані зображення: {n}")); - } - // This trailing argument is queue progress, not an English plural suffix. - let queued = tr_format!(" · {queued} waiting", queued = 5); - assert_eq!( - tr_format!("Denoising {name}: {done} of {total} tiles{}", queued, name = "IMG.CR3", done = 1, total = 4), - "Усунення шуму IMG.CR3: ділянки — 1 із 4 · очікують: 5" - ); - let name = "Color {title} 日本語"; - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22), format!("До «{name}» додано фото: 22")); - assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_eq!(builtin_label("Warm Glow", true), "Тепле сяйво"); - assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); - assert_eq!(tr("develop.set"), "develop.set"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert!(saved.contains(r#""language":"uk""#)); - assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::Uk); - let ctx = egui::Context::default(); - for code in ["uk", "uk-UA", "uk_UA.UTF-8", "uk-Cyrl-UA"] { - assert_eq!(Locale::parse_tag(code), Some(Locale::Uk)); - let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": code})); - let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; - assert_eq!(reply["ok"], true); - assert_eq!(language(), Locale::Uk); - } - set_language(Locale::En); - } - - #[test] - fn georgian_switches_formats_counts_and_dates() { - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.georgian", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::Ka); - assert_eq!(crate::menubar::checked(&app, "app.language.georgian"), Some(true)); - assert_eq!(tr("Light"), "სინათლე"); - assert_eq!(date_group_label("2026-09-20", false), "კვირა, 20.09.2026"); - assert_eq!(date_group_label("2026-09", false), "09.2026"); - for n in [0, 1, 2, 5, 21] { - assert_eq!(tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }), format!("იმპორტირებულია ფოტო: {n}")); - } - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", "Trip", n = 3), "„Trip“-ს დაემატა ფოტო: 3"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert!(saved.contains(r#""language":"ka""#)); - for code in ["ka", "ka-GE", "ka_GE.UTF-8"] { - assert_eq!(Locale::parse_tag(code), Some(Locale::Ka)); - } - // no Mtavruli: Georgian UI text is written in lowercase Mkhedruli - for text in Locale::Ka.catalog().values() { - assert!(!text.chars().any(|c| ('\u{1C90}'..='\u{1CBF}').contains(&c)), "{text}"); - } - set_language(Locale::En); } #[test] @@ -1206,13 +1019,12 @@ mod tests { let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); app.ui.left_panel = true; let text = painted_text(&ctx, &mut app, Locale::Uk); - assert!(text.contains("Мої фото") && text.contains("Усі фото"), "{text}"); - for (command, title) in [("app.about", "Про LightCraft"), ("app.shortcuts", "Клавіатурні скорочення"), ("app.settings", "Налаштування")] - { + assert!(text.contains(Locale::Uk.tr("My Photos")) && text.contains(Locale::Uk.tr("All Photos")), "{text}"); + for (command, title) in [("app.about", "About LightCraft"), ("app.shortcuts", "Keyboard Shortcuts"), ("app.settings", "Settings")] { app.ui.dialog = None; app.run(command, serde_json::json!({})).unwrap(); let text = painted_text(&ctx, &mut app, Locale::Uk); - assert!(text.contains(title), "{command}: {text}"); + assert!(text.contains(Locale::Uk.tr(title)), "{command}: {text}"); } ctx.fonts_mut(|fonts| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { @@ -1228,94 +1040,18 @@ mod tests { set_language(Locale::En); } - /// Italian's coverage of every catalog message and display label, reported like Ukrainian's. - #[test] - fn italian_coverage_of_catalogs_commands_controls_and_rules_is_reported() { - let catalog = Locale::It.catalog(); - let keys: std::collections::BTreeSet<&String> = Locale::ALL.iter().flat_map(|language| language.catalog().keys()).collect(); - let lacking: Vec<_> = keys.into_iter().filter(|key| !catalog.contains_key(key.as_str())).collect(); - if !lacking.is_empty() { - eprintln!("it lacks {} catalog message(s) (shown in English): {lacking:?}", lacking.len()); - } - let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); - labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); - labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); - labels.extend(crate::panels::settings::TABS.iter().map(|(_, label)| *label)); - for (_, label, kind) in lightcraft_catalog::rules::FIELDS { - labels.push(label); - labels.extend(lightcraft_catalog::rules::ops_for(*kind).iter().map(|(_, label)| *label)); - } - labels.extend(lightcraft_engine::rename::TOKENS.iter().map(|token| token.meaning)); - labels.extend(lightcraft_engine::rename::TEMPLATE_NOTES); - let missing: Vec<_> = labels.into_iter().filter(|label| !catalog.contains_key(*label)).collect(); - if !missing.is_empty() { - eprintln!("it lacks {} display label(s) (shown in English): {missing:?}", missing.len()); - } - } - - #[test] - fn italian_switches_persists_formats_dates_and_preserves_values() { - use crate::control::{ControlRequest, Outcome}; - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.italian", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::It); - assert_eq!(crate::menubar::checked(&app, "app.language.italian"), Some(true)); - assert_eq!(tr("Light"), "Luce"); - assert_eq!(tr("Landscape"), "Paesaggio"); - assert_eq!(tr("Home"), "Cartella personale"); - assert_eq!(date_group_label("2026-09-20", false), "Domenica 20/09/2026"); - assert_eq!(date_group_label("2026-09", false), "09/2026"); - assert_eq!(display_time("2026-09-20T16:04:05"), "Domenica 20/09/2026 16:04:05"); - // Italian agrees adjectives with the count ("1 foto importata", "2 foto importate"), so the - // count follows a label instead, which reads right for every number; the English plural - // suffix is consumed and never shows. - for n in [0, 1, 2, 5, 11, 21, 22, 25, 111] { - assert_eq!(tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }), format!("Foto importate: {n}")); - assert_eq!(tr_format!("{} files and {f} folder{}", n, "s", f = n), format!("{n} file, cartelle: {n}")); - let noun = tr(if n == 1 { "cached picture" } else { "cached pictures" }); - let expected = if n == 1 { "1 immagine in cache".to_string() } else { format!("{n} immagini in cache") }; - assert_eq!(tr_format!("{n} {noun}", n = n, noun = noun), expected); - } - // This trailing argument is queue progress, not an English plural suffix. - let queued = tr_format!(" · {queued} waiting", queued = 5); - assert_eq!( - tr_format!("Denoising {name}: {done} of {total} tiles{}", queued, name = "IMG.CR3", done = 1, total = 4), - "Riduzione disturbo di IMG.CR3: 1 di 4 riquadri · in attesa: 5" - ); - let name = "Color {title} 日本語"; - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22), format!("Foto aggiunte a “{name}”: 22")); - assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_eq!(builtin_label("Warm Glow", true), "Bagliore caldo"); - assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); - assert_eq!(tr("develop.set"), "develop.set"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert!(saved.contains(r#""language":"it""#)); - assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::It); - let ctx = egui::Context::default(); - for code in ["it", "it-IT", "it_IT.UTF-8", "it-Latn-IT", "it-CH"] { - assert_eq!(Locale::parse_tag(code), Some(Locale::It)); - let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": code})); - let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; - assert_eq!(reply["ok"], true); - assert_eq!(language(), Locale::It); - } - set_language(Locale::En); - } - #[test] fn italian_panels_dialogs_and_letters_paint_with_bundled_fonts() { let ctx = fonts_ctx(&[]); let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); app.ui.left_panel = true; let text = painted_text(&ctx, &mut app, Locale::It); - assert!(text.contains("Le mie foto") && text.contains("Tutte le foto"), "{text}"); - for (command, title) in - [("app.about", "Informazioni su LightCraft"), ("app.shortcuts", "Scorciatoie da tastiera"), ("app.settings", "Impostazioni")] - { + assert!(text.contains(Locale::It.tr("My Photos")) && text.contains(Locale::It.tr("All Photos")), "{text}"); + for (command, title) in [("app.about", "About LightCraft"), ("app.shortcuts", "Keyboard Shortcuts"), ("app.settings", "Settings")] { app.ui.dialog = None; app.run(command, serde_json::json!({})).unwrap(); let text = painted_text(&ctx, &mut app, Locale::It); - assert!(text.contains(title), "{command}: {text}"); + assert!(text.contains(Locale::It.tr(title)), "{command}: {text}"); } ctx.fonts_mut(|fonts| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { @@ -1331,95 +1067,18 @@ mod tests { set_language(Locale::En); } - /// Finnish's coverage of every catalog message and display label, reported like Italian's. - #[test] - fn finnish_coverage_of_catalogs_commands_controls_and_rules_is_reported() { - let catalog = Locale::Fi.catalog(); - let keys: std::collections::BTreeSet<&String> = Locale::ALL.iter().flat_map(|language| language.catalog().keys()).collect(); - let lacking: Vec<_> = keys.into_iter().filter(|key| !catalog.contains_key(key.as_str())).collect(); - if !lacking.is_empty() { - eprintln!("fi lacks {} catalog message(s) (shown in English): {lacking:?}", lacking.len()); - } - let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); - labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); - labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); - labels.extend(crate::panels::settings::TABS.iter().map(|(_, label)| *label)); - for (_, label, kind) in lightcraft_catalog::rules::FIELDS { - labels.push(label); - labels.extend(lightcraft_catalog::rules::ops_for(*kind).iter().map(|(_, label)| *label)); - } - labels.extend(lightcraft_engine::rename::TOKENS.iter().map(|token| token.meaning)); - labels.extend(lightcraft_engine::rename::TEMPLATE_NOTES); - let missing: Vec<_> = labels.into_iter().filter(|label| !catalog.contains_key(*label)).collect(); - if !missing.is_empty() { - eprintln!("fi lacks {} display label(s) (shown in English): {missing:?}", missing.len()); - } - } - - #[test] - fn finnish_switches_persists_formats_dates_and_preserves_values() { - use crate::control::{ControlRequest, Outcome}; - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.finnish", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::Fi); - assert_eq!(crate::menubar::checked(&app, "app.language.finnish"), Some(true)); - assert_eq!(tr("Light"), "Valo"); - assert_eq!(tr("Landscape"), "Maisema"); - assert_eq!(tr("Home"), "Kotikansio"); - // Finnish dates have no leading zeros and a lower-case weekday; times are 24-hour with colons. - assert_eq!(date_group_label("2026-09-20", false), "sunnuntai 20.9.2026"); - assert_eq!(date_group_label("2026-09-20", true), "sunnuntai 20."); - assert_eq!(date_group_label("2026-09", false), "9/2026"); - assert_eq!(date_group_label("2026-09", true), "9"); - assert_eq!(date_group_label("2026", false), "2026"); - assert_eq!(display_time("2026-09-20T16:04:05"), "sunnuntai 20.9.2026 16:04:05"); - // A noun after a numeral is in the partitive singular (1 kuva, 2 kuvaa), which the English - // plural suffix cannot choose, so counts follow a label; the suffix is consumed and never shows. - for n in [0, 1, 2, 5, 11, 21, 22, 25, 111] { - assert_eq!(tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }), format!("Tuotuja kuvia: {n}")); - assert_eq!(tr_format!("{} files and {f} folder{}", n, "s", f = n), format!("Tiedostoja: {n}, kansioita: {n}")); - let noun = tr(if n == 1 { "cached picture" } else { "cached pictures" }); - let expected = if n == 1 { "1 välimuistissa oleva kuva".to_string() } else { format!("{n} välimuistissa olevaa kuvaa") }; - assert_eq!(tr_format!("{n} {noun}", n = n, noun = noun), expected); - } - // This trailing argument is queue progress, not an English plural suffix. - let queued = tr_format!(" · {queued} waiting", queued = 5); - assert_eq!( - tr_format!("Denoising {name}: {done} of {total} tiles{}", queued, name = "IMG.CR3", done = 1, total = 4), - "Kohinanpoisto IMG.CR3: 1 / 4 ruutua · odottaa: 5" - ); - let name = "Color {title} 日本語"; - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22), format!("Lisättyjä kuvia kohteeseen ”{name}”: 22")); - assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_eq!(builtin_label("Warm Glow", true), "Lämmin hehku"); - assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); - assert_eq!(tr("develop.set"), "develop.set"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert!(saved.contains(r#""language":"fi""#)); - assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::Fi); - let ctx = egui::Context::default(); - for code in ["fi", "fi-FI", "fi_FI.UTF-8", "fi-Latn-FI"] { - assert_eq!(Locale::parse_tag(code), Some(Locale::Fi)); - let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": code})); - let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; - assert_eq!(reply["ok"], true); - assert_eq!(language(), Locale::Fi); - } - set_language(Locale::En); - } - #[test] fn finnish_panels_dialogs_and_letters_paint_with_bundled_fonts() { let ctx = fonts_ctx(&[]); let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); app.ui.left_panel = true; let text = painted_text(&ctx, &mut app, Locale::Fi); - assert!(text.contains("Omat kuvat") && text.contains("Kaikki kuvat"), "{text}"); - for (command, title) in [("app.about", "Tietoja LightCraftista"), ("app.shortcuts", "Pikanäppäimet"), ("app.settings", "Asetukset")] { + assert!(text.contains(Locale::Fi.tr("My Photos")) && text.contains(Locale::Fi.tr("All Photos")), "{text}"); + for (command, title) in [("app.about", "About LightCraft"), ("app.shortcuts", "Keyboard Shortcuts"), ("app.settings", "Settings")] { app.ui.dialog = None; app.run(command, serde_json::json!({})).unwrap(); let text = painted_text(&ctx, &mut app, Locale::Fi); - assert!(text.contains(title), "{command}: {text}"); + assert!(text.contains(Locale::Fi.tr(title)), "{command}: {text}"); } ctx.fonts_mut(|fonts| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { @@ -1435,66 +1094,14 @@ mod tests { set_language(Locale::En); } - /// Every command, control, rule and rename label, and every line of What's New, is a message a - /// catalog can translate. What a language lacks is reported, not failed (like - /// `catalogs_agree_on_placeholders_and_report_gaps`): a feature PR doesn't have to ship every - /// language, and the translations catch up at their own pace. #[test] - fn display_label_gaps_are_reported() { - let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); - labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); - labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); - for (_, label, kind) in lightcraft_catalog::rules::FIELDS { - labels.push(label); - labels.extend(lightcraft_catalog::rules::ops_for(*kind).iter().map(|(_, label)| *label)); - } - labels.extend(lightcraft_catalog::rules::FIELD_GROUPS.iter().map(|group| group.0)); - labels.extend(lightcraft_engine::rename::TOKENS.iter().map(|token| token.meaning)); - labels.extend(lightcraft_engine::rename::TEMPLATE_NOTES); - let ui_labels = labels.len(); - for line in crate::panels::dialogs::WHATS_NEW.lines().map(str::trim) { - if line.is_empty() || line.starts_with("# ") { - continue; - } - let label = line.strip_prefix("### ").or_else(|| line.strip_prefix("## ")).or_else(|| line.strip_prefix("- ")).unwrap_or(line); - labels.push(label); - } - for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { - let catalog = language.catalog(); - let missing: Vec<&&str> = labels[..ui_labels].iter().filter(|label| !catalog.contains_key(**label)).collect(); - let notes = labels[ui_labels..].iter().filter(|label| !catalog.contains_key(**label)).count(); - if !missing.is_empty() || notes > 0 { - eprintln!( - "{} lacks {} display label(s) (shown in English): {missing:?}; and {notes} What's New line(s)", - language.code(), - missing.len() - ); - } - } - // the German catalog, which set out to cover them all, still covers every other catalog - let german = Locale::De.catalog(); - let gaps: Vec<&String> = - Locale::ALL.iter().flat_map(|language| language.catalog().keys()).filter(|key| !german.contains_key(key.as_str())).collect(); - if !gaps.is_empty() { - eprintln!("de lacks {} message(s) another catalog has: {gaps:?}", gaps.len()); - } - } - - #[test] - fn german_switches_via_menu_and_control_persists_and_formats_dates() { + fn german_switches_via_menu_and_control_and_persists() { use crate::control::{ControlRequest, Outcome}; let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); app.run("app.language.german", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Locale::De); - assert_eq!(tr("File"), "Datei"); + assert_eq!(language(), Locale::De); assert_eq!(crate::menubar::checked(&app, "app.language.german"), Some(true)); - assert_eq!(date_group_label("2026-09-20", false), "Sonntag, 20.09.2026"); - assert_eq!(date_group_label("2026-09-20", true), "Sonntag, 20."); - assert_eq!(date_group_label("2026-09", false), "09/2026"); - assert_eq!(display_time("2026-09-20T16:04:05"), "Sonntag, 20.09.2026 16:04:05"); - assert_eq!(tr_format!("Imported {} photo{}", 1, ""), "1 Foto importiert"); - assert_eq!(tr_format!("Imported {} photo{}", 12, "s"), "12 Fotos importiert"); - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", "Color", n = 12), "12 Fotos zu „Color“ hinzugefügt"); let saved = serde_json::to_string(&app.ui).unwrap(); assert!(saved.contains(r#""language":"de""#)); assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::De); @@ -1506,7 +1113,7 @@ mod tests { assert_eq!(language(), Locale::De); } assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_eq!(builtin_label("Warm Glow", true), "Warmer Glanz"); + assert_eq!(builtin_label("Warm Glow", true), Locale::De.tr("Warm Glow")); assert_eq!(tr("my-photo.jpg"), "my-photo.jpg"); let rules = lightcraft_catalog::RuleSet { mode: lightcraft_catalog::Match::All, @@ -1516,7 +1123,9 @@ mod tests { catalog .apply(lightcraft_catalog::Op::AddAlbum { album: lightcraft_catalog::Album::new(lightcraft_catalog::AlbumId(4), "Ausgeschlossen") }) .unwrap(); - assert_eq!(rules_label(&rules, &catalog), "Stichwörter enthält Color"); + // "Color" is a message too, but a rule's free-text value stays as written + let keywords = lightcraft_catalog::rules::field_label("keywords").unwrap_or("keywords"); + assert_eq!(rules_label(&rules, &catalog), format!("{} {} Color", Locale::De.tr(keywords), Locale::De.tr("contains"))); let album = lightcraft_catalog::RuleSet { mode: lightcraft_catalog::Match::All, rules: vec![lightcraft_catalog::Rule::Field { field: "album".into(), op: "isNot".into(), value: serde_json::json!(4) }], @@ -1530,21 +1139,42 @@ mod tests { value: serde_json::json!("publicDomain"), }], }; - assert!(rules_label(&rules, &catalog).ends_with(" Gemeinfrei"), "{}", rules_label(&rules, &catalog)); + let public_domain = format!(" {}", choice_text_in(Locale::De, "copyrightStatus", "publicDomain")); + assert!(rules_label(&rules, &catalog).ends_with(&public_domain), "{}", rules_label(&rules, &catalog)); for value in [serde_json::json!(false), serde_json::json!("false")] { let rules = lightcraft_catalog::RuleSet { mode: lightcraft_catalog::Match::All, rules: vec![lightcraft_catalog::Rule::Field { field: "edited".into(), op: "is".into(), value }], }; - assert!(rules_label(&rules, &catalog).ends_with(" Nein"), "{}", rules_label(&rules, &catalog)); + let no = format!(" {}", bool_text_in(Locale::De, false)); + assert!(rules_label(&rules, &catalog).ends_with(&no), "{}", rules_label(&rules, &catalog)); } + let both = lightcraft_catalog::Filter { + label: Some(lightcraft_catalog::ColorLabel::Red), + labels: vec![lightcraft_catalog::ColorLabel::Blue, lightcraft_catalog::ColorLabel::Red], + ..Default::default() + }; + let name = |label| color_label(&app.session.catalog, label); + let (red, blue, green) = + (name(lightcraft_catalog::ColorLabel::Red), name(lightcraft_catalog::ColorLabel::Blue), name(lightcraft_catalog::ColorLabel::Green)); + let (label, and, or) = (tr("Label"), tr("and"), tr("or")); + assert_eq!(filter_label(&both, &app.session.catalog), format!("{label}: {red}")); + let both = lightcraft_catalog::Filter { labels: vec![lightcraft_catalog::ColorLabel::Blue], ..both }; + assert_eq!(filter_label(&both, &app.session.catalog), format!("{label}: {red} {and} {blue}")); + let both = lightcraft_catalog::Filter { labels: vec![lightcraft_catalog::ColorLabel::Blue, lightcraft_catalog::ColorLabel::Green], ..both }; + assert_eq!(filter_label(&both, &app.session.catalog), format!("{label}: {red} {and} ({blue} {or} {green})")); let filter = lightcraft_catalog::Filter { labels: vec![lightcraft_catalog::ColorLabel::Red, lightcraft_catalog::ColorLabel::Blue], ..Default::default() }; - assert_eq!(filter_label(&filter, &app.session.catalog), "Farbmarkierung: Rot oder Blau"); + let blue = color_label(&app.session.catalog, lightcraft_catalog::ColorLabel::Blue); + let red = color_label(&app.session.catalog, lightcraft_catalog::ColorLabel::Red); + let label = filter_label(&filter, &app.session.catalog); + assert!(label.contains(&red) && label.contains(&blue), "{label}"); + // a label set's own name is the user's app.run("label.setNames", serde_json::json!({"names": {"red": "Color"}})).unwrap(); - assert_eq!(filter_label(&filter, &app.session.catalog), "Farbmarkierung: Color oder Blau"); + let label = filter_label(&filter, &app.session.catalog); + assert!(label.contains("Color") && !label.contains(&red) && label.contains(&blue), "{label}"); set_language(Locale::En); } @@ -1554,15 +1184,15 @@ mod tests { let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); app.ui.left_panel = true; let text = painted_text(&ctx, &mut app, Locale::De); - assert!(text.contains("Meine Fotos") && text.contains("Alle Fotos"), "{text}"); + assert!(text.contains(Locale::De.tr("My Photos")) && text.contains(Locale::De.tr("All Photos")), "{text}"); app.ui.view = crate::state::ViewMode::People; let text = painted_text(&ctx, &mut app, Locale::De); - assert!(text.contains("Benannte Personen"), "{text}"); - for (command, title) in [("app.about", "Über LightCraft"), ("app.shortcuts", "Tastenkürzel"), ("app.settings", "Einstellungen")] { + assert!(text.contains(Locale::De.tr("Named People")), "{text}"); + for (command, title) in [("app.about", "About LightCraft"), ("app.shortcuts", "Keyboard Shortcuts"), ("app.settings", "Settings")] { app.ui.dialog = None; app.run(command, serde_json::json!({})).unwrap(); let text = painted_text(&ctx, &mut app, Locale::De); - assert!(text.contains(title), "{command}: {text}"); + assert!(text.contains(Locale::De.tr(title)), "{command}: {text}"); } ctx.fonts_mut(|fonts| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { @@ -1634,10 +1264,6 @@ mod tests { assert_eq!(crate::menubar::display_item_label("app.export", &serde_json::json!({"preset": "Color"}), "Color"), "Color"); assert_eq!(crate::menubar::display_item_label("view.photoGrid", &serde_json::Value::Null, "Color"), language.tr("Color")); } - set_language(Locale::ZhHans); - assert_eq!(crate::menubar::display_item_label("view.photoGrid", &serde_json::Value::Null, "Color"), "颜色"); - set_language(Locale::Ja); - assert_eq!(crate::menubar::display_item_label("view.photoGrid", &serde_json::Value::Null, "Color"), "カラー"); set_language(Locale::En); } @@ -1689,12 +1315,6 @@ mod tests { assert_eq!(app.font_language, *language, "the fonts follow the language"); assert_eq!(ids(&app), english_ids, "{language:?}: command ids are presentation-independent"); } - let text = painted_text(&ctx, &mut app, Locale::Ja); - assert!(text.contains("マイフォト") && text.contains("すべての写真"), "{text}"); - let text = painted_text(&ctx, &mut app, Locale::ZhHans); - assert!(text.contains("我的照片") && text.contains("所有照片"), "{text}"); - let text = painted_text(&ctx, &mut app, Locale::PtBr); - assert!(text.contains("Minhas fotos") && text.contains("Todas as fotos"), "{text}"); set_language(Locale::En); } @@ -1765,7 +1385,7 @@ mod tests { } /// Traditional Chinese through the menu command and the control channel, persisted, with - /// localised headings and dates; ids and user text are untouched. + /// localised headings; ids and user text are untouched. #[test] fn traditional_chinese_switches_through_menu_and_control_and_persists() { use crate::control::{ControlRequest, Outcome}; @@ -1773,15 +1393,9 @@ mod tests { app.run("app.language.traditionalChinese", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Locale::ZhHant); // Applied at once, not on the next frame. - assert_eq!(tr("File"), "檔案"); - assert_eq!(source_label(lightcraft_engine::LibrarySource::All, &app.session.catalog), "所有照片"); - assert_eq!(date_group_label("2026-09-20", false), "2026年9月20日 星期日"); - assert_eq!(date_group_label("2026-09-20", true), "20日 星期日"); - assert_eq!(date_group_label("2026-09", false), "2026年9月"); - assert_eq!(date_group_label("2026-09", true), "9月"); - assert_eq!(date_group_label("2026", false), "2026年"); - assert_eq!(date_group_label("", false), "未知日期"); - assert_eq!(display_time("2026-09-20T16:04:05"), "2026年9月20日 星期日 16:04:05"); + assert_eq!(language(), Locale::ZhHant); + assert_eq!(source_label(lightcraft_engine::LibrarySource::All, &app.session.catalog), Locale::ZhHant.tr("All Photos")); + assert_eq!(date_group_label("", false), Locale::ZhHant.tr("Unknown Date")); assert_eq!(display_time("a-user-value"), "a-user-value"); assert_eq!(crate::menubar::checked(&app, "app.language.traditionalChinese"), Some(true)); assert_eq!(crate::menubar::checked(&app, "app.language.english"), Some(false)); @@ -1789,9 +1403,7 @@ mod tests { for id in ["album.addPhotos", "metadata.applyPreset", "label.applySet"] { assert_eq!(crate::menubar::display_item_label(id, &serde_json::json!({"id": 1}), "Color"), "Color"); } - assert_eq!(crate::menubar::display_item_label("view.photoGrid", &serde_json::Value::Null, "Color"), "色彩"); - assert_eq!(tr_format!("{n} photo{}", "s", n = 12), "12 張照片"); - assert_eq!(tr_format!("Exported {ok} of {total} photo{}", "s", ok = 4, total = 12), "已匯出 4/12 張照片"); + assert_eq!(crate::menubar::display_item_label("view.photoGrid", &serde_json::Value::Null, "Color"), Locale::ZhHant.tr("Color")); let saved = serde_json::to_string(&app.ui).unwrap(); assert!(saved.contains(r#""language":"zh-hant""#), "{saved}"); assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::ZhHant); @@ -1815,7 +1427,8 @@ mod tests { assert_eq!(chinese_ids, ids(&app)); } - /// Dates follow every language's own patterns; English keeps the catalog's wording. + /// Dates follow every language's own patterns (English keeps the catalog's wording); a key that + /// is not a date never panics and never shows a raw pattern. #[test] fn date_headings_in_every_language() { set_language(Locale::En); @@ -1823,14 +1436,16 @@ mod tests { assert_eq!(date_group_label("2026-09-20", true), "Sunday, 20"); assert_eq!(date_group_label("2026-09", true), "September"); assert_eq!(display_time("2026-09-20T16:04:05"), lightcraft_catalog::dates::display_time("2026-09-20T16:04:05")); - set_language(Locale::Ja); - assert_eq!(date_group_label("2026-09-20", false), "2026年9月20日(日曜日)"); - assert_eq!(date_group_label("2026-09", true), "9月"); - set_language(Locale::ZhHans); - assert_eq!(date_group_label("2026-09-20", false), "2026年9月20日 星期日"); for language in Locale::ALL { set_language(*language); - // A key that is not a date never panics and never shows a raw pattern. + if *language != Locale::En { + let day = date_group_label("2026-09-20", false); + assert!(day.contains("20") && day.contains("2026") && day.contains(tr("Sunday")), "{language:?}: {day}"); + assert!(date_group_label("2026-09-20", true).contains("20"), "{language:?}"); + assert!(date_group_label("2026-09", false).contains("2026"), "{language:?}"); + assert!(date_group_label("2026", false).contains("2026"), "{language:?}"); + assert_eq!(display_time("2026-09-20T16:04:05"), format!("{day} 16:04:05"), "{language:?}"); + } for key in ["", "abcd", "2026-xx", "2026-13", "2026-09-xx", "2026-09"] { assert!(!date_group_label(key, false).contains('{'), "{language:?}: {key:?}"); assert!(!date_group_label(key, true).contains('{'), "{language:?}: {key:?}"); @@ -1849,172 +1464,18 @@ mod tests { app.ui.presets = true; let builtin = app.session.presets.iter().find(|p| p.name == "Warm Glow").unwrap().clone(); app.session.presets.push(lightcraft_develop::Preset { id: "user.test".into(), builtin: false, ..builtin }); - for (panel, title) in [(crate::state::RightPanel::Activity, "歷史紀錄"), (crate::state::RightPanel::Versions, "版本")] { + let zh = Locale::ZhHant; + for (panel, title) in [(crate::state::RightPanel::Activity, "History"), (crate::state::RightPanel::Versions, "Versions")] { app.ui.right = panel; - let text = painted_text(&ctx, &mut app, Locale::ZhHant); - assert!(text.contains(title), "{text}"); - assert!(!text.contains("History") && !text.contains("Versions"), "{text}"); - assert!(text.contains("暖光"), "stock preset: {text}"); + let text = painted_text(&ctx, &mut app, zh); + assert!(text.contains(zh.tr(title)), "{text}"); + assert!(text.contains(zh.tr("Warm Glow")), "stock preset: {text}"); assert!(text.contains("Warm Glow"), "user preset: {text}"); - assert!(text.contains("色彩"), "stock group: {text}"); - } - assert_eq!(history_label("Exposure", &app.session.presets), "曝光"); - assert_eq!(history_label("Preset: Warm Film", &app.session.presets), "預設集:暖調底片"); - assert_eq!(history_label("Preset: Warm Glow", &app.session.presets), "預設集:Warm Glow"); - set_language(Locale::En); - } - - /// English catalog values Vietnamese keeps on purpose. Grouped by reason: - /// standards/acronyms (`ISO`, `HDR`, …), product names (`LightCraft`, `PhotoCraft`), - /// file-type tokens (`Raw`/`raw`, `video`), look names left as established labels - /// (`Bleach Bypass`, `Vintage`), and machine ids that must stay byte-identical - /// (`publicDomain`, `denoiseModel.accept`). `Album` stays as the common loanword. - /// Every other required label must differ from its English source. - const VI_INTENTIONAL_ENGLISH: &[&str] = &[ - "OK", - "ISO", - "RGB", - "HDR", - "JPEG", - "PNG", - "TIFF", - "WebP", - "AVIF", - "HEIF", - "HEIC", - "DNG", - "ICC", - "EXIF", - "XMP", - "GPU", - "MCP", - "SAM", - "RAW", - "Raw", - "raw", - "B&W", - "LUT", - "LightCraft", - "ArtCraft", - "GitHub", - "Discord", - "English", - "日本語", - "繁體中文(台灣)", - "Display P3", - "Bleach Bypass", - "Cross Process", - "HDR…", - "video", - "Video", - "true", - "false", - "Album", - "Vintage", - "publicDomain", - "denoiseModel.accept", - "Panorama", - "Panorama…", - "PhotoCraft", - "SDR", - "Matrix/TRC", - "LUT-based", - ]; - - /// Vietnamese's coverage of every catalog message and display label, reported like Italian's; the - /// messages it has are never left in English. - #[test] - fn vietnamese_covers_catalogs_commands_controls_and_rules() { - let catalog = Locale::Vi.catalog(); - assert!(!catalog.is_empty()); - let keys: std::collections::BTreeSet<&String> = Locale::ALL.iter().flat_map(|language| language.catalog().keys()).collect(); - let lacking: Vec<_> = keys.into_iter().filter(|key| !catalog.contains_key(key.as_str())).collect(); - if !lacking.is_empty() { - eprintln!("vi lacks {} catalog message(s) (shown in English): {lacking:?}", lacking.len()); - } - - let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); - labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); - labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); - labels.extend(crate::panels::settings::TABS.iter().map(|(_, label)| *label)); - for (_, label, kind) in lightcraft_catalog::rules::FIELDS { - labels.push(label); - labels.extend(lightcraft_catalog::rules::ops_for(*kind).iter().map(|(_, label)| *label)); - } - labels.extend(lightcraft_catalog::rules::FIELD_GROUPS.iter().map(|group| group.0)); - labels.extend(lightcraft_engine::rename::TOKENS.iter().map(|token| token.meaning)); - labels.extend(lightcraft_engine::rename::TEMPLATE_NOTES); - for word in crate::date_picker::WEEKDAY_SHORT.iter().chain(&["Pick a date", "Year", "Month", "Day"]) { - labels.push(*word); - } - for day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] { - labels.push(day); - } - let missing: Vec<_> = labels.into_iter().filter(|label| !catalog.contains_key(*label)).collect(); - if !missing.is_empty() { - eprintln!("vi lacks {} display label(s) (shown in English): {missing:?}", missing.len()); - } - - for (key, value) in catalog { - if key.contains('|') { - continue; - } - if VI_INTENTIONAL_ENGLISH.contains(&key.as_str()) { - continue; - } - assert!(!value.is_empty(), "vi empty for {key:?}"); - // Identical values outside the allowlist are accidental English fallbacks. - if value == key && key.chars().any(|ch| ch.is_ascii_alphabetic()) && key.len() > 1 { - // Single-letter ops / symbols may match; longer shared English must be listed. - assert!( - key.len() <= 2 || key.chars().all(|ch| !ch.is_ascii_alphabetic()), - "vi keeps English for {key:?}; add it to VI_INTENTIONAL_ENGLISH if intentional" - ); - } - } - } - - #[test] - fn vietnamese_switches_persists_formats_dates_and_preserves_values() { - use crate::control::{ControlRequest, Outcome}; - let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - app.run("app.language.vietnamese", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Locale::Vi); - assert_eq!(crate::menubar::checked(&app, "app.language.vietnamese"), Some(true)); - assert_eq!(tr("Light"), "Ánh sáng"); - assert_eq!(tr("Exposure"), "Phơi sáng"); - assert_eq!(Locale::Vi.name(), "Tiếng Việt"); - assert_eq!(tr("Settings"), "Cài đặt"); - assert_eq!(tr("Appearance"), "Giao diện"); - assert_eq!(tr("My Photos"), "Ảnh của tôi"); - assert_eq!(tr("Candidate"), "Ảnh ứng viên"); - assert_eq!(tr("Subject"), "Chủ thể"); - assert_eq!(date_group_label("2026-09-20", false), "Chủ Nhật, 20/9/2026"); - assert_eq!(date_group_label("2026-09", false), "Tháng 9 năm 2026"); - assert_eq!(date_group_label("2026-09", true), "Tháng 9"); - assert_eq!(display_time("2026-09-20T16:04:05"), "Chủ Nhật, 20/9/2026 16:04:05"); - for n in [0, 1, 2, 5, 22] { - let text = tr_format!("Imported {} photo{}", n, if n == 1 { "" } else { "s" }); - assert!(text.contains(&n.to_string()) && text.contains("ảnh"), "{n}: {text}"); - assert!(!text.contains("photos") && !text.contains("photo"), "{n}: {text}"); - } - let name = "Color {title} 日本語"; - assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22), format!("Đã thêm 22 ảnh vào «{name}»")); - assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); - assert_ne!(builtin_label("Warm Glow", true), "Warm Glow"); - assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); - assert_eq!(tr("develop.set"), "develop.set"); - let saved = serde_json::to_string(&app.ui).unwrap(); - assert!(saved.contains(r#""language":"vi""#), "{saved}"); - assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::Vi); - let ctx = egui::Context::default(); - for code in ["vi", "vi-VN", "vi_VN", "vi_VN.UTF-8"] { - assert_eq!(Locale::parse_tag(code), Some(Locale::Vi)); - let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": code})); - let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; - assert_eq!(reply["ok"], true); - assert_eq!(language(), Locale::Vi); + assert!(text.contains(zh.tr("Color")), "stock group: {text}"); } + assert_eq!(history_label("Exposure", &app.session.presets), zh.tr("Exposure")); + assert!(history_label("Preset: Warm Film", &app.session.presets).ends_with(zh.tr("Warm Film"))); + assert!(history_label("Preset: Warm Glow", &app.session.presets).ends_with("Warm Glow"), "the user's preset shares the name"); set_language(Locale::En); } @@ -2024,12 +1485,12 @@ mod tests { let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); app.ui.left_panel = true; let text = painted_text(&ctx, &mut app, Locale::Vi); - assert!(text.contains("Ảnh của tôi") && text.contains("Tất cả ảnh"), "{text}"); - for (command, title) in [("app.about", "Giới thiệu LightCraft"), ("app.shortcuts", "Phím tắt"), ("app.settings", "Cài đặt")] { + assert!(text.contains(Locale::Vi.tr("My Photos")) && text.contains(Locale::Vi.tr("All Photos")), "{text}"); + for (command, title) in [("app.about", "About LightCraft"), ("app.shortcuts", "Keyboard Shortcuts"), ("app.settings", "Settings")] { app.ui.dialog = None; app.run(command, serde_json::json!({})).unwrap(); let text = painted_text(&ctx, &mut app, Locale::Vi); - assert!(text.contains(title), "{command}: {text}"); + assert!(text.contains(Locale::Vi.tr(title)), "{command}: {text}"); } ctx.fonts_mut(|fonts| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { @@ -2047,6 +1508,267 @@ mod tests { }); set_language(Locale::En); } + /// The messages each language lacks, which it shows in English. Never fails: `cargo xtask ci` + /// runs it with `--nocapture`, so the list lands in the gate log. Plain messages are every key + /// some catalog has plus the labels the UI passes to `tr` from tables (commands, controls, rule + /// fields…); formats are every key some `*-formats.json` has plus every `tr_format!` message in + /// the app's source. An empty translation counts as missing. + #[test] + fn translation_gaps_report() { + let notes = whats_new_lines(); + let messages: std::collections::BTreeSet<String> = plain_messages().into_iter().filter(|m| !notes.contains(&m.as_str())).collect(); + let formats = format_messages(); + let quoted = |list: &[&str]| list.iter().map(|m| format!("{m:?}")).collect::<Vec<_>>().join(", "); + let mut out = format!( + "Translation gaps, shown in English ({} messages, {} formats, {} What's New lines):\n", + messages.len(), + formats.len(), + notes.len() + ); + for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { + let catalog = language.catalog(); + let own_formats = formats_catalog(language.code()); + let missing: Vec<&str> = messages.iter().map(String::as_str).filter(|m| !catalog.contains_key(*m)).collect(); + let missing_formats: Vec<&str> = formats.iter().map(String::as_str).filter(|m| !own_formats.contains_key(*m)).collect(); + let missing_notes = notes.iter().filter(|line| !catalog.contains_key(**line)).count(); + out.push_str(&format!( + "{}: {} messages, {} formats, {} What's New lines\n", + language.code(), + missing.len(), + missing_formats.len(), + missing_notes + )); + if !missing.is_empty() { + out.push_str(&format!(" messages: {}\n", quoted(&missing))); + } + if !missing_formats.is_empty() { + out.push_str(&format!(" formats: {}\n", quoted(&missing_formats))); + } + } + println!("{out}"); + } + + /// Every plain message: the keys of every catalog (but contextual entries, which a language adds + /// only where it needs one) and the labels the UI translates from tables. + fn plain_messages() -> std::collections::BTreeSet<String> { + use lightcraft_catalog::rules; + let mut labels: Vec<&str> = lightcraft_engine::command_specs().iter().map(|spec| spec.label).collect(); + labels.extend(crate::menus::ui_commands().map(|command| command.1).filter(|label| !Locale::ALL.iter().any(|locale| locale.name() == *label))); + labels.extend(lightcraft_develop::CONTROLS.iter().map(|control| control.label)); + labels.extend(crate::panels::settings::TABS.iter().map(|(_, label)| *label)); + for (_, label, kind) in rules::FIELDS { + labels.push(label); + labels.extend(rules::ops_for(*kind).iter().map(|(_, label)| *label)); + if let rules::Kind::Choice(choices) = kind { + labels.extend(choices.iter().map(|(_, label)| *label)); + } + } + labels.extend(rules::FIELD_GROUPS.iter().map(|group| group.0)); + labels.extend(rules::Issue::ALL.iter().map(|issue| issue.text())); + labels.extend([rules::bool_label(true), rules::bool_label(false)]); + labels.extend(lightcraft_engine::rename::TOKENS.iter().map(|token| token.meaning)); + labels.extend(lightcraft_engine::rename::TEMPLATE_NOTES); + labels.extend(crate::date_picker::WEEKDAY_SHORT); + labels.extend(["Pick a date", "Year", "Month", "Day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]); + // the album pickers + labels.extend([ + "Choose an album…", + "No albums yet", + "Search albums", + "No albums match", + "This is the album you're editing", + "It tests this album, so testing it back would loop", + "Fix the marked rules to save this album.", + "None", + "New album", + "New album…", + "Imported Photos", + ]); + labels.extend(crate::panels::keyword_list::VARIABLE_LABELS); + let contextual = format!("{BOOL_CONTEXT}|"); + Locale::ALL + .iter() + .flat_map(|language| language.catalog().keys()) + .filter(|key| !key.starts_with(&contextual)) + .cloned() + .chain(labels.into_iter().map(str::to_string)) + .collect() + } + + /// Help ▸ What's New, line by line as the dialog looks each one up. + fn whats_new_lines() -> Vec<&'static str> { + crate::panels::dialogs::WHATS_NEW + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with("# ")) + .map(|line| line.strip_prefix("### ").or_else(|| line.strip_prefix("## ")).or_else(|| line.strip_prefix("- ")).unwrap_or(line)) + .collect() + } + + /// `locales/<code>-formats.json` (the catalog `build.rs` compiles into `tr_format!`), without + /// empty translations. + fn formats_catalog(code: &str) -> BTreeMap<String, String> { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(format!("locales/{code}-formats.json")); + let mut messages: BTreeMap<String, String> = + std::fs::read_to_string(path).ok().and_then(|text| serde_json::from_str(&text).ok()).unwrap_or_default(); + messages.retain(|_, text| !text.is_empty()); + messages + } + + /// Every format message: the keys of every formats catalog and the message of every + /// `tr_format!` call in `src/` outside its test modules. + fn format_messages() -> std::collections::BTreeSet<String> { + let mut all: std::collections::BTreeSet<String> = Locale::ALL + .iter() + .filter(|language| **language != Locale::En) + .flat_map(|language| formats_catalog(language.code()).into_keys()) + .collect(); + let mut dirs = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")]; + while let Some(dir) = dirs.pop() { + for path in std::fs::read_dir(&dir).unwrap().map(|entry| entry.unwrap().path()) { + if path.is_dir() { + dirs.push(path); + } else if path.extension().is_some_and(|ext| ext == "rs") { + let source = std::fs::read_to_string(&path).unwrap(); + let app = source + .split( + "#[cfg(test)] +mod ", + ) + .next() + .unwrap_or_default(); + all.extend(tr_format_messages(app)); + } + } + } + all + } + + /// The first argument of each `tr_format!` call in `source`, when it is a string literal. + fn tr_format_messages(source: &str) -> Vec<String> { + // built from parts, so this file's own source holds no call to find + let call = concat!("tr_format", "!("); + let mut messages = Vec::new(); + for (at, _) in source.match_indices(call) { + let Some(body) = source[at + call.len()..].trim_start().strip_prefix('"') else { continue }; + let mut message = String::new(); + let mut chars = body.chars(); + while let Some(ch) = chars.next() { + match ch { + '"' => break, + '\\' => match chars.next() { + Some('n') => message.push('\n'), + Some('t') => message.push('\t'), + Some('u') => { + let hex: String = chars.by_ref().skip(1).take_while(|ch| *ch != '}').collect(); + message.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)); + } + Some(other) => message.push(other), + None => break, + }, + _ => message.push(ch), + } + } + messages.push(message); + } + messages + } + + #[test] + fn tr_format_messages_are_read_from_source() { + let call = concat!("tr_format", "!("); + let source = format!("{call}\"Imported {{}} photo{{}}\", n, s); crate::i18n::{call}\n \"Say \\\"hi\\\" \\u{{2192}}\", x); {call}name)"); + assert_eq!(tr_format_messages(&source), ["Imported {} photo{}", "Say \"hi\" →"]); + } + + /// A drop's notice comes from what `library.import` reported: a photo added, one brought back from Recently + /// Deleted and a file that could not be read are each named; a drop of duplicates only says nothing. + #[test] + fn a_dropped_photos_notice_names_every_outcome_of_the_import_and_is_silent_for_duplicates_only() { + set_language(Locale::En); + let dir = std::env::temp_dir().join(format!("lc-drop-notice-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let png = |name: &str, seed: u8| { + let data: Vec<[u8; 4]> = (0..48 * 32).map(|i| [(i % 48 * 5) as u8, (i / 48 * 7) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: 48, height: 32, data }; + let bytes = + lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join(name), bytes).unwrap(); + dir.join(name).to_string_lossy().into_owned() + }; + let (trashed, added) = (png("trashed.png", 1), png("new.png", 2)); + let broken = dir.join("broken.jpg"); + std::fs::write(&broken, b"not a jpeg at all").unwrap(); + let mut s = lightcraft_engine::Session::new().with_fs(); + let r = s.execute("library.import", &serde_json::json!({"paths": [trashed]})).unwrap(); + s.execute("photo.delete", &serde_json::json!({"ids": [r["imported"][0]]})).unwrap(); + let report = s.execute("library.import", &serde_json::json!({"paths": [trashed, added, broken]})).unwrap(); + assert_eq!( + dropped_photos_outcome(&report).as_deref(), + Some("Added 1 photo · Restored 1 photo from Recently Deleted · 1 photo not readable"), + "{report}" + ); + let again = s.execute("library.import", &serde_json::json!({"paths": [added]})).unwrap(); + assert_eq!(dropped_photos_outcome(&again), None, "a duplicate only: {again}"); + let _ = std::fs::remove_dir_all(dir); + } + + /// Polish: the menu and control channel select it, dates read day.month.year, and every count + /// reads right for any number. Polish has three plural forms (1 zdjęcie, 2 zdjęcia, 5 zdjęć), so + /// counts follow their noun ("Zaimportowane zdjęcia: 22") instead of a form that fits only some. + #[test] + fn polish_switches_formats_dates_and_reads_every_count() { + use crate::control::{ControlRequest, Outcome}; + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + app.run("app.language.polish", serde_json::json!({})).unwrap(); + assert_eq!(app.ui.language, Locale::Pl); + assert_eq!(Locale::Pl.name(), "Polski"); + assert_eq!(crate::menubar::checked(&app, "app.language.polish"), Some(true)); + assert_eq!(tr("File"), "Plik"); + assert_eq!(tr("Exposure"), "Ekspozycja"); + assert_eq!(date_group_label("2026-09-20", false), "Niedziela, 20.09.2026"); + assert_eq!(date_group_label("2026-09-20", true), "Niedziela, 20"); + assert_eq!(date_group_label("2026-09", false), "09.2026"); + assert_eq!(date_group_label("2026", false), "2026"); + assert_eq!(display_time("2026-09-20T16:04:05"), "Niedziela, 20.09.2026 16:04:05"); + for n in [0, 1, 2, 3, 4, 5, 12, 21, 22, 25, 111] { + let s = if n == 1 { "" } else { "s" }; + assert_eq!(tr_format!("Imported {} photo{}", n, s), format!("Zaimportowane zdjęcia: {n}")); + for (one, many, noun) in [ + ("photo waiting", "photos waiting", "Oczekujące zdjęcia"), + ("cached picture", "cached pictures", "Obrazy w pamięci podręcznej"), + ("photo has its denoised picture.", "photos have their denoised picture.", "Zdjęcia z odszumioną wersją"), + ] { + assert_eq!(tr_format!("{n} {noun}", n = n, noun = tr(if n == 1 { one } else { many })), format!("{noun}: {n}")); + } + assert_eq!(tr_format!("Delete {n} Photos", n = n), format!("Usuń zdjęcia ({n})")); + assert_eq!(tr_format!("{n} preset{}", s, n = n), format!("Ustawienia: {n}")); + } + let name = String::from("Color 1234.56 {title} 日本語"); + assert_eq!(tr_format!("Added {n} photo{} to “{}”", "s", name, n = 22), format!("Dodano do „{name}”: 22")); + let saved = serde_json::to_string(&app.ui).unwrap(); + assert_eq!(serde_json::from_str::<crate::state::UiState>(&saved).unwrap().language, Locale::Pl); + let ctx = egui::Context::default(); + for tag in ["pl", "pl-PL", "pl_PL.UTF-8", "PL-pl"] { + assert_eq!(Locale::parse_tag(tag), Some(Locale::Pl), "{tag}"); + let (request, _) = ControlRequest::new("ui.set", serde_json::json!({"language": tag})); + let Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected reply") }; + assert_eq!(reply["ok"], true); + assert_eq!(language(), Locale::Pl); + } + let text = painted_text(&ctx, &mut app, Locale::Pl); + assert!(text.contains("Plik") && text.contains("Ekspozycja"), "{text}"); + ctx.fonts_mut(|fonts| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_SEMIBOLD.into())] { + let font = egui::FontId::new(13.0, family); + for ch in "ąćęłńóśźżĄĆĘŁŃÓŚŹŻ„”".chars() { + assert!(fonts.has_glyph(&font, ch), "missing Polish glyph {ch}"); + } + } + }); + set_language(Locale::En); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index 323d8d902f..74dcc6c406 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -47,7 +47,7 @@ pub(crate) fn grid_height(available: f32, below: f32, row: f32) -> f32 { pub(crate) fn note_dialog_bottom(ui: &egui::Ui) { if !ui.is_sizing_pass() { let y = ui.min_rect().bottom(); - ui.ctx().data_mut(|m| m.insert_temp(egui::Id::new(CONTENT_BOTTOM), y)); + ui.ctx().data_mut(|m| m.insert_temp(egui::Id::unique(CONTENT_BOTTOM), y)); } } @@ -91,6 +91,10 @@ pub struct ImportDialog { /// The candidate clicked last: where a Shift-click range starts ([`ImportDialog::click`]). #[serde(skip)] pub last_clicked: Option<usize>, + /// The library the scan was made in ([`lightcraft_engine::Session::library_generation`]): its duplicate + /// decisions and album ids belong to that catalog, so the review is not shown or confirmed in another. + #[serde(skip)] + pub library: Option<u64>, } /// A candidate's file type, as the review groups them: its format, or its extension when the @@ -114,6 +118,11 @@ impl ImportDialog { let checked = candidates.iter().map(|c| c.duplicate.is_none() && c.error.is_none()).collect(); ImportDialog { candidates, checked, on_deleted: "restore".into(), ..Default::default() } } + + /// Whether the library the scan was made in is still the open one (a review that names none counts). + fn in_library(&self, app: &LightcraftApp) -> bool { + self.library.is_none_or(|g| g == app.session.library_generation()) + } /// Mark the candidates whose photo is in Recently Deleted. They are checked when the choice /// for them (`on_deleted`) imports them — by default it restores them, so a photo deleted by /// mistake comes back by importing its file again (issue #706). @@ -471,6 +480,9 @@ pub fn open(app: &mut LightcraftApp, paths: Vec<String>) -> Result<Value, String if app.scan.is_some() { return Err("a scan is already running".into()); } + if app.review_pending.is_some() { + return Err("an import review is waiting for the open dialog to close".into()); + } let sources = paths.clone(); let (input, paths) = ScanInput::new(&mut app.session, &paths); let progress = std::sync::Arc::new(ScanProgress::default()); @@ -556,6 +568,7 @@ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option<bool>) -> /// Collect a finished scan and open the review (called every frame). pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { + show_pending_review(app, ctx); let Some(task) = app.scan.as_ref() else { return }; ctx.request_repaint_after(std::time::Duration::from_millis(100)); let out = match task.rx.try_recv() { @@ -626,7 +639,52 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { // only an album the review offers (it may have been deleted while the scan ran) d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart())); d.sources = task.sources; - app.ui.dialog = Some(crate::state::Dialog::Import { opts: Box::new(d) }); + d.library = Some(app.session.library_generation()); + app.review_pending = Some(crate::state::Dialog::Import { opts: Box::new(d) }); + show_pending_review(app, ctx); +} + +/// Open the review of a finished scan once no other dialog is open (a face model's licence, Settings… +/// opened while the scan ran stays), checked again shortly while it waits. A review whose library was +/// closed meanwhile (Settings can open another) is dropped. +fn show_pending_review(app: &mut LightcraftApp, ctx: &egui::Context) { + if app.review_pending.is_none() { + return; + } + if let Some(crate::state::Dialog::Import { opts }) = &app.review_pending + && !opts.in_library(app) + { + app.review_pending = None; + return; + } + if app.ui.dialog.is_none() { + app.ui.dialog = app.review_pending.take(); + } else { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } +} + +/// Tests: a review scan that never ends while the returned value lives, so a drop meets it running. +#[cfg(test)] +pub(crate) fn stall_scan(app: &mut LightcraftApp) -> Box<dyn std::any::Any> { + stall_scan_of(app, false) +} + +/// Tests: the same, for a Local folder browse scan (`browse`) instead of the review's scan. +#[cfg(test)] +pub(crate) fn stall_scan_of(app: &mut LightcraftApp, browse: bool) -> Box<dyn std::any::Any> { + let progress = std::sync::Arc::new(ScanProgress::default()); + let (tx, rx) = std::sync::mpsc::channel::<ScanOutput>(); + let guard = scan_guard(app, &progress, false); + app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse, sources: Vec::new(), guard }); + Box::new(tx) +} + +/// Whether an import or any scan (the review's, or a Local folder browse) is running, or a finished scan's +/// review waits for a dialog to close, which a drop of photos must not replace: `open` refuses while a scan +/// runs, and a browse that finishes replaces `app.import`. +pub fn running(app: &LightcraftApp) -> bool { + app.import.is_some() || app.scan.is_some() || app.review_pending.is_some() } impl ScanTask { @@ -636,9 +694,17 @@ impl ScanTask { } } -/// Start importing the dialog's checked files (the dialog's OK / `ui.dialog.confirm`). +/// Start importing the dialog's checked files (the dialog's OK / `ui.dialog.confirm`). Refused while another +/// import runs: replacing `app.import` would stop its worker. pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String> { busy_synchronizing(app)?; + if !d.in_library(app) { + return Err("another library was opened since the photos were scanned: nothing was imported".into()); + } + // a browse scan that finishes starts its own import, replacing this one + if app.import.is_some() || app.scan.as_ref().is_some_and(|t| t.browse) { + return Err(crate::i18n::tr("An import is running").to_string()); + } let queue = d.selected_paths(); if queue.is_empty() { return Err("no photos selected".into()); @@ -691,8 +757,8 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String> /// Start importing `paths` (files or folders) in the background, e.g. dropped on the window. pub fn start_paths(app: &mut LightcraftApp, paths: Vec<String>) -> Result<Value, String> { busy_synchronizing(app)?; - if app.import.is_some() || app.scan.as_ref().is_some_and(|t| !t.browse) { - return Err("an import is running".into()); + if running(app) { + return Err(crate::i18n::tr("An import is running").to_string()); } let undo0 = app.session.undo.len(); let total = paths.len(); @@ -1040,7 +1106,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { // as tall as the window leaves after the options and buttons below it (measured last frame), // so resizing the dialog resizes the grid let below = ui.ctx().data(|m| { - let y = |key: &str| m.get_temp::<f32>(egui::Id::new(key)); + let y = |key: &str| m.get_temp::<f32>(egui::Id::unique(key)); y(CONTENT_BOTTOM).zip(y(GRID_BOTTOM)).map(|(content, grid)| content - grid) }); let grid_h = grid_height(ui.available_height(), below.unwrap_or(DEFAULT_BELOW_GRID), cell + 26.0); @@ -1058,7 +1124,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } }); if !ui.is_sizing_pass() { - ui.ctx().data_mut(|m| m.insert_temp(egui::Id::new(GRID_BOTTOM), grid.inner_rect.bottom())); + ui.ctx().data_mut(|m| m.insert_temp(egui::Id::unique(GRID_BOTTOM), grid.inner_rect.bottom())); } ui.add_space(4.0); // options @@ -1072,7 +1138,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { .map(|summary| summary.display()) .unwrap_or_else(|| crate::i18n::tr_format!("{} item{}", d.sources.len(), if d.sources.len() == 1 { "" } else { "s" })); let r = ui.label(egui::RichText::new(summary).color(t.text_label)).on_hover_text(joined); - register(ui.ctx(), "label:importSource", r.rect); + register(ui, "label:importSource", r.rect); }); ui.label( egui::RichText::new(crate::i18n::tr("Importing scans the source for photos; it doesn't add the folder to Local (use Local → Browse Folder… to work in a folder without importing).")) @@ -1118,7 +1184,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { .color(if d.copy && d.move_files { t.caution } else { t.text_dim }) .small(), ); - register(ui.ctx(), "label:importModeHelp", r.rect); + register(ui, "label:importModeHelp", r.rect); if d.copy { field(ui, if d.move_files { "Move to" } else { "Copy to" }, |ui| { ui.spacing_mut().item_spacing.x = 4.0; @@ -1146,7 +1212,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let combo = crate::widgets::combo_box("import-organize").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { for (k, label) in opts { let r = ui.selectable_label(key == k, crate::i18n::tr(label)); - register(ui.ctx(), format!("button:importOrganize-{k}"), r.rect); + register(ui, format!("button:importOrganize-{k}"), r.rect); if r.clicked() { d.organize = k.to_string(); if k == "custom" && d.folder_template.trim().is_empty() { @@ -1155,15 +1221,16 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } } }); - register(ui.ctx(), "combo:importOrganize", combo.response.rect); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Organize into")); + register(ui, "combo:importOrganize", combo.response.rect); }); if d.organize == "custom" { - let folders_id = egui::Id::new("import-folder-template"); + let folders_id = egui::Id::unique("import-folder-template"); let tags_open = field(ui, "Template", |ui| { ui.spacing_mut().item_spacing.x = 4.0; let w = tag_field_width(ui); let r = ui.add(egui::TextEdit::singleline(&mut d.folder_template).id(folders_id).hint_text(DEFAULT_FOLDER_TEMPLATE).desired_width(w)); - register(ui.ctx(), "field:importFolderTemplate", r.rect); + register(ui, "field:importFolderTemplate", r.rect); tag_toggle(ui, "importFolders") }); if tags_open { @@ -1187,10 +1254,10 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { if !d.move_files { field(ui, "Raw files", |ui| { let r = ui.checkbox(&mut d.dng, crate::i18n::tr("Copy as DNG")); - register(ui.ctx(), "check:importDng", r.rect); + register(ui, "check:importDng", r.rect); }); } - let rename_id = egui::Id::new("import-rename"); + let rename_id = egui::Id::unique("import-rename"); let tags_open = field(ui, "Rename", |ui| { ui.spacing_mut().item_spacing.x = 4.0; let w = tag_field_width(ui); @@ -1200,7 +1267,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { .hint_text(crate::i18n::tr("keep names — or e.g. {date}_{seq:3}")) .desired_width(w), ); - register(ui.ctx(), "field:importRename", r.rect); + register(ui, "field:importRename", r.rect); tag_toggle(ui, "importRename") }); if tags_open { @@ -1210,7 +1277,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { if let Some(example) = example_destination(app, d) { let t = Tokens::get(ui.ctx()); let r = ui.label(egui::RichText::new(crate::i18n::tr_format!("Example: {example}", example = example)).color(t.text_dim)); - register(ui.ctx(), "label:importExample", r.rect); + register(ui, "label:importExample", r.rect); ui.label( egui::RichText::new(crate::i18n::tr("Folders and {date} use the capture time; a photo without one uses today's date.")) .color(t.text_dim) @@ -1226,13 +1293,14 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { _ => "Leave them", }; let mut pick = None; - crate::widgets::combo_box("import-on-deleted").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box("import-on-deleted").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { for (v, label) in [("restore", "Restore them"), ("fresh", "Import as new"), ("", "Leave them")] { if ui.selectable_label(d.on_deleted == v, crate::i18n::tr(label)).clicked() { pick = Some(v); } } }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Recently deleted files")); if let Some(v) = pick { d.set_on_deleted(v); } @@ -1258,12 +1326,12 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { .empty_text(empty) .show_with_choices(ui, |ui| { let none = ui.selectable_label(d.album.is_none() && d.new_album.is_empty(), crate::i18n::tr("None")); - register(ui.ctx(), "importAlbum:none", none.rect); + register(ui, "importAlbum:none", none.rect); if none.clicked() { extra = Some(false); } let new = ui.selectable_label(d.album.is_none() && !d.new_album.is_empty(), crate::i18n::tr("New album…")); - register(ui.ctx(), "importAlbum:new", new.rect); + register(ui, "importAlbum:new", new.rect); if new.clicked() { extra = Some(true); } @@ -1284,7 +1352,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } if d.album.is_none() && !d.new_album.is_empty() { let r = ui.add(egui::TextEdit::singleline(&mut d.new_album).desired_width(f32::INFINITY)); - register(ui.ctx(), "field:importAlbumName", r.rect); + register(ui, "field:importAlbumName", r.rect); } }); }); @@ -1296,7 +1364,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { .find(|p| p.id == d.preset) .map(|p| crate::i18n::builtin_label(&p.name, p.builtin).to_string()) .unwrap_or_else(|| crate::i18n::tr("None").into()); - crate::widgets::combo_box("import-preset").selected_text(cur).height(300.0).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box("import-preset").selected_text(cur).height(300.0).show_ui(ui, |ui| { if ui.selectable_label(d.preset.is_empty(), crate::i18n::tr("None")).clicked() { d.preset.clear(); } @@ -1305,11 +1373,12 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { d.preset = pid; } }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Preset")); }); if !app.session.metadata_presets.is_empty() { field(ui, "Metadata", |ui| { let cur = if d.metadata_preset.is_empty() { crate::i18n::tr("None").to_string() } else { d.metadata_preset.clone() }; - crate::widgets::combo_box("import-metadata").selected_text(cur).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box("import-metadata").selected_text(cur).show_ui(ui, |ui| { if ui.selectable_label(d.metadata_preset.is_empty(), crate::i18n::tr("None")).clicked() { d.metadata_preset.clear(); } @@ -1319,24 +1388,29 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } } }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Metadata preset")); }); } field(ui, "Keywords", |ui| { let r = ui.add(egui::TextEdit::singleline(&mut d.keywords).hint_text(crate::i18n::tr("comma, separated")).desired_width(f32::INFINITY)); - register(ui.ctx(), "field:importKeywords", r.rect); + register(ui, "field:importKeywords", r.rect); }); } +/// Draw one import-dialog candidate cell: register `import:{i}`, request the cell's thumbnail, +/// paint the selection checkbox, and label duplicates, unreadable or trashed files. A click on an +/// importable cell toggles it (Shift extends the range); `rect` is the full cell and the thumbnail +/// uses its width as height. fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog, i: usize, rect: Rect) { let t = Tokens::get(ui.ctx()); let c = d.candidates[i].clone(); let ok = d.importable(i); let img = Rect::from_min_size(rect.min, vec2(rect.width(), rect.width())); - let resp = ui.interact(img, egui::Id::new(("import-cell", i)), Sense::click()); + let resp = ui.interact(img, egui::Id::unique(("import-cell", i)), Sense::click()); crate::widgets::announce(&resp, c.name.clone()); - register(ui.ctx(), format!("import:{i}"), img); + register(ui, format!("import:{i}"), img); let p = ui.painter(); - p.rect_filled(img, 3.0, Color32::from_gray(30)); + p.rect_filled(img, 3.0, t.skeleton); // thumbnail (background job; the grid only asks for the cells in view) let slot = Slot::Import(i as u32); if !app.renderer.textures.contains_key(&slot) @@ -1415,7 +1489,7 @@ pub(crate) fn tag_field_width(ui: &egui::Ui) -> f32 { /// The "Tags" toggle beside a template field (`button:<key>Tags`); returns whether the tag help /// ([`tag_help`]) is open. pub(crate) fn tag_toggle(ui: &mut egui::Ui, key: &str) -> bool { - let id = egui::Id::new((key, "tags-open")); + let id = egui::Id::unique((key, "tags-open")); let mut open = ui.ctx().data(|d| d.get_temp::<bool>(id)).unwrap_or(false); let r = crate::widgets::text_button(ui, &format!("{key}Tags"), crate::i18n::tr("Tags"), open) .on_hover_text(crate::i18n::tr("Show the template tags; click one to insert it")); @@ -1481,7 +1555,7 @@ pub(crate) fn tag_help(ui: &mut egui::Ui, key: &str, text: &mut String, edit_id: crate::i18n::tr_format!("Insert at the cursor (also written {})", tok.aliases.join(", ")) }, ); - register(ui.ctx(), format!("button:{key}Tag-{i}"), r.rect); + register(ui, format!("button:{key}Tag-{i}"), r.rect); if r.clicked() { insert_at_cursor(ui.ctx(), edit_id, text, tok.tag); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1b2517907d..be1a9e879f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -15,12 +15,15 @@ pub mod control; pub mod credits; pub mod date_picker; pub mod docking; +mod drop_overlay; pub mod export_task; mod focus_scan; +mod frame_rate; pub mod headless; pub mod i18n; pub mod icons; pub mod import; +pub mod lightroom_destination; pub mod lightroom_import; pub mod links; pub mod menu_level; @@ -31,6 +34,8 @@ mod model_setup; pub mod panels; pub mod pick; pub mod print_view; +pub mod progress; +pub mod rating; pub mod recheck; pub mod region; pub mod reload; @@ -45,6 +50,7 @@ pub mod tasks; pub mod text_field; pub mod theme; pub mod titlebar; +pub mod updates_ui; pub mod widgets; pub mod window_place; @@ -65,6 +71,10 @@ mod tests_button; #[cfg(test)] mod tests_canvas_keys; #[cfg(test)] +mod tests_canvas_pan; +#[cfg(test)] +mod tests_capture_time; +#[cfg(test)] mod tests_compare; #[cfg(test)] mod tests_copy_paste_dialogs; @@ -81,8 +91,14 @@ mod tests_dialog_fit; #[cfg(test)] mod tests_dialog_primary; #[cfg(test)] +mod tests_dialog_settings; +#[cfg(test)] +mod tests_dialog_tab; +#[cfg(test)] mod tests_dialogs; #[cfg(test)] +mod tests_drop_import; +#[cfg(test)] mod tests_edit_layout; #[cfg(test)] mod tests_empty_library; @@ -101,6 +117,8 @@ mod tests_grid; #[cfg(test)] mod tests_guided_guides; #[cfg(test)] +mod tests_histogram_drag; +#[cfg(test)] mod tests_info_dialogs; #[cfg(test)] mod tests_keymap; @@ -117,10 +135,16 @@ mod tests_keywording; #[cfg(test)] mod tests_labels; #[cfg(test)] +mod tests_launch_library; +#[cfg(test)] mod tests_layout_image; #[cfg(test)] mod tests_library_problem; #[cfg(test)] +mod tests_lifecycle_037; +#[cfg(test)] +mod tests_lightroom_destination; +#[cfg(test)] mod tests_lights_out; #[cfg(test)] mod tests_mask_effects; @@ -131,12 +155,16 @@ mod tests_masking_layout; #[cfg(test)] mod tests_menubar; #[cfg(test)] +mod tests_merge_preview; +#[cfg(test)] mod tests_offline; #[cfg(test)] mod tests_open_lightroom; #[cfg(test)] mod tests_panels; #[cfg(test)] +mod tests_preset_favorites; +#[cfg(test)] mod tests_preset_import; #[cfg(test)] mod tests_preview_limit; @@ -147,8 +175,12 @@ mod tests_profile_menu; #[cfg(test)] mod tests_profiles_layout; #[cfg(test)] +mod tests_progress; +#[cfg(test)] mod tests_quit_unsaved; #[cfg(test)] +mod tests_rating; +#[cfg(test)] mod tests_recheck; #[cfg(test)] mod tests_rename_person; @@ -271,7 +303,15 @@ pub struct Services { pub pick_slideshow_templates: Option<PickFiles>, /// Save dialog for an exported slideshow template (`.json`). pub save_slideshow_template: Option<SaveFile>, + /// Open dialog for print template files (`.lcprint`; File ▸ Print… ▸ Templates ▸ Import…). + pub pick_print_templates: Option<PickFiles>, + /// Save dialog for an exported print template (`.lcprint`). + pub save_print_template: Option<SaveFile>, pub write: Option<WriteFn>, + /// Create-new writer (never replaces an existing path), for screenshots of destinations that + /// did not exist when the request was admitted. Required for such captures: falling back to + /// [`Self::write`] would reopen the admission-to-write race. + pub write_new: Option<WriteFn>, /// Thread-safe writer: with it, UI-started exports run in the background (desktop only). pub write_shared: Option<SharedWrite>, /// PNG encoder (the host links an image encoder; the UI crate stays codec-free). @@ -370,25 +410,79 @@ pub struct LightcraftApp { pub headless_host: bool, /// Warnings to show one at a time (damaged settings files…, issue #103). pub notices: Vec<String>, + pub(crate) updates_rt: updates_ui::Runtime, /// Quitting was stopped to ask first: changes couldn't be saved, or tasks are running. pub quit_prompt: Option<QuitPrompt>, + /// Keyboard/focus/input state for the prompt above, including its one-frame creation barrier. + pub(crate) notice_input: panels::notices::PromptInput, /// Quit Anyway was chosen: the window may close with unsaved changes. pub quit_confirmed: bool, control_rx: Option<Receiver<ControlRequest>>, pending_screenshots: Vec<PendingShot>, + /// Synthetic-input control requests waiting for a fresh layout and delivery (plan §4.5). + pending_gestures: Vec<PendingGesture>, + /// Completed, nondiscarded UI layouts. A gesture admitted before this advanced may resolve. + layout_epoch: u64, screenshot_token: u64, + /// Bytes reserved by admitted, not-yet-drained screenshots (in-flight and completed alike). + shot_bytes: usize, + /// A geometry change since the last logic call: a completed image from an older epoch is + /// stale even when the window has meanwhile been resized back to the issued size. + shot_geometry_epoch: u64, + last_shot_geometry: Option<ShotGeometry>, + /// The texture limit the host last reported (`RawInput::max_texture_side`), retained across + /// passes where the host reports it only once. + max_texture_side: usize, + /// Monotonic app clock (`web_time::Instant`), not the wall clock and not egui's per-pass time: + /// timers must keep advancing while the window is hidden. + clock: AppClock, + /// The language already sent to `Context::set_language`, so a logic pass does not allocate a + /// `String` just to compare it. + accesskit_language: Option<String>, + /// When playback was auto-paused because the window became hidden (`None`: it is running, or + /// the user paused it). On unhide the pause is lifted and the slide keeps its remaining time. + slideshow_hidden_at: Option<f64>, + /// The app (not the user) paused the slideshow because the window was hidden. + slideshow_auto_paused: bool, + /// Files dropped since the last UI pass, consumed exactly once by the UI phase. + dropped_files: Vec<egui::DroppedFileHandle>, + /// A synthetic batch was injected into a pass and has not been consumed by a completed + /// (nondiscarded) UI pass yet: a hidden logic tick must not inject another one. + synthetic_in_flight: bool, + /// Completed, nondiscarded root UI passes; host frames, not layout passes. + ui_passes: u64, + /// Test-only: the library barrier's per-pass decisions, so a first-return test can observe the + /// dedicated shield/discard pass and the following background pass rather than only its input + /// effects (which the global shortcut guard also hides). + #[cfg(test)] + pub(crate) library_passes: Vec<panels::library_problem::LibraryPass>, /// Offscreen context for headless screenshots of the windowed app. shadow: Option<headless::HeadlessView>, /// Synthetic input events (from the control channel) injected one step per frame. pub synthetic: Vec<egui::Event>, + /// A gesture was canceled after its synthetic pointer press reached egui. The next + /// [`Self::raw_input_hook`] cancels that press before egui's next input pass, without a + /// `PointerMoved` (which can start a drag) or a `PointerButton` release (which can become a + /// click). + pointer_cleanup: bool, + /// Files the control channel (`ui.dropFiles`) holds over the window: every frame reports them + /// as hovered, as the OS does while a drag is over the window. + drop_hover: Vec<String>, + /// Files the control channel dropped: delivered as `dropped_files` on the next frame. + drop_pending: Vec<String>, /// The text the UI last put on the clipboard (`ui.inspect` → `copied`). pub copied: Option<String>, /// Native file dialogs up for commands (`pick`): each command runs again when its closes. pub(crate) pending_picks: Vec<pick::Pending>, - /// Modifiers announced for synthetic input (held from a button down to its release). + /// Modifiers announced for synthetic input (held from a button down to its release). This is + /// only the app's synthetic ownership; the real host state is tracked separately in + /// `host_mods`, so a canceled synthetic gesture never clears a physically held key. synthetic_mods: egui::Modifiers, /// Clear `synthetic_mods` on the next frame. synthetic_mods_release: bool, + /// The host's last reported physical modifier state (`ModifiersChanged`), restored after a + /// synthetic gesture releases instead of unconditionally announcing `NONE`. + host_mods: egui::Modifiers, styled: bool, /// The language the installed fonts were built for: the CJK fallback order follows the UI /// language's script, so switching language reinstalls them. @@ -404,8 +498,14 @@ pub struct LightcraftApp { /// drawn last (`ui.inspect` → `scroll`). pub grid_scroll: Option<f32>, pub film_scroll: Option<f32>, - /// Widget registry from the last frame (automation ids → rects). + /// Widget registry from the last completed, nondiscarded frame (automation ids → rects). pub widgets: Vec<(String, egui::Rect)>, + /// Egui hit owners for [`Self::widgets`] from the same completed pass. A press is delivered + /// only when this id still owns egui's pointer hit (see `control::widget_target_visible`). + pub widget_hits: Vec<(String, widgets::WidgetHit)>, + /// Registry collected by the pass being laid out, published only if that pass completes. + next_widgets: Vec<(String, egui::Rect)>, + next_widget_hits: Vec<(String, widgets::WidgetHit)>, /// In-progress on-canvas gesture (brush stroke points, gradient drag…). pub gesture: Option<panels::detail::Gesture>, /// The brush stroke being painted, as drawn on the photo until it's committed (issue #517). @@ -450,6 +550,8 @@ pub struct LightcraftApp { pub lightroom_last: Option<Value>, /// A completed import result waiting for another modal dialog to close. pub(crate) lightroom_result: Option<state::Dialog>, + /// The import review of a finished scan, waiting for another dialog to close. + pub(crate) review_pending: Option<state::Dialog>, /// The library generation the window title and the recent list were last updated for. pub shown_library: Option<u64>, /// A background export in progress. @@ -483,11 +585,21 @@ pub struct LightcraftApp { /// The library failed to open at launch: the blocking window, then the temporary-session /// banner (issue #100). Cleared once a library opens. pub library_problem: Option<panels::library_problem::LibraryProblem>, + /// First-frame focus/input state for a newly shown blocking library window. + pub(crate) library_window_input: panels::library_problem::WindowBarrier, + /// Alt/Option held as the window first appears offers the recent libraries once (issue + /// #1290); the desktop host arms it when nothing chose the library already. + pub alt_asks_for_library: bool, + /// Whether each recent library can be opened, answered by a worker (issue #1290): the launch + /// list and File ▸ Open Recent Library never look at a folder on the UI thread. + pub recent_checks: panels::library_problem::RecentChecks, /// The activity stack shows every task, not just the first few ("+N more" was clicked). pub activity_expanded: bool, } impl LightcraftApp { + /// Build the app with default UI, renderer, cache and control state, and move AI segmentation + /// to a worker so frames apply results instead of waiting. pub fn new(mut session: Session, services: Services) -> Self { // AI mask requests run on the model's worker; frames apply their results (never wait) session.segmenter.background = true; @@ -505,17 +617,38 @@ impl LightcraftApp { text_focus: false, headless_host: false, notices: vec![], + updates_rt: Default::default(), quit_prompt: None, + notice_input: Default::default(), quit_confirmed: false, control_rx: None, pending_screenshots: vec![], + pending_gestures: vec![], + layout_epoch: 0, screenshot_token: 0, + shot_bytes: 0, + shot_geometry_epoch: 0, + last_shot_geometry: None, + max_texture_side: MAX_TEXTURE_SIDE, + clock: AppClock::new(), + accesskit_language: None, + slideshow_hidden_at: None, + slideshow_auto_paused: false, + dropped_files: vec![], + synthetic_in_flight: false, + ui_passes: 0, + #[cfg(test)] + library_passes: vec![], shadow: None, synthetic: vec![], + pointer_cleanup: false, + drop_hover: vec![], + drop_pending: vec![], copied: None, pending_picks: vec![], synthetic_mods: egui::Modifiers::NONE, synthetic_mods_release: false, + host_mods: egui::Modifiers::NONE, styled: false, font_language: i18n::Locale::En, chinese_font: None, @@ -526,6 +659,9 @@ impl LightcraftApp { grid_scroll: None, film_scroll: None, widgets: vec![], + widget_hits: vec![], + next_widgets: vec![], + next_widget_hits: vec![], gesture: None, brush_live: None, loupe_shown: None, @@ -547,6 +683,7 @@ impl LightcraftApp { lightroom: None, lightroom_last: None, lightroom_result: None, + review_pending: None, shown_library: None, export: None, tasks: Default::default(), @@ -562,6 +699,9 @@ impl LightcraftApp { screen_profile: None, screen_profile_read: None, library_problem: None, + library_window_input: Default::default(), + alt_asks_for_library: false, + recent_checks: Default::default(), activity_expanded: false, model_setup: Default::default(), } @@ -575,6 +715,8 @@ impl LightcraftApp { self } + /// Attach the control-channel receiver and keep CPU copies of photo textures, which headless + /// screenshots need; returns the app for chaining. pub fn with_control(mut self, rx: Receiver<ControlRequest>) -> Self { self.control_rx = Some(rx); // keep CPU copies of photo textures so `ui.screenshot {"headless": true}` can draw them @@ -582,6 +724,110 @@ impl LightcraftApp { self } + /// Seconds on the app's monotonic clock. Every timer that must advance while the window is + /// hidden (imports, autosave, playback, toasts, captures) uses this, never `i.time`. + pub fn tick_now(&self) -> f64 { + self.clock.now() + } + + /// The app clock in milliseconds, for control deadlines and timers. + fn tick_now_ms(&self) -> f64 { + self.clock.now() * 1000.0 + } + + /// The immutable identity a capture is bound to: the library generation. It changes when a + /// different library is opened, not on every edit, import batch or keyword op (`catalog.revision` + /// bumps on all of those), so a screenshot during interactive editing still belongs to the + /// document the user asked for. + fn shot_document_generation(&self) -> u64 { + self.session.library_generation() + } + + /// Give a headless driver its simulated time (`None` returns to the monotonic host clock). + pub fn set_simulated_clock(&mut self, seconds: Option<f64>) { + self.clock.simulated = seconds.filter(|s| s.is_finite() && *s >= 0.0); + } + + /// The window's current surface geometry as native points plus native pixels per point. + /// `run_logic` refreshes `input.viewports`, so this is fresh even while the UI is not laid out; + /// without one, the last laid-out content rect is used. + fn shot_geometry(&self, ctx: &egui::Context) -> ShotGeometry { + // Both `viewport.inner_rect` and the content rect are in egui points, and `pixels_per_point` + // already includes the UI zoom (egui-winit divides by the zoomed ppp). Multiplying by the + // zoom again would reserve a surface that is too small, so the zoom is only tracked as a + // change signal. + let zoom = ctx.zoom_factor(); + let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }; + let pixels_per_point = ctx.input(|i| i.pixels_per_point()); + let viewport = ctx.input(|i| { + i.viewport().inner_rect.filter(|r| r.width() > 0.0 && r.height() > 0.0).map_or_else(|| i.content_rect().size(), |inner| inner.size()) + }); + ShotGeometry { viewport, pixels_per_point, zoom, epoch: self.shot_geometry_epoch } + } + + /// Track geometry changes as a generation. Called once per logic tick from the refreshed + /// viewport information, so a hidden window still notices a resize. + fn note_shot_geometry(&mut self, ctx: &egui::Context) { + let mut now = self.shot_geometry(ctx); + if let Some(last) = self.last_shot_geometry + && (last.viewport != now.viewport || last.pixels_per_point != now.pixels_per_point || last.zoom != now.zoom) + { + self.shot_geometry_epoch = self.shot_geometry_epoch.wrapping_add(1); + now.epoch = self.shot_geometry_epoch; + } + self.last_shot_geometry = Some(now); + } + + /// The texture limit the host reported (16 384 unless it said otherwise). + fn max_texture_side(&self) -> usize { + self.max_texture_side + } + + /// Retain the host's `RawInput::max_texture_side`. Hosts (egui-winit, `Headless`) report it + /// only when it changes, so keep the last value instead of assuming 16 384. + fn note_max_texture_side(&mut self, ctx: &egui::Context) { + if let Some(limit) = ctx.input(|i| i.raw.max_texture_side) + && limit > 0 + { + self.max_texture_side = limit; + } + } + + /// Reserve a new image's `bytes` against the aggregate screenshot budget, or report why not. + fn reserve_shot_bytes(&mut self, bytes: usize) -> Result<(), String> { + if bytes > MAX_SHOT_BYTES { + return Err(format!("ui.screenshot: {bytes} bytes is over the {MAX_SHOT_BYTES}-byte per-image limit")); + } + let total = self.shot_bytes.checked_add(bytes).ok_or("ui.screenshot: byte reservation overflow")?; + if total > MAX_SHOT_TOTAL_BYTES { + return Err(format!("ui.screenshot: {total} bytes reserved is over the {MAX_SHOT_TOTAL_BYTES}-byte limit")); + } + self.shot_bytes = total; + Ok(()) + } + + /// A surface that grew after admission (a stale `content_rect` on Wayland, a resize between + /// issue and completion): bound the *new image* against the per-image limit, then reserve only + /// the growth against the aggregate. The old per-image check would compare the delta to the + /// per-image cap and name the delta as if it were the image. + fn grow_shot_reservation(&mut self, current_reserved: usize, image_bytes: usize) -> Result<(), String> { + if image_bytes > MAX_SHOT_BYTES { + return Err(format!("ui.screenshot: {image_bytes} bytes is over the {MAX_SHOT_BYTES}-byte per-image limit")); + } + let extra = image_bytes.saturating_sub(current_reserved); + let total = self.shot_bytes.checked_add(extra).ok_or("ui.screenshot: byte reservation overflow")?; + if total > MAX_SHOT_TOTAL_BYTES { + return Err(format!("ui.screenshot: {total} bytes reserved is over the {MAX_SHOT_TOTAL_BYTES}-byte limit")); + } + self.shot_bytes = total; + Ok(()) + } + + /// Release a reservation; never let an accounting bug underflow `usize`. + fn release_shot_bytes(&mut self, bytes: usize) { + self.shot_bytes = self.shot_bytes.saturating_sub(bytes); + } + /// The open person page, the way back to it, and the photo it was opened from follow a rename. fn follow_renamed_person(&mut self, from: &str, to: &str) { let same = |n: &str| n.trim().to_lowercase() == from.trim().to_lowercase(); @@ -635,6 +881,10 @@ impl LightcraftApp { .map(|d| d.crop.aspect.map_or(serde_json::json!("free"), |(w, h)| serde_json::json!([w as f64 / 100.0, h as f64 / 100.0]))) }; } + if r.is_ok() && id == "library.toggleFilters" { + // the search field shows the text filter: empty while the filters are off, back with them + self.ui.search = self.session.filter.text.clone(); + } if r.is_ok() && id == "library.clearFilter" { // the search field shows the text filter: cleared from anywhere (the loupe's pill, the // menu), it must not keep a search that no longer applies (issue #1648) @@ -655,13 +905,12 @@ impl LightcraftApp { // be invisible once the activity stack is gone. Never show success on error. let completed = match id { "library.compact" => Some(format!("✓ {}", i18n::tr("Optimize Library"))), - "library.clearPreviews" => Some(format!("✓ {}", i18n::tr("Clear Preview Cache"))), + "library.clearPreviews" => Some(format!("✓ {}", i18n::tr("Discard Preview Cache"))), "develop.autoSync" => Some(format!("{}: {}", i18n::tr("Auto Sync"), i18n::tr(if self.session.auto_sync { "On" } else { "Off" }))), _ => None, }; if let Some(message) = completed { - // Menu clicks can arrive before the next frame updates last_time. - let now = self.tasks.repaint.as_ref().map(|ctx| ctx.input(|i| i.time)).unwrap_or(self.last_time); + let now = self.tick_now(); self.ui.toast = Some((message, now + TOAST_SECONDS, None)); } } @@ -675,8 +924,7 @@ impl LightcraftApp { } None => i18n::tr("Color label cleared").into(), }; - // Native menu clicks can arrive before logic() updates last_time after an idle gap. - let now = self.tasks.repaint.as_ref().map(|ctx| ctx.input(|i| i.time)).unwrap_or(self.last_time); + let now = self.tick_now(); self.ui.toast = Some((text, now + TOAST_SECONDS, label)); } match &r { @@ -746,10 +994,34 @@ impl LightcraftApp { Ok(()) } - /// Show a transient toast at the bottom of the canvas (like the reference app's HUD). - /// Advance a running slideshow. - fn slideshow_tick(&mut self, ctx: &egui::Context) { - panels::slideshow::tick(self, ctx); + /// Advance a running slideshow, but not while the window is hidden: in 0.36 `i.time` froze + /// there, and a minimized show must not keep waking the event loop or requesting full-size + /// slide renders overnight. Playback is auto-paused on hide and resumed on unhide with the + /// slide's remaining time preserved. + fn slideshow_tick(&mut self, ctx: &egui::Context, now: f64) { + let hidden = ctx.input(|i| i.viewport().visible() == Some(false)); + let Some(run) = self.ui.slideshow.as_mut() else { + self.slideshow_hidden_at = None; + self.slideshow_auto_paused = false; + return; + }; + if hidden { + if self.slideshow_hidden_at.is_none() { + self.slideshow_hidden_at = Some(now); + if !run.play.is_paused() { + run.play.toggle_pause(now); + self.slideshow_auto_paused = true; + } + } + return; + } + if self.slideshow_hidden_at.take().is_some() && self.slideshow_auto_paused { + self.slideshow_auto_paused = false; + if run.play.is_paused() { + run.play.toggle_pause(now); + } + } + panels::slideshow::tick(self, ctx, now); } /// Announce the end of a Build Previews run. @@ -787,7 +1059,7 @@ impl LightcraftApp { match (unsaved, self.ui.unsaved_seen) { (Some((n, e)), false) => { self.ui.unsaved_seen = true; - let t = ctx.input(|i| i.time); + let t = self.tick_now(); self.ui.toast = Some(( crate::i18n::tr_format!( "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry", @@ -812,9 +1084,21 @@ impl LightcraftApp { self.toast_for(ctx, text, TOAST_SECONDS); } + /// Auto straighten (the crop panel's Auto, a double-click with the Straighten tool), saying so + /// when it finds nothing to level by instead of leaving the photo as it is without a word. + pub fn auto_straighten(&mut self, ctx: &egui::Context) { + match self.run("crop.autoStraighten", serde_json::json!({})) { + Ok(r) if r.get("changed").and_then(Value::as_bool) == Some(false) => { + self.toast(ctx, crate::i18n::tr("No horizon or vertical lines to level by")); + } + Ok(_) => {} + Err(e) => self.toast(ctx, e), + } + } + /// A toast that stays `secs` seconds (messages that say where to look or what to do next). - pub fn toast_for(&mut self, ctx: &egui::Context, text: impl Into<String>, secs: f64) { - let t = ctx.input(|i| i.time); + pub fn toast_for(&mut self, _ctx: &egui::Context, text: impl Into<String>, secs: f64) { + let t = self.tick_now(); self.ui.toast = Some((text.into(), t + secs, None)); } @@ -833,9 +1117,8 @@ impl LightcraftApp { /// AI masks: apply finished background requests (clicks, descriptions, detail passes) and /// show their errors; start a zoomed-in detail pass once the clicking stops /// (`ui.detail_due`); watch the model download. Never waits for the model. - fn ai_mask_detail(&mut self, ctx: &egui::Context) { + fn ai_mask_detail(&mut self, ctx: &egui::Context, now: f64) { let polled = self.session.segment_poll(); - let now = ctx.input(|i| i.time); if polled.changed { ctx.request_repaint(); } @@ -901,11 +1184,14 @@ impl LightcraftApp { } /// A toast for an error the user has to read and act on (stays 6 s). - pub fn toast_error(&mut self, ctx: &egui::Context, text: impl Into<String>) { - let t = ctx.input(|i| i.time); + pub fn toast_error(&mut self, _ctx: &egui::Context, text: impl Into<String>) { + let t = self.tick_now(); self.ui.toast = Some((text.into(), t + 6.0, None)); } + /// Take the control receiver for this frame, run every queued request whose sender still + /// wants it, and reply directly or admit its screenshot/gesture to a later completed pass. + /// Requests abandoned by their sender are skipped rather than executed late. fn drain_control(&mut self, ctx: &egui::Context) { let Some(rx) = self.control_rx.take() else { return }; while let Ok(req) = rx.try_recv() { @@ -919,68 +1205,540 @@ impl LightcraftApp { control::Outcome::Done(v) => { let _ = reply.send(v); } - control::Outcome::Screenshot { path, headless } => { - self.screenshot_token += 1; - let now = now_ms(); - self.pending_screenshots.push(PendingShot { - token: self.screenshot_token, - path, - reply, - headless: headless && !self.headless_host, - not_before: now + 120.0, - deadline: now + SCREENSHOT_SETTLE_MS, - frames: 0, - sent_at: None, - }); + control::Outcome::Screenshot { target, headless } => { + if let Err(error) = self.admit_shot(ctx, target, headless, reply.clone()) { + let _ = reply.send(serde_json::json!({"ok": false, "error": error})); + } + } + control::Outcome::Gesture { method, params } => { + if let Err(error) = self.admit_gesture(ctx, method, params, reply.clone()) { + let _ = reply.send(serde_json::json!({"ok": false, "error": error})); + } } } } self.control_rx = Some(rx); } - /// Advance pending screenshots: wait (≥ 3 frames, ≥ 120 ms) until no renders are in flight - /// (or a timeout), then capture — via the host's compositor, or headlessly - /// ([`Self::headless_screenshot`]) when asked or when the compositor delivers nothing. + /// The navigation/document/modal/panel state that decides what an automation id means. + fn gesture_frame(&self) -> GestureFrame { + GestureFrame { + view: self.ui.view, + active: self.session.active(), + library: self.session.library_generation(), + dialog: self.ui.dialog.as_ref().map(std::mem::discriminant), + left_panel: self.ui.left_panel, + right: self.ui.right, + presets: self.ui.presets, + filmstrip: self.ui.filmstrip, + } + } + + /// Queue a synthetic-input request. Nothing is answered and no event is queued until a + /// completed layout newer than this admission exists (see [`Self::resolve_pending_gestures`]). + fn admit_gesture(&mut self, ctx: &egui::Context, method: String, params: Value, reply: Sender<ControlResponse>) -> Result<(), String> { + if self.pending_gestures.len() >= MAX_PENDING_GESTURES { + return Err(format!("{}: {MAX_PENDING_GESTURES} control gestures are already pending", method)); + } + let now = self.tick_now_ms(); + self.pending_gestures.push(PendingGesture { + method, + params, + reply, + admitted_epoch: self.layout_epoch, + frame: self.gesture_frame(), + deadline_ms: now + GESTURE_TIMEOUT_MS, + resolved_pass: None, + remaining_events: 0, + started: false, + target: None, + pressed: None, + result: Value::Null, + }); + ctx.request_repaint(); + Ok(()) + } + + /// Resolve one queued gesture against the fresh widgets/image rect of the pass that just + /// completed. A changed view/document/dialog/panel state cancels instead of retargeting. + fn resolve_pending_gestures(&mut self, ctx: &egui::Context) { + if self.pending_gestures.is_empty() { + return; + } + let now = self.tick_now_ms(); + let frame = self.gesture_frame(); + let epoch = self.layout_epoch; + let mut gestures = std::mem::take(&mut self.pending_gestures); + let mut keep = Vec::with_capacity(gestures.len()); + for mut gesture in gestures.drain(..) { + if gesture.resolved_pass.is_some() { + // Already handed to the delivery queue; `reply_delivered_gestures` (or + // `expire_gestures`) owns its deadline and must remove its unsent events too. + keep.push(gesture); + continue; + } + if now > gesture.deadline_ms { + // Only this request failed to get a fresh layout. A later gesture has its own + // deadline and must not be canceled with it. + let _ = + gesture.reply.send(serde_json::json!({"ok": false, "error": format!("{} timed out before the UI consumed it", gesture.method)})); + continue; + } + if epoch <= gesture.admitted_epoch { + keep.push(gesture); + continue; + } + if gesture.frame != frame { + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} canceled: the view, document, dialog or panel layout changed before a fresh layout", gesture.method), + })); + continue; + } + let before = self.synthetic.len(); + match control::gesture_events(self, ctx, &gesture.method, &gesture.params) { + Ok(outcome) => { + gesture.target = outcome.target; + gesture.result = outcome.result; + gesture.resolved_pass = Some(self.ui_passes); + gesture.remaining_events = self.synthetic.len().saturating_sub(before); + gesture.started = gesture.remaining_events == 0; + keep.push(gesture); + } + Err(error) => { + let _ = gesture.reply.send(serde_json::json!({"ok": false, "error": error})); + } + } + } + self.pending_gestures = keep; + } + + /// Answer gestures whose last synthetic event a completed, nondiscarded UI pass consumed. + /// A zero-event action waits for one completed pass after resolution. + /// + /// Delivery does not compare the frame again: the gesture's own event may legitimately change + /// the view, document, dialog or panel (a click that opens a dialog, a key that starts Compare), + /// so a second snapshot would cancel exactly the input that did its job. Freshness is checked + /// before resolution ([`Self::resolve_pending_gestures`]) and again immediately before the + /// batch is injected ([`Self::drop_gestures_stale_before_injection`]). + fn reply_delivered_gestures(&mut self) { + if self.pending_gestures.is_empty() { + return; + } + let now = self.tick_now_ms(); + // Cancel only the gestures that actually stalled: their unsent events are at the front of + // the queue, and gestures queued behind them are independent input that must survive. + let mut i = 0; + while i < self.pending_gestures.len() { + if self.pending_gestures[i].resolved_pass.is_none() || now <= self.pending_gestures[i].deadline_ms { + i += 1; + continue; + } + let at_head = self.head_gesture() == Some(i); + let gesture = self.pending_gestures.remove(i); + self.cancel_gesture_events(&gesture, at_head); + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} timed out before the UI consumed its last event", gesture.method), + })); + } + if !self.synthetic.is_empty() || self.synthetic_in_flight { + return; + } + let mut gestures = std::mem::take(&mut self.pending_gestures); + let mut keep = Vec::with_capacity(gestures.len()); + for mut gesture in gestures.drain(..) { + let Some(resolved) = gesture.resolved_pass else { + keep.push(gesture); + continue; + }; + if self.ui_passes <= resolved { + keep.push(gesture); + continue; + } + if gesture.remaining_events > 0 { + // A defensive queue reset (a non-head gesture owned unsent events) dropped this + // batch. It must not become an `ok: true` for input no panel ever saw. + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} canceled: its queued input was dropped before delivery", gesture.method), + })); + continue; + } + let result = std::mem::take(&mut gesture.result); + let _ = gesture.reply.send(serde_json::json!({"ok": true, "result": result})); + } + self.pending_gestures = keep; + } + + /// The gesture whose events sit at the head of the synthetic queue. + fn head_gesture(&self) -> Option<usize> { + self.pending_gestures.iter().position(|gesture| gesture.resolved_pass.is_some() && gesture.remaining_events > 0) + } + + /// Fail resolved gestures whose view/document/dialog/panel snapshot changed before their + /// first synthetic batch reached the next completed pass. A hidden logic tick runs between + /// passes and may change what an automation id or a photo click means; fail closed instead of + /// delivering it against the new state. + /// + /// A widget gesture also has to keep aiming at the requested widget. egui attributes a click + /// to the widget under the press point in the *previous completed pass*, while the control + /// batch spans several host frames (a move, then press, then release). Recheck the target + /// before the first event and before every press; if it moved or disappeared, cancel this + /// gesture with an error instead of clicking whatever is now at those coordinates. + /// + /// Only the gesture at the head of the queue is checked, and later batches of the same gesture + /// may see its own partial effect (the first click of a double click selects the photo the + /// second one opens). A second, concurrently queued gesture is checked when its events reach + /// the head. + fn drop_gestures_stale_before_injection(&mut self, ctx: &egui::Context) -> bool { + let Some(head) = self.head_gesture() else { return false }; + let first_batch = !self.pending_gestures[head].started; + if first_batch && self.pending_gestures[head].frame != self.gesture_frame() { + let gestures = std::mem::take(&mut self.pending_gestures); + for gesture in gestures { + if gesture.resolved_pass.is_none() { + self.pending_gestures.push(gesture); + } else { + if gesture.pressed.is_some() { + self.queue_pointer_cleanup(); + } + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} canceled: the view, document, dialog or panel layout changed before delivery", gesture.method), + })); + } + } + self.synthetic.clear(); + return true; + } + let Some(target) = self.pending_gestures[head].target.clone() else { return false }; + let press_next = matches!(self.synthetic.first(), Some(egui::Event::PointerButton { pressed: true, .. })); + let release_next = matches!(self.synthetic.first(), Some(egui::Event::PointerButton { pressed: false, .. })); + // A drag legitimately ends outside the widget it started on; only a click must still find + // its target at the release that egui attributes the click to. A hover must still find a + // visible widget for its single pointer move. + let check_release = release_next && target.check_release; + let check_visible = first_batch && target.check_visible; + if !first_batch && !press_next && !check_release && !check_visible { + return false; + } + let latest = control::widget_rect(self, &target.id); + let latest_hit = control::widget_hit(self, &target.id); + // A press must go to the widget that owns the point. A click's release must too (a drag + // may legitimately end outside the widget it started on), so an overlay that appears + // between press and release cancels the click before the release rather than activating it. + // A hover's single move must also still find the widget visible: the documented contract + // rejects a clipped or newly covered target instead of moving the pointer at stale coordinates. + let must_own = press_next || (release_next && target.check_release) || check_visible; + // A quit prompt or settings notice owns input even before its Foreground areas have + // settled (egui's first layout pass is non-interactable), and even when a control request + // is resolved against the registry of that first pass. Only the prompt's own buttons pass. + let notice_ok = !must_own || crate::panels::notices::allows_target(self, latest_hit); + let still_aimed = latest.is_some_and(|rect| { + // A changed widget cancels any gesture before its first event. Owned presses, click + // releases and hovers must also be inside egui's clipped, visible part and be the + // topmost widget hit: a target scrolled out of its panel, or one under a non-modal + // overlay, must not be pressed or hovered at stale coordinates. + let geometry_ok = rect == target.rect || rect.contains(target.at); + geometry_ok && notice_ok && (!must_own || control::widget_target_visible(ctx, latest_hit, target.at)) + }); + if still_aimed { + return false; + } + let outside_registered = !target.rect.contains(target.at); + let reason = match latest { + None => "disappeared", + Some(rect) if !(rect == target.rect || rect.contains(target.at)) => "moved", + Some(_) if outside_registered => "has no visible interaction area at the requested point", + Some(_) => "is no longer visible", + }; + let phase = if first_batch { + "its first event" + } else if check_release { + "its release" + } else { + "its press" + }; + // Only this gesture's unsent events are removed: they are at the front of the queue, and + // gestures resolved after it are checked in turn when they reach the head. Failing the + // whole click would also discard unrelated input. + let gesture = self.pending_gestures.remove(head); + self.cancel_gesture_events(&gesture, true); + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} canceled: widget `{}` {reason} before {phase}; nothing was retargeted", gesture.method, target.id), + })); + true + } + + /// Remove a canceled gesture's unsent events from the front of the queue and release a pointer + /// button it left down. Callers cancel in queue order, so the events removed are exactly this + /// gesture's unsent prefix; a later gesture's events stay queued. + fn cancel_gesture_events(&mut self, gesture: &PendingGesture, at_head: bool) { + if at_head { + let unsent = gesture.remaining_events.min(self.synthetic.len()); + self.synthetic.drain(..unsent); + } else if gesture.remaining_events > 0 { + // The queue order makes only the head own unsent events. If a caller ever breaks that + // invariant, fail safe: stale synthetic input must not reach an unrelated widget, even + // at the cost of dropping the rest of this batch instead of panicking or guessing a + // prefix. `reply_delivered_gestures` fails any gesture whose events disappeared this + // way instead of reporting a false success. + log::warn!("canceled non-head gesture still owned {} unsent synthetic events; dropping the queue", gesture.remaining_events); + self.synthetic.clear(); + self.synthetic_in_flight = false; + } + if gesture.pressed.is_some() { + self.queue_pointer_cleanup(); + } + } + + /// Cancel every synthetic gesture that a newly shown prompt or blocking library window makes + /// unsafe. + /// + /// A gesture whose input is still queued must not be delivered under the barrier or later when + /// it is gone. A gesture whose press already reached egui must be released without a click. A + /// gesture that already delivered all its events may still complete its reply: the barrier may + /// well be its own result (e.g. a key that opened the quit prompt). `all` is for a batch already + /// injected this host frame before the barrier was discovered after `raw_input_hook`: the + /// barrier filter drops it before any panel sees it, so even a fully injected gesture must fail + /// rather than report a successful delivery. + fn cancel_gestures_for_barrier(&mut self, all: bool, reason: &str) { + // All not-yet-injected events belong to the queue's head, one gesture at a time. Cancel + // them in order so only that gesture's unsent prefix is removed. + while let Some(head) = self.head_gesture() { + let gesture = self.pending_gestures.remove(head); + self.cancel_gesture_events(&gesture, true); + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} canceled: {reason} before its input was delivered", gesture.method), + })); + } + let mut i = 0; + while i < self.pending_gestures.len() { + if all || self.pending_gestures[i].resolved_pass.is_none() || self.pending_gestures[i].pressed.is_some() { + let gesture = self.pending_gestures.remove(i); + self.cancel_gesture_events(&gesture, false); + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} canceled: {reason} before its input was delivered", gesture.method), + })); + } else { + i += 1; + } + } + } + + /// Cancel a press that reached egui without making it a click or starting a drag. The reset + /// itself happens before egui's next input pass in [`Self::raw_input_hook`], where replacing + /// the pointer state and stopping the drag is safe (the same approach as the sibling + /// SoundCraft/VectorCraft apps). No pointer movement is injected: moving beyond + /// `max_click_dist` suppresses a click but can also start a drag on a slider or curve. + fn queue_pointer_cleanup(&mut self) { + self.pointer_cleanup = true; + } + + /// Apply a queued pointer cancellation before egui processes the next input pass. + fn apply_pointer_cleanup(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + if !std::mem::take(&mut self.pointer_cleanup) { + return; + } + ctx.input_mut(|input| input.pointer = egui::PointerState::default()); + ctx.stop_dragging(); + if self.synthetic_mods != egui::Modifiers::NONE { + // The cleanup removes only the app's synthetic modifiers, never a real host change. + // A host `ModifiersChanged` in this same raw batch is already authoritative and was + // recorded before this call; otherwise restore the host's last known state (which may + // be a physically held Shift), rather than clearing it unconditionally with NONE. + let host_changed = raw.events.iter().any(|event| matches!(event, egui::Event::ModifiersChanged(_))); + self.synthetic_mods = egui::Modifiers::NONE; + if !host_changed { + raw.events.push(egui::Event::ModifiersChanged(self.host_mods)); + } + } + self.synthetic_mods_release = false; + } + + /// Fail pending gestures at the monotonic deadline even when no UI pass runs (a hidden window + /// whose paint request the host ignored). `logic` calls this every tick. + fn expire_gestures(&mut self) { + if self.pending_gestures.is_empty() { + return; + } + let now = self.tick_now_ms(); + if !self.pending_gestures.iter().any(|gesture| now > gesture.deadline_ms) { + return; + } + // Cancel exactly the stalled requests, in queue order, so a later gesture's input survives. + let mut i = 0; + while i < self.pending_gestures.len() { + if now <= self.pending_gestures[i].deadline_ms { + i += 1; + continue; + } + let at_head = self.head_gesture() == Some(i); + let gesture = self.pending_gestures.remove(i); + self.cancel_gesture_events(&gesture, at_head); + let _ = gesture.reply.send(serde_json::json!({"ok": false, "error": format!("{} timed out before the UI consumed it", gesture.method)})); + } + } + + /// Admit a `ui.screenshot` request against the bounded capture budget. Nothing is written and + /// no capture is issued here: [`Self::issue_screenshots`] waits for a settled, nondiscarded UI + /// pass and a fresh geometry generation. + fn admit_shot( + &mut self, + ctx: &egui::Context, + target: Option<lightcraft_engine::originals::WriteTarget>, + headless: bool, + reply: Sender<ControlResponse>, + ) -> Result<(), String> { + if self.pending_screenshots.len() >= MAX_PENDING_SHOTS { + return Err(format!("ui.screenshot: {MAX_PENDING_SHOTS} requests are already pending; wait for a reply first")); + } + let geometry = self.last_shot_geometry.unwrap_or_else(|| self.shot_geometry(ctx)); + let bytes = geometry.bytes(self.max_texture_side()).ok_or_else(|| geometry.rejection(self.max_texture_side()))?; + self.reserve_shot_bytes(bytes)?; + self.screenshot_token = self.screenshot_token.wrapping_add(1); + let now = self.tick_now_ms(); + self.pending_screenshots.push(PendingShot { + token: self.screenshot_token, + target, + reply, + headless: headless && !self.headless_host, + admitted_passes: self.ui_passes, + not_before_ms: now + SHOT_SETTLE_MS, + // Capture the current settled frame at this instant even if renders are still in flight + // (0.36 did this at its three-second deadline, so automation never got an error instead + // of an image while a slider/import kept the renderer busy). + force_ms: now + SHOT_FORCE_BUSY_MS, + // Settle + forced capture + compositor fallback + the headless settle, all from admission. + deadline_ms: now + SHOT_SETTLE_MS + SCREENSHOT_SETTLE_MS + SCREENSHOT_FALLBACK_MS + SCREENSHOT_SETTLE_MS, + sent_at_ms: None, + reserved: bytes, + slot: None, + issued: None, + issued_library: self.shot_document_generation(), + }); + ctx.request_repaint(); + Ok(()) + } + + /// Advance pending screenshots: wait (≥ 3 completed UI frames, ≥ 120 ms) until no renders are + /// in flight — or until the forced-capture instant, so sustained rendering cannot turn a + /// request into a timeout — then capture through the compositor's one-shot callback, or + /// headlessly ([`Self::headless_screenshot`]) when asked or when the compositor delivers nothing. fn issue_screenshots(&mut self, ctx: &egui::Context) { if self.pending_screenshots.is_empty() { return; } - let now = now_ms(); + let now = self.tick_now_ms(); let busy = self.renderer.in_flight() > 0 || self.merge.busy(); + let max_side = self.max_texture_side(); + let library = self.shot_document_generation(); + let geometry = self.last_shot_geometry.unwrap_or_else(|| self.shot_geometry(ctx)); let mut shots = std::mem::take(&mut self.pending_screenshots); let mut shadow_ticked = false; - shots.retain_mut(|s| { - if let Some(sent) = s.sent_at { + let mut keep = Vec::with_capacity(shots.len()); + for mut shot in shots.drain(..) { + // Hard deadline from admission: a compositor fallback does not extend it. + if now > shot.deadline_ms { + let _ = shot.reply.send(serde_json::json!({"ok": false, "error": format!("screenshot {} timed out", shot.token)})); + if let Some(slot) = shot.slot.take() { + slot.cancel(); + } + self.release_shot_bytes(shot.reserved); + continue; + } + if let Some(sent) = shot.sent_at_ms { if now - sent < SCREENSHOT_FALLBACK_MS || self.headless_host { - return true; + keep.push(shot); + continue; } // The compositor delivered nothing (display asleep, window occluded): go headless. log::warn!("ui.screenshot: no frame from the compositor after {SCREENSHOT_FALLBACK_MS} ms; rendering headlessly"); - s.sent_at = None; - s.headless = true; - s.deadline = now + SCREENSHOT_SETTLE_MS; + if let Some(slot) = shot.slot.take() { + slot.cancel(); + } + shot.sent_at_ms = None; + shot.issued = None; + shot.headless = true; } - s.frames += 1; - let ready = now >= s.not_before && s.frames >= 3 && (!busy || now > s.deadline); - if s.headless { + // A busy renderer only defers the capture until the forced instant; after that the + // settled frame that exists now is captured (0.36's deadline behavior), never an error. + let ready = shot_ready(now, &shot, busy, self.ui_passes); + if !ready { + keep.push(shot); + continue; + } + if shot.headless { // The shadow frame requests the renders the UI needs, even while the window shows nothing. - let img = if ready || !shadow_ticked { self.headless_screenshot(ctx, ready) } else { None }; + let img = if shadow_ticked { None } else { self.headless_screenshot(ctx, true) }; shadow_ticked = true; if let Some(img) = img { - let _ = s.reply.send(control::save_screenshot(self, &img, s.path.as_deref())); - return false; + let bytes = img.size[0].checked_mul(img.size[1]).and_then(|p| p.checked_mul(std::mem::size_of::<egui::Color32>())); + match bytes { + Some(bytes) if bytes > shot.reserved => { + // A stale/undersized reservation is not a user error: grow it to the + // actual image and encode it when the per-image and aggregate caps allow. + if let Err(error) = self.grow_shot_reservation(shot.reserved, bytes) { + let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error})); + self.release_shot_bytes(shot.reserved); + continue; + } + shot.reserved = bytes; + } + Some(_) => {} + None => { + let reply = serde_json::json!({ + "ok": false, + "error": "ui.screenshot: the rendered image has invalid dimensions", + }); + let _ = shot.reply.send(reply); + self.release_shot_bytes(shot.reserved); + continue; + } + } + let _ = shot.reply.send(control::save_screenshot(self, &img, shot.target.as_ref())); + self.release_shot_bytes(shot.reserved); + continue; } - true - } else { - if ready { - ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(s.token))); - s.sent_at = Some(now); - } - true + keep.push(shot); + continue; } - }); - shots.append(&mut self.pending_screenshots); - self.pending_screenshots = shots; + // The compositor path needs a real, laid-out UI and fresh fonts; a queued request on a + // hidden window is kept alive by RequestPaintWhileHidden from `logic`. + if !self.fonts_ready || self.ui_passes == 0 { + keep.push(shot); + continue; + } + // Revalidate the reservation against the geometry the command is actually bound to. + let Some(bytes) = geometry.bytes(max_side) else { + let _ = shot.reply.send(serde_json::json!({"ok": false, "error": geometry.rejection(max_side)})); + self.release_shot_bytes(shot.reserved); + continue; + }; + if bytes > shot.reserved { + if let Err(error) = self.grow_shot_reservation(shot.reserved, bytes) { + let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error})); + self.release_shot_bytes(shot.reserved); + continue; + } + shot.reserved = bytes; + } + // One slot and one callback per issue; the callback only holds a weak slot and wakes + // the viewport. File writes and replies happen in `collect_screenshots`. + let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES); + ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback)); + log::debug!("ui.screenshot {}: issued at {:?}, {} bytes reserved", shot.token, geometry.viewport, shot.reserved); + shot.slot = Some(slot); + shot.sent_at_ms = Some(now); + shot.issued = Some(geometry); + shot.issued_library = library; + keep.push(shot); + } + self.pending_screenshots = keep; if !self.pending_screenshots.is_empty() { ctx.request_repaint_after(std::time::Duration::from_millis(16)); } @@ -1019,7 +1777,7 @@ impl LightcraftApp { // same scroll offsets, open sections, style… as the window let memory = main.memory(|m| m.clone()); view.ctx.memory_mut(|m| *m = memory); - view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.ui(ui)); + view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.draw_window(ui)); let img = capture.then(|| { let mut tex = self.renderer.cpu_textures(); if let (Some((t, ..)), Some(px)) = (&self.merge.preview, &self.merge.preview_pixels) { @@ -1031,29 +1789,76 @@ impl LightcraftApp { img } - fn collect_screenshots(&mut self, ctx: &egui::Context) { + /// Take each completed capture once, reject stale generations before writing anything, and + /// reply exactly once. A late callback after cancel/drop finds no slot and is inert. + fn collect_screenshots(&mut self, _ctx: &egui::Context) { if self.pending_screenshots.is_empty() { return; } - let events: Vec<_> = ctx.input(|i| { - i.raw - .events - .iter() - .filter_map(|e| match e { - egui::Event::Screenshot { user_data, image, .. } => { - let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::<u64>()).copied()?; - Some((token, image.clone())) + let now = self.tick_now_ms(); + let current = self.last_shot_geometry; + let library = self.shot_document_generation(); + let mut shots = std::mem::take(&mut self.pending_screenshots); + let mut keep = Vec::with_capacity(shots.len()); + for mut shot in shots.drain(..) { + let completed = shot.slot.as_ref().and_then(craft_ui::capture::CaptureSlot::take); + match completed { + Some(Ok(image)) => { + let stale = + shot.issued.is_none_or(|issued| current.is_none_or(|now| now.epoch != issued.epoch)) || shot.issued_library != library; + if stale { + // A resize/DPI/zoom or library change between issue and completion: never + // combine old pixels with new geometry. Retry with a fresh slot. + shot.slot = None; + shot.sent_at_ms = None; + shot.issued = None; + shot.not_before_ms = now + SHOT_SETTLE_MS; + keep.push(shot); + continue; } - _ => None, - }) - .collect() - }); - for (token, image) in events { - if let Some(i) = self.pending_screenshots.iter().position(|s| s.token == token) { - let s = self.pending_screenshots.remove(i); - let _ = s.reply.send(control::save_screenshot(self, &image, s.path.as_deref())); + let pixels = image.size[0].checked_mul(image.size[1]).and_then(|p| p.checked_mul(std::mem::size_of::<egui::Color32>())); + let Some(bytes) = pixels else { + let reply = serde_json::json!({ + "ok": false, + "error": "ui.screenshot: the rendered image has invalid dimensions", + }); + let _ = shot.reply.send(reply); + self.release_shot_bytes(shot.reserved); + continue; + }; + if bytes > shot.reserved { + // Wayland reports no `inner_rect`, so the reservation can be based on a stale + // content rect while the compositor returns the new, larger surface. Treat a + // larger-but-legal image as a stale reservation and grow it; never mix it + // with geometry of another epoch (checked above). + if let Err(error) = self.grow_shot_reservation(shot.reserved, bytes) { + let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error})); + self.release_shot_bytes(shot.reserved); + continue; + } + shot.reserved = bytes; + } + self.release_shot_bytes(shot.reserved); + let _ = shot.reply.send(control::save_screenshot(self, &image, shot.target.as_ref())); + } + Some(Err(error)) => { + let _ = shot.reply.send(serde_json::json!({"ok": false, "error": error.to_string()})); + self.release_shot_bytes(shot.reserved); + } + None => { + if now > shot.deadline_ms { + let _ = shot.reply.send(serde_json::json!({"ok": false, "error": format!("screenshot {} timed out", shot.token)})); + if let Some(slot) = shot.slot.take() { + slot.cancel(); + } + self.release_shot_bytes(shot.reserved); + } else { + keep.push(shot); + } + } } } + self.pending_screenshots = keep; } /// The process is about to end (settings and library are saved by then): make sure nothing is @@ -1073,19 +1878,38 @@ impl LightcraftApp { stopped && idle } - /// Per-frame logic before layout (control channel, renders, shortcuts, drops). + /// Background and queue work. Called before layout on every host pass and, while the window is + /// hidden, from `Context::run_logic`. It may read the refreshed viewport fields only: never + /// `i.time`, events, keys or dropped files. pub fn logic(&mut self, ctx: &egui::Context) { i18n::set_language(self.ui.language); - let t0 = now_ms(); - panels::library_problem::logic(self); - self.logic_inner(ctx); - self.perf.logic_ms = now_ms() - t0; + // The fork's AccessKit root language and bidi runs follow the locale; presentation only. + // Compare against the cached string: `Context::language()` allocates on every call, and + // this runs on every UI pass and every hidden logic tick. + let language = self.ui.language.code(); + if self.accesskit_language.as_deref() != Some(language) { + ctx.set_language(Some(language.to_owned())); + self.accesskit_language = Some(language.to_owned()); + } + let t0 = monotonic_ms(); + self.note_max_texture_side(ctx); + self.note_shot_geometry(ctx); + self.ensure_fonts(ctx); + // Applying the theme belongs to logic: a host that only calls `logic` (and every hidden + // tick) must see an Appearance Mode / system-theme change, and the UI pass that follows + // then draws with the new visuals. `ui` keeps its own call for a settings change made by + // a command during the same pass; it is a no-op when the theme already matches. + self.sync_theme(ctx); + self.logic_background(ctx); + self.perf.logic_ms = monotonic_ms() - t0; } - fn logic_inner(&mut self, ctx: &egui::Context) { + /// Install/refresh fonts once and watch the device and availability caches. Setup, not input. + fn ensure_fonts(&mut self, ctx: &egui::Context) { if !self.styled { theme::install_fonts_with_chinese(ctx, self.chinese_font.as_ref()); theme::apply(ctx); + Self::drop_legacy_panel_state(ctx); // File → Add from Device lists cards scanned in the background: show hot-plugs let repaint = ctx.clone(); lightcraft_engine::devices::on_change(move || repaint.request_repaint()); @@ -1103,25 +1927,32 @@ impl LightcraftApp { } else { self.fonts_ready = true; } - self.sync_theme(ctx); + } + + /// 0.36 stored each `PanelState` under the panel's exact `Id`; 0.37 stores it under + /// `parent_ui.scope_id().with_salt(id_salt)`, so the old entries are unreachable and the + /// panels reset once by simply not finding them. Remove the old keys anyway so egui memory + /// does not retain dead entries (no document, workspace JSON, catalog or XMP data is + /// migrated; nothing above a user's photo edits depends on them). + fn drop_legacy_panel_state(ctx: &egui::Context) { + for salt in ["top_bar", "bottom_bar", "tool_strip", "library-problem-banner"] { + ctx.data_mut(|d| d.remove::<egui::containers::panel::PanelState>(egui::Id::unique(salt))); + } + } + + /// Queues and timers. Each consumed queue is drained once per call; time-gated work uses the + /// monotonic app clock, so a hidden `run_logic` keeps it advancing and a second layout pass is + /// a no-op rather than a duplicate. + fn logic_background(&mut self, ctx: &egui::Context) { panels::notices::logic(self); // closing the window (or Quit) with changes only in memory: retry, else ask first if ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); } - // (once a frame: a pass drawn again after a discard has no input of its own, and still the - // widgets of the pass thrown away, where a request would find them out of place) - if ctx.current_pass_index() == 0 { - let now = ctx.input(|i| i.time); - let dt = now - self.last_time; - if dt > 0.0 { - self.perf.fps = self.perf.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1; - } - self.last_time = now; - self.drain_control(ctx); - } + let now = self.tick_now(); + self.drain_control(ctx); self.apply_settings(ctx); - if !self.synthetic.is_empty() { + if self.queued_input_needs_repaint() { ctx.request_repaint(); } self.renderer.poll(ctx, &mut self.session); @@ -1129,31 +1960,30 @@ impl LightcraftApp { import::poll_scan(self, ctx); sync::poll(self, ctx); sync::poll_run(self, ctx); - import::tick(self, ctx); + // Import commits batches and must not run twice in one host frame. The first layout pass + // and a hidden logic tick both report pass index 0; a second pass reports 1. A wall-clock + // gate cannot express that (a slow discarded first pass would re-run it). + if import_tick_allowed(ctx) { + import::tick(self, ctx); + } lightroom_import::tick(self, ctx); recheck::tick(self); tasks::poll(self, ctx); + updates_ui::tick(self, ctx); self.preview_build_status(ctx); self.save_status(ctx); - self.slideshow_tick(ctx); - panels::faces::pump(self, ctx); - // back from an external editor: pick up the files it saved - let focused = ctx.input(|i| i.focused); - if focused && !self.ui.was_focused && !self.ui.external_edits.is_empty() { - let ids = self.ui.external_edits.clone(); - if let Ok(r) = self.session.execute("photo.reload", &serde_json::json!({"ids": ids})) - && r["reloaded"].as_array().is_some_and(|a| !a.is_empty()) - { - self.toast(ctx, crate::i18n::tr("Updated the edits saved in the external editor")); - } - } - self.ui.was_focused = focused; + self.ai_mask_detail(ctx, now); + self.place_names_outcome(ctx); + self.slideshow_tick(ctx, now); + panels::denoise::pump_background(self, ctx, now); + panels::faces::pump_background(self, ctx, now); + model_setup::pump(self, ctx, now); + focus_scan::pump(self, ctx, now); // auto import: list the watched folder every few seconds (on a worker thread: it may be on // a network share), then import what's new like any import (also on a worker thread) #[cfg(not(target_arch = "wasm32"))] if let Some(folder) = self.session.import_defaults.auto_folder.clone() { const LABEL: &str = "Auto Import"; - let now = ctx.input(|i| i.time); if now - self.ui.auto_import_at >= 3.0 && self.import.is_none() && self.sync_run.is_none() @@ -1190,7 +2020,6 @@ impl LightcraftApp { #[cfg(not(target_arch = "wasm32"))] { if self.session.unsaved_sidecars() > 0 { - let now = ctx.input(|i| i.time); if now - self.ui.sidecar_retry_at >= 10.0 { self.ui.sidecar_retry_at = now; self.session.retry_unsaved_sidecars(); @@ -1223,40 +2052,177 @@ impl LightcraftApp { self.ui.known_cards = None; } self.session.persist_if_dirty(); - panels::denoise::pump(self, ctx); - model_setup::pump(self, ctx); - panels::faces::pump(self, ctx); - focus_scan::pump(self, ctx); + self.expire_gestures(); self.collect_screenshots(ctx); self.issue_screenshots(ctx); - if self.fonts_ready { + self.request_paint_while_hidden(ctx); + } + + /// While hidden, queued captures and an injected gesture step need a real UI pass; a pending + /// screenshot command paints by itself once issued. + fn request_paint_while_hidden(&self, ctx: &egui::Context) { + // `logic` runs per layout pass; one command per host frame is enough. + if ctx.current_pass_index() != 0 { + return; + } + // `ViewportInfo::visible()`: minimized or fully occluded is `Some(false)`; `None` + // (headless, `RawInput::default()`) is normal and must not be treated as hidden. + let hidden = ctx.input(|i| i.viewport().visible() == Some(false)); + if hidden && self.needs_ui_pass_while_hidden() { + ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden); + } + } + + /// A hidden window needs a real UI pass for queued/settling captures, for control gestures + /// that still have to resolve or deliver, and for an injected synthetic step. An already + /// issued screenshot has its own compositor-driven paint and must not request another + /// `RequestPaintWhileHidden`; its fallback and timeout keep running from `logic`. + fn needs_ui_pass_while_hidden(&self) -> bool { + !self.pending_gestures.is_empty() + || self.pointer_cleanup + || self.pending_screenshots.iter().any(|shot| shot.sent_at_ms.is_none()) + || !self.synthetic.is_empty() + || self.synthetic_in_flight + } + + /// Queued synthetic input, including a queued pointer cancellation that is not part of + /// `synthetic`, needs the next visible frame even when an earlier stall left the synthetic + /// queue empty. + fn queued_input_needs_repaint(&self) -> bool { + !self.synthetic.is_empty() || self.pointer_cleanup + } + + /// Input, layout and setup for a known UI phase: at most once per host frame, and never from a + /// hidden logic tick. `current_pass_index() == 0` is the first pass of this `run_ui`; a second + /// pass has empty events. + fn ui_pass(&mut self, ctx: &egui::Context) { + if ctx.current_pass_index() != 0 { + return; + } + // A prompt owns the keyboard and focus. A notice may have been added by this frame's logic + // after `raw_input_hook`; capture its Tab/Enter/Space/Escape and drop everything else + // before any panel, focused control or shortcut reads the input. A new prompt gets a + // shielding pass whose background is not drawn at all (see `draw_window`). + let batch_in_flight = self.synthetic_in_flight; + if panels::notices::prepare_ui_pass(self, ctx) { + self.cancel_gestures_for_barrier(batch_in_flight, "a modal prompt appeared"); + } + panels::library_problem::prepare_ui_pass(self, ctx, batch_in_flight); + let now = self.tick_now(); + // the last pass's time is fine here: this is a UI phase, not a hidden tick + let t = ctx.input(|i| i.time); + let dt = t - self.last_time; + if dt > 0.0 { + self.perf.fps = self.perf.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1; + } + self.last_time = t; + panels::denoise::pump_ui_input(self, ctx, now); + panels::faces::pump_ui_input(self, ctx, now); + // A prompt owns the library too: files dropped while it is up wait in the queue and are + // imported on the first UI pass after it goes away, never behind it. + if !panels::notices::blocks_input(self) { + self.import_dropped_files(ctx); + } + self.check_external_editor(ctx); + // Recent-library checks and launch-list keys read focus/time/keys: they belong to the UI + // phase, not the hidden-capable `logic` tick (plan §4.5 / migration input contract). + panels::library_problem::logic(self, ctx); + if self.fonts_ready && !updates_ui::blocks_input(self) { shortcuts::handle(self, ctx); } + } + + /// Take the host's dropped files, exactly once. The queue is filled by `raw_input_hook`, so a + /// hidden logic tick can never replay the last pass's drop. Web hosts call this in their UI + /// phase (they need `bytes_async`, which is not available on a native file path). + pub fn take_dropped_files(&mut self) -> Vec<egui::DroppedFileHandle> { + std::mem::take(&mut self.dropped_files) + } + + /// Import native drops as presets, face models or photos. + fn import_dropped_files(&mut self, ctx: &egui::Context) { + let dropped = self.take_dropped_files(); + if dropped.is_empty() { + return; + } #[cfg(not(target_arch = "wasm32"))] + self.handle_dropped_files(ctx, dropped); + #[cfg(target_arch = "wasm32")] + let _ = (dropped, ctx); + } + + /// Files dropped on the window: face models open their licence dialog, presets import as + /// presets, photos and folders go to the import review (or straight in, Settings ▸ Import). + #[cfg(not(target_arch = "wasm32"))] + fn handle_dropped_files(&mut self, ctx: &egui::Context, dropped: Vec<egui::DroppedFileHandle>) { + let dropped: Vec<String> = + dropped.iter().map(|f| egui::DroppedFile::path(f.as_ref()).to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect(); + if dropped.is_empty() { + return; + } + // a dialog is on screen: the review would replace it, losing what it holds + if self.ui.dialog.is_some() { + self.toast(ctx, crate::i18n::tr("Close the open dialog, then drop the files again")); + return; + } + let drop = drop_overlay::classify(dropped); + if let Some(model) = drop.models.first() + && let Err(e) = panels::faces::open_dialog(self, model) { - let dropped: Vec<String> = - ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect()); - // preset files import as presets, everything else as photos - // a dropped face model opens its licence dialog; presets and photos as before - let (models, dropped): (Vec<String>, Vec<String>) = dropped.into_iter().partition(|p| is_model_file(p)); - if let Some(model) = models.first() - && let Err(e) = panels::faces::open_dialog(self, model) - { - self.toast(ctx, e); - } - let (presets, photos) = split_presets(dropped); - if !presets.is_empty() { - let _ = self.run("file.importPresets", serde_json::json!({"paths": presets})); - } - // read and added on a worker thread (dropped folders can be large, or on a slow drive) - if !photos.is_empty() { - if self.lightroom.is_some() { - self.toast(ctx, "Finish Lightroom catalog import before adding photos"); - } else if let Err(e) = import::start_paths(self, photos) { - self.toast(ctx, e); - } + self.toast(ctx, e); + } + if !drop.presets.is_empty() { + // presets live in a library: with none open they would go with the session it replaces + if panels::library_problem::holds_drops(self) { + self.toast(ctx, crate::i18n::tr("Open a library first, then drop the presets again")); + } else { + let _ = self.run("file.importPresets", serde_json::json!({"paths": drop.presets})); } } + if drop.photos.is_empty() { + return; + } + // no library open yet (the launch list, a library that failed to open): they wait for one + let Some(photos) = panels::library_problem::hold_dropped(self, ctx, drop.photos) else { return }; + if self.lightroom.is_some() { + self.toast(ctx, crate::i18n::tr("Finish Lightroom catalog import before adding photos")); + return; + } + if import::running(self) { + self.toast(ctx, crate::i18n::tr("An import is running")); + return; + } + let started = if self.ui.settings.import_dropped_directly { + // read and added on a worker thread (dropped folders can be large, or on a slow drive) + import::start_paths(self, photos).map(|_| ()) + } else { + import::open(self, photos).map(|_| ()) + }; + if let Err(e) = started { + self.toast(ctx, e); + } + } + + /// A file dropped by the host, kept for the next UI pass (web hosts consume their own queue). + fn queue_dropped_files(&mut self, raw: &mut egui::RawInput) { + if !raw.dropped_files.is_empty() { + self.dropped_files.append(&mut raw.dropped_files); + } + } + + /// Back from an external editor: pick up the files it saved. Reads `i.focused`, which + /// `run_logic` does not refresh, so it belongs to the UI phase. + fn check_external_editor(&mut self, ctx: &egui::Context) { + let focused = ctx.input(|i| i.focused); + if focused && !self.ui.was_focused && !self.ui.external_edits.is_empty() { + let ids = self.ui.external_edits.clone(); + if let Ok(r) = self.session.execute("photo.reload", &serde_json::json!({"ids": ids})) + && r["reloaded"].as_array().is_some_and(|a| !a.is_empty()) + { + self.toast(ctx, crate::i18n::tr("Updated the edits saved in the external editor")); + } + } + self.ui.was_focused = focused; } /// Apply settings that act outside the UI state: GPU rendering and window full screen. @@ -1313,8 +2279,8 @@ impl LightcraftApp { /// While no display profile is chosen, show previews through the profile of the screen the /// window is on (`services.screen_profile`), read about once a second so moving the window to /// another screen is followed. Without the service (or a profile) the display is sRGB. - fn follow_screen_profile(&mut self, ctx: &egui::Context) { - let now = ctx.input(|i| i.time); + fn follow_screen_profile(&mut self, _ctx: &egui::Context) { + let now = self.tick_now(); if self.services.screen_profile.is_none() || self.screen_profile_read.is_some_and(|t| (0.0..1.0).contains(&(now - t))) { return; } @@ -1341,12 +2307,69 @@ impl LightcraftApp { self.screen_profile = icc; } - /// Inject synthetic events (pointer events one per frame; key sequences up to the release). - pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) { - // the frame after a synthetic release / key: modifiers back up + /// Take the host's dropped files once and inject synthetic events (pointer events one per + /// frame; key sequences up to the release). + /// + /// The hook also runs before a hidden logic-only tick, so it injects at most one batch and + /// keeps that batch in flight until a completed UI pass consumed it. It never injects while + /// the fonts are not installed (the pass would draw nothing and the events would be lost). + pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + let file = |p: &String| (!p.is_empty()).then(|| std::path::PathBuf::from(p)); + if !self.drop_pending.is_empty() { + raw.dropped_files = std::mem::take(&mut self.drop_pending) + .into_iter() + .map(|p| std::sync::Arc::new(InjectedDrop(p.into())) as egui::DroppedFileHandle) + .collect(); + } + if !self.drop_hover.is_empty() { + raw.hovered_files = self.drop_hover.iter().map(|p| egui::HoveredFile { path: file(p), ..Default::default() }).collect(); + } + // Queue after injecting, so a `ui.dropFiles` request is consumed exactly once by the UI phase. + self.queue_dropped_files(raw); + // Track the real host modifier state separately from the app's synthetic ownership. A host + // change means the host now owns the modifier state: relinquish any synthetic claim and do + // not later synthesise a release for a key that is physically held. + if let Some(host_mods) = raw.events.iter().rev().find_map(|event| match event { + egui::Event::ModifiersChanged(modifiers) => Some(*modifiers), + _ => None, + }) { + self.host_mods = host_mods; + self.synthetic_mods = egui::Modifiers::NONE; + self.synthetic_mods_release = false; + } + // A prompt owns all input. On its first host frame this also removes pointer/touch input + // before egui computes its hit test; later frames keep only key releases, the prompt's own + // keys, and AccessKit actions targeted at a prompt button. See `notices::filter_raw_input`. + let batch_in_flight = self.synthetic_in_flight; + if crate::panels::notices::prepare_raw_input(self, ctx, raw) { + // A prompt appearing during a synthetic drag must abort the drag, not let its remaining + // move/release events act under the prompt or after it is dismissed. If a whole batch + // was already injected, it is unsafe as well: this frame's prompt filter drops it + // before a panel sees it, so it must not report a successful delivery. + self.cancel_gestures_for_barrier(batch_in_flight, "a modal prompt appeared"); + self.queue_pointer_cleanup(); + } + // Enforce the stall deadline before injecting another event: a request that expired during + // a long frame gap must not get one more event on the frame that resumes. + self.expire_gestures(); + // A canceled press is released by resetting egui's pointer state before its next input + // pass, even while another batch is in flight or the fonts are not ready, so the pointer + // cannot stay down. No move/release event is injected: either could start a drag or + // become a click on the widget being canceled. + self.apply_pointer_cleanup(ctx, raw); + if !self.fonts_ready || self.synthetic_in_flight { + return; + } + if self.drop_gestures_stale_before_injection(ctx) { + // The stale check can cancel the head gesture while its press is already down. + self.apply_pointer_cleanup(ctx, raw); + return; + } + // the frame after a synthetic release / key: restore the host's physical modifiers, not + // necessarily NONE (Shift may still be held while a synthetic Alt gesture is released) if std::mem::take(&mut self.synthetic_mods_release) && self.synthetic_mods != egui::Modifiers::NONE { self.synthetic_mods = egui::Modifiers::NONE; - raw.events.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + raw.events.push(egui::Event::ModifiersChanged(self.host_mods)); } if self.synthetic.is_empty() { return; @@ -1355,7 +2378,9 @@ impl LightcraftApp { egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. } => 1, _ => self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1), }; - if let Some(egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. }) = self.synthetic.first() { + // A press needs the pointer at its position before the button event; the move that is + // itself the first event is delivered by the drain below, so it must not be sent twice. + if let Some(egui::Event::PointerButton { pos: p, .. }) = self.synthetic.first() { raw.events.push(egui::Event::PointerMoved(*p)); } // egui's `input.modifiers` follow `ModifiersChanged` events, not the modifiers carried by @@ -1373,7 +2398,49 @@ impl LightcraftApp { } self.synthetic_mods_release = ends; } + let blocked_by_prompt = self.synthetic[..n].iter().any(|event| !crate::panels::notices::prompt_allows_event(self, event)); + let head = self.head_gesture(); + if let Some(head) = head { + let gesture = &mut self.pending_gestures[head]; + for event in &self.synthetic[..n] { + match event { + egui::Event::PointerButton { button, pressed: true, .. } => { + gesture.pressed = Some(InjectedPress { button: *button }); + } + egui::Event::PointerButton { button, pressed: false, .. } + if gesture.pressed.as_ref().is_some_and(|press| press.button == *button) => + { + gesture.pressed = None; + } + _ => {} + } + } + gesture.started = true; + gesture.remaining_events = gesture.remaining_events.saturating_sub(n); + } raw.events.extend(self.synthetic.drain(..n)); + // The same barrier applies after injection: only the prompt's own keys and targeted + // AccessKit actions survive; host input and `ui.text`/clipboard never reach the background. + crate::panels::notices::filter_raw_input(self, raw); + if blocked_by_prompt && let Some(index) = head { + // A settled prompt is already laid out, so this is not the prompt-creation-cancels-all + // path: only the gesture whose batch the barrier removed fails. Allowed prompt keys, + // pointer input and targeted AccessKit actions still report a successful delivery. + let gesture = self.pending_gestures.remove(index); + self.cancel_gesture_events(&gesture, true); + let _ = gesture.reply.send(serde_json::json!({ + "ok": false, + "error": format!("{} canceled: the open modal prompt blocked this input", gesture.method), + })); + } + // The 5 s deadline is a delivery-stall limit, not a limit on a gesture's frame count: a + // drag feeds one event per host frame, so every batch that the app consumes proves the UI + // is alive and restarts the clock for the whole queue. + let now = self.tick_now_ms(); + for gesture in &mut self.pending_gestures { + gesture.deadline_ms = now + GESTURE_TIMEOUT_MS; + } + self.synthetic_in_flight = true; } /// Lights Out: veil everything but the photo (the loupe's image, or the grid / Compare / @@ -1386,7 +2453,7 @@ impl LightcraftApp { let screen = ctx.content_rect(); let keep = if self.ui.view == state::ViewMode::Detail { self.image_rect.or(self.canvas_rect) } else { self.canvas_rect }; let veil = egui::Color32::from_black_alpha((a.clamp(0.0, 1.0) * 255.0).round() as u8); - let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("lights-out"))); + let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::unique("lights-out"))); let k = keep.unwrap_or(egui::Rect::NOTHING).intersect(screen); if !k.is_positive() { p.rect_filled(screen, 0.0, veil); @@ -1402,6 +2469,12 @@ impl LightcraftApp { /// Frame timings once layout is done (`t0`: when layout started). fn end_frame(&mut self, ctx: &egui::Context, t0: f64) { + if self.ui.frame_rate { + frame_rate::show(ctx, self); + } else { + frame_rate::forget(ctx); + } + panels::edit::wheel_pointer_frame_end(ctx); ctx.output(|o| { for c in &o.commands { if let egui::OutputCommand::CopyText(text) = c { @@ -1409,7 +2482,7 @@ impl LightcraftApp { } } }); - self.perf.frame_ms = now_ms() - t0; + self.perf.frame_ms = monotonic_ms() - t0; self.perf.update_ms = self.perf.logic_ms + self.perf.frame_ms; self.perf.max_update_ms = self.perf.max_update_ms.max(self.perf.update_ms); } @@ -1425,6 +2498,12 @@ impl LightcraftApp { if let Some(l) = self.session.library.as_ref().filter(|l| l.on_disk) { let path = l.dir.to_string_lossy().into_owned(); panels::settings::remember_library(&mut self.ui.settings.recent_libraries, &path); + // it is open: whatever an earlier check said about it is over + self.recent_checks.opened(&path); + // when, for the launch window (issue #1290); only the listed libraries keep a time + let settings = &mut self.ui.settings; + settings.recent_opened.insert(path, (self.session.clock)()); + settings.recent_opened.retain(|p, _| settings.recent_libraries.contains(p)); } ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.window_title())); } @@ -1437,7 +2516,20 @@ impl LightcraftApp { } } - /// Lay out the whole window. + /// The browser page's title: "<file name>[ •] — LightCraft" for the active photo (• while + /// `unsaved`: changes not yet written to storage), else the window title. The web build has no + /// window for `ViewportCommand::Title`; a host embedding it reads this title to tell which + /// document a drop opened and whether it is saved (issue #2397). + pub fn page_title(&self, unsaved: bool) -> String { + let dot = if unsaved { " •" } else { "" }; + match self.session.active().and_then(|id| self.session.catalog.photo(id)) { + Some(p) => format!("{}{dot} — LightCraft", p.file_name), + None => format!("{}{dot}", self.window_title()), + } + } + + /// Lay out the whole window: input/setup for the known UI phase, then presentation, then the + /// frame bookkeeping. A hidden `run_logic` never reaches this. pub fn ui(&mut self, ui: &mut egui::Ui) { i18n::set_language(self.ui.language); let ctx = ui.ctx().clone(); @@ -1445,27 +2537,109 @@ impl LightcraftApp { ctx.request_repaint(); return; } + self.sync_theme(&ctx); + self.ui_pass(&ctx); + self.draw_window(ui); + self.finish_ui_pass(&ctx); + } + + /// A completed, nondiscarded pass is a settled frame; a discarded pass threw its widgets away + /// and must not advance the geometry generation a capture binds to. + fn finish_ui_pass(&mut self, ctx: &egui::Context) { + // Any pass consumed the injected batch; a discarded pass still read its events and the + // next pass has none. Only a nondiscarded pass, however, is a settled frame a capture may + // bind to and a control gesture may resolve against. + self.synthetic_in_flight = false; + if ctx.will_discard() { + self.next_widgets.clear(); + self.next_widget_hits.clear(); + return; + } + self.widgets = std::mem::take(&mut self.next_widgets); + self.widget_hits = std::mem::take(&mut self.next_widget_hits); + panels::notices::finish_ui_pass(self, ctx); + panels::library_problem::finish_ui_pass(self, ctx); + self.ui_passes = self.ui_passes.wrapping_add(1); + self.layout_epoch = self.layout_epoch.wrapping_add(1); + self.resolve_pending_gestures(ctx); + self.reply_delivered_gestures(); + if self.pointer_cleanup { + // A canceled press may be discovered by a timeout after the synthetic queue emptied; + // nothing else may ask for the frame that applies its cancellation. + ctx.request_repaint(); + } + } + + /// Presentation only: the window's panels, dialogs and overlays. + fn draw_window(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let t0 = monotonic_ms(); + panels::library_problem::begin_draw(self); + // A command or shortcut drawn before this can create the window after `ui_pass`; catch it + // here before any panel draws with the still-focused background text field. + let batch_in_flight = self.synthetic_in_flight; + panels::library_problem::prepare_ui_pass(self, &ctx, batch_in_flight); + // A newly shown blocking library window gets the same barrier as a prompt: its first Area + // layout is non-interactable and hit testing still uses the previous pass, so background + // panels (and a focused text field) must not draw in that pass. + if panels::library_problem::shield_pass(self, &ctx) { + #[cfg(test)] + self.library_passes.push(panels::library_problem::LibraryPass::Shield); + panels::library_problem::show(self, &ctx, false); + (self.next_widgets, self.next_widget_hits) = widgets::take_registries(&ctx); + ctx.request_discard("library problem: shield the window's creation frame"); + self.end_frame(&ctx, t0); + return; + } + // A newly shown prompt gets one pass with no background. egui's first Area layout is + // non-interactable and its hit test uses the previous pass, so drawing panels here would + // let a pointer press/release in the prompt's creation frame act underneath it. `ui()` then + // reruns this pass with empty raw input, where the settled prompt and the full window draw + // together. This is a state/input-routing barrier, not a wholesale input disable: once + // settled, raw pointer input still reaches the prompt backdrop (a no-op) or its buttons. + if panels::notices::shield_pass(self, &ctx) { + panels::notices::show(self, &ctx); + (self.next_widgets, self.next_widget_hits) = widgets::take_registries(&ctx); + ctx.request_discard("notice: shield the prompt's creation frame"); + self.end_frame(&ctx, t0); + return; + } + #[cfg(test)] + self.library_passes.push(panels::library_problem::LibraryPass::Background); panels::dialogs::prepare(self, ui); - let t0 = now_ms(); + // Freeze this frame's notice barrier before `notices::show` can dismiss a prompt: the same + // click or key must never be acted on again by the dialog drawn after it. + let notice_blocks = panels::notices::blocks_input(self); if std::mem::take(&mut self.ui.quit) { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } self.library_changed(&ctx); // panels set it again this frame while the pointer rests on a preset or profile self.hover_preview = None; - self.ai_mask_detail(&ctx); - self.place_names_outcome(&ctx); if self.ui.fullscreen { // full-screen preview: the photo alone on black egui::CentralPanel::default() .frame(egui::Frame::NONE.fill(egui::Color32::BLACK)) .show(ui, |ui| if self.ui.slideshow.is_some() { panels::slideshow::show(self, ui) } else { panels::detail::show(self, ui) }); panels::second::show(self, &ctx); + if notice_blocks { + panels::notices::restore_prompt_pointer(self, &ctx); + } panels::notices::show(self, &ctx); - panels::dialogs::show(self, &ctx); - panels::library_problem::show(self, &ctx); + if notice_blocks { + panels::notices::hide_background_pointer(&ctx); + } + panels::dialogs::show(self, &ctx, notice_blocks); + updates_ui::show(self, &ctx); + panels::library_problem::show(self, &ctx, notice_blocks); panels::toast(self, &ctx); - self.widgets = widgets::take_registry(&ctx); + drop_overlay::show(self, &ctx); + if notice_blocks { + // Keep the real press/release state for the next pass: an ordinary click spans + // host frames, and resetting it above must only hide it from this pass's dialogs. + panels::notices::restore_prompt_pointer(self, &ctx); + } + (self.next_widgets, self.next_widget_hits) = widgets::take_registries(&ctx); self.end_frame(&ctx, t0); return; } @@ -1479,9 +2653,16 @@ impl LightcraftApp { egui::CentralPanel::default().frame(egui::Frame::NONE.fill(chrome)).show(ui, |ui| docking::show(self, ui)); self.lights_out(&ctx); panels::second::show(self, &ctx); + if notice_blocks { + panels::notices::restore_prompt_pointer(self, &ctx); + } panels::notices::show(self, &ctx); - panels::dialogs::show(self, &ctx); - panels::library_problem::show(self, &ctx); + if notice_blocks { + panels::notices::hide_background_pointer(&ctx); + } + panels::dialogs::show(self, &ctx, notice_blocks); + updates_ui::show(self, &ctx); + panels::library_problem::show(self, &ctx, notice_blocks); export_task::poll(self, &ctx); slideshow_export::poll(self, &ctx); panels::activity::show(self, &ctx); @@ -1492,31 +2673,234 @@ impl LightcraftApp { panels::left::section_drag_feedback(self, &ctx); panels::keyword_list::drag_feedback(self, &ctx); panels::toast(self, &ctx); - self.widgets = widgets::take_registry(&ctx); + drop_overlay::show(self, &ctx); + if notice_blocks { + // Keep the real press/release state for the next pass: an ordinary click spans host + // frames, and resetting it above must only hide it from this pass's dialogs. + panels::notices::restore_prompt_pointer(self, &ctx); + } + (self.next_widgets, self.next_widget_hits) = widgets::take_registries(&ctx); self.text_focus = ctx.egui_wants_keyboard_input(); self.end_frame(&ctx, t0); } } -/// How long a screenshot waits for in-flight renders. +/// How long a screenshot waits for in-flight renders before it is captured anyway (and the +/// headless fallback's settle budget). const SCREENSHOT_SETTLE_MS: f64 = 3000.0; /// How long a windowed screenshot waits for the compositor before falling back to headless. const SCREENSHOT_FALLBACK_MS: f64 = 2000.0; +/// Screenshots admitted at once (queued, issued and completed-but-undrained). +const MAX_PENDING_SHOTS: usize = 4; +/// Bytes one screenshot image may use. +const MAX_SHOT_BYTES: usize = 128 * 1024 * 1024; +/// Largest RGBA surface that fits [`MAX_SHOT_BYTES`], checked with the viewport dimensions before +/// layout. The CPU rasterizer's own `softpaint::MAX_IMAGE_PIXELS` may be larger; a snapshot that +/// cannot be captured must be rejected up front rather than after admission. +pub(crate) const MAX_SHOT_PIXELS: usize = MAX_SHOT_BYTES / std::mem::size_of::<egui::Color32>(); +/// Bytes all pending/completed screenshots may reserve together. +const MAX_SHOT_TOTAL_BYTES: usize = 256 * 1024 * 1024; +/// Slack for PNG framing and deflate overhead while encoding one screenshot. zlib can exceed the +/// raw bytes slightly for incompressible input; this bounds that transient honestly. +const SHOT_ENCODE_SLACK_BYTES: usize = 64 * 1024; +/// Peak working set of capture encoding: every reserved image (≤ [`MAX_SHOT_TOTAL_BYTES`]) plus, +/// for the image being written, its `Rgba8` copy and encoded PNG (each ≤ [`MAX_SHOT_BYTES`] plus +/// [`SHOT_ENCODE_SLACK_BYTES`]). Encoding runs on the UI thread, one image at a time. +const MAX_SHOT_WORKING_SET_BYTES: usize = MAX_SHOT_TOTAL_BYTES + 2 * MAX_SHOT_BYTES + SHOT_ENCODE_SLACK_BYTES; +const _: () = { + assert!(MAX_SHOT_WORKING_SET_BYTES > MAX_SHOT_TOTAL_BYTES); + assert!(SHOT_ENCODE_SLACK_BYTES > 0); + assert!(MAX_SHOT_BYTES.is_multiple_of(std::mem::size_of::<egui::Color32>())); + assert!(MAX_SHOT_PIXELS * std::mem::size_of::<egui::Color32>() == MAX_SHOT_BYTES); +}; +/// Synthetic-input control requests waiting for a fresh layout/delivery at once. +const MAX_PENDING_GESTURES: usize = 32; +/// A control gesture is answered with an error after this long without a completed UI pass and +/// delivery (milliseconds). +/// How long synthetic input may wait without the UI consuming a batch. Each consumed batch +/// restarts this clock, so it is a stall limit, not a cap on a many-step drag's total time. +const GESTURE_TIMEOUT_MS: f64 = 5000.0; +/// Completed UI frames a request waits for before it is issued (a settled, laid-out frame). +const SHOT_SETTLE_FRAMES: u64 = 3; +/// Time a request waits before it is issued, so a control command that triggered a layout change +/// is not captured mid-change. +const SHOT_SETTLE_MS: f64 = 120.0; +/// A settled capture is issued at this instant even while renders are still in flight. The hard +/// admission deadline below still leaves the compositor fallback and the headless settle after it. +const SHOT_FORCE_BUSY_MS: f64 = SCREENSHOT_SETTLE_MS; +/// The texture limit when the host has not reported one. +const MAX_TEXTURE_SIDE: usize = 16_384; + +/// The viewport geometry a screenshot was issued for. A completion from an older generation is +/// rejected even if the window has since returned to the same size. +#[derive(Clone, Copy, Debug, PartialEq)] +struct ShotGeometry { + /// Viewport size in egui points (the same units as `content_rect`). + viewport: egui::Vec2, + /// Egui pixels per point, including UI zoom. + pixels_per_point: f32, + /// The UI zoom factor. + zoom: f32, + /// [`LightcraftApp::shot_geometry_epoch`] at issue. + epoch: u64, +} + +impl ShotGeometry { + /// The surface pixels this geometry would produce, before the host's texture limit. + fn surface_pixels(self) -> Option<(usize, usize)> { + let w = (self.viewport.x * self.pixels_per_point).round(); + let h = (self.viewport.y * self.pixels_per_point).round(); + if !w.is_finite() || !h.is_finite() || w < 1.0 || h < 1.0 { + return None; + } + Some((w as usize, h as usize)) + } + + /// The surface pixels this geometry can produce, or `None` when it is not a usable surface or + /// exceeds one side of the host's texture limit. + fn pixels(self, max_texture_side: usize) -> Option<(usize, usize)> { + let (w, h) = self.surface_pixels()?; + (w <= max_texture_side && h <= max_texture_side).then_some((w, h)) + } + + /// Checked `width * height * 4` bytes for this geometry. + fn bytes(self, max_texture_side: usize) -> Option<usize> { + let (w, h) = self.pixels(max_texture_side)?; + w.checked_mul(h)?.checked_mul(std::mem::size_of::<egui::Color32>()) + } + + /// Why [`Self::bytes`] returned `None`: no laid-out surface, or one side over the host's limit. + /// The two are not the same user action (a driver/GL limit is not "the window has not drawn"). + fn rejection(self, max_texture_side: usize) -> String { + match self.surface_pixels() { + None => "ui.screenshot: the window has no usable surface size yet (no frame has been laid out)".to_string(), + Some((w, h)) => format!("ui.screenshot: the {w}×{h} pixel surface is over the host's {max_texture_side}-pixel per-side texture limit"), + } + } +} + +/// Import commits batches at most once per host frame. The first layout pass and a hidden +/// `run_logic` tick both report pass index 0; a discarded frame's later passes report 1+. A +/// wall-clock gate cannot express that (a slow first pass could re-run it within one frame). +fn import_tick_allowed(ctx: &egui::Context) -> bool { + ctx.current_pass_index() == 0 +} + +/// Whether a pending request may be issued now: it has waited for the settle time and completed +/// UI frames, and either no render is in flight or the forced-capture instant has passed. +fn shot_ready(now_ms: f64, shot: &PendingShot, busy: bool, ui_passes: u64) -> bool { + let settled = ui_passes.saturating_sub(shot.admitted_passes) >= SHOT_SETTLE_FRAMES && now_ms >= shot.not_before_ms; + settled && (!busy || now_ms >= shot.force_ms) +} + +/// The navigation/document/modal/panel state a gesture was admitted under. The same automation +/// id can mean a different control after any of these changes; the request is canceled rather +/// than retargeted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct GestureFrame { + view: crate::state::ViewMode, + active: Option<lightcraft_catalog::PhotoId>, + library: u64, + dialog: Option<std::mem::Discriminant<crate::state::Dialog>>, + left_panel: bool, + right: crate::state::RightPanel, + presets: bool, + filmstrip: bool, +} + +/// A synthetic-input control request waiting for a fresh layout and for its last event to be +/// consumed by a completed UI pass. +struct PendingGesture { + method: String, + params: Value, + reply: Sender<ControlResponse>, + /// [`LightcraftApp::layout_epoch`] at admission; resolution needs a later one. + admitted_epoch: u64, + frame: GestureFrame, + /// Monotonic stall deadline (milliseconds): delivery refreshes it whenever the UI consumes a + /// batch, so a long but progressing drag is not a timeout. + deadline_ms: f64, + /// [`LightcraftApp::ui_passes`] when the events were queued (`None`: not resolved yet). + resolved_pass: Option<u64>, + /// Synthetic events queued for this gesture that the host has not injected yet. + remaining_events: usize, + /// At least one batch of this gesture's events has reached a pass. Later batches may see the + /// gesture's own effect (a first click selects, the second opens), so the semantic frame + /// snapshot is only checked before the first one. + started: bool, + /// For a widget gesture, the id and point resolved against the completed layout. Delivery + /// rechecks the widget's fresh rect before the first event, before each press and (for a click) + /// before its release. + target: Option<control::GestureTarget>, + /// A pointer button this gesture has pressed but not yet released. Cancellation resets the + /// pointer state before egui's next input pass, so a refused click neither leaves the pointer + /// down nor turns the cleanup into a click or drag. + pressed: Option<InjectedPress>, + result: Value, +} + +/// A pointer press delivered to the UI, kept so a canceled gesture knows that a button is down. +#[derive(Clone, Copy, Debug)] +struct InjectedPress { + button: egui::PointerButton, +} /// A `ui.screenshot` request in progress. struct PendingShot { token: u64, - path: Option<String>, + /// Destination identity pinned at admission (revalidated immediately before the write). + target: Option<lightcraft_engine::originals::WriteTarget>, reply: Sender<ControlResponse>, headless: bool, - not_before: f64, - deadline: f64, - frames: u32, + /// Admitted UI pass count and monotonic deadlines (milliseconds). + admitted_passes: u64, + not_before_ms: f64, + /// At this instant a busy renderer no longer holds the capture back. + force_ms: f64, + deadline_ms: f64, /// When the viewport screenshot command went out. - sent_at: Option<f64>, + sent_at_ms: Option<f64>, + /// Bytes this request reserves until it is drained or cancelled. + reserved: usize, + /// The one-shot completion slot; only the app owns the strong reference. + slot: Option<craft_ui::capture::CaptureSlot>, + /// The geometry and document generation the issued command was bound to. + issued: Option<ShotGeometry>, + /// Library generation at issue (a different library changed mid-capture). + issued_library: u64, } -/// Wall-clock milliseconds since the Unix epoch (`web-time` maps to `Date.now()` on the web). +/// A monotonic clock for the app's own timers. +/// +/// `web_time::Instant` is backed by the browser's `performance.now()` on WASM and by +/// `std::time::Instant` natively: it never jumps with the wall clock and has no `Date.now()` +/// zero-origin problem. A headless host may supply its simulated time instead. +#[derive(Clone, Copy, Debug)] +struct AppClock { + start: web_time::Instant, + simulated: Option<f64>, +} + +impl AppClock { + /// Start the clock at the current monotonic instant with no simulated time. + fn new() -> Self { + Self { start: web_time::Instant::now(), simulated: None } + } + + /// Seconds on the clock: the supplied simulated time when set, otherwise time since `new`. + fn now(&self) -> f64 { + self.simulated.unwrap_or_else(|| self.start.elapsed().as_secs_f64()) + } +} + +/// Monotonic milliseconds since the first call, for durations and deadlines. +pub fn monotonic_ms() -> f64 { + static START: std::sync::OnceLock<web_time::Instant> = std::sync::OnceLock::new(); + START.get_or_init(web_time::Instant::now).elapsed().as_secs_f64() * 1000.0 +} + +/// Wall-clock milliseconds since the Unix epoch, only for names that must be unique in the world +/// (`library-restored-<ms>`), never for timing or deadlines. pub fn now_ms() -> f64 { use web_time::{SystemTime, UNIX_EPOCH}; SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64() * 1000.0).unwrap_or(0.0) @@ -1563,6 +2947,26 @@ fn sam_download_ended(download: &lightcraft_engine::segment::DownloadStatus) -> } } +/// A file `ui.dropFiles` delivers as dropped, as a real OS drop arrives in `raw.dropped_files`. +#[derive(Debug)] +struct InjectedDrop(std::path::PathBuf); + +impl egui::DroppedFile for InjectedDrop { + fn path(&self) -> &std::path::Path { + &self.0 + } + + #[cfg(not(target_arch = "wasm32"))] + fn bytes(&self) -> Result<Vec<u8>, String> { + std::fs::read(&self.0).map_err(|e| e.to_string()) + } + + #[cfg(target_arch = "wasm32")] + fn bytes_async(&self) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>, String>> + '_>> { + Box::pin(async { Err("the web build has no files to read".to_string()) }) + } +} + /// A dropped face model file (`.onnx`). pub fn is_model_file(path: &str) -> bool { std::path::Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("onnx")) diff --git a/crates/ui-egui/src/lightroom_destination.rs b/crates/ui-egui/src/lightroom_destination.rs new file mode 100644 index 0000000000..5fd781cfdd --- /dev/null +++ b/crates/ui-egui/src/lightroom_destination.rs @@ -0,0 +1,366 @@ +//! File ▸ Import Lightroom Catalog…: where the catalog goes (issue #2672). +//! +//! Before the import starts, a window asks whether the catalog's photos, collections and edits +//! merge into the library open now or go into a new library, named after the catalog and put next +//! to the open one. The new library is made and opened as File ▸ New Library… does +//! (`app.newLibrary`: refused in a folder that isn't empty, or while another import runs), then the +//! catalog is imported into it. Settings ▸ General ▸ Library (or the window's "Don't ask again") +//! turns the question off: the catalog then merges into the open library, as it always did. +//! +//! Only the app command `file.importLightroom` changes: it takes `{into?: "open" | "new", name?, +//! location?}` so the control channel can make the choice without the window. The import itself +//! (`library.importLightroom`, [`crate::lightroom_import`]) is unchanged. A session with no +//! library on disk (in memory) has nothing to put a new library next to: it merges without asking. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::state::{Dialog, LightroomImport}; + +/// Where `file.importLightroom {into}` puts the catalog. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Destination { + /// `"open"`: merge into the library open now. + Open, + /// `"new"`: a new library, opened before the import. + New, +} + +/// The destination params of `file.importLightroom`, checked. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Request { + /// `into`; `None`: ask (or merge, as the setting says). + pub into: Option<Destination>, + /// `name`: the new library's name (default: the catalog file's name without `.lrcat`). + pub name: Option<String>, + /// `location`: the folder the new library goes in (default: the open library's parent folder). + pub location: Option<String>, +} + +impl Request { + /// Read `{into?, name?, location?}` from `file.importLightroom`'s params. A wrong type or an + /// unknown `into` is an error, before any file dialog opens. + pub fn parse(p: &Value) -> Result<Request, String> { + let into = match p.get("into") { + None | Some(Value::Null) => None, + Some(Value::String(s)) if s == "open" => Some(Destination::Open), + Some(Value::String(s)) if s == "new" => Some(Destination::New), + Some(v) => return Err(format!("file.importLightroom: `into` must be \"open\" or \"new\", not {v}")), + }; + let text = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.clone())), + Some(v) => Err(format!("file.importLightroom: `{key}` must be a string, not {v}")), + }; + Ok(Request { into, name: text("name")?, location: text("location")? }) + } +} + +/// What `file.importLightroom` does with a catalog. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Plan { + /// Import into the library open now. + Merge, + /// Make a new library, open it, import into it. + NewLibrary, + /// Show the window; `new_library`: "Create a new library" is the choice it opens with. + Ask { new_library: bool }, +} + +/// The decision, from the setting, the open library (`on_disk`: saved in a folder, not in memory; +/// `photos`: how many it holds) and the command's `into`. `into` always wins; without it a library +/// in memory, or the setting "Always merge", merges; otherwise the window asks, opening on "Merge" +/// when the library is empty (there is nothing to merge with) and on "Create a new library" when +/// it holds photos. +pub fn decide(setting: LightroomImport, on_disk: bool, photos: usize, into: Option<Destination>) -> Plan { + match into { + Some(Destination::Open) => Plan::Merge, + Some(Destination::New) => Plan::NewLibrary, + None if !on_disk || setting == LightroomImport::AlwaysMerge => Plan::Merge, + None => Plan::Ask { new_library: photos > 0 }, + } +} + +/// The photos in the open library (not those in Recently Deleted or browsed under Local). +fn library_photos(app: &LightcraftApp) -> usize { + app.session.catalog.photos().filter(|p| p.in_library()).count() +} + +/// The open library's folder, when it is saved on disk. +fn library_dir(app: &LightcraftApp) -> Option<PathBuf> { + app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()) +} + +/// Where a new library goes by default: next to the open one (its parent folder). +pub fn default_location(app: &LightcraftApp) -> Option<PathBuf> { + library_dir(app).and_then(|d| d.parent().map(Path::to_path_buf)) +} + +/// The new library's default name: the catalog's file name without `.lrcat` (`Travel.lrcat` → +/// `Travel`), or `Travel 2`, `Travel 3`… when `location` has something by that name already. +pub fn default_name(catalog: &Path, location: Option<&Path>) -> String { + let stem = catalog.file_stem().map(|s| s.to_string_lossy().trim().to_string()).filter(|s| !s.is_empty()); + let stem = stem.unwrap_or_else(|| "Lightroom Catalog".to_string()); + match location { + Some(loc) => crate::panels::settings::free_name(loc, &stem).file_name().map_or(stem.clone(), |n| n.to_string_lossy().into_owned()), + None => stem, + } +} + +/// Refuse while a Lightroom catalog task or another import runs (as the import itself would), +/// before a window asks a question whose answer couldn't be carried out. +fn busy(app: &LightcraftApp) -> Result<(), String> { + if crate::lightroom_import::is_running(app) { + return Err("a Lightroom catalog task is already running; wait for it to finish".into()); + } + if app.import.is_some() || app.scan.is_some() { + return Err("an import is running; wait for it to finish before importing a Lightroom catalog".into()); + } + Ok(()) +} + +/// `file.importLightroom` once the catalog `path` is known: merge, make a new library first, or +/// ask, as [`decide`] says. Returns the import's start (`{running, kind, path}`), with +/// `library: {path, name, photos}` when a new library was made, or `{asking: true, path, into}` +/// while the window asks (`into`: the choice it opens with). +pub fn import(app: &mut LightcraftApp, path: &str, req: &Request) -> Result<Value, String> { + // the browser build can't import a catalog at all: the import says so (and no library is made) + if cfg!(target_arch = "wasm32") { + return app.run("library.importLightroom", json!({"path": path})); + } + let on_disk = library_dir(app).is_some(); + match decide(app.ui.settings.lightroom_import, on_disk, library_photos(app), req.into) { + Plan::Merge => app.run("library.importLightroom", json!({"path": path})), + Plan::NewLibrary => into_new_library(app, path, req), + Plan::Ask { new_library } => { + busy(app)?; + if !Path::new(path).is_file() { + return Err(format!("{path}: there is no Lightroom catalog file here")); + } + let location = req.location.clone().or_else(|| default_location(app).map(|d| d.to_string_lossy().into_owned())).unwrap_or_default(); + let name = req.name.clone().unwrap_or_else(|| default_name(Path::new(path), (!location.is_empty()).then_some(Path::new(&location)))); + app.ui.dialog = Some(Dialog::LightroomDestination { + catalog: path.to_string(), + library: crate::panels::settings::open_library_name(app).unwrap_or_default(), + photos: library_photos(app), + new_library, + name, + location, + dont_ask: false, + generation: app.session.library_generation(), + }); + Ok(json!({"asking": true, "path": path, "into": if new_library { "new" } else { "open" }})) + } + } +} + +/// Make the new library (`app.newLibrary {path: location, name}`: its rules, its errors), open it +/// and import the catalog there. The catalog is checked first, so a mistyped path doesn't leave an +/// empty library behind. +fn into_new_library(app: &mut LightcraftApp, path: &str, req: &Request) -> Result<Value, String> { + busy(app)?; + if !Path::new(path).is_file() { + return Err(format!("{path}: there is no Lightroom catalog file here")); + } + let location = match req.location.as_deref().map(str::trim) { + Some("") => return Err("file.importLightroom: choose where to put the new library (`location`)".into()), + Some(l) => PathBuf::from(l), + None => default_location(app).ok_or("file.importLightroom: no library is open on disk to put the new one next to; give `location`")?, + }; + if !location.is_absolute() { + return Err(format!("file.importLightroom: {}: the location must be a full folder path", location.display())); + } + let name = req.name.clone().unwrap_or_else(|| default_name(Path::new(path), Some(&location))); + let library = app.run("app.newLibrary", json!({"path": location.to_string_lossy(), "name": name}))?; + let mut started = app.run("library.importLightroom", json!({"path": path}))?; + if let Some(o) = started.as_object_mut() { + o.insert("library".into(), library); + } + Ok(started) +} + +/// The window's choice as `file.importLightroom` params. +fn params(catalog: &str, new_library: bool, name: &str, location: &str) -> Value { + if new_library { json!({"path": catalog, "into": "new", "name": name, "location": location}) } else { json!({"path": catalog, "into": "open"}) } +} + +/// The window's confirm button: import as chosen. "Don't ask again" is kept once a merge has +/// started (it only applies to merging). Another library opened while the window was up (by an +/// agent, the control channel) makes the window stale for both choices: nothing is merged into +/// it, and no new library is made from defaults that described the library it replaced. +pub fn confirm(app: &mut LightcraftApp, dialog: &Dialog) -> Result<Value, String> { + let Dialog::LightroomDestination { catalog, new_library, name, location, dont_ask, generation, .. } = dialog else { + return Err("not the Lightroom catalog destination window".into()); + }; + if *generation != app.session.library_generation() { + return Err(crate::i18n::tr("Another library was opened since this window appeared: nothing was imported").to_string()); + } + let r = app.run("file.importLightroom", params(catalog, *new_library, name, location))?; + if !*new_library && *dont_ask { + app.ui.settings.lightroom_import = LightroomImport::AlwaysMerge; + } + Ok(r) +} + +/// After a failed confirm the window stays open to be corrected (a folder that isn't empty, a +/// name a folder can't have), unless the library it named has gone. +pub fn keeps_open_on_error(app: &LightcraftApp, dialog: &Dialog) -> bool { + matches!(dialog, Dialog::LightroomDestination { generation, .. } if *generation == app.session.library_generation()) +} + +/// The confirm button's label. +pub fn ok_label(dialog: &Dialog) -> &'static str { + match dialog { + Dialog::LightroomDestination { new_library: true, .. } => "Create Library and Import", + _ => "Import", + } +} + +/// The window's body: the two choices, the new library's name and location, and "Don't ask again". +pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, dialog: &mut Dialog) { + let Dialog::LightroomDestination { catalog, library, photos, new_library, name, location, dont_ask, .. } = dialog else { return }; + let t = crate::theme::Tokens::get(ui.ctx()); + let tr = crate::i18n::tr; + let file = Path::new(catalog.as_str()).file_name().map_or_else(|| catalog.clone(), |n| n.to_string_lossy().into_owned()); + ui.label(crate::i18n::tr_format!("Where should the Lightroom catalog “{catalog}” go?", catalog = file)); + ui.label(egui::RichText::new(catalog.as_str()).color(t.text_dim)); + ui.add_space(4.0); + let n = *photos; + let merge = crate::i18n::tr_format!( + "Merge into the open library “{library}” ({count} photo{})", + if n == 1 { "" } else { "s" }, + library = library, + count = n + ); + let r = ui.radio_value(new_library, false, merge); + crate::widgets::register(ui, "radio:lightroomDestination-open", r.rect); + let indent = ui.spacing().icon_width + ui.spacing().icon_spacing; + let note = |ui: &mut egui::Ui, text: &str| { + ui.horizontal(|ui| { + ui.add_space(indent); + ui.add(egui::Label::new(egui::RichText::new(text).color(t.text_dim)).wrap()); + }); + }; + note( + ui, + if n == 0 { + tr("The library is empty: the catalog's photos, collections and edits become its first.") + } else { + tr("The catalog's photos, collections and edits join the ones already in this library.") + }, + ); + let r = ui.radio_value(new_library, true, tr("Create a new library")); + crate::widgets::register(ui, "radio:lightroomDestination-new", r.rect); + ui.add_enabled_ui(*new_library, |ui| { + // a field's caption, left-aligned in a column as wide as the longer one (in any language) + let font = egui::TextStyle::Body.resolve(ui.style()); + let caption_w = [tr("Library name"), tr("Location")] + .iter() + .map(|c| ui.painter().layout_no_wrap(c.to_string(), font.clone(), t.text_label).size().x) + .fold(60.0_f32, f32::max) + + 8.0; + let caption = |ui: &mut egui::Ui, text: &str| { + ui.allocate_ui_with_layout(egui::vec2(caption_w, 20.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(caption_w); + ui.label(egui::RichText::new(text).color(t.text_label)); + }); + }; + ui.horizontal(|ui| { + ui.add_space(indent); + caption(ui, tr("Library name")); + crate::text_field::TextField::singleline("field:lightroomLibraryName", name) + .label(tr("Library name")) + .width(ui.available_width().max(120.0)) + .show(ui); + }); + ui.horizontal(|ui| { + ui.add_space(indent); + caption(ui, tr("Location")); + let choose = app.services.pick_folder.is_some(); + let button_w = if choose { 80.0 } else { 0.0 }; + crate::text_field::TextField::singleline("field:lightroomLibraryLocation", location) + .label(tr("Location")) + .width((ui.available_width() - button_w).max(120.0)) + .show(ui); + if choose + && crate::widgets::text_button(ui, "lightroomLibraryChoose", tr("Choose…"), false).clicked() + && let Some(pick) = app.services.pick_folder.as_mut() + && let Some(d) = pick() + { + *location = d; + } + }); + note(ui, tr("LightCraft opens the new library, then imports the catalog into it. Its folder must be new or empty.")); + }); + ui.add_space(4.0); + // (it only speaks of merging: unticked and greyed out while a new library is chosen) + let mut ticked = *dont_ask && !*new_library; + let c = ui.add_enabled(!*new_library, egui::Checkbox::new(&mut ticked, tr("Don't ask again (always merge into the open library)"))); + crate::widgets::register(ui, "check:lightroomDontAsk", c.rect); + if !*new_library { + *dont_ask = ticked; + } + ui.label(egui::RichText::new(tr("To be asked again: Settings → General → When importing a Lightroom catalog.")).size(11.0).color(t.text_dim)); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every combination of the setting, an empty or full library on disk or in memory, and `into`. + #[test] + fn the_setting_the_library_and_into_decide() { + use Destination::{New, Open}; + use LightroomImport::{AlwaysMerge, Ask}; + for setting in [Ask, AlwaysMerge] { + for on_disk in [true, false] { + for photos in [0, 5] { + // `into` always wins: the control channel acts without asking + assert_eq!(decide(setting, on_disk, photos, Some(Open)), Plan::Merge); + assert_eq!(decide(setting, on_disk, photos, Some(New)), Plan::NewLibrary); + } + } + } + // without it: ask, opening on Merge for an empty library and on a new library for a full one + assert_eq!(decide(Ask, true, 0, None), Plan::Ask { new_library: false }); + assert_eq!(decide(Ask, true, 5, None), Plan::Ask { new_library: true }); + // "Always merge" doesn't ask + assert_eq!(decide(AlwaysMerge, true, 0, None), Plan::Merge); + assert_eq!(decide(AlwaysMerge, true, 5, None), Plan::Merge); + // a library in memory has no folder to put a new one next to: it merges, as before + assert_eq!(decide(Ask, false, 0, None), Plan::Merge); + assert_eq!(decide(Ask, false, 5, None), Plan::Merge); + } + + /// `into`, `name` and `location` are read, and a wrong one is an error naming the command. + #[test] + fn params_are_checked_before_anything_happens() { + assert_eq!(Request::parse(&json!({})).unwrap(), Request::default()); + assert_eq!(Request::parse(&json!({"into": null})).unwrap(), Request::default()); + let r = Request::parse(&json!({"into": "new", "name": "Travel", "location": "/photos"})).unwrap(); + assert_eq!(r, Request { into: Some(Destination::New), name: Some("Travel".into()), location: Some("/photos".into()) }); + assert_eq!(Request::parse(&json!({"into": "open"})).unwrap().into, Some(Destination::Open)); + for bad in [json!({"into": "elsewhere"}), json!({"into": 1}), json!({"name": 3}), json!({"location": ["a"]})] { + let err = Request::parse(&bad).unwrap_err(); + assert!(err.starts_with("file.importLightroom:"), "{err}"); + } + } + + /// The catalog's file name, or the next free one in the location. + #[test] + fn the_new_library_is_named_after_the_catalog() { + assert_eq!(default_name(Path::new("/x/Travel.lrcat"), None), "Travel"); + assert_eq!(default_name(Path::new("/x/Lightroom Catalog-v13-3.lrcat"), None), "Lightroom Catalog-v13-3"); + // nothing to name it after + assert_eq!(default_name(Path::new(""), None), "Lightroom Catalog"); + // a name taken in the location: the next free one + let dir = std::env::temp_dir().join(format!("lc-ui-lrdest-name-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Travel")).unwrap(); + assert_eq!(default_name(Path::new("/x/Travel.lrcat"), Some(&dir)), "Travel 2"); + assert_eq!(default_name(Path::new("/x/Family.lrcat"), Some(&dir)), "Family"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/ui-egui/src/lightroom_import.rs b/crates/ui-egui/src/lightroom_import.rs index 2bda28cf42..098c989d5c 100644 --- a/crates/ui-egui/src/lightroom_import.rs +++ b/crates/ui-egui/src/lightroom_import.rs @@ -140,6 +140,22 @@ fn unsupported_wasm() -> Result<Value, String> { Err("Lightroom catalog import is unavailable in browser builds; open the catalog in the native LightCraft app".into()) } +/// Tests: a catalog import that never ends while the returned value lives, so a drop meets it pending. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn stall_import(app: &mut LightcraftApp) -> Box<dyn std::any::Any> { + let (tx, rx) = mpsc::channel::<Message>(); + let task = LightroomTask::new( + &app.session, + Kind::Import, + PathBuf::from("catalog.lrcat"), + Arc::new(AtomicBool::new(false)), + LightroomProgress::default(), + rx, + ); + app.lightroom = Some(task); + Box::new(tx) +} + /// Whether a Lightroom task currently owns the catalog transition. pub fn is_running(app: &LightcraftApp) -> bool { app.lightroom.is_some() @@ -684,25 +700,17 @@ mod tests { } #[test] - fn skipped_images_are_one_line_in_the_ui_language() { + fn skipped_images_are_one_line() { let value = json!({"report": {"photos": 3, "collections": 0, "warnings": ["w1", "w2"], "skipped": [ {"image": 7, "reason": "missingFile"}, {"image": 8, "reason": "missingRoot"}, {"image": 9, "reason": "masterSkipped"}, ]}}); - let details = |locale| { - crate::i18n::set_language(locale); - let dialog = result_dialog(&value, "done"); - crate::i18n::set_language(crate::i18n::Locale::En); - let crate::state::Dialog::LightroomResult { details, .. } = dialog else { panic!("not a Lightroom result") }; - details - }; - let en = details(crate::i18n::Locale::En); + crate::i18n::set_language(crate::i18n::Locale::En); + let crate::state::Dialog::LightroomResult { details: en, .. } = result_dialog(&value, "done") else { panic!("not a Lightroom result") }; assert_eq!(en.len(), 4, "{en:?}"); assert_eq!(en[1], "3 catalog images were not imported because their records in the catalog are incomplete."); assert_eq!(&en[2..], ["w1", "w2"]); - let es = details(crate::i18n::Locale::Es); - assert_eq!(es[1], "No se importaron 3 imágenes del catálogo porque sus registros en el catálogo están incompletos."); } #[test] diff --git a/crates/ui-egui/src/menu_level.rs b/crates/ui-egui/src/menu_level.rs index 96ff422f41..611812901f 100644 --- a/crates/ui-egui/src/menu_level.rs +++ b/crates/ui-egui/src/menu_level.rs @@ -15,8 +15,9 @@ const EDGE: f32 = 6.0; /// How fast resting on a scroll arrow scrolls, in points per second. const SPEED: f32 = 600.0; +/// The egui temp-data id holding the row a menu at `depth` hangs from. fn anchor_id(depth: usize) -> Id { - Id::new(("lc-menu-anchor", depth)) + Id::unique(("lc-menu-anchor", depth)) } /// Remember the row the submenu at `depth` (2 = a top-level menu's submenu) hangs from. It is @@ -76,7 +77,7 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOn let screen = ctx.content_rect(); // The menu frame's margin and stroke around the rows. let frame = ui.spacing().menu_margin.sum().y + 2.0; - let key = ui.id().with(("lc-menu-level", depth)); + let key = ui.scope_id().with(("lc-menu-level", depth)); // Rows' height from the last frame: does this level overflow? let content: Option<f32> = ctx.data(|d| d.get_temp(key)); let room = level_room(screen, bar_bottom, depth, anchor(&ctx, depth), content, frame); @@ -89,21 +90,27 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOn // No scrollbar: the ▲ / ▼ strips, the wheel and dragging scroll a menu, like native menus. // egui's floating bar is drawn over the rows' right edge, where the shortcut text ends, and in // its wide (hovered) state its background hides the last character (issue #691). - let out = egui::ScrollArea::vertical() + // 0.37's `ScrollAreaState.offset` is private: a scroll requested after layout is applied as + // the next frame's start offset instead of writing the state directly. + let scroll_to = ctx.data_mut(|d| d.remove_temp::<f32>(key.with("scroll-to"))); + let mut area = egui::ScrollArea::vertical() .id_salt(("menu-level", depth)) .max_height(height) .min_scrolled_height(height) .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) - .scroll_source(egui::containers::scroll_area::ScrollSource::ALL) - .show(ui, rows); + .scroll_source(egui::containers::scroll_area::ScrollSource::ALL); + if let Some(y) = scroll_to { + area = area.vertical_scroll_offset(y); + } + let out = area.show(ui, rows); let down = over.then(|| ui.allocate_exact_size(vec2(0.0, ARROW), Sense::hover()).0); ctx.data_mut(|d| d.insert_temp(key, out.content_size.y)); - crate::widgets::register(&ctx, format!("menu-level:{depth}"), ui.min_rect()); + crate::widgets::register(ui, format!("menu-level:{depth}"), ui.min_rect()); let (Some(up), Some(down)) = (up, down) else { return }; let t = crate::theme::Tokens::get(&ctx); let x = ui.min_rect().x_range(); let max = (out.content_size.y - out.inner_rect.height()).max(0.0); - let offset = out.state.offset.y; + let offset = out.state.clamped_offset().y; let dt = ctx.input(|i| i.stable_dt).clamp(0.0, 0.1); let mut target = offset; for (strip, dir, live) in [(up, -1.0, offset > 0.5), (down, 1.0, offset < max - 0.5)] { @@ -118,7 +125,7 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOn let id = key.with(dir < 0.0); let r = ui.interact(strip, id, Sense::hover()); r.widget_info(|| { - egui::WidgetInfo::labeled(egui::WidgetType::Button, live, crate::i18n::tr(if dir < 0.0 { "Scroll menu up" } else { "Scroll menu down" })) + egui::WidgetInfo::labeled(egui::Role::Button, live, crate::i18n::tr(if dir < 0.0 { "Scroll menu up" } else { "Scroll menu down" })) }); if live && pointer_on(ui, strip) { target = (offset + dir * SPEED * dt.max(1.0 / 120.0)).clamp(0.0, max); @@ -132,10 +139,9 @@ pub fn level(ui: &mut Ui, depth: usize, bar_bottom: Option<f32>, rows: impl FnOn } } } - if target != offset { - let mut st = out.state; - st.offset.y = target; - st.store(&ctx, out.id); + if (target - offset).abs() > 0.01 { + ctx.data_mut(|d| d.insert_temp(key.with("scroll-to"), target)); + ctx.request_repaint(); } } diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index 1ac3e99265..ba4a8a7c29 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -48,6 +48,7 @@ pub fn display_item_label<'a>(id: &str, params: &Value, label: &'a str) -> &'a s if matches!(id, "metadata.applyPreset" | "album.addPhotos" | "label.applySet") || (id == "app.export" && params.get("preset").is_some()) || (id == "app.openLibrary" && params.get("path").is_some()) + || (id == "app.recentLibraries" && params.get("remove").is_some()) { label } else { @@ -55,6 +56,67 @@ pub fn display_item_label<'a>(id: &str, params: &Value, label: &'a str) -> &'a s } } +/// Whether AppKit offers a shortcut to its menu instead of the window. Plain letters stay +/// with egui even when the native menu displays them as key equivalents. +pub fn native_menu_delivers(sc: &str) -> bool { + sc.split('+').any(|part| matches!(part, "Cmd" | "Ctrl") || part.strip_prefix('F').is_some_and(|n| n.parse::<u8>().is_ok())) +} + +/// Native label and accelerator for a menu row. A grid row may borrow the cycle key as a +/// hint, but must not consume a modified key and turn cycling into direct grid selection. +/// AppKit has no separate shortcut-hint column: borrowed native-owned keys are appended to +/// the translated label instead, leaving their dispatch with egui. Ordinary G stays in the +/// native key-equivalent column because AppKit never hands it to the menu. +pub fn native_item_presentation<'a>( + keymap: &crate::shortcuts::Keymap, + id: &str, + params: &Value, + label: &str, + shortcut: Option<&'a str>, +) -> (String, Option<&'a str>) { + let label = display_item_label(id, params, label); + let borrowed = matches!(id, "view.photoGrid" | "view.squareGrid") && shortcut != crate::shortcuts::shortcut_of(keymap, id); + match shortcut.filter(|sc| borrowed && native_menu_delivers(sc)) { + Some(sc) => (format!("{label} ({})", shortcut_text(sc, true)), None), + None => (label.to_string(), shortcut), + } +} + +/// Cache key for native menu structure and effective accelerator ownership. A transfer from +/// a direct grid binding to a borrowed cycle hint must rebuild native handles and republish +/// their owned shortcuts even when the visible menu model is identical. +pub fn native_menu_structure(bar: &[(String, Vec<MenuNode>)], keymap: &crate::shortcuts::Keymap) -> String { + /// Add stable identities and effective native keys; live checked values stay outside the cache key. + fn walk(n: &[MenuNode], out: &mut String, keymap: &crate::shortcuts::Keymap) { + for x in n { + match x { + MenuNode::Item { id, params, label, checked, shortcut, .. } => { + out.push_str(&MenuNode::key(id, params)); + out.push(if checked.is_some() { 'c' } else { 'i' }); + out.push_str(shortcut.as_deref().unwrap_or("")); + // A key can change owners while both visible hints stay identical. + out.push('|'); + out.push_str(native_item_presentation(keymap, id, params, label, shortcut.as_deref()).1.unwrap_or("")); + } + MenuNode::Separator => out.push('-'), + MenuNode::Submenu { label, children } => { + out.push('['); + out.push_str(label); + walk(children, out, keymap); + out.push(']'); + } + } + out.push(';'); + } + } + let mut s = format!("{};", crate::i18n::language().code()); + for (t, items) in bar { + s.push_str(t); + walk(items, &mut s, keymap); + } + s +} + /// Top-level menus in order (the macOS app menu is added by the host). pub const MENUS: &[&str] = &["File", "Edit", "View", "Photo", "Window", "Help"]; @@ -172,6 +234,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "@Sort", "@Stacks", "view.filterBar", + "library.toggleFilters", "library.clearFilter", "library.refresh", "library.holdView", @@ -259,6 +322,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "app.systemInfo", "app.openLogFolder", "---", + "app.checkForUpdates", "app.about", ], ), @@ -341,6 +405,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option<bool> { "view.focusPoint" => Some(u.settings.focus_point), "view.zoomToFocus" => Some(u.settings.zoom_to_focus), "view.filmstrip" => Some(u.filmstrip), + "view.frameRate" => Some(u.frame_rate), "view.histogram" => Some(u.histogram), "view.clipping" => Some(u.show_clipping), "view.visualizeHdr" => Some(u.hdr_visualize), @@ -353,6 +418,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option<bool> { "view.beforeAfterSplit" => Some(u.before_after == crate::state::BeforeAfter::Split), "view.autoAdvance" => Some(u.auto_advance), "view.filterBar" => Some(u.filter_bar), + "library.toggleFilters" => Some(!app.session.filters_off()), "view.soloSections" => Some(u.single_panel), "view.navigator" => Some(u.navigator), "view.layoutImage" => Some(u.layout_image.show && !u.layout_image.path.trim().is_empty()), @@ -545,7 +611,7 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>> item( "view.layoutImage", Value::Null, - "Show Layout Image", + "Layout Image", crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "view.layoutImage"), chosen, Some(li.show && chosen), @@ -631,23 +697,28 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>> "Open Recent Library" => { let can = crate::panels::settings::can_switch_library(app).is_ok(); let open = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()); - let mut v: Vec<MenuNode> = app - .ui - .settings - .recent_libraries + let recent = &app.ui.settings.recent_libraries; + let label = |r: &str| { + let d = std::path::Path::new(r); + format!("{} — {}", crate::panels::settings::library_name(d), d.parent().map(|p| p.display().to_string()).unwrap_or_default()) + }; + let mut v: Vec<MenuNode> = recent .iter() .map(|r| { let d = std::path::Path::new(r); - // a missing library (moved, drive disconnected) is shown greyed out - let label = - format!("{} — {}", crate::panels::settings::library_name(d), d.parent().map(|p| p.display().to_string()).unwrap_or_default()); - item("app.openLibrary", json!({"path": r}), label, None, can && d.is_dir(), Some(open.as_deref() == Some(d))) + // a library a check found missing (moved, drive disconnected) is greyed out; the + // check runs on a worker (`RecentChecks`), never here: the menu is rebuilt every frame + let gone = app.recent_checks.exists(r) == Some(false); + item("app.openLibrary", json!({"path": r}), label(r), None, can && !gone, Some(open.as_deref() == Some(d))) }) .collect(); if v.is_empty() { v.push(item("app.clearRecentLibraries", Value::Null, "No Recent Libraries", None, false, None)); } else { v.push(MenuNode::Separator); + // one entry at a time, missing ones too: only the list forgets it (issue #1290) + let forget = recent.iter().map(|r| item("app.recentLibraries", json!({"remove": r}), label(r), None, true, None)).collect(); + v.push(MenuNode::Submenu { label: "Remove from List".into(), children: forget }); v.push(item("app.clearRecentLibraries", Value::Null, "Clear Recent Libraries", None, true, None)); } v @@ -737,12 +808,14 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>> }) } +/// Resolve a live menu row, including contextual keys and borrowed grid-cycle hints. fn node(app: &LightcraftApp, e: &MenuEntry) -> MenuNode { // Shift+P picks and advances in Library; don't advertise it on Presets in those views. let shortcut = if e.id == "panel.presets" && crate::shortcuts::library_grid(app) { None } else { e.shortcut.as_deref() }; // in an album the Delete key removes from the album (issue #1805): the menu says so let delete_key = crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "photo.delete"); let shortcut = match e.id.as_str() { + "view.photoGrid" | "view.squareGrid" => shortcut.or_else(|| crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "view.gridToggle")), "album.removePhotos" => delete_key, "photo.delete" if matches!(app.session.source, lightcraft_engine::LibrarySource::Album(_)) => None, _ => shortcut, @@ -861,13 +934,62 @@ pub fn run_item(app: &mut LightcraftApp, id: &str, params: Value) -> Result<Valu if id == "photo.delete" && crate::menus::confirm_delete(app) { return Ok(Value::Null); } + let was = app.session.active(); let r = app.run(id, params); if culling_cmd && r.is_ok() && app.ui.auto_advance { - crate::panels::compare::advance(app); + crate::panels::compare::advance(app, was); } r } +/// What the native menu bar may do with one command it queued. +/// +/// AppKit delivers menu accelerators and clicks straight to the host, so they never pass through +/// [`crate::shortcuts::handle`]. The explicit policy below is the equivalent guard for that path. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NativeCommand { + /// Run the command through the ordinary menu path. + Run, + /// Quit stays available: the host still runs the existing tasks/unsaved-changes confirmation. + Quit, + /// A quit/settings notice or the blocking library window owns input: drop the command. + Blocked, +} + +/// The safety policy for commands queued by the native menu bar. +/// +/// While a prompt or the blocking library window owns input, no queued command may act on the +/// library behind it — including Settings… and About, which would otherwise open their dialog +/// behind the blocking window. Quit is the one exception: the window itself offers Quit, and the +/// host's existing confirmation ([`crate::panels::notices::may_close`]) still decides whether the +/// process may end. +pub fn native_command_policy(app: &LightcraftApp, id: &str) -> NativeCommand { + if id == "app.quit" { + return NativeCommand::Quit; + } + if crate::panels::notices::blocks_input(app) || crate::panels::library_problem::blocks_dialog_input(app) { + return NativeCommand::Blocked; + } + NativeCommand::Run +} + +/// Run one command resolved from a native menu event under [`native_command_policy`]. +/// +/// The host calls this for every queued native command, so a macOS accelerator, click or About/ +/// Settings item respects the notice and blocking-library barriers. Ordinary dialogs retain +/// their existing native-menu behavior. +pub fn run_native_command(app: &mut LightcraftApp, id: &str, params: Value) -> NativeCommand { + let policy = native_command_policy(app, id); + match policy { + NativeCommand::Run => { + let _ = run_item(app, id, params); + } + NativeCommand::Blocked => log::debug!("native menu: {id} is blocked while another window owns input"), + NativeCommand::Quit => {} + } + policy +} + /// Human-readable shortcut text for menus: `Cmd+Shift+Z` → `⌘⇧Z` on macOS, `Ctrl+Shift+Z` elsewhere. pub fn shortcut_text(sc: &str, mac: bool) -> String { if mac { @@ -933,7 +1055,7 @@ pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32 .iter() .map(|(title, _)| { let r = ui.add(egui::Button::new(egui::RichText::new(crate::i18n::tr(title)).font(font.clone()).color(t.text_label)).frame(false)); - crate::widgets::register(ui.ctx(), format!("menu:{title}"), r.rect); + crate::widgets::register(ui, format!("menu:{title}"), r.rect); r }) .collect(); @@ -954,7 +1076,7 @@ pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32 ui.spacing_mut().item_spacing.x = saved; } else { let r = ui.add(egui::Button::new(egui::RichText::new(crate::i18n::tr("Menu")).font(font.clone()).color(t.text_label)).frame(false)); - crate::widgets::register(ui.ctx(), "menu:all", r.rect); + crate::widgets::register(ui, "menu:all", r.rect); egui::Popup::menu(&r).show(|ui| { crate::menu_level::level(ui, 1, bar_bottom, |ui| { for (title, items) in &bar { @@ -983,7 +1105,7 @@ pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32 /// Returns the menu whose title was just clicked right after a hover opened it. fn switch_open_title(ctx: &egui::Context, titles: &[egui::Response]) -> Option<egui::Id> { let popup = egui::Popup::default_response_id; - let key = egui::Id::new("lc-menubar-hover-opened"); + let key = egui::Id::unique("lc-menubar-hover-opened"); let open = titles.iter().position(|r| egui::Popup::is_id_open(ctx, popup(r))); // the menu a hover opened, until it closes or is clicked let mut confirmed = None; @@ -1022,7 +1144,7 @@ fn switch_open_title(ctx: &egui::Context, titles: &[egui::Response]) -> Option<e /// label), and while its submenu is open it is the anchor the next frame's room is measured from. fn submenu(ui: &mut egui::Ui, label: &str, text: String, depth: usize, bar_bottom: Option<f32>, children: impl FnOnce(&mut egui::Ui)) { let r = crate::widgets::menu_button(ui, text, |ui| crate::menu_level::level(ui, depth + 1, bar_bottom, children)); - crate::widgets::register(ui.ctx(), format!("menusub:{label}"), r.response.rect); + crate::widgets::register(ui, format!("menusub:{label}"), r.response.rect); if r.inner.is_some() { crate::menu_level::set_anchor(ui.ctx(), depth + 1, r.response.rect); } @@ -1048,7 +1170,7 @@ fn nodes_ui(ui: &mut egui::Ui, nodes: &[MenuNode], mac: bool, clicked: &mut Opti b = b.shortcut_text(shortcut_text(sc, mac)); } let r = ui.add_enabled(*enabled, b); - crate::widgets::register(ui.ctx(), format!("menuitem:{id}"), r.rect); + crate::widgets::register(ui, format!("menuitem:{id}"), r.rect); if *checked == Some(true) { let t = crate::theme::Tokens::get(ui.ctx()); let c = egui::Rect::from_center_size(egui::pos2(r.rect.left() + 11.0, r.rect.center().y), egui::vec2(13.0, 13.0)); @@ -1079,6 +1201,123 @@ mod tests { }) } + /// #2500: a direct-grid binding takes precedence over the borrowed cycle hint. + #[test] + fn grid_menu_shortcut_hints_preserve_direct_bindings_and_clicks() { + let mut a = app(); + crate::shortcuts::assign(&mut a.ui.settings.keymap, "view.photoGrid", Some("Cmd+Shift+1")).unwrap(); + let bar = menu_bar(&a); + let nodes = &bar.iter().find(|(title, _)| title == "View").unwrap().1; + assert!(matches!(find(nodes, "view.photoGrid"), Some(MenuNode::Item { shortcut: Some(sc), .. }) if sc == "Cmd+Shift+1")); + assert!(matches!(find(nodes, "view.squareGrid"), Some(MenuNode::Item { shortcut: Some(sc), .. }) if sc == "G")); + // A hint never assigns the cycle key to another command. + assert_eq!(crate::shortcuts::shortcut_of(&a.ui.settings.keymap, "view.squareGrid"), None); + run_item(&mut a, "view.photoGrid", Value::Null).unwrap(); + assert_eq!(a.ui.view, ViewMode::PhotoGrid); + run_item(&mut a, "view.photoGrid", Value::Null).unwrap(); + assert_eq!(a.ui.view, ViewMode::PhotoGrid, "clicking the active row does not cycle"); + run_item(&mut a, "view.squareGrid", Value::Null).unwrap(); + assert_eq!(a.ui.view, ViewMode::SquareGrid); + run_item(&mut a, "view.gridToggle", Value::Null).unwrap(); + assert_eq!(a.ui.view, ViewMode::PhotoGrid); + } + + /// #2500: native hints never install a borrowed modifier/function key as a direct-grid + /// accelerator. Plain G remains in AppKit's shortcut column and is dispatched by egui. + #[test] + fn grid_menu_shortcut_hints_keep_native_toggle_dispatch() { + let mut keymap = crate::shortcuts::Keymap::new(); + for id in ["view.photoGrid", "view.squareGrid"] { + let (label, accelerator) = native_item_presentation(&keymap, id, &Value::Null, "Photo Grid", Some("G")); + assert_eq!(label, "Photo Grid"); + assert_eq!(accelerator, Some("G")); + assert!(!native_menu_delivers(accelerator.unwrap())); + for (key, text) in [("Cmd+Shift+G", "⌘⇧G"), ("Ctrl+G", "⌃G"), ("F3", "F3")] { + crate::shortcuts::assign(&mut keymap, "view.gridToggle", Some(key)).unwrap(); + let (label, accelerator) = native_item_presentation(&keymap, id, &Value::Null, "Photo Grid", Some(key)); + assert_eq!(label, format!("Photo Grid ({text})")); + assert_eq!(accelerator, None, "egui keeps {key}"); + } + } + crate::shortcuts::assign(&mut keymap, "view.photoGrid", Some("Cmd+Shift+1")).unwrap(); + let (label, accelerator) = native_item_presentation(&keymap, "view.photoGrid", &Value::Null, "Photo Grid", Some("Cmd+Shift+1")); + assert_eq!(label, "Photo Grid"); + assert_eq!(accelerator, Some("Cmd+Shift+1"), "the row's own shortcut is a real accelerator"); + } + + /// #2500: the control channel runs the real keyboard path exactly once and menu commands + /// continue to select their named grid after the cycle shortcut is remapped. + #[test] + fn grid_menu_shortcut_hints_preserve_control_keyboard_dispatch() { + let mut h = crate::headless::Headless::new(app(), [960.0, 720.0], 1.0); + h.app.ui.view = ViewMode::PhotoGrid; + for _ in 0..3 { + h.step(); + } + let timeout = std::time::Duration::from_secs(20); + let press = |h: &mut crate::headless::Headless, params| { + let reply = h.request("ui.key", params, timeout); + assert_eq!(reply["ok"], true, "{reply}"); + }; + press(&mut h, json!({"key": "G"})); + assert_eq!(h.app.ui.view, ViewMode::SquareGrid); + press(&mut h, json!({"key": "G"})); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + crate::shortcuts::assign(&mut h.app.ui.settings.keymap, "view.gridToggle", Some("Cmd+Shift+G")).unwrap(); + press(&mut h, json!({"key": "G"})); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + press(&mut h, json!({"key": "G", "cmd": true, "shift": true})); + assert_eq!(h.app.ui.view, ViewMode::SquareGrid); + press(&mut h, json!({"key": "G", "cmd": true, "shift": true})); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + for _ in 0..2 { + let reply = h.request("ui.menu.invoke", json!({"command": "view.squareGrid"}), timeout); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(h.app.ui.view, ViewMode::SquareGrid); + } + } + + /// #2513 review: moving a direct-grid key to the cycle command leaves the visible model + /// unchanged, but must invalidate the native cache so its old accelerator is removed. + #[test] + fn grid_menu_shortcut_hints_invalidate_native_ownership_cache() { + let mut a = app(); + crate::shortcuts::assign(&mut a.ui.settings.keymap, "view.gridToggle", None).unwrap(); + crate::shortcuts::assign(&mut a.ui.settings.keymap, "view.photoGrid", Some("Cmd+Shift+G")).unwrap(); + crate::shortcuts::assign(&mut a.ui.settings.keymap, "view.squareGrid", Some("Cmd+Shift+2")).unwrap(); + let before = menu_bar(&a); + let direct = native_menu_structure(&before, &a.ui.settings.keymap); + crate::shortcuts::assign(&mut a.ui.settings.keymap, "view.gridToggle", Some("Cmd+Shift+G")).unwrap(); + let after = menu_bar(&a); + assert_eq!(before, after, "visible hint text does not expose the ownership change"); + assert_ne!(direct, native_menu_structure(&after, &a.ui.settings.keymap), "rebuild removes the stale direct-grid accelerator"); + } + + /// #2500: grid view rows show the separate cycle command's current shortcut. + #[test] + fn grid_menu_shortcut_hints_follow_the_cycle_key() { + let mut a = app(); + let hint = |a: &LightcraftApp, id: &str| { + let bar = menu_bar(a); + let nodes = &bar.iter().find(|(title, _)| title == "View").expect("View menu").1; + match find(nodes, id).expect("grid row") { + MenuNode::Item { shortcut, .. } => shortcut.clone(), + _ => panic!("grid row must be an item"), + } + }; + for id in ["view.photoGrid", "view.squareGrid"] { + assert_eq!(hint(&a, id).as_deref(), Some("G"), "{id}"); + } + crate::shortcuts::assign(&mut a.ui.settings.keymap, "view.gridToggle", Some("Cmd+Shift+G")).unwrap(); + for id in ["view.photoGrid", "view.squareGrid"] { + assert_eq!(hint(&a, id).as_deref(), Some("Cmd+Shift+G"), "{id}"); + } + crate::shortcuts::assign(&mut a.ui.settings.keymap, "view.gridToggle", None).unwrap(); + for id in ["view.photoGrid", "view.squareGrid"] { + assert_eq!(hint(&a, id), None, "{id}"); + } + } + #[test] fn view_menu_offers_the_hold_and_the_refresh_and_checks_the_hold_while_it_is_on() { let mut a = app(); @@ -1395,6 +1634,23 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + // Regression test for #49: the in-window menu headings (File, Edit, ...) sat only egui's default + // 8 px apart, too close to read or aim at. + #[test] + fn in_window_menu_headings_are_spaced_apart() { + let mut a = app(); + a.native_menu = false; + let mut h = crate::headless::Headless::new(a, [1400.0, 900.0], 1.0); + h.step(); + h.step(); + let rect = |id: &str| h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("{id} is on screen")); + let titles: Vec<_> = ["File", "Edit", "View", "Photo", "Window", "Help"].iter().map(|t| rect(&format!("menu:{t}"))).collect(); + for pair in titles.windows(2) { + let gap = pair[1].left() - pair[0].right(); + assert!(gap >= 24.0 - 0.5, "headings {:?} and {:?} are only {gap} px apart", pair[0], pair[1]); + } + } + /// A backup the host refuses (changes still unsaved, issue #1508) says why when started from /// the menu, as a refused export does; the refusal used to reach only the control channel. #[test] @@ -1634,10 +1890,129 @@ mod tests { assert_eq!(app.session.catalog.photo(other).unwrap().meta.copyright, "© Me"); } + /// Native menu accelerators never pass through `shortcuts::handle`: a command queued by the + /// native menu must obey the same blocking-window/prompt policy. Settings… and About must not + /// open behind the blocking window, and Quit stays available for its existing confirmation. + #[test] + fn native_menu_commands_respect_the_blocking_window_policy() { + use crate::panels::library_problem::LibraryProblem; + use crate::state::Dialog; + + let mut h = crate::headless::Headless::new(app(), [1000.0, 760.0], 1.0); + h.settle(std::time::Duration::from_secs(20)); + h.app.ui.view = ViewMode::PhotoGrid; + h.app.library_problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + + assert_eq!(native_command_policy(&h.app, "app.settings"), NativeCommand::Blocked); + assert_eq!(native_command_policy(&h.app, "app.about"), NativeCommand::Blocked); + assert_eq!(native_command_policy(&h.app, "view.gridToggle"), NativeCommand::Blocked); + assert_eq!(native_command_policy(&h.app, "app.quit"), NativeCommand::Quit, "Quit keeps its own confirmation"); + assert_eq!(run_native_command(&mut h.app, "app.settings", Value::Null), NativeCommand::Blocked); + assert!(h.app.ui.dialog.is_none(), "Settings must not open behind the blocking library window"); + assert_eq!(run_native_command(&mut h.app, "app.about", Value::Null), NativeCommand::Blocked); + assert!(h.app.ui.dialog.is_none(), "About must not open behind the blocking library window"); + assert_eq!(run_native_command(&mut h.app, "view.gridToggle", Value::Null), NativeCommand::Blocked); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid, "a menu command did not act on the library behind the window"); + assert_eq!( + run_native_command(&mut h.app, "app.quit", Value::Null), + NativeCommand::Quit, + "Quit stays for the host's existing tasks/unsaved-changes confirmation" + ); + assert!(h.app.ui.dialog.is_none()); + + // The launch list owns input the same way. + let settings = crate::state::AppSettings { + recent_libraries: vec!["/no/such/library-one".into()], + library_path: "/no/such/library-one".into(), + ..Default::default() + }; + h.app.library_problem = Some(LibraryProblem::choose(&settings)); + assert_eq!(native_command_policy(&h.app, "app.about"), NativeCommand::Blocked); + assert_eq!(run_native_command(&mut h.app, "app.about", Value::Null), NativeCommand::Blocked); + assert!(h.app.ui.dialog.is_none(), "About must not open behind the launch list"); + // The launch list's own New Library prompt is not a background barrier: it keeps its + // priority instead of being treated as an unrelated dialog behind the list. + h.app.ui.dialog = Some(Dialog::TextPrompt { + title: "New Library".into(), + hint: "Library name".into(), + value: "New Library".into(), + command: "app.newLibrary".into(), + params: json!({}), + key: "name".into(), + }); + assert_eq!(native_command_policy(&h.app, "app.settings"), NativeCommand::Run, "the launch list's own prompt is not a background barrier"); + h.app.ui.dialog = None; + + // A quit/settings notice owns input in the same way. + h.app.library_problem = None; + h.app.notices.push("The settings file could not be read and was reset.".into()); + assert_eq!(native_command_policy(&h.app, "app.settings"), NativeCommand::Blocked); + assert_eq!(run_native_command(&mut h.app, "app.settings", Value::Null), NativeCommand::Blocked); + assert!(h.app.ui.dialog.is_none(), "Settings must not open behind a notice"); + + // Once nothing blocks input, the same queued command runs normally. + h.app.notices.clear(); + assert_eq!(native_command_policy(&h.app, "app.settings"), NativeCommand::Run); + assert_eq!(run_native_command(&mut h.app, "app.settings", Value::Null), NativeCommand::Run); + assert!(matches!(h.app.ui.dialog, Some(Dialog::Settings { .. })), "the command runs when no barrier owns input"); + } + #[test] fn shortcut_text_per_platform() { assert_eq!(shortcut_text("Cmd+Shift+Z", true), "⌘⇧Z"); assert_eq!(shortcut_text("Cmd+Shift+Z", false), "Ctrl+Shift+Z"); assert_eq!(shortcut_text("Delete", true), "⌫"); } + + /// Every item of a menu, submenus included. + fn flat(nodes: &[MenuNode]) -> Vec<&MenuNode> { + nodes + .iter() + .flat_map(|n| match n { + MenuNode::Submenu { children, .. } => flat(children), + MenuNode::Item { .. } => vec![n], + MenuNode::Separator => vec![], + }) + .collect() + } + + /// Given the menu bar, Then an item that turns something on or off is named for the thing, + /// with its check mark saying whether it is on: "Filmstrip ✓", never "Show Filmstrip ✓". + /// Show Original is a view (\), not a switch: it keeps Lightroom's name. + #[test] + fn toggles_are_named_for_the_thing_not_show() { + let mut a = app(); + a.ui.view = ViewMode::Detail; + let shows: Vec<String> = menu_bar(&a) + .iter() + .flat_map(|(_, items)| flat(items).into_iter().cloned().collect::<Vec<_>>()) + .filter_map(|n| match n { + MenuNode::Item { id, params, label, checked: Some(_), .. } + if params.is_null() && label.starts_with("Show ") && id != "view.showOriginal" => + { + Some(format!("{id}: {label}")) + } + _ => None, + }) + .collect(); + assert!(shows.is_empty(), "toggles named \"Show …\": {shows:#?}"); + } + + /// Given every command with a menu path, Then no two of them share a label, and none is named + /// like a menu: the menus, the keyboard shortcuts list and the control channel tell them apart + /// by name ("Detail" the view and "Detail" the Edit section were two things called the same). + #[test] + fn no_two_menu_commands_share_a_label() { + let entries = crate::menus::menu_entries(&app()); + let mut clashes = Vec::new(); + for (i, e) in entries.iter().enumerate() { + if MENUS.contains(&e.label.as_str()) { + clashes.push(format!("{} is called like the {} menu", e.id, e.label)); + } + if let Some(other) = entries[..i].iter().find(|o| o.label == e.label && o.id != e.id) { + clashes.push(format!("{} and {} are both {:?}", other.id, e.id, e.label)); + } + } + assert!(clashes.is_empty(), "{clashes:#?}"); + } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 04d43e0d34..84ec8ae0c1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -78,13 +78,13 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.gridToggle", "Grid", Some("G"), ""), ("library.selectOnlyActive", "Select Only Active Photo", Some("Cmd+Shift+D"), "Edit"), ("tool.guidedUpright", "Guided Upright", Some("Shift+G"), "Window>Tools"), - ("view.detail", "Detail", Some("D"), "View"), + ("view.detail", "Detail View", Some("D"), "View"), ("view.compare", "Compare", Some("Shift+C"), "View"), ("view.survey", "Survey", Some("N"), "View"), ("view.people", "People", None, "View"), ("view.person", "Show Person", None, ""), ("view.faceBoxes", "Face Boxes", None, "View"), - ("view.focusPoint", "Show Focus Point", Some("Alt+F"), "View"), + ("view.focusPoint", "Focus Point", Some("Alt+F"), "View"), ("view.zoomToFocus", "Zoom to Focus Point", None, "View"), ("view.reference", "Reference View", Some("Shift+R"), "View"), ("photo.setReference", "Set as Reference Photo", None, ""), @@ -95,7 +95,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.filmstrip", "Filmstrip", Some("/"), "View"), ("view.leftPanel", "My Photos Panel", Some("Cmd+Shift+L"), "View"), ("view.rightPanel", "Right Panel", None, "View"), - ("view.beforeAfter", "Compare Before and After", Some("Y"), "View"), + ("view.beforeAfter", "Before/After Side by Side", Some("Y"), "View"), ("view.beforeAfterSplit", "Before/After Split", Some("Shift+Y"), "View"), ("view.beforeAfterTopBottom", "Before/After Top/Bottom", Some("Alt+Y"), "View"), ("view.beforeAfterSplitTopBottom", "Before/After Split Top/Bottom", Some("Alt+Shift+Y"), "View"), @@ -111,23 +111,26 @@ pub const UI_COMMANDS: &[UiCommand] = &[ // Library grids only (Photo Grid, Square Grid, People): the bottom-bar slider's step by key ("view.thumbSizeUp", "Increase Grid Thumbnail Size", Some("="), "View"), ("view.thumbSizeDown", "Decrease Grid Thumbnail Size", Some("-"), "View"), - ("view.clipping", "Show Clipping", Some("J"), "View"), + ("view.clipping", "Clipping", Some("J"), "View"), ("view.visualizeHdr", "Visualize HDR", None, "View"), // in grids S expands/collapses stacks (the engine command it shadows) ("view.softProof", "Soft Proofing", Some("S"), "View"), ("view.histogram", "Histogram", Some("Cmd+Shift+H"), "View"), - ("view.maskOverlay", "Show Mask Overlay", Some("O"), "View"), + ("view.maskOverlay", "Mask Overlay", Some("O"), "View"), // Ctrl+Shift+O / Cmd+Shift+O: every mask's region at once, not just the selected one - ("view.maskOverlayAll", "Show All Mask Overlays", Some("Cmd+Shift+O"), "View"), + ("view.maskOverlayAll", "All Mask Overlays", Some("Cmd+Shift+O"), "View"), // Shift+O in the Masking panel (elsewhere it cycles the crop overlay) ("view.maskOverlayMode", "Cycle Mask Overlay Mode", None, "View"), ("view.maskOverlayColor", "Cycle Mask Overlay Color", None, "View"), - ("view.maskPins", "Show Mask Pins", None, "View"), + ("view.maskPins", "Mask Pins", None, "View"), // {mode?: auto | always | selected | never}: when spot and mask pins show (steps to the next // mode when omitted; Shift+H, like Classic's H for pins, since H opens Remove). View ▸ Tool // Overlay and the Remove panel list the modes. ("view.toolOverlay", "Cycle Tool Overlay", Some("Shift+H"), ""), ("view.visualizeSpots", "Visualize Spots", Some("A"), "View"), + // A while the Crop panel is open: the aspect lock as a first-class row. Visualize Spots keeps + // the key outside the panel; the two are a contextual pair in shortcuts::handle + ("crop.lockAspect", "Lock Aspect Ratio", Some("A"), ""), ("view.cropOverlay", "Cycle Crop Overlay", Some("Shift+O"), "View"), ("view.cropOverlayOrientation", "Cycle Crop Overlay Orientation", None, "View"), ("view.back", "Back to Grid", Some("Escape"), ""), @@ -136,17 +139,19 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("local.addRoot", "Add Folder to Local", None, ""), ("local.hide", "Remove from Local", None, ""), ("local.restoreHidden", "Show Hidden Local Locations", None, ""), + // {on?}: the Info panel's Target Photo / Selected Photos choice (on = Selected Photos) + ("view.infoSelectedPhotos", "Show Metadata for Selected Photos", None, ""), ("view.fullScreenPreview", "Full Screen Preview", Some("F"), "View"), ("view.lightsOut", "Lights Out", Some("Shift+L"), "View"), ("view.enterFullScreen", "Enter Full Screen", Some("Cmd+Shift+F"), "View"), ("view.infoOverlay", "Cycle Info Overlay", Some("Cmd+I"), "View"), ("view.viewOptions", "View Options…", Some("Cmd+J"), "View"), ("view.chooseLayoutImage", "Choose Layout Image…", None, "View"), - ("view.layoutImage", "Show Layout Image", Some("Cmd+Alt+O"), "View"), + ("view.layoutImage", "Layout Image", Some("Cmd+Alt+O"), "View"), ("view.layoutImageOpacity", "Layout Image Opacity", None, ""), ("view.layoutImageMatte", "Layout Image Matte", None, ""), ("view.navigator", "Navigator", None, "View"), - ("panel.edit", "Edit", Some("E"), "Window"), + ("panel.edit", "Edit Panel", Some("E"), "Window"), ("panel.profiles", "Profile Browser", None, "Window"), ("panel.crop", "Crop & Rotate", Some("C"), "Window"), ("panel.remove", "Remove", Some("H"), "Window"), @@ -155,6 +160,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("panel.presets", "Presets", Some("Shift+P"), "Window"), ("panel.info", "Info", Some("I"), "Window"), ("panel.keywords", "Keywords", Some("K"), "Window"), + // the Keywords panel with the cursor in its Add keyword box + ("panel.addKeywords", "Add Keywords", Some("Cmd+K"), ""), ("panel.versions", "Versions", Some("Shift+V"), "Window"), ("panel.activity", "History", None, "Window"), ("panel.close", "Close Panel", None, ""), @@ -180,7 +187,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("dialog.newAlbum", "New Album…", Some("Cmd+N"), "File"), ("dialog.newFolder", "New Folder…", Some("Cmd+Shift+N"), "File"), ("dialog.smartAlbum", "New Smart Album…", None, "File"), - ("view.photoCounts", "Show Photo Counts", None, "View"), + ("view.photoCounts", "Photo Counts", None, "View"), ("view.sidebarSection", "Show Sidebar Section", None, ""), ("view.sidebarMoveSection", "Move Sidebar Section", None, ""), ("view.sidebarReset", "Reset Sidebar Sections", None, ""), @@ -227,6 +234,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("merge.hdrPanoramaLast", "HDR Panorama with Last Settings", None, "Photo>Photo Merge"), ("file.addPhotos", "Import Photos…", Some("Cmd+Shift+I"), "File"), ("file.addFolder", "Import from Folder…", None, "File"), + // {path?, into?: open | new, name?, location?}: asks where the catalog goes unless `into` (or + // Settings) says (#2672, `lightroom_destination`) ("file.importLightroom", "Import Lightroom Catalog…", None, "File"), ("file.addFromDevice", "Import from Device", None, ""), ("file.findMissing", "Find Missing Photos…", None, "File"), @@ -254,8 +263,11 @@ pub const UI_COMMANDS: &[UiCommand] = &[ // Settings ▸ Display ("app.displayProfile", "Display Profile", None, ""), ("app.about", "About LightCraft", None, "Help"), + ("app.checkForUpdates", "Check for Updates…", None, "Help"), ("app.systemInfo", "System Info…", None, "Help"), ("app.openLogFolder", "Open Log Folder", None, "Help"), + // the frame-rate display (`frame_rate`): a debugging aid, never saved + ("view.frameRate", "Frame Rate", None, "Help>Debug"), ("app.whatsNew", "What's New", None, "Help"), ("dialog.cull", "Assisted Culling…", None, "Photo"), ("app.help", "LightCraft Help", Some("F1"), "Help"), @@ -340,7 +352,7 @@ fn import_into_album(app: &mut LightcraftApp, p: &Value, r: Result<Value, String pub fn parse_rgb(v: &Value) -> Option<[u8; 3]> { if let Some(s) = v.as_str() { let h = s.strip_prefix('#').unwrap_or(s); - if h.len() != 6 { + if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let c = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok(); @@ -656,8 +668,9 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re } else if app.ui.keyword_painter.is_some() { app.ui.keyword_painter = None; } else if app.ui.fullscreen { - app.ui.fullscreen = false; - app.ui.slideshow = None; + // Through `slideshow::end`: it also releases the held slide textures. Clearing the + // two fields directly left every rendered slide in the renderer. + crate::panels::slideshow::end(app); } else if !app.ui.tool.is_empty() { app.ui.tool.clear(); } else if app.ui.right == RightPanel::Crop && app.ui.view == ViewMode::Detail { @@ -681,7 +694,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re } "view.slideshow" => { // the photos in view, full screen, with the playback settings (see panels::slideshow) - let now = ctx.input(|i| i.time); + let now = app.tick_now(); let r = crate::panels::slideshow::start(app, p, now); if r.is_ok() { app.toast(&ctx, crate::i18n::tr("Slideshow · Space pauses · Esc ends")); @@ -689,7 +702,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re r } "slideshow.togglePause" | "slideshow.next" | "slideshow.previous" | "slideshow.end" => { - let now = ctx.input(|i| i.time); + let now = app.tick_now(); crate::panels::slideshow::command(app, id, now) } "view.slideshowOptions" => { @@ -697,11 +710,12 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re Ok(Value::Null) } "view.fullScreenPreview" => { - app.ui.fullscreen = !app.ui.fullscreen; - if !app.ui.fullscreen { - app.ui.slideshow = None; - } if app.ui.fullscreen { + // Through `slideshow::end`: it also releases the held slide textures. Clearing the + // two fields directly left every rendered slide in the renderer. + crate::panels::slideshow::end(app); + } else { + app.ui.fullscreen = true; app.ui.zoom = Zoom::Fit; app.ui.tool.clear(); let _ = app.session.end_interaction(); @@ -742,9 +756,22 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re Ok(json!({"infoOverlay": app.ui.info_overlay})) } "view.viewOptions" => { - // `info1` / `info2` set the lines for an agent; without them the window opens + // `info1` / `info2` set the lines, `briefly` the Info that Show Briefly When Photo Changes + // shows and `loupeMessages` Show message when loading or rendering photos, for an agent; + // without any of them the window opens let mut info = app.ui.settings.loupe_info; let mut set = false; + // `loupeMessages` sets Show message when loading or rendering photos + let messages = match p.get("loupeMessages") { + None => app.ui.settings.loupe_messages, + Some(v) => match v.as_bool() { + Some(on) => { + set = true; + on + } + None => return Some(Err("`loupeMessages`: true|false".into())), + }, + }; for (key, lines) in [("info1", &mut info.info1), ("info2", &mut info.info2)] { let Some(v) = p.get(key) else { continue }; match serde_json::from_value(v.clone()) { @@ -755,12 +782,20 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re } set = true; } + if let Some(v) = p.get("briefly") { + match serde_json::from_value(v.clone()) { + Ok(v) => info.briefly = v, + Err(_) => return Some(Err("`briefly`: off|basic|exposure (neither, Info 1 or Info 2)".into())), + } + set = true; + } if set { app.ui.settings.loupe_info = info; + app.ui.settings.loupe_messages = messages; } else { app.ui.dialog = Some(Dialog::ViewOptions); } - Ok(json!({"loupeInfo": app.ui.settings.loupe_info})) + Ok(json!({"loupeInfo": app.ui.settings.loupe_info, "loupeMessages": app.ui.settings.loupe_messages})) } "view.chooseLayoutImage" => { let path = match p.get("path").and_then(Value::as_str) { @@ -839,6 +874,11 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re app.ui.filmstrip = !app.ui.filmstrip; Ok(Value::Null) } + "view.frameRate" => { + // {show?: bool} (toggles when omitted) + app.ui.frame_rate = p.get("show").and_then(Value::as_bool).unwrap_or(!app.ui.frame_rate); + Ok(json!({"show": app.ui.frame_rate})) + } "view.leftPanel" => { app.ui.left_panel = !app.ui.left_panel; Ok(Value::Null) @@ -1102,6 +1142,16 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re app.ui.mask_pins = p.get("show").and_then(Value::as_bool).unwrap_or(!app.ui.mask_pins); Ok(json!({"maskPins": app.ui.mask_pins})) } + "view.infoSelectedPhotos" => { + // {on?}; no params toggles. On: the Info panel shows what the selected photos share. + let on = match p.get("on") { + None | Some(Value::Null) => !app.ui.settings.info_selected_photos, + Some(Value::Bool(on)) => *on, + Some(v) => return Some(Err(format!("view.infoSelectedPhotos: `on` must be true or false, not {v}"))), + }; + app.ui.settings.info_selected_photos = on; + Ok(json!({"on": on})) + } "view.toolOverlay" => { use crate::state::ToolOverlay; let mode = match p.get("mode") { @@ -1125,6 +1175,8 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re } Ok(Value::Null) } + // A under the Crop panel: the aspect lock (the panel's button runs the same toggle) + "crop.lockAspect" => app.run("crop.aspect", json!({"aspect": "toggle"})), "view.cropOverlay" => { use crate::state::CropOverlay::*; app.ui.crop_overlay = match app.ui.crop_overlay { @@ -1228,6 +1280,15 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re panel(app, &ctx, RightPanel::Keywords, "Keywords"); Ok(Value::Null) } + "panel.addKeywords" => { + // opens Keywording when it is folded shut; the panel stays open when pressed again + if app.ui.right != RightPanel::Keywords { + panel(app, &ctx, RightPanel::Keywords, "Keywords"); + } + app.ui.folded_sections.retain(|s| s != "keywording"); + app.ui.focus_keywords = Some(ctx.cumulative_pass_nr()); + Ok(Value::Null) + } "panel.versions" => { panel(app, &ctx, RightPanel::Versions, "Versions"); Ok(Value::Null) @@ -1394,7 +1455,15 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re Ok(Value::Null) } "dialog.captureTime" => { - let time = app.session.active().and_then(|id| app.session.catalog.photo(id)).map(|p| p.date().replace('T', " ")).unwrap_or_default(); + // a time that doesn't fully read isn't offered as the starting point (`10:0` would read as midnight) + let time = app + .session + .active() + .and_then(|id| app.session.catalog.photo(id)) + .map(|p| p.date()) + .filter(|d| lightcraft_catalog::dates::shift_iso(d, 0).is_some()) + .map(|d| d.replace('T', " ")) + .unwrap_or_default(); let mode = p.get("mode").and_then(Value::as_str).unwrap_or("set").to_string(); app.ui.dialog = Some(Dialog::CaptureTime { mode, time: time.get(..19).unwrap_or(&time).to_string(), days: 0, hours: 0, minutes: 0, zone: 0.0 }); @@ -1519,11 +1588,13 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re app.ui.dialog = Some(Dialog::About); Ok(Value::Null) } + "app.checkForUpdates" => crate::updates_ui::check(app), "photo.editInPhotoCraft" => edit_in(app, &ctx, p, true), "photo.editInExternal" => edit_in(app, &ctx, p, false), "photo.openOriginalInExternal" => open_original_in(app, &ctx, p), "dialog.cull" => { - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true }); + let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); + app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, burst_gap, similarity }); Ok(Value::Null) } "app.whatsNew" => { @@ -1614,6 +1685,11 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re import_into_album(app, p, r) } "file.importLightroom" => { + // where the catalog goes (#2672): checked before a file dialog opens + let req = match crate::lightroom_destination::Request::parse(p) { + Ok(req) => req, + Err(e) => return Some(Err(e)), + }; let path = match p.get("path").and_then(Value::as_str).map(str::to_string) { Some(path) => Some(path), None => { @@ -1626,7 +1702,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Re } }; match path { - Some(path) => app.run("library.importLightroom", json!({"path":path})), + Some(path) => crate::lightroom_destination::import(app, &path, &req), None => Ok(Value::Null), } } @@ -2407,8 +2483,14 @@ fn show_in_folders(app: &mut LightcraftApp, id: Option<lightcraft_catalog::Photo /// Photo ▸ Edit In: render a copy of each selected photo with its edits (stacked on its original) /// as Settings ▸ External Editing asks for that editor, then open them there. `p` may override the /// file (`format`, `colorSpace`, `bitDepth`) and the editor (`app`). PhotoCraft is checked first, -/// so a missing editor leaves no copy behind. +/// so a missing editor leaves no copy behind. Once the copies exist, an editor that won't open them +/// is reported in the result's `failed` (and a toast), not as an error. fn edit_in(app: &mut LightcraftApp, ctx: &egui::Context, p: &Value, photocraft: bool) -> Result<Value, String> { + // every way in (menu, shortcut, context menu, the control channel) says why nothing opened + edit_in_inner(app, ctx, p, photocraft).inspect_err(|e| app.toast(ctx, crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e))) +} + +fn edit_in_inner(app: &mut LightcraftApp, ctx: &egui::Context, p: &Value, photocraft: bool) -> Result<Value, String> { let settings = &app.ui.settings; let (file, configured) = if photocraft { let path = settings.photocraft_path.trim(); @@ -2417,11 +2499,8 @@ fn edit_in(app: &mut LightcraftApp, ctx: &egui::Context, p: &Value, photocraft: (settings.external_file, settings.external_editor.clone()) }; let editor = p.get("app").and_then(Value::as_str).map_or(configured, str::to_string); - if let Some(check) = app.services.check_editor.as_ref() - && let Err(e) = check(&editor) - { - app.toast(ctx, e.clone()); - return Err(e); + if let Some(check) = app.services.check_editor.as_ref() { + check(&editor)?; } let mut params = file.params(); if let (Some(o), Some(given)) = (params.as_object_mut(), p.as_object()) { @@ -2451,9 +2530,18 @@ fn edit_in(app: &mut LightcraftApp, ctx: &egui::Context, p: &Value, photocraft: } } } - match (failed, copies.as_slice()) { - (Some(e), _) => app.toast(ctx, crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e)), - (None, [(path, _)]) => { + let mut r = r; + if let Some(o) = r.as_object_mut() { + o.insert("failed".into(), json!(failed)); + } + if let Some(e) = failed { + // the copies are in the library already (one undo step): an error would invite a retry + // that makes another set, so the result says what failed and the toast says why + app.toast(ctx, crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e)); + return Ok(r); + } + match copies.as_slice() { + [(path, _)] => { let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); app.toast(ctx, crate::i18n::tr_format!("{name} opened for editing; it is stacked with the original", name = name)); } diff --git a/crates/ui-egui/src/merge.rs b/crates/ui-egui/src/merge.rs index 61485a2710..4dc744b6d2 100644 --- a/crates/ui-egui/src/merge.rs +++ b/crates/ui-egui/src/merge.rs @@ -104,6 +104,9 @@ pub struct MergeState { pub error: Option<String>, /// Options whose preview failed (not retried until they change). pub failed_options: Option<MergeDialog>, + /// The preview zoomed in by a click: the point of it (0..1 across and down) at the middle of + /// the box. `None` fits it in the box. Kept while the options change, to compare them there. + pub zoom: Option<(f32, f32)>, /// The last finished merge (`{id, path, …}`). pub last_result: Option<Value>, /// Photos the dialog merges (the selection when it opened). @@ -164,6 +167,7 @@ pub fn open(app: &mut LightcraftApp, command: &str) -> Result<Value, String> { app.merge.error = None; app.merge.preview = None; app.merge.preview_pixels = None; + app.merge.zoom = None; if let Some(t) = app.merge.preview_task.take() { t.cancel.store(true, Ordering::Relaxed); } @@ -365,6 +369,56 @@ fn last_failed_matches(app: &LightcraftApp, opts: &MergeDialog) -> bool { app.merge.failed_options.as_ref() == Some(opts) } +/// Where a preview of `size` pixels is drawn in `area`: fitted, or zoomed in on the point `zoom` +/// to one preview pixel per screen pixel (at least twice the fitted size), kept over the box +/// where it covers it. Returns the rectangle and the point actually at the middle. +fn preview_rect(area: egui::Rect, size: [usize; 2], ppp: f32, zoom: Option<(f32, f32)>) -> (egui::Rect, Option<(f32, f32)>) { + let (w, h) = (size[0].max(1) as f32, size[1].max(1) as f32); + let fit = (area.width() / w).min(area.height() / h); + let Some((u, v)) = zoom else { + return (egui::Rect::from_center_size(area.center(), egui::vec2(w * fit, h * fit)), None); + }; + let s = (1.0 / ppp.max(0.1)).max(fit * 2.0); + let img = egui::vec2(w * s, h * s); + // the point clicked to the middle, but no gap at an edge where the image covers the box + let axis = |t: f32, len: f32, lo: f32, centre: f32, span: f32| -> (f32, f32) { + if len <= span { + return (centre - len / 2.0, 0.5); + } + let start = (centre - t.clamp(0.0, 1.0) * len).clamp(lo + span - len, lo); + (start, (centre - start) / len) + }; + let (x, u) = axis(u, img.x, area.left(), area.center().x, area.width()); + let (y, v) = axis(v, img.y, area.top(), area.center().y, area.height()); + (egui::Rect::from_min_size(egui::pos2(x, y), img), Some((u, v))) +} + +/// Click on the preview: zoom in on the point clicked, or back out; drag pans while zoomed in. +fn preview_input(app: &mut LightcraftApp, ui: &egui::Ui, resp: &egui::Response, img: egui::Rect) { + let zoomed = app.merge.zoom.is_some(); + if resp.hovered() { + let cursor = match (zoomed, resp.dragged()) { + (false, _) => egui::CursorIcon::ZoomIn, + (true, false) => egui::CursorIcon::Grab, + (true, true) => egui::CursorIcon::Grabbing, + }; + ui.ctx().set_cursor_icon(cursor); + } + if resp.clicked() { + app.merge.zoom = if zoomed { + None + } else { + resp.interact_pointer_pos() + .map(|q| (((q.x - img.left()) / img.width()).clamp(0.0, 1.0), ((q.y - img.top()) / img.height()).clamp(0.0, 1.0))) + }; + } else if resp.dragged() + && let Some((u, v)) = app.merge.zoom + { + let d = resp.drag_delta(); + app.merge.zoom = Some((u - d.x / img.width(), v - d.y / img.height())); + } +} + /// The dialog body (options on the left, preview on the right). pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog) { let t = crate::theme::Tokens::get(ui.ctx()); @@ -372,13 +426,15 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog) // preview ui.vertical(|ui| { let box_size = egui::vec2(520.0, 360.0); - let (rect, _) = ui.allocate_exact_size(box_size, egui::Sense::hover()); + let (rect, resp) = ui.allocate_exact_size(box_size, egui::Sense::click_and_drag()); ui.painter().rect_filled(rect, 4.0, t.canvas); - crate::widgets::register(ui.ctx(), "merge.preview", rect); + crate::widgets::register(ui, "merge.preview", rect); if let Some((tex, size, _, _)) = &app.merge.preview { - let s = (box_size.x / size[0] as f32).min(box_size.y / size[1] as f32); - let r = egui::Rect::from_center_size(rect.center(), egui::vec2(size[0] as f32 * s, size[1] as f32 * s)); - ui.painter().image(tex.id(), r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + let (tex, size) = (tex.id(), *size); + let (r, zoom) = preview_rect(rect, size, ui.ctx().pixels_per_point(), app.merge.zoom); + app.merge.zoom = zoom; + ui.painter_at(rect).image(tex, r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + preview_input(app, ui, &resp, r); } if let Some(task) = &app.merge.preview_task { let (f, stage) = task.progress.lock().map(|g| g.clone()).unwrap_or_default(); @@ -497,6 +553,46 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, v: &mut f64) - mod tests { use super::*; + fn area() -> egui::Rect { + egui::Rect::from_min_size(egui::pos2(100.0, 50.0), egui::vec2(520.0, 360.0)) + } + + #[test] + fn the_preview_fits_until_clicked() { + let (r, zoom) = preview_rect(area(), [1024, 683], 1.0, None); + assert_eq!(zoom, None); + assert!((r.width() - 520.0).abs() < 0.5 && r.height() < 360.0 && (r.center() - area().center()).length() < 0.5, "{r:?}"); + } + + /// Like Lightroom's: a click zooms in to one preview pixel per screen pixel on the point clicked. + #[test] + fn a_click_zooms_in_on_the_point_clicked() { + // a panorama preview, wide enough that one pixel per pixel is more than twice the fitted size + let (r, zoom) = preview_rect(area(), [1600, 1000], 1.0, Some((0.4, 0.55))); + assert_eq!(r.size(), egui::vec2(1600.0, 1000.0)); + let (u, v) = zoom.unwrap(); + assert!((u - 0.4).abs() < 1e-4 && (v - 0.55).abs() < 1e-4, "{u} {v}"); + let at = r.min + egui::vec2(r.width() * 0.4, r.height() * 0.55); + assert!((at - area().center()).length() < 0.5, "the point clicked is in the middle: {at:?}"); + // on a Retina screen, one preview pixel per physical pixel, but always at least twice the fitted size + let (r, _) = preview_rect(area(), [1024, 683], 2.0, Some((0.5, 0.5))); + assert!((r.width() - 1040.0).abs() < 0.5, "{r:?}"); + } + + /// Zoomed in near a corner (or panned past it), the image still covers the box. + #[test] + fn a_zoomed_preview_stays_over_the_box() { + for p in [(0.0, 0.0), (1.0, 1.0), (-3.0, 7.0)] { + let (r, zoom) = preview_rect(area(), [1024, 683], 1.0, Some(p)); + assert!(r.contains_rect(area()), "{p:?}: {r:?}"); + let (u, v) = zoom.unwrap(); + assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v), "{p:?}: {u} {v}"); + } + // a wide panorama is shorter than the box: centred up and down + let (r, _) = preview_rect(area(), [1024, 120], 1.0, Some((0.9, 0.0))); + assert!((r.center().y - area().center().y).abs() < 0.5 && r.left() < area().left() && r.right() >= area().right(), "{r:?}"); + } + /// Issue #1455: a panorama held to the computer's memory, or to the largest size, says so. #[test] fn a_smaller_panorama_says_why() { diff --git a/crates/ui-egui/src/model_setup.rs b/crates/ui-egui/src/model_setup.rs index bb088eaa99..78587697eb 100644 --- a/crates/ui-egui/src/model_setup.rs +++ b/crates/ui-egui/src/model_setup.rs @@ -91,13 +91,15 @@ pub(crate) fn intercept(app: &mut LightcraftApp, command: &str, params: &Value) })) } +/// Show the pending model-setup note for `kind` in the model dialog, with a button that cancels +/// the pending action. Does nothing unless a valid denoise setup is waiting. pub(crate) fn notice(app: &mut LightcraftApp, ui: &mut egui::Ui, kind: &str) { if kind != "denoise" || !app.model_setup.denoise.as_ref().is_some_and(|r| r.valid(app)) { return; } ui.add(egui::Label::new(tr("After installation, AI Denoise will turn on for the requesting photo.")).wrap()); let r = ui.small_button(tr("Cancel pending action")); - crate::widgets::register(ui.ctx(), "modelSetup:cancel:denoise", r.rect); + crate::widgets::register(ui, "modelSetup:cancel:denoise", r.rect); if r.clicked() { let _ = app.run("modelSetup.cancel", json!({"kind": "denoise"})); } @@ -118,7 +120,12 @@ fn abandoned(app: &mut LightcraftApp) -> bool { !v["downloads"].as_array().into_iter().flatten().any(|d| matches!(d["state"].as_str(), Some("running" | "done" | "installing" | "installed"))) } -pub(crate) fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { +/// Advance a pending model setup. An abandoned setup is cancelled on any call (the +/// abandonment/download probe is not throttled); while another interaction is open it waits, and +/// otherwise it checks the photo's model state at most every 250 ms. A photo that still has no +/// model (or cannot use one) keeps waiting; otherwise denoise is enabled and the outcome reported +/// in the status line. +pub(crate) fn pump(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { if app.model_setup.denoise.is_none() { return; } @@ -132,7 +139,6 @@ pub(crate) fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { ctx.request_repaint_after(std::time::Duration::from_millis(250)); return; } - let now = ctx.input(|i| i.time); if now < app.model_setup.next_check { return; } diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index 2e4137fdaf..dffdd1c4d3 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -3,7 +3,7 @@ //! that can be cancelled. The tasks come from the engine's registry ([`lightcraft_engine::activity`]); ✕ runs //! `activity.cancel` like any other frontend would. -use egui::{Align, Layout, Margin, Rect, RichText, Sense, Stroke, pos2, vec2}; +use egui::{Align, Layout, Margin, RichText, Sense, Stroke, pos2, vec2}; use lightcraft_engine::activity::{TaskInfo, Unit}; use serde_json::json; @@ -73,7 +73,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let mut cancel = None; let mut toggle = false; let frame = egui::Frame::NONE.fill(t.chrome).stroke(Stroke::new(1.0, t.field_border)).corner_radius(6).inner_margin(Margin::same(MARGIN)); - egui::Area::new(egui::Id::new("activity-stack")).order(egui::Order::Middle).fixed_pos(pos2(8.0, t.top_bar_h + 8.0)).show(ctx, |ui| { + egui::Area::new(egui::Id::unique("activity-stack")).order(egui::Order::Middle).fixed_pos(pos2(8.0, t.top_bar_h + 8.0)).show(ctx, |ui| { // An area lays out in the size it had last frame, and the scroll area would take that as all the room there // is: the stack would never grow when rows are added. Give it the whole height below the top bar instead // (the scroll area keeps to `max_height`). @@ -96,7 +96,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { ui.add_space(4.0); let text = if hidden > 0 { tr_format!("+{n} more", n = hidden) } else { tr("Show less").to_string() }; let r = ui.add(egui::Label::new(RichText::new(text).font(t.font(11.0)).color(t.accent)).sense(Sense::click())); - register(ui.ctx(), "activity:more", r.rect); + register(ui, "activity:more", r.rect); toggle = r.clicked(); } }); @@ -132,35 +132,25 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { let (rect, resp) = ui.allocate_exact_size(vec2(CROSS, CROSS), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr("Cancel")); paint(ui.painter(), rect.shrink(2.0), Icon::Close, if resp.hovered() { t.text } else { t.icon }); - register(ui.ctx(), format!("activity:cancel:{}", task.id), rect); + register(ui, format!("activity:cancel:{}", task.id), rect); clicked = resp.on_hover_text(tr("Cancel")).clicked(); } }); - bar(ui, t, task, width); + bar(ui, task, width); let line = detail_line(task); if !line.is_empty() { ui.add(egui::Label::new(RichText::new(line).font(t.font(11.0)).color(t.text_dim)).truncate()); } }); - register(ui.ctx(), format!("activity:row:{}", task.id), r.response.rect); + register(ui, format!("activity:row:{}", task.id), r.response.rect); clicked } -/// The progress bar; while the amount of work isn't known, a segment sweeps across. -fn bar(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) { - let (rect, _) = ui.allocate_exact_size(vec2(width, 5.0), Sense::hover()); - let p = ui.painter(); - p.rect_filled(rect, 2.5, t.field); - let fill = if task.total > 0 { - let frac = (task.done as f64 / task.total as f64).clamp(0.0, 1.0) as f32; - Rect::from_min_size(rect.min, vec2(rect.width() * frac, rect.height())) - } else { - let phase = (ui.input(|i| i.time) * 0.7).fract() as f32; - let w = rect.width() * 0.3; - let x = rect.left() + (rect.width() + w) * phase - w; - Rect::from_min_max(pos2(x.max(rect.left()), rect.top()), pos2((x + w).min(rect.right()), rect.bottom())) - }; - if fill.width() > 0.0 { - p.rect_filled(fill, 2.5, if task.cancelling { t.text_dim } else { t.accent }); - } +/// The progress bar, named after its task for screen readers; while the amount of work isn't +/// known, a segment sweeps across. +pub(crate) fn bar(ui: &mut egui::Ui, task: &TaskInfo, width: f32) -> egui::Response { + let fraction = (task.total > 0).then(|| (task.done as f64 / task.total as f64) as f32); + let response = crate::progress::Progress::new(fraction).width(width).dimmed(task.cancelling).show(ui); + crate::widgets::screen_reader_name(ui.ctx(), response.id, tr(&task.label)); + response } diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index 69b76bcb8c..0b48d1e34a 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -8,7 +8,7 @@ use crate::LightcraftApp; use crate::icons::{Icon, paint}; use crate::state::{ViewMode, Zoom}; use crate::theme::Tokens; -use crate::widgets::{icon_button, register, stars}; +use crate::widgets::{icon_button, register}; const VIEW_MODES: &[(&str, Icon, ViewMode, &str)] = &[ ("photoGrid", Icon::GridPhoto, ViewMode::PhotoGrid, "Photo Grid (G)"), @@ -105,7 +105,7 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: ui.new_child(egui::UiBuilder::new().max_rect(pill.shrink2(vec2(10.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); pill_ui.spacing_mut().item_spacing.x = 3.0; let rating = active.as_ref().map(|p| p.rating).unwrap_or(0); - if let Some(r) = stars(&mut pill_ui, "bottom", rating, 19.0) { + if let Some(r) = crate::rating::Rating::new("bottom", rating).show(&mut pill_ui) { let mut params = json!({"rating": r}); crate::panels::compare::target_active(app, &mut params); let _ = app.run("photo.rate", params); @@ -123,7 +123,7 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: }), flag == f, ); - register(pill_ui.ctx(), format!("flag:{id}"), r); + register(&pill_ui, format!("flag:{id}"), r); let on = flag == f && f != Flag::None; let c = if on { if f == Flag::Reject { t.reject } else { t.pick } @@ -146,9 +146,9 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: return; } let copy_r = Rect::from_min_size(pos2(pill.right() + 10.0, pill.top()), vec2(copy_width, 30.0)); - let cresp = ui.interact(copy_r, egui::Id::new("copy-settings"), Sense::click()); + let cresp = ui.interact(copy_r, egui::Id::unique("copy-settings"), Sense::click()); crate::widgets::announce(&cresp, label.to_string()); - register(ui.ctx(), "button:copySettings", copy_r); + register(ui, "button:copySettings", copy_r); ui.painter().rect_filled(copy_r, 15.0, if cresp.hovered() { t.hover } else { t.canvas }); ui.painter().text(copy_r.center(), Align2::CENTER_CENTER, label, t.font(13.0), if active.is_some() { t.text_label } else { t.text_disabled }); if cresp.clicked() && active.is_some() { @@ -157,9 +157,9 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: app.toast(ui.ctx(), crate::i18n::tr(msg)); } let gear_r = Rect::from_min_size(pos2(copy_r.right() + 4.0, pill.top()), vec2(30.0, 30.0)); - let gresp = ui.interact(gear_r, egui::Id::new("copy-gear"), Sense::click()); + let gresp = ui.interact(gear_r, egui::Id::unique("copy-gear"), Sense::click()); crate::widgets::announce(&gresp, crate::i18n::tr("Copy Settings…")); - register(ui.ctx(), "icon:copyGear", gear_r); + register(ui, "icon:copyGear", gear_r); ui.painter().rect_filled(gear_r, 15.0, if gresp.hovered() { t.hover } else { t.canvas }); paint(ui.painter(), gear_r.shrink(7.0), Icon::Gear, t.icon); if gresp.clicked() { @@ -243,7 +243,7 @@ fn right_side(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, compact_zo // thumbnail size slider let (r, resp) = child.allocate_exact_size(vec2(110.0, 20.0), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Thumbnail size")); - register(child.ctx(), "slider:thumbSize", r); + register(&child, "slider:thumbSize", r); let p = child.painter(); let y = r.center().y; p.line_segment([pos2(r.left(), y), pos2(r.right(), y)], egui::Stroke::new(2.0, t.track)); @@ -292,7 +292,7 @@ fn sort_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { // a view that holds its photos shows what matches now when asked to if app.session.hold_view { let r = ui.button(crate::i18n::tr("Refresh View")); - crate::widgets::register(ui.ctx(), "button:refreshView", r.rect); + crate::widgets::register(ui, "button:refreshView", r.rect); if r.clicked() { let _ = app.run("library.refresh", json!({})); } @@ -368,7 +368,8 @@ mod visual_regressions { harness.run_steps(4); let stem = format!("lightcraft-bottom-{view:?}-{width}-{scale}x"); harness.render().unwrap().save(directory.join(format!("{stem}.png"))).unwrap(); - let panel = egui::containers::panel::PanelState::load(&harness.ctx, egui::Id::new("bottom_bar")).unwrap().outer_rect; + let panel_id = harness.ctx.viewport_id().root_ui_id().with("bottom_bar"); + let panel = egui::containers::panel::PanelState::load(&harness.ctx, panel_id).unwrap().outer_rect; let controls: serde_json::Map<String, serde_json::Value> = crate::widgets::take_registry(&harness.ctx) .into_iter() .map(|(id, r)| (id, json!([r.left(), r.top(), r.width(), r.height()]))) diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index 30f03971b1..c18b3ad721 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -41,10 +41,16 @@ pub(crate) fn display_label(chip: &FilterChip, filter: &lightcraft_catalog::Filt return format!("{}: {}", tr("Rules"), rules_label(rules, catalog)); } if chip.clear.get("label").is_some() { - let mut labels = filter.labels.clone(); - labels.extend(filter.label.filter(|label| !labels.contains(label))); - let names = labels.iter().map(|label| crate::i18n::color_label(catalog, *label)).collect::<Vec<_>>(); - return format!("{}: {}", tr("Label"), names.join(&format!(" {} ", tr("or")))); + let shown = filter.labels_shown().unwrap_or_default(); + let name = |label: &lightcraft_catalog::ColorLabel| crate::i18n::color_label(catalog, *label); + let or = |labels: &[lightcraft_catalog::ColorLabel]| labels.iter().map(name).collect::<Vec<_>>().join(&format!(" {} ", tr("or"))); + let names = if shown.is_empty() { + let plural = if filter.labels.len() > 1 { format!("({})", or(&filter.labels)) } else { or(&filter.labels) }; + format!("{} {} {plural}", filter.label.as_ref().map(name).unwrap_or_default(), tr("and")) + } else { + or(&shown) + }; + return format!("{}: {names}", tr("Label")); } if chip.clear.get("dateFrom").is_some() || chip.clear.get("dateTo").is_some() { return match (&filter.date_from, &filter.date_to) { @@ -55,7 +61,7 @@ pub(crate) fn display_label(chip: &FilterChip, filter: &lightcraft_catalog::Filt }; } if chip.clear.get("only").is_some() { - return format!("{} {}", tr("Only"), crate::i18n::tr_format!("{n} photos", n = filter.only.len())); + return format!("{} {}", tr("Only"), crate::i18n::tr_format!("{n} photos", n = if filter.only_none { 0 } else { filter.only.len() })); } if let Some((prefix, value)) = chip.label.split_once(": ") { let value = if matches!(prefix, "Flag" | "Type") { @@ -83,7 +89,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { let t = Tokens::get(ui.ctx()); let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), HEIGHT), Sense::hover()); ui.painter().rect_filled(bar, 0.0, t.canvas); - register(ui.ctx(), "filterchips", bar); + register(ui, "filterchips", bar); let font = t.font(12.0); let right = bar.right() - 16.0; let mut x = bar.left() + 20.0; @@ -101,9 +107,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { let text_r = Rect::from_min_max(r.min, pos2(r.right() - 22.0, r.max.y)); ui.painter().with_clip_rect(text_r).text(pos2(r.left() + 10.0, r.center().y), egui::Align2::LEFT_CENTER, &label, font.clone(), t.text); let xr = Rect::from_center_size(pos2(r.right() - 12.0, r.center().y), vec2(18.0, 18.0)); - let resp = ui.interact(xr, egui::Id::new(("filter-chip-x", i)), Sense::click()).on_hover_text(crate::i18n::tr("Remove this filter")); + let resp = ui.interact(xr, egui::Id::unique(("filter-chip-x", i)), Sense::click()).on_hover_text(crate::i18n::tr("Remove this filter")); crate::widgets::announce(&resp, format!("{}: {label}", crate::i18n::tr("Remove this filter"))); - register(ui.ctx(), format!("chip:{i}"), xr); + register(ui, format!("chip:{i}"), xr); let col = if resp.hovered() { t.text } else { t.text_dim }; let m = 3.5; let (a, b) = (xr.center() - vec2(m, m), xr.center() + vec2(m, m)); diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index bb79376409..829500da47 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -164,11 +164,13 @@ pub fn survey_step(app: &mut LightcraftApp, d: isize) -> Result<Value, String> { } /// After rating/flagging with Auto Advance: next candidate (Compare), next photo in the survey, -/// else the next photo in the view. -pub fn advance(app: &mut LightcraftApp) { +/// else the next photo in the view. `was` is the active photo before the rating: a rating that took +/// it out of the view made the photo after it active already, and that is the next one (#2312). +pub fn advance(app: &mut LightcraftApp, was: Option<PhotoId>) { let _ = match app.ui.view { ViewMode::Compare => compare_step(app, 1), ViewMode::Survey => survey_step(app, 1), + _ if app.session.active() != was => Ok(Value::Null), _ => app.session.execute("library.next", &json!({})).map_err(|e| e.to_string()), }; } @@ -200,7 +202,7 @@ fn area_and_filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui) -> Rect { fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slot, area: Rect, label: &str, zoom: Zoom) -> (Rect, egui::Response) { let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let resp = ui.interact(area, egui::Id::new(("cull-tile", slot_index(slot), id.0)), Sense::click_and_drag()); + let resp = ui.interact(area, egui::Id::unique(("cull-tile", slot_index(slot), id.0)), Sense::click_and_drag()); crate::widgets::announce(&resp, app.session.catalog.photo(id).map(|p| p.file_name.clone()).unwrap_or_default()); let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, resp) }; let caption_h = 26.0; @@ -279,7 +281,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan); p.image(tex.tex.id(), display, uv, Color32::WHITE); } else { - p.rect_filled(img.intersect(img_area), 0.0, Color32::from_gray(38)); + p.rect_filled(img.intersect(img_area), 0.0, Tokens::get(ui.ctx()).skeleton); } if photo.flag == Flag::Reject { p.rect_filled(display, 0.0, Color32::from_black_alpha(110)); @@ -306,7 +308,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo let now = ui.input(|i| i.time); // (the wait belongs to the photo in the pane: one moved in starts its own) let rendering = ui.ctx().data_mut(|d| { - let (photo, wait) = d.get_temp_mut_or(egui::Id::new(("compare-rendering", i)), (id, None)); + let (photo, wait) = d.get_temp_mut_or(egui::Id::unique(("compare-rendering", i)), (id, None)); if *photo != id { (*photo, *wait) = (id, None); } @@ -343,7 +345,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo let filled = i < photo.rating; let r = Rect::from_min_size(pos2(x + i as f32 * 13.0, cap.center().y - 6.0), vec2(12.0, 12.0)); if r.right() < cap.right() { - paint(pt, r, if filled { Icon::StarFilled } else { Icon::Star }, if filled { t.star } else { t.icon.gamma_multiply(0.6) }); + crate::rating::paint_star(pt, r, filled, if filled { t.star } else { t.icon.gamma_multiply(0.6) }); } } x += 5.0 * 13.0 + 4.0; @@ -359,9 +361,9 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo && lr.right() < cap.right() { pt.circle_filled(lr.center(), 5.0, super::grid::label_color(l)); - register(ui.ctx(), format!("cull:{}:label", id.0), lr); + register(ui, format!("cull:{}:label", id.0), lr); } - register(ui.ctx(), format!("cull:{}", id.0), display); + register(ui, format!("cull:{}", id.0), display); (display, resp) } @@ -572,7 +574,7 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { // remove from the survey (deselect) on hover if resp.hovered() && photos.len() > 1 { let xr = Rect::from_min_size(pos2(img.right() - 26.0, img.top() + 6.0), vec2(20.0, 20.0)); - let xresp = ui.interact(xr, egui::Id::new(("survey-x", id.0)), Sense::click()).on_hover_text(crate::i18n::tr("Remove from survey")); + let xresp = ui.interact(xr, egui::Id::unique(("survey-x", id.0)), Sense::click()).on_hover_text(crate::i18n::tr("Remove from survey")); crate::widgets::announce(&xresp, crate::i18n::tr("Remove from survey")); ui.painter().circle_filled(xr.center(), 10.0, Color32::from_black_alpha(if xresp.hovered() { 230 } else { 160 })); paint(ui.painter(), xr.shrink(4.0), Icon::Close, t.text); diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index 437a378a74..fdb208b511 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -41,9 +41,16 @@ pub struct Ui { /// Called every frame: keeps the engine's denoise work going and asks for a redraw when a photo's picture appears (the /// loupe and the thumbnails then render from it) or while one is being made (the progress). +/// `pump_background` plus the UI-input half, for hosts/tests that have no phase split (the app's +/// own `logic` and `ui_pass` keep them apart so a hidden tick never paces work from stale input). pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { - watch_downloads(app, ctx); - let now = ctx.input(|i| i.time); + let now = app.tick_now(); + pump_ui_input(app, ctx, now); + pump_background(app, ctx, now); +} + +/// The input-reading half: fresh pointer/key activity and its timestamp. UI phase only. +pub fn pump_ui_input(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { let (working, moving) = ctx.input(|i| { let keys = i.events.iter().any(|e| matches!(e, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::MouseWheel { .. })); (i.pointer.any_down() || keys, i.pointer.is_moving()) @@ -54,6 +61,11 @@ pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { if moving || working { app.caches.last_move = now; } +} + +/// Worker results and pacing on monotonic deadlines; safe in `logic`, including while hidden. +pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { + watch_downloads(app, ctx); if now < app.caches.denoise.next_pump { return; } @@ -85,8 +97,8 @@ pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { } /// The engine's model list, re-read at most every [`REFRESH_SECS`], or at once after an action changed it. -fn models(app: &mut LightcraftApp, ctx: &egui::Context) -> Value { - let now = ctx.input(|i| i.time); +fn models(app: &mut LightcraftApp, _ctx: &egui::Context) -> Value { + let now = app.tick_now(); let epoch = app.caches.denoise.epoch; if let Some((e, at, v)) = &app.caches.denoise.list && *e == epoch @@ -134,13 +146,30 @@ pub fn detail_toggle(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, on let mut enabled = on || crate::model_setup::denoise_requested(app, id); egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 6, bottom: 2 }).show(ui, |ui| { let r = ui.add_enabled(applicable, egui::Checkbox::new(&mut enabled, crate::i18n::tr("AI Denoise"))); - register(ui.ctx(), "denoise:enabled", r.rect); + register(ui, "denoise:enabled", r.rect); if r.changed() { let _ = app.run("denoise.toggle", json!({"id": id.0, "enabled": enabled})); } }); } +/// The bar under the Denoise slider while a photo's picture is made: at most 240 px wide, and +/// sweeping while the number of tiles is not known yet. The percentage is `progress::percent`, as the +/// bar's accessible value is: 100 % only once done. +pub(crate) fn detail_bar(ui: &mut egui::Ui, done: u64, total: u64) -> egui::Response { + let fraction = crate::progress::fraction_of(done, total); + let text = match fraction { + Some(f) => tr_format!("Making the denoised picture… {}%", crate::progress::percent(f)), + None => tr("Starting…").to_string(), + }; + crate::progress::Progress::new(fraction).label(text).width(ui.available_width().min(240.0)).widget("denoise:progress").show(ui) +} + +/// The bar in Settings, AI Denoise: 380 px wide however wide the tab is. +pub(crate) fn settings_bar(ui: &mut egui::Ui, done: u64, total: u64, text: String) -> egui::Response { + crate::progress::Progress::new(crate::progress::fraction_of(done, total)).label(text).width(380.0).widget("denoise:settingsProgress").show(ui) +} + /// The line under the Denoise slider for the photo `id`, whose Amount is `amount`. pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, amount: f64) { let t = Tokens::get(ui.ctx()); @@ -156,7 +185,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am note(ui, "AI Denoise needs a model. Install one in Settings.", t.text_dim); ui.add_space(2.0); let r = ui.small_button(crate::i18n::tr("Set up AI Denoise…")); - register(ui.ctx(), "denoise:setup", r.rect); + register(ui, "denoise:setup", r.rect); if r.clicked() { let _ = app.run("denoise.toggle", json!({"id": id.0, "enabled": true})); } @@ -165,16 +194,21 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am PhotoState::Idle => { if amount > 0.0 && app.session.denoise_auto() { // the pump has not met this photo yet: let it come round soon instead of waiting out its pause - let now = ui.ctx().input(|i| i.time); + let now = app.tick_now(); app.caches.denoise.next_pump = app.caches.denoise.next_pump.min(now + 0.05); ui.ctx().request_repaint_after(std::time::Duration::from_millis(60)); - egui::Frame::NONE.inner_margin(pad).show(ui, |ui| note(ui, "Waiting to start…", t.text_dim)); + egui::Frame::NONE.inner_margin(pad).show(ui, |ui| { + ui.horizontal(|ui| { + crate::progress::spinner(ui, 12.0); + note(ui, "Waiting to start…", t.text_dim); + }) + }); } else if amount > 0.0 { egui::Frame::NONE.inner_margin(pad).show(ui, |ui| { note(ui, "Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).", t.text_dim); ui.add_space(2.0); let r = ui.small_button(crate::i18n::tr("Make it now")); - register(ui.ctx(), "denoise:make", r.rect); + register(ui, "denoise:make", r.rect); if r.clicked() { let _ = app.run("denoise.queue", json!({"ids": [id.0]})); } @@ -193,14 +227,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am } PhotoState::Running { done, total } => { egui::Frame::NONE.inner_margin(pad).show(ui, |ui| { - let frac = if total > 0 { (done as f32 / total as f32).clamp(0.0, 1.0) } else { 0.0 }; - let text = if total > 0 { - tr_format!("Making the denoised picture… {}%", (frac * 100.0).round() as u32) - } else { - tr("Starting…").to_string() - }; - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(ui.available_width().min(240.0)).text(RichText::new(text).size(11.0))); - register(ui.ctx(), "denoise:progress", bar.rect); + detail_bar(ui, done as u64, total as u64); }); } PhotoState::Failed { why, unsupported } => { @@ -209,7 +236,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am note(ui, &sentence(&why), color); if !unsupported { let r = ui.small_button(crate::i18n::tr("Try again")); - register(ui.ctx(), "denoise:retry", r.rect); + register(ui, "denoise:retry", r.rect); if r.clicked() { let _ = app.run("denoise.queue", json!({"ids": [id.0], "retry": true})); } @@ -245,8 +272,12 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { .map(|v| v["downloads"].as_array().cloned().unwrap_or_default()) .unwrap_or_default(); heading(ui, t, "Models"); - let r = ui.add_enabled(runtime && app.services.pick_denoise_model.is_some(), egui::Button::new(tr("Install from file…"))); - register(ui.ctx(), "denoise:installFile", r.rect); + let installing = downloads.iter().any(|d| d["id"] == "local-install" && d["state"].as_str() == Some("installing")); + let r = crate::button::Button::new("Install from file…") + .enabled(runtime && app.services.pick_denoise_model.is_some()) + .busy(installing) + .widget("denoise:installFile") + .show(ui); if r.clicked() && let Some(path) = app.services.pick_denoise_model.as_mut().and_then(|f| f().into_iter().next()) { @@ -304,7 +335,7 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V hint(ui, t, &device_line(&status["device"], run_on)); if run_on != "cpu" && status["device"]["retry"] == true { let r = ui.small_button(crate::i18n::tr("Try the graphics card again")); - register(ui.ctx(), "denoise:retryGpu", r.rect); + register(ui, "denoise:retryGpu", r.rect); if r.clicked() { // choosing where it runs, even the same again, forgets the failed set-up let _ = app.run("denoise.settings", json!({"runOn": run_on})); @@ -321,7 +352,6 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V let (running, queued) = (app.caches.denoise.running, app.caches.denoise.queued); match running { Some((done, total)) => { - let frac = if total > 0 { (done as f32 / total as f32).clamp(0.0, 1.0) } else { 0.0 }; let name = status["running"]["photo"] .as_u64() .and_then(|p| app.session.catalog.photo(PhotoId(p)).map(|p| p.file_name.clone())) @@ -333,8 +363,7 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V done = done, total = total ); - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(380.0).text(RichText::new(text).size(11.5))); - register(ui.ctx(), "denoise:settingsProgress", bar.rect); + settings_bar(ui, done, total, text); } None if queued > 0 => hint(ui, t, &count(queued, "photo waiting", "photos waiting")), None => { @@ -344,13 +373,13 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V } ui.horizontal(|ui| { let r = ui.button(tr("Denoise all photos with an Amount")); - register(ui.ctx(), "denoise:queueAll", r.rect); + register(ui, "denoise:queueAll", r.rect); if r.clicked() { let _ = app.run("denoise.queue", json!({"scope": "withAmount"})); } if running.is_some() || queued > 0 { let r = ui.button(tr("Stop")); - register(ui.ctx(), "denoise:stop", r.rect); + register(ui, "denoise:stop", r.rect); if r.clicked() { let _ = app.run("denoise.cancel", json!({})); } @@ -371,17 +400,18 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V ui.label(RichText::new(crate::i18n::tr("Limit")).color(t.text_label)); let current = list["cacheGb"].as_u64().unwrap_or(20) as u32; let mut choice = current; - crate::widgets::combo_box("denoise-cache-limit").selected_text(tr_format!("{size} GB", size = current)).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box("denoise-cache-limit").selected_text(tr_format!("{size} GB", size = current)).show_ui(ui, |ui| { for gb in CACHE_LIMITS { ui.selectable_value(&mut choice, gb, tr_format!("{size} GB", size = gb)); } }); + crate::widgets::name_combo(&combo.response, tr("Cache limit")); if choice != current { let _ = app.run("denoise.settings", json!({"cacheGb": choice})); app.caches.denoise.epoch += 1; } let r = ui.button(tr("Clear cache")); - register(ui.ctx(), "denoise:clear", r.rect); + register(ui, "denoise:clear", r.rect); if r.clicked() { let _ = app.run("denoise.clear", json!({})); } @@ -438,17 +468,22 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, match (dl_state, dl) { (Some("running"), Some(d)) => { let (got, total) = (d["bytes"].as_u64().unwrap_or(0), d["total"].as_u64().unwrap_or(0)); - let frac = if total > 0 { (got as f32 / total as f32).clamp(0.0, 1.0) } else { 0.0 }; let text = if total > 0 && got >= total { tr("Checking…").to_string() } else { tr_format!("{} of {} from {host}", mb(Some(got)), mb(Some(total)), host = host) }; - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(260.0).text(RichText::new(text).font(t.font(11.5)))); - register(ui.ctx(), format!("denoise:progress:{id}"), bar.rect); + crate::progress::Progress::new(crate::progress::fraction_of(got, total)) + .label(text) + .width(crate::progress::ROW_WIDTH.min(ui.available_width())) + .widget(format!("denoise:progress:{id}")) + .show(ui); } (Some("done" | "installing"), _) => { - ui.label(RichText::new(tr("Downloaded and checked. Installing…")).font(t.font(11.5)).color(t.text_dim)); + ui.horizontal(|ui| { + crate::progress::spinner(ui, 12.0); + ui.label(RichText::new(tr("Downloaded and checked. Installing…")).font(t.font(11.5)).color(t.text_dim)); + }); } (Some("failed"), Some(d)) => { let why = sentence(d["error"].as_str().unwrap_or("The download failed")); @@ -460,21 +495,21 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if installed { let r = ui.button(tr("Remove")); - register(ui.ctx(), format!("denoise:remove:{id}"), r.rect); + register(ui, format!("denoise:remove:{id}"), r.rect); if r.clicked() { let _ = app.run("denoise.models.remove", json!({"id": id})); app.caches.denoise.epoch += 1; } if selected { let r = ui.button(tr("Turn off")); - register(ui.ctx(), format!("denoise:off:{id}"), r.rect); + register(ui, format!("denoise:off:{id}"), r.rect); if r.clicked() { let _ = app.run("denoise.models.select", json!({"id": null})); app.caches.denoise.epoch += 1; } } else { let r = ui.button(tr("Use")); - register(ui.ctx(), format!("denoise:use:{id}"), r.rect); + register(ui, format!("denoise:use:{id}"), r.rect); if r.clicked() { let _ = app.run("denoise.models.select", json!({"id": id})); app.caches.denoise.epoch += 1; @@ -484,7 +519,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, match dl_state { Some("running") => { let r = ui.button(tr("Cancel")); - register(ui.ctx(), format!("denoise:cancelDownload:{id}"), r.rect); + register(ui, format!("denoise:cancelDownload:{id}"), r.rect); if r.clicked() { let _ = app.run("denoise.models.downloadCancel", json!({"id": id})); app.caches.denoise.dl_watch.retain(|w| w != &id); @@ -497,7 +532,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, let r = ui .button(tr("Open page")) .on_hover_text(tr("Opens the model's own page in your browser, to read about it or get the file yourself.")); - register(ui.ctx(), format!("denoise:get:{id}"), r.rect); + register(ui, format!("denoise:get:{id}"), r.rect); if r.clicked() { open_page(app, url); } @@ -510,7 +545,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, host = host ); let r = ui.button(tr(label)).on_hover_text(tip); - register(ui.ctx(), format!("denoise:download:{id}"), r.rect); + register(ui, format!("denoise:download:{id}"), r.rect); if r.clicked() { open_download_dialog(app, m); } @@ -573,8 +608,11 @@ fn count(n: u64, one: &str, many: &str) -> String { tr_format!("{n} {noun}", n = n, noun = tr(if n == 1 { one } else { many })) } +/// The pace to ask the denoise worker for: "light" when minimized, "normal" while unfocused, +/// "pause" shortly after input, then "light"/"full"/"normal" according to move recency and +/// whether the Denoise settings tab is being watched. pub(super) fn window_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64, watching: bool) -> &'static str { - let (focused, minimized) = ctx.input(|i| (i.focused, i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.minimized).unwrap_or(false))); + let (focused, minimized) = ctx.input(|i| (i.raw.focused, i.viewport().minimized.unwrap_or(false))); pace_for(focused, minimized, now - app.caches.last_input, now - app.caches.last_move, watching) } @@ -630,6 +668,9 @@ pub(super) fn open_page(app: &mut LightcraftApp, url: &str) { } } +/// Draw the denoise model's terms dialog from the engine's model info: unsupported files show +/// why; otherwise the name/size, download host, licence and provenance, an optional page link, +/// and the acceptance checkbox in `accepted`. pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info: &Value, accepted: &mut bool) { let kind = info["kind"].as_str().unwrap_or("unsupported"); let file = info["fileName"].as_str().unwrap_or(""); @@ -688,7 +729,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info } if let Some(url) = m["source"].as_str().or(m["licence"]["url"].as_str()) { let r = ui.link(tr("Open the model's page")); - register(ui.ctx(), "denoiseModel:page", r.rect); + register(ui, "denoiseModel:page", r.rect); if r.clicked() { open_page(app, url); } diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index b95d7b056a..5e610b098d 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -12,7 +12,7 @@ use crate::LightcraftApp; use crate::render::Slot; use crate::state::{BeforeAfter, RightPanel, ToolOverlay, Zoom}; use crate::theme::Tokens; -use crate::widgets::register; +use crate::widgets::{register, register_geometry}; /// An in-progress on-canvas gesture. #[derive(Clone, Debug)] @@ -76,6 +76,13 @@ pub enum Gesture { at: Point, acc: f32, }, + /// A drag of one of the histogram's tonal zones (see [`super::histogram`]): the control the + /// press locked and the unrounded value its sideways travel has reached. It holds no canvas + /// geometry: the zone stays locked wherever the pointer goes. + HistogramDrag { + control: &'static str, + value: f64, + }, } /// Screen ↔ normalized-image mapping for the displayed frame. @@ -187,6 +194,20 @@ pub(crate) fn pan_image(app: &mut LightcraftApp, area: Rect, img: Rect, delta: e let _ = app.run("view.navigate", json!({"pan": pan})); } +/// A drag with the middle button (the mouse wheel pressed) pans the zoomed photo whatever tool is +/// active, so the healing brush, mask brushes and crop never paint or move while you look around; +/// the hand cursor shows while it does. +fn middle_pan(app: &mut LightcraftApp, ui: &egui::Ui, resp: &egui::Response, area: Rect, img: Rect) -> bool { + if !resp.dragged_by(egui::PointerButton::Middle) { + return false; + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + if img.width() > area.width() + 1.0 || img.height() > area.height() + 1.0 { + pan_image(app, area, img, resp.drag_delta()); + } + true +} + /// Net vertical notches (up is positive) of unmodified line/page-unit wheel events: a real mouse wheel, not a trackpad. fn wheel_notches(events: &[egui::Event]) -> f32 { events @@ -211,7 +232,7 @@ pub(crate) fn navigate_gesture(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: ui.input(|i| (i.zoom_delta(), i.translation_delta(), i.multi_touch().map(|t| t.center_pos).or(i.pointer.hover_pos()))); // A notched mouse wheel (line/page units, no modifier) zooms around the pointer, through egui's smoothed wheel // delta like Ctrl+wheel (so it glides instead of jumping); trackpads report points and still pan. - let wheel_id = egui::Id::new("loupe-wheel-zoom"); + let wheel_id = egui::Id::unique("loupe-wheel-zoom"); if ui.input(|i| wheel_notches(&i.events)) != 0.0 { ui.data_mut(|d| d.insert_temp(wheel_id, true)); } @@ -306,7 +327,7 @@ pub(crate) fn focus_pan(app: &LightcraftApp, id: PhotoId) -> Option<(f32, f32)> Some((((r.x0 + r.x1) / 2.0) as f32, ((r.y0 + r.y1) / 2.0) as f32)) } -/// Draw the camera's focus box over a photo drawn in `img` (View ▸ Show Focus Point): green corner +/// Draw the camera's focus box over a photo drawn in `img` (View ▸ Focus Point): green corner /// brackets with a dark keyline, the way cameras show their AF frame, never smaller than 14 pt. /// `key` names it for tests and the control channel (`canvas:focusPoint`, `compare:focusPoint:<id>`). pub(crate) fn draw_focus_point(p: &egui::Painter, img: Rect, photo: &lightcraft_catalog::Photo, key: &str) { @@ -324,13 +345,13 @@ pub(crate) fn draw_focus_point(p: &egui::Painter, img: Rect, photo: &lightcraft_ let c = b.center(); p.circle_filled(c, 2.5, Color32::from_black_alpha(170)); p.circle_filled(c, 1.5, green); - register(p.ctx(), key, b); + register_geometry(p.ctx(), key, b); } /// Ease the loupe rect toward `target` while a click-zoom animation runs; otherwise follow it exactly. fn animated_rect(ctx: &egui::Context, anim: &mut bool, target: Rect) -> Rect { let t = if *anim { 0.22 } else { 0.0 }; - let id = egui::Id::new("loupe_anim"); + let id = egui::Id::unique("loupe_anim"); let v = |k: &str, x: f32| ctx.animate_value_with_time(id.with(k), x, t); let (c, s) = (target.center(), target.size()); let r = Rect::from_center_size(pos2(v("cx", c.x), v("cy", c.y)), vec2(v("w", s.x), v("h", s.y))); @@ -340,13 +361,35 @@ fn animated_rect(ctx: &egui::Context, anim: &mut bool, target: Rect) -> Rect { r } -/// Whether an overlay can be rendered on a region tile without changing what the tile means. -/// Mask overlays (one mask, or every visible mask at once) are evaluated from the same mask -/// alphas as the full render; the other diagnostic overlays either need whole-frame context or -/// deliberately replace the loupe. +/// View Options' Show Briefly When Photo Changes: note when the loupe changes to photo `id`, and +/// whether the brief info overlay shows this frame (until [`BRIEF_INFO_SECS`] have passed; a +/// repaint is asked for then, so it hides without input). +/// +/// [`BRIEF_INFO_SECS`]: crate::state::BRIEF_INFO_SECS +fn brief_info(app: &mut LightcraftApp, ctx: &egui::Context, id: PhotoId) { + let now = ctx.input(|i| i.time); + let brief = &mut app.ui.brief_info; + if brief.photo != Some(id) { + brief.photo = Some(id); + brief.since = now; + } + let left = crate::state::BRIEF_INFO_SECS - (now - brief.since); + brief.shown = app.ui.settings.loupe_info.briefly != crate::state::InfoOverlay::Off && left > 0.0; + if brief.shown { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(left)); + } +} + +/// Whether an overlay can be rendered on a region tile without changing what the tile means. Mask (one or all) +/// overlays are evaluated from the same mask alpha as the full render; Point Color range and Visualize +/// HDR act pixel by pixel (the HDR rendition is rendered for the same window); Visualize Spots' high +/// pass reads about 3σ = 1.8 % of the long edge, inside the window's margin +/// ([`crate::region::margin_for`]: 4.5 %). Each is tested equal to the whole-frame render's pixels. pub(crate) fn overlay_supports_window(overlay: lightcraft_pipeline::Overlay) -> bool { - use lightcraft_pipeline::Overlay; - matches!(overlay, Overlay::None | Overlay::Mask { .. } | Overlay::AllMasks { .. }) + use lightcraft_pipeline::Overlay as O; + match overlay { + O::None | O::Mask { .. } | O::AllMasks { .. } | O::PointColorRange(_) | O::HdrRange | O::Spots(_) => true, + } } /// What a window render of the loupe needs to know about the view it belongs to. @@ -455,6 +498,10 @@ fn draw_window(p: &egui::Painter, app: &LightcraftApp, c: &WindowCtx, v: &Window p.image(tex.tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } +/// Draw the Develop loupe: the optional filmstrip, the fitted or zoomed photo (before/after and +/// full-screen aware), crop overlays and the render requests for the current view, or, when no +/// photo is active, the empty-library message if the library is empty and "No photo selected" +/// otherwise. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let full = ui.max_rect(); @@ -475,6 +522,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { return; }; let Some(photo) = app.session.catalog.photo(id).cloned() else { return }; + brief_info(app, ui.ctx(), id); let d = (*photo.develop).clone(); // the full-screen preview shows the photo only: no tool overlays let right = if fullscreen { RightPanel::None } else { app.ui.right }; @@ -524,7 +572,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // another crop): a texture's whole-pixel size is a little off the exact aspect, and the crop // tool's overlays need the frame's own geometry. let display_aspect = visible_texture_aspect.filter(|a| !crop_tool && (a / aspect - 1.0).abs() > 0.02).unwrap_or(aspect); - let resp = ui.interact(canvas, egui::Id::new("loupe"), Sense::click_and_drag()); + let resp = ui.interact(canvas, egui::Id::unique("loupe"), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Photo")); let mut target_rect = fit_rect(main_area, display_aspect, app.ui.zoom, native, ppp, app.ui.pan); let mut img_rect = animated_rect(ui.ctx(), &mut app.ui.zoom_anim, target_rect); @@ -532,7 +580,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let mut navigating = false; for &view_area in &areas { let view_img = in_pane(view_area, img_rect); - if navigate_gesture(app, ui, &resp, view_area, view_img, native) { + if navigate_gesture(app, ui, &resp, view_area, view_img, native) || middle_pan(app, ui, &resp, view_area, view_img) { navigating = true; target_rect = fit_rect(main_area, display_aspect, app.ui.zoom, native, ppp, app.ui.pan); img_rect = target_rect; @@ -548,7 +596,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // a drag drafts at full size where the GPU draws the view (by the GPU's own rule, `handles`; // `ready` first: `available` would wait for a device still being created) let gpu = interacting - && lightcraft_engine::gpu::handles(lightcraft_pipeline::OutputDepth::U8, app.ui.soft_proof, overlay) + && lightcraft_engine::gpu::handles( + lightcraft_pipeline::OutputDepth::U8, + app.ui.soft_proof && lightcraft_pipeline::proof_profile(app.ui.proof.profile).is_some(), + overlay, + ) && lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::available(); let shown = app.renderer.textures.get(&Slot::Main).filter(|t| t.photo == id && t.quick.is_none()).map(|t| (t.key, t.ms)); @@ -796,9 +848,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ); p.text(canvas.center() + vec2(0.0, 12.0), Align2::CENTER_CENTER, e, t.font(12.0), t.text_dim); } - None => { + None if app.ui.settings.loupe_messages => { p.text(canvas.center(), Align2::CENTER_CENTER, crate::i18n::tr("Rendering…"), t.font(13.0), t.text_dim); } + None => {} } } } @@ -832,7 +885,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if let Some((bg, g)) = before_badge { p.rect_filled(bg, 4.0, Color32::from_black_alpha(160)); p.galley(bg.min + vec2(8.0, 4.0), g, Color32::WHITE); - register(ui.ctx(), "canvas:beforeLabel", bg); + register(ui, "canvas:beforeLabel", bg); } // the line of a wipe over both if app.ui.before_after == BeforeAfter::Split { @@ -846,7 +899,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } // View ▸ Loupe Overlay ▸ Layout Image, over the photo (the After view in a before/after) super::layout_overlay::draw(app, &p, img_rect); - register(ui.ctx(), "canvas:image", img_rect); + register(ui, "canvas:image", img_rect); let map = CanvasMap::new(&frame, img_rect); info_overlay(app, &p, canvas, &photo); if !fullscreen { @@ -935,7 +988,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { && whole.iter().chain(windows.iter().map(|(v, _)| &v.slot)).any(|s| app.renderer.is_pending(*s) && !app.renderer.retrying(*s)); let keys = [Slot::Main, Slot::Before, Slot::Region, Slot::RegionBefore].map(|s| app.renderer.textures.get(&s).filter(|t| t.photo == id).map(|t| t.key)); - let rendering = ui.ctx().data_mut(|d| rendering_overdue(d.get_temp_mut_or(egui::Id::new("loupe-rendering"), None), keys, coming, now)); + let rendering = ui.ctx().data_mut(|d| rendering_overdue(d.get_temp_mut_or(egui::Id::unique("loupe-rendering"), None), keys, coming, now)); // the render failed while a stand-in is up: what is on screen is all there will be (also while // a library change retries it) let failed = (!rendering @@ -950,9 +1003,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let over = if over.is_positive() { over } else { canvas }; match failed { Some(e) => failed_pill(ui, app, &photo, canvas, over, nav, "loupe:renderFailed", e), - None => { + // View Options' Show message when loading or rendering photos + None if app.ui.settings.loupe_messages => { loupe_pill(ui, canvas, over, nav, "loupe:rendering", crate::i18n::tr("Rendering…"), false); } + None => {} } } if let Some(why) = photo.preview_only.as_deref().filter(|_| !fullscreen) { @@ -988,7 +1043,7 @@ fn label_badge_rect(photo: Rect, pane: Rect, text: egui::Vec2, top_inset: f32) - fn info_overlay(app: &LightcraftApp, p: &egui::Painter, canvas: Rect, photo: &lightcraft_catalog::Photo) { let Some(lines) = info_overlay_lines(app, photo) else { return }; let t = Tokens::get(p.ctx()); - let mut y = canvas.top() + INFO_OVERLAY_TOP; + let mut y = canvas.top() + info_overlay_top(app, &t); for (i, l) in lines.iter().enumerate() { // laid out uncoloured: `galley` only fills placeholder text with its colour, so a white // layout made the shadow a second white copy (#1690) @@ -999,10 +1054,12 @@ fn info_overlay(app: &LightcraftApp, p: &egui::Painter, canvas: Rect, photo: &li p.galley(at, g.clone(), Color32::WHITE); y += g.size().y + INFO_OVERLAY_GAP; } - register(p.ctx(), "canvas:infoOverlay", Rect::from_min_max(canvas.min, pos2(canvas.left() + 320.0, y))); + y = overlay_badges(p, &t, pos2(canvas.left() + 14.0, y), photo); + register_geometry(p.ctx(), "canvas:infoOverlay", Rect::from_min_max(canvas.min, pos2(canvas.left() + 320.0, y))); } -/// Where the info overlay's text starts below the canvas' top, and the gap after each line. +/// Where the info overlay's text starts below the canvas' top (without window controls over it), +/// and the gap after each line. const INFO_OVERLAY_TOP: f32 = 12.0; const INFO_OVERLAY_GAP: f32 = 3.0; @@ -1011,20 +1068,31 @@ fn info_overlay_font(t: &Tokens, i: usize) -> egui::FontId { if i == 0 { t.semibold(15.0) } else { t.font(12.5) } } -/// How far below the canvas' top the info overlay's text reaches (0 when it is off), so a label -/// drawn in that corner can sit below it. +/// How far below the canvas' top the info overlay's text and badges reach (0 when it is off), so a +/// label drawn in that corner can sit below it. fn info_overlay_extent(app: &LightcraftApp, p: &egui::Painter, photo: &lightcraft_catalog::Photo) -> f32 { let Some(lines) = info_overlay_lines(app, photo) else { return 0.0 }; let t = Tokens::get(p.ctx()); - lines.iter().enumerate().fold(INFO_OVERLAY_TOP, |y, (i, l)| { + let text = lines.iter().enumerate().fold(info_overlay_top(app, &t), |y, (i, l)| { y + p.layout_no_wrap(l.clone(), info_overlay_font(&t, i), Color32::PLACEHOLDER).size().y + INFO_OVERLAY_GAP - }) + }); + text + if has_overlay_badges(photo) { OVERLAY_BADGES_H } else { 0.0 } +} + +/// Where the info overlay's text starts below the canvas' top: the full-screen preview has no top +/// bar, so on macOS it starts below the window controls that sit over the photo there (#2460). +fn info_overlay_top(app: &LightcraftApp, t: &Tokens) -> f32 { + let controls = app.ui.fullscreen && app.integrated_titlebar && !app.window_is_fullscreen; + if controls { t.top_bar_h } else { INFO_OVERLAY_TOP } } /// The info overlay's lines for `photo`, or `None` when it is off. fn info_overlay_lines(app: &LightcraftApp, photo: &lightcraft_catalog::Photo) -> Option<Vec<String>> { use crate::state::InfoOverlay; - let fields = match app.ui.info_overlay { + // with the overlay off, Show Briefly When Photo Changes shows its Info for a moment + let brief = app.ui.info_overlay == InfoOverlay::Off && app.ui.brief_info.shown; + let mode = if brief { app.ui.settings.loupe_info.briefly } else { app.ui.info_overlay }; + let fields = match mode { InfoOverlay::Off => return None, InfoOverlay::Basic => &app.ui.settings.loupe_info.info1, InfoOverlay::Exposure => &app.ui.settings.loupe_info.info2, @@ -1036,6 +1104,45 @@ fn info_overlay_lines(app: &LightcraftApp, photo: &lightcraft_catalog::Photo) -> Some(lines) } +/// The height of the info overlay's rating and flag row. +const OVERLAY_BADGES_H: f32 = 17.0; + +fn has_overlay_badges(photo: &lightcraft_catalog::Photo) -> bool { + photo.rating > 0 || photo.flag != lightcraft_catalog::Flag::None +} + +/// The star rating and flag under the info overlay's lines, when the photo has either; returns +/// the y below them. +fn overlay_badges(p: &egui::Painter, t: &Tokens, at: Pos2, photo: &lightcraft_catalog::Photo) -> f32 { + use crate::icons::{Icon, paint}; + use lightcraft_catalog::Flag; + let flag = match photo.flag { + Flag::Pick => Some((Icon::FlagPickFilled, Color32::WHITE)), + Flag::Reject => Some((Icon::FlagReject, t.reject)), + Flag::None => None, + }; + if !has_overlay_badges(photo) { + return at.y; + } + let stars = photo.rating.min(5); + let mut icons: Vec<(Icon, Color32)> = vec![(Icon::StarFilled, Color32::WHITE); stars as usize]; + icons.extend(flag); + let side = 12.0; + let mut x = at.x; + for (i, (icon, color)) in icons.into_iter().enumerate() { + // the flag stands a little apart from the stars + if i > 0 && i == stars as usize { + x += 5.0; + } + let r = Rect::from_min_size(pos2(x, at.y + 1.0), vec2(side, side)); + paint(p, r.translate(vec2(1.0, 1.0)), icon, Color32::from_black_alpha(200)); + paint(p, r, icon, color); + x += side + 2.0; + } + register_geometry(p.ctx(), "canvas:infoOverlayBadges", Rect::from_min_max(at, pos2(x, at.y + side + 2.0))); + at.y + OVERLAY_BADGES_H +} + /// What the user did to a face box this frame. enum RegionEdit { /// The × was clicked. @@ -1080,7 +1187,7 @@ fn region_overlay( let clip = p.clip_rect(); let pointer = ui.input(|i| i.pointer.hover_pos()); // the box being dragged: (region index, its box so far) - let drag_key = egui::Id::new("region-drag"); + let drag_key = egui::Id::unique("region-drag"); let live: Option<(usize, lightcraft_geom::Rect)> = ui.data(|d| d.get_temp(drag_key)); let mut edit = None; for (index, r) in photo.meta.regions.iter().enumerate() { @@ -1093,7 +1200,7 @@ fn region_overlay( if dragging.is_some() || (live.is_none() && pointer.is_some_and(|h| rect.expand(8.0).contains(h))) { for (h, (fx, fy, cursor)) in REGION_HANDLES.iter().enumerate() { let c = pos2(rect.left() + fx * rect.width(), rect.top() + fy * rect.height()); - let resp = ui.interact(Rect::from_center_size(c, vec2(14.0, 14.0)), egui::Id::new(("region-handle", index, h)), Sense::drag()); + let resp = ui.interact(Rect::from_center_size(c, vec2(14.0, 14.0)), egui::Id::unique(("region-handle", index, h)), Sense::drag()); crate::widgets::announce(&resp, crate::i18n::tr("Resize region")); if resp.hovered() || resp.dragged() { ui.ctx().set_cursor_icon(*cursor); @@ -1138,9 +1245,9 @@ fn region_overlay( } if dragging.is_none() && live.is_none() && pointer.is_some_and(|h| rect.expand(3.0).contains(h)) { let xr = Rect::from_center_size(pos2(rect.right() - 13.0, rect.top() + 13.0), vec2(16.0, 16.0)); - let resp = ui.interact(xr, egui::Id::new(("region-x", index)), Sense::click()); + let resp = ui.interact(xr, egui::Id::unique(("region-x", index)), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr("Remove region")); - register(ui.ctx(), format!("regionRemove:{index}"), xr); + register(ui, format!("regionRemove:{index}"), xr); let fill = Color32::from_black_alpha(if resp.hovered() { 235 } else { 190 }); p.rect_filled(xr, 2.0, fill); p.rect_stroke(xr, 2.0, Stroke::new(1.0, Color32::from_white_alpha(120)), StrokeKind::Inside); @@ -1188,9 +1295,9 @@ fn region_overlay( p.galley(label.min + pad, g, text_color); if is_face && live.is_none() { // a click on the label opens the name box, filled with the name or the guess - let resp = ui.interact(label, egui::Id::new(("region-label", index)), Sense::click()); + let resp = ui.interact(label, egui::Id::unique(("region-label", index)), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr("Click to name this face")); - register(ui.ctx(), format!("regionLabel:{index}"), label); + register(ui, format!("regionLabel:{index}"), label); if resp.on_hover_text(crate::i18n::tr("Click to name this face")).clicked() { let start = r.name.clone().or_else(|| hint.and_then(|h| h.suggestion.as_ref().map(|(n, _)| n.clone()))).unwrap_or_default(); *editing = Some(crate::state::NameEdit { photo: photo.id.0, index, text: start, fresh: true }); @@ -1235,9 +1342,9 @@ fn filter_pill(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect) { let inset = FILTER_PILL_INSET; let w = (g.size().x + 40.0).min((canvas.width() - 2.0 * inset).max(60.0)); let r = Rect::from_min_size(canvas.min + vec2(inset, inset), vec2(w, FILTER_PILL_HEIGHT)); - let resp = ui.interact(r, egui::Id::new("loupe-filter-pill"), Sense::click()); + let resp = ui.interact(r, egui::Id::unique("loupe-filter-pill"), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr("Filters")); - register(ui.ctx(), "loupe:filters", r); + register(ui, "loupe:filters", r); p.rect_filled(r, 10.0, Color32::from_black_alpha(if resp.hovered() { 225 } else { 185 })); let text_clip = Rect::from_min_max(r.min, pos2(r.right() - 24.0, r.max.y)); p.with_clip_rect(text_clip).galley(pos2(r.left() + 10.0, r.center().y - g.size().y / 2.0), g, Color32::from_gray(225)); @@ -1262,8 +1369,8 @@ fn preview_only_pill(ui: &mut egui::Ui, canvas: Rect, reason: &str) { p.rect_filled(r, 13.0, Color32::from_black_alpha(185)); crate::icons::paint(&p, Rect::from_center_size(pos2(r.left() + 16.0, r.center().y), vec2(15.0, 15.0)), crate::icons::Icon::Info, t.caution); p.galley(pos2(r.left() + 29.0, r.center().y - g.size().y / 2.0), g, Color32::WHITE); - register(ui.ctx(), "notice:previewOnly:loupe", r); - ui.interact(r, egui::Id::new("preview-only-pill"), Sense::hover()).on_hover_text(crate::widgets::preview_only_explanation(reason)); + register(ui, "notice:previewOnly:loupe", r); + ui.interact(r, egui::Id::unique("preview-only-pill"), Sense::hover()).on_hover_text(crate::widgets::preview_only_explanation(reason)); } /// One line of the info overlay for `photo`; `None` when the field is None or the photo has @@ -1323,7 +1430,7 @@ fn navigator(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, img: Rect p.rect_filled(frame.expand(5.0), 4.0, Color32::from_black_alpha(190)); match tex { Some(t) => p.image(t.tex.id(), frame, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), - None => p.rect_filled(frame, 0.0, Color32::from_gray(40)), + None => p.rect_filled(frame, 0.0, Tokens::get(ui.ctx()).skeleton), }; // the visible part of the photo, in normalized image coordinates let vis = canvas.intersect(img); @@ -1333,8 +1440,8 @@ fn navigator(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, img: Rect let view = Rect::from_min_max(to_nav(a), to_nav(b)); p.rect_stroke(view, 0.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Inside); p.rect_stroke(view.expand(1.5), 0.0, Stroke::new(1.0, Color32::from_black_alpha(160)), StrokeKind::Outside); - register(ui.ctx(), "canvas:navigator", frame); - let resp = ui.interact(frame.expand(5.0), egui::Id::new("navigator"), Sense::click_and_drag()); + register(ui, "canvas:navigator", frame); + let resp = ui.interact(frame.expand(5.0), egui::Id::unique("navigator"), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Navigator")); if (resp.clicked() || resp.dragged()) && let Some(q) = resp.interact_pointer_pos() @@ -1395,7 +1502,7 @@ pub(crate) fn loupe_pill(ui: &egui::Ui, canvas: Rect, over: Rect, navigator: Opt crate::icons::paint(&p, Rect::from_center_size(pos2(r.left() + 16.0, r.center().y), vec2(13.0, 13.0)), crate::icons::Icon::Info, t.caution); } p.galley(pos2(r.left() + inset, r.center().y - g.size().y / 2.0), g, Color32::from_gray(225)); - register(ui.ctx(), id, r); + register(ui, id, r); r } @@ -1416,8 +1523,8 @@ pub(crate) fn failed_pill( let offline = matches!(&photo.source, lightcraft_catalog::Source::File { path } if app.session.media.availability.is_offline(path)); let text = crate::i18n::tr(if offline { "Original offline · no smart preview" } else { "This photo can't be opened" }); let r = loupe_pill(ui, canvas, over, navigator, id, text, true); - let resp = ui.interact(r, egui::Id::new(("render-failed", id)), Sense::hover()).on_hover_text(error); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, format!("{text}: {error}"))); + let resp = ui.interact(r, egui::Id::unique(("render-failed", id)), Sense::hover()).on_hover_text(error); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text}: {error}"))); } fn quick_name(q: lightcraft_engine::media::QuickSource) -> &'static str { @@ -1641,7 +1748,7 @@ fn crop_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons // handles: 0..3 corners, 4..7 edges (top, right, bottom, left) let handles: Vec<Pos2> = (0..8).map(|i| if i < 4 { pts[i] } else { lerp(pts[i - 4], pts[(i - 3) % 4], 0.5) }).collect(); for (i, h) in handles.iter().enumerate() { - register(ui.ctx(), format!("cropHandle:{i}"), Rect::from_center_size(*h, vec2(14.0, 14.0))); + register(ui, format!("cropHandle:{i}"), Rect::from_center_size(*h, vec2(14.0, 14.0))); let s = if i < 4 { 12.0 } else { 9.0 }; p.rect_filled(Rect::from_center_size(*h, vec2(s, 3.0)), 0.0, Color32::WHITE); p.rect_filled(Rect::from_center_size(*h, vec2(3.0, s)), 0.0, Color32::WHITE); @@ -1847,7 +1954,7 @@ pub(crate) fn readout_rect(at: Pos2, size: egui::Vec2, bounds: Rect) -> Rect { /// On top of everything (the tooltip layer), so neither the photo nor a panel covers it. fn top_painter(ui: &egui::Ui, name: &'static str) -> egui::Painter { - ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new(name))) + ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique(name))) } /// The rotation pointer: a curved double arrow on a dark disc, so it reads over any photo, @@ -1857,7 +1964,7 @@ fn rotate_cursor(ui: &egui::Ui, at: Pos2, turn: f32) { let r = Rect::from_center_size(at, vec2(22.0, 22.0)); p.circle_filled(at, 12.0, Color32::from_black_alpha(150)); crate::icons::paint_turned(&p, r.shrink(2.0), crate::icons::Icon::RotateDrag, Color32::WHITE, turn); - register(ui.ctx(), "cropRotateCursor", r); + register(ui, "cropRotateCursor", r); } /// How far to turn the rotation pointer (radians, clockwise) so its arc, drawn bulging up, bulges @@ -1891,7 +1998,7 @@ fn angle_readout(ui: &egui::Ui, at: Pos2, angle: f64, bounds: Rect) { let rect = readout_rect(at, galley.size() + vec2(12.0, 6.0), bounds); p.rect_filled(rect, 4.0, Color32::from_black_alpha(170)); p.galley(rect.min + vec2(6.0, 3.0), galley, Color32::WHITE); - register(ui.ctx(), "cropAngleReadout", rect); + register(ui, "cropAngleReadout", rect); } /// Guided Upright: draw up to four guides along lines that should be vertical or horizontal. Guides are @@ -1924,7 +2031,7 @@ fn guided_overlay( }; for (i, guide) in d.geometry.guides.iter().enumerate() { let (sa, sb) = on_screen(guide); - register(ui.ctx(), format!("uprightGuide:{i}"), Rect::from_two_pos(sa, sb)); + register(ui, format!("uprightGuide:{i}"), Rect::from_two_pos(sa, sb)); draw(sa, sb, selected == Some(i)); } ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); @@ -2245,9 +2352,15 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons } for m in &d.masks { let sel = Some(m.id) == active; + // Ctrl+Shift+O (`mask_overlay_all`) shows every visible mask's region; outline each one + // too, not just the selected mask. Handles and the rotation grip stay on the selected + // mask so nothing else becomes draggable. The component check keeps this in step with the + // painted region (`view_overlay` at detail.rs:1354 only covers masks with components). + let show_outline = sel || (app.ui.mask_overlay_all && m.visible && !m.components.is_empty()); + let stroke_a: u8 = if sel { 230 } else { 170 }; for (ci, c) in m.components.iter().enumerate() { match &c.shape { - MaskShape::Radial { center, rx, ry, angle, .. } if sel => { + MaskShape::Radial { center, rx, ry, angle, .. } if show_outline => { let pts: Vec<Pos2> = (0..64) .map(|i| { let a = i as f64 / 64.0 * std::f64::consts::TAU; @@ -2257,39 +2370,44 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons map.screen(Point::new(center.x + (x * co - y * s) * l.0, center.y + (x * s + y * co) * l.1)) }) .collect(); - p.add(egui::Shape::closed_line(pts, Stroke::new(1.5, Color32::from_white_alpha(230)))); + p.add(egui::Shape::closed_line(pts, Stroke::new(1.5, Color32::from_white_alpha(stroke_a)))); + + if sel { + let l = frame_long_norm(map); + for (i, a_deg) in [0.0_f64, 90.0_f64, 180.0_f64, 270.0_f64].into_iter().enumerate() { + let a_local = a_deg.to_radians(); + let (s, co) = angle.to_radians().sin_cos(); + let (x, y) = (rx * a_local.cos(), ry * a_local.sin()); + let q = map.screen(Point::new(center.x + (x * co - y * s) * l.0, center.y + (x * s + y * co) * l.1)); + p.circle_stroke(q, 5.0, Stroke::new(1.5, Color32::WHITE)); + register(ui, format!("maskHandle:{}:{ci}:{}", m.id, i + 1), Rect::from_center_size(q, vec2(14.0, 14.0))); + grips.push((m.id, ci, i as u8 + 1, q)); + } - let l = frame_long_norm(map); - for (i, a_deg) in [0.0_f64, 90.0_f64, 180.0_f64, 270.0_f64].into_iter().enumerate() { - let a_local = a_deg.to_radians(); let (s, co) = angle.to_radians().sin_cos(); - let (x, y) = (rx * a_local.cos(), ry * a_local.sin()); - let q = map.screen(Point::new(center.x + (x * co - y * s) * l.0, center.y + (x * s + y * co) * l.1)); - p.circle_stroke(q, 5.0, Stroke::new(1.5, Color32::WHITE)); - register(ui.ctx(), format!("maskHandle:{}:{ci}:{}", m.id, i + 1), Rect::from_center_size(q, vec2(14.0, 14.0))); - grips.push((m.id, ci, i as u8 + 1, q)); + let rot_r = rx + 0.08; + let rot_q = map.screen(Point::new(center.x + (rot_r * co) * l.0, center.y + (rot_r * s) * l.1)); + let h1_q = map.screen(Point::new(center.x + (rx * co) * l.0, center.y + (rx * s) * l.1)); + p.line_segment([h1_q, rot_q], Stroke::new(1.0, Color32::from_white_alpha(200))); + p.circle_stroke(rot_q, 4.0, Stroke::new(1.5, Color32::WHITE)); + register(ui, format!("maskHandle:{}:{ci}:5", m.id), Rect::from_center_size(rot_q, vec2(14.0, 14.0))); + grips.push((m.id, ci, 5, rot_q)); } - - let (s, co) = angle.to_radians().sin_cos(); - let rot_r = rx + 0.08; - let rot_q = map.screen(Point::new(center.x + (rot_r * co) * l.0, center.y + (rot_r * s) * l.1)); - let h1_q = map.screen(Point::new(center.x + (rx * co) * l.0, center.y + (rx * s) * l.1)); - p.line_segment([h1_q, rot_q], Stroke::new(1.0, Color32::from_white_alpha(200))); - p.circle_stroke(rot_q, 4.0, Stroke::new(1.5, Color32::WHITE)); - register(ui.ctx(), format!("maskHandle:{}:{ci}:5", m.id), Rect::from_center_size(rot_q, vec2(14.0, 14.0))); - grips.push((m.id, ci, 5, rot_q)); } - MaskShape::Linear { start, end } if sel => { + MaskShape::Linear { start, end } if show_outline => { let (a, b) = (map.screen(*start), map.screen(*end)); let dir = (b - a).normalized(); let perp = vec2(-dir.y, dir.x) * 3000.0; - for (q, alpha) in [(a, 230), (b, 110)] { + let (a1, a2): (u8, u8) = if sel { (230, 110) } else { (170, 80) }; + for (q, alpha) in [(a, a1), (b, a2)] { p.line_segment([q - perp, q + perp], Stroke::new(1.0, Color32::from_white_alpha(alpha))); } - for (i, q) in [a, b].iter().enumerate() { - p.circle_stroke(*q, 5.0, Stroke::new(1.5, Color32::WHITE)); - register(ui.ctx(), format!("maskHandle:{}:{ci}:{i}", m.id), Rect::from_center_size(*q, vec2(14.0, 14.0))); - grips.push((m.id, ci, i as u8 + 1, *q)); + if sel { + for (i, q) in [a, b].iter().enumerate() { + p.circle_stroke(*q, 5.0, Stroke::new(1.5, Color32::WHITE)); + register(ui, format!("maskHandle:{}:{ci}:{i}", m.id), Rect::from_center_size(*q, vec2(14.0, 14.0))); + grips.push((m.id, ci, i as u8 + 1, *q)); + } } } _ => {} @@ -2300,7 +2418,7 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons { let q = map.screen(at); pin(&pins, q, sel); - register(ui.ctx(), format!("maskPin:{}:{ci}", m.id), Rect::from_center_size(q, vec2(14.0, 14.0))); + register(ui, format!("maskPin:{}:{ci}", m.id), Rect::from_center_size(q, vec2(14.0, 14.0))); grips.push((m.id, ci, 0, q)); } } @@ -2348,7 +2466,7 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons match app.run_typed("mask.objectPoint", json!({"x": n.x, "y": n.y, "exclude": exclude})) { Ok(_) => { if let Some(mid) = app.session.active_mask { - app.ui.detail_due = Some((ui.input(|i| i.time) + 1.0, mid)); + app.ui.detail_due = Some((app.tick_now() + 1.0, mid)); } } Err(e) => app.ai_error(ui.ctx(), e, Some(("object", "new"))), @@ -2583,11 +2701,11 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo } let dir = (tq - sq).normalized(); p.arrow(sq + dir * r, (tq - sq) - dir * (2.0 * r).min((tq - sq).length()), Stroke::new(1.0, Color32::from_white_alpha(200))); - register(ui.ctx(), format!("spotSource:{i}"), Rect::from_center_size(sq, vec2(14.0, 14.0))); + register(ui, format!("spotSource:{i}"), Rect::from_center_size(sq, vec2(14.0, 14.0))); grips.push((i, true, sq, r)); } pin(p, tq, sel); - register(ui.ctx(), format!("spotPin:{i}"), Rect::from_center_size(tq, vec2(14.0, 14.0))); + register(ui, format!("spotPin:{i}"), Rect::from_center_size(tq, vec2(14.0, 14.0))); grips.push((i, false, tq, r)); } if spot_keys(app, ui, map, d, &grips) { @@ -2698,7 +2816,7 @@ fn spot_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &De } } // where a new spot goes: the photo's centre at first, then wherever the arrows took it - let key = egui::Id::new("lc-spot-placement"); + let key = egui::Id::unique("lc-spot-placement"); let place: (f64, f64) = ui.data(|m| m.get_temp(key)).unwrap_or((0.5, 0.5)); let q = map.screen(Point::new(place.0, place.1)); let keys = crate::canvas_keys::handle( @@ -2798,6 +2916,11 @@ fn film_label(name: &str) -> String { if name.chars().nth(14).is_some() { format!("{}…", name.chars().take(13).collect::<String>()) } else { name.to_string() } } +/// Draw the horizontal filmstrip in `r`: selectable thumbnail cells with names and format when +/// film names are on, badges when film badges are on, and stack counts, following the active +/// photo and scrolling sideways with the wheel. Clicks select: Command toggles and Shift extends +/// the range; in Compare they adjust the pair's selection, and a plain click replaces the active +/// side. pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { let t = Tokens::get(ui.ctx()); ui.painter().rect_filled(r, 0.0, t.canvas); @@ -2815,10 +2938,10 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { // a vertical mouse wheel scrolls the strip sideways (horizontal trackpad scrolls still work) child.style_mut().always_scroll_the_only_direction = true; // only a new active photo (or the strip appearing) scrolls it; see `grid::follow_active` - let follow = super::grid::follow_active(child.ctx(), egui::Id::new("film-follow-active"), active, app.session.source); + let follow = super::grid::follow_active(child.ctx(), egui::Id::unique("film-follow-active"), active, app.session.source); // a wheel notch scrolls a third of its width; see `grid::wheel_step` - register(ui.ctx(), "filmstrip", child.max_rect()); - let wheel = super::grid::wheel_step(&child, egui::Id::new("film-wheel"), child.max_rect(), child.max_rect().width(), true); + register(ui, "filmstrip", child.max_rect()); + let wheel = super::grid::wheel_step(&child, egui::Id::unique("film-wheel"), child.max_rect(), child.max_rect().width(), true); egui::ScrollArea::horizontal().id_salt("filmstrip").auto_shrink([false, false]).show_viewport(&mut child, |ui, vp| { if wheel != egui::Vec2::ZERO { ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none()); @@ -2835,9 +2958,10 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { if !local.intersects(vp.expand2(vec2(cell_w * 4.0, 0.0))) { continue; } - let resp = ui.interact(cr, egui::Id::new(("film", id.0)), Sense::click()); - crate::widgets::announce(&resp, app.session.catalog.photo(*id).map(|p| p.file_name.clone()).unwrap_or_default()); - register(ui.ctx(), format!("film:{}", id.0), cr); + let resp = ui.interact(cr, egui::Id::unique(("film", id.0)), Sense::click()); + let failed = app.renderer.thumb(*id).is_none() && app.renderer.failure(Slot::Thumb(*id)).is_some(); + crate::widgets::announce(&resp, film_spoken(app.session.catalog.photo(*id).map_or("", |p| p.file_name.as_str()), failed)); + register(ui, format!("film:{}", id.0), cr); let state = app.session.selection.state_of(*id); let sel = state == lightcraft_engine::SelectionState::Active; let p = ui.painter(); @@ -2859,7 +2983,14 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { } let img_area = Rect::from_min_max(cr.min + vec2(10.0, 22.0), cr.max - vec2(10.0, 8.0)); super::grid::request_thumb(app, *id, (256.0 * ppp.min(2.0) / 2.0) as usize * 2, 8); - if let Some(tex) = app.renderer.thumb(*id) { + let thumb = app.renderer.thumb(*id); + if thumb.is_none() { + p.rect_filled(img_area, 0.0, t.skeleton); + if failed { + p.text(img_area.center(), Align2::CENTER_CENTER, "!", t.semibold(14.0), t.text); + } + } + if let Some(tex) = thumb { let [tw, th] = tex.size; let s = (img_area.width() / tw as f32).min(img_area.height() / th as f32); let fr = Rect::from_center_size(img_area.center(), vec2(tw as f32 * s, th as f32 * s)); @@ -2881,13 +3012,13 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE); let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0)); // like the grid's badge: a click expands / collapses the stack - let badge = ui.interact(br, egui::Id::new(("film-stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed { + let badge = ui.interact(br, egui::Id::unique(("film-stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed { "Stack — click to expand" } else { "Stack — click to collapse" }); crate::widgets::announce(&badge, crate::i18n::tr(if collapsed { "Expand Stack" } else { "Collapse Stack" })); - register(ui.ctx(), format!("filmstack:{}", id.0), br); + register(ui, format!("filmstack:{}", id.0), br); let p = ui.painter(); let fill = if badge.hovered() { Color32::from_black_alpha(230) } else { Color32::from_black_alpha(170) }; p.rect_filled(br, 7.5, fill); @@ -2927,6 +3058,17 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { }); } +/// What a screen reader says for a filmstrip thumbnail: the file, and why there is no picture +/// when the thumbnail failed (the painted `!` has no name of its own). The name is empty when the +/// catalog no longer has the photo (or its file name is blank); the reason then stands alone. +pub(crate) fn film_spoken(file_name: &str, failed: bool) -> String { + match (file_name.is_empty(), failed) { + (_, false) => file_name.to_string(), + (true, true) => crate::i18n::tr("This photo can't be opened").to_string(), + (false, true) => format!("{file_name}, {}", crate::i18n::tr("This photo can't be opened")), + } +} + /// Rating, flag and edited badges along a filmstrip thumbnail's bottom edge (Settings → Interface). fn film_badges(p: &egui::Painter, t: &Tokens, fr: Rect, ph: &lightcraft_catalog::Photo) { use crate::icons::{Icon, paint}; @@ -2939,10 +3081,7 @@ fn film_badges(p: &egui::Painter, t: &Tokens, fr: Rect, ph: &lightcraft_catalog: p.rect_filled(bar, 0.0, Color32::from_black_alpha(130)); let y = bar.center().y; let mut x = bar.left() + 3.0; - for i in 0..ph.rating { - paint(p, Rect::from_min_size(pos2(x + i as f32 * 9.0, y - 4.0), vec2(8.0, 8.0)), Icon::StarFilled, t.star); - } - x += ph.rating as f32 * 9.0 + 2.0; + x += crate::rating::paint_rating(p, pos2(x, y), ph.rating, crate::rating::RatingSize::Small, t.star) + 2.0; match ph.flag { Flag::Pick => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagPickFilled, t.pick), Flag::Reject => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagReject, t.reject), @@ -3047,7 +3186,7 @@ mod preview_geometry_tests { fn straighten_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, held: bool) { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !held && resp.double_clicked() { - let _ = app.run("crop.autoStraighten", json!({})); + app.auto_straighten(ui.ctx()); app.ui.tool.clear(); app.gesture = None; return; @@ -3278,7 +3417,7 @@ mod wheel_zoom_tests { use super::*; fn wheel(unit: egui::MouseWheelUnit, y: f32, modifiers: egui::Modifiers) -> egui::Event { - egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers } + egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, y), phase: egui::TouchPhase::Move, source: egui::MouseWheelSource::Unknown, modifiers } } #[test] @@ -3424,6 +3563,38 @@ mod info_overlay_tests { assert!(copies[0].r() < 64 && copies[0].a() > 0, "the shadow under it is dark: {:?}", copies[0]); } + /// View Options' Show Briefly When Photo Changes: with the overlay off, the chosen Info shows + /// for `BRIEF_INFO_SECS` after the loupe changes photo, then hides; an overlay that is on stays. + #[test] + fn show_briefly_shows_the_info_after_the_photo_changes() { + use crate::state::{BRIEF_INFO_SECS, InfoOverlay}; + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services { png: None, ..Default::default() }); + let photos: Vec<lightcraft_catalog::Photo> = app.session.catalog.photos().take(2).map(|p| (**p).clone()).collect(); + assert_eq!(photos.len(), 2, "the demo catalog has two photos"); + let ctx = egui::Context::default(); + // the loupe shows photo `i` at `time`: the lines the overlay paints then + let at = |app: &mut LightcraftApp, i: usize, time: f64| { + let raw = crate::headless::HeadlessView::raw_input(vec2(1000.0, 700.0), 1.0, time, vec![]); + let mut out = ctx.run_ui(raw, |ui| brief_info(app, ui.ctx(), photos[i].id)); + out.textures_delta.clear(); + painted_lines(app, &photos[i]) + }; + let name = |i: usize| photos[i].file_name.clone(); + assert!(at(&mut app, 0, 1.0).is_empty(), "off by default"); + app.ui.settings.loupe_info.briefly = InfoOverlay::Exposure; + let info2 = at(&mut app, 1, 2.0); + assert_eq!(info2.first(), Some(&name(1)), "Info 2 shows when the photo changes: {info2:?}"); + assert!(!at(&mut app, 1, 2.0 + BRIEF_INFO_SECS - 0.5).is_empty(), "still up"); + assert!(at(&mut app, 1, 2.0 + BRIEF_INFO_SECS + 0.1).is_empty(), "then hidden"); + assert_eq!(at(&mut app, 0, 10.0).first(), Some(&name(0)), "and shown again for the next photo"); + app.ui.settings.loupe_info.briefly = InfoOverlay::Basic; + let info1 = at(&mut app, 1, 20.0); + assert_eq!(info1.len(), 3, "Info 1's three lines: {info1:?}"); + assert_ne!(info1, info2, "Info 1, not Info 2"); + app.ui.info_overlay = InfoOverlay::Exposure; + assert_eq!(at(&mut app, 1, 30.0), info2, "an overlay that is on shows its own Info, and stays"); + } + /// The lines the overlay paints, top to bottom (each once: the shadow copies left out). fn painted_lines(app: &LightcraftApp, photo: &lightcraft_catalog::Photo) -> Vec<String> { let ctx = egui::Context::default(); @@ -3462,4 +3633,83 @@ mod info_overlay_tests { app.ui.info_overlay = InfoOverlay::Basic; assert_eq!(painted_lines(&app, &photo), Vec::<String>::new(), "nothing chosen, nothing shown"); } + + fn demo_app() -> (LightcraftApp, lightcraft_catalog::Photo) { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services { png: None, ..Default::default() }); + app.ui.info_overlay = crate::state::InfoOverlay::Basic; + let photo = app.session.catalog.photos().next().map(|p| (**p).clone()).expect("the demo catalog has photos"); + (app, photo) + } + + /// The overlay's text shapes and the rects it registered, painted on a canvas at the window's corner. + fn paint_overlay(app: &LightcraftApp, photo: &lightcraft_catalog::Photo) -> (Vec<egui::epaint::TextShape>, Vec<(String, Rect)>) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let canvas = Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 700.0)); + let raw = crate::headless::HeadlessView::raw_input(vec2(1000.0, 700.0), 1.0, 0.0, vec![]); + let mut out = ctx.run_ui(raw, |ui| info_overlay(app, ui.painter(), canvas, photo)); + out.textures_delta.clear(); + fn texts(shape: &egui::epaint::Shape, out: &mut Vec<egui::epaint::TextShape>) { + match shape { + egui::epaint::Shape::Text(t) => out.push(t.clone()), + egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut all = Vec::new(); + out.shapes.iter().for_each(|c| texts(&c.shape, &mut all)); + (all, crate::widgets::take_registry(&ctx)) + } + + fn name_top(app: &LightcraftApp, photo: &lightcraft_catalog::Photo) -> f32 { + let (texts, _) = paint_overlay(app, photo); + texts.iter().filter(|t| t.galley.job.text == photo.file_name).map(|t| t.pos.y).fold(f32::INFINITY, f32::min) + } + + /// #2460: in the full-screen preview on macOS the window controls stay at the top-left, so the + /// file name starts below them; in macOS full screen they are gone and it keeps the corner. + #[test] + fn the_file_name_clears_the_macos_window_controls_in_the_full_screen_preview() { + let (mut app, photo) = demo_app(); + app.ui.fullscreen = true; + assert_eq!(name_top(&app, &photo), 12.0, "no window controls over the photo"); + app.integrated_titlebar = true; + let bar = Tokens::get(&egui::Context::default()).top_bar_h; + assert!(name_top(&app, &photo) >= bar, "below the window controls"); + app.window_is_fullscreen = true; + assert_eq!(name_top(&app, &photo), 12.0, "macOS full screen hides the window controls"); + app.window_is_fullscreen = false; + app.ui.fullscreen = false; + assert_eq!(name_top(&app, &photo), 12.0, "the loupe's canvas starts below the top bar"); + } + + /// #2460: a rated or flagged photo shows its stars and flag under the date and size. + #[test] + fn the_info_overlay_shows_the_rating_and_flag_under_the_date() { + let (_, mut photo) = demo_app(); + let (app, _) = demo_app(); + photo.rating = 0; + photo.flag = lightcraft_catalog::Flag::None; + let badges = |photo: &lightcraft_catalog::Photo| { + paint_overlay(&app, photo).1.into_iter().find(|(id, _)| id == "canvas:infoOverlayBadges").map(|(_, r)| r) + }; + assert_eq!(badges(&photo), None, "nothing to show"); + photo.rating = 3; + let stars = badges(&photo).expect("three stars"); + photo.flag = lightcraft_catalog::Flag::Pick; + let flagged = badges(&photo).expect("three stars and a flag"); + assert!(flagged.width() > stars.width(), "the flag follows the stars: {stars:?} {flagged:?}"); + let (texts, _) = paint_overlay(&app, &photo); + let date_bottom = texts.iter().map(|t| t.pos.y + t.galley.size().y).fold(0.0, f32::max); + assert!(flagged.top() >= date_bottom, "under the date and size: {flagged:?}, text ends at {date_bottom}"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let raw = crate::headless::HeadlessView::raw_input(vec2(1000.0, 700.0), 1.0, 0.0, vec![]); + let mut extent = 0.0; + ctx.run_ui(raw, |ui| extent = info_overlay_extent(&app, ui.painter(), &photo)).textures_delta.clear(); + assert!(extent >= flagged.bottom(), "a label below the overlay clears the badges: {extent} < {flagged:?}"); + photo.rating = 0; + photo.flag = lightcraft_catalog::Flag::Reject; + assert!(badges(&photo).is_some(), "a rejected photo shows its flag alone"); + } } diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index 894ad2bd5e..f26b433255 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -28,7 +28,7 @@ pub(crate) fn rename_preview( let mut h = std::collections::hash_map::DefaultHasher::new(); (template, start, app.session.catalog.revision, &ids).hash(&mut h); let key = h.finish(); - let id = egui::Id::new("rename-preview-rows"); + let id = egui::Id::unique("rename-preview-rows"); let read = |rows: &Rows| rows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); if let Some((k, rows)) = ctx.data(|d| d.get_temp::<(u64, Rows)>(id)) && k == key @@ -82,7 +82,7 @@ fn watermark_preview( (id, app.session.catalog.revision, px).hash(&mut h); let key = h.finish(); let ctx = ui.ctx().clone(); - let (base_id, shown_id) = (egui::Id::new("export-wm-preview-base"), egui::Id::new("export-wm-preview-shown")); + let (base_id, shown_id) = (egui::Id::unique("export-wm-preview-base"), egui::Id::unique("export-wm-preview-shown")); let base = match ctx.data(|d| d.get_temp::<(u64, Base)>(base_id)) { Some((k, base)) if k == key => base, _ => { @@ -133,7 +133,14 @@ fn watermark_preview( Ok(img) => img, Err(e) => { let note = if e.is_some() { "Preview unavailable" } else { "Loading preview…" }; - let r = ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)); + let r = ui + .horizontal(|ui| { + if e.is_none() { + crate::progress::spinner(ui, 12.0); + } + ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)) + }) + .inner; if let Some(e) = e { r.on_hover_text(e); } @@ -162,7 +169,7 @@ fn watermark_preview( let size = tex.size_vec2(); let scale = ui.available_width() / size.x.max(1.0); let r = ui.vertical_centered(|ui| ui.add(egui::Image::new((tex.id(), size * scale)))).inner; - crate::widgets::register(ui.ctx(), "image:exportWatermarkPreview", r.rect); + crate::widgets::register(ui, "image:exportWatermarkPreview", r.rect); } /// About dialog tabs: (widget id suffix, label). The credits come from `crate::credits`. @@ -174,7 +181,7 @@ pub const WHATS_NEW: &str = include_str!("../../../../docs/whats-new.md"); /// The import review and Settings keep window ids of their own, so the size each is given /// doesn't carry over to the other dialogs. fn window_id(dialog: &Dialog) -> egui::Id { - egui::Id::new(match dialog { + egui::Id::unique(match dialog { Dialog::Import { .. } => "lightcraft-import-dialog", Dialog::Print => "lightcraft-print-dialog", Dialog::Settings { .. } => "lightcraft-settings-dialog", @@ -193,19 +200,28 @@ pub(crate) fn prepare(app: &LightcraftApp, ui: &mut egui::Ui) { } } -pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { +/// Draw the open dialog. `blocked` is true when a quit prompt or settings notice was on screen at +/// the start of this frame: the dialog is still drawn (its state is preserved), but none of its raw +/// keyboard/backdrop handling may act. The caller freezes `blocked` for the whole frame so the +/// click or key that dismisses the prompt cannot also reach the dialog drawn after it. The +/// blocking library-problem/launch-list window gets the same raw-input treatment while it is +/// actually on screen over this dialog; ordinary dialogs without that window keep their normal +/// Escape and outside-click behaviour. +pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { let Some(mut dlg) = app.ui.dialog.clone() else { return }; let at_start = dlg.clone(); + let library_blocks = crate::panels::library_problem::blocks_dialog_input(app); + let raw_blocked = blocked || library_blocks; // Esc with a popup open in the dialog (a dropdown, a date picker's calendar) closes the popup // only: claimed before the dialog is drawn, since the popup is gone once it has handled the key - if ctx.input(|i| i.key_pressed(egui::Key::Escape)) && egui::Popup::is_any_open(ctx) { + if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && egui::Popup::is_any_open(ctx) { crate::widgets::take_escape(ctx); } let t = Tokens::get(ctx); let screen = ctx.content_rect(); // The backdrop is an area below the dialog window (a bare `Middle` layer painter would be // painted after every area — i.e. over the dialog too). - egui::Area::new(egui::Id::new("dialog-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| { + egui::Area::new(egui::Id::unique("dialog-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| { ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140)); }); let mut close = false; @@ -213,7 +229,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { // Return presses OK in a dialog without a text field of its own (Lightroom's default button); // a widget that has the keyboard focus (a text field, a button or checkbox reached with Tab) // takes Return itself. Consumed before the dialog is drawn, so nothing else sees it too. - if return_confirms(&dlg) + if !raw_blocked + && return_confirms(&dlg) && ctx.memory(|m| m.focused().is_none()) && !egui::Popup::is_any_open(ctx) && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) @@ -261,6 +278,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { Dialog::ConfirmDelete { .. } => "Delete Photos", Dialog::MovePhotos { .. } => "Move Photos", Dialog::LightroomCatalog { .. } => "Lightroom Classic Catalog", + Dialog::LightroomDestination { .. } => "Import Lightroom Catalog", Dialog::SaveEffect { .. } => "New Effect Preset", Dialog::ManageEffects { .. } => "Manage Effect Presets", Dialog::DeleteEffects { names } if names.len() == 1 => "Delete Effect Preset", @@ -300,6 +318,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let widest = if settings { ctx.data(|d| d.get_temp::<f32>(widest_id)).unwrap_or(0.0).min(screen.width() * 0.9) } else { 0.0 }; let mut content_w = 0.0f32; let mut body_h = None; + // before the window: drawing it closes a dropdown the click lands outside of + let popup_was_open = egui::Popup::is_any_open(ctx); let shown = egui::Window::new(crate::i18n::tr(&title)).id(window_id) .collapsible(false) .resizable(import) @@ -315,10 +335,18 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { Dialog::Print => 1100.0, Dialog::FaceModel { .. } => 460.0, Dialog::LightroomCatalog { .. } => 440.0, + Dialog::LightroomDestination { .. } => 480.0, Dialog::ManageEffects { .. } => 560.0, _ => 380.0, }) .show(ctx, |ui| { + // Disabled, not skipped: the dialog keeps its layout and state, but a raw event in the + // first prompt frame cannot toggle a checkbox or press a button underneath it. The + // blocking library window gets the same treatment: it owns input while it is on screen, + // so the dialog behind it must not take focus or accept typed text either. + if raw_blocked { + ui.disable(); + } ui.spacing_mut().item_spacing.y = 8.0; body_h = dialog_body(ui, (!import && !print).then_some(title.as_str()), body_max, |ui| match &mut dlg { Dialog::AutoStack { gap } => { @@ -328,7 +356,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { .logarithmic(true) .smallest_positive(1.0) .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v)) - .custom_parser(|s| s.trim().trim_end_matches('s').parse().ok()), + .custom_parser(crate::panels::dialogs::parse_gap), ); crate::widgets::named(r, crate::i18n::tr("Stack photos taken within this time of each other:")); let preview = app.session.execute("stack.auto", &json!({"gap": *gap, "preview": true})).unwrap_or_default(); @@ -337,16 +365,41 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), ); } - Dialog::Cull { reject_below, pick_best } => { + Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); ui.add_space(6.0); let r = ui.add(egui::Slider::new(reject_below, 0.0..=80.0).text(crate::i18n::tr("Reject below focus")).step_by(1.0)); - crate::widgets::register(ui.ctx(), "field:cullReject", r.rect); + crate::widgets::register(ui, "field:cullReject", r.rect); ui.label(egui::RichText::new(crate::i18n::tr(if *reject_below > 0.0 { "Blurry photos below the score are flagged as rejects." } else { "0: nothing is rejected." })).color(t.text_dim)); let r = ui.checkbox(pick_best, crate::i18n::tr("Pick the sharpest photo of each burst")); - crate::widgets::register(ui.ctx(), "check:cullPick", r.rect); + crate::widgets::register(ui, "check:cullPick", r.rect); + ui.add_space(6.0); + // the sliders drag over the usual range; their value fields take whatever + // `photo.analyze` accepts (a gap of 0 s to a day, a similarity of 0 to 1) + let r = ui.add( + egui::Slider::new(burst_gap, 1.0..=600.0) + .logarithmic(true) + .smallest_positive(1.0) + .clamping(egui::SliderClamping::Never) + .text(crate::i18n::tr("Burst: shots at most this far apart")) + .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v)) + .custom_parser(crate::panels::dialogs::parse_gap), + ); + crate::widgets::register(ui, "field:cullGap", r.rect); + let r = ui.add( + egui::Slider::new(similarity, 0.70..=0.99) + .clamping(egui::SliderClamping::Never) + .text(crate::i18n::tr("Burst: how alike (loose … strict)")) + // a typed 0.995 is kept (whole hundredths would round it to 1.00) + .step_by(0.001) + .min_decimals(2) + .max_decimals(3), + ); + crate::widgets::register(ui, "field:cullSimilar", r.rect); + clamp_cull_burst(burst_gap, similarity); + ui.label(egui::RichText::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).color(t.text_dim)); ui.label(egui::RichText::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots.")).color(t.text_dim)); } Dialog::WhatsNew => { @@ -400,7 +453,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { Dialog::AllMetadata { title, rows, search } => { ui.label(egui::RichText::new(title.as_str()).color(t.text_label)); let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(search).hint_text(crate::i18n::tr("Filter fields")).desired_width(f32::INFINITY)), crate::i18n::tr("Filter fields")); - crate::widgets::register(ui.ctx(), "field:metadataSearch", r.rect); + crate::widgets::register(ui, "field:metadataSearch", r.rect); let q = search.trim().to_lowercase(); let keep = |n: &str, v: &str| q.is_empty() || n.to_lowercase().contains(&q) || v.to_lowercase().contains(&q); let mut groups: Vec<(String, Vec<(String, String)>)> = Vec::new(); @@ -443,7 +496,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } Dialog::SmartRules { id, name, rules, .. } => { let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Name")); - crate::widgets::register(ui.ctx(), "field:smartName", r.rect); + crate::widgets::register(ui, "field:smartName", r.rect); ui.add_space(6.0); // the folder an album made from a folder view carries is not in the editor, but it counts let folder = id.and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id))).and_then(|a| a.smart.as_deref().and_then(|f| f.library_folder.clone())); @@ -497,7 +550,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { "set" => { field(ui, "New time", |ui| { let r = ui.add(egui::TextEdit::singleline(time).hint_text("2026-09-30 14:05:00").desired_width(f32::INFINITY)); - crate::widgets::register(ui.ctx(), "field:captureTime", r.rect); + crate::widgets::register(ui, "field:captureTime", r.rect); }); json!({"time": time}) } @@ -523,10 +576,18 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { "shift" => params["shift"].as_i64(), _ => Some((*zone as f64 * 3600.0).round() as i64), }; - let after = delta.and_then(|d| lightcraft_catalog::dates::shift_iso(&cur, d)); + // the photo's own time is the problem (a Lightroom catalog's capture time + // is copied verbatim), not what was typed + let unreadable = lightcraft_catalog::dates::shift_iso(&cur, 0).is_none(); + let after = match (mode.as_str(), unreadable && n == 1) { + // alone, it simply gets the time typed (photo.setCaptureTime repairs it) + ("set", true) => lightcraft_catalog::dates::normalize_iso(time), + _ => delta.and_then(|d| lightcraft_catalog::dates::shift_iso(&cur, d)), + }; ui.label( egui::RichText::new(match after { Some(a) => format!("{name}: {} → {}", cur.replace('T', " "), a.replace('T', " ")), + None if unreadable && !(mode == "set" && n == 1) => crate::i18n::tr("The active photo's capture time can't be read").to_string(), None => "Enter a date as YYYY-MM-DD HH:MM:SS".into(), }) .color(t.text_label), @@ -555,12 +616,12 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); ui.painter().circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l)); let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut names[i]).hint_text(colour.as_str()).desired_width(f32::INFINITY)), crate::i18n::tr(&colour)); - crate::widgets::register(ui.ctx(), format!("field:labelName-{}", colour.to_lowercase()), te.rect); + crate::widgets::register(ui, format!("field:labelName-{}", colour.to_lowercase()), te.rect); }); } field(ui, "Save as set", |ui| { let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(save_as).hint_text(crate::i18n::tr("Optional name")).desired_width(f32::INFINITY)), crate::i18n::tr("Save as set")); - crate::widgets::register(ui.ctx(), "field:labelSetName", te.rect); + crate::widgets::register(ui, "field:labelSetName", te.rect); }); ui.label( egui::RichText::new(crate::i18n::tr("Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.")) @@ -570,12 +631,12 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { Dialog::Rename { template, start } => { let n = app.session.selected().len(); ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim)); - let template_id = egui::Id::new("rename-template"); + let template_id = egui::Id::unique("rename-template"); let tags_open = field(ui, "Template", |ui| { ui.spacing_mut().item_spacing.x = 4.0; let w = crate::import::tag_field_width(ui); let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(template).id(template_id).hint_text("{name}").desired_width(w)), crate::i18n::tr("Template")); - crate::widgets::register(ui.ctx(), "field:renameTemplate", r.rect); + crate::widgets::register(ui, "field:renameTemplate", r.rect); crate::import::tag_toggle(ui, "renameTemplate") }); if tags_open { @@ -611,7 +672,10 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { }); } None => { - ui.label(egui::RichText::new(crate::i18n::tr("Checking names…")).color(t.text_dim)); + ui.horizontal(|ui| { + crate::progress::spinner(ui, 12.0); + ui.label(egui::RichText::new(crate::i18n::tr("Checking names…")).color(t.text_dim)); + }); } } let more = total.saturating_sub(RENAME_PREVIEW_ROWS); @@ -646,7 +710,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { .color(t.caution), ); let r = ui.checkbox(merge, crate::i18n::tr("Combine with the existing person")); - crate::widgets::register(ui.ctx(), "check:personMerge", r.rect); + crate::widgets::register(ui, "check:personMerge", r.rect); } } Dialog::RenameKeyword { from, to } => { @@ -695,7 +759,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if !*folder && !app.session.selected().is_empty() { ui.add_space(6.0); let r = ui.checkbox(include_selected, crate::i18n::tr("Include selected photos")); - crate::widgets::register(ui.ctx(), "check:albumIncludeSelected", r.rect); + crate::widgets::register(ui, "check:albumIncludeSelected", r.rect); } } Dialog::RenameAlbum { name, .. } => { @@ -725,10 +789,11 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let n = app.session.selected().len(); ui.label(crate::i18n::tr_format!("{n} selected photos · {pages} pages", n = n, pages = n.div_ceil(options.columns * options.rows))); field(ui, "Paper", |ui| { - crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| { + let c = crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| { ui.selectable_value(&mut options.paper, "a4".into(), "A4"); ui.selectable_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter")); }); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Paper")); }); ui.checkbox(&mut options.landscape, crate::i18n::tr("Landscape")); field(ui, "Columns", |ui| { ui.add(egui::DragValue::new(&mut options.columns).range(1..=8)); }); @@ -756,7 +821,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } } }); - crate::widgets::register(ui.ctx(), "combo:exportPreset", c.response.rect); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Preset")); + crate::widgets::register(ui, "combo:exportPreset", c.response.rect); if let Some(name) = chosen && let Ok(params) = app.session.export_params(&json!({"preset": name})) { @@ -913,11 +979,11 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } if let Some(wm) = &mut opts.watermark { // text, or a graphic (a logo with transparency) - let mut graphic = !wm.image.is_empty() || ui.data(|d| d.get_temp::<bool>(egui::Id::new("wm-graphic"))).unwrap_or(false); + let mut graphic = !wm.image.is_empty() || ui.data(|d| d.get_temp::<bool>(egui::Id::unique("wm-graphic"))).unwrap_or(false); let before = graphic; choices(ui, "Style", "exportWmStyle", &[(false, "Text"), (true, "Graphic")], &mut graphic); if graphic != before { - ui.data_mut(|d| d.insert_temp(egui::Id::new("wm-graphic"), graphic)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("wm-graphic"), graphic)); if !graphic { wm.image.clear(); } @@ -989,7 +1055,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { use lightcraft_engine::export::DngCompression as Z; choices(ui, "Compression", "exportDngCompression", &[(Z::Lossless, "Lossless"), (Z::Deflate, "ZIP"), (Z::Uncompressed, "None"), (Z::Lossy, "Lossy")], &mut opts.dng_compression); } - let naming_id = egui::Id::new("export-naming"); + let naming_id = egui::Id::unique("export-naming"); let tags_open = field(ui, "File name", |ui| { ui.spacing_mut().item_spacing.x = 4.0; let w = crate::import::tag_field_width(ui); @@ -1047,7 +1113,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { #[cfg(target_os = "macos")] { let r = ui.checkbox(&mut opts.add_to_photos, crate::i18n::tr("Add to Apple Photos")); - crate::widgets::register(ui.ctx(), "exportAddToPhotos", r.rect); + crate::widgets::register(ui, "exportAddToPhotos", r.rect); if opts.add_to_photos { field(ui, "Album", |ui| { crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut opts.photos_album).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)), crate::i18n::tr("Album")) @@ -1084,7 +1150,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } Dialog::Merge { opts } => crate::merge::body(app, ui, opts), Dialog::Import { opts } => crate::import::body(app, ui, opts), - Dialog::Settings { tab } => crate::panels::settings::body(app, ui, tab), + // (Settings is never taller than `body_max`, so the scroll area round it never + // scrolls: its tab bar stays put and its pages scroll by themselves) + Dialog::Settings { tab } => crate::panels::settings::window(app, ui, tab, body_max), Dialog::SamModel { error, .. } => sam_model_body(app, ui, error.as_deref()), Dialog::KeywordTag { editing, @@ -1106,7 +1174,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { .width(f32::INFINITY) .select_on_focus(true) .show(ui); - if just_opened(ui, "keyword-tag") { + if ui.is_enabled() && just_opened(ui, "keyword-tag") { r.response.request_focus(); } if r.ending == Some(crate::text_field::Ending::Return) { @@ -1126,11 +1194,11 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if editing.is_none() { if let Some(p) = parent { let r = ui.checkbox(inside, crate::i18n::tr_format!("Put inside “{parent}”", parent = p.replace('|', " › "))); - crate::widgets::register(ui.ctx(), "check:keywordInside", r.rect); + crate::widgets::register(ui, "check:keywordInside", r.rect); } let n = app.session.selection.ids.len(); let r = ui.add_enabled(n > 0, egui::Checkbox::new(add_to_selected, crate::i18n::tr("Add to Selected Photos"))); - crate::widgets::register(ui.ctx(), "check:keywordAddToSelected", r.rect); + crate::widgets::register(ui, "check:keywordAddToSelected", r.rect); ui.add_space(4.0); } ui.label(egui::RichText::new(crate::i18n::tr("Keyword Tag Options")).color(t.text_dim)); @@ -1141,7 +1209,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { (person, "Person", "check:keywordPerson"), ] { let r = ui.checkbox(on, crate::i18n::tr(label)); - crate::widgets::register(ui.ctx(), id, r.rect); + crate::widgets::register(ui, id, r.rect); } } Dialog::KeywordSet { replaces, name, slots, as_new } => { @@ -1151,7 +1219,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { .width(f32::INFINITY) .select_on_focus(true) .show(ui); - if just_opened(ui, "keyword-set") { + if ui.is_enabled() && just_opened(ui, "keyword-set") { r.response.request_focus(); } let mut returned = r.ending == Some(crate::text_field::Ending::Return); @@ -1175,7 +1243,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if replaces.is_some() { ui.add_space(6.0); let r = ui.checkbox(as_new, crate::i18n::tr("Save as a new set")); - crate::widgets::register(ui.ctx(), "check:keywordSetAsNew", r.rect); + crate::widgets::register(ui, "check:keywordSetAsNew", r.rect); } // Return in any field saves the set if returned { @@ -1237,20 +1305,24 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { ui.label(egui::RichText::new(crate::i18n::tr("Their files and XMP sidecars move on disk. Edit → Undo moves them back.")).color(t.text_dim)); ui.add_space(4.0); let c = ui.checkbox(dont_ask, crate::i18n::tr("Don't ask again")); - crate::widgets::register(ui.ctx(), "check:moveDontAsk", c.rect); + crate::widgets::register(ui, "check:moveDontAsk", c.rect); c.on_hover_text(crate::i18n::tr("Settings → Confirm before moving photos to another folder on disk turns it back on")); } d @ Dialog::SynchronizeFolder { .. } => crate::sync::body(app, ui, d), Dialog::LightroomCatalog { folder, catalog } => { ui.label(crate::i18n::tr("This is a Lightroom catalog, not a LightCraft library. Import it into a LightCraft library instead?")); ui.label(egui::RichText::new(catalog.as_deref().unwrap_or(folder.as_str())).color(t.text_dim)); - ui.label( - egui::RichText::new(crate::i18n::tr( - "The import reads the catalog without changing it and adds its photos, edits, keywords and collections to the library open now.", - )) - .color(t.text_dim), - ); + // (the import then asks where the catalog goes, unless Settings says to merge, #2672) + let asks = app.ui.settings.lightroom_import == crate::state::LightroomImport::Ask + && app.session.library.as_ref().is_some_and(|l| l.on_disk); + let what = if asks { + "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library." + } else { + "The import reads the catalog without changing it and adds its photos, edits, keywords and collections to the library open now." + }; + ui.label(egui::RichText::new(crate::i18n::tr(what)).color(t.text_dim)); } + d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::body(app, ui, d), Dialog::RemoveFolder { name, count, path, disk } => { ui.label(crate::i18n::tr_format!( "Remove “{name}” and its {count} photo{} from the library?", @@ -1268,7 +1340,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } Dialog::About => { ui.set_min_width(680.0); - let tab_id = egui::Id::new("about_tab"); + let tab_id = egui::Id::unique("about_tab"); let mut tab = ui.data_mut(|d| d.get_temp::<u8>(tab_id)).unwrap_or(0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; @@ -1368,6 +1440,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { Dialog::KeywordTag { .. } => "Save", Dialog::RemoveFolder { .. } => "Remove", Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…", + d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), Dialog::SynchronizeFolder { .. } if informational => "Close", Dialog::SynchronizeFolder { .. } => "Synchronize", Dialog::SamModel { then: Some(_), .. } if sam_installed => "Continue", @@ -1437,6 +1510,16 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if settings && content_w > widest + 0.5 { ctx.data_mut(|d| d.insert_temp(widest_id, content_w)); } + if let Some(w) = &shown { + // (the import review keeps its hand-picked photos however the click lands) + if !raw_blocked && app.ui.settings.close_dialogs_outside && !import && clicked_backdrop(ctx, w.response.rect, popup_was_open) { + close = true; + } else if raw_blocked { + // A press made under the prompt or library window must not be remembered as a + // backdrop press for a release that arrives after that covering window goes away. + ctx.data_mut(|d| d.remove_temp::<bool>(egui::Id::unique("dialog-backdrop-press"))); + } + } if let Some(w) = shown { ctx.memory_mut(|m| m.set_modal_layer(w.response.layer_id)); if let Some(body_h) = body_h { @@ -1447,17 +1530,18 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { } } ctx.move_to_top(w.response.layer_id); - crate::widgets::register(ctx, "dialog:window", w.response.rect); + crate::widgets::register_response("dialog:window", w.response.rect, &w.response); } // (while the shortcuts editor records a key, it takes Esc itself to cancel; an open popup in // the dialog, such as a date picker's calendar, takes it to close itself) - if ctx.input(|i| i.key_pressed(egui::Key::Escape)) && !crate::widgets::escape_taken(ctx) { + if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && !crate::widgets::escape_taken(ctx) { close = true; } - if confirm { + if !raw_blocked && confirm { match confirm_dialog(app, &dlg) { // the import review stays open on an error (e.g. an unusable folder template), and so - // does Export (e.g. no folder chosen) so the choices aren't lost + // does Export (e.g. no folder chosen) so the choices aren't lost, and Edit Capture Time + // (a time that isn't a date, or a shift it refuses) Err(e) if matches!( dlg, @@ -1473,6 +1557,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { | Dialog::KeywordSet { .. } | Dialog::SynchronizeFolder { .. } | Dialog::SaveEffect { .. } + | Dialog::CaptureTime { .. } ) => { app.toast(ctx, e) @@ -1500,6 +1585,17 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { app.toast(ctx, e); close = true; } + // photos whose capture time doesn't read are left as they were: say so + Ok(r) if matches!(dlg, Dialog::CaptureTime { .. }) && r["unreadable"].as_u64().is_some_and(|n| n > 0) => { + app.toast(ctx, crate::i18n::tr("Photos whose capture time can't be read were left as they were")); + close = true; + } + // where a Lightroom catalog goes: stays open to be corrected (a folder that isn't + // empty), unless the library it names has gone + Err(e) if matches!(dlg, Dialog::LightroomDestination { .. }) => { + close = !crate::lightroom_destination::keeps_open_on_error(app, &dlg); + app.toast(ctx, e); + } Ok(_) if keeps_open(app, &dlg) => { if let Dialog::SamModel { error, .. } = &mut dlg { *error = None; @@ -1512,9 +1608,50 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if app.ui.dialog.as_ref().is_some_and(|now| *now != at_start) { return; } + if !close && !blocked { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame)); + } app.ui.dialog = if close { None } else { Some(dlg) }; } +/// The last frame a dialog was drawn and stayed open, for [`clicked_backdrop`]. +const BACKDROP_SHOWN: &str = "dialog-backdrop-shown"; + +/// A click on the dimmed backdrop around the dialog: it closes the dialog like Esc. Pressed and +/// released outside the window, so a slider dragged past its edge doesn't close it; a press while a +/// popup is open (a dropdown, a date picker's calendar) only closes the popup: `popup_was_open` is +/// read before the window is drawn, since drawing it already closes the popup. Only a press made +/// while the dialog is shown counts: in the frame a dialog appears, its input is the click that +/// opened it (a quick click on a slow frame presses and releases in that one frame), so it never +/// closes it. (Read from the raw events: egui forgets the press origin on release.) +fn clicked_backdrop(ctx: &egui::Context, window: egui::Rect, popup_was_open: bool) -> bool { + let press_id = egui::Id::unique("dialog-backdrop-press"); + let frame = ctx.cumulative_frame_nr(); + // the same frame too: a second pass of it gets no input + let shown = ctx.data(|d| d.get_temp::<u64>(egui::Id::unique(BACKDROP_SHOWN))).is_some_and(|f| f + 1 >= frame); + if !shown { + ctx.data_mut(|d| d.remove_temp::<bool>(press_id)); + return false; + } + let (press, release, clicked) = ctx.input(|i| { + let at = |down: bool| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } if *pressed == down => Some(*pos), + _ => None, + }) + }; + (at(true), at(false), i.pointer.primary_clicked()) + }); + if let Some(p) = press { + let outside = !window.contains(p) && !popup_was_open; + ctx.data_mut(|d| d.insert_temp(press_id, outside)); + } + let Some(release) = release else { return false }; + let pressed_outside = ctx.data_mut(|d| d.remove_temp::<bool>(press_id)).unwrap_or(false); + clicked && pressed_outside && !window.contains(release) +} + /// Room kept free above and below a dialog (#781). const DIALOG_SCREEN_MARGIN: f32 = 12.0; /// A dialog's title bar, frame and button row before the first frame measures them. @@ -1526,11 +1663,11 @@ const DIALOG_MIN_BODY: f32 = 80.0; const DIALOG_MIN_LIST: f32 = 120.0; fn list_shrink_id() -> egui::Id { - egui::Id::new("dialog-list-shrink") + egui::Id::unique("dialog-list-shrink") } fn list_applied_id() -> egui::Id { - egui::Id::new("dialog-list-applied") + egui::Id::unique("dialog-list-applied") } /// The height for a list in a dialog that scrolls on its own (What's New, All Metadata, the @@ -1576,6 +1713,61 @@ fn dialog_body(ui: &mut egui::Ui, scroll: Option<&str>, max_height: f32, body: i } /// Apply a dialog's action (also used by `ui.dialog.confirm`). +/// What [`fmt_gap`] writes, read back: `90`, `90 s`, `1 min 30 s`, `2 h 5 min`, `1 day` +/// (units `s`, `min`, `h`, `day`, each optional after a plain number of seconds). +pub fn parse_gap(text: &str) -> Option<f64> { + // the one translated text `fmt_gap` writes ("1 Tag") + if text.trim() == crate::i18n::tr("1 day") { + return Some(86400.0); + } + let mut total = 0.0; + let mut seen = false; + let mut words = text.split_whitespace().peekable(); + while let Some(word) = words.next() { + // "90s" as well as "90 s" + let split = word.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(word.len()); + let (num, unit) = word.split_at(split); + let n: f64 = num.parse().ok().filter(|n: &f64| n.is_finite())?; + let unit = if unit.is_empty() { + match words.peek() { + Some(u) if u.parse::<f64>().is_err() => words.next().unwrap_or_default(), + _ => "s", + } + } else { + unit + }; + let scale = match unit.trim_end_matches('.').to_lowercase().as_str() { + "s" | "sec" | "secs" | "second" | "seconds" => 1.0, + "m" | "min" | "mins" | "minute" | "minutes" => 60.0, + "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0, + "d" | "day" | "days" => 86400.0, + _ => return None, + }; + total += n * scale; + seen = true; + } + seen.then_some(total) +} + +/// The longest burst gap `photo.analyze` accepts: a day. +pub const MAX_BURST_GAP: f32 = 86_400.0; + +/// Keep what was typed in the Assisted Culling value fields within what `photo.analyze` accepts +/// (a gap of 0 s to a day, a similarity of 0 to 1), not within the sliders' drag range. +pub fn clamp_cull_burst(gap: &mut f32, similarity: &mut f32) { + *gap = if gap.is_finite() { gap.clamp(0.0, MAX_BURST_GAP) } else { 10.0 }; + *similarity = if similarity.is_finite() { similarity.clamp(0.0, 1.0) } else { 0.93 }; +} + +/// The `photo.analyze` parameters of the Assisted Culling dialog, its values as they are. +pub fn cull_params(reject_below: f32, pick_best: bool, burst_gap: f32, similarity: f32) -> serde_json::Value { + let mut p = json!({"pickBest": pick_best, "burstGap": burst_gap, "similarity": similarity}); + if reject_below > 0.0 { + p["rejectBelow"] = json!(reject_below); + } + p +} + /// `90` → `1 min 30 s`. pub fn fmt_gap(v: f64) -> String { let v = v.round() as u64; @@ -1584,7 +1776,9 @@ pub fn fmt_gap(v: f64) -> String { 60..3600 if v.is_multiple_of(60) => format!("{} min", v / 60), 60..3600 => format!("{} min {} s", v / 60, v % 60), 3600..86400 if v.is_multiple_of(3600) => format!("{} h", v / 3600), - 3600..86400 => format!("{} h {} min", v / 3600, v % 3600 / 60), + 3600..86400 if v.is_multiple_of(60) => format!("{} h {} min", v / 3600, v % 3600 / 60), + // the seconds too, so editing the text reads back the same gap + 3600..86400 => format!("{} h {} min {} s", v / 3600, v % 3600 / 60, v % 60), _ => crate::i18n::tr("1 day").into(), } } @@ -1657,19 +1851,17 @@ fn sam_model_body(app: &mut LightcraftApp, ui: &mut egui::Ui, error: Option<&str .color(t.text_label), ); let r = ui.link(crate::i18n::tr("Read the SAM License")).on_hover_text(LICENSE_URL); - crate::widgets::register(ui.ctx(), "link:samLicense", r.rect); + crate::widgets::register(ui, "link:samLicense", r.rect); if r.clicked() { let _ = crate::links::open(app, LICENSE_URL); } let seg = &app.session.segmenter; if d.running { ui.add_space(4.0); - let frac = if d.total > 0 { d.done as f64 / d.total as f64 } else { 0.0 }; let text = format!("{:.2} / {:.2} GB · {}", gb(d.done), gb(d.total), d.file); - let r = ui.add(egui::ProgressBar::new(frac as f32).text(text)); - crate::widgets::register(ui.ctx(), "progress:samDownload", r.rect); + crate::progress::Progress::new(crate::progress::fraction_of(d.done, d.total)).label(text).widget("progress:samDownload").show(ui); let r = ui.button(crate::i18n::tr("Cancel Download")); - crate::widgets::register(ui.ctx(), "button:samCancel", r.rect); + crate::widgets::register(ui, "button:samCancel", r.rect); if r.clicked() { app.session.segmenter.cancel_download(); } @@ -1689,7 +1881,7 @@ fn sam_model_body(app: &mut LightcraftApp, ui: &mut egui::Ui, error: Option<&str ui.horizontal_wrapped(|ui| { if dir.is_some() && crate::menus::ui_enabled(app, "app.openSamModelFolder") { let r = ui.button(crate::i18n::tr(crate::menus::reveal_label())); - crate::widgets::register(ui.ctx(), "button:samFolder", r.rect); + crate::widgets::register(ui, "button:samFolder", r.rect); if r.clicked() && let Err(e) = app.run("app.openSamModelFolder", json!({})) { @@ -1697,7 +1889,7 @@ fn sam_model_body(app: &mut LightcraftApp, ui: &mut egui::Ui, error: Option<&str } } let r = ui.link(crate::i18n::tr("How to install the model")).on_hover_text(SAM_HELP); - crate::widgets::register(ui.ctx(), "link:samHelp", r.rect); + crate::widgets::register(ui, "link:samHelp", r.rect); if r.clicked() && let Err(e) = crate::links::open(app, SAM_HELP) { @@ -1873,12 +2065,9 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jso Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best } => { - let mut p = json!({"pickBest": pick_best}); - if *reject_below > 0.0 { - p["rejectBelow"] = json!(reject_below); - } - app.run("photo.analyze", p) + Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + app.ui.cull_burst = Some((*burst_gap, *similarity)); + app.run("photo.analyze", cull_params(*reject_below, *pick_best, *burst_gap, *similarity)) } Dialog::SmartRules { id, name, rules, parent } => { // refused before anything changes (not even the name) @@ -1932,6 +2121,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jso Dialog::LightroomCatalog { catalog, .. } => { app.run("file.importLightroom", catalog.as_ref().map_or_else(|| json!({}), |c| json!({"path": c}))) } + d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::confirm(app, d), Dialog::SaveEffect { name, group, fields, amount, brush } => { crate::panels::mask_effects::save_confirm(app, name, group, fields, *amount, *brush) } @@ -1975,7 +2165,7 @@ fn group_checklist(ui: &mut egui::Ui, tag: &str, groups: &mut Vec<String>) { let key = key_of(g); let mut on = groups.contains(&key); let r = cols[i % 2].checkbox(&mut on, crate::i18n::tr(g.label())); - crate::widgets::register(&r.ctx, format!("{tag}:{key}"), r.rect); + crate::widgets::register_response(format!("{tag}:{key}"), r.rect, &r); if r.changed() { if on { groups.push(key); @@ -1987,12 +2177,12 @@ fn group_checklist(ui: &mut egui::Ui, tag: &str, groups: &mut Vec<String>) { }); ui.horizontal(|ui| { let all = ui.small_button(crate::i18n::tr("All")); - crate::widgets::register(ui.ctx(), format!("{tag}:all"), all.rect); + crate::widgets::register(ui, format!("{tag}:all"), all.rect); if all.clicked() { *groups = SettingsGroup::ALL.iter().map(key_of).collect(); } let none = ui.small_button(crate::i18n::tr("None")); - crate::widgets::register(ui.ctx(), format!("{tag}:none"), none.rect); + crate::widgets::register(ui, format!("{tag}:none"), none.rect); if none.clicked() { groups.clear(); } @@ -2029,7 +2219,7 @@ fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::ex (R::Percent, "Percentage"), ]; let r_full = ui.checkbox(full, crate::i18n::tr("Full size")); - crate::widgets::register(ui.ctx(), "check:exportFullSize", r_full.rect); + crate::widgets::register(ui, "check:exportFullSize", r_full.rect); if !*full { field(ui, "Resize to", |ui| { let cur = MODES.iter().find(|m| m.0 == r.mode).map_or("Long Edge", |m| m.1); @@ -2039,7 +2229,8 @@ fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::ex ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l)); } }); - crate::widgets::register(ui.ctx(), "combo:exportResizeMode", c.response.rect); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize")); + crate::widgets::register(ui, "combo:exportResizeMode", c.response.rect); if r.mode != before { // a sensible value for the new unit r.value = match r.mode { @@ -2070,7 +2261,7 @@ fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::ex } } let c = ui.checkbox(&mut r.dont_enlarge, crate::i18n::tr("Don't enlarge")); - crate::widgets::register(ui.ctx(), "check:exportDontEnlarge", c.rect); + crate::widgets::register(ui, "check:exportDontEnlarge", c.rect); } let mut p = *ppi as f64; if num(ui, &PPI, &mut p) { @@ -2140,12 +2331,12 @@ fn slideshow_export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, settings: & } field(ui, "Quality", |ui| { let r = ui.add(egui::Slider::new(&mut settings.quality, 1..=100)); - crate::widgets::register(ui.ctx(), "slider:slideshowExportQuality", r.rect); + crate::widgets::register(ui, "slider:slideshowExportQuality", r.rect); }); let note = match settings.format { Format::Pdf => { let r = ui.checkbox(&mut settings.full_screen, crate::i18n::tr("Automatically show full screen")); - crate::widgets::register(ui.ctx(), "check:slideshowExportFullScreen", r.rect); + crate::widgets::register(ui, "check:slideshowExportFullScreen", r.rect); "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode." } Format::Jpeg => "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.", @@ -2244,13 +2435,17 @@ fn person_rename_plan(cat: &lightcraft_catalog::Catalog, from: &str, to: &str) - PersonRenamePlan { faces, needs_merge: needs_merge && from_key != to_key, block } } -/// A dialog's one text field: it keeps the focus (except while its own menu has it) and opens -/// with its text selected, so typing replaces it. True when Return confirms the dialog; Esc -/// cancels the dialog (`show`). Taking the focus back with a bare `TextEdit` every frame hid the -/// focus Return gives up, and Return did nothing. +/// A dialog's one text field: it takes the focus when the dialog opens, and opens with its text +/// selected, so typing replaces it. It takes the focus back only while nothing else has it: taking +/// it back every frame would keep Tab from ever reaching the dialog's buttons and check boxes. +/// True when Return confirms the dialog; Esc cancels the dialog (`show`). fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str) -> bool { let r = crate::text_field::TextField::singleline(widget, text).hint(crate::i18n::tr(hint)).width(f32::INFINITY).select_on_focus(true).show(ui); - if !r.editing { + // (and takes it back when nothing has it: after a click on the dialog's background or a check box, + // or when Return gave it up on a refusal; a control Tab reached keeps it). A disabled dialog (a + // prompt or the blocking library window owns input) must not request the focus at all: egui's + // text edit would otherwise keep editing the draft from host text behind that window. + if ui.is_enabled() && (just_opened(ui, widget) || (!r.editing && r.ending.is_none() && ui.memory(|m| m.focused().is_none()))) { r.response.request_focus(); } r.ending == Some(crate::text_field::Ending::Return) @@ -2259,7 +2454,7 @@ fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str) /// The dialog part `key` is drawn this frame but wasn't the frame before: the dialog has just /// opened (to give its first field the focus once). fn just_opened(ui: &egui::Ui, key: &str) -> bool { - let id = egui::Id::new(("dialog-shown", key)); + let id = egui::Id::unique(("dialog-shown", key)); let pass = ui.ctx().cumulative_pass_nr(); let last: Option<u64> = ui.data_mut(|d| d.get_temp(id)); ui.data_mut(|d| d.insert_temp(id, pass)); @@ -2325,3 +2520,132 @@ fn only_shows(dlg: &Dialog) -> bool { | Dialog::ViewOptions ) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date()) } + +#[cfg(test)] +mod gap_tests { + use super::{fmt_gap, parse_gap}; + + #[test] + fn gap_text_reads_back_what_it_shows() { + for v in [0.0, 1.0, 12.0, 59.0, 60.0, 90.0, 600.0, 3599.0, 3600.0, 3601.0, 3661.0, 3900.0, 7325.0, 86340.0, 86399.0] { + assert_eq!(parse_gap(&fmt_gap(v)), Some(v), "{}", fmt_gap(v)); + } + assert_eq!(parse_gap("1 day"), Some(86400.0)); + assert_eq!(parse_gap("45"), Some(45.0)); + assert_eq!(parse_gap(" 45s "), Some(45.0)); + assert_eq!(parse_gap("2min 5s"), Some(125.0)); + for bad in ["", "abc", "5 parsecs", "NaN", "1 min x"] { + assert_eq!(parse_gap(bad), None, "{bad:?}"); + } + // a day reads back in the UI language too ("1 Tag") + crate::i18n::set_language(crate::i18n::Locale::De); + let shown = fmt_gap(86400.0); + let back = parse_gap(&shown); + crate::i18n::set_language(crate::i18n::Locale::En); + assert_eq!((shown.as_str(), back), ("1 Tag", Some(86400.0))); + } + + #[test] + fn gaps_past_the_slider_read_back_too() { + // the Assisted Culling slider drags to 10 min; its value field takes up to a day + for (v, text) in [(1800.0, "30 min"), (5400.0, "1 h 30 min"), (3601.0, "1 h 0 min 1 s"), (86400.0, "1 day")] { + assert_eq!(fmt_gap(v), text); + assert_eq!(parse_gap(text), Some(v), "{text}"); + } + assert_eq!(parse_gap("1800"), Some(1800.0)); + assert_eq!(parse_gap("0"), Some(0.0)); + } +} + +#[cfg(test)] +mod cull_dialog_tests { + use std::time::Duration; + + use serde_json::json; + + use super::{clamp_cull_burst, cull_params}; + use crate::headless::Headless; + use crate::state::Dialog; + use crate::{LightcraftApp, Services}; + + const T: Duration = Duration::from_secs(20); + + #[test] + fn typed_values_are_kept_within_what_photo_analyze_accepts() { + for (gap, sim) in [(0.0, 0.0), (1800.0, 1.0), (86400.0, 0.5), (0.5, 0.995)] { + let (mut g, mut s) = (gap, sim); + clamp_cull_burst(&mut g, &mut s); + assert_eq!((g, s), (gap, sim), "in range: kept as typed"); + } + for ((gap, sim), want) in [((-5.0, -0.1), (0.0, 0.0)), ((90000.0, 1.5), (86400.0, 1.0)), ((f32::NAN, f32::INFINITY), (10.0, 0.93))] { + let (mut g, mut s) = (gap, sim); + clamp_cull_burst(&mut g, &mut s); + assert_eq!((g, s), want); + } + assert_eq!(cull_params(0.0, true, 1800.0, 1.0), json!({"pickBest": true, "burstGap": 1800.0, "similarity": 1.0})); + assert_eq!(cull_params(20.0, false, 0.0, 0.7)["rejectBelow"], 20.0); + } + + /// Click the value field right of a slider registered as `id`, type `text`, Enter. + fn type_value(h: &mut Headless, id: &str, text: &str) { + let r = h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("{id} not on screen")); + let spacing = h.view.ctx.global_style().spacing.clone(); + let x = r.left() + spacing.slider_width + spacing.item_spacing.x + 6.0; + assert_eq!(h.request("ui.click", json!({"x": x, "y": r.center().y}), T)["ok"], true); + h.step(); + for key in ["a", "Backspace"] { + assert_eq!(h.request("ui.key", json!({"key": key, "cmd": key == "a"}), T)["ok"], true); + } + assert_eq!(h.request("ui.text", json!({"text": text}), T)["ok"], true); + assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true); + h.step(); + h.step(); + } + + fn burst(h: &Headless) -> (f32, f32) { + match &h.app.ui.dialog { + Some(Dialog::Cull { burst_gap, similarity, .. }) => (*burst_gap, *similarity), + d => panic!("{d:?}"), + } + } + + #[test] + fn the_culling_value_fields_take_values_past_the_sliders() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + h.step(); + h.app.run("dialog.cull", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert_eq!(burst(&h), (10.0, 0.93)); + // half an hour and "only identical shots": past the sliders' 10 min and 0.99 + type_value(&mut h, "field:cullGap", "30 min"); + type_value(&mut h, "field:cullSimilar", "1.0"); + assert_eq!(burst(&h), (1800.0, 1.0)); + // a day is as far as photo.analyze goes; more is held there + type_value(&mut h, "field:cullGap", "2 days"); + assert_eq!(burst(&h).0, 86400.0); + type_value(&mut h, "field:cullGap", "0"); + assert_eq!(burst(&h), (0.0, 1.0)); + type_value(&mut h, "field:cullGap", "1800"); + assert_eq!(burst(&h).0, 1800.0); + // a similarity between the slider's hundredths is kept to the thousandth + type_value(&mut h, "field:cullSimilar", "0.995"); + assert_eq!(burst(&h).1, 0.995); + type_value(&mut h, "field:cullSimilar", "0.9951"); + assert_eq!(burst(&h).1, 0.995); + type_value(&mut h, "field:cullSimilar", "1.0"); + assert_eq!(burst(&h).1, 1.0); + // OK hands them to photo.analyze as typed (it refuses values out of its range) + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog); + assert_eq!(h.app.ui.cull_burst, Some((1800.0, 1.0))); + // and the next opening starts from them, not from the sliders' range + h.app.run("dialog.cull", json!({})).unwrap(); + h.step(); + h.step(); + assert_eq!(burst(&h), (1800.0, 1.0)); + } +} diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 08f70bd022..10542e4432 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -6,6 +6,7 @@ use egui::{Align2, Color32, Pos2, Rect, RichText, Sense, Stroke, pos2, vec2}; use lightcraft_catalog::PhotoId; use lightcraft_develop::{ControlSpec, DevelopSettings, Section, Track, WbMode, controls}; use lightcraft_geom::Point; +use lightcraft_pipeline::{PARAM_AMOUNTS, ParametricCurve}; use lightcraft_raster::Histogram; use serde_json::{Value, json}; @@ -198,7 +199,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 0, bottom: 10 }).show(ui, |ui| { let mut on = d.profile.camera_local_tone; let r = ui.checkbox(&mut on, crate::i18n::tr("Camera local tone mapping")); - crate::widgets::register(ui.ctx(), "check:profile.cameraLocalTone", r.rect); + crate::widgets::register(ui, "check:profile.cameraLocalTone", r.rect); if r.on_hover_text(crate::i18n::tr("Apply the local tone mapping stored in the raw (Apple ProRAW), as the camera renders it")).changed() { let _ = app.run("develop.merge", json!({"settings": {"profile": {"camera_local_tone": on}}, "label": "Camera Local Tone Mapping"})); } @@ -446,7 +447,7 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett let mut pick: (Option<String>, Option<String>) = (None, None); let item = |ui: &mut egui::Ui, key: &str, id: &str, name: &str, pick: &mut (Option<String>, Option<String>)| { let r = ui.selectable_label(id == cur, crate::i18n::profile_label(id, name)); - register(ui.ctx(), format!("profileMenu:{key}:{id}"), r.rect); + register(ui, format!("profileMenu:{key}:{id}"), r.rect); if r.clicked() { pick.0 = Some(id.to_string()); } @@ -477,7 +478,7 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett } }); }); - register(ui.ctx(), format!("profileMenu:groupMenu:{g}"), r.response.rect); + register(ui, format!("profileMenu:groupMenu:{g}"), r.response.rect); if r.inner.is_some() { crate::menu_level::set_anchor(ui.ctx(), 2, r.response.rect); } @@ -496,7 +497,7 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett } }); }); - register(ui.ctx(), format!("profileMenu:lutGroupMenu:{g}"), r.response.rect); + register(ui, format!("profileMenu:lutGroupMenu:{g}"), r.response.rect); if r.inner.is_some() { crate::menu_level::set_anchor(ui.ctx(), 2, r.response.rect); } @@ -510,13 +511,13 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett crate::i18n::tr_format!("Add “{}” to Favorites", crate::i18n::profile_label(cur, name)) }; let r = ui.button(label); - register(ui.ctx(), "profileMenu:toggleFavorite", r.rect); + register(ui, "profileMenu:toggleFavorite", r.rect); if r.clicked() { let _ = app.run("profile.favorite", json!({"id": cur})); } } let r = ui.button(crate::i18n::tr("Browse…")); - register(ui.ctx(), "profileMenu:browse", r.rect); + register(ui, "profileMenu:browse", r.rect); if r.clicked() { let _ = app.run("panel.profiles", json!({})); } @@ -564,7 +565,7 @@ fn section( crate::widgets::context_menu(&resp, |ui| { let mut solo = app.ui.single_panel; let item = ui.checkbox(&mut solo, crate::i18n::tr("Solo Mode")); - register(ui.ctx(), "sectionMenu:solo", item.rect); + register(ui, "sectionMenu:solo", item.rect); if item.clicked() { if let Err(e) = app.run("view.soloSections", json!({"on": solo})) { app.toast(ui.ctx(), e); @@ -595,7 +596,7 @@ fn preview_histogram(app: &LightcraftApp, id: PhotoId) -> Option<lightcraft_rast /// the SDR layout and back while a slider moves. Every render with HDR bins replaces the one kept for the photo, so /// the histogram still follows the edit live; an SDR edit shows what it gets. fn steady_hdr_histogram(ctx: &egui::Context, id: PhotoId, hdr_edit: bool, hist: Option<Histogram>) -> Option<Histogram> { - let key = egui::Id::new(("hdrHistogram", id)); + let key = egui::Id::unique(("hdrHistogram", id)); match hist { Some(h) if h.hdr.is_some() => { ctx.data_mut(|d| d.insert_temp(key, h.clone())); @@ -630,12 +631,19 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // row under the plot let hdr = hist.as_ref().and_then(|h| h.hdr); let legend = if hdr.is_some() { 26.0 } else { 0.0 }; - let (r, resp) = ui.allocate_exact_size(vec2(w, 118.0 + legend), Sense::click()); + let (r, resp) = ui.allocate_exact_size(vec2(w, 118.0 + legend), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Histogram")); - register(ui.ctx(), "histogram", r); + register(ui, "histogram", r); let p = ui.painter(); p.rect_filled(r, 0.0, t.button); let plot = Rect::from_min_max(r.min + vec2(0.0, 6.0), pos2(r.right(), r.bottom() - 26.0 - legend)); + // Lightroom Classic's tonal zones (Blacks / Shadows / Exposure / Highlights / Whites across the + // plot): a drag over one moves its control (the band and the readout show which and how far), a + // double-click puts it back to its default, and Shift drags a tenth as far + let zone = super::histogram::interact(app, ui, &resp, plot, id); + if let Some(a) = &zone { + super::histogram::paint_zone(p, plot, a, &t); + } if let Some(b) = hdr { // white for SDR, then one band per stop above SDR white: white too, or (Visualize HDR // range on) in its colours @@ -656,7 +664,7 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { p.text(pos2((x0 + plot.right()) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("HDR"), t.font(12.5), t.text_label); let info = Rect::from_center_size(pos2(plot.right() - 16.0, y), vec2(14.0, 14.0)); paint(p, info, Icon::Info, t.text_label); - ui.interact(info, egui::Id::new("hdrHistogramInfo"), Sense::hover()).on_hover_text(crate::i18n::tr( + ui.interact(info, egui::Id::unique("hdrHistogramInfo"), Sense::hover()).on_hover_text(crate::i18n::tr( "Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.", )); } @@ -723,16 +731,14 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let mut clicked = resp.clicked(); // the panel's floating scroll bar widens over the right edge when hovered: both buttons keep // clear of it, the left one too so they stay symmetric (#1640) - let scroll = ui.spacing().scroll; - let inset = 20.0 + scroll.bar_width + scroll.bar_outer_margin; - for (name, x, label, clipped) in [ - ("shadows", plot.left() + inset, "Shadow clipping", clipping.map(|(lo, _)| lo > 0.003)), - ("highlights", plot.right() - inset, "Highlight clipping", clipping.map(|(_, hi)| hi > 0.003)), + let [shadow_rect, highlight_rect] = super::histogram::clipping_rects(ui, plot); + for (name, rect, label, clipped) in [ + ("shadows", shadow_rect, "Shadow clipping", clipping.map(|(lo, _)| lo > 0.003)), + ("highlights", highlight_rect, "Highlight clipping", clipping.map(|(_, hi)| hi > 0.003)), ] { - let rect = Rect::from_center_size(pos2(x, plot.top() + 14.0), vec2(24.0, 22.0)); - let response = ui.interact(rect, ui.id().with(("histogram-clipping", name)), Sense::click()); - register(ui.ctx(), format!("histogram:{name}"), rect); - response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), app.ui.show_clipping, crate::i18n::tr(label))); + let response = ui.interact(rect, ui.scope_id().with(("histogram-clipping", name)), Sense::click()); + register(ui, format!("histogram:{name}"), rect); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), app.ui.show_clipping, crate::i18n::tr(label))); clicked |= response.clicked(); let active = app.ui.show_clipping; // Keep the hit target comfortable, with a smaller box and clear space to the plot edges. @@ -776,8 +782,11 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if clicked { let _ = app.run("view.clipping", json!({})); } - // EXIF strip - if let Some(ph) = app.session.catalog.photo(id) { + // the tonal zone the pointer is on replaces the EXIF strip while it is there + if let Some(text) = zone.as_ref().and_then(|a| a.readout()) { + register(ui, "histogramReadout", r); + p.text(pos2(r.left() + r.width() / 2.0, r.bottom() - 13.0), Align2::CENTER_CENTER, text, t.font(12.5), t.text_label); + } else if let Some(ph) = app.session.catalog.photo(id) { let m = &ph.meta; let parts: Vec<String> = [ m.iso.map(|i| format!("ISO {i}")), @@ -812,12 +821,12 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let r = ui .toggle_value(&mut dest, RichText::new("■").color(Color32::from_rgb(255, 40, 40))) .on_hover_text(crate::i18n::tr("Show destination gamut warning")); - register(ui.ctx(), "button:proofDestWarning", r.rect); + register(ui, "button:proofDestWarning", r.rect); let mut disp = app.ui.proof.display_warning; let r2 = ui .toggle_value(&mut disp, RichText::new("■").color(Color32::from_rgb(40, 90, 255))) .on_hover_text(crate::i18n::tr("Show display gamut warning")); - register(ui.ctx(), "button:proofDisplayWarning", r2.rect); + register(ui, "button:proofDisplayWarning", r2.rect); if dest != app.ui.proof.dest_warning || disp != app.ui.proof.display_warning { let _ = app.run("view.softProof", json!({"destWarning": dest, "displayWarning": disp})); } @@ -829,7 +838,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let device = app.ui.proof_profile.as_ref().map(|(_, n)| n.clone()); let shown = device.clone().unwrap_or_else(|| cur.label().to_string()); let mut pick = false; - crate::widgets::combo_box("proof-space").width(170.0).selected_text(shown).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box("proof-space").width(170.0).selected_text(shown).show_ui(ui, |ui| { for s in OutputSpace::ALL { if ui.selectable_label(device.is_none() && cur == s, s.label()).clicked() { let _ = app.run("view.softProof", json!({"space": s})); @@ -842,6 +851,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { pick = true; } }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Profile")); if pick && let Some(path) = app.services.pick_display_profile.as_mut().and_then(|pick| pick().into_iter().next()) && let Err(e) = app.run("view.softProof", json!({"profile": path})) @@ -855,7 +865,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { use lightcraft_engine::proof::ProofIntent; for (i, label) in [(ProofIntent::Perceptual, "Perceptual"), (ProofIntent::Relative, "Relative")] { let r = ui.selectable_label(app.ui.proof_intent == i, crate::i18n::tr(label)); - register(ui.ctx(), format!("button:proofIntent-{}", i.name()), r.rect); + register(ui, format!("button:proofIntent-{}", i.name()), r.rect); if r.clicked() && app.ui.proof_intent != i { let _ = app.run("view.softProof", json!({"intent": i.name()})); } @@ -863,13 +873,13 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { }); let mut paper = app.ui.proof_paper_ink; let r = ui.checkbox(&mut paper, crate::i18n::tr("Simulate Paper & Ink")); - register(ui.ctx(), "button:proofPaperInk", r.rect); + register(ui, "button:proofPaperInk", r.rect); if r.changed() { let _ = app.run("view.softProof", json!({"paperInk": paper})); } } let r = ui.button(crate::i18n::tr("Create Proof Copy")); - register(ui.ctx(), "button:createProofCopy", r.rect); + register(ui, "button:createProofCopy", r.rect); if r.clicked() { let target = app.ui.proof_profile.as_ref().map_or_else(|| app.ui.proof.space.label().to_string(), |(_, n)| n.clone()); let name = crate::i18n::tr_format!("Proof Copy ({})", target); @@ -929,6 +939,115 @@ fn draw_curve_histogram(p: &egui::Painter, r: Rect, h: &lightcraft_raster::Histo p.add(mesh); } +/// Segments the graph's curve line is drawn with. +pub(crate) const CURVE_SAMPLES: i32 = 96; + +/// Close a graph drag's `develop` interaction, as one undo step. +/// +/// It is closed when the drag ends *or* the pointer comes up without egui reporting `drag_stopped` +/// for this widget (released outside the window, over a popup, or on a frame the widget does not +/// run). A dangling interaction would make every later edit a silent preview — Undo would then +/// appear to do nothing at all. Returns whether the drag is over, so the caller clears its state. +fn commit_interaction(app: &mut LightcraftApp, ui: &egui::Ui, dragging: bool, stopped: bool) -> bool { + let released = ui.input(|i| i.pointer.any_released()) || !ui.input(|i| i.pointer.primary_down()); + if !dragging || !(stopped || released) { + return false; + } + let _ = app.run("develop.endInteraction", json!({})); + true +} + +/// How close (screen points) to the curve a press counts as grabbing it. +const PARAM_GRAB: f32 = 14.0; + +/// The parametric curve's own drag: the graph shows the curve and nothing else, and dragging the +/// line bends the region the pointer is over, with that region's slider following on the same frame. +/// +/// The whole gesture runs inside one `develop` interaction, so it is one undo step (Ctrl+Z takes the +/// gesture back, not the last frame of it), and every write goes through `develop.set`, so the +/// slider, the curve and what is drawn are the same state rather than three things kept in step. +fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui::Response, d: &DevelopSettings) { + if r.width() <= 1.0 || r.height() <= 1.0 { + return; + } + let t = Tokens::get(ui.ctx()); + let model = ParametricCurve::new(&d.curve); + let to_screen = |x: f64, y: f64| pos2(r.left() + x as f32 * r.width(), r.bottom() - y as f32 * r.height()); + let from_screen_x = |q: Pos2| ((q.x - r.left()) / r.width()).clamp(0.0, 1.0) as f64; + // the graph x of a point, and how far it is from the drawn curve (in screen points) + let near_curve = |q: Pos2| { + let x = from_screen_x(q); + to_screen(x, model.at(x)).distance(q) + }; + let drag_id = egui::Id::unique("curve-param-drag"); + let cursor_id = egui::Id::unique("curve-param-cursor"); + // (region, x, initial_amount, start_y): the region being dragged, the graph x the drag is anchored + // at, the region's starting amount, and the starting screen Y position. + let mut dragged: Option<(usize, f64, f64, f32)> = ui.data(|dd| dd.get_temp::<Option<(usize, f64, f64, f32)>>(drag_id)).flatten(); + let hovered = dragged.is_none() && resp.hover_pos().is_some_and(|q| near_curve(q) <= PARAM_GRAB); + let mut set: Option<(&'static str, f64)> = None; + // the press, not where the pointer is once the drag threshold has passed: a press slightly off + // the line is still a grab, and the pointer has usually left that spot by the time it starts + let press = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()); + if resp.drag_started() + && let Some(q) = press + && near_curve(q) <= PARAM_GRAB + { + let x = from_screen_x(q); + let _ = app.run("develop.beginInteraction", json!({"label": "Parametric Curve"})); + let region = model.region_at(x); + let initial_amount = model.amounts.get(region).copied().unwrap_or(0.0); + let start_pos = to_screen(x, model.at(x)); + dragged = Some((region, x, initial_amount, start_pos.y)); + ui.data_mut(|dd| dd.insert_temp(cursor_id, start_pos)); + } + if let Some((region, x, initial_amount, start_y)) = dragged + && resp.dragged() + { + // Follow the pointer's motion from where the curve was grabbed, so the press itself moves + // nothing and the line tracks the hand. ⌥ = a tenth of the motion, as the point curve does. + let alt = ui.input(|i| i.modifiers.alt); + let dd = ui.input(|i| i.pointer.delta()); + let step = if alt { vec2(dd.x * 0.1, dd.y * 0.1) } else { vec2(dd.x, dd.y) }; + let cursor = ui.data(|d| d.get_temp::<Pos2>(cursor_id)).unwrap_or(pos2(0.0, start_y)) + step; + ui.data_mut(|d| d.insert_temp(cursor_id, cursor)); + let delta_y = start_y - cursor.y; + let delta_level = (delta_y / r.height()) as f64; + let per_unit = model.level_per_unit(region, x); + let new_amount = + if per_unit.abs() > f64::EPSILON { (initial_amount + delta_level / per_unit).clamp(-100.0, 100.0).round() } else { initial_amount }; + if let Some(&id) = PARAM_AMOUNTS.get(region) { + set = Some((id, new_amount)); + } + } + if let Some((id, v)) = set { + let _ = app.run("develop.set", json!({"control": id, "value": v})); + } + let dropped = resp.drag_stopped(); + if commit_interaction(app, ui, dragged.is_some(), dropped) { + dragged = None; + ui.data_mut(|d| { + d.remove::<Pos2>(cursor_id); + d.remove::<Option<(usize, f64, f64, f32)>>(drag_id); + }); + } + ui.data_mut(|dd| dd.insert_temp(drag_id, dragged)); + if dragged.is_some() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } else if hovered { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + // the region under the pointer (or the one in hand), named as its slider below reads it + let shown = dragged.map(|(region, ..)| region).or_else(|| hovered.then(|| resp.hover_pos()).flatten().map(|q| model.region_at(from_screen_x(q)))); + if let Some(region) = shown + && let Some(&id) = PARAM_AMOUNTS.get(region) + && let Some(v) = set.and_then(|(s_id, v)| (s_id == id).then_some(v)).or_else(|| controls::get(d, id)) + { + let name = controls::find(id).map_or("", |s| s.label); + ui.painter().text(r.left_top() + vec2(6.0, 4.0), Align2::LEFT_TOP, format!("{name} {v:.0}"), t.font(11.0), t.text_dim); + } +} + fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &DevelopSettings) { let t = Tokens::get(ui.ctx()); // channel selector @@ -943,7 +1062,7 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev ] { let (r, resp) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click()); crate::widgets::announce(&resp, format!("{} {ch}", crate::i18n::tr("Curve channel"))); - register(ui.ctx(), format!("curveChannel:{ch}"), r); + register(ui, format!("curveChannel:{ch}"), r); let sel = app.ui.curve_channel == ch; if ch == "parametric" { paint(ui.painter(), r.shrink(4.0), Icon::Curve, if sel { t.text } else { t.icon }); @@ -981,9 +1100,9 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev let side = (w - 48.0).max(80.0); let (outer, _) = ui.allocate_exact_size(vec2(w, side + 12.0), Sense::hover()); let r = Rect::from_min_size(pos2(outer.left() + 24.0, outer.top() + 6.0), vec2(side, side)); - let resp = ui.interact(r, egui::Id::new(("curve", &ch)), Sense::click_and_drag()); + let resp = ui.interact(r, egui::Id::unique(("curve", &ch)), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Tone Curve")); - register(ui.ctx(), "curve", r); + register(ui, "curve", r); crate::widgets::context_menu(&resp, |ui| curve_reset_menu(app, ui, &ch)); let p = ui.painter(); p.rect_filled(r, 2.0, t.canvas); @@ -1005,29 +1124,17 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev let to_screen = |x: f64, y: f64| pos2(r.left() + x as f32 * r.width(), r.bottom() - y as f32 * r.height()); let from_screen = |q: Pos2| (((q.x - r.left()) / r.width()).clamp(0.0, 1.0) as f64, ((r.bottom() - q.y) / r.height()).clamp(0.0, 1.0) as f64); if ch == "parametric" { - // draw the effective parametric curve by sampling the pipeline's region curve approximation + // The Effective curve: the model the renderer builds from the four region sliders, sampled + // here and rebuilt every frame. The graph holds no state of its own, so a slider moved by + // hand, a Reset or an Undo redraws it from the settings in the same frame it changes. let c = &d.curve; - let regions = [ - (0.0, c.split_shadows / 100.0, c.shadows), - (c.split_shadows / 100.0, c.split_mid / 100.0, c.darks), - (c.split_mid / 100.0, c.split_highlights / 100.0, c.lights), - (c.split_highlights / 100.0, 1.0, c.highlights), - ]; - let pts: Vec<Pos2> = (0..=64) - .map(|i| { - let x = i as f64 / 64.0; - let mut dd = 0.0; - for (a, b, amt) in regions { - let (ctr, half) = ((a + b) / 2.0, (b - a) * 0.75 + 0.05); - let tt = ((x - ctr) / half).clamp(-1.0, 1.0); - dd += amt / 100.0 * 0.22 * (0.5 + 0.5 * (tt * std::f64::consts::PI).cos()); - } - to_screen(x, (x + dd * 4.0 * x * (1.0 - x)).clamp(0.0, 1.0)) - }) - .collect(); + let model = ParametricCurve::new(c); + let pts: Vec<Pos2> = + (0..=CURVE_SAMPLES).map(|i| to_screen(i as f64 / CURVE_SAMPLES as f64, model.at(i as f64 / CURVE_SAMPLES as f64))).collect(); p.add(egui::Shape::line(pts, Stroke::new(2.0, Color32::from_gray(220)))); + param_drag(app, ui, r, &resp, d); curve_footer(app, ui, d); - for c in ["curve.highlights", "curve.lights", "curve.darks", "curve.shadows"] { + for &c in PARAM_AMOUNTS.iter().rev() { control(app, ui, d, c, true); } control(app, ui, d, "curve.refineSaturation", true); @@ -1058,7 +1165,7 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev p.add(egui::Shape::line(line, Stroke::new(2.0, color))); // interaction: drag a point (both axes, between its neighbours; ⌥ = fine), drag empty space to add and // drag a new point, click empty space to add, double-click a point to delete it - let drag_id = egui::Id::new(("curve-drag", &ch)); + let drag_id = egui::Id::unique(("curve-drag", &ch)); // the point being dragged (stored as `Option<usize>` so a stale value can be cleared) let mut dragging: Option<usize> = ui.data(|dd| dd.get_temp::<Option<usize>>(drag_id)).flatten(); let nearest = |q: Pos2| pts.iter().enumerate().map(|(i, p)| (i, to_screen(p.x, p.y).distance(q))).min_by(|a, b| a.1.total_cmp(&b.1)); @@ -1159,9 +1266,11 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev let arr: Vec<[f64; 2]> = v.iter().map(|p| [p.x, p.y]).collect(); let _ = app.run("develop.curve", json!({"channel": ch, "points": arr})); } - if resp.drag_stopped() { + // the drag is over when egui says so, or when the pointer comes up without it saying so (a + // release outside the window would otherwise leave the interaction open, and every later edit a + // silent preview that Undo cannot take back) + if commit_interaction(app, ui, dragging.is_some(), resp.drag_stopped()) { dragging = None; - let _ = app.run("develop.endInteraction", json!({})); } ui.data_mut(|dd| dd.insert_temp(drag_id, dragging)); curve_footer(app, ui, d); @@ -1190,7 +1299,7 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) ui.separator(); } let r = ui.selectable_label(current.as_deref() == Some(p.name.as_str()), crate::i18n::builtin_label(&p.name, p.builtin)); - register(ui.ctx(), format!("curvePreset:{}", p.name), r.rect); + register(ui, format!("curvePreset:{}", p.name), r.rect); if r.clicked() { let _ = app.run("curve.applyPreset", json!({"name": p.name})); ui.close(); @@ -1207,7 +1316,7 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) ui.separator(); let shaped = current.as_deref() != Some("Linear"); let r = ui.add_enabled(shaped, egui::Button::new(crate::i18n::tr("Save Point Curve…"))); - register(ui.ctx(), "curvePresetMenu:save", r.rect); + register(ui, "curvePresetMenu:save", r.rect); if r.clicked() { crate::panels::dialogs::prompt(app, "Save Point Curve Preset", "Preset name", "", "curve.savePreset", json!({}), "name"); ui.close(); @@ -1245,13 +1354,13 @@ fn curve_reset_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, ch: &str) { crate::i18n::tr_format!("Reset {} Channel", crate::i18n::tr(channel_label(ch))) }; let r = ui.button(label); - register(ui.ctx(), "curveMenu:resetChannel", r.rect); + register(ui, "curveMenu:resetChannel", r.rect); if r.clicked() { let _ = app.run("curve.reset", json!({"channel": ch})); ui.close(); } let r = ui.button(crate::i18n::tr("Reset All Curves")); - register(ui.ctx(), "curveMenu:resetAll", r.rect); + register(ui, "curveMenu:resetAll", r.rect); if r.clicked() { let _ = app.run("curve.reset", json!({"channel": "all"})); ui.close(); @@ -1300,7 +1409,7 @@ fn mixer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { for (i, b) in bands.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr(b)); - register(ui.ctx(), format!("mixerBand:{b}"), r); + register(ui, format!("mixerBand:{b}"), r); ui.painter().circle_filled(r.center(), 9.0, hex(BAND_COLORS[i])); if i == sel { ui.painter().circle_stroke(r.center(), 10.5, Stroke::new(1.5, t.text)); @@ -1392,7 +1501,7 @@ fn point_color(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) for (i, p) in d.point_colors.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); crate::widgets::announce(&resp, format!("{} {}", crate::i18n::tr("Point Color"), i + 1)); - register(ui.ctx(), format!("pointColor:{i}"), r); + register(ui, format!("pointColor:{i}"), r); ui.painter().rect_filled(r.shrink(2.0), 3.0, oklch_color(p.lum, p.chroma, p.hue)); if i == sel { ui.painter().rect_stroke(r, 4.0, Stroke::new(1.5, t.text), egui::StrokeKind::Inside); @@ -1443,7 +1552,7 @@ fn hdr_row(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 4, bottom: 4 }).show(ui, |ui| { let mut v = app.ui.hdr_visualize; let r = ui.checkbox(&mut v, "Visualize HDR"); - register(ui.ctx(), "check:hdrVisualize", r.rect); + register(ui, "check:hdrVisualize", r.rect); if r.on_hover_text("Grey below SDR white; yellow, orange, red, magenta up to 1, 2, 3 and over 3 stops above it").changed() { app.ui.hdr_visualize = v; } @@ -1526,12 +1635,12 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings // the corners (eye, readout) count as the wheel for hovering let zone = r.expand(10.0); let hovering = ui.rect_contains_pointer(zone); - let resp = ui.interact(r, egui::Id::new(("wheel", key)), Sense::click_and_drag()); + let resp = ui.interact(r, egui::Id::unique(("wheel", key)), Sense::click_and_drag()); crate::widgets::announce(&resp, format!("{} {key}", crate::i18n::tr("Color wheel"))); let resp = resp.on_hover_text(crate::i18n::tr( "Drag to set hue and saturation. Hold Shift to keep the hue, Cmd/Ctrl to keep the saturation, Alt/Option to fine-adjust. Double-click to reset.", )); - register(ui.ctx(), format!("wheel:{key}"), r); + register(ui, format!("wheel:{key}"), r); paint_wheel(ui.painter(), c, rad); if hidden { ui.painter().circle_filled(c, rad, Color32::from_black_alpha(150)); @@ -1550,9 +1659,10 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings // Modifiers (as in Lightroom): Shift keeps the hue, Cmd/Ctrl keeps the saturation, Alt moves // the puck a tenth as far as the pointer. Pressing or releasing one mid-drag re-grabs the // puck as it is at that moment. - let grab_id = egui::Id::new(("wheelGrab", key)); + let grab_id = egui::Id::unique(("wheelGrab", key)); let mods = ui.input(|i| WheelMods::from_modifiers(i.modifiers)); - let grab = match resp.interact_pointer_pos() { + let pointer = wheel_pointer(ui, &resp); + let grab = match pointer { Some(q) if resp.dragged() || resp.clicked() => { let held = ui.data(|m| m.get_temp::<WheelGrab>(grab_id)).filter(|g| g.mods == mods && !resp.drag_started()); Some(held.unwrap_or_else(|| { @@ -1591,7 +1701,7 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings let _ = app.run("develop.beginInteraction", json!({"label": crate::i18n::tr_format!("{label} Grading", label = label)})); } if (resp.dragged() || resp.clicked()) - && let Some(q) = resp.interact_pointer_pos() + && let Some(q) = pointer { let (hue, sat) = grab.map_or_else(|| wheel_pick(q - c, rad, None), |g| g.pick(q - c, rad)); let _ = app.run("develop.set", json!({"values": {format!("grading.{key}.hue"): hue.round(), format!("grading.{key}.sat"): sat.round()}})); @@ -1599,6 +1709,13 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings if resp.drag_stopped() || resp.clicked() { let _ = app.run("develop.endInteraction", json!({})); } + // released, or Esc (egui ends a drag on it) + if resp.drag_stopped() + && let Some(held) = ui.ctx().data_mut(|m| m.remove_temp::<WheelCapture>(egui::Id::unique(WHEEL_CAPTURE))) + && !held.dropped + { + give_pointer_back(ui.ctx(), held.origin); + } if resp.double_clicked() { let _ = app.run("develop.set", json!({"values": {format!("grading.{key}.hue"): 0, format!("grading.{key}.sat"): 0}})); } @@ -1616,9 +1733,9 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings // the eye: on top of the wheel, shown while hovering or while the wheel is hidden if hovering || hidden { let eye = Rect::from_center_size(r.left_bottom() + vec2(2.0, -2.0), vec2(16.0, 16.0)); - let er = ui.interact(eye, egui::Id::new(("wheelEye", key)), Sense::click()); + let er = ui.interact(eye, egui::Id::unique(("wheelEye", key)), Sense::click()); crate::widgets::announce(&er, crate::i18n::tr("Show / hide")); - register(ui.ctx(), format!("wheelEye:{key}"), eye); + register(ui, format!("wheelEye:{key}"), eye); paint(ui.painter(), eye, if hidden { Icon::EyeOff } else { Icon::Eye }, if hidden { t.text_disabled } else { t.icon }); let er = er.on_hover_text(crate::i18n::tr(if hidden { "Show this wheel's effect" } else { "Hide this wheel's effect" })); if er.clicked() { @@ -1702,6 +1819,99 @@ impl WheelGrab { } } +/// A wheel drag holds the pointer, as in Lightroom (issue #1899): it is hidden for the drag, the +/// puck follows the mouse's own travel, and on release the pointer is back where the button went +/// down, so a long (Alt) drag doesn't leave it far from the wheels. On macOS the pointer is locked +/// in place for the drag; elsewhere it moves unseen and is put back. The browser can't move it +/// (eframe's web host ignores the command), so there it only shows again where the drag ended. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct WheelCapture { + /// Where the button went down: the pointer goes back there. + origin: Pos2, + /// Where the pointer would be had it been free: where the drag began plus the travel since. + pos: Pos2, + /// Let go early (the window lost focus): the rest of this drag leaves the wheel alone. + dropped: bool, + /// The pass that last drew the dragged wheel. + pass: u64, +} + +/// One wheel is dragged at a time, so one capture for them all. +const WHEEL_CAPTURE: &str = "wheelCapture"; + +/// The mouse's travel this frame: the pointer's, or, while the pointer stands still (locked, or +/// against a screen edge), the raw motion the host reports. +fn wheel_travel(delta: egui::Vec2, motion: Option<egui::Vec2>) -> egui::Vec2 { + if delta != egui::Vec2::ZERO { + return delta; + } + motion.filter(|m| m.x.is_finite() && m.y.is_finite()).unwrap_or(egui::Vec2::ZERO) +} + +/// Where the wheel `resp` reads the pointer this frame: where it clicked, or for a drag the held +/// pointer ([`WheelCapture`]), `None` once a lost focus let go of it (Esc ends the drag itself: +/// egui stops a drag on Esc). +fn wheel_pointer(ui: &egui::Ui, resp: &egui::Response) -> Option<Pos2> { + let q = resp.interact_pointer_pos()?; + if !resp.dragged() { + return Some(q); + } + let ctx = ui.ctx(); + let id = egui::Id::unique(WHEEL_CAPTURE); + let held = ctx.data(|m| m.get_temp::<WheelCapture>(id)).filter(|_| !resp.drag_started()); + let mut cap = held.unwrap_or_else(|| { + if cfg!(target_os = "macos") { + ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked)); + } + WheelCapture { origin: ui.input(|i| i.pointer.press_origin()).unwrap_or(q), pos: q, ..Default::default() } + }); + cap.pass = ctx.cumulative_pass_nr(); + if !cap.dropped { + let (travel, unfocused) = ui.input(|i| { + // the event, not `focused`: a click that activates the window may land before its focus + let unfocused = i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(false))); + (wheel_travel(i.pointer.delta(), i.pointer.motion()), unfocused) + }); + if !resp.drag_started() { + cap.pos += travel; + } + if unfocused { + give_pointer_back(ctx, cap.origin); + cap.dropped = true; + } else { + ctx.set_cursor_icon(egui::CursorIcon::None); + } + } + ctx.data_mut(|m| m.insert_temp(id, cap)); + (!cap.dropped).then_some(cap.pos) +} + +/// Unlock and show the pointer a wheel drag held, back at `origin`. +fn give_pointer_back(ctx: &egui::Context, origin: Pos2) { + if cfg!(target_os = "macos") { + ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(egui::CursorGrab::None)); + } + if cfg!(not(target_arch = "wasm32")) { + ctx.send_viewport_cmd(egui::ViewportCommand::CursorPosition(origin)); + } +} + +/// Once a frame, after the panels: a held pointer stays hidden over whatever set its own cursor, +/// and is given back if no wheel drew this pass (the flyout closed or the view changed under the +/// drag), so it is never left locked or hidden. +pub(crate) fn wheel_pointer_frame_end(ctx: &egui::Context) { + let id = egui::Id::unique(WHEEL_CAPTURE); + let Some(cap) = ctx.data(|m| m.get_temp::<WheelCapture>(id)) else { return }; + if cap.pass != ctx.cumulative_pass_nr() { + ctx.data_mut(|m| m.remove::<WheelCapture>(id)); + if !cap.dropped { + give_pointer_back(ctx, cap.origin); + } + } else if !cap.dropped { + ctx.set_cursor_icon(egui::CursorIcon::None); + } +} + /// Hue (degrees) and saturation (0..100) for a pointer at offset `v` from a wheel's centre. /// `lock`: hold the hue (the saturation is `v` projected onto that hue's spoke) or hold the /// saturation (the hue is the angle of `v`). A non-finite `v` gives a finite answer (the locked @@ -1797,12 +2007,12 @@ fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize) { let r = crate::widgets::arrow_button(ui, "", icon, false); r.widget_info(|| { egui::WidgetInfo::labeled( - egui::WidgetType::Button, + egui::Role::Button, ui.is_enabled(), crate::i18n::tr_format!("{label} {d:+} on every selected photo", d = d, label = crate::i18n::tr(label)), ) }); - crate::widgets::register(ui.ctx(), format!("button:quick-{ctl}-{txt}"), r.rect); + crate::widgets::register(ui, format!("button:quick-{ctl}-{txt}"), r.rect); if r.on_hover_text(crate::i18n::tr_format!("{label} {d:+} on every selected photo", d = d, label = crate::i18n::tr(label))) .clicked() { diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rs index f1eb97caf5..76cd1295cb 100644 --- a/crates/ui-egui/src/panels/faces.rs +++ b/crates/ui-egui/src/panels/faces.rs @@ -21,7 +21,7 @@ use crate::widgets::register; /// machine once they have been idle for a few seconds, or while another app has the keyboard but this window is still /// on screen; most of it while they are looking at the scan's progress. fn scan_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64) -> (&'static str, bool) { - let (focused, minimized) = ctx.input(|i| (i.focused, i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.minimized).unwrap_or(false))); + let (focused, minimized) = ctx.input(|i| (i.raw.focused, i.viewport().minimized.unwrap_or(false))); let watching = matches!(&app.ui.dialog, Some(crate::state::Dialog::Settings { tab }) if tab == "faces") || app.ui.view == crate::state::ViewMode::People; (pace_for(focused, minimized, now - app.caches.last_input, now - app.caches.last_move, watching), focused && !minimized) @@ -30,7 +30,7 @@ fn scan_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64) -> (&'static st /// The pace for other background work that reads the library's files (the focus-point reader): the face scan's, without /// the "watching" speed-up. pub(crate) fn background_pace(app: &LightcraftApp, ctx: &egui::Context, now: f64) -> &'static str { - let (focused, minimized) = ctx.input(|i| (i.focused, i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.minimized).unwrap_or(false))); + let (focused, minimized) = ctx.input(|i| (i.raw.focused, i.viewport().minimized.unwrap_or(false))); pace_for(focused, minimized, now - app.caches.last_input, now - app.caches.last_move, false) } @@ -58,12 +58,12 @@ fn pace_for(focused: bool, minimized: bool, worked: f64, moved: f64, watching: b const REFRESH_SECS: f64 = 1.5; fn list_id() -> egui::Id { - egui::Id::new("faces-model-list") + egui::Id::unique("faces-model-list") } /// The engine's model list, re-read at most every [`REFRESH_SECS`], or at once after an action changed it. fn models(app: &mut LightcraftApp, ctx: &egui::Context) -> Value { - let now = ctx.input(|i| i.time); + let now = app.tick_now(); let epoch = app.caches.faces_epoch; if let Some((e, at, v)) = ctx.data(|d| d.get_temp::<(u64, f64, Value)>(list_id())) && e == epoch @@ -156,7 +156,7 @@ pub fn setup_banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.horizontal_wrapped(|ui| { ui.label(RichText::new(message).font(t.font(12.5)).color(t.text_dim)); let r = ui.button(button); - register(ui.ctx(), "faces:setup", r.rect); + register(ui, "faces:setup", r.rect); if r.clicked() { take_step(app, ui.ctx(), step); } @@ -170,7 +170,7 @@ fn gpu_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, gpu: &Val heading(ui, t, "Processor"); let mut cpu = gpu["cpuOnly"].as_bool().unwrap_or(false); let r = ui.checkbox(&mut cpu, crate::i18n::tr("Run face models on the CPU only")); - register(ui.ctx(), "check:settings.facesCpuOnly", r.rect); + register(ui, "check:settings.facesCpuOnly", r.rect); if r.changed() { match app.run("faces.gpu", json!({"cpuOnly": cpu})) { Ok(_) => app.caches.faces_epoch += 1, @@ -190,8 +190,11 @@ fn gpu_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, gpu: &Val }; ui.horizontal(|ui| { ui.label(RichText::new(crate::i18n::tr(label)).color(t.text_dim)); + if st["checking"] == true { + crate::progress::spinner(ui, 12.0); + } let r = ui.label(text); - register(ui.ctx(), format!("faces:device:{what}"), r.rect); + register(ui, format!("faces:device:{what}"), r.rect); if let Some(why) = why { r.on_hover_text(sentence(why)); } @@ -254,7 +257,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = ui .add_enabled(on || (runtime && usable), egui::Checkbox::new(&mut on, crate::i18n::tr("Recognise faces (experimental)"))) .on_disabled_hover_text(crate::i18n::tr("Choose a model below (Use) to start.")); - register(ui.ctx(), "check:settings.facesEnabled", r.rect); + register(ui, "check:settings.facesEnabled", r.rect); if r.changed() { match app.run("faces.enable", json!({"enabled": on})) { Ok(_) => app.caches.faces_epoch += 1, @@ -288,7 +291,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ui.horizontal(|ui| { let can = app.services.pick_model_file.is_some(); let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Add a model file…"))); - register(ui.ctx(), "faces:addModel", r.rect); + register(ui, "faces:addModel", r.rect); if r.clicked() { let _ = app.run("dialog.faceModel", json!({})); } @@ -312,10 +315,7 @@ fn scan_progress(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { return; } let text = format!("Scanning photos for faces: {left} left · {faces} faces so far"); - let bar = ui.add( - egui::ProgressBar::new((1.0 - left as f32 / peak as f32).clamp(0.0, 1.0)).desired_width(380.0).text(RichText::new(text).font(t.font(11.5))), - ); - register(ui.ctx(), "faces:scanProgress", bar.rect); + crate::progress::Progress::new(Some(1.0 - left as f32 / peak as f32)).label(text).widget("faces:scanProgress").show(ui); } fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, dl: Option<&Value>, can_run: bool) { @@ -361,17 +361,22 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, match (dl_state, dl) { (Some("running"), Some(d)) => { let (got, total) = (d["bytes"].as_u64().unwrap_or(0), d["total"].as_u64().unwrap_or(0)); - let frac = if total > 0 { (got as f32 / total as f32).clamp(0.0, 1.0) } else { 0.0 }; let text = if total > 0 && got >= total { "Checking…".to_string() } else { format!("{} of {} from {host}", mb(Some(got)), mb(Some(total))) }; - let bar = ui.add(egui::ProgressBar::new(frac).desired_width(260.0).text(RichText::new(text).font(t.font(11.5)))); - register(ui.ctx(), format!("faces:progress:{id}"), bar.rect); + crate::progress::Progress::new(crate::progress::fraction_of(got, total)) + .label(text) + .width(crate::progress::ROW_WIDTH.min(ui.available_width())) + .widget(format!("faces:progress:{id}")) + .show(ui); } (Some("done"), _) => { - ui.label(RichText::new(crate::i18n::tr("Downloaded and checked. Installing…")).font(t.font(11.5)).color(t.text_dim)); + ui.horizontal(|ui| { + crate::progress::spinner(ui, 12.0); + ui.label(RichText::new(crate::i18n::tr("Downloaded and checked. Installing…")).font(t.font(11.5)).color(t.text_dim)); + }); } (Some("failed"), Some(d)) => { let why = sentence(d["error"].as_str().unwrap_or("The download failed")); @@ -383,14 +388,14 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if installed { let r = ui.button(crate::i18n::tr("Remove")); - register(ui.ctx(), format!("faces:remove:{id}"), r.rect); + register(ui, format!("faces:remove:{id}"), r.rect); if r.clicked() { let _ = app.run("faces.models.remove", json!({"id": id})); app.caches.faces_epoch += 1; } if !selected && !detector { let r = ui.button("Use"); - register(ui.ctx(), format!("faces:use:{id}"), r.rect); + register(ui, format!("faces:use:{id}"), r.rect); if r.clicked() { let _ = app.run("faces.models.select", json!({"id": id})); app.caches.faces_epoch += 1; @@ -400,7 +405,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, match dl_state { Some("running") => { let r = ui.button(crate::i18n::tr("Cancel")); - register(ui.ctx(), format!("faces:cancelDownload:{id}"), r.rect); + register(ui, format!("faces:cancelDownload:{id}"), r.rect); if r.clicked() { let _ = app.run("faces.models.downloadCancel", json!({"id": id})); app.caches.faces_dl_watch.retain(|w| w != &id); @@ -413,7 +418,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, let r = ui.button(crate::i18n::tr("Open page")).on_hover_text(crate::i18n::tr( "Opens the model's own page in your browser, to read about it or get the file yourself.", )); - register(ui.ctx(), format!("faces:get:{id}"), r.rect); + register(ui, format!("faces:get:{id}"), r.rect); if r.clicked() { open_page(app, url); } @@ -426,7 +431,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, if detector { "" } else { ", starts using it" } ); let r = ui.button(label).on_hover_text(tip); - register(ui.ctx(), format!("faces:download:{id}"), r.rect); + register(ui, format!("faces:download:{id}"), r.rect); if r.clicked() { open_download_dialog(app, m); } @@ -500,7 +505,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info } if let Some(url) = m["source"].as_str().or(m["licence"]["url"].as_str()) { let r = ui.link("Open the model's page"); - register(ui.ctx(), "faceModel:page", r.rect); + register(ui, "faceModel:page", r.rect); if r.clicked() { open_page(app, url); } @@ -642,11 +647,11 @@ pub fn name_editor( let t = Tokens::get(ctx); let mut outcome = Editor::Open; let opening = edit.fresh; - let shown = egui::Area::new(egui::Id::new("face-name-editor")).order(egui::Order::Foreground).fixed_pos(at).constrain(true).show(ctx, |ui| { + let shown = egui::Area::new(egui::Id::unique("face-name-editor")).order(egui::Order::Foreground).fixed_pos(at).constrain(true).show(ctx, |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { ui.set_min_width(230.0); let r = ui.add(egui::TextEdit::singleline(&mut edit.text).hint_text("Name").desired_width(220.0)); - register(ui.ctx(), "field:faceName", r.rect); + register(ui, "field:faceName", r.rect); if edit.fresh { r.request_focus(); edit.fresh = false; @@ -672,14 +677,14 @@ pub fn name_editor( None => name.clone(), }; let b = ui.add(egui::Button::new(RichText::new(label).color(t.text_label)).frame(false).min_size(egui::vec2(220.0, 0.0))); - register(ui.ctx(), format!("faceName:pick:{name}"), b.rect); + register(ui, format!("faceName:pick:{name}"), b.rect); if b.clicked() { outcome = Editor::Submit(name); } } if let Some(label) = setup.short() { let b = ui.add(egui::Button::new(RichText::new(label).font(t.font(12.0)).color(t.accent)).frame(false)); - register(ui.ctx(), "faces:setup", b.rect); + register(ui, "faces:setup", b.rect); if b.clicked() { outcome = Editor::Setup; } @@ -700,9 +705,15 @@ pub fn name_editor( /// Called every frame: keeps the background face indexer going while recognition is on, and notes whether it is /// running, how many faces it has done and how many photos are left (the loupe's suggestions depend on it). +/// `pump_background` plus the UI-input half; the app's own phases keep them apart. pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { - watch_downloads(app, ctx); - let now = ctx.input(|i| i.time); + let now = app.tick_now(); + pump_ui_input(app, ctx, now); + pump_background(app, ctx, now); +} + +/// Fresh pointer/key activity (UI phase only). +pub fn pump_ui_input(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { let (working, moving) = ctx.input(|i| { let key_or_scroll = i.events.iter().any(|e| matches!(e, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::MouseWheel { .. })); (i.pointer.any_down() || key_or_scroll, i.pointer.is_moving()) @@ -713,6 +724,11 @@ pub fn pump(app: &mut LightcraftApp, ctx: &egui::Context) { if moving || working { app.caches.last_move = now; } +} + +/// Worker results and pacing on monotonic deadlines; safe while hidden. +pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { + watch_downloads(app, ctx); if now < app.caches.faces_next_pump { return; } diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index 8365a1ff89..8b34fbaf95 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -33,7 +33,7 @@ fn toggle(ui: &mut egui::Ui, id: &str, on: bool, tip: &str, draw: impl FnOnce(&e let t = Tokens::get(ui.ctx()); let (r, resp) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::click()); crate::widgets::announce_selected(&resp, crate::i18n::tr(tip), on); - register(ui.ctx(), format!("filter:{id}"), r); + register(ui, format!("filter:{id}"), r); let p = ui.painter(); if on { p.rect_filled(r, 5.0, t.tool_active); @@ -100,7 +100,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), if two_rows { 2.0 * HEIGHT - 8.0 } else { HEIGHT }), Sense::hover()); ui.painter().rect_filled(bar, 0.0, t.chrome); ui.painter().line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.divider)); - register(ui.ctx(), "filterbar", bar); + register(ui, "filterbar", bar); let f = app.session.filter.clone(); let row = |ui: &mut egui::Ui, i: f32| { let r = Rect::from_min_size(bar.min + vec2(16.0, 4.0 + i * (HEIGHT - 8.0)), vec2(bar.width() - 32.0, HEIGHT - 8.0)); @@ -130,22 +130,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { .map(|(l, k, op)| (l.to_string(), json!({"ratingOp": k}), f.rating_op == op)) .collect(), ); - for i in 1..=5u8 { - let (r, resp) = ui.allocate_exact_size(vec2(17.0, 26.0), Sense::click()); - crate::widgets::announce(&resp, format!("{i} ★")); - register(ui.ctx(), format!("filter:star{i}"), r); - let filled = i <= f.rating; - let c = if filled { - t.star - } else if resp.hovered() { - t.text_label - } else { - t.icon - }; - paint(ui.painter(), Rect::from_center_size(r.center(), vec2(14.0, 14.0)), if filled { Icon::StarFilled } else { Icon::Star }, c); - if resp.clicked() { - filter(app, json!({"rating": if f.rating == i { 0 } else { i }})); - } + if let Some(r) = crate::rating::Rating::new("filter", f.rating).automation_ids("filter:star").show(ui) { + filter(app, json!({"rating": r})); } ui.add_space(14.0); @@ -172,13 +158,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // colour labels caption(ui, "Label"); - // several labels can be on at once (any of them matches) - let mut chosen: Vec<ColorLabel> = f.labels.clone(); - if let Some(l) = f.label - && !chosen.contains(&l) - { - chosen.push(l); - } + // several labels can be on at once (any of them matches); lit are those `label` and `labels` both let through + let chosen: Vec<ColorLabel> = f.labels_shown().unwrap_or_default(); for l in ColorLabel::ALL { let on = chosen.contains(&l); let name = format!("{l:?}").to_lowercase(); @@ -272,19 +253,19 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.add_space(14.0); let filtering = app.session.filter != Default::default(); let save = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.font(12.5)))); - register(ui.ctx(), "button:filterSave", save.rect); + register(ui, "button:filterSave", save.rect); if save.clicked() { let _ = app.run("dialog.newSmartAlbum", json!({})); } let clear = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Clear")).font(t.font(12.5)))); - register(ui.ctx(), "button:filterClear", clear.rect); + register(ui, "button:filterClear", clear.rect); if clear.clicked() { app.ui.search.clear(); let _ = app.run("library.clearFilter", json!({})); } // filter presets: apply one, save the current filter, delete let presets = crate::widgets::dropdown(ui, "filterPresets", crate::i18n::tr("Presets"), t.font(12.5), t.text); - register(ui.ctx(), "button:filterPresets", presets.rect); + register(ui, "button:filterPresets", presets.rect); egui::Popup::menu(&presets).show(|ui| { let names: Vec<String> = app.session.filter_presets.iter().map(|f| f.name.clone()).collect(); for n in &names { diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index a1184892c4..ba2e488698 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -309,10 +309,10 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x); let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text); let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.font(12.5), t.text_dim); - crate::widgets::register(ui.ctx(), "grid:title", title_rect); - crate::widgets::register(ui.ctx(), "grid:count", count_rect); + crate::widgets::register(ui, "grid:title", title_rect); + crate::widgets::register(ui, "grid:count", count_rect); if title != full { - ui.interact(title_rect, ui.id().with("grid-title"), Sense::hover()).on_hover_text(full); + ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full); } } } @@ -384,7 +384,7 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let active = app.session.selection.active; // bring the active photo into view when it changes (keyboard, click, command) or the grid // comes back on screen; otherwise the scroll position is the user's - let scroll_to: Option<Rect> = if follow_active(ui.ctx(), egui::Id::new("grid-follow-active"), active, app.session.source) { + let scroll_to: Option<Rect> = if follow_active(ui.ctx(), egui::Id::unique("grid-follow-active"), active, app.session.source) { active.and_then(|a| ids.iter().position(|x| *x == a)).and_then(|i| lay.cells.get(i).copied()) } else { None @@ -393,8 +393,8 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let mut visited = 0u64; // a wheel notch scrolls a third of the grid's height let scroll_rect = ui.available_rect_before_wrap(); - crate::widgets::register(ui.ctx(), "grid:scroll", scroll_rect); - let wheel = wheel_step(ui, egui::Id::new("grid-wheel"), scroll_rect, scroll_rect.height(), false); + crate::widgets::register(ui, "grid:scroll", scroll_rect); + let wheel = wheel_step(ui, egui::Id::unique("grid-wheel"), scroll_rect, scroll_rect.height(), false); egui::ScrollArea::vertical().id_salt("grid-scroll").auto_shrink([false, false]).show_viewport(ui, |ui, viewport| { if wheel != egui::Vec2::ZERO { ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none()); @@ -656,10 +656,10 @@ pub fn layout(aspects: &[f32], groups: &[(usize, usize)], avail_w: f32, target: /// (Cmd/Shift: adds to the selection). fn group_header(app: &mut LightcraftApp, ui: &mut egui::Ui, run: &DateRun, ids: &[PhotoId], r: Rect, pinned: bool) { let t = Tokens::get(ui.ctx()); - let resp = ui.interact(r, egui::Id::new(("group-header", run.start, pinned)), Sense::click()); + let resp = ui.interact(r, egui::Id::unique(("group-header", run.start, pinned)), Sense::click()); crate::widgets::announce(&resp, if run.key.is_empty() { crate::i18n::tr("Unknown date").to_string() } else { run.key.clone() }); if !pinned { - register(ui.ctx(), format!("group:{}", if run.key.is_empty() { "unknown" } else { &run.key }), r); + register(ui, format!("group:{}", if run.key.is_empty() { "unknown" } else { &run.key }), r); } let p = ui.painter(); if pinned { @@ -758,8 +758,8 @@ pub const BACKGROUND_THUMB_PRIORITY: u32 = 3; fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square: bool, onscreen: bool, ppp: f32) { let t = Tokens::get(ui.ctx()); let Some(photo) = app.session.catalog.photo(id).cloned() else { return }; - let resp = ui.interact(r, egui::Id::new(("cell", id.0)), Sense::click_and_drag()); - register(ui.ctx(), format!("thumb:{}", id.0), r); + let resp = ui.interact(r, egui::Id::unique(("cell", id.0)), Sense::click_and_drag()); + register(ui, format!("thumb:{}", id.0), r); let state = app.session.selection.state_of(id); let selected = state != lightcraft_engine::SelectionState::NotSelected; // screen readers: the file, then rating / flag / label @@ -775,7 +775,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square if let Some(l) = photo.label { spoken.push_str(&crate::i18n::tr_format!(", {} label", crate::i18n::color_label(&app.session.catalog, l))); } - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &spoken)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &spoken)); let active = state == lightcraft_engine::SelectionState::Active; let p = ui.painter(); let img_rect = if square { @@ -800,16 +800,18 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square } } else { let ph = img_rect.shrink(if square { 20.0 } else { 0.0 }); - p.rect_filled(ph, 0.0, Color32::from_gray(38)); + p.rect_filled(ph, 0.0, t.skeleton); // not drawn yet (or unreadable): the selection is still visible if active { p.rect_stroke(ph, 0.0, Stroke::new(2.0, Color32::WHITE), StrokeKind::Outside); } else if selected { - p.rect_stroke(ph, 0.0, Stroke::new(2.0, Color32::from_gray(170)), StrokeKind::Outside); + // a light theme's skeleton is itself mid-grey: the ring takes the dim text colour + let ring = if t.skeleton.r() > 0x80 { t.text_dim } else { Color32::from_gray(170) }; + p.rect_stroke(ph, 0.0, Stroke::new(2.0, ring), StrokeKind::Outside); } if app.renderer.failure(Slot::Thumb(id)).is_some() { // unreadable / missing file - p.text(ph.center(), Align2::CENTER_CENTER, "!", t.semibold(18.0), t.text_dim); + p.text(ph.center(), Align2::CENTER_CENTER, "!", t.semibold(18.0), t.text); } } // labels and badges @@ -857,10 +859,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square p.rect_filled(bar, 0.0, Color32::from_black_alpha(120)); } let mut x = bar.left() + 6.0; - for i in 0..photo.rating { - paint(p, Rect::from_min_size(pos2(x + i as f32 * 13.0, bar.center().y - 6.0), vec2(12.0, 12.0)), Icon::StarFilled, t.star); - } - x += photo.rating as f32 * 13.0 + 4.0; + x += crate::rating::paint_rating(p, pos2(x, bar.center().y), photo.rating, crate::rating::RatingSize::Medium, t.star) + 4.0; match photo.flag { Flag::Pick => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagPickFilled, t.pick), Flag::Reject => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagReject, t.reject), @@ -901,8 +900,8 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square p.rect_filled(br, 8.0, Color32::from_black_alpha(170)); paint(p, Rect::from_center_size(pos2(br.left() + 9.0, br.center().y), vec2(12.0, 12.0)), Icon::Info, t.caution); p.galley(pos2(br.left() + 17.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE); - register(ui.ctx(), format!("badge:previewOnly:{}", id.0), br); - ui.interact(br, egui::Id::new(("preview-only-badge", id.0)), Sense::hover()) + register(ui, format!("badge:previewOnly:{}", id.0), br); + ui.interact(br, egui::Id::unique(("preview-only-badge", id.0)), Sense::hover()) .on_hover_text(crate::i18n::tr_format!("Preview only — {}", crate::widgets::preview_only_explanation(why))); } if photo.flag == Flag::Reject { @@ -963,7 +962,7 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi folder_breadcrumbs(app, ui, &b.path); }); let count = ui.add_sized(vec2(count_w, 24.0), egui::Label::new(egui::RichText::new(cnt).size(12.5).color(t.text_dim)).truncate()); - register(ui.ctx(), "grid:count", count.rect); + register(ui, "grid:count", count.rect); count.on_hover_text(cnt); }); ui.horizontal_wrapped(|ui| { @@ -971,7 +970,7 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); let mut sub = b.subfolders; let c = ui.checkbox(&mut sub, crate::i18n::tr("Include subfolders")); - register(ui.ctx(), "check:includeSubfolders", c.rect); + register(ui, "check:includeSubfolders", c.rect); if c.changed() { let _ = app.run("library.browse", json!({"path": b.path, "subfolders": sub})); } @@ -980,7 +979,7 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi let label = crate::i18n::tr_format!("Add {local_n} to My Photos", local_n = local_n); let button = ui.add(egui::Button::new(egui::RichText::new(label).font(t.semibold(11.5)).color(t.text)).wrap().min_size(vec2(37.0, 24.0))); - register(ui.ctx(), "button:addToLibrary", button.rect); + register(ui, "button:addToLibrary", button.rect); if button.clicked() { let local: Vec<u64> = ids.iter().filter(|id| app.session.catalog.photo(**id).is_some_and(|p| p.local)).map(|id| id.0).collect(); let n = local.len(); @@ -992,7 +991,7 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi } }); }); - register(ui.ctx(), "grid:folderHeader", header.response.rect); + register(ui, "grid:folderHeader", header.response.rect); header.response.rect } @@ -1043,7 +1042,7 @@ fn folder_breadcrumbs(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) { let width = ((ui.available_width() - separator_w * (remaining - 1) as f32) / remaining as f32).max(0.0).floor(); let text = egui::RichText::new(*part).size(13.0).color(if last { t.text } else { t.text_label }); let r = ui.add_sized(vec2(width, 24.0), egui::Label::new(if last { text.strong() } else { text }).truncate().sense(Sense::click())); - register(ui.ctx(), format!("crumb:{i}"), r.rect); + register(ui, format!("crumb:{i}"), r.rect); if !last { if r.hovered() { ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); @@ -1065,7 +1064,7 @@ fn folder_breadcrumbs(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) { /// drop would put them (set by the drop target under the pointer, read by [`drag_feedback`]). pub fn drag_hint(ctx: &egui::Context, text: String) { let frame = ctx.cumulative_frame_nr(); - ctx.data_mut(|d| d.insert_temp(egui::Id::new("drag-photos-hint"), (frame, text))); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("drag-photos-hint"), (frame, text))); } pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { @@ -1081,14 +1080,17 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { ctx.set_cursor_icon(egui::CursorIcon::Grabbing); // a drop target under the pointer says where they would go (only this frame's) let frame = ctx.cumulative_frame_nr(); - let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::new("drag-photos-hint"))).filter(|(f, _)| *f == frame).map(|(_, text)| text); + let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))).filter(|(f, _)| *f == frame).map(|(_, text)| text); let text = hint.unwrap_or_else(|| crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)); - egui::Area::new(egui::Id::new("drag-photos")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(ctx, |ui| { - egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { - let label = ui.add(egui::Label::new(egui::RichText::new(text).color(Color32::WHITE).font(t.semibold(12.0))).extend()); - crate::widgets::register(ui.ctx(), "dragPhotos", label.rect); - }); - }); + egui::Area::new(egui::Id::unique("drag-photos")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show( + ctx, + |ui| { + egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { + let label = ui.add(egui::Label::new(egui::RichText::new(text).color(Color32::WHITE).font(t.semibold(12.0))).extend()); + crate::widgets::register(ui, "dragPhotos", label.rect); + }); + }, + ); } pub use super::filterbar::label_color; @@ -1142,13 +1144,13 @@ pub fn label_items(app: &mut LightcraftApp, ui: &mut egui::Ui, current: Option<C ui.painter().circle_filled(r.center(), 5.0, label_color(l)); ui.selectable_label(current == Some(l), name) }); - register(ui.ctx(), format!("{widget}:{}", label_param(Some(l))), resp.inner.rect); + register(ui, format!("{widget}:{}", label_param(Some(l))), resp.inner.rect); if resp.inner.clicked() { chosen = Some(Some(l)); } } let none = ui.selectable_label(current.is_none(), crate::i18n::tr("None")); - register(ui.ctx(), format!("{widget}:none"), none.rect); + register(ui, format!("{widget}:none"), none.rect); if none.clicked() { chosen = Some(None); } @@ -1176,13 +1178,13 @@ pub fn stack_badge(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, sid: let g = p.layout_no_wrap(text, t.semibold(11.0), Color32::WHITE); let origin = if square { r.min + vec2(10.0, 26.0) } else { r.min + vec2(5.0, 5.0) }; let br = Rect::from_min_size(origin, vec2(g.size().x + 30.0, 20.0)); - let resp = ui.interact(br, egui::Id::new(("stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed { + let resp = ui.interact(br, egui::Id::unique(("stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed { "Stack — click to expand (S)" } else { "Stack — click to collapse (S)" }); crate::widgets::announce(&resp, crate::i18n::tr(if collapsed { "Expand Stack" } else { "Collapse Stack" })); - register(ui.ctx(), format!("stack:{}", id.0), br); + register(ui, format!("stack:{}", id.0), br); let fill = if resp.hovered() { Color32::from_black_alpha(220) } else { Color32::from_black_alpha(165) }; p.rect_filled(br, 10.0, fill); if pos == 0 && !collapsed { @@ -1274,14 +1276,14 @@ pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if local_only(app, &app.session.selected()) { // albums hold library photos (issue #684): nothing here to add until they join My Photos let add = ui.add_enabled(false, egui::Button::new(crate::i18n::tr("Add to Album"))).on_disabled_hover_text(albums_hint()); - register(ui.ctx(), "button:contextAddToAlbum", add.rect); + register(ui, "button:contextAddToAlbum", add.rect); } else { let add = crate::widgets::menu_button(ui, crate::i18n::tr("Add to Album"), |ui| { let albums: Vec<_> = app.session.catalog.albums().filter(|a| !a.folder && !a.is_smart()).map(|a| (a.id.0, a.name.clone())).collect(); let any = !albums.is_empty(); for (aid, name) in albums { let b = ui.button(name); - register(ui.ctx(), format!("button:contextAlbum:{aid}"), b.rect); + register(ui, format!("button:contextAlbum:{aid}"), b.rect); if b.clicked() { match app.run("album.addPhotos", json!({"id": aid})) { Ok(r) => toast_skipped(app, ui.ctx(), &r), @@ -1295,12 +1297,12 @@ pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // as in the Photo menu: a new album holding the selection, also when there is none yet // to pick (issue #676: the submenu came up empty) let new = ui.button(crate::i18n::tr("New Album…")); - register(ui.ctx(), "button:contextNewAlbum", new.rect); + register(ui, "button:contextNewAlbum", new.rect); if new.clicked() { let _ = app.run("dialog.newAlbum", json!({})); } }); - register(ui.ctx(), "button:contextAddToAlbum", add.response.rect); + register(ui, "button:contextAddToAlbum", add.response.rect); } // in a (non-smart) album: take the selection out of it, or make this photo its cover if let lightcraft_engine::LibrarySource::Album(aid) = app.session.source @@ -1436,7 +1438,7 @@ pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } } else { let delete = ui.button(crate::i18n::tr("Delete Photo")); - register(ui.ctx(), "button:contextDeletePhoto", delete.rect); + register(ui, "button:contextDeletePhoto", delete.rect); if delete.clicked() { let _ = crate::menubar::run_item(app, "photo.delete", json!({})); } @@ -1533,18 +1535,6 @@ mod tests { } } - #[test] - fn library_context_menu_labels_have_french_translations() { - let saved = crate::i18n::language(); - crate::i18n::set_language(crate::i18n::Locale::Fr); - for (label, expected) in - [("Pick", "Sélectionnée"), ("Reject", "Rejeter"), ("Group into Stack", "Regrouper en pile"), ("HDR Panorama…", "Panorama HDR…")] - { - assert_eq!(crate::i18n::tr(label), expected); - } - crate::i18n::set_language(saved); - } - #[test] fn square_grid_groups_and_auto_levels() { let l = layout(&[1.0; 5], &[(0, 3), (3, 2)], 400.0, 100.0, true); diff --git a/crates/ui-egui/src/panels/histogram.rs b/crates/ui-egui/src/panels/histogram.rs new file mode 100644 index 0000000000..3f26b46bde --- /dev/null +++ b/crates/ui-egui/src/panels/histogram.rs @@ -0,0 +1,372 @@ +//! The histogram's tonal zones, as in Lightroom Classic: hovering one names it and shows its value, +//! dragging one sideways moves its Basic control, and a double-click puts that control back to its +//! default. +//! +//! The zone a press landed in stays locked for the whole drag, so the pointer may cross the others; +//! every step is a `develop.set` between `develop.beginInteraction` and `develop.endInteraction`, the +//! path the panel's sliders take: the draft render follows the drag live and the whole drag lands as +//! one undo step (`end_interaction`). + +use egui::{Painter, Pos2, Rect, Response, pos2}; +use lightcraft_catalog::PhotoId; +use lightcraft_develop::{ControlSpec, controls}; +use serde_json::json; + +use crate::LightcraftApp; +use crate::panels::detail::Gesture; +use crate::theme::Tokens; +use crate::widgets::{register, shown_value}; + +/// One tonal zone across the histogram's plot. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Zone { + /// The develop control the zone adjusts: an id of [`lightcraft_develop::controls`]. + pub control: &'static str, + /// The zone's span of the plot's width, normalized 0 (left) to 1 (right). + pub from: f32, + pub to: f32, +} + +/// Lightroom Classic's five histogram regions, left to right: Blacks, Shadows, Exposure, Highlights, +/// Whites. Each names the Basic panel's own control, so the zone has that control's range, default +/// and steps. +pub const ZONES: [Zone; 5] = [ + Zone { control: "light.blacks", from: 0.00, to: 0.15 }, + Zone { control: "light.shadows", from: 0.15, to: 0.35 }, + Zone { control: "light.exposure", from: 0.35, to: 0.65 }, + Zone { control: "light.highlights", from: 0.65, to: 0.85 }, + Zone { control: "light.whites", from: 0.85, to: 1.00 }, +]; + +/// How far a sideways drag moves a control: crossing the whole plot sweeps the control's whole range, +/// as dragging a slider's thumb across its track does. Shift is a tenth of that, as on the sliders. +const SENSITIVITY: f64 = 1.0; +const FINE: f64 = 0.1; + +impl Zone { + /// The zone's control spec; `None` for an id the control table no longer has. + pub fn spec(self) -> Option<&'static ControlSpec> { + controls::find(self.control) + } + + /// The zone's band in `plot`. + pub fn rect(self, plot: Rect) -> Rect { + let x = |f: f32| plot.left() + plot.width() * f; + Rect::from_min_max(pos2(x(self.from), plot.top()), pos2(x(self.to), plot.bottom())) + } +} + +/// The zone covering `fx`, a position across the plot normalized to 0..1. `None` off the plot (NaN +/// too); 1.0 is the last zone's, whose right edge is the plot's. +pub fn zone_at(fx: f32) -> Option<Zone> { + if !(0.0..=1.0).contains(&fx) { + return None; + } + ZONES.iter().copied().find(|zone| fx >= zone.from && fx < zone.to).or_else(|| ZONES.last().copied()) +} + +/// The value `base` moved by a sideways drag of `dx` points over a plot `width` points wide. The +/// result is clamped to the control's range; a drag that can't be measured (no width, a hostile +/// delta) or a non-finite `base` leaves `base` alone. +pub fn dragged(spec: &ControlSpec, base: f64, dx: f32, width: f32, fine: bool) -> f64 { + if !width.is_finite() || width <= 0.0 { + return base; + } + let travel = f64::from(dx) / f64::from(width) * if fine { FINE } else { SENSITIVITY }; + let v = base + travel * (spec.max - spec.min); + if v.is_finite() { v.clamp(spec.min, spec.max) } else { base } +} + +/// `v` on the control's own steps, as the panel's sliders round and dispatch it. A non-finite `v` +/// gives the control's default, as [`ControlSpec::clamp`] does. +pub fn quantized(spec: &ControlSpec, v: f64) -> f64 { + if !v.is_finite() { + return spec.default; + } + let step = spec.step.max(1e-9); + ((v / step).round() * step).clamp(spec.min, spec.max) +} + +/// What the histogram is acting on this frame. +#[derive(Clone, Copy, Debug)] +pub struct Active { + /// The zone under the pointer, or the one a drag locked. + pub zone: Zone, + /// The zone's control's live value. + pub value: f64, + /// A drag of the zone is in progress: its zone stays locked until the release. + pub dragging: bool, +} + +impl Active { + /// The readout under the histogram: "Exposure: +0.45 EV", "Shadows: +25". + pub fn readout(&self) -> Option<String> { + let spec = self.zone.spec()?; + let shown = shown_value(spec, self.value); + let value = if spec.id == "light.exposure" { format!("{shown} EV") } else { shown }; + Some(format!("{}: {value}", crate::i18n::tr(spec.label))) + } +} + +/// The rectangles of the clipping buttons in the plot's top corners (shadows left, highlights right). +pub fn clipping_rects(ui: &egui::Ui, plot: Rect) -> [Rect; 2] { + let scroll = ui.spacing().scroll; + clipping_rects_in(plot, scroll.bar_width, scroll.bar_outer_margin) +} + +/// The clipping indicator rectangles for a given `plot` and scroll-bar geometry. +pub fn clipping_rects_in(plot: Rect, scroll_bar_width: f32, scroll_bar_outer_margin: f32) -> [Rect; 2] { + let inset = 20.0 + scroll_bar_width + scroll_bar_outer_margin; + [ + Rect::from_center_size(pos2(plot.left() + inset, plot.top() + 14.0), egui::vec2(24.0, 22.0)), + Rect::from_center_size(pos2(plot.right() - inset, plot.top() + 14.0), egui::vec2(24.0, 22.0)), + ] +} + +/// The histogram's pointer input for this frame: the press locks its zone and opens the interaction, +/// the drag moves that control, a double-click resets it. Returns what the highlight and the readout +/// should show, `None` when the pointer is nowhere near a zone. +/// +/// `plot` is the plot's rect: the strip under it (the readout and the EXIF line) is not a zone, and +/// neither are the clipping buttons in the plot's top corners, which take their own presses. +pub fn interact(app: &mut LightcraftApp, ui: &egui::Ui, resp: &Response, plot: Rect, id: PhotoId) -> Option<Active> { + let width = plot.width(); + let clips = clipping_rects(ui, plot); + let in_plot = |q: Pos2| plot.contains(q) && !clips.iter().any(|c| c.contains(q)); + let zone_of = |q: Pos2| in_plot(q).then(|| (q.x - plot.left()) / width).and_then(zone_at); + // the zone the pointer is over, and the one a press (or a double-click) landed in: the press's + // origin, so a drag is judged by where it started + let hovered = resp.hover_pos().and_then(zone_of); + let pressed = ui.input(|i| i.pointer.press_origin()).or_else(|| resp.interact_pointer_pos()).and_then(zone_of); + let was_dragging = matches!(app.gesture, Some(Gesture::HistogramDrag { .. })); + // a drag cut short — the release went elsewhere, the panel closed — leaves the interaction open: + // with no button held the gesture is over, as the crop tool's gestures decide too + if was_dragging && !resp.drag_stopped() && !ui.input(|i| i.pointer.any_down()) { + finish(app); + } + // 1. the press locks its zone: one interaction holds the whole drag as one undo step + if resp.drag_started() + && !was_dragging + && let Some(zone) = pressed + && let Some(spec) = zone.spec() + && app.run("develop.beginInteraction", json!({"label": spec.label})).is_ok() + { + app.ui.dragging_control = Some(spec.id.to_string()); + app.gesture = Some(Gesture::HistogramDrag { control: zone.control, value: value_of(app, id, spec) }); + } + // 2. the drag moves the locked zone's control, wherever the pointer has gone since + if let Some(Gesture::HistogramDrag { control, value }) = app.gesture.clone() + && let Some(spec) = controls::find(control) + { + if resp.dragged() || resp.drag_stopped() { + // The frame a drag is first reported, take the whole travel from the press: egui only + // starts reporting a drag once the pointer has left its click threshold, and those first + // points are the user's movement too. Later frames add their own delta (a one-frame flick + // reports the drag as started and stopped together: then this is its delta), so Shift — + // a tenth — scales the travel it was held for, as the sliders' fine drag does. The + // unrounded value is kept from frame to frame, so a slow drag adds up instead of rounding + // back to the step it already has. + let dx = if resp.drag_started() { + ui.input(|i| i.pointer.total_drag_delta()).map_or(resp.drag_delta().x, |d| d.x) + } else { + resp.drag_delta().x + }; + let next = dragged(spec, value, dx, width, ui.input(|i| i.modifiers.shift)); + app.gesture = Some(Gesture::HistogramDrag { control, value: next }); + let v = quantized(spec, next); + if value_of(app, id, spec) != v { + let _ = app.run("develop.set", json!({"control": control, "value": v})); + } + } + if resp.drag_stopped() { + finish(app); + } + } + // 3. a double-click in a zone puts that control back to its default, in one undo step + if resp.double_clicked() + && let Some(zone) = pressed + && let Some(spec) = zone.spec() + { + let _ = app.run("develop.beginInteraction", json!({"label": spec.label})); + app.ui.dragging_control = Some(spec.id.to_string()); + let _ = app.run("develop.set", json!({"control": spec.id, "value": spec.default})); + finish(app); + } + // the highlight and the readout follow the drag's locked zone, else the pointer's + let zone = match app.gesture { + Some(Gesture::HistogramDrag { control, .. }) => ZONES.iter().copied().find(|zone| zone.control == control), + _ => hovered, + }?; + let spec = zone.spec()?; + let dragging = matches!(app.gesture, Some(Gesture::HistogramDrag { .. })); + if dragging || hovered.is_some() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + register(ui, "histogram:zone", zone.rect(plot)); + Some(Active { zone, value: value_of(app, id, spec), dragging }) +} + +/// End the histogram drag: the interaction commits the whole drag as one undo step. +fn finish(app: &mut LightcraftApp) { + app.gesture = None; + app.ui.dragging_control = None; + let _ = app.run("develop.endInteraction", json!({})); +} + +/// A control's value on the photo, or its default when the photo has no settings yet. +fn value_of(app: &LightcraftApp, id: PhotoId, spec: &ControlSpec) -> f64 { + controls::get(&app.session.develop_of(id).unwrap_or_default(), spec.id).unwrap_or(spec.default) +} + +/// The band the active zone draws over the plot: a subtle translucent highlight, a little stronger +/// while the zone is being dragged. Painted behind the histogram's curves. +pub fn paint_zone(painter: &Painter, plot: Rect, active: &Active, tokens: &Tokens) { + let tint = if active.dragging { tokens.pressed } else { tokens.hover }; + painter.rect_filled(active.zone.rect(plot), 0.0, tint.gamma_multiply(if active.dragging { 0.75 } else { 0.45 })); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec_of(control: &str) -> &'static ControlSpec { + controls::find(control).unwrap_or_else(|| panic!("{control} is not a control")) + } + + /// The five zones tile the plot left to right, each naming a real Basic tone control of the + /// range this app documents (the panel's own specs, not a copy of them). + #[test] + fn the_zones_tile_the_plot_and_name_real_tone_controls() { + assert_eq!(ZONES.len(), 5); + assert_eq!(ZONES.first().map(|z| z.from), Some(0.0)); + assert_eq!(ZONES.last().map(|z| z.to), Some(1.0)); + for pair in ZONES.windows(2) { + assert_eq!(pair[0].to, pair[1].from, "{:?} does not meet {:?}", pair[0].control, pair[1].control); + } + for zone in ZONES { + let spec = spec_of(zone.control); + assert_eq!(spec.section, lightcraft_develop::Section::Light, "{}", spec.id); + assert_eq!(spec.default, 0.0, "{}", spec.id); + let (min, max) = if spec.id == "light.exposure" { (-5.0, 5.0) } else { (-100.0, 100.0) }; + assert_eq!((spec.min, spec.max), (min, max), "{}", spec.id); + } + } + + /// A position across the plot picks its zone, at the boundaries too; anything off the plot — + /// including NaN — picks none. + #[test] + fn a_position_across_the_plot_picks_its_zone() { + for (fx, control) in [ + (0.0, "light.blacks"), + (0.14, "light.blacks"), + (0.15, "light.shadows"), + (0.34, "light.shadows"), + (0.35, "light.exposure"), + (0.64, "light.exposure"), + (0.65, "light.highlights"), + (0.84, "light.highlights"), + (0.85, "light.whites"), + (0.99, "light.whites"), + (1.0, "light.whites"), + ] { + assert_eq!(zone_at(fx).map(|z| z.control), Some(control), "{fx}"); + } + for off in [-0.01, -1.0, 1.01, f32::NAN, f32::INFINITY] { + assert!(zone_at(off).is_none(), "{off}"); + } + } + + /// The zones' bands are their share of the plot's width, in order. + #[test] + fn a_zones_band_is_its_share_of_the_plot() { + let plot = Rect::from_min_max(pos2(100.0, 20.0), pos2(400.0, 200.0)); + let bands: Vec<Rect> = ZONES.iter().map(|z| z.rect(plot)).collect(); + assert_eq!(bands.first().map(|b| b.left()), Some(plot.left())); + assert_eq!(bands.last().map(|b| b.right()), Some(plot.right())); + for band in &bands { + assert_eq!((band.top(), band.bottom()), (plot.top(), plot.bottom())); + } + for pair in bands.windows(2) { + assert_eq!(pair[0].right(), pair[1].left()); + } + let exposure = bands.get(2).copied().unwrap_or(plot); + assert!((exposure.width() - plot.width() * 0.30).abs() < 1e-3, "{exposure:?}"); + } + + /// A drag across the whole plot sweeps the whole range; Shift is a tenth; the ends clamp; the + /// unrounded value a slow drag accumulates keeps adding up. + #[test] + fn a_drag_sweeps_the_control_and_clamps_at_its_ends() { + let exposure = spec_of("light.exposure"); + let blacks = spec_of("light.blacks"); + assert!((dragged(exposure, 0.0, 20.0, 200.0, false) - 1.0).abs() < 1e-9, "a tenth of the plot is a tenth of ±5 EV"); + assert!((dragged(blacks, 0.0, 20.0, 200.0, false) - 20.0).abs() < 1e-9); + assert!((dragged(blacks, 0.0, 200.0, 200.0, false) - 100.0).abs() < 1e-9); + assert_eq!(dragged(blacks, 0.0, 400.0, 200.0, false), 100.0, "past the right end it stays"); + assert_eq!(dragged(blacks, 0.0, -400.0, 200.0, false), -100.0, "and past the left end"); + assert!((dragged(blacks, 0.0, 20.0, 200.0, true) - 2.0).abs() < 1e-9, "Shift is a tenth of the travel"); + assert!((dragged(blacks, 0.0, -20.0, 200.0, false) + 20.0).abs() < 1e-9, "left lowers"); + // a drag whose frames are each smaller than one step still adds up over the whole drag (the + // deltas are f32 points, so the sum carries their rounding) + let mut acc = 0.0; + for _ in 0..10 { + acc = dragged(blacks, acc, 0.4, 200.0, false); + } + assert!((acc - 4.0).abs() < 1e-6, "{acc}"); + // hostile input: no width, a hostile delta, a base that isn't a number + assert_eq!(dragged(blacks, 5.0, 20.0, 0.0, false), 5.0); + assert_eq!(dragged(blacks, 5.0, 20.0, -10.0, false), 5.0); + assert_eq!(dragged(blacks, 5.0, f32::NAN, 200.0, false), 5.0); + assert_eq!(dragged(blacks, 5.0, f32::INFINITY, 200.0, false), 5.0); + assert!(dragged(blacks, f64::NAN, 20.0, 200.0, false).is_nan(), "a base that isn't a number stays as it is"); + } + + /// Dispatched values land on the control's steps (as the sliders dispatch them) and inside its + /// range; a value that isn't a number gives the default rather than a NaN. + #[test] + fn a_dispatched_value_lands_on_the_controls_steps() { + let blacks = spec_of("light.blacks"); + let exposure = spec_of("light.exposure"); + assert_eq!(quantized(blacks, 20.4), 20.0); + assert_eq!(quantized(blacks, 20.6), 21.0); + assert_eq!(quantized(blacks, 1e9), 100.0); + assert_eq!(quantized(blacks, -1e9), -100.0); + assert_eq!(quantized(blacks, f64::NAN), 0.0); + assert!((quantized(exposure, 0.454) - 0.45).abs() < 1e-9, "{}", quantized(exposure, 0.454)); + for v in [-1e9, -3.7, 0.0, 2.2, 1e9] { + let q = quantized(exposure, v); + assert!((exposure.min..=exposure.max).contains(&q), "{v} → {q}"); + } + } + + /// The readout names the zone's control and shows its value: EV for the exposure, the plain + /// signed number otherwise, exactly as the sliders show them. + #[test] + fn the_readout_names_the_zone_and_its_value() { + let active = |control: &str, value: f64, dragging: bool| Active { + zone: ZONES.iter().copied().find(|z| z.control == control).unwrap_or(ZONES[0]), + value, + dragging, + }; + assert_eq!(active("light.exposure", 0.45, false).readout().as_deref(), Some("Exposure: +0.45 EV")); + assert_eq!(active("light.exposure", -2.0, true).readout().as_deref(), Some("Exposure: -2.00 EV")); + assert_eq!(active("light.shadows", 25.0, true).readout().as_deref(), Some("Shadows: +25")); + assert_eq!(active("light.blacks", 0.0, false).readout().as_deref(), Some("Blacks: 0")); + assert_eq!(active("light.highlights", -100.0, false).readout().as_deref(), Some("Highlights: -100")); + assert_eq!(active("light.whites", 13.0, false).readout().as_deref(), Some("Whites: +13")); + } + + /// The clipping rectangles sit in the plot's top corners, symmetric from both edges. + #[test] + fn clipping_rects_sit_in_the_plots_top_corners() { + let plot = Rect::from_min_max(pos2(100.0, 20.0), pos2(400.0, 200.0)); + let [low, high] = clipping_rects_in(plot, 10.0, 4.0); + assert!(plot.contains(low.center())); + assert!(plot.contains(high.center())); + assert_eq!(low.top(), plot.top() + 3.0); + assert_eq!(high.top(), plot.top() + 3.0); + assert_eq!(low.size(), egui::vec2(24.0, 22.0)); + assert_eq!(high.size(), egui::vec2(24.0, 22.0)); + assert!((low.left() - plot.left() - (plot.right() - high.right())).abs() < 1e-4); + } +} diff --git a/crates/ui-egui/src/panels/keymap.rs b/crates/ui-egui/src/panels/keymap.rs index 1bda177589..3ebe250570 100644 --- a/crates/ui-egui/src/panels/keymap.rs +++ b/crates/ui-egui/src/panels/keymap.rs @@ -15,21 +15,24 @@ use crate::widgets::register; const SEARCH: &str = "shortcuts-search"; const SHOW_ALL: &str = "shortcuts-show-all"; +/// Draw the Keyboard Shortcuts editor: search and "show all", Reset All, one row per bindable +/// command that has a shortcut (all bindable commands when "Show commands without a shortcut" is +/// on), and the fixed non-command keys. Pending shortcut capture is processed once per frame. pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; capture(app, ui.ctx()); ui.set_min_width(560.0); - let (search_id, all_id) = (egui::Id::new(SEARCH), egui::Id::new(SHOW_ALL)); + let (search_id, all_id) = (egui::Id::unique(SEARCH), egui::Id::unique(SHOW_ALL)); let mut search: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); let mut show_all: bool = ui.data(|d| d.get_temp(all_id)).unwrap_or(false); ui.horizontal(|ui| { let r = ui.add(egui::TextEdit::singleline(&mut search).hint_text(crate::i18n::tr("Search commands or keys")).desired_width(220.0)); - register(ui.ctx(), "field:shortcutsSearch", r.rect); + register(ui, "field:shortcutsSearch", r.rect); let r = ui.checkbox(&mut show_all, crate::i18n::tr("Show commands without a shortcut")); - register(ui.ctx(), "check:shortcuts.showAll", r.rect); + register(ui, "check:shortcuts.showAll", r.rect); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let r = ui.add_enabled(!app.ui.settings.keymap.is_empty(), egui::Button::new(crate::i18n::tr("Reset All"))); - register(ui.ctx(), "button:shortcutsResetAll", r.rect); + register(ui, "button:shortcutsResetAll", r.rect); if r.clicked() { let _ = app.run("app.resetShortcuts", serde_json::json!({})); app.recording_shortcut = None; @@ -79,8 +82,12 @@ fn menu_text(sc: &str, mac: bool) -> String { crate::menubar::shortcut_text(sc, mac) } +/// One editable command row: its label and id, a click-to-record shortcut button, and buttons +/// that clear or restore it. The restore button is enabled when a saved binding exists or the +/// declared default is currently yielded to another command. fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc: Option<&str>, mac: bool) { - let changed = app.ui.settings.keymap.contains_key(b.id); + // a declared key that yields to another command's saved key counts as changed: ↺ takes it back + let changed = app.ui.settings.keymap.contains_key(b.id) || (sc.is_none() && b.default.is_some()); let mut name = RichText::new(crate::i18n::tr(b.label)).color(t.text); if changed { name = name.strong(); @@ -102,14 +109,14 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc: } }; let r = ui.add(egui::Button::new(text).min_size(egui::vec2(110.0, 0.0)).selected(recording)); - register(ui.ctx(), format!("button:shortcut-{}", b.id), r.rect); + register(ui, format!("button:shortcut-{}", b.id), r.rect); if r.clicked() { app.recording_shortcut = if recording { None } else { Some(b.id.to_string()) }; } ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 2.0; let r = ui.add_enabled(sc.is_some(), egui::Button::new("×").small()).on_hover_text(crate::i18n::tr("Remove shortcut")); - register(ui.ctx(), format!("button:shortcutClear-{}", b.id), r.rect); + register(ui, format!("button:shortcutClear-{}", b.id), r.rect); if r.clicked() { apply(app, ui.ctx(), serde_json::json!({"id": b.id, "shortcut": null})); } @@ -117,7 +124,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc: Some(d) => crate::i18n::tr_format!("Restore {}", menu_text(d, mac)), None => crate::i18n::tr("Restore (no shortcut)").to_string(), }); - register(ui.ctx(), format!("button:shortcutReset-{}", b.id), r.rect); + register(ui, format!("button:shortcutReset-{}", b.id), r.rect); if r.clicked() { apply(app, ui.ctx(), serde_json::json!({"id": b.id, "reset": true})); } @@ -171,7 +178,8 @@ fn fixed_keys(app: &LightcraftApp, ui: &mut egui::Ui, t: &Tokens, mac: bool, nee } ui.add_space(8.0); ui.label(RichText::new(crate::i18n::tr("Fixed keys")).font(t.semibold(12.5)).color(t.text)); - let taken: Vec<_> = app.ui.settings.keymap.values().filter_map(|s| shortcuts::parse(s)).collect(); + // keys saved for commands this build knows: an entry for an unknown command takes no key + let taken: Vec<_> = shortcuts::saved_keys(&app.ui.settings.keymap).map(|(_, k)| k).collect(); egui::Grid::new("shortcuts-fixed").striped(true).num_columns(2).spacing([12.0, 4.0]).show(ui, |ui| { for (sc, label) in fixed { ui.label(RichText::new(crate::i18n::tr(label)).color(t.text_label)); diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index 1ec97d1c9b..ba31c6676d 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -23,7 +23,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { crate::widgets::divider(ui); // the title, where a dragged keyword goes back to the top level let (title, title_resp) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), Sense::click()); - register(ui.ctx(), "keywordList:topLevel", title); + register(ui, "keywordList:topLevel", title); let dragging = app.ui.dragging_keyword.clone(); let (pointer, released) = ui.input(|i| (i.pointer.latest_pos(), i.pointer.any_released())); let over_title = shown_under(ui, title, pointer); @@ -42,7 +42,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if !open { return; } - let fid = egui::Id::new("keyword-list-filter"); + let fid = egui::Id::unique("keyword-list-filter"); let mut filter: String = ui.data(|d| d.get_temp(fid)).unwrap_or_default(); ui.horizontal(|ui| { ui.add_space(24.0); @@ -52,13 +52,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { .show(ui); // + creates a keyword (inside the picked one), − deletes the picked one let plus = ui.button("+").on_hover_text(crate::i18n::tr("Create Keyword Tag")); - register(ui.ctx(), "keywordList:create", plus.rect); + register(ui, "keywordList:create", plus.rect); if plus.clicked() { app.ui.dialog = Some(create_dialog(app)); } let picked = app.ui.keyword_list_selected.clone().filter(|k| in_tree(&app.caches.keyword_tree(&app.session.catalog), k)); let minus = ui.add_enabled(picked.is_some(), egui::Button::new("−")).on_hover_text(crate::i18n::tr("Delete Keyword")); - register(ui.ctx(), "keywordList:delete", minus.rect); + register(ui, "keywordList:delete", minus.rect); if minus.clicked() && let Some(k) = picked { @@ -130,11 +130,14 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let t = Tokens::get(ctx); ctx.set_cursor_icon(egui::CursorIcon::Grabbing); let name = keyword.rsplit('|').next().unwrap_or(&keyword).to_string(); - egui::Area::new(egui::Id::new("drag-keyword")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show(ctx, |ui| { - egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { - ui.label(egui::RichText::new(name).color(Color32::WHITE).font(t.semibold(12.0))); - }); - }); + egui::Area::new(egui::Id::unique("drag-keyword")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show( + ctx, + |ui| { + egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { + ui.label(egui::RichText::new(name).color(Color32::WHITE).font(t.semibold(12.0))); + }); + }, + ); } /// Drop the dragged `keyword` inside `parent` (`None`: the top level). Where one of its name is @@ -167,7 +170,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId let t = Tokens::get(ui.ctx()); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click_and_drag()); crate::widgets::announce(&resp, r.path.clone()); - register(ui.ctx(), format!("keywordRow:{}", r.path), rect); + register(ui, format!("keywordRow:{}", r.path), rect); if resp.drag_started() { app.ui.dragging_keyword = Some(r.path.clone()); } @@ -185,9 +188,9 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId if r.has_children { let c = pos2(x + 6.0, cy); let tri = Rect::from_center_size(c, vec2(16.0, 16.0)); - let tr = ui.interact(tri, egui::Id::new(("keyword-list-tri", r.path.to_lowercase())), Sense::click()); + let tr = ui.interact(tri, egui::Id::unique(("keyword-list-tri", r.path.to_lowercase())), Sense::click()); crate::widgets::announce(&tr, crate::i18n::tr(if r.open { "Collapse" } else { "Expand" })); - register(ui.ctx(), format!("keywordRowToggle:{}", r.path), tri); + register(ui, format!("keywordRowToggle:{}", r.path), tri); // while a filter opens the levels the triangle does nothing: it doesn't light up either let lit = tr.hovered() && can_fold; paint(ui.painter(), tri, if r.open { Icon::ChevronDown } else { Icon::ChevronRight }, if lit { t.text } else { t.text_dim }); @@ -202,13 +205,14 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId } // the tick box: does the selection have it? let state = ticks.tick(&r.path); + let inside = ticks.inside(&r.path); let boxr = Rect::from_center_size(pos2(x + 22.0, cy), vec2(13.0, 13.0)); let on = !selection.is_empty(); // (it senses drags too, so a press there that moves doesn't pick the keyword up) let sense = if on { Sense::click_and_drag() } else { Sense::hover() }; - let tb = ui.interact(boxr.expand(3.0), egui::Id::new(("keyword-list-tick", r.path.to_lowercase())), sense); + let tb = ui.interact(boxr.expand(3.0), egui::Id::unique(("keyword-list-tick", r.path.to_lowercase())), sense); crate::widgets::announce(&tb, format!("{} {}", crate::i18n::tr("Keyword"), r.path)); - register(ui.ctx(), format!("keywordCheck:{}", r.path), boxr); + register(ui, format!("keywordCheck:{}", r.path), boxr); let edge = if on { t.text_label } else { t.text_dim.gamma_multiply(0.5) }; match state { Tick::All => { @@ -222,14 +226,27 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId } Tick::No => { ui.painter().rect_stroke(boxr, 2.0, Stroke::new(1.0, edge), StrokeKind::Inside); + // the selection has a keyword inside this one: a dot in the empty box, so a folded + // keyword shows that it holds something applied (a shape of its own beside the tick + // and the dash, which are about the keyword itself) + if !inside.is_empty() { + let dot = Rect::from_center_size(boxr.center(), vec2(5.0, 5.0)); + ui.painter().circle_filled(dot.center(), 2.5, t.text); + register(ui, format!("keywordInside:{}", r.path), dot); + } } } // (with nothing selected it does nothing, and says nothing) let tb = if on { - tb.on_hover_text(crate::i18n::tr(match state { + let does = crate::i18n::tr(match state { Tick::All => "Remove from Selected Photos", _ => "Add to Selected Photos", - })) + }); + // what is inside comes first: it is what the box shows + match inside_said(inside) { + Some(said) => tb.on_hover_text(format!("{said}\n{does}")), + None => tb.on_hover_text(does), + } } else { tb }; @@ -240,12 +257,12 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId // the count, then the arrow left of it (shown on hover) let count = ui.painter().layout_no_wrap(r.count.to_string(), t.font(12.0), t.text_dim); let count_rect = Rect::from_min_size(pos2(inner.right() - 6.0 - count.size().x, cy - count.size().y / 2.0), count.size()); - register(ui.ctx(), format!("keywordCount:{}", r.path), count_rect); + register(ui, format!("keywordCount:{}", r.path), count_rect); ui.painter().galley(count_rect.min, count, t.text_dim); let arrow = Rect::from_center_size(pos2(count_rect.left() - 12.0, cy), vec2(16.0, 16.0)); - let ar = ui.interact(arrow, egui::Id::new(("keyword-list-show", r.path.to_lowercase())), Sense::click()); + let ar = ui.interact(arrow, egui::Id::unique(("keyword-list-show", r.path.to_lowercase())), Sense::click()); crate::widgets::announce(&ar, crate::i18n::tr("Show photos")); - register(ui.ctx(), format!("keywordShow:{}", r.path), arrow); + register(ui, format!("keywordShow:{}", r.path), arrow); if resp.hovered() || ar.hovered() { paint(ui.painter(), arrow, Icon::ChevronRight, if ar.hovered() { t.text } else { t.text_dim }); } @@ -263,7 +280,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId if app.session.catalog.default_keyword_parent().as_deref().is_some_and(|k| same(k, &r.path)) { let dot = Rect::from_center_size(pos2(label.right() + 7.0, cy), vec2(6.0, 6.0)); ui.painter().circle_filled(dot.center(), 3.0, t.accent); - register(ui.ctx(), format!("keywordDefault:{}", r.path), dot); + register(ui, format!("keywordDefault:{}", r.path), dot); } let resp = resp.on_hover_text(r.path.replace('|', " › ")); if resp.clicked() { @@ -275,6 +292,17 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId crate::widgets::context_menu(&resp, |ui| menu(app, ui, &r.path, selection)); } +/// How many of the keywords inside one are named before the rest are counted. +const INSIDE_NAMED: usize = 4; + +/// "Inside: Rome, Venice": the applied keywords inside a keyword, the first few by name. +fn inside_said(inside: &[String]) -> Option<String> { + let named = inside.iter().take(INSIDE_NAMED).map(String::as_str).collect::<Vec<_>>().join(", "); + let more = inside.len().saturating_sub(INSIDE_NAMED); + let names = if more > 0 { format!("{named} {}", crate::i18n::tr_format!("+{n} more", n = more)) } else { named }; + (!inside.is_empty()).then(|| crate::i18n::tr_format!("Inside: {names}", names = names)) +} + /// A row while a keyword or photos are dragged: outlined under the pointer when the drop would /// do something (a keyword never goes inside itself), and a release there does it: nests the /// keyword inside this one, or gives this keyword to the photos. @@ -326,7 +354,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str, selection: &[Pho let name = path.replace('|', " › "); let item = |ui: &mut egui::Ui, id: &str, label: &str, enabled: bool| { let r = ui.add_enabled(enabled, egui::Button::new(label)); - register(ui.ctx(), format!("keywordMenu:{id}"), r.rect); + register(ui, format!("keywordMenu:{id}"), r.rect); r.clicked() }; if item(ui, "create", &crate::i18n::tr_format!("Create Keyword Tag Inside “{name}”…", name = name), true) { @@ -485,23 +513,51 @@ pub(crate) struct Ticks { photos: usize, /// Photos with it, by cleaned lower-case keyword. counts: std::collections::HashMap<String, usize>, + /// The applied keywords inside each keyword (by cleaned lower-case keyword): their own names, + /// in order, each once. What a folded keyword's box says of what it holds. + inside: std::collections::HashMap<String, Vec<String>>, } impl Ticks { pub(crate) fn of(catalog: &Catalog, photos: &[PhotoId]) -> Ticks { let photos = super::keywording::distinct(catalog, photos); let mut counts: std::collections::HashMap<String, usize> = Default::default(); + // (each keyword as it was first written, to name it by) + let mut shown: std::collections::HashMap<String, String> = Default::default(); let mut seen = std::collections::HashSet::new(); for p in &photos { seen.clear(); for k in &p.meta.keywords { - let key = lightcraft_catalog::keywords::clean(k).to_lowercase(); + let clean = lightcraft_catalog::keywords::clean(k); + let key = clean.to_lowercase(); if seen.insert(key.clone()) { - *counts.entry(key).or_default() += 1; + *counts.entry(key.clone()).or_default() += 1; + shown.entry(key).or_insert(clean); } } } - Ticks { photos: photos.len(), counts } + // every keyword above an applied one holds it: worked out here, once per selection, from the + // keywords the selection has (not per row and frame) + let mut inside: std::collections::HashMap<String, Vec<String>> = Default::default(); + let mut applied: Vec<(&String, &String)> = shown.iter().collect(); + applied.sort(); + for (key, as_written) in applied { + let name = as_written.rsplit('|').next().unwrap_or(as_written); + for (at, _) in key.match_indices('|') { + let Some(above) = key.get(..at) else { continue }; + let names = inside.entry(above.to_string()).or_default(); + if !names.iter().any(|n| same(n, name)) { + names.push(name.to_string()); + } + } + } + Ticks { photos: photos.len(), counts, inside } + } + + /// The applied keywords inside `path` (their own names): what the selection has of the + /// keywords below it, at any depth. Empty for a keyword with nothing applied inside. + pub(crate) fn inside(&self, path: &str) -> &[String] { + self.inside.get(&lightcraft_catalog::keywords::clean(path).to_lowercase()).map_or(&[], Vec::as_slice) } /// The tick box of `path`: a photo counts when it has the keyword itself (any case); one with @@ -520,6 +576,35 @@ fn in_tree(tree: &[KeywordNode], path: &str) -> bool { tree.iter().any(|n| same(&n.path, path) || (lightcraft_catalog::keywords::is_under(path, &n.path) && in_tree(&n.children, path))) } +/// The labels the Keyword List and its dialogs pass to `tr` through variables, out of reach of a +/// literal search: the translation gaps report (`i18n`) checks them. +#[cfg(test)] +pub(crate) const VARIABLE_LABELS: &[&str] = &[ + "Include on Export", + "Export Containing Keywords", + "Export Synonyms", + "Person", + "Merge Keywords", + "No keywords yet", + "No keywords match", + "Add to Selected Photos", + "Remove from Selected Photos", + "Keywords", + "& Containing", + "Will Export", + "No keywords are exported", + "Add to All Selected Photos", + "Set name", + "Edit Set…", + "Edit Keyword Set", + "A keyword set needs a name", + "Recent Keywords", + "Keywords (⌥1–⌥9)", + "Save as a new set", + "Import Keywords…", + "Export Keywords…", +]; + #[cfg(test)] mod tests { use lightcraft_catalog::{Op, Photo, Source}; @@ -590,44 +675,30 @@ mod tests { assert_eq!(Ticks::of(&c, &ids).tick("ärzte"), Tick::Some); } - /// The labels the Keyword List and its dialogs pass to `tr` through variables (out of reach of - /// a literal search) are translated in every language. + /// Given photos that have keywords inside other keywords, when the list is asked what is + /// inside a keyword for the selection, then every keyword above an applied one names it (by + /// its own name, once, in order), whichever case it was written in and however deep; a keyword + /// with nothing applied inside, a keyword that is itself the applied one, and an empty + /// selection name nothing. #[test] - fn labels_passed_through_variables_are_translated() { - use crate::i18n::Locale; - let labels = [ - "Include on Export", - "Export Containing Keywords", - "Export Synonyms", - "Person", - "Merge Keywords", - "No keywords yet", - "No keywords match", - "Add to Selected Photos", - "Remove from Selected Photos", - "Keywords", - "& Containing", - "Will Export", - "No keywords are exported", - "Add to All Selected Photos", - "Set name", - "Edit Set…", - "Edit Keyword Set", - "A keyword set needs a name", - "Recent Keywords", - "Keywords (⌥1–⌥9)", - "Save as a new set", - "Import Keywords…", - "Export Keywords…", - ]; - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("locales"); - for code in ["de", "es", "fr", "pt-br", "ru", "uk", "it", "ka", "ja", "zh-hans", "zh-hant", "pl", "cs", "sv", "fi", "id", "vi"] { - let text = std::fs::read_to_string(dir.join(format!("{code}.json"))).unwrap(); - let catalog: std::collections::HashMap<String, String> = serde_json::from_str(&text).unwrap(); - for label in labels { - assert!(catalog.contains_key(label), "{code}: “{label}”"); - } - } - assert_eq!(Locale::ALL.len(), 18, "a language added: list its file above"); + fn a_keyword_names_the_applied_keywords_inside_it() { + let (c, ids) = library(&[&["Travel|Italy|Rome", "beach"], &["travel|italy|venice", "travel|Spain"], &["travel|italy|ROME"]]); + let all = Ticks::of(&c, &ids); + assert_eq!(all.inside("travel"), ["Italy|Rome", "Italy|venice", "Spain"].map(|k| k.rsplit('|').next().unwrap())); + assert_eq!(all.inside("Travel|Italy"), ["Rome", "venice"]); + assert_eq!(all.inside("travel|italy|rome"), [] as [&str; 0], "nothing is inside the applied keyword itself"); + assert_eq!(all.inside("travel|spain"), [] as [&str; 0]); + assert_eq!(all.inside("beach"), [] as [&str; 0]); + assert_eq!(all.inside("weddings"), [] as [&str; 0], "a keyword no photo has anything of"); + // the selection decides: the third photo alone has nothing of Spain or Venice + assert_eq!(Ticks::of(&c, &ids[2..]).inside("travel"), ["ROME"]); + assert_eq!(Ticks::of(&c, &[]).inside("travel"), [] as [&str; 0]); + // a keyword applied itself and with one inside: the tick is its own, and what is inside is still named + let (c, ids) = library(&[&["travel", "travel|Italy"]]); + let t = Ticks::of(&c, &ids); + assert_eq!((t.tick("travel"), t.inside("travel")), (Tick::All, &["Italy".to_string()][..])); + // a name that only starts like another is not inside it + let (c, ids) = library(&[&["travelling|Rome"]]); + assert_eq!(Ticks::of(&c, &ids).inside("travel"), [] as [&str; 0]); } } diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index a6f53562da..4861d4c6fa 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -18,7 +18,7 @@ pub fn view_switch(app: &mut LightcraftApp, ui: &mut egui::Ui) { [(V::Keywords, "keywords", "Keywords"), (V::Containing, "containing", "& Containing"), (V::WillExport, "willExport", "Will Export")] { let r = ui.selectable_label(app.ui.keywording_view == view, crate::i18n::tr(label)); - register(ui.ctx(), format!("keywordView:{id}"), r.rect); + register(ui, format!("keywordView:{id}"), r.rect); if r.clicked() { app.ui.keywording_view = view; } @@ -41,7 +41,7 @@ pub fn names_row(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.horizontal_wrapped(|ui| { for n in names.iter() { let (body, _) = chip(ui, &n.path, &n.path, !n.on_all(), false, ui.max_rect().width()); - register(ui.ctx(), format!("{prefix}:{}", n.path), body.rect); + register(ui, format!("{prefix}:{}", n.path), body.rect); if n.on_all() { body.on_hover_text(&n.path); } else { @@ -87,17 +87,17 @@ fn chip(ui: &mut egui::Ui, path: &str, name: &str, partial: bool, cross: bool, r // the row places it; its name and × answer under ids of their own keyword, so an open menu // stays with its keyword when the chips change let (rect, _) = ui.allocate_exact_size(vec2(w, 22.0), Sense::hover()); - let id = egui::Id::new(("keyword-chip", path.to_lowercase(), cross)); + let id = egui::Id::unique(("keyword-chip", path.to_lowercase(), cross)); let body = Rect::from_min_max(rect.min, pos2(rect.right() - cross_w, rect.bottom())); let full = path.replace('|', " › "); let resp = ui.interact(body, id, Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &full)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &full)); // the ×: the whole end of the chip, so that it is hard to miss and easy to tell from the name let x = cross.then(|| { let xr = Rect::from_min_max(pos2(rect.right() - cross_w, rect.top()), rect.max); let xresp = ui.interact(xr, id.with("remove"), Sense::click()); let said = crate::i18n::tr_format!("Remove “{name}”", name = full); - xresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &said)); + xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &said)); xresp }); let p = ui.painter(); @@ -148,7 +148,7 @@ fn remove(app: &mut LightcraftApp, ctx: &egui::Context, chip: &Chip) { fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, chip: &Chip) { let item = |ui: &mut egui::Ui, id: &str, label: &str| { let r = ui.button(label); - register(ui.ctx(), format!("keywordChipMenu:{id}"), r.rect); + register(ui, format!("keywordChipMenu:{id}"), r.rect); r.clicked() }; if !chip.on_all() && item(ui, "add", crate::i18n::tr("Add to All Selected Photos")) { @@ -177,7 +177,7 @@ pub fn scope(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) let t = Tokens::get(ui.ctx()); let said = crate::i18n::tr_format!("Keywords of {n} selected photos", n = photos); let r = ui.label(egui::RichText::new(said).size(11.5).color(t.text_label)); - register(ui.ctx(), "keywordScope", r.rect); + register(ui, "keywordScope", r.rect); ui.add_space(4.0); } @@ -189,7 +189,7 @@ pub fn chip_row(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId if chips.is_empty() { let t = Tokens::get(ui.ctx()); let r = ui.label(egui::RichText::new(crate::i18n::tr("No keywords yet")).color(t.text_dim)); - register(ui.ctx(), "keywordChipsEmpty", r.rect); + register(ui, "keywordChipsEmpty", r.rect); return; } if app.ui.settings.keyword_chips == crate::state::KeywordChips::Grouped { @@ -208,9 +208,9 @@ pub fn chip_row(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId /// A drawn chip does its work: its × takes the keyword off the selected photos, its name has the /// tooltip and the menu. fn chip_acts(app: &mut LightcraftApp, ui: &egui::Ui, c: &Chip, body: egui::Response, x: Option<egui::Response>) { - register(ui.ctx(), format!("keywordChip:{}", c.path), body.rect); + register(ui, format!("keywordChip:{}", c.path), body.rect); if let Some(x) = x { - register(ui.ctx(), format!("keywordChipRemove:{}", c.path), x.rect); + register(ui, format!("keywordChipRemove:{}", c.path), x.rect); if x.on_hover_text(crate::i18n::tr("Remove from Selected Photos")).clicked() { remove(app, ui.ctx(), c); } @@ -220,7 +220,7 @@ fn chip_acts(app: &mut LightcraftApp, ui: &egui::Ui, c: &Chip, body: egui::Respo let body = if c.on_all() { body.on_hover_text(full) } else { - register(ui.ctx(), format!("keywordChipPartial:{}", c.path), body.rect); + register(ui, format!("keywordChipPartial:{}", c.path), body.rect); let n = crate::i18n::tr_format!("On {have} of {of} selected photos", have = c.have, of = c.of); body.on_hover_text(format!("{full}\n{n}")) }; @@ -273,13 +273,13 @@ fn chip_groups(app: &mut LightcraftApp, ui: &mut egui::Ui, groups: &[Group], sel let measure = |s: &str| ui.painter().layout_no_wrap(s.to_string(), small.clone(), t.text_label).size().x; let shown = chip_label(&group.parent, false, avail, measure); let full = group.parent.replace('|', " › "); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &full)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &full)); ui.painter().text(r.left_center(), Align2::LEFT_CENTER, &shown, small.clone(), t.text_label); // (cut short, it says its whole name on hover, as a chip does) if shown != full { resp.on_hover_text(&full); } - register(ui.ctx(), format!("keywordGroup:{}", group.parent), r); + register(ui, format!("keywordGroup:{}", group.parent), r); } Line::Chips(g, row) => { let Some(group) = groups.get(g) else { continue }; @@ -296,7 +296,7 @@ fn chip_groups(app: &mut LightcraftApp, ui: &mut egui::Ui, groups: &[Group], sel ui.add_space(6.0); let label = crate::i18n::tr_format!("+{n} more", n = n); let r = ui.add(egui::Button::new(egui::RichText::new(label).color(t.text_label)).corner_radius(10.0)); - register(ui.ctx(), "keywordChipsMore", r.rect); + register(ui, "keywordChipsMore", r.rect); if r.on_hover_text(crate::i18n::tr("Show every keyword of the selected photos")).clicked() { app.ui.keyword_chips_all = Some(selection); } @@ -304,7 +304,7 @@ fn chip_groups(app: &mut LightcraftApp, ui: &mut egui::Ui, groups: &[Group], sel Line::Fewer => { ui.add_space(6.0); let r = ui.add(egui::Button::new(egui::RichText::new(crate::i18n::tr("Show fewer")).color(t.text_label)).corner_radius(10.0)); - register(ui.ctx(), "keywordChipsFewer", r.rect); + register(ui, "keywordChipsFewer", r.rect); if r.clicked() { app.ui.keyword_chips_all = None; } @@ -434,7 +434,7 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, at let lit = at.and_then(|k| offers.keywords.iter().position(|x| x == k)); let first = lit.map_or(0, |a| a.saturating_add(1).saturating_sub(count)).min(offers.keywords.len().saturating_sub(count)); let listed = offers.keywords.iter().skip(first).take(count); - let area = egui::Area::new(egui::Id::new("keyword-offers")).order(egui::Order::Foreground).constrain(true); + let area = egui::Area::new(egui::Id::unique("keyword-offers")).order(egui::Order::Foreground).constrain(true); let area = if over { area.pivot(Align2::LEFT_BOTTOM).fixed_pos(below.left_top() - vec2(0.0, 2.0)) } else { @@ -448,7 +448,7 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, at let line = |ui: &mut egui::Ui, id: egui::Id, name: &str, place: &str, said: &str, lit: bool| { let (r, resp) = ui.allocate_exact_size(vec2(width, 24.0), Sense::hover()); let resp = ui.interact(r, id, Sense::click()).union(resp); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, lit, said)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, lit, said)); if lit || resp.hovered() { ui.painter().rect_filled(r, 4.0, if lit { t.pressed } else { t.hover }); } @@ -469,10 +469,10 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, at let (place, name) = k.rsplit_once(SEP).unwrap_or(("", k)); let whole = k.replace(SEP, " › "); let lit = at == Some(k.as_str()); - let r = line(ui, egui::Id::new(("keyword-offer", k.to_lowercase())), name, place, &whole, lit); - register(ui.ctx(), format!("kwComplete:{k}"), r.rect); + let r = line(ui, egui::Id::unique(("keyword-offer", k.to_lowercase())), name, place, &whole, lit); + register(ui, format!("kwComplete:{k}"), r.rect); if lit { - register(ui.ctx(), format!("kwCompleteAt:{k}"), r.rect); + register(ui, format!("kwCompleteAt:{k}"), r.rect); } if r.clicked() { picked = Some(Picked::Keyword(k.clone())); @@ -497,10 +497,10 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, at ) }; // (its place is said in words: not a path to cut from the front) - let r = line(ui, egui::Id::new("keyword-offer-create"), name, "", &said, false); + let r = line(ui, egui::Id::unique("keyword-offer-create"), name, "", &said, false); let small = t.font(11.5); ui.painter().text(pos2(r.rect.right() - 8.0, r.rect.center().y), Align2::RIGHT_CENTER, place, small, t.text_label); - register(ui.ctx(), "kwCompleteCreate", r.rect); + register(ui, "kwCompleteCreate", r.rect); // (Return gives the highlighted offer instead, while there is one) let r = if at.is_none() { r.on_hover_text(crate::i18n::tr("Return creates this keyword and gives it to the selected photos")) diff --git a/crates/ui-egui/src/panels/layout_overlay.rs b/crates/ui-egui/src/panels/layout_overlay.rs index 9b4800d0f7..655e2ae33a 100644 --- a/crates/ui-egui/src/panels/layout_overlay.rs +++ b/crates/ui-egui/src/panels/layout_overlay.rs @@ -16,7 +16,7 @@ use lightcraft_raster::Rgba8; use crate::LightcraftApp; use crate::theme::Tokens; -use crate::widgets::register; +use crate::widgets::register_geometry; /// The longest side a layout image keeps (a screen never shows more of it). pub const MAX_SIDE: usize = 4096; @@ -112,7 +112,7 @@ pub fn draw(app: &LightcraftApp, p: &egui::Painter, photo: Rect) { return; } let ctx = p.ctx().clone(); - let id = egui::Id::new("loupe-layout-image"); + let id = egui::Id::unique("loupe-layout-image"); let file = (path.to_string(), li.revision); let mut cache = match ctx.data(|d| d.get_temp::<Cache>(id)) { Some(c) if c.file == file => c, @@ -153,7 +153,7 @@ pub fn draw(app: &LightcraftApp, p: &egui::Painter, photo: Rect) { } let alpha = (li.opacity.clamp(0.0, 1.0) * 255.0).round() as u8; p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::from_white_alpha(alpha)); - register(&ctx, "canvas:layoutImage", r.intersect(p.clip_rect())); + register_geometry(&ctx, "canvas:layoutImage", r.intersect(p.clip_rect())); } ctx.data_mut(|d| d.insert_temp(id, cache)); } @@ -173,7 +173,7 @@ fn note(p: &egui::Painter, why: &str) { p.galley(at, g, Color32::WHITE); y -= 3.0; } - register(p.ctx(), "canvas:layoutImageError", Rect::from_min_max(pos2(canvas.left(), y), pos2(canvas.left() + 360.0, canvas.bottom()))); + register_geometry(p.ctx(), "canvas:layoutImageError", Rect::from_min_max(pos2(canvas.left(), y), pos2(canvas.left() + 360.0, canvas.bottom()))); } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 2c7d2642c9..5a81edfab8 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -15,7 +15,7 @@ use crate::widgets::{icon_button, register}; /// drawn at this width (or the panel's, if wider), and the sidebar scrolls sideways when it /// exceeds the panel. One frame behind, which needs no second layout pass. pub(crate) fn content_width(ctx: &egui::Context) -> f32 { - ctx.data(|d| d.get_temp::<f32>(egui::Id::new("left-content-width"))).unwrap_or(0.0) + ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("left-content-width"))).unwrap_or(0.0) } /// The most a row asks for its name: longer ones are cut when there is no more room. @@ -35,7 +35,7 @@ const LIBFOLDER_REVEALED: &str = "libfolder-revealed"; /// A row says how wide it needs to be. fn note_width(ui: &egui::Ui, w: f32) { ui.data_mut(|d| { - let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::new("left-content-width-next"), || 0.0); + let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::unique("left-content-width-next"), || 0.0); *m = m.max(w); }); } @@ -56,7 +56,7 @@ const COUNT_ROOM: f32 = 40.0; /// The step a level is drawn with this frame: [`INDENT_STEP`] while the deepest open row fits the /// panel, narrower when it would not, never below [`MIN_INDENT_STEP`]. From the last frame. pub(crate) fn indent_step(ctx: &egui::Context) -> f32 { - ctx.data(|d| d.get_temp::<f32>(egui::Id::new("left-indent-step"))).unwrap_or(INDENT_STEP) + ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("left-indent-step"))).unwrap_or(INDENT_STEP) } /// How far right a row at `indent` (in [`INDENT_STEP`]s) is drawn this frame. @@ -68,7 +68,7 @@ fn indent_x(ctx: &egui::Context, indent: f32) -> f32 { /// frame's step. fn drawn_indent(ui: &egui::Ui, indent: f32) -> f32 { ui.data_mut(|d| { - let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::new("left-deepest-indent-next"), || 0.0); + let m = d.get_temp_mut_or_insert_with::<f32>(egui::Id::unique("left-deepest-indent-next"), || 0.0); *m = m.max(indent); }); indent_x(ui.ctx(), indent) @@ -138,22 +138,22 @@ fn row_sensed( if scroll_asked(ui, id) { ui.scroll_to_rect_animation(r, None, egui::style::ScrollAnimation::none()); } - register(ui.ctx(), format!("source:{id}"), r); + register(ui, format!("source:{id}"), r); let mark_w = if mark.is_some() { MARK_W } else { 0.0 }; let said = spoken.unwrap_or(label); let name = match count { Some(n) => crate::i18n::tr_format!("{label}, {n} photos", label = said, n = n), None => said.to_string(), }; - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &name)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &name)); // what is visible of the row: when the sidebar is scrolled sideways its bars and counts end at // the panel's edge, not at the end of the (wider) content - let visible_right: f32 = ui.data(|d| d.get_temp(egui::Id::new("left-visible-right"))).unwrap_or(f32::MAX); + let visible_right: f32 = ui.data(|d| d.get_temp(egui::Id::unique("left-visible-right"))).unwrap_or(f32::MAX); let edge = r.right().min(visible_right); let inner = Rect::from_min_max(r.min + vec2(8.0, 0.0), pos2((r.right() - 8.0).min(edge - 8.0).max(r.left() + 8.0), r.bottom())); if selected { ui.painter().rect_filled(inner, 4.0, t.canvas); - register(ui.ctx(), format!("highlight:{id}"), inner); + register(ui, format!("highlight:{id}"), inner); } else if resp.hovered() { ui.painter().rect_filled(inner, 4.0, t.hover.gamma_multiply(0.6)); } @@ -174,7 +174,7 @@ fn row_sensed( if let Some(c) = mark { let dot = Rect::from_center_size(pos2(count_left - MARK_W / 2.0, r.center().y), vec2(8.0, 8.0)); ui.painter().circle_filled(dot.center(), 4.0, c); - register(ui.ctx(), format!("labelMark:{id}"), dot); + register(ui, format!("labelMark:{id}"), dot); } // the name gives way to the count: cut with an ellipsis, in full on hover let room = count_left - mark_w - 8.0 - label_left; @@ -182,12 +182,12 @@ fn row_sensed( let full_w = measure(label); let shown = if full_w <= room { label.to_string() } else { crate::widgets::elide_head(label, room.max(0.0), measure) }; let label_rect = ui.painter().text(pos2(label_left, r.center().y), Align2::LEFT_CENTER, &shown, font.clone(), color); - register(ui.ctx(), format!("label:{id}"), label_rect); + register(ui, format!("label:{id}"), label_rect); let resp = if shown != label { resp.on_hover_text(label) } else { resp }; note_width(ui, row_need(indent, full_w, mark_w, count_galley.as_ref().map(|g| g.size().x))); if let Some(galley) = count_galley { let rect = Rect::from_min_size(pos2(edge - 18.0 - galley.size().x, r.center().y - galley.size().y / 2.0), galley.size()); - register(ui.ctx(), format!("count:{id}"), rect); + register(ui, format!("count:{id}"), rect); ui.painter().galley(rect.min, galley, t.text_dim); } resp @@ -204,7 +204,7 @@ fn out_of_sight(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, label: &str, c return false; } ui.allocate_space(r.size()); - register(ui.ctx(), format!("source:{id}"), r); + register(ui, format!("source:{id}"), r); let indent = drawn_indent(ui, indent); let t = Tokens::get(ui.ctx()); let painter = ui.painter(); @@ -216,7 +216,7 @@ fn out_of_sight(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, label: &str, c /// Whether the sidebar is asked to scroll to the row `id` this frame ([`SCROLL_TO_ROW`]). fn scroll_asked(ui: &egui::Ui, id: &str) -> bool { - ui.data(|d| d.get_temp::<String>(egui::Id::new(SCROLL_TO_ROW))).is_some_and(|want| want == id.to_lowercase()) + ui.data(|d| d.get_temp::<String>(egui::Id::unique(SCROLL_TO_ROW))).is_some_and(|want| want == id.to_lowercase()) } /// How wide a row needs to be, from its indent, name, colour dot and count widths. It asks for @@ -234,7 +234,7 @@ fn disclosure_chevron(ui: &mut egui::Ui, row: &egui::Response, indent: f32, open let c = pos2(row.rect.left() + 10.0 + indent_x(ui.ctx(), indent), row.rect.center().y); let tri = Rect::from_center_size(c, vec2(16.0, 16.0)); let tr = ui.interact(tri, id, Sense::click()); - register(ui.ctx(), widget, tri); + register(ui, widget, tri); let col = if tr.hovered() { t.text } else { t.text_dim }; paint(ui.painter(), Rect::from_center_size(c, vec2(16.0, 16.0)), if open { Icon::ChevronDown } else { Icon::ChevronRight }, col); tr @@ -260,7 +260,7 @@ fn tree_toggle(ui: &mut egui::Ui, row: &egui::Response, indent: f32, key: egui:: set_tree_open(ui, key, *open); } let label = if *open { crate::i18n::tr("Collapse") } else { crate::i18n::tr("Expand") }; - tri.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); + tri.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); tri } @@ -286,7 +286,7 @@ fn section( let edge = visible_right(ui).min(header.right()); let y = header.top() - SECTION_GAP / 2.0; ui.painter().hline(header.left() + 18.0..=(edge - 18.0).max(header.left() + 18.0), y, egui::Stroke::new(1.0, t.divider)); - let show = egui::Id::new("left-show-section"); + let show = egui::Id::unique("left-show-section"); if let Some((asked, frame)) = ui.data(|d| d.get_temp::<(SidebarSection, u64)>(show)) && asked == section { @@ -294,7 +294,7 @@ fn section( // asked for by the frame before (a request the section was not drawn for is forgotten), // and up or down only: the sidebar stays where it was scrolled sideways if ui.ctx().cumulative_frame_nr().saturating_sub(frame) <= 2 { - let view_top: f32 = ui.data(|d| d.get_temp(egui::Id::new("left-view-top"))).unwrap_or(header.top()); + let view_top: f32 = ui.data(|d| d.get_temp(egui::Id::unique("left-view-top"))).unwrap_or(header.top()); let delta = vec2(0.0, view_top - header.top()); ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none()); } @@ -313,7 +313,7 @@ fn section( /// Where what the panel shows of the sidebar's content ends (screen x): the content is wider /// than the panel while the sidebar scrolls sideways. fn visible_right(ui: &egui::Ui) -> f32 { - ui.data(|d| d.get_temp(egui::Id::new("left-visible-right"))).unwrap_or(f32::MAX) + ui.data(|d| d.get_temp(egui::Id::unique("left-visible-right"))).unwrap_or(f32::MAX) } /// The header of the open section whose own header has scrolled out of sight stays at the top of @@ -327,7 +327,7 @@ fn pinned_header(app: &mut LightcraftApp, ui: &mut egui::Ui, placed: &[PlacedSec Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + SECTION_HEADER) }); // rows ask where it is (next frame: they are laid out before it) - ui.data_mut(|d| d.insert_temp(egui::Id::new("left-pinned-rect"), rect)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-pinned-rect"), rect)); let (Some(p), Some(r)) = (pinned, rect) else { return }; let t = Tokens::get(ui.ctx()); let view = ui.clip_rect(); @@ -338,7 +338,7 @@ fn pinned_header(app: &mut LightcraftApp, ui: &mut egui::Ui, placed: &[PlacedSec // folded from here: its own header comes into view, not whatever was below the section // (next frame, when the section is laid out folded: see `section`) let frame = ui.ctx().cumulative_frame_nr(); - ui.data_mut(|d| d.insert_temp(egui::Id::new("left-show-section"), (p.section, frame))); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-show-section"), (p.section, frame))); ui.ctx().request_repaint(); } } @@ -348,7 +348,7 @@ fn pinned_header(app: &mut LightcraftApp, ui: &mut egui::Ui, placed: &[PlacedSec fn empty_hint(ui: &mut egui::Ui, section: SidebarSection) { let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); - register(ui.ctx(), format!("sidebarEmpty:{}", section.id()), r); + register(ui, format!("sidebarEmpty:{}", section.id()), r); let text = crate::i18n::tr(section.empty_hint()); let galley = ui.painter().layout_no_wrap(text.to_string(), t.font(12.5), t.text_dim); note_width(ui, 42.0 + galley.size().x + 18.0); @@ -416,7 +416,7 @@ fn section_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, placed: &[PlacedSect let t = Tokens::get(ui.ctx()); let line = Rect::from_min_max(pos2(view.left() + 8.0, y - 1.0), pos2(visible_right(ui).min(view.right()) - 8.0, y + 1.0)); ui.painter().rect_filled(line, 1.0, t.accent); - register(ui.ctx(), "sidebarSectionDrop", line); + register(ui, "sidebarSectionDrop", line); } } @@ -432,7 +432,7 @@ pub fn section_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(pos) = pos else { return }; let t = Tokens::get(ctx); ctx.set_cursor_icon(egui::CursorIcon::Grabbing); - egui::Area::new(egui::Id::new("drag-section")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show( + egui::Area::new(egui::Id::unique("drag-section")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show( ctx, |ui| { egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { @@ -452,8 +452,8 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe let id = section.id(); let title = crate::i18n::tr(section.title()); let (interact, widget) = if pinned { ("sidebar-section-pinned", "sidebarSectionPinned") } else { ("sidebar-section", "sidebarSection") }; - let resp = ui.interact(r, ui.id().with((interact, id)), Sense::click_and_drag()); - register(ui.ctx(), format!("{widget}:{id}"), r); + let resp = ui.interact(r, ui.scope_id().with((interact, id)), Sense::click_and_drag()); + register(ui, format!("{widget}:{id}"), r); let toggled = resp.clicked(); if toggled { app.ui.sidebar.toggle_collapsed(section); @@ -463,12 +463,12 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe let on_button = header_button(section).is_some() && ui.input(|i| i.pointer.press_origin()).is_some_and(|p| header_button_rect(ui, r).contains(p)); if resp.drag_started_by(egui::PointerButton::Primary) && !on_button { // picked up by the pinned header, the drag starts inside the top edge (see `drag_auto_scroll`) - ui.data_mut(|d| d.insert_temp(egui::Id::new("left-section-drag-from-pinned"), pinned)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-section-drag-from-pinned"), pinned)); app.ui.dragging_section = Some(section); } crate::widgets::context_menu(&resp, |ui| sections_menu(app, ui, Some(section))); let open = !app.ui.sidebar.is_collapsed(section); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title)); + crate::widgets::announce_disclosure(&resp, true, open, title); // what is visible of the header: its bar and count end at the panel's edge, like a row's let edge = r.right().min(visible_right(ui)); let hovered = resp.hovered() && app.ui.dragging_section.is_none(); @@ -477,7 +477,7 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe ui.painter().rect_filled(bar, 4.0, t.hover.gamma_multiply(0.6)); } let c = pos2(r.left() + 10.0, r.center().y); - register(ui.ctx(), format!("{widget}Chevron:{id}"), Rect::from_center_size(c, vec2(16.0, 16.0))); + register(ui, format!("{widget}Chevron:{id}"), Rect::from_center_size(c, vec2(16.0, 16.0))); let col = if hovered { t.text } else { t.text_dim }; paint(ui.painter(), Rect::from_center_size(c, vec2(16.0, 16.0)), if open { Icon::ChevronDown } else { Icon::ChevronRight }, col); ui.painter().text(pos2(r.left() + 18.0, r.center().y), Align2::LEFT_CENTER, title, t.semibold(13.5), t.text_label); @@ -488,7 +488,7 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe // folded: how much is in there (left of the header's own button) let right = edge - 18.0 - if button.is_some() { HEADER_BUTTON + 4.0 } else { 0.0 }; let count = ui.painter().text(pos2(right, r.center().y), Align2::RIGHT_CENTER, rows.to_string(), t.font(12.5), t.text_dim); - register(ui.ctx(), format!("{widget}Count:{id}"), count); + register(ui, format!("{widget}Count:{id}"), count); } if section == SidebarSection::Albums { top_level_drop_target(app, ui, r); @@ -577,13 +577,13 @@ fn sections_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, on: Option<SidebarS let mut run = None; if let Some(section) = on { let hide = ui.button(crate::i18n::tr("Hide This Section")); - register(ui.ctx(), "sidebarMenu:hide", hide.rect); + register(ui, "sidebarMenu:hide", hide.rect); if hide.clicked() { run = Some(("view.sidebarSection", json!({"section": section.id(), "show": false}))); } for (up, label, widget) in [(true, "Move Up", "sidebarMenu:moveUp"), (false, "Move Down", "sidebarMenu:moveDown")] { let item = ui.add_enabled(app.ui.sidebar.can_move(section, up), egui::Button::new(crate::i18n::tr(label))); - register(ui.ctx(), widget, item.rect); + register(ui, widget, item.rect); if item.clicked() { run = Some(("view.sidebarMoveSection", json!({"section": section.id(), "direction": if up { "up" } else { "down" }}))); } @@ -592,14 +592,14 @@ fn sections_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, on: Option<SidebarS } for s in app.ui.sidebar.sections().iter().filter(|s| s.id.available()) { let shown = ui.selectable_label(!s.hidden, crate::i18n::tr(s.id.title())); - register(ui.ctx(), format!("sidebarMenu:section:{}", s.id.id()), shown.rect); + register(ui, format!("sidebarMenu:section:{}", s.id.id()), shown.rect); if shown.clicked() { run = Some(("view.sidebarSection", json!({"section": s.id.id(), "show": s.hidden}))); } } ui.separator(); let reset = ui.add_enabled(!app.ui.sidebar.is_default(), egui::Button::new(crate::i18n::tr("Reset Sidebar Sections"))); - register(ui.ctx(), "sidebarMenu:reset", reset.rect); + register(ui, "sidebarMenu:reset", reset.rect); if reset.clicked() { run = Some(("view.sidebarReset", json!({}))); } @@ -639,6 +639,8 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } +/// Draw the My Photos sidebar: title and open-library name, the scrollable sources, albums, +/// folders and sections, with the section visibility menu on the title. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)); @@ -647,7 +649,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // the title offers the sections' menu too: where hidden sections come back from let (hr, title) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::click()); crate::widgets::announce(&title, crate::i18n::tr("My Photos")); - register(ui.ctx(), "sidebarTitle", hr); + register(ui, "sidebarTitle", hr); crate::widgets::context_menu(&title, |ui| sections_menu(app, ui, None)); // the open library's name under the title, so nobody edits in the wrong one (issue #902) let library = crate::panels::settings::open_library_name(app); @@ -661,7 +663,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { t.font(11.0), t.text_dim, ); - crate::widgets::register(ui.ctx(), "label:libraryName", hr); + crate::widgets::register(ui, "label:libraryName", hr); if let Some(l) = app.session.library.as_ref() { title.on_hover_text(l.dir.display().to_string()); } @@ -672,16 +674,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { drag_auto_scroll(app, ui); // where the visible part of the content starts (screen y), for the pinned header let view_top = ui.cursor().top() + viewport.min.y; - ui.data_mut(|d| d.insert_temp(egui::Id::new("left-view-top"), view_top)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-view-top"), view_top)); // rows are as wide as the widest one needs (last frame), at least the panel let wide = viewport.width().max(content_width(ui.ctx())); ui.set_min_width(wide); ui.set_max_width(wide); ui.data_mut(|d| { - d.insert_temp(egui::Id::new("left-content-width-next"), 0.0f32); - d.insert_temp(egui::Id::new("left-deepest-indent-next"), 0.0f32); + d.insert_temp(egui::Id::unique("left-content-width-next"), 0.0f32); + d.insert_temp(egui::Id::unique("left-deepest-indent-next"), 0.0f32); // where the visible part of the content ends (screen x), for what stays at the edge - d.insert_temp(egui::Id::new("left-visible-right"), ui.cursor().left() + viewport.max.x); + d.insert_temp(egui::Id::unique("left-visible-right"), ui.cursor().left() + viewport.max.x); }); let src = app.session.source; for (id, icon, label, count, s) in [ @@ -719,18 +721,18 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { above.push('|'); } above.push_str(name); - set_tree_open(ui, egui::Id::new(("kw-open", above.to_lowercase())), true); + set_tree_open(ui, egui::Id::unique(("kw-open", above.to_lowercase())), true); } // …and the sidebar scrolls to it - ui.data_mut(|d| d.insert_temp(egui::Id::new(SCROLL_TO_ROW), format!("keyword:{path}").to_lowercase())); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(SCROLL_TO_ROW), format!("keyword:{path}").to_lowercase())); } // the folder Show in Folders went to: Folders is shown and opened, and so are the // folders above it, also when it was already the one shown and one was folded by hand… if let Some(path) = app.ui.reveal_folder.take() { app.ui.sidebar.reveal(SidebarSection::Folders); - ui.data_mut(|d| d.remove::<Option<String>>(egui::Id::new(LIBFOLDER_REVEALED))); + ui.data_mut(|d| d.remove::<Option<String>>(egui::Id::unique(LIBFOLDER_REVEALED))); // …and the sidebar scrolls to it - ui.data_mut(|d| d.insert_temp(egui::Id::new(SCROLL_TO_ROW), format!("libfolder:{path}").to_lowercase())); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(SCROLL_TO_ROW), format!("libfolder:{path}").to_lowercase())); } // Local keeps track of the folder being browsed whether or not it is drawn let local = local_now(app, ui); @@ -764,22 +766,22 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { }; placed.push(at); } - ui.data_mut(|d| d.remove::<String>(egui::Id::new(SCROLL_TO_ROW))); + ui.data_mut(|d| d.remove::<String>(egui::Id::unique(SCROLL_TO_ROW))); // room below the last section (a section dragged to the end is dropped here) ui.add_space(SECTION_GAP * 2.0); pinned_header(app, ui, &placed, view_top); section_drag(app, ui, &placed); // what the rows asked for becomes next frame's width - let next = ui.data(|d| d.get_temp::<f32>(egui::Id::new("left-content-width-next"))).unwrap_or(0.0); + let next = ui.data(|d| d.get_temp::<f32>(egui::Id::unique("left-content-width-next"))).unwrap_or(0.0); if (next - content_width(ui.ctx())).abs() > 0.5 { - ui.data_mut(|d| d.insert_temp(egui::Id::new("left-content-width"), next)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-content-width"), next)); ui.ctx().request_repaint(); } // …and the deepest row drawn (or passed over out of sight) sets next frame's step - let deepest = ui.data(|d| d.get_temp::<f32>(egui::Id::new("left-deepest-indent-next"))).unwrap_or(0.0); + let deepest = ui.data(|d| d.get_temp::<f32>(egui::Id::unique("left-deepest-indent-next"))).unwrap_or(0.0); let step = step_for(viewport.width(), deepest); if step != indent_step(ui.ctx()) { - ui.data_mut(|d| d.insert_temp(egui::Id::new("left-indent-step"), step)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("left-indent-step"), step)); ui.ctx().request_repaint(); } }); @@ -831,7 +833,7 @@ fn missing_count(app: &mut LightcraftApp, ui: &mut egui::Ui) -> usize { at: f64, rev: u64, } - let id = egui::Id::new("missing-count"); + let id = egui::Id::unique("missing-count"); let now = ui.input(|i| i.time); let rev = app.session.catalog.revision; let mut job: Job = ui.data(|d| d.get_temp(id)).unwrap_or(Job { rev: u64::MAX, at: f64::MIN, ..Default::default() }); @@ -942,7 +944,7 @@ fn local_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, now: &LocalNow) { fn hidden_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, hidden: &[(String, String)]) { for (name, path) in hidden { let r = ui.button(name).on_hover_text(path); - register(ui.ctx(), format!("local:restoreHidden:{path}"), r.rect); + register(ui, format!("local:restoreHidden:{path}"), r.rect); if r.clicked() { let _ = app.run("local.restoreHidden", json!({"path": path})); ui.close(); @@ -950,7 +952,7 @@ fn hidden_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, hidden: &[(String, St } ui.separator(); let r = ui.button(crate::i18n::tr("Restore All")); - register(ui.ctx(), "local:restoreHidden:all", r.rect); + register(ui, "local:restoreHidden:all", r.rect); if r.clicked() { let _ = app.run("local.restoreHidden", json!({})); ui.close(); @@ -1058,7 +1060,7 @@ pub(crate) fn fs_cached_running(ctx: &egui::Context) -> usize { } fn fs_running_counter(ctx: &egui::Context) -> std::sync::Arc<std::sync::atomic::AtomicUsize> { - ctx.data_mut(|d| d.get_temp_mut_or_default::<std::sync::Arc<std::sync::atomic::AtomicUsize>>(egui::Id::new("fs-cached-running")).clone()) + ctx.data_mut(|d| d.get_temp_mut_or_default::<std::sync::Arc<std::sync::atomic::AtomicUsize>>(egui::Id::unique("fs-cached-running")).clone()) } /// A file-system answer for `path` (`f(path)`), kept per `kind` and path and refreshed on a worker @@ -1071,7 +1073,7 @@ pub(crate) fn fs_cached<T: Clone + Send + 'static>(ui: &egui::Ui, kind: &'static running: bool, } type Cell<T> = std::sync::Arc<std::sync::Mutex<Entry<T>>>; - let id = egui::Id::new(("fs-cached", kind, path.to_string())); + let id = egui::Id::unique(("fs-cached", kind, path.to_string())); let now = ui.input(|i| i.time); let cell: Cell<T> = match ui.data(|d| d.get_temp::<Cell<T>>(id)) { Some(c) => c, @@ -1136,13 +1138,13 @@ fn folder_tree( reveal: bool, transient: bool, ) { - let open_id = egui::Id::new(("folder-open", place.to_string(), path.to_string())); + let open_id = egui::Id::unique(("folder-open", place.to_string(), path.to_string())); let sel = current.is_some_and(|c| same_folder(c, path)); let on_the_way = !sel && current.is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)); let mut open = tree_open(ui, open_id, false); if reveal && on_the_way { // opened once per browsed folder: collapsing it again afterwards sticks - let revealed_id = egui::Id::new(("folder-revealed", place.to_string(), path.to_string())); + let revealed_id = egui::Id::unique(("folder-revealed", place.to_string(), path.to_string())); let target = current.map(str::to_string); if ui.data(|d| d.get_temp::<Option<String>>(revealed_id)) != Some(target.clone()) { open = true; @@ -1220,7 +1222,7 @@ fn folder_tree( /// One By Date row (`key`: `YYYY`, `YYYY-MM` or `YYYY-MM-DD`); returns whether it is open. fn date_row(app: &mut LightcraftApp, ui: &mut egui::Ui, key: &str, label: &str, count: usize, indent: f32) -> bool { - let open_id = egui::Id::new(("date-open", key.to_string())); + let open_id = egui::Id::unique(("date-open", key.to_string())); let mut open = tree_open(ui, open_id, false); let sel = app.session.filter.date.as_deref() == Some(key); let resp = row(app, ui, &format!("date:{key}"), Icon::Clock, label, Some(count), sel, indent); @@ -1256,7 +1258,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare let Some(kids) = all.get(&parent) else { return }; for a in kids { if a.folder { - let open_id = egui::Id::new(("folder-open", a.id.0)); + let open_id = egui::Id::unique(("folder-open", a.id.0)); let mut open = tree_open(ui, open_id, true); if open_to.contains(&a.id) && !open { open = true; @@ -1304,7 +1306,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare let label = if problems.is_empty() { label } else { format!("⚠ {label}") }; let mut resp = row_sensed(app, ui, &format!("album:{}", a.id.0), icon, &label, None, Some(n), sel, indent, Sense::click_and_drag(), None); if !problems.is_empty() { - crate::widgets::register(ui.ctx(), format!("albumProblem:{}", a.id.0), resp.rect); + crate::widgets::register(ui, format!("albumProblem:{}", a.id.0), resp.rect); } if resp.drag_started() { app.ui.dragging_album = Some(a.id.0); @@ -1348,7 +1350,7 @@ fn pointer_over_row(ui: &egui::Ui, rect: Rect) -> bool { /// Where the pinned header was drawn last frame, if one was (rows are laid out before it). fn pinned_rect(ui: &egui::Ui) -> Option<Rect> { - ui.data(|d| d.get_temp::<Option<Rect>>(egui::Id::new("left-pinned-rect"))).flatten() + ui.data(|d| d.get_temp::<Option<Rect>>(egui::Id::unique("left-pinned-rect"))).flatten() } fn pointer_on_pinned_header(ui: &egui::Ui) -> bool { @@ -1380,7 +1382,7 @@ fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { let Some(p) = ui.input(|i| i.pointer.latest_pos()).filter(|p| p.x >= view.left() && p.x <= view.right()) else { return }; // a section picked up by its pinned header starts inside the top edge: it scrolls once it has // left the header. Any other drag scrolls there as at any edge, to reach what is above - let from_pinned = egui::Id::new("left-section-drag-from-pinned"); + let from_pinned = egui::Id::unique("left-section-drag-from-pinned"); if app.ui.dragging_section.is_some() && ui.data(|d| d.get_temp::<bool>(from_pinned)) == Some(true) { if pointer_on_pinned_header(ui) { return; @@ -1429,7 +1431,7 @@ fn forget_hover(app: &LightcraftApp, ctx: &egui::Context) { let ids: Vec<u64> = app.session.catalog.albums().filter(|a| a.folder).map(|a| a.id.0).collect(); ctx.data_mut(|d| { for id in ids { - d.remove_temp::<f64>(egui::Id::new(("album-hover", id))); + d.remove_temp::<f64>(egui::Id::unique(("album-hover", id))); } }); } @@ -1497,7 +1499,7 @@ fn album_drop_at(app: &LightcraftApp, dragged: AlbumId, target: &Album, frac: f3 /// done on release. A closed folder with something inside (`open`) opens once the pointer rests on /// it; returns whether it did. fn album_drag_over(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, row: &Album, open: Option<&mut bool>, indent: f32) -> bool { - let hover_id = egui::Id::new(("album-hover", row.id.0)); + let hover_id = egui::Id::unique(("album-hover", row.id.0)); let Some(dragged) = app.ui.dragging_album.map(AlbumId) else { return false }; let pos = ui.input(|i| i.pointer.latest_pos()).filter(|_| pointer_over_row(ui, resp.rect)); let Some(pos) = pos else { @@ -1560,7 +1562,7 @@ fn top_level_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, header: Rec return; } let t = Tokens::get(ui.ctx()); - register(ui.ctx(), "albumDrop:top", header); + register(ui, "albumDrop:top", header); let over = pointer_over(ui, header); let stroke = if over { egui::Stroke::new(1.5, t.accent) } else { egui::Stroke::new(1.0, t.text_dim.gamma_multiply(0.5)) }; ui.painter().rect_stroke(header.shrink2(vec2(8.0, 3.0)), 4.0, stroke, egui::StrokeKind::Inside); @@ -1586,11 +1588,14 @@ pub fn album_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let (Some(pos), Some(name)) = (pos, app.session.catalog.album(AlbumId(id)).map(|a| a.name.clone())) else { return }; let t = Tokens::get(ctx); ctx.set_cursor_icon(egui::CursorIcon::Grabbing); - egui::Area::new(egui::Id::new("drag-album")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(ctx, |ui| { - egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { - ui.label(egui::RichText::new(name).color(egui::Color32::WHITE).font(t.semibold(12.0))); - }); - }); + egui::Area::new(egui::Id::unique("drag-album")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show( + ctx, + |ui| { + egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { + ui.label(egui::RichText::new(name).color(egui::Color32::WHITE).font(t.semibold(12.0))); + }); + }, + ); } /// An album row while photos are dragged from the grid: highlighted under the pointer; a @@ -1678,7 +1683,7 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { let menu = crate::widgets::menu_button(ui, crate::i18n::tr("Import"), |ui| { let mut entry = |ui: &mut egui::Ui, label: String, widget: String, command: &str, params: serde_json::Value| { let r = ui.button(label); - crate::widgets::register(ui.ctx(), widget, r.rect); + crate::widgets::register(ui, widget, r.rect); if r.clicked() { if let Err(e) = app.run(command, params) { app.toast(ui.ctx(), e); @@ -1703,9 +1708,9 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { entry(ui, format!("{}…", d.name), format!("button:albumImportDevice:{i}"), "file.addFromDevice", params); } }); - crate::widgets::register(ui.ctx(), "button:albumImportDevice", device.response.rect); + crate::widgets::register(ui, "button:albumImportDevice", device.response.rect); }); - crate::widgets::register(ui.ctx(), "button:albumImport", menu.response.rect); + crate::widgets::register(ui, "button:albumImport", menu.response.rect); } if !a.folder && !a.is_smart() { let is_target = app.session.target_album == Some(a.id) || (app.session.target_album.is_none() && a.quick); @@ -1773,7 +1778,7 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { app.ui.dialog = Some(crate::state::Dialog::RenameAlbum { id: a.id.0, name: a.name.clone() }); } let delete = ui.button(crate::i18n::tr("Delete")); - register(ui.ctx(), format!("albumDelete:{}", a.id.0), delete.rect); + register(ui, format!("albumDelete:{}", a.id.0), delete.rect); let delete = delete.on_hover_text(crate::i18n::tr("Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.")); if delete.clicked() { @@ -1812,7 +1817,7 @@ fn is_within(app: &LightcraftApp, id: lightcraft_catalog::AlbumId, ancestor: lig fn reveal_chosen(app: &LightcraftApp, ui: &egui::Ui, tree: &[FolderNode]) { let shown = app.session.library_folder.clone().filter(|_| app.session.source == LibrarySource::LibraryFolder); let chosen = shown.filter(|c| !lightcraft_catalog::query::folder_key(c).is_empty()); - let seen = egui::Id::new(LIBFOLDER_REVEALED); + let seen = egui::Id::unique(LIBFOLDER_REVEALED); let now = chosen.as_deref().map(lightcraft_catalog::query::folder_key); if ui.data(|d| d.get_temp::<Option<String>>(seen)) == Some(now.clone()) { return; @@ -1823,7 +1828,7 @@ fn reveal_chosen(app: &LightcraftApp, ui: &egui::Ui, tree: &[FolderNode]) { for n in nodes { if lightcraft_catalog::query::folder_within(chosen, &n.path) && !same_folder(chosen, &n.path) { let key = lightcraft_catalog::query::folder_key(&n.path); - ui.data_mut(|d| d.insert_temp(egui::Id::new(("libfolder-open", key)), true)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(("libfolder-open", key)), true)); open_above(ui, &n.children, chosen); } } @@ -1844,7 +1849,7 @@ pub(crate) fn folder_row_of<'a>(tree: &'a [FolderNode], dir: &str) -> Option<&'a fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[FolderNode], indent: f32) { for n in nodes { let key = lightcraft_catalog::query::folder_key(&n.path); - let open_id = egui::Id::new(("libfolder-open", key.clone())); + let open_id = egui::Id::unique(("libfolder-open", key.clone())); // a disk starts open, and so does a folder that holds nothing itself and leads to one // folder (`Users` → `me`): the first row where the library branches is what you look for let leads_on = n.own == 0 && n.children.len() == 1; @@ -1970,7 +1975,7 @@ fn spring_open(ui: &egui::Ui, n: &FolderNode, open_id: egui::Id, open: &mut bool if *open || n.children.is_empty() { return; } - let key = egui::Id::new("folder-spring-open"); + let key = egui::Id::unique("folder-spring-open"); let (now, frame) = (ui.input(|i| i.time), ui.ctx().cumulative_frame_nr()); // held without a break: over this row last frame too let since = match ui.data(|d| d.get_temp::<(String, f64, u64)>(key)) { @@ -2051,7 +2056,7 @@ fn row_menu(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) { /// background finder relink only this folder's photos (including the folders inside it). fn locate_missing_item(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode) { let r = ui.button(crate::i18n::tr("Locate Missing Files…")); - register(ui.ctx(), "folderLocateMissing", r.rect); + register(ui, "folderLocateMissing", r.rect); if r.clicked() { if let Err(e) = app.run("file.findMissing", json!({"within": n.path})) { app.toast(ui.ctx(), e); @@ -2098,7 +2103,7 @@ fn synchronize_item(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, let r = ui .button(crate::i18n::tr("Synchronize Folder…")) .on_hover_text(crate::i18n::tr("Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps")); - crate::widgets::register(ui.ctx(), "folderSynchronize", r.rect); + crate::widgets::register(ui, "folderSynchronize", r.rect); if r.clicked() { // a disk, or a folder holding disks, was chosen as such if let Err(e) = crate::sync::open(app, &n.path, name, n.volume || !n.selectable) { @@ -2119,7 +2124,7 @@ fn folder_label_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode) ui.close(); } }); - register(ui.ctx(), "folderLabelMenu", menu.response.rect); + register(ui, "folderLabelMenu", menu.response.rect); } /// The context menu of a folder row: the folder's disk actions (the same as Local's, photos @@ -2200,7 +2205,7 @@ fn folder_menu_for_library(app: &mut LightcraftApp, resp: &egui::Response, n: &F fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[KeywordNode], indent: f32) { for n in nodes { // leaves (most keywords) have no open state to look up - let open_id = (!n.children.is_empty()).then(|| egui::Id::new(("kw-open", n.path.to_lowercase()))); + let open_id = (!n.children.is_empty()).then(|| egui::Id::unique(("kw-open", n.path.to_lowercase()))); let mut open = open_id.is_some_and(|k| tree_open(ui, k, false)); let id = format!("keyword:{}", n.path); if !out_of_sight(app, ui, &id, &n.name, Some(n.count), indent, false) { diff --git a/crates/ui-egui/src/panels/library_problem.rs b/crates/ui-egui/src/panels/library_problem.rs index 212e57d904..31128e9a9f 100644 --- a/crates/ui-egui/src/panels/library_problem.rs +++ b/crates/ui-egui/src/panels/library_problem.rs @@ -2,14 +2,331 @@ //! blocking window says which library and why, and offers Try Again, Choose Another Library…, //! Continue Without Saving and Quit. Continuing shows a banner under the top bar for as long as the //! session is temporary. +//! +//! The same window lists the recent libraries to choose from when Settings ▸ General ▸ At launch +//! is *Ask me*, or when Alt/Option is held as the window first appears (issue #1290): Open, Open +//! Another…, New Library…, Remove from List and Quit, with the arrow keys, Return and Esc. +//! [`launch_plan`] decides at launch which of the two the desktop app starts with. +//! +//! Whether each recent library can be opened is checked on a worker ([`RecentChecks`]), never on +//! the UI thread: a library on a network share whose server is gone, or on a disk that has to +//! spin up, can take seconds to answer. Until its answer comes the list shows the row as +//! "Checking…" (it can still be opened: opening says why if it can't), and File ▸ Open Recent +//! Library keeps it enabled; the same answers grey out the menu's entries. + +use std::path::{Path, PathBuf}; use egui::{Align2, RichText, vec2}; use serde_json::json; use crate::LightcraftApp; +use crate::state::{AppSettings, LaunchLibrary}; use crate::theme::Tokens; use crate::widgets::register; +/// Egui ids/layers shared by the window drawing and the control-channel barrier: the two blocking +/// windows and their dim. +const DIM_ID: &str = "library-problem-dim"; +const ERROR_WINDOW_ID: &str = "library-problem"; +const CHOOSER_WINDOW_ID: &str = "library-chooser"; + +/// The named `Foreground` layer used by the dim and the two blocking library windows. +fn foreground_layer(id: &str) -> egui::LayerId { + egui::LayerId::new(egui::Order::Foreground, egui::Id::unique(id)) +} + +/// The full-screen backdrop that takes the modal layer while the library window is up. +pub(crate) fn dim_layer() -> egui::LayerId { + foreground_layer(DIM_ID) +} + +/// Whether `layer` is one of the blocking library windows' own layers (the error window or the +/// launch list). Their registered controls are the only targets allowed through the dim. +fn is_window_layer(layer: egui::LayerId) -> bool { + layer == foreground_layer(ERROR_WINDOW_ID) || layer == foreground_layer(CHOOSER_WINDOW_ID) +} + +/// Whether a control-channel press must be explicitly refused because the library window's dim +/// owns the modal layer and the target is not one of that window's own controls. Ordinary dialogs +/// keep their existing backdrop semantics; only this blocking window is different. +pub(crate) fn refuses_control_target(top_modal: Option<egui::LayerId>, target: egui::LayerId) -> bool { + top_modal == Some(dim_layer()) && !is_window_layer(target) +} + +/// Which blocking window is on screen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WindowMode { + Error, + Chooser, +} + +/// What one draw pass did for the blocking library window (test instrumentation). +/// +/// The first-return tests used to prove shielding only through a rating shortcut, which the global +/// shortcut guard now blocks on every settled blocking frame. Recording the pass itself keeps +/// those regressions non-vacuous: removing the shield pass, its discard or its settlement changes +/// this sequence even though the rating shortcut would still stay blocked. +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LibraryPass { + /// The dedicated shield pass for a newly visible window: only the window drew, background + /// input was dropped, and egui discarded the pass. + Shield, + /// A pass that went on to draw the background (with the visible window, when there is one). + Background, +} + +/// First-frame input state for the blocking library window. +/// +/// Its `Foreground` areas are non-interactable during their first layout pass, and a text field +/// behind it may still own the keyboard focus. The frame that creates a window therefore draws +/// only that window and drops background input, just as a new notice prompt does. +#[derive(Default)] +pub(crate) struct WindowBarrier { + /// The window whose completed layout has already settled. `None` until the first pass is + /// accepted (and again once the window or its banner replaces it). + shown: Option<WindowMode>, + /// The next pass 0 is the shielding pass for a newly shown window. Also armed while the + /// window is hidden by a prompt or by a dialog it opened, so the first pass that actually + /// draws it again is shielded rather than reusing a background pass's hit-test snapshot. + transition: bool, + /// The window actually drew in the pass being completed (reset at the start of every draw). + drawn: Option<WindowMode>, + /// The shield pass for the current transition has already run (the discarded pass drew only + /// the window); the following pass may settle it. Without this, a window that appeared in the + /// middle of a pass could settle without ever having had a dedicated shield pass. + shielded: bool, + /// The current transition may have dropped an injected synthetic batch; cancel its gesture + /// once so it reports an error instead of a false `ok: true`. + cancel_injected: bool, +} + +impl WindowBarrier { + /// Begin a new shield transition. It stays armed until a completed pass has drawn the window + /// after a dedicated shield pass. + fn begin_transition(&mut self) { + self.transition = true; + self.shielded = false; + self.cancel_injected = true; + } +} + +/// The blocking library window that is present (not dismissed), if any: the launch chooser when +/// it is shown, otherwise the error window. +fn present_mode(app: &LightcraftApp) -> Option<WindowMode> { + let problem = app.library_problem.as_ref().filter(|p| !p.dismissed)?; + Some(if problem.chooser.is_some() { WindowMode::Chooser } else { WindowMode::Error }) +} + +/// Whether the open dialog is the launch list's own New Library name prompt. +/// +/// Any other dialog (Settings opened before Alt/Option created the chooser, for example) is not +/// owned by the launch list: the blocking window stays visible over it and keeps owning input, +/// instead of stepping aside for a dialog it did not open. +fn chooser_owns_dialog(app: &LightcraftApp) -> bool { + app.library_problem.as_ref().is_some_and(|p| p.chooser.is_some()) + && matches!( + app.ui.dialog.as_ref(), + Some(crate::state::Dialog::TextPrompt { command, .. }) if command == "app.newLibrary" + ) +} + +/// The window actually drawn this pass. A prompt suppresses it, and the launch list yields only to +/// the New Library name dialog it opened itself. +fn visible_mode(app: &LightcraftApp) -> Option<WindowMode> { + let mode = present_mode(app)?; + if crate::panels::notices::blocks_input(app) { + return None; + } + if mode == WindowMode::Chooser && chooser_owns_dialog(app) { + return None; + } + Some(mode) +} + +/// Whether the blocking library window is actually on screen over the rest of the UI this frame, +/// so a background dialog's own raw input handlers must stay still. +pub(crate) fn blocks_dialog_input(app: &LightcraftApp) -> bool { + visible_mode(app).is_some() +} + +/// A window drawn before its barrier saw it (a command late in a draw pass created it) must not +/// settle this pass: arm the transition so the next frame gets the shielded first draw. +fn note_first_draw(app: &mut LightcraftApp, mode: WindowMode) { + if app.library_window_input.shown != Some(mode) && !app.library_window_input.transition { + app.library_window_input.begin_transition(); + } +} + +/// Surrender egui's current keyboard focus, so a background field cannot receive text in the +/// window's first shielded pass. +fn clear_focus(ctx: &egui::Context) { + ctx.memory_mut(|memory| { + if let Some(id) = memory.focused() { + memory.surrender_focus(id); + } + }); +} + +/// Note a new blocking window before any panel or shortcut reads this pass's input. Its first +/// frame clears a background text field's focus and drops text, pointer, wheel, keys and +/// accessibility input. `keys_down` is cleared so no key is left held after the discarded pass; +/// touch End/Cancel still reach egui to clear its private touch state. Modifier and window-focus +/// changes also survive, as for a prompt. +pub(crate) fn prepare_ui_pass(app: &mut LightcraftApp, ctx: &egui::Context, batch_in_flight: bool) { + if ctx.current_pass_index() != 0 { + return; + } + // A pass 0 starts a new shield cycle; `shield_pass` records that its dedicated pass ran. + app.library_window_input.shielded = false; + let Some(mode) = visible_mode(app) else { + if app.library_problem.as_ref().is_none_or(|p| p.dismissed) { + app.library_window_input = WindowBarrier::default(); + } else if !app.library_window_input.transition { + // The window is present but a prompt or the dialog it opened hides it. The next pass + // that actually draws it must be shielded: while hidden, its controls are absent from + // the previous pass's widget snapshot, and egui's hit test would belong to the + // background. + app.library_window_input.begin_transition(); + } + return; + }; + if app.library_window_input.shown != Some(mode) { + app.library_window_input.begin_transition(); + } + if !app.library_window_input.transition { + return; + } + // A background text field may have kept or regained focus while the window was hidden by a + // prompt or dialog; the shielded first frame must not let it receive the host's text. + clear_focus(ctx); + if batch_in_flight && std::mem::take(&mut app.library_window_input.cancel_injected) { + // The library barrier below removes this pass's already-injected events before any panel + // sees them. Like the prompt barrier, the gesture that queued them must fail, never report + // a successful delivery of input that was discarded. + app.cancel_gestures_for_barrier(true, "a blocking library window appeared"); + } + ctx.stop_dragging(); + ctx.input_mut(|input| { + // The discarded pass must not leave a key held merely because its release arrived in the + // window's creation frame. + input.keys_down.clear(); + input.pointer = egui::PointerState::default(); + input.smooth_scroll_delta = egui::Vec2::ZERO; + input.events.retain(|event| { + matches!( + event, + egui::Event::ModifiersChanged(_) + | egui::Event::WindowFocused(_) + | egui::Event::Touch { phase: egui::TouchPhase::End | egui::TouchPhase::Cancel, .. } + ) + }); + }); +} + +/// Whether `draw_window` must render only the new blocking window for this first pass. +pub(crate) fn shield_pass(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { + let shield = ctx.current_pass_index() == 0 && app.library_window_input.transition && visible_mode(app).is_some(); + if shield { + app.library_window_input.shielded = true; + } + shield +} + +/// Reset the per-pass draw witness before any panel runs. `show` marks the window only when it +/// actually draws it; a prompt/dialog hiding the window must not inherit a previous pass's mark. +pub(crate) fn begin_draw(app: &mut LightcraftApp) { + app.library_window_input.drawn = None; +} + +/// A completed, nondiscarded pass has laid the window out. Only an actual draw after the shield +/// pass settles it; a window hidden by a prompt or by the dialog it opened, or one that appeared +/// midway through this pass (the banner's Open Library… button), keeps the transition armed so +/// the first pass that draws it again is shielded. +pub(crate) fn finish_ui_pass(app: &mut LightcraftApp, ctx: &egui::Context) { + if ctx.will_discard() { + return; + } + if let Some(mode) = visible_mode(app) { + if app.library_window_input.drawn == Some(mode) && (!app.library_window_input.transition || app.library_window_input.shielded) { + app.library_window_input.shown = Some(mode); + app.library_window_input.transition = false; + app.library_window_input.shielded = false; + app.library_window_input.cancel_injected = false; + } else if !app.library_window_input.transition { + app.library_window_input.begin_transition(); + } + } else if app.library_problem.as_ref().is_none_or(|p| p.dismissed) { + app.library_window_input = WindowBarrier::default(); + } else if !app.library_window_input.transition { + // A prompt appeared or changed during the draw and now hides the window. + app.library_window_input.begin_transition(); + } +} + +/// How long after the window appears holding Alt/Option still asks (egui time, seconds). The +/// modifier keys can't be read before the first frame, and macOS reports one held since before +/// launch only once it changes, so it is watched over the first frames. +pub const ALT_SECONDS: f64 = 2.0; + +/// What the desktop app opens at launch (issue #1290). +#[derive(Clone, Debug, PartialEq)] +pub enum Launch { + /// Open this library folder (`None`: there is nowhere to keep one; the problem window says + /// so). `alt_asks`: holding Alt/Option as the window appears offers the recent libraries. + Open { dir: Option<PathBuf>, alt_asks: bool }, + /// Open nothing yet: the window lists the recent libraries ([`LibraryProblem::choose`]). + Ask, +} + +/// What to open at launch: `--library` (`flag`), else `$LIGHTCRAFT_LIBRARY` (`env`), else with +/// *Ask me* the list, else the library last opened, else `default` (the default location). +/// `settings` is `None` without a settings file; `memory` (`--memory`) never asks. +pub fn launch_plan(memory: bool, flag: Option<PathBuf>, env: Option<PathBuf>, settings: Option<&AppSettings>, default: Option<PathBuf>) -> Launch { + if memory { + return Launch::Open { dir: None, alt_asks: false }; + } + if let Some(dir) = flag.or(env) { + return Launch::Open { dir: Some(dir), alt_asks: false }; + } + if settings.is_some_and(|s| s.at_launch == LaunchLibrary::Ask) { + return Launch::Ask; + } + let last = settings.map(|s| s.library_path.clone()).filter(|p| !p.is_empty()).map(PathBuf::from); + Launch::Open { dir: last.or(default), alt_asks: true } +} + +/// One library in the launch window's list. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RecentLibrary { + pub path: String, + /// When it was last opened (ISO 8601), if known. + pub opened: Option<String>, + /// Why it can't be opened (`None`: it can, or it is still being checked), as checked when + /// the window opened or when opening it failed. + pub unavailable: Option<String>, + /// Its check hasn't answered yet ([`RecentChecks`]). + pub checking: bool, + /// Its check has gone on for longer than [`SLOW_AFTER`] (the drive may be asleep or offline). + pub slow: bool, +} + +/// The launch window's list of recent libraries (issue #1290). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Chooser { + /// Newest first, as File ▸ Open Recent Library lists them. + pub libraries: Vec<RecentLibrary>, + /// The highlighted row (`None`: the list is empty). + pub selected: Option<usize>, + /// The person moved the highlight: answers arriving later don't move it again. + pub touched: bool, + /// Its rows' checks were started ([`logic`]). + pub asked: bool, + /// The library open behind the window (Alt/Option held at launch), by + /// [`lightcraft_engine::Session::library_generation`]: Esc keeps it. `None`: no library is open. + pub over: Option<u64>, +} + /// A library that failed to open (set by the host at launch). #[derive(Clone, Debug, Default, PartialEq)] pub struct LibraryProblem { @@ -24,25 +341,411 @@ pub struct LibraryProblem { /// Try Again reopens `path` as a library folder (`false` in the browser, whose storage isn't /// a folder: reloading the page tries again). pub can_retry: bool, + /// The window lists the recent libraries to choose from instead (issue #1290); `error` then + /// says why the last one tried didn't open. + pub chooser: Option<Chooser>, } impl LibraryProblem { + /// The window for a library at `path` that failed to open with `error`. pub fn new(path: impl Into<String>, error: impl Into<String>) -> LibraryProblem { LibraryProblem { path: path.into(), error: error.into(), can_retry: true, ..Default::default() } } + /// The window listing the recent libraries, each checked now without writing anything + /// ([`unavailable`]): one that is gone, isn't a LightCraft library any more or can't be read + /// is greyed out with the reason. The last library opened is selected, or else the first one + /// that can be opened. + #[cfg(test)] + pub(crate) fn choose(settings: &AppSettings) -> LibraryProblem { + let mut p = LibraryProblem::choose_later(settings); + if let Some(c) = p.chooser.as_mut() { + for l in &mut c.libraries { + l.unavailable = unavailable(&l.path).map(|u| u.text()); + l.checking = false; + } + c.selected = initial_selection(&c.libraries, &settings.library_path); + c.asked = true; + } + p + } + + /// [`LibraryProblem::choose`] without looking at any folder: every row is "Checking…" until + /// [`logic`] has the answers from a worker ([`RecentChecks`]). The last library opened is + /// selected meanwhile (or the first row); once every answer is in, the selection follows the + /// same rule as [`LibraryProblem::choose`] unless the person moved it. + pub fn choose_later(settings: &AppSettings) -> LibraryProblem { + // as many as File ▸ Open Recent Library keeps (a hand-edited settings file may hold more) + let libraries: Vec<RecentLibrary> = settings + .recent_libraries + .iter() + .take(crate::state::RECENT_LIBRARIES) + .map(|path| RecentLibrary { + path: path.clone(), + opened: settings.recent_opened.get(path).cloned(), + unavailable: None, + checking: true, + slow: false, + }) + .collect(); + let selected = libraries.iter().position(|l| l.path == settings.library_path).or((!libraries.is_empty()).then_some(0)); + LibraryProblem { chooser: Some(Chooser { libraries, selected, over: None, touched: false, asked: false }), ..Default::default() } + } + + /// The session promises to save nothing (the failed-library window or Continue Without + /// Saving): the host writes no settings meanwhile. The launch list is not such a session. + pub fn saves_nothing(&self) -> bool { + self.chooser.is_none() + } + /// `ui.inspect` → `libraryProblem`. pub fn to_json(&self) -> serde_json::Value { - json!({"path": self.path, "error": self.error, "temporarySession": self.dismissed, "pendingImport": self.pending_import.len()}) + let chooser = self.chooser.as_ref().map(|c| { + let libraries: Vec<serde_json::Value> = c + .libraries + .iter() + .map(|l| json!({"path": l.path, "lastOpened": l.opened, "available": l.unavailable.is_none(), "checking": l.checking, "reason": l.unavailable})) + .collect(); + json!({"libraries": libraries, "selected": c.selected, "libraryOpen": c.over.is_some()}) + }); + json!({"path": self.path, "error": self.error, "temporarySession": self.dismissed, "pendingImport": self.pending_import.len(), "chooser": chooser}) } } +/// The row first selected: the last library opened if it can be opened, else the first one that +/// can, else the first row. +fn initial_selection(libraries: &[RecentLibrary], last: &str) -> Option<usize> { + let can = |l: &RecentLibrary| l.unavailable.is_none(); + libraries.iter().position(|l| l.path == last && can(l)).or_else(|| libraries.iter().position(can)).or((!libraries.is_empty()).then_some(0)) +} + +/// Why a recent library can't be opened, found on a worker and put into words on the UI thread +/// (the interface language is per thread). +#[derive(Clone, Debug, PartialEq)] +pub enum Unavailable { + /// Nothing at that path (moved, renamed, or on a disconnected drive). + NotFound, + /// A file, not a folder. + NotAFolder, + /// The folder can't be listed (the system's reason). + Unreadable(String), + /// The folder holds no LightCraft library any more. + NoLibrary, + /// The library's catalog file can't be opened (the system's reason). + CatalogUnreadable(String), + /// The check itself failed (its worker stopped, or couldn't start). + CheckFailed(String), + /// Looking at the path failed without saying it is gone (a parent folder it may not read, a + /// share that timed out; the system's reason). + LookupFailed(String), +} + +impl Unavailable { + /// The folder isn't a library that is there to open (gone, a file, or not a library any more): + /// what greys out File ▸ Open Recent Library and makes `app.recentLibraries` say `exists: false`. + /// A folder that can't be listed, an unreadable catalog or a check that failed doesn't say the + /// library is gone (the launch window still shows why, and offers Open only for one it checked). + pub fn is_missing(&self) -> bool { + // a folder that refuses to list is there (permissions, macOS privacy): opening it says why + matches!(self, Unavailable::NotFound | Unavailable::NotAFolder | Unavailable::NoLibrary) + } + + /// In the interface language. + pub fn text(&self) -> String { + match self { + Unavailable::NotFound => crate::i18n::tr("Not found: moved, renamed or on a disconnected drive").to_string(), + Unavailable::NotAFolder => crate::i18n::tr("This is a file, not a library folder").to_string(), + Unavailable::Unreadable(e) => format!("{} {e}", crate::i18n::tr("This folder can't be read:")), + Unavailable::NoLibrary => crate::i18n::tr("There is no LightCraft library in this folder any more").to_string(), + Unavailable::CatalogUnreadable(e) => format!("{} {e}", crate::i18n::tr("The library's catalog can't be read:")), + Unavailable::CheckFailed(e) => e.clone(), + Unavailable::LookupFailed(e) => format!("{} {e}", crate::i18n::tr("This library couldn't be checked:")), + } + } +} + +/// How old an answer must be to be asked again: a library not found, on its own (a drive plugged +/// back in); any other, when the window comes back to the front (a library moved away meanwhile). +/// Only "not found" goes on a timer: looking again at the others would wake every external drive +/// and network share in the list over and over. +pub const RECHECK_AFTER: std::time::Duration = std::time::Duration::from_secs(30); +/// How long a row stays "Checking…" before it says the drive isn't answering (it can still be +/// opened: opening says why if it can't). +pub const SLOW_AFTER: std::time::Duration = std::time::Duration::from_secs(5); + +/// The activity stack's row for a check (English: the stack translates it). +const CHECK_LABEL: &str = "Checking recent libraries"; + +/// One path's answer and when it came. +#[derive(Clone, Debug)] +struct Answer { + why: Option<Unavailable>, + at: web_time::Instant, + /// The root UI frame that applied this answer ([`egui::Context::cumulative_frame_nr_for`]). + /// Scheduling must not ask about a check answer again in the frame that delivered it, which + /// also covers every layout pass of that frame; `None` for an answer no check worker made + /// (`opened`, or a check that couldn't start). + delivered_frame: Option<u64>, +} + +impl Answer { + /// An answer from a check worker, delivered in root UI frame `delivered_frame`. + fn from_check(why: Option<Unavailable>, delivered_frame: u64) -> Answer { + Answer { why, at: web_time::Instant::now(), delivered_frame: Some(delivered_frame) } + } + + /// An answer no check worker made, with no publication fence: it may be asked about again on + /// the next frame as before. + fn local(why: Option<Unavailable>) -> Answer { + Answer { why, at: web_time::Instant::now(), delivered_frame: None } + } +} + +/// Answers to "can this recent library be opened?", each found on a worker thread of its own (a +/// library on a network share whose server is gone, or on a sleeping disk, can take seconds or +/// never answer; the others don't wait for it). +pub struct RecentChecks { + known: std::collections::HashMap<String, Answer>, + /// Paths being checked, and since when. + pending: std::collections::HashMap<String, web_time::Instant>, + /// How one path is checked ([`unavailable`]; tests put a slow one here). + check: std::sync::Arc<dyn Fn(&str) -> Option<Unavailable> + Send + Sync>, + /// [`RECHECK_AFTER`] (shorter in tests). + recheck_after: std::time::Duration, + /// Whether the window had the focus on the last frame: answers are refreshed when it comes back. + pub(crate) focused: bool, +} + +impl Default for RecentChecks { + /// Nothing known yet, checking with [`unavailable`]. + fn default() -> Self { + RecentChecks { + known: Default::default(), + pending: Default::default(), + check: std::sync::Arc::new(unavailable), + recheck_after: RECHECK_AFTER, + focused: false, + } + } +} + +impl RecentChecks { + /// Why `path` can't be opened, if a check said so (`None`: it can, or it isn't known yet). + pub fn reason(&self, path: &str) -> Option<&Unavailable> { + self.known.get(path).and_then(|a| a.why.as_ref()) + } + + /// Whether the library at `path` is there: `Some(false)` when a check found it missing + /// ([`Unavailable::is_missing`]), `Some(true)` when one found it, `None` when no check could tell. + pub fn exists(&self, path: &str) -> Option<bool> { + match self.known.get(path)?.why.as_ref() { + None => Some(true), + Some(why) if why.is_missing() => Some(false), + Some(_) => None, + } + } + + /// Whether a check of `path` has answered. + pub fn is_known(&self, path: &str) -> bool { + self.known.contains_key(path) + } + + /// Whether `path` is being checked. + pub fn is_checking(&self, path: &str) -> bool { + self.pending.contains_key(path) + } + + /// Since when `path` has been checked, if it is. + fn checking_since(&self, path: &str) -> Option<web_time::Instant> { + self.pending.get(path).copied() + } + + /// A check is running. + pub fn is_running(&self) -> bool { + !self.pending.is_empty() + } + + /// Check paths with another function (tests). + pub fn with_check(check: impl Fn(&str) -> Option<Unavailable> + Send + Sync + 'static) -> RecentChecks { + RecentChecks { check: std::sync::Arc::new(check), ..Default::default() } + } + + /// Ask again about answers older than `after` when the window comes back (tests). + #[cfg(test)] + pub fn recheck_after(mut self, after: std::time::Duration) -> RecentChecks { + self.recheck_after = after; + self + } + + /// `path` was just opened (or made): it can be opened. + pub fn opened(&mut self, path: &str) { + self.known.insert(path.to_string(), Answer::local(None)); + } + + /// Opening `path` from the launch window failed. That says nothing about whether it is there + /// (another program may have it open): its answer is dropped, so it is checked again on the next + /// frame. The launch list keeps the open's error on that row for as long as it shows. + pub fn failed(&mut self, path: &str) { + self.known.remove(path); + } + + /// `path` left the list: forget its answer. + pub fn forget(&mut self, path: &str) { + self.known.remove(path); + } +} + +/// Check each of `paths` on a worker of its own (one that is being checked already is left to +/// finish). The activity stack lists each check while it runs (a quick one doesn't show: rows +/// appear after half a second); none can be stopped, as a stat that hangs can't be. +fn start_checks(app: &mut LightcraftApp, paths: Vec<String>) { + for path in paths { + if app.recent_checks.pending.contains_key(&path) { + continue; + } + // asked again about an answer it has (not after a failed open, which dropped it and says why + // on its row) + let recheck = app.recent_checks.known.contains_key(&path); + let check = app.recent_checks.check.clone(); + let p = path.clone(); + let started = crate::tasks::spawn(app, CHECK_LABEL, Some("library"), move || check(&p), { + let path = path.clone(); + move |app, ctx, why| { + app.recent_checks.pending.remove(&path); + let delivered_frame = ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT); + app.recent_checks.known.insert(path, Answer::from_check(why, delivered_frame)); + apply_answers(app); + ctx.request_repaint(); + } + }); + match started { + Ok(()) => { + // a row of the launch list waits for this answer again (a library not found looked for + // again, a window back to the front): without it, the row kept its old answer + if recheck + && let Some(l) = + app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()).and_then(|c| c.libraries.iter_mut().find(|l| l.path == path)) + { + l.checking = true; + l.slow = false; + l.unavailable = None; + } + app.recent_checks.pending.insert(path, web_time::Instant::now()); + } + // no worker thread: say so on the row, and don't try again every frame + Err(e) => { + log::warn!("{e}"); + app.recent_checks.known.insert(path, Answer::local(Some(Unavailable::CheckFailed(e)))); + apply_answers(app); + } + } + } +} + +/// Checks whose worker stopped without answering (it panicked: `tasks::poll` already said so) +/// end as failed, so the row and the menu don't wait for them forever. +fn reap_checks(app: &mut LightcraftApp) { + // (every check has the same label: when none is listed any more, the ones still pending died) + if app.recent_checks.pending.is_empty() || app.tasks.is_running(CHECK_LABEL) { + return; + } + let dead: Vec<String> = app.recent_checks.pending.keys().cloned().collect(); + for path in dead { + app.recent_checks.pending.remove(&path); + let why = Unavailable::CheckFailed(crate::i18n::tr("This library couldn't be checked").to_string()); + app.recent_checks.known.insert(path, Answer::local(Some(why))); + } + apply_answers(app); +} + +/// Put the answers in into the launch list; once none is missing, select as +/// [`LibraryProblem::choose`] does unless the person moved the highlight. +fn apply_answers(app: &mut LightcraftApp) { + let last = app.ui.settings.library_path.clone(); + let checks = &app.recent_checks; + let Some(c) = app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()) else { return }; + let checking_before = c.libraries.iter().any(|l| l.checking); + for l in &mut c.libraries { + if l.checking && !checks.is_checking(&l.path) && checks.is_known(&l.path) { + l.unavailable = checks.reason(&l.path).map(Unavailable::text); + l.checking = false; + } + } + if checking_before && !c.libraries.iter().any(|l| l.checking) && !c.touched { + c.selected = initial_selection(&c.libraries, &last); + } +} + +/// Why the library at `path` can't be opened (`None`: as far as can be told without opening it). +/// +/// Read-only: the folder and its catalog file are looked at, never locked or written (the list +/// may name libraries on other drives, network shares or sleeping disks). A library another +/// program has open is therefore found when Open is pressed: the open fails and the window says +/// who has it. Runs on a worker: the reason is put into words on the UI thread. +fn unavailable(path: &str) -> Option<Unavailable> { + let dir = Path::new(path); + // only a definite answer marks it missing: a lookup that fails otherwise (a parent folder it may + // not read, a share that timed out) is "couldn't check", and the library can still be opened + match std::fs::metadata(dir) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(Unavailable::NotFound), + Err(e) => return Some(Unavailable::LookupFailed(e.to_string())), + Ok(m) if !m.is_dir() => return Some(Unavailable::NotAFolder), + Ok(_) => {} + } + match std::fs::read_dir(dir) { + Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => return Some(Unavailable::Unreadable(e.to_string())), + Err(e) => return Some(Unavailable::LookupFailed(e.to_string())), + Ok(_) => {} + } + // opening would make a new, empty library in it + if !lightcraft_engine::library::is_library(dir) { + return Some(Unavailable::NoLibrary); + } + // the catalog the open reads first: the snapshot, else the log alone (opened to read, not read) + let snapshot = dir.join(lightcraft_catalog::journal::SNAPSHOT); + let catalog = if snapshot.is_file() { snapshot } else { dir.join(lightcraft_catalog::journal::LOG) }; + if let Err(e) = std::fs::File::open(&catalog) { + return Some(Unavailable::CatalogUnreadable(e.to_string())); + } + None +} + /// What the user chose. +#[derive(Clone, Copy, Debug, PartialEq)] enum Choice { Retry, Choose, Temporary, Quit, + /// The launch list: open the selected library. + Open, + /// The launch list: forget the selected library. + Remove, + /// The launch list: make a library (New Library…). + New, + /// The launch list over a library already open: close the window and keep it. + Keep, +} + +/// Whether dropped photos wait for a library ([`hold_dropped`]): none is open and the window +/// asking for one is up (not dismissed by Continue Without Saving). +pub fn holds_drops(app: &LightcraftApp) -> bool { + app.session.library.is_none() && app.library_problem.as_ref().is_some_and(|p| !p.dismissed) +} + +/// Photos dropped on the window while no library is open (the launch list, or the window of a +/// library that failed to open): kept with the command line's files and imported once a library +/// opens, instead of going into the session the next library replaces. Gives the photos back when +/// a library is open or Continue Without Saving was chosen. +pub fn hold_dropped(app: &mut LightcraftApp, ctx: &egui::Context, photos: Vec<String>) -> Option<Vec<String>> { + // called every frame, with nothing dropped most of the time: only a real drop is held (and toasted) + if photos.is_empty() || !holds_drops(app) { + return Some(photos); + } + let problem = app.library_problem.as_mut()?; + problem.pending_import.extend(photos); + app.toast(ctx, crate::i18n::tr("The photos are imported once a library is open")); + None } /// Open `path` (`None`: ask for a folder) through `app.openLibrary`; on success the problem is @@ -64,7 +767,21 @@ fn open(app: &mut LightcraftApp, path: Option<String>) { } } Err(e) => { + // a failed switch reopens the library that was open behind the launch list + let generation = app.session.library.as_ref().map(|_| app.session.library_generation()); + if let Some(path) = path.as_deref() { + app.recent_checks.failed(path); + } if let Some(p) = app.library_problem.as_mut() { + if let Some(c) = p.chooser.as_mut() { + if c.over.is_some() { + c.over = generation; + } + if let Some(l) = c.libraries.iter_mut().find(|l| path.as_deref() == Some(l.path.as_str())) { + l.unavailable = Some(e.clone()); + l.checking = false; + } + } if let Some(path) = path { p.path = path; } @@ -75,30 +792,208 @@ fn open(app: &mut LightcraftApp, path: Option<String>) { } } -/// Clear the problem once a library is open (e.g. through Settings → Open Library…). -pub fn logic(app: &mut LightcraftApp) { - if app.library_problem.is_some() && app.session.library.is_some() { - app.library_problem = None; +/// Clear the problem once a library is open (e.g. through Settings → Open Library…) — another +/// one than the launch list was opened over; offer the list when Alt/Option is held as the window +/// appears; and the list's keys. +pub fn logic(app: &mut LightcraftApp, ctx: &egui::Context) { + if let Some(p) = &app.library_problem + && app.session.library.is_some() + && p.chooser.as_ref().and_then(|c| c.over) != Some(app.session.library_generation()) + { + // files from the command line go into the library opened another way (New Library…, + // File ▸ Open Library…), as through the window's own buttons + let files = app.library_problem.take().map(|p| p.pending_import).unwrap_or_default(); + if !files.is_empty() + && let Err(e) = crate::import::start_paths(app, files) + { + log::warn!("import: {e}"); + } + } + let batch_in_flight = app.synthetic_in_flight; + alt_at_launch(app, ctx); + // Alt/Option can create the launch list here, after the frame's input was accepted. Drop + // background text/pointer/keys and give it a shield pass before its own key handler reads them. + // An already injected synthetic batch is dropped by that barrier and must fail its gesture. + prepare_ui_pass(app, ctx, batch_in_flight); + reap_checks(app); + // the launch list asks for fresh answers once + let listed: Option<Vec<String>> = + app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()).and_then(|c| { + (!std::mem::replace(&mut c.asked, true)).then(|| c.libraries.iter().filter(|l| l.checking).map(|l| l.path.clone()).collect()) + }); + if let Some(listed) = listed { + for path in &listed { + if !app.recent_checks.is_checking(path) { + app.recent_checks.forget(path); + } + } + start_checks(app, listed); + apply_answers(app); + } + // File ▸ Open Recent Library: paths never checked; libraries not found, every RECHECK_AFTER (a + // drive plugged back in; looking at a path that isn't there wakes nothing); the others when the + // window comes back to the front and their answer is that old. The list as shown (at most + // RECENT_LIBRARIES). + let focused = ctx.input(|i| i.focused); + let regained = focused && !std::mem::replace(&mut app.recent_checks.focused, focused); + let after = app.recent_checks.recheck_after; + // The frame whose UI phase is scheduling now. An answer applied during this frame (by + // `logic_background`'s `tasks::poll`, or a hidden logic tick just before the first visible UI) + // has this number too, so it is shown for at least this whole frame: scheduling it again in + // the same frame would erase it before any completed frame showed it, and a discarded layout + // pass must not change that. Unknown paths have no answer and still start immediately. + let frame = ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT); + let stale: Vec<String> = app + .ui + .settings + .recent_libraries + .iter() + .take(crate::state::RECENT_LIBRARIES) + .filter(|p| { + !app.recent_checks.is_checking(p) + && app.recent_checks.known.get(*p).is_none_or(|a| { + a.delivered_frame != Some(frame) && (regained || matches!(a.why, Some(Unavailable::NotFound))) && a.at.elapsed() > after + }) + }) + .cloned() + .collect(); + start_checks(app, stale); + if app.recent_checks.is_running() { + // rows still checking say so once it takes long + let checks = &app.recent_checks; + if let Some(c) = app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()) { + for l in c.libraries.iter_mut().filter(|l| l.checking) { + l.slow = checks.checking_since(&l.path).is_some_and(|t| t.elapsed() > SLOW_AFTER); + } + } + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } + // A quit prompt or settings notice sits above the launch list; its Escape/Return must not + // quit or switch libraries behind the prompt. + if !crate::panels::notices::blocks_input(app) { + chooser_keys(app, ctx); } } -/// The blocking window (until a choice is made). -pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { - let Some(problem) = app.library_problem.clone() else { return }; - if problem.dismissed { +/// Alt/Option held during the first [`ALT_SECONDS`] after the window appears opens the launch list +/// once, over the library that opened (opening another one closes it). Not while files from the +/// command line are importing into that library. +fn alt_at_launch(app: &mut LightcraftApp, ctx: &egui::Context) { + if !app.alt_asks_for_library { return; } - let t = Tokens::get(ctx); + let (alt, time) = ctx.input(|i| (i.modifiers.alt, i.time)); + if time > ALT_SECONDS || app.library_problem.is_some() { + app.alt_asks_for_library = false; + return; + } + if !alt { + return; + } + app.alt_asks_for_library = false; + if crate::panels::settings::can_switch_library(app).is_err() { + return; + } + let mut p = LibraryProblem::choose_later(&app.ui.settings); + if let Some(c) = p.chooser.as_mut() { + c.over = app.session.library.as_ref().map(|_| app.session.library_generation()); + } + app.library_problem = Some(p); + ctx.request_repaint(); +} + +/// The launch list on screen (not covered by the New Library name dialog it opened). +fn chooser_shown(app: &LightcraftApp) -> Option<&Chooser> { + let p = app.library_problem.as_ref().filter(|p| !p.dismissed)?; + p.chooser.as_ref().filter(|_| !chooser_owns_dialog(app)) +} + +/// ↑ / ↓ move the selection, Return opens it (unless a button has the keyboard focus: it acts +/// itself), Esc quits — or, over a library already open, keeps it. Taken before the shortcuts. +fn chooser_keys(app: &mut LightcraftApp, ctx: &egui::Context) { + let Some(c) = chooser_shown(app) else { return }; + let (n, selected, over) = (c.libraries.len(), c.selected, c.over.is_some()); + let focused = ctx.memory(|m| m.focused().is_some()); + use egui::{Key, Modifiers}; + let (up, down, enter, esc) = ctx.input_mut(|i| { + let up = i.consume_key(Modifiers::NONE, Key::ArrowUp); + let down = i.consume_key(Modifiers::NONE, Key::ArrowDown); + let enter = !focused && i.consume_key(Modifiers::NONE, Key::Enter); + (up, down, enter, i.consume_key(Modifiers::NONE, Key::Escape)) + }); + if (up || down) && n > 0 { + let at = match selected { + Some(s) if up => s.saturating_sub(1), + Some(s) => (s + 1).min(n - 1), + None => 0, + }; + select(app, at); + } + if enter { + act(app, Choice::Open); + } else if esc { + act(app, if over { Choice::Keep } else { Choice::Quit }); + } +} + +/// Highlight row `at` of the launch list. +fn select(app: &mut LightcraftApp, at: usize) { + if let Some(c) = app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()) + && at < c.libraries.len() + { + c.selected = Some(at); + c.touched = true; + } +} + +/// Dim everything behind the window; it swallows clicks, so nothing there can be used meanwhile. +/// The dim is `Foreground` and takes the modal layer: a `Middle` dialog such as Settings may be +/// open underneath, and without this the dialog's own modal layer would let its controls receive +/// clicks through the dim. Dialogs are drawn before this window, and a quit prompt or settings +/// notice suppresses this window entirely (`show` returns early), so neither is covered by it. +/// Pressing the dim raises its area, so each window is moved back above it after being shown. +fn dim(ctx: &egui::Context) { let screen = ctx.content_rect(); - egui::Area::new(egui::Id::new("library-problem-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(true).show(ctx, |ui| { + let dim = egui::Area::new(egui::Id::unique(DIM_ID)).order(egui::Order::Foreground).fixed_pos(screen.min).interactable(true).show(ctx, |ui| { // swallows clicks: nothing behind the window can be used meanwhile ui.allocate_rect(screen, egui::Sense::click_and_drag()); ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(160)); }); + // A bare interactable Area does not become the modal layer by itself. Without this, a + // Settings dialog opened before the library window can keep the modal layer and receive a + // control-channel press that the dim is meant to cover. + ctx.memory_mut(|memory| memory.set_modal_layer(dim.response.layer_id)); +} + +/// The blocking window (until a choice is made). `blocked` freezes the barrier of a quit prompt +/// or settings notice that was on screen when this frame began: the launch list/error window is +/// `Order::Foreground` too, so drawing it after the prompt could cover it and let the same +/// click or key act twice. It returns on the first pass after the prompt goes away. +pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { + if blocked || crate::panels::notices::blocks_input(app) { + return; + } + let Some(problem) = app.library_problem.clone() else { return }; + if problem.dismissed { + return; + } + if let Some(chooser) = &problem.chooser { + // its own New Library name dialog goes first; the list comes back after it. An unrelated + // dialog (Settings) does not hide the list: the blocking window stays above it. + if !chooser_owns_dialog(app) { + note_first_draw(app, WindowMode::Chooser); + show_chooser(app, ctx, &problem, chooser); + app.library_window_input.drawn = Some(WindowMode::Chooser); + } + return; + } + let t = Tokens::get(ctx); + note_first_draw(app, WindowMode::Error); + dim(ctx); let mut choice = None; let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(18, 14)); - egui::Window::new(crate::i18n::tr("Your library couldn't be opened")) - .id(egui::Id::new("library-problem")) + let shown = egui::Window::new(crate::i18n::tr("Your library couldn't be opened")) + .id(egui::Id::unique(ERROR_WINDOW_ID)) .order(egui::Order::Foreground) .collapsible(false) .resizable(false) @@ -128,7 +1023,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { let mut button = |ui: &mut egui::Ui, id: &str, label: &str, enabled: bool, c: Choice| { let r = ui.add_enabled(enabled, egui::Button::new(crate::i18n::tr(label)).min_size(vec2(0.0, 26.0))); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); if r.clicked() { choice = Some(c); } @@ -139,10 +1034,55 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { button(ui, "libraryQuit", "Quit", true, Choice::Quit); }); }); + if let Some(w) = &shown { + // A press on the dim raises its area; keep this window (and its own buttons) above it. + ctx.move_to_top(w.response.layer_id); + } + app.library_window_input.drawn = Some(WindowMode::Error); + if let Some(c) = choice { + act(app, c); + } +} + +/// Carry out `choice` (a button or key of either window). +fn act(app: &mut LightcraftApp, choice: Choice) { + let Some(problem) = app.library_problem.clone() else { return }; + let chosen = problem.chooser.as_ref().and_then(|c| c.selected.and_then(|i| c.libraries.get(i)).map(|l| (l.clone(), c.over))); match choice { - Some(Choice::Retry) => open(app, Some(problem.path)), - Some(Choice::Choose) => open(app, None), - Some(Choice::Temporary) => { + Choice::Retry => open(app, Some(problem.path)), + Choice::Choose => open(app, None), + Choice::Open => { + let Some((library, over)) = chosen.filter(|(l, _)| l.unavailable.is_none()) else { return }; + // the library already open behind the list: nothing to switch + let open_now = app.session.library.as_ref().filter(|l| l.on_disk).is_some_and(|l| l.dir == Path::new(&library.path)); + if over.is_some() && open_now { + app.library_problem = None; + } else { + open(app, Some(library.path)); + } + } + Choice::Remove => { + let Some((library, _)) = chosen else { return }; + crate::panels::settings::forget_library(&mut app.ui.settings, &library.path); + app.recent_checks.forget(&library.path); + if let Some(c) = app.library_problem.as_mut().and_then(|p| p.chooser.as_mut()) { + c.libraries.retain(|l| l.path != library.path); + c.selected = c.selected.map(|s| s.min(c.libraries.len().saturating_sub(1))).filter(|_| !c.libraries.is_empty()); + } + } + Choice::New => { + // asks for the name, then the place; the list shows again if that's cancelled + match app.run("app.newLibrary", json!({})) { + Ok(_) => {} + Err(e) => { + if let Some(p) = app.library_problem.as_mut() { + p.error = e; + } + } + } + } + Choice::Keep => app.library_problem = None, + Choice::Temporary => { if let Some(p) = app.library_problem.as_mut() { p.dismissed = true; } @@ -154,11 +1094,141 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { log::warn!("import: {e}"); } } - Some(Choice::Quit) => app.ui.quit = true, - None => {} + Choice::Quit => app.ui.quit = true, } } +/// The launch list (issue #1290): the recent libraries, greyed out with the reason when they +/// can't be opened, and Open / Open Another… / New Library… / Remove from List / Quit. +fn show_chooser(app: &mut LightcraftApp, ctx: &egui::Context, problem: &LibraryProblem, chooser: &Chooser) { + let t = Tokens::get(ctx); + dim(ctx); + let mut choice = None; + let mut clicked_row = None; + let can_pick = app.services.pick_folder.is_some(); + let open_now = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()); + let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(18, 14)); + let shown = egui::Window::new(crate::i18n::tr("Open a Library")) + .id(egui::Id::unique(CHOOSER_WINDOW_ID)) + .order(egui::Order::Foreground) + .collapsible(false) + .resizable(false) + .frame(frame) + .anchor(Align2::CENTER_CENTER, [0.0, 0.0]) + .default_width(520.0) + .show(ctx, |ui| { + // a fixed width: a wrapped label in an auto-sized, centred window would move it every frame + ui.set_width(500.0); + ui.spacing_mut().item_spacing.y = 8.0; + ui.label(RichText::new(crate::i18n::tr("Choose the library to open.")).color(t.text_label)); + if chooser.libraries.is_empty() { + let r = ui.label(RichText::new(crate::i18n::tr("No recent libraries. Open one from a folder, or make a new one.")).color(t.text_dim)); + register(ui, "indicator:noRecentLibraries", r.rect); + } + egui::ScrollArea::vertical().max_height(300.0).auto_shrink([false, true]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + for (i, library) in chooser.libraries.iter().enumerate() { + let r = recent_row(ui, &t, i, library, chooser.selected == Some(i), open_now.as_deref() == Some(Path::new(&library.path))); + if r.double_clicked() { + clicked_row = Some((i, true)); + } else if r.clicked() { + clicked_row = Some((i, false)); + } + } + }); + if !problem.error.is_empty() { + ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap()); + } + let selected = chooser.selected.and_then(|i| chooser.libraries.get(i)); + let mut button = |ui: &mut egui::Ui, id: &str, label: &str, enabled: bool, c: Choice| { + let r = ui.add_enabled(enabled, egui::Button::new(crate::i18n::tr(label)).min_size(vec2(0.0, 26.0))); + register(ui, format!("button:{id}"), r.rect); + if r.clicked() { + choice = Some(c); + } + }; + ui.horizontal(|ui| { + button(ui, "libraryForget", "Remove from List", selected.is_some(), Choice::Remove); + ui.label(RichText::new(crate::i18n::tr("The library itself stays where it is.")).size(11.0).color(t.text_dim)); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + button(ui, "libraryOpen", "Open", selected.is_some_and(|l| l.unavailable.is_none()), Choice::Open); + button(ui, "libraryOpenAnother", "Open Another…", can_pick, Choice::Choose); + button(ui, "libraryNew", "New Library…", can_pick, Choice::New); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + button(ui, "libraryQuit", "Quit", true, Choice::Quit); + }); + }); + }); + if let Some(w) = &shown { + // A press on the dim raises its area; keep the launch list above it. + ctx.move_to_top(w.response.layer_id); + } + if let Some((i, open)) = clicked_row { + select(app, i); + if open { + act(app, Choice::Open); + } + } + if let Some(c) = choice { + act(app, c); + } +} + +/// One row of the launch list: the library's name and when it was last opened, the folder it is +/// in, and why it can't be opened (then greyed out). Registered as `libraryRecent:<index>`. +fn recent_row(ui: &mut egui::Ui, t: &Tokens, i: usize, library: &RecentLibrary, selected: bool, open: bool) -> egui::Response { + let dir = Path::new(&library.path); + let name = crate::panels::settings::library_name(dir); + let parent = dir.parent().map(|p| p.display().to_string()).unwrap_or_default(); + let ok = library.unavailable.is_none(); + let (main, dim) = if ok { (t.text, t.text_dim) } else { (t.text_disabled, t.text_disabled) }; + let background = ui.painter().add(egui::Shape::Noop); + let inner = egui::Frame::NONE.inner_margin(egui::Margin::symmetric(8, 5)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.spacing_mut().item_spacing.y = 1.0; + ui.horizontal(|ui| { + ui.add(egui::Label::new(RichText::new(name).font(t.semibold(12.5)).color(main)).truncate().selectable(false)); + let when = if open { + Some(crate::i18n::tr("Open now").to_string()) + } else { + library + .opened + .as_deref() + .and_then(|iso| iso.get(..10)) + .map(|day| format!("{} {}", crate::i18n::tr("Last opened"), crate::i18n::date_group_label(day, false))) + }; + if let Some(when) = when { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(when).size(11.0).color(dim)).selectable(false)); + }); + } + }); + ui.add(egui::Label::new(RichText::new(parent).size(11.0).color(dim)).truncate().selectable(false)); + if let Some(why) = &library.unavailable { + ui.add(egui::Label::new(RichText::new(why).size(11.0).color(t.caution)).wrap().selectable(false)); + } else if library.checking { + let text = + if library.slow { crate::i18n::tr("Not answering yet: the drive may be asleep or offline") } else { crate::i18n::tr("Checking…") }; + ui.add(egui::Label::new(RichText::new(text).size(11.0).color(dim)).wrap().selectable(false)); + } + }); + let r = ui.interact(inner.response.rect, egui::Id::unique(("library-recent", i)), egui::Sense::click()); + register(ui, format!("libraryRecent:{i}"), r.rect); + let fill = if selected { + Some(t.tool_active) + } else if r.hovered() { + Some(t.hover) + } else { + None + }; + if let Some(fill) = fill { + ui.painter().set(background, egui::Shape::rect_filled(r.rect, 4.0, fill)); + } + r +} + /// The banner under the top bar while the session is temporary (Continue Without Saving). pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { if !app.library_problem.as_ref().is_some_and(|p| p.dismissed) { @@ -176,15 +1246,21 @@ pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { .font(t.semibold(12.5)) .color(t.canvas), ); - register(ui.ctx(), "indicator:temporarySession", r.rect); + register(ui, "indicator:temporarySession", r.rect); let b = ui.add( egui::Button::new(RichText::new(crate::i18n::tr("Open Library…")).color(t.canvas)).fill(egui::Color32::from_black_alpha(40)), ); - register(ui.ctx(), "button:libraryReopen", b.rect); + register(ui, "button:libraryReopen", b.rect); reopen = b.clicked(); }); }); if reopen && let Some(p) = app.library_problem.as_mut() { p.dismissed = false; + // The banner was drawn before the window; reopening it here would otherwise settle in this + // same pass, whose background already consumed its input. Shield the next frame's first + // actual window draw. + app.library_window_input.begin_transition(); + clear_focus(ui.ctx()); + ui.ctx().request_repaint(); } } diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rs index 6062d241c7..86f3796b9f 100644 --- a/crates/ui-egui/src/panels/mask_effects.rs +++ b/crates/ui-egui/src/panels/mask_effects.rs @@ -12,7 +12,7 @@ use serde_json::{Value, json}; use crate::LightcraftApp; use crate::state::Dialog; use crate::theme::Tokens; -use crate::widgets::register; +use crate::widgets::{register, register_response}; /// A slider's label in the effect lists (the colour tint's hue and saturation are one "Color"). pub fn field_label(k: &str) -> &'static str { @@ -123,7 +123,7 @@ struct MenuState { } fn state_id() -> egui::Id { - egui::Id::new("maskEffectMenuState") + egui::Id::unique("maskEffectMenuState") } /// The effects the menu lists for `query`: (section heading, effect name, its row widget id). @@ -223,7 +223,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); // (rows scrolled out of view can't be clicked) if ui.is_rect_visible(rect) { - register(ui.ctx(), widget.clone(), rect); + register(ui, widget.clone(), rect); } let lit = st.highlight == Some(i) || resp.hovered(); if lit { @@ -237,7 +237,12 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option let elided = g.elided; ui.painter().galley(rect.left_center() + vec2(18.0, -g.size().y / 2.0), g, t.text); if fav { - ui.painter().text(rect.right_center() - vec2(4.0, 0.0), egui::Align2::RIGHT_CENTER, "★", t.font(11.0), t.text_dim); + crate::rating::paint_star( + ui.painter(), + egui::Rect::from_center_size(rect.right_center() - vec2(10.0, 0.0), vec2(11.0, 11.0)), + true, + t.text_dim, + ); } if moved && st.highlight == Some(i) { resp.scroll_to_me(None); @@ -265,7 +270,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option ui.separator(); let item = |ui: &mut egui::Ui, id: &str, text: String, enabled: bool| { let r = ui.add_enabled(enabled, egui::Button::new(text).frame(false)); - register(ui.ctx(), id.to_string(), r.rect); + register(ui, id.to_string(), r.rect); r.clicked() }; if item(ui, "maskEffectMenu:reset", crate::i18n::tr("Reset Sliders").to_string(), true) { @@ -317,7 +322,7 @@ fn preview(app: &mut LightcraftApp, mask: &Mask, name: &str) { fn row_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, name: &str, fav: bool) { let run = |app: &mut LightcraftApp, ui: &mut egui::Ui, text: &str, cmd: &str, p: Value| { let r = ui.button(crate::i18n::tr(text)); - register(ui.ctx(), format!("maskEffectRow:{text}"), r.rect); + register(ui, format!("maskEffectRow:{text}"), r.rect); if r.clicked() { if let Err(e) = app.run(cmd, p) { app.toast_error(ui.ctx(), e); @@ -393,7 +398,7 @@ pub fn save_body( .width(ui.available_width() - 30.0) .show(ui); let pick = ui.small_button("…").on_hover_text(crate::i18n::tr("Choose a group")); - register(ui.ctx(), "button:effectGroupPick", pick.rect); + register(ui, "button:effectGroupPick", pick.rect); egui::Popup::menu(&pick).show(|ui| { for (g, _) in fx::menu_order(&app.session.mask_effects) { if ui.button(if g.is_empty() { crate::i18n::tr("None").to_string() } else { g.clone() }).clicked() { @@ -417,7 +422,7 @@ pub fn save_body( // the sliders this mask changes stand out; the others are dimmed let text = if changed.iter().any(|c| c == k) { text.color(t.text).strong() } else { text.color(t.text_dim) }; let r = cols[i % 2].checkbox(&mut on, text); - register(&r.ctx, format!("effectInclude:{k}"), r.rect); + register_response(format!("effectInclude:{k}"), r.rect, &r); if r.changed() { fields.retain(|f| f != k); if on { @@ -429,7 +434,7 @@ pub fn save_body( ui.horizontal(|ui| { for (id, text) in [("all", "All"), ("none", "None"), ("changed", "Changed Only")] { let b = ui.small_button(crate::i18n::tr(text)); - register(ui.ctx(), format!("effectInclude:{id}"), b.rect); + register(ui, format!("effectInclude:{id}"), b.rect); if b.clicked() { *fields = match id { "all" => list.iter().map(|k| k.to_string()).collect(), @@ -445,9 +450,9 @@ pub fn save_body( .size(11.0), ); let r = ui.checkbox(amount, crate::i18n::tr("Include Amount")); - register(ui.ctx(), "check:effectAmount", r.rect); + register(ui, "check:effectAmount", r.rect); let r = ui.checkbox(brush, crate::i18n::tr("Include brush size, feather and flow")); - register(ui.ctx(), "check:effectBrush", r.rect); + register(ui, "check:effectBrush", r.rect); enter } @@ -514,7 +519,7 @@ pub fn manage_body( egui::Label::new(egui::RichText::new(format!("{heading} ({})", list.len())).font(t.semibold(12.0)).color(t.text_label)) .sense(Sense::click()), ); - register(ui.ctx(), format!("effectGroup:{group}"), h.rect); + register(ui, format!("effectGroup:{group}"), h.rect); if h.clicked() { // a click on the heading selects the group *selected = list.iter().map(|e| e.name.clone()).collect(); @@ -522,10 +527,7 @@ pub fn manage_body( for e in list { let sel = selected.contains(&e.name); ui.horizontal(|ui| { - let star = ui.add(egui::Button::new(if e.favorite { "★" } else { "☆" }).frame(false)).on_hover_text(crate::i18n::tr("Favorite")); - if ui.is_rect_visible(star.rect) { - register(ui.ctx(), format!("effectStar:{}", e.name), star.rect); - } + let star = crate::rating::favorite_button(ui, format!("effectStar:{}", e.name), e.favorite, crate::i18n::tr("Favorite")); if star.clicked() { toggle_star = Some((e.name.clone(), !e.favorite)); } @@ -543,7 +545,7 @@ pub fn manage_body( } let (rect, r) = ui.allocate_exact_size(vec2(240.0, 22.0), Sense::click()); if ui.is_rect_visible(rect) { - register(ui.ctx(), format!("effectRow:{}", e.name), rect); + register(ui, format!("effectRow:{}", e.name), rect); } if sel { ui.painter().rect_filled(rect, 3.0, t.tool_active); @@ -601,14 +603,14 @@ pub fn manage_body( ); ui.horizontal(|ui| { let d = ui.button(crate::i18n::tr("Delete")); - register(ui.ctx(), "button:effectDeleteConfirm", d.rect); + register(ui, "button:effectDeleteConfirm", d.rect); if d.clicked() { let _ = app.run("mask.deleteEffect", json!({"names": selected.clone()})); selected.clear(); *confirm_delete = false; } let c = ui.button(crate::i18n::tr("Cancel")); - register(ui.ctx(), "button:effectDeleteCancel", c.rect); + register(ui, "button:effectDeleteCancel", c.rect); if c.clicked() { *confirm_delete = false; } @@ -618,7 +620,7 @@ pub fn manage_body( ui.horizontal_wrapped(|ui| { let button = |ui: &mut egui::Ui, id: &str, text: &str, enabled: bool| { let r = ui.add_enabled(enabled, egui::Button::new(crate::i18n::tr(text))); - register(ui.ctx(), format!("button:effect{id}"), r.rect); + register(ui, format!("button:effect{id}"), r.rect); r.clicked() }; if button(ui, "Apply", "Apply", one.is_some() && mask.is_some()) @@ -648,7 +650,7 @@ pub fn manage_body( let _ = app.run("mask.favoriteEffect", json!({"names": selected.clone(), "favorite": !all_fav})); } let g = ui.add_enabled(n > 0, egui::Button::new(crate::i18n::tr("Move to Group…"))); - register(ui.ctx(), "button:effectGroup", g.rect); + register(ui, "button:effectGroup", g.rect); egui::Popup::menu(&g).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { let names = selected.clone(); for (grp, _) in fx::menu_order(&app.session.mask_effects) { diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index b0371c422a..ce28482c46 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -118,7 +118,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { for (i, (kind, label, icon)) in tiles.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(tile, 52.0), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr(label)); - register(ui.ctx(), format!("maskNew:{kind}"), r); + register(ui, format!("maskNew:{kind}"), r); ui.painter().rect_filled(r, 4.0, if resp.hovered() { t.hover } else { t.inset }); paint(ui.painter(), Rect::from_center_size(r.center() - vec2(0.0, 7.0), vec2(20.0, 20.0)), *icon, t.text_label); // (cut short only in a panel too narrow for the label: the full name on hover) @@ -126,7 +126,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let g = one_line(ui.painter(), label, t.font(size), t.text_dim, tile - 2.0 * TILE_PAD); let elided = g.elided; let at = pos2(r.center().x, r.bottom() - 9.0) - g.size() / 2.0; - register(ui.ctx(), format!("maskNewLabel:{kind}"), Rect::from_min_size(at, g.size())); + register(ui, format!("maskNewLabel:{kind}"), Rect::from_min_size(at, g.size())); ui.painter().galley(at, g, t.text_dim); let resp = if elided { resp.on_hover_text(label) } else { resp }; if resp.clicked() { @@ -169,7 +169,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { }; if let Some(status) = status { ui.add_space(4.0); - ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr(status)).color(t.text_dim)).wrap()); + ui.horizontal_top(|ui| { + crate::progress::spinner(ui, 14.0); + ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr(status)).color(t.text_dim)).wrap()); + }); ui.ctx().request_repaint_after(std::time::Duration::from_millis(250)); } // the model download, while its dialog is closed @@ -177,11 +180,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if download.running && app.ui.dialog.is_none() { ui.add_space(4.0); ui.horizontal(|ui| { - let pct = if download.total > 0 { download.done as f64 / download.total as f64 } else { 0.0 }; - let r = ui.add( - egui::ProgressBar::new(pct as f32).desired_width(ui.available_width() - 70.0).text(format!("SAM 3: {} %", (pct * 100.0).floor())), - ); - register(ui.ctx(), "maskSamProgress", r.rect); + // the bar takes what the Details button leaves + let details = ui.spacing().interact_size.x + 30.0; + sam_download_bar(ui, download.done, download.total, (ui.available_width() - details).max(96.0)); if text_button(ui, "maskSamDetails", crate::i18n::tr("Details"), false).clicked() { app.offer_sam_download(None); } @@ -220,7 +221,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // inline rename: Enter (or leaving the field) commits, Escape cancels let rid = *rid; let r = ui.add(egui::TextEdit::singleline(name).desired_width(ui.available_width()).id_salt(("maskRename", rid))); - register(ui.ctx(), format!("maskRename:{rid}"), r.rect); + register(ui, format!("maskRename:{rid}"), r.rect); if !r.has_focus() && !r.lost_focus() { r.request_focus(); } @@ -237,7 +238,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click()); crate::widgets::announce_selected(&resp, m.name.clone(), Some(m.id) == app.session.active_mask); - register(ui.ctx(), format!("mask:{}", m.id), r); + register(ui, format!("mask:{}", m.id), r); ui.painter().rect_filled( r, 4.0, @@ -256,15 +257,15 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let g = one_line(ui.painter(), &m.name, t.font(13.0), color, r.width() - 32.0 - 32.0); let elided = g.elided; let at = pos2(r.left() + 32.0, r.center().y - g.size().y / 2.0); - register(ui.ctx(), format!("maskName:{}", m.id), Rect::from_min_size(at, g.size())); + register(ui, format!("maskName:{}", m.id), Rect::from_min_size(at, g.size())); ui.painter().galley(at, g, color); let resp = if elided { resp.on_hover_text(&m.name) } else { resp }; // show / hide on hover (and always while hidden) // (the pointer test, not `hovered`: over the eye, the row itself no longer counts as hovered) if ui.rect_contains_pointer(r) || !m.visible { let er = Rect::from_center_size(pos2(r.right() - 16.0, r.center().y), vec2(22.0, 22.0)); - register(ui.ctx(), format!("maskVisible:{}", m.id), er); - let eye = ui.interact(er, egui::Id::new(("maskVisible", m.id)), Sense::click()); + register(ui, format!("maskVisible:{}", m.id), er); + let eye = ui.interact(er, egui::Id::unique(("maskVisible", m.id)), Sense::click()); crate::widgets::announce_selected(&eye, crate::i18n::tr("Show mask"), m.visible); paint( ui.painter(), @@ -322,7 +323,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if let Some((_, _, name)) = app.ui.renaming_component.as_mut().filter(|(mid, k, _)| *mid == m.id && *k == i) { // inline rename: Enter (or leaving the field) commits, Escape cancels let r = ui.add(egui::TextEdit::singleline(name).desired_width(ui.available_width() - 30.0).id_salt(("compRename", m.id, i))); - register(ui.ctx(), format!("componentRename:{i}"), r.rect); + register(ui, format!("componentRename:{i}"), r.rect); if !r.has_focus() && !r.lost_focus() { r.request_focus(); } @@ -345,14 +346,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.add(egui::Label::new(text).truncate().sense(Sense::click())) }); let resp = resp.inner; - register(ui.ctx(), format!("component:{i}"), resp.rect); + register(ui, format!("component:{i}"), resp.rect); if resp.double_clicked() { app.ui.renaming_component = Some((m.id, i, label.clone())); } crate::widgets::context_menu(&resp, |ui| component_row_menu(app, ui, m.id, i, &label, m.components.len())); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let more = ui.small_button("…").on_hover_text(crate::i18n::tr("Component options")); - register(ui.ctx(), format!("button:componentMenu{i}"), more.rect); + register(ui, format!("button:componentMenu{i}"), more.rect); egui::Popup::menu(&more).show(|ui| component_row_menu(app, ui, m.id, i, &label, m.components.len())); }); }); @@ -473,7 +474,7 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { for c in OVERLAY_COLORS { let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click()); crate::widgets::announce(&resp, format!("{} #{:02x}{:02x}{:02x}", crate::i18n::tr("Overlay color"), c[0], c[1], c[2])); - register(ui.ctx(), format!("maskOverlayColor:{:02x}{:02x}{:02x}", c[0], c[1], c[2]), r); + register(ui, format!("maskOverlayColor:{:02x}{:02x}{:02x}", c[0], c[1], c[2]), r); ui.painter().rect_filled(r.shrink(2.0), 3.0, egui::Color32::from_rgb(c[0], c[1], c[2])); if app.ui.mask_overlay_color == c { ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, t.text), egui::StrokeKind::Inside); @@ -522,7 +523,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape let w = ui.available_width().min(240.0); let (rect, resp) = ui.allocate_exact_size(vec2(w, 18.0), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Select Luminance Range")); - register(ui.ctx(), format!("lumRange:{comp}"), rect); + register(ui, format!("lumRange:{comp}"), rect); let p = ui.painter(); // dark → light ramp, the selected span outlined let n = 24; @@ -589,7 +590,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape }); let mut map = app.ui.mask_overlay && app.ui.mask_overlay_mode == "colorOnBw"; let r = ui.checkbox(&mut map, crate::i18n::tr("Show Luminance Map")); - register(ui.ctx(), format!("check:lumMap{comp}"), r.rect); + register(ui, format!("check:lumMap{comp}"), r.rect); if r.changed() { // the luminance map: the photo in black & white with the selected range tinted if map { @@ -760,6 +761,28 @@ pub(crate) fn start_describe(app: &mut LightcraftApp, op: &str) { app.ui.describe = Some((op.to_string(), String::new())); } +/// The SAM model's download, `width` wide. The label is a percentage once the size is known and +/// just the model's name before, so the bar keeps its height and its accessible name. +pub(crate) fn sam_download_bar(ui: &mut egui::Ui, done: u64, total: u64, width: f32) -> egui::Response { + let fraction = crate::progress::fraction_of(done, total); + let label = match fraction { + Some(f) => format!("SAM 3: {} %", crate::progress::percent(f)), + None => "SAM 3".to_string(), + }; + crate::progress::Progress::new(fraction).label(label).width(width).widget("maskSamProgress").show(ui) +} + +/// Whether the segmenter has work (loading, analyzing, a request, a detail pass running or waiting +/// to start): nothing new starts then. +fn segmenter_working(analyzing: bool, busy: bool, detail_busy: bool, detail_due: bool) -> bool { + analyzing || busy || detail_busy || detail_due +} + +/// Enter in the Describe field is the Select button: it starts nothing while the segmenter works. +fn enter_submits(working: bool, lost_focus: bool, enter_pressed: bool) -> bool { + !working && lost_focus && enter_pressed +} + /// The Describe field: type what to select ("sky", "the red car") and press Return. fn describe_field(app: &mut LightcraftApp, ui: &mut egui::Ui, new_mask: bool) { let Some((op, mut text)) = app.ui.describe.clone() else { return }; @@ -777,7 +800,9 @@ fn describe_field(app: &mut LightcraftApp, ui: &mut egui::Ui, new_mask: bool) { let mut submit = false; // the (translated) Select button is placed first, at the right; the field takes what is left ui.allocate_ui_with_layout(vec2(ui.available_width(), 24.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { - if text_button(ui, "maskDescribeGo", crate::i18n::tr("Select"), false).clicked() { + let seg = &app.session.segmenter; + let working = segmenter_working(seg.analyzing(), seg.busy(), seg.detail_busy(), app.ui.detail_due.is_some()); + if crate::button::Button::new("Select").small().busy(working).widget("button:maskDescribeGo").show(ui).clicked() { submit = true; } let r = ui.add( @@ -785,11 +810,12 @@ fn describe_field(app: &mut LightcraftApp, ui: &mut egui::Ui, new_mask: bool) { .hint_text(crate::i18n::tr("e.g. sky · the red car · car, road")) .desired_width(ui.available_width()), ); - register(ui.ctx(), "maskDescribe", r.rect); + register(ui, "maskDescribe", r.rect); if !r.has_focus() && !r.lost_focus() && text.is_empty() { r.request_focus(); } - if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + // Enter is the Select button: nothing starts while the segmenter is working + if enter_submits(working, r.lost_focus(), ui.input(|i| i.key_pressed(egui::Key::Enter))) { submit = true; } }); @@ -814,12 +840,12 @@ fn describe_field(app: &mut LightcraftApp, ui: &mut egui::Ui, new_mask: bool) { fn component_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, op: &str) { let b = ui.button(crate::i18n::tr("Object")); - register(ui.ctx(), format!("maskComp:{op}:object"), b.rect); + register(ui, format!("maskComp:{op}:object"), b.rect); if b.clicked() { start_object(app, ui.ctx(), op); } let b = ui.button(crate::i18n::tr("Describe…")); - register(ui.ctx(), format!("maskComp:{op}:prompt"), b.rect); + register(ui, format!("maskComp:{op}:prompt"), b.rect); if b.clicked() { start_describe(app, op); } @@ -836,7 +862,7 @@ fn component_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, op: &str) { continue; } let b = ui.button(menu_label(label)); - register(ui.ctx(), format!("maskComp:{op}:{kind}"), b.rect); + register(ui, format!("maskComp:{op}:{kind}"), b.rect); if b.clicked() { if kind == "brush" { let _ = app.run("tool.brush", json!({"op": op})); @@ -898,22 +924,25 @@ mod tests { use super::*; #[test] - fn masking_context_actions_use_catalog_translations() { - let saved = crate::i18n::language(); - crate::i18n::set_language(crate::i18n::Locale::Fr); - for (english, translated) in [ - ("Duplicate Mask", "Dupliquer le masque"), - ("Invert Mask", "Inverser le masque"), - ("Hide Mask", "Masquer le masque"), - ("Move Up", "Monter"), - ("Brush", "Pinceau"), - ("Luminance Range", "Plage de luminance"), - ] { - assert_eq!(menu_label(english), translated, "{english}"); - } - // An arbitrary user name has no catalog entry and is left unchanged. - assert_eq!(menu_label("My custom mask"), "My custom mask"); - crate::i18n::set_language(saved); + fn a_detail_pass_counts_as_the_segmenter_working() { + assert!(segmenter_working(false, false, true, false)); + assert!(segmenter_working(true, false, false, false)); + assert!(segmenter_working(false, true, false, false)); + assert!(!segmenter_working(false, false, false, false)); + } + + #[test] + fn a_pending_detail_pass_counts_as_the_segmenter_working() { + // a new prompt finishing before it starts would replace its target, and that mask never refines + assert!(segmenter_working(false, false, false, true)); + } + + #[test] + fn enter_in_the_describe_field_starts_nothing_while_the_segmenter_works() { + assert!(enter_submits(false, true, true)); + assert!(!enter_submits(true, true, true)); + assert!(!enter_submits(false, false, true)); + assert!(!enter_submits(false, true, false)); } /// The grid keeps four 52 pt tiles when the labels fit, and gives a long (translated) label diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 2fcb36663c..e3300e04f1 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -13,6 +13,7 @@ pub mod empty_library; pub mod faces; pub mod filterbar; pub mod grid; +pub mod histogram; pub mod keymap; pub mod keyword_list; pub mod keywording; @@ -28,6 +29,7 @@ pub mod presets; pub mod profiles; pub mod right; pub mod rules_editor; +pub mod rules_move; pub mod second; pub mod settings; pub mod slide_layout; @@ -59,13 +61,16 @@ pub fn resizable_side( reserve: f32, add: impl FnOnce(&mut egui::Ui), ) -> Option<f32> { - let pid = egui::Id::new(id); + // `Panel::new` stores `IdSalt::new(id)`; the panel's persisted key is + // `parent_ui.scope_id().with_salt(that_salt)`, which is exactly `scope_id().with(id)`. + // (Passing an already-built `Id` through `Panel::left` would salt it a second time.) + let pid = ui.scope_id().with(id); ui.ctx().data_mut(|d| d.remove::<egui::containers::panel::PanelState>(pid)); let avail = ui.available_rect_before_wrap(); let max = (avail.width() - reserve - crate::state::MIN_PHOTO_WIDTH).clamp(limits.min, limits.max); - let panel = if left { egui::Panel::left(pid) } else { egui::Panel::right(pid) }; + let panel = if left { egui::Panel::left(id) } else { egui::Panel::right(id) }; let r = panel.frame(frame).resizable(true).size_range(limits.min..=max).default_size(limits.clamp(width).min(max)).show(ui, add); - crate::widgets::register(ui.ctx(), format!("panel:{id}"), r.response.rect); + crate::widgets::register(ui, format!("panel:{id}"), r.response.rect); // egui names the edge's drag widget `<panel id>.with("__resize")`; the width is measured from // the panel's fixed edge to the pointer (contents wider than the panel don't count) if !ui.ctx().is_being_dragged(pid.with("__resize")) { @@ -78,7 +83,7 @@ pub fn resizable_side( /// The HUD toast at the bottom centre of the canvas. pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) { - let now = ctx.input(|i| i.time); + let now = app.tick_now(); let Some((text, until, label)) = app.ui.toast.clone() else { return }; if now > until { app.ui.toast = None; @@ -87,7 +92,7 @@ pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(canvas) = app.canvas_rect else { return }; let t = Tokens::get(ctx); let fade = ((until - now) / 0.25).clamp(0.0, 1.0) as f32; - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("toast"))); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("toast"))); // long messages (a save warning, the web build's notices) wrap within the canvas let wrap = (canvas.width() - 80.0).clamp(200.0, 720.0); let (background, foreground) = label.map(crate::theme::label_toast_colors).unwrap_or((egui::Color32::from_black_alpha(200), t.text)); @@ -168,7 +173,7 @@ pub fn empty_state(ui: &mut egui::Ui, rect: Rect, title: &str, body: &str, actio let button = if i == 0 { egui::Button::new(label.color(egui::Color32::WHITE)).fill(t.accent) } else { egui::Button::new(label.color(t.text)) }; let resp = ui.put(r, button); - crate::widgets::register(ui.ctx(), a.widget, resp.rect); + crate::widgets::register(ui, a.widget, resp.rect); if resp.clicked() { clicked = Some(a.command); } diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rs index 016323e95c..4dbbc1fd9f 100644 --- a/crates/ui-egui/src/panels/notices.rs +++ b/crates/ui-egui/src/panels/notices.rs @@ -5,7 +5,7 @@ use egui::{Align2, RichText, vec2}; use crate::theme::Tokens; -use crate::widgets::register; +use crate::widgets::WidgetHit; use crate::{LightcraftApp, QuitPrompt}; /// Collect the library's settings-file warnings (each is shown once), and the no-GPU notice once the GPU device has @@ -82,6 +82,7 @@ pub fn may_close(app: &mut LightcraftApp) -> bool { } } +#[derive(Clone, Copy, PartialEq, Eq)] enum Choice { Retry, QuitAnyway, @@ -89,17 +90,387 @@ enum Choice { Ok, } -fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&str, &str, Choice)]) -> Option<usize> { +/// The prompt (quit or settings notice) that owns input this frame, if any. +/// +/// The dim area is `Order::Foreground`, so a settled egui pass routes pointer input to it before +/// the main view or a `Middle` dialog. The control channel and raw keyboard/event handlers do not +/// go through that hit test, however: they must consult this explicit barrier as well. +pub(crate) fn prompt_layer(app: &LightcraftApp) -> Option<egui::LayerId> { + let id = match (&app.quit_prompt, app.notices.is_empty()) { + (Some(QuitPrompt::Tasks(_)), _) => "quit-tasks", + (Some(QuitPrompt::Unsaved(_)), _) => "quit-unsaved", + (None, false) => "settings-notice", + (None, true) => return None, + }; + Some(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique(id))) +} + +/// Whether a prompt is on screen and owns all pointer and keyboard input. +pub fn blocks_input(app: &LightcraftApp) -> bool { + prompt_layer(app).is_some() +} + +/// Whether a registered automation target may receive input. While a prompt is up only its own +/// Foreground window is interactive; the same barrier must hold before the first prompt layout +/// settles, when egui has not yet made the new areas interactable. +pub(crate) fn allows_target(app: &LightcraftApp, hit: Option<WidgetHit>) -> bool { + match prompt_layer(app) { + None => true, + Some(layer) => hit.is_some_and(|hit| hit.layer_id == layer), + } +} + +/// Identity of the prompt whose focus we track. A queued settings notice is a different prompt +/// from the one before it even though both use the same layer and id. +#[derive(Clone, Debug, PartialEq, Eq)] +struct PromptKey { + layer: egui::LayerId, + text: String, + queue_len: usize, +} + +/// Identity of the prompt currently owning input: its layer, text and, for the settings-notice +/// queue, the number of notices remaining, including the one shown. `None` when no prompt is up. +fn prompt_key(app: &LightcraftApp) -> Option<PromptKey> { + let (layer, text, queue_len) = match (&app.quit_prompt, app.notices.first()) { + (Some(prompt), _) => (prompt_layer(app)?, prompt.text().to_string(), 0), + (None, Some(text)) => (prompt_layer(app)?, text.clone(), app.notices.len()), + (None, None) => return None, + }; + Some(PromptKey { layer, text, queue_len }) +} + +/// The prompt's keyboard/focus state, isolated from the still-drawn background. +/// +/// The first host frame of a new prompt is a shielding pass: pointer/touch/key/accessibility input +/// is removed before panels are drawn, and the frame is discarded so a second pass can lay out the +/// new `Area` without any input. From then on this state routes only the prompt's own keys and +/// AccessKit actions; everything else is dropped before egui or the panels can see it. +#[derive(Default)] +pub(crate) struct PromptInput { + key: Option<PromptKey>, + /// The prompt has completed a layout pass; its `Area`s are interactable and its button ids are + /// known. Before this, input must not reach it or the panels under it. + laid_out: bool, + /// The next `pass 0` is the shielding pass for a newly shown prompt. + transition: bool, + /// Focused button index; `focus_set` distinguishes "not chosen yet" from index 0. + focus: usize, + focus_set: bool, + /// Enter/Space or an AccessKit Click on a prompt button. + activate: Option<usize>, + /// Escape (safe cancel). + cancel: bool, + /// Actual egui response ids of the prompt's buttons from its latest draw. + button_ids: Vec<(String, egui::Id)>, + /// Pointer state saved before the background draws. Restored only while the prompt itself is + /// drawn (egui's `Response::clicked` needs `pointer_events`), then hidden again for the + /// dialogs and overlays drawn after it. + pointer: Option<egui::PointerState>, +} + +impl PromptInput { + /// Reset the prompt input state for `key`, discarding layout, focus, button ids and pending + /// activation. A present key arms the shield transition; `None` leaves input unowned. + fn reset_to(&mut self, key: Option<PromptKey>) { + let transition = key.is_some(); + self.key = key; + self.laid_out = false; + self.transition = transition; + self.focus = 0; + self.focus_set = false; + self.activate = None; + self.cancel = false; + self.button_ids.clear(); + self.pointer = None; + } + + /// The index of the prompt button whose real egui id matches AccessKit's `node`, if any. + fn button_index(&self, accesskit_node: egui::accesskit::NodeId) -> Option<usize> { + self.button_ids.iter().position(|(_, id)| id.accesskit_id() == accesskit_node) + } +} + +/// Surrender egui's current keyboard focus before a chosen prompt button disappears. +fn clear_prompt_focus(ctx: &egui::Context) { + ctx.memory_mut(|memory| { + if let Some(id) = memory.focused() { + memory.surrender_focus(id); + } + }); +} + +/// Whether a key press belongs to the prompt: Tab (optionally with Shift) or unmodified Enter, +/// Space or Escape. +fn prompt_key_allowed(key: egui::Key, modifiers: egui::Modifiers) -> bool { + match key { + egui::Key::Tab => modifiers.is_none() || modifiers.shift_only(), + egui::Key::Enter | egui::Key::Space | egui::Key::Escape => modifiers.is_none(), + _ => false, + } +} + +/// Whether an AccessKit action targets a prompt button on the root tree and is a Focus or Click +/// request. +fn prompt_accesskit_allowed(request: &egui::accesskit::ActionRequest, ids: &[(String, egui::Id)]) -> bool { + request.target_tree == egui::accesskit::TreeId::ROOT + && ids.iter().any(|(_, id)| id.accesskit_id() == request.target_node) + && matches!(request.action, egui::accesskit::Action::Focus | egui::accesskit::Action::Click) +} + +/// Drop host and synthetic input that the background must not receive while a prompt is up. +/// +/// Key releases and modifier changes always survive: egui updates `keys_down` from them in +/// `begin_pass`, so dropping a release would leave a key held after the prompt goes away. Pointer +/// and accessibility input is kept only once the prompt's first layout has settled. Wheel/zoom/ +/// rotate/text/clipboard input has no prompt meaning and is always removed. A touch Start/Move is +/// dropped while the prompt is open; End/Cancel always stays, +/// including the creation/transition frames, because egui's private `touch_states` tracks the +/// finger separately and dropping the release would leave it pressed after the prompt goes away. +fn filter_prompt_events(app: &LightcraftApp, raw: &mut egui::RawInput) { + raw.events.retain(|event| prompt_allows_event(app, event)); +} + +/// Whether `event` is the release half of a touch gesture. Its state lives in egui's private +/// `touch_states`, outside the `PointerState` that the prompt's cleanup resets, so it must survive +/// even before the prompt's first layout has settled. +fn touch_release(event: &egui::Event) -> bool { + matches!(event, egui::Event::Touch { phase: egui::TouchPhase::End | egui::TouchPhase::Cancel, .. }) +} + +/// Whether an input event may reach egui while a prompt is up. This is the single rule used both +/// for host input before `begin_pass` and for a synthetic batch after `raw_input_hook`; the control +/// channel can therefore reject the exact gestures that the prompt barrier would drop, while an +/// allowed prompt key, pointer action or targeted AccessKit action is still delivered. +pub(crate) fn prompt_allows_event(app: &LightcraftApp, event: &egui::Event) -> bool { + if app.notice_input.key.is_none() { + return true; + } + let laid_out = app.notice_input.laid_out; + let ids = &app.notice_input.button_ids; + match event { + // Key releases and modifier/window-focus changes always survive: egui updates `keys_down` + // from them in `begin_pass`, so dropping a release would leave a key held afterwards. + egui::Event::Key { pressed: false, .. } | egui::Event::ModifiersChanged(_) | egui::Event::WindowFocused(_) => true, + egui::Event::Key { key, pressed: true, modifiers, .. } => laid_out && prompt_key_allowed(*key, *modifiers), + egui::Event::AccessKitActionRequest(request) => laid_out && prompt_accesskit_allowed(request, ids), + egui::Event::Text(_) + | egui::Event::Ime(_) + | egui::Event::Cut + | egui::Event::Copy + | egui::Event::Paste(_) + | egui::Event::PasteImage(_) + | egui::Event::MiddleClickPaste { .. } + | egui::Event::MouseWheel { .. } + | egui::Event::Zoom(_) + | egui::Event::Rotate(_) => false, + // Pointer input at a settled prompt belongs to its backdrop or buttons. A new touch + // gesture does not, but its End/Cancel must still clear egui's private touch state even + // in the prompt's creation/transition frames. + egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::PointerGone => laid_out, + touch @ egui::Event::Touch { .. } if touch_release(touch) => true, + egui::Event::Touch { .. } => false, + _ => true, + } +} + +/// Restore the pointer state saved for the prompt just before it is drawn. The background has +/// already drawn with no pointer; egui's `Response::clicked` still needs the pass's pointer events +/// to turn the interaction snapshot into a click on a prompt button. +pub(crate) fn restore_prompt_pointer(app: &LightcraftApp, ctx: &egui::Context) { + if let Some(pointer) = &app.notice_input.pointer { + ctx.input_mut(|input| input.pointer = pointer.clone()); + } +} + +/// Hide pointer state again after the prompt has drawn, so a dialog or overlay drawn later in the +/// same pass cannot act on the same release that dismissed the prompt. +pub(crate) fn hide_background_pointer(ctx: &egui::Context) { + ctx.input_mut(|input| { + input.pointer = egui::PointerState::default(); + input.smooth_scroll_delta = egui::Vec2::ZERO; + }); + ctx.stop_dragging(); +} + +/// Apply the prompt barrier after synthetic events have been appended to `raw`. +pub(crate) fn filter_raw_input(app: &LightcraftApp, raw: &mut egui::RawInput) { + filter_prompt_events(app, raw); +} + +/// Note a prompt transition before egui sees the host input. Returns true when this host frame +/// first sees a new prompt (its synthetic gestures must be canceled and its pointer state reset). +pub(crate) fn prepare_raw_input(app: &mut LightcraftApp, ctx: &egui::Context, raw: &mut egui::RawInput) -> bool { + let current = prompt_key(app); + let started = current.is_some() && app.notice_input.key != current; + if app.notice_input.key != current { + app.notice_input.reset_to(current); + clear_prompt_focus(ctx); + } + filter_prompt_events(app, raw); + started +} + +/// Apply the same barrier to the live input after `begin_pass`. A prompt can be created by this +/// frame's logic after `raw_input_hook` already ran; this captures its keys before panels read +/// them, drops the rest, and reports whether the prompt was first discovered here (so its +/// pre-existing gesture queue must be canceled). The draw pass itself uses [`shield_pass`]. +pub(crate) fn prepare_ui_pass(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { + let current = prompt_key(app); + let has_prompt = current.is_some(); + let started = has_prompt && app.notice_input.key != current; + if app.notice_input.key != current { + app.notice_input.reset_to(current); + clear_prompt_focus(ctx); + } + if !has_prompt { + return false; + } + let shield = ctx.current_pass_index() == 0 && app.notice_input.transition; + let laid_out = app.notice_input.laid_out && !shield; + if laid_out { + // A screen reader's Focus/Click can target only a button whose actual response id we + // recorded in a completed prompt pass. Tab/Shift+Tab and Enter/Space/Escape are handled + // here too, so no background panel sees a key that belongs to the prompt. + let events = ctx.input(|input| input.events.clone()); + for event in &events { + match event { + egui::Event::Key { key, pressed: true, modifiers, .. } if prompt_key_allowed(*key, *modifiers) => match key { + egui::Key::Tab => { + let len = app.notice_input.button_ids.len(); + if len > 0 { + app.notice_input.focus_set = true; + app.notice_input.focus = if modifiers.shift_only() { + app.notice_input.focus.checked_add(len - 1).map_or(0, |i| i % len) + } else { + app.notice_input.focus.checked_add(1).map_or(0, |i| i % len) + }; + } + } + egui::Key::Enter | egui::Key::Space => { + app.notice_input.focus_set = true; + app.notice_input.activate = Some(app.notice_input.focus); + } + egui::Key::Escape => app.notice_input.cancel = true, + _ => {} + }, + egui::Event::AccessKitActionRequest(request) => { + if let Some(index) = app.notice_input.button_index(request.target_node) { + app.notice_input.focus_set = true; + app.notice_input.focus = index; + if request.action == egui::accesskit::Action::Click { + app.notice_input.activate = Some(index); + } + } + } + _ => {} + } + } + } + if laid_out { + app.notice_input.pointer = Some(ctx.input(|input| input.pointer.clone())); + } + ctx.input_mut(|input| { + if shield || !laid_out { + // The pass is discarded. Clear held keys too: the background must not keep a key down + // merely because its release arrived in the prompt's creation frame. + input.keys_down.clear(); + } + // The interaction snapshot was computed at begin_pass, before this reset: a prompt + // button's `Response::clicked` still reflects this pass's click. Removing the pointer from + // the live input stops panels that read `ctx.input().pointer` directly from starting a + // drag, scrolling or completing a click underneath the prompt. + input.pointer = egui::PointerState::default(); + input.smooth_scroll_delta = egui::Vec2::ZERO; + input.events.retain(|event| match event { + egui::Event::ModifiersChanged(_) | egui::Event::WindowFocused(_) => true, + egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Ime(_) => false, + egui::Event::Cut + | egui::Event::Copy + | egui::Event::Paste(_) + | egui::Event::PasteImage(_) + | egui::Event::MiddleClickPaste { .. } + | egui::Event::MouseWheel { .. } + | egui::Event::Zoom(_) + | egui::Event::Rotate(_) => false, + // The allowed Focus/Click was already dispatched above to the prompt's own button; + // dropping every AccessKit request here leaves no residual for a covered panel to act + // on in this pass (including a request that targeted a background node). + egui::Event::AccessKitActionRequest(_) => false, + egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::PointerGone => false, + // A touch End/Cancel must reach egui even in this creation pass; Start/Move is + // background input like a new pointer gesture. + touch @ egui::Event::Touch { .. } if touch_release(touch) => true, + egui::Event::Touch { .. } => false, + _ => true, + }); + }); + ctx.stop_dragging(); + started +} + +/// Whether `draw_window` must render only the new prompt for this first pass. The second pass +/// (after the discard) draws the whole window with empty raw input, so the new prompt's first +/// frame cannot activate a panel underneath it. +pub(crate) fn shield_pass(app: &LightcraftApp, ctx: &egui::Context) -> bool { + ctx.current_pass_index() == 0 && app.notice_input.transition && prompt_key(app).is_some() +} + +/// A completed, nondiscarded pass has laid out and focused the prompt: input may reach it from the +/// next host frame. A changed/dismissed prompt is reset here as well, so a queued next notice is +/// treated as a new transition. +pub(crate) fn finish_ui_pass(app: &mut LightcraftApp, ctx: &egui::Context) { + if ctx.will_discard() { + return; + } + let current = prompt_key(app); + if app.notice_input.key != current { + // A prompt can change during the draw itself (Tasks -> Unsaved, or OK -> next notice). + // Leave it in its transition state so the next host frame shields the new prompt too. + app.notice_input.reset_to(current); + return; + } + if current.is_some() { + app.notice_input.laid_out = true; + app.notice_input.transition = false; + } +} + +/// Draw one modal prompt and return the index of the chosen button. The dim takes the modal +/// layer and a sizing pass is discarded so the first interactive pass has settled geometry; +/// `input` keeps focus on the safe Cancel/OK button unless a keyboard or AccessKit choice arrives. +fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&str, &str, Choice)], input: &mut PromptInput) -> Option<usize> { let t = Tokens::get(ctx); let screen = ctx.content_rect(); - egui::Area::new(egui::Id::new((id, "dim"))).order(egui::Order::Middle).fixed_pos(screen.min).show(ctx, |ui| { + let last = buttons.len().checked_sub(1)?; + let cancel_index = buttons.iter().position(|(_, _, choice)| matches!(choice, Choice::Cancel | Choice::Ok)).unwrap_or(last); + if !input.focus_set { + input.focus = cancel_index; + input.focus_set = true; + } + input.focus = input.focus.min(last); + let focus = input.focus; + let manual = if std::mem::take(&mut input.cancel) { Some(cancel_index) } else { input.activate.take().filter(|index| *index <= last) }; + // The backdrop must cover modal Middle-order dialogs as well as the main view. + let dim = egui::Area::new(egui::Id::unique((id, "dim"))).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { + // The first layout of a newly shown Area is a sizing pass: egui keeps it invisible and + // `interactable = false`. A release injected before the next host frame would then bypass + // the layer check and reach the widget below. Finish the real hit area in this same frame. + if ui.is_sizing_pass() { + ctx.request_discard("notice dim: settle the modal hit area before input"); + } ui.allocate_rect(screen, egui::Sense::click_and_drag()); ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140)); }); - let mut chosen = None; + // The dim (with its full-screen hit area) is the modal scope; the prompt window below is moved + // above it. Everything below the dim, including a Middle-order Settings dialog, is then + // outside egui's modal layer and loses keyboard focus registration as well as pointer hits. + ctx.memory_mut(|memory| memory.set_modal_layer(dim.response.layer_id)); + let mut chosen = manual; + let mut seen = Vec::with_capacity(buttons.len()); let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(18, 14)); - egui::Window::new(crate::i18n::tr(title)) - .id(egui::Id::new(id)) + let shown = egui::Window::new(crate::i18n::tr(title)) + .id(egui::Id::unique(id)) .order(egui::Order::Foreground) .collapsible(false) .resizable(false) @@ -107,6 +478,10 @@ fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&s .anchor(Align2::CENTER_CENTER, [0.0, 0.0]) .default_width(440.0) .show(ctx, |ui| { + // The prompt window has the same first-pass sizing rule as the dim above. + if ui.is_sizing_pass() { + ctx.request_discard("notice prompt: settle its buttons before input"); + } // a fixed width: a wrapped label in an auto-sized, centred window would move it every frame ui.set_width(420.0); ui.spacing_mut().item_spacing.y = 8.0; @@ -115,22 +490,45 @@ fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&s ui.horizontal(|ui| { for (i, (bid, label, _)) in buttons.iter().enumerate() { let r = ui.add(egui::Button::new(crate::i18n::tr(label)).min_size(vec2(0.0, 26.0))); - register(ui.ctx(), format!("button:{bid}"), r.rect); - if r.clicked() { + let widget = format!("button:{bid}"); + // The real response id is the AccessKit node a screen reader targets. A hover + // probe's id would make every Focus/Click action fail to match the button. + crate::widgets::register_response(widget.clone(), r.rect, &r); + if i == focus { + r.request_focus(); + } + seen.push((widget, r.id)); + if r.clicked() && chosen.is_none() { chosen = Some(i); } } }); }); + // A backdrop press can raise its area; keep the prompt buttons above it. + if let Some(window) = shown { + ctx.move_to_top(window.response.layer_id); + } + input.button_ids = seen; + if chosen.is_some() { + // The focused prompt button is about to disappear. Drop its focus now so this pass's + // `egui_wants_keyboard_input` (and `text_focus`) does not make the next Esc look like it + // belongs to a text field/dialog still underneath. + clear_prompt_focus(ctx); + } chosen } +/// Draw the prompt owning input, if any, and act on its answer: quit-while-tasks cancels jobs +/// and re-checks for unsaved changes; quit-with-unsaved retries, quits or cancels; a settings +/// notice is removed when acknowledged. Returns without drawing when no prompt is up. pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if let Some(QuitPrompt::Tasks(text)) = app.quit_prompt.clone() { let buttons = [("quitAnyway", "Quit Anyway", Choice::QuitAnyway), ("quitCancel", "Cancel", Choice::Cancel)]; - let Some(i) = window(ctx, "quit-tasks", "Quit while tasks are running?", &text, &buttons) else { return }; + let Some(i) = window(ctx, "quit-tasks", "Quit while tasks are running?", &text, &buttons, &mut app.notice_input) else { + return; + }; app.quit_prompt = None; - if matches!(buttons[i].2, Choice::QuitAnyway) { + if buttons.get(i).is_some_and(|(_, _, choice)| *choice == Choice::QuitAnyway) { app.session.activity.cancel_all(); // unsaved changes still get their own question if may_close(app) { @@ -145,26 +543,34 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { ("quitAnyway", "Quit Anyway", Choice::QuitAnyway), ("quitCancel", "Cancel", Choice::Cancel), ]; - let Some(i) = window(ctx, "quit-unsaved", "Quit with unsaved changes?", &text, &buttons) else { return }; - match buttons[i].2 { - Choice::Retry => { + let Some(i) = window(ctx, "quit-unsaved", "Quit with unsaved changes?", &text, &buttons, &mut app.notice_input) else { + return; + }; + match buttons.get(i).map(|(_, _, choice)| *choice) { + Some(Choice::Retry) => { app.quit_prompt = None; + // A retry that fails again recreates the same notice text, so its `PromptKey` + // would otherwise look unchanged: keep the old layout, focus and button ids from + // the Retry press. Start a fresh prompt so the next frame shields it and resets + // focus to the safe Cancel/OK choice. + app.notice_input.reset_to(None); + clear_prompt_focus(ctx); if may_close(app) { app.ui.quit = true; } } - Choice::QuitAnyway => { + Some(Choice::QuitAnyway) => { app.quit_prompt = None; app.quit_confirmed = true; app.ui.quit = true; } - Choice::Cancel | Choice::Ok => app.quit_prompt = None, + Some(Choice::Cancel | Choice::Ok) | None => app.quit_prompt = None, } return; } if let Some(text) = app.notices.first().cloned() { let buttons = [("noticeOk", "OK", Choice::Ok)]; - if window(ctx, "settings-notice", "Settings file problem", &text, &buttons).is_some() { + if window(ctx, "settings-notice", "Settings file problem", &text, &buttons, &mut app.notice_input).is_some() { app.notices.remove(0); } } @@ -172,7 +578,94 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests { - use super::gpu_notice; + use super::{PromptKey, gpu_notice, prepare_ui_pass, prompt_allows_event, prompt_key}; + + /// The prompt barrier keeps its own keys and pointer input, drops text/wheel input, and drops + /// the start/move half of a new touch gesture while keeping End/Cancel to clear egui's private + /// touch state. No prompt means everything survives. + #[test] + fn a_settled_prompt_allows_its_keys_and_pointer_but_not_text_wheel_or_new_touches() { + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + app.notice_input.key = Some(PromptKey { + layer: egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("test-prompt")), + text: "prompt".into(), + queue_len: 1, + }); + app.notice_input.laid_out = true; + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + assert!(prompt_allows_event(&app, &key(egui::Key::Tab, egui::Modifiers::NONE))); + assert!(prompt_allows_event(&app, &key(egui::Key::Escape, egui::Modifiers::NONE))); + assert!(!prompt_allows_event(&app, &key(egui::Key::A, egui::Modifiers::NONE))); + assert!(!prompt_allows_event(&app, &egui::Event::Text("x".into()))); + assert!(!prompt_allows_event( + &app, + &egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 10.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + } + )); + let touch = + |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: egui::pos2(10.0, 10.0), force: None }; + assert!(!prompt_allows_event(&app, &touch(egui::TouchPhase::Start))); + assert!(!prompt_allows_event(&app, &touch(egui::TouchPhase::Move))); + assert!(prompt_allows_event(&app, &touch(egui::TouchPhase::End))); + assert!(prompt_allows_event(&app, &touch(egui::TouchPhase::Cancel))); + assert!(prompt_allows_event(&app, &egui::Event::PointerMoved(egui::pos2(10.0, 10.0)))); + app.notice_input.key = None; + assert!(prompt_allows_event(&app, &egui::Event::Text("x".into()))); + assert!(prompt_allows_event(&app, &touch(egui::TouchPhase::Start))); + } + + /// A touch that began before a prompt must still get its End/Cancel while the prompt is in its + /// creation/transition frames (`laid_out` false). Start/Move remains background input. egui's + /// private touch state is not cleared by the pointer cleanup, so dropping the release would + /// leave the finger pressed after the prompt goes away. + #[test] + fn a_prompt_in_its_creation_frames_still_releases_touches() { + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + app.notice_input.key = Some(PromptKey { + layer: egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("test-prompt")), + text: "prompt".into(), + queue_len: 1, + }); + app.notice_input.laid_out = false; + let touch = + |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: egui::pos2(10.0, 10.0), force: None }; + assert!(!prompt_allows_event(&app, &touch(egui::TouchPhase::Start)), "a new touch must not start on the background"); + assert!(!prompt_allows_event(&app, &touch(egui::TouchPhase::Move)), "a touch move is still background input"); + assert!(prompt_allows_event(&app, &touch(egui::TouchPhase::End)), "the release must clear egui's touch state"); + assert!(prompt_allows_event(&app, &touch(egui::TouchPhase::Cancel)), "a canceled touch must clear egui's touch state"); + app.notice_input.laid_out = true; + assert!(!prompt_allows_event(&app, &touch(egui::TouchPhase::Start)), "settling does not let a new touch reach the background"); + assert!(prompt_allows_event(&app, &touch(egui::TouchPhase::End)), "settled prompts still release existing touches"); + } + + /// `prepare_ui_pass` dispatches the prompt's own AccessKit action manually; no AccessKit + /// request may survive that pass for a covered background widget (or be dispatched twice). + #[test] + fn manual_prompt_dispatch_drops_all_accesskit_requests() { + let ctx = egui::Context::default(); + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + app.quit_prompt = Some(crate::QuitPrompt::Tasks("tasks".into())); + app.notice_input.key = prompt_key(&app); + app.notice_input.laid_out = true; + let mut raw = egui::RawInput::default(); + raw.events.push(egui::Event::AccessKitActionRequest(egui::accesskit::ActionRequest { + action: egui::accesskit::Action::Click, + target_tree: egui::accesskit::TreeId::ROOT, + target_node: egui::accesskit::NodeId::from(42_u64), + data: None, + })); + let mut output = ctx.run_ui(raw, |ui| { + assert!(!prepare_ui_pass(&mut app, ui.ctx()), "the prompt was already known"); + let events = ui.ctx().input(|input| input.events.clone()); + assert!(events.is_empty(), "an AccessKit action survived manual prompt dispatch: {events:?}"); + }); + output.textures_delta.clear(); + } #[test] fn the_gpu_notice_is_only_for_a_missing_adapter() { diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rs index c5cd27b405..73d19cbaa9 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -74,7 +74,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = Rect::from_min_size(pos2(title.right() + 14.0, head.center().y - 12.0), vec2(width, 24.0)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r)); let b = crate::widgets::arrow_button(&mut child, RichText::new(label).font(t.font(13.0)), crate::icons::Icon::ChevronRight, false); - register(ui.ctx(), "people:last", b.rect); + register(ui, "people:last", b.rect); if b.on_hover_text(crate::i18n::tr("Back to this person")).clicked() { let _ = app.run("view.person", json!({"name": last})); } @@ -156,9 +156,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, edge: f32, ppp: f32, selected: bool) { let t = Tokens::get(ui.ctx()); let face = Rect::from_min_size(r.min, vec2(edge, edge)); - let resp = ui.interact(r, egui::Id::new(("person-card", &person.name)), Sense::click()); + let resp = ui.interact(r, egui::Id::unique(("person-card", &person.name)), Sense::click()); crate::widgets::announce(&resp, person.name.clone()); - register(ui.ctx(), format!("person:{}", person.name), r); + register(ui, format!("person:{}", person.name), r); let view = app.session.face_view(person.photo, person.face); let p = ui.painter(); p.rect_filled(face, 3.0, t.canvas); @@ -187,7 +187,7 @@ fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, ed let full = person.name.clone(); crate::widgets::context_menu(&resp, |ui| { let r = ui.button(crate::i18n::tr("Rename Person…")); - register(ui.ctx(), "personMenu:rename", r.rect); + register(ui, "personMenu:rename", r.rect); if r.clicked() { open_rename(app, &full); } diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index f2c719d435..98b738cf23 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -129,7 +129,8 @@ pub(crate) fn handle_bulk_key(app: &mut LightcraftApp, ctx: &egui::Context) -> b .or_else(|| { page.more.iter().filter(|f| !app.ui.dismissed_faces.contains(&(f.photo, f.index))).find(|f| { ctx.memory(|m| { - m.has_focus(egui::Id::new(("more-face", f.photo, f.index))) || m.has_focus(egui::Id::new(("more-face-above", f.photo, f.index))) + m.has_focus(egui::Id::unique(("more-face", f.photo, f.index))) + || m.has_focus(egui::Id::unique(("more-face-above", f.photo, f.index))) }) }) }); @@ -148,13 +149,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { ui.horizontal(|ui| { ui.add_space(PAD - 4.0); let back = crate::widgets::arrow_button(ui, crate::i18n::tr("People"), crate::icons::Icon::ChevronLeft, true); - register(ui.ctx(), "person:back", back.rect); + register(ui, "person:back", back.rect); if back.clicked() { let _ = app.run("view.people", json!({})); } ui.label(RichText::new(&shown_name).font(t.semibold(15.0)).color(t.text)); let rename = ui.button(crate::i18n::tr("Rename Person…")); - register(ui.ctx(), "person:rename", rename.rect); + register(ui, "person:rename", rename.rect); if rename.clicked() { super::people::open_rename(app, &shown_name); } @@ -163,7 +164,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_space(PAD - 4.0); let photos = ui.button(crate::i18n::tr("Show photos")).on_hover_text(crate::i18n::tr("Their photos in the grid")); - register(ui.ctx(), "person:photos", photos.rect); + register(ui, "person:photos", photos.rect); if photos.clicked() { let _ = app.run("library.filter", json!({"person": shown_name})); let _ = app.run("view.photoGrid", json!({})); @@ -237,7 +238,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { let r = Rect::from_min_size(pos2(area.left() + PAD + 330.0, area.top() + more_top + 8.0), vec2(120.0, 24.0)); let label = if step == super::faces::Setup::TurnOn { "Turn on" } else { "Open Settings" }; let b = ui.put(r, egui::Button::new(label)); - register(ui.ctx(), "faces:setup", b.rect); + register(ui, "faces:setup", b.rect); if b.clicked() { if step == super::faces::Setup::TurnOn { super::faces::take_step(app, ui.ctx(), step); @@ -291,16 +292,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, f: &Face, ppp: f32, more: bool, name: &str, above_count: usize) -> Hit { let t = Tokens::get(ui.ctx()); let salt = if more { "more-face" } else { "person-face" }; - let resp = ui.interact(r, egui::Id::new((salt, f.photo, f.index)), Sense::click()); + let resp = ui.interact(r, egui::Id::unique((salt, f.photo, f.index)), Sense::click()); crate::widgets::announce(&resp, name.to_string()); - register(ui.ctx(), format!("{salt}:{}:{}", f.photo, f.index), r); + register(ui, format!("{salt}:{}:{}", f.photo, f.index), r); // the × is added after the tile, so it wins where they overlap let x_rect = Rect::from_min_size(pos2(r.right() - 24.0, r.top() + 4.0), vec2(20.0, 20.0)); - let x_resp = more.then(|| ui.interact(x_rect, egui::Id::new(("more-face-x", f.photo, f.index)), Sense::click())); + let x_resp = more.then(|| ui.interact(x_rect, egui::Id::unique(("more-face-x", f.photo, f.index)), Sense::click())); let above_rect = Rect::from_min_size(pos2(r.left() + 4.0, r.top() + 4.0), vec2(24.0, 20.0)); - let above_resp = more.then(|| ui.interact(above_rect, egui::Id::new(("more-face-above", f.photo, f.index)), Sense::click())); + let above_resp = more.then(|| ui.interact(above_rect, egui::Id::unique(("more-face-above", f.photo, f.index)), Sense::click())); if more { - register(ui.ctx(), format!("more-face-above:{}:{}", f.photo, f.index), above_rect); + register(ui, format!("more-face-above:{}:{}", f.photo, f.index), above_rect); } let hovered = resp.hovered() || x_resp.as_ref().is_some_and(|x| x.hovered()) || above_resp.as_ref().is_some_and(|x| x.hovered()); let p = ui.painter(); diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index a8cf214241..6d35a50274 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -62,7 +62,7 @@ impl AppliedByPhoto { /// Remember `preset` on the photos `preset.apply` just changed (the selection, else the active /// photo; an active photo outside the selection wasn't changed and isn't marked). fn remember(ctx: &egui::Context, session: &lightcraft_engine::Session, preset: &str) { - let id = egui::Id::new(Self::ID); + let id = egui::Id::unique(Self::ID); let mut map: Self = ctx.data(|d| d.get_temp(id)).unwrap_or_default(); for photo in session.selected() { if let Some(d) = session.develop_of(photo) { @@ -75,13 +75,15 @@ impl AppliedByPhoto { /// The preset to mark for `photo`: the one it was given, while its settings are unchanged since. fn of(ctx: &egui::Context, session: &lightcraft_engine::Session, photo: Option<lightcraft_catalog::PhotoId>) -> Option<String> { let photo = photo?; - let map: Self = ctx.data(|d| d.get_temp(egui::Id::new(Self::ID)))?; + let map: Self = ctx.data(|d| d.get_temp(egui::Id::unique(Self::ID)))?; let (preset, then) = map.0.get(&photo)?; let now = session.develop_of(photo)?; (Arc::ptr_eq(then, &now) || **then == *now).then(|| preset.clone()) } } +/// The Presets panel: the Favorites section of starred presets on top (issue #1999), then the +/// groups of built-in and user presets, each row applying its preset on click. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)).show(ui, |ui| { @@ -109,7 +111,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let more = icon_button(&mut hdr, "presetMore", Icon::More, vec2(28.0, 28.0), false, true, crate::i18n::tr("More preset options")); egui::Popup::menu(&more).show(|ui| { let r = ui.checkbox(&mut app.ui.preset_thumbs, crate::i18n::tr("Show Thumbnails")); - register(ui.ctx(), "presetMenu:thumbnails", r.rect); + register(ui, "presetMenu:thumbnails", r.rect); ui.separator(); if ui.button(crate::i18n::tr("Import Presets…")).clicked() { let _ = app.run("file.importPresets", json!({})); @@ -121,7 +123,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { }); divider(ui); // amount slider (applies to the last applied preset) - let amt_id = egui::Id::new("preset-amount"); + let amt_id = egui::Id::unique("preset-amount"); let last: Option<AppliedPreset> = ui.data(|d| d.get_temp(amt_id)); if let Some(last) = last.clone().filter(|last| last.is_current(&app.session)) { let spec = ControlSpec { @@ -166,12 +168,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // imported whole is 10 000+ presets, and building every row each frame took seconds. let visible = ui.clip_rect().expand(row_h); for grp in groups.iter() { - let (g, builtin) = (grp.name.clone(), grp.builtin); - let open_id = egui::Id::new(("preset-group", &g)); + let (g, builtin, favorites) = (grp.name.clone(), grp.builtin, grp.favorites); + // the Favorites section opens and closes apart from a user group named "Favorites" + let open_id = egui::Id::unique(("preset-group", favorites, &g)); let open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(true); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click()); crate::widgets::announce(&resp, g.to_string()); - register(ui.ctx(), format!("presetGroup:{g}"), r); + // outside the `presetGroup:` ids, which a user group of any name can take + register(ui, if favorites { "presetFavorites".to_string() } else { format!("presetGroup:{g}") }, r); paint( ui.painter(), Rect::from_center_size(pos2(r.left() + 22.0, r.center().y), vec2(16.0, 16.0)), @@ -188,11 +192,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if resp.clicked() { ui.data_mut(|d| d.insert_temp(open_id, !open)); } - crate::widgets::context_menu(&resp, |ui| { - if ui.button(crate::i18n::tr("Export Group…")).clicked() { - let _ = app.run("file.exportPresets", json!({"group": g})); - } - }); + if !favorites { + crate::widgets::context_menu(&resp, |ui| { + if ui.button(crate::i18n::tr("Export Group…")).clicked() { + let _ = app.run("file.exportPresets", json!({"group": g})); + } + }); + } if !open { continue; } @@ -205,10 +211,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let (pid, name, fav) = (pr.id.clone(), crate::i18n::builtin_label(&pr.name, pr.builtin).to_string(), pr.favorite); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click()); crate::widgets::announce(&resp, name.clone()); - register(ui.ctx(), format!("preset:{pid}"), r); + // a starred preset is listed twice: in Favorites and in its group + register(ui, if favorites { format!("presetFavorite:{pid}") } else { format!("preset:{pid}") }, r); let is_last = marked.as_deref() == Some(pid.as_str()); if is_last { - register(ui.ctx(), "presetApplied", r); + register(ui, "presetApplied", r); ui.painter().rect_filled(r, 0.0, t.tool_active); } else if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.7)); @@ -227,7 +234,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } ui.painter().text(pos2(text_x, r.center().y), Align2::LEFT_CENTER, &name, t.font(13.0), t.text_label); if fav { - paint(ui.painter(), Rect::from_center_size(pos2(r.right() - 20.0, r.center().y), vec2(16.0, 16.0)), Icon::StarFilled, t.star); + crate::rating::paint_star( + ui.painter(), + Rect::from_center_size(pos2(r.right() - 20.0, r.center().y), vec2(16.0, 16.0)), + true, + t.star, + ); } // resting on a preset previews it in the loupe (no history entry) if resp.hovered() @@ -236,13 +248,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let label = crate::i18n::tr_format!("Preset: {name}", name = name); app.hover_preview = Some(HoverPreview { label: label.clone(), settings: s }); if let Some(id) = active { - ui.data_mut(|d| d.insert_temp(egui::Id::new("last-preset-hover"), (id, pr.clone(), label))); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("last-preset-hover"), (id, pr.clone(), label))); } } if resp.clicked() && app.run("preset.apply", json!({"id": pid, "amount": 100})).is_ok() { AppliedByPhoto::remember(ui.ctx(), &app.session, &pid); ui.data_mut(|d| d.insert_temp(amt_id, AppliedPreset::new(&app.session, pid.clone(), 100.0))); - ui.data_mut(|d| d.remove::<(lightcraft_catalog::PhotoId, Preset, String)>(egui::Id::new("last-preset-hover"))); + ui.data_mut(|d| d.remove::<(lightcraft_catalog::PhotoId, Preset, String)>(egui::Id::unique("last-preset-hover"))); app.toast(ui.ctx(), crate::i18n::tr_format!("Preset: {name}", name = name)); } let (builtin, group) = (pr.builtin, pr.group.clone()); @@ -296,7 +308,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } ui.add_space(30.0); }); - let last_hover_id = egui::Id::new("last-preset-hover"); + let last_hover_id = egui::Id::unique("last-preset-hover"); let pointer_in_scroll = ui.ctx().input(|i| i.pointer.hover_pos()).is_some_and(|pos| scroll.inner_rect.contains(pos)); if pointer_in_scroll { if app.hover_preview.is_none() @@ -321,13 +333,15 @@ struct Group { builtin: bool, /// Holds a user preset (a Move to Group target). user: bool, + /// The Favorites section on top (issue #1999): the starred presets, each also in its own group. + favorites: bool, items: Vec<usize>, } /// The presets by group (groups sorted by name, presets in list order), rebuilt only when the /// list changed (its generation). fn grouped(ctx: &egui::Context, presets: &PresetList) -> Arc<Vec<Group>> { - let id = egui::Id::new("presets-grouped"); + let id = egui::Id::unique("presets-grouped"); if let Some((generation, groups)) = ctx.data(|d| d.get_temp::<(u64, Arc<Vec<Group>>)>(id)) && generation == presets.generation() { @@ -335,12 +349,21 @@ fn grouped(ctx: &egui::Context, presets: &PresetList) -> Arc<Vec<Group>> { } let mut by_name: BTreeMap<&str, Group> = BTreeMap::new(); for (i, p) in presets.iter().enumerate() { - let g = by_name.entry(&p.group).or_insert_with(|| Group { name: p.group.clone(), builtin: false, user: false, items: Vec::new() }); + let g = by_name.entry(&p.group).or_insert_with(|| Group { + name: p.group.clone(), + builtin: false, + user: false, + favorites: false, + items: Vec::new(), + }); g.builtin |= p.builtin; g.user |= !p.builtin; g.items.push(i); } - let groups = Arc::new(by_name.into_values().collect::<Vec<_>>()); + // starred presets first, in their own section, as Profiles does + let starred: Vec<usize> = presets.iter().enumerate().filter(|(_, p)| p.favorite).map(|(i, _)| i).collect(); + let favorites = (!starred.is_empty()).then(|| Group { name: "Favorites".into(), builtin: true, user: false, favorites: true, items: starred }); + let groups = Arc::new(favorites.into_iter().chain(by_name.into_values()).collect::<Vec<_>>()); ctx.data_mut(|d| d.insert_temp(id, (presets.generation(), groups.clone()))); groups } @@ -349,7 +372,7 @@ fn grouped(ctx: &egui::Context, presets: &PresetList) -> Arc<Vec<Group>> { /// wherever the group changes. Only the rows in view are built (10 000+ presets made an open /// picker take seconds a frame). Returns the id of the preset clicked. pub fn picker_rows(ui: &mut egui::Ui, salt: &str, presets: &PresetList, selected: Option<&str>) -> Option<String> { - let id = egui::Id::new("preset-picker-rows"); + let id = egui::Id::unique("preset-picker-rows"); let rows = match ui.ctx().data(|d| d.get_temp::<(u64, Arc<Vec<PickRow>>)>(id)) { Some((generation, rows)) if generation == presets.generation() => rows, _ => { diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index 8a4b083457..cf9a6c50cd 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -72,11 +72,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } for (title, tag, imported, list) in sections { // an imported folder named like a built-in group still opens and closes on its own - let open_id = egui::Id::new(("profile-group", imported, title)); + let open_id = egui::Id::unique(("profile-group", imported, title)); let open: bool = ui.data(|m| m.get_temp(open_id)).unwrap_or(true); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click()); crate::widgets::announce(&resp, title.to_string()); - register(ui.ctx(), if imported { format!("profileGroup:lut:{title}") } else { format!("profileGroup:{title}") }, r); + register(ui, if imported { format!("profileGroup:lut:{title}") } else { format!("profileGroup:{title}") }, r); paint( ui.painter(), Rect::from_center_size(pos2(r.left() + 22.0, r.center().y), vec2(16.0, 16.0)), @@ -110,7 +110,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.add_space(6.0); } ui.add_space(30.0); - let last_hover_id = egui::Id::new("last-profile-hover"); + let last_hover_id = egui::Id::unique("last-profile-hover"); let pointer_in_profiles = ui.ctx().input(|i| i.pointer.hover_pos()).is_some_and(|pos| ui.max_rect().contains(pos)); if pointer_in_profiles { if app.hover_preview.is_none() @@ -153,9 +153,9 @@ fn cell_ui( let (p_id, p_name, p_group) = (p.0.as_str(), p.1.as_str(), p.2.as_str()); let t = Tokens::get(ui.ctx()); let key = if tag.is_empty() { format!("profileCell:{p_id}") } else { format!("profileCell:{tag}:{p_id}") }; - let resp = ui.interact(cell, egui::Id::new(&key), Sense::click()); + let resp = ui.interact(cell, egui::Id::unique(&key), Sense::click()); crate::widgets::announce(&resp, p_name.to_string()); - register(ui.ctx(), key, cell); + register(ui, key, cell); let thumb = Rect::from_min_size(cell.min, vec2(cell.width(), th)); let s = with_profile_id(d, p_id); let painter = ui.painter(); @@ -178,19 +178,19 @@ fn cell_ui( // favourite star (always shown when set, on hover otherwise) let fav = app.session.profile_favorites.iter().any(|f| f == p_id); let star = Rect::from_center_size(pos2(thumb.right() - 13.0, thumb.top() + 13.0), vec2(20.0, 20.0)); - register(ui.ctx(), format!("profileStar:{}{}", if tag.is_empty() { "" } else { "fav:" }, p_id), star); + register(ui, format!("profileStar:{}{}", if tag.is_empty() { "" } else { "fav:" }, p_id), star); let over_star = resp.hover_pos().is_some_and(|q| star.contains(q)); if fav || resp.hovered() { painter.circle_filled(star.center(), 10.0, Color32::from_black_alpha(110)); - paint(painter, star.shrink(4.0), if fav { Icon::StarFilled } else { Icon::Star }, if fav || over_star { t.star } else { Color32::WHITE }); + crate::rating::paint_star(painter, star.shrink(4.0), fav, if fav || over_star { t.star } else { Color32::WHITE }); } if resp.hovered() && !applied && !over_star { app.hover_preview = Some(HoverPreview { label: crate::i18n::tr_format!("Profile: {}", crate::i18n::profile_label(p_id, p_name)), settings: s.clone() }); - ui.data_mut(|m| m.insert_temp(egui::Id::new("last-profile-hover"), (id, p_id.to_string()))); + ui.data_mut(|m| m.insert_temp(egui::Id::unique("last-profile-hover"), (id, p_id.to_string()))); } else if resp.hovered() && applied { // resting on the applied profile shows it (no preview), not the last other profile hovered - ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::new("last-profile-hover"))); + ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))); } let resp = resp.on_hover_text(format!( "{} ({})", @@ -202,7 +202,7 @@ fn cell_ui( let _ = app.run("profile.favorite", json!({"id": p_id})); } else if !applied { let _ = app.run("develop.profile", json!({"id": p_id, "amount": 100})); - ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::new("last-profile-hover"))); + ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))); } } } diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 76ecc746a1..45a7bf2579 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -20,6 +20,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let Some(id) = app.session.active() else { // the Keyword List is the library's, not a photo's: it is there without a selection if app.ui.right == RightPanel::Keywords { + // (without a selection there is no Add keyword box for Add Keywords to put the cursor in) + app.ui.focus_keywords = None; egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]).show(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; if fold_header(app, ui, "keywording", "Keywords") { @@ -45,13 +47,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { area = area.vertical_scroll_offset(offset); } // (where the pass starts: by its end egui may have pulled a shrunken panel's offset back) - let area_id = ui.data(|d| d.get_temp::<egui::Id>(egui::Id::new(AREA))); - let start = held.or_else(|| area_id.and_then(|a| egui::scroll_area::State::load(ui.ctx(), a)).map(|s| s.offset.y)); + let area_id = ui.data(|d| d.get_temp::<egui::Id>(egui::Id::unique(AREA))); + let start = held.or_else(|| area_id.and_then(|a| egui::scroll_area::State::load(ui.ctx(), a)).map(|s| s.clamped_offset().y)); ui.data_mut(|d| match start { Some(o) => { - d.insert_temp(egui::Id::new(OFFSET), o); + d.insert_temp(egui::Id::unique(OFFSET), o); } - None => d.remove::<f32>(egui::Id::new(OFFSET)), + None => d.remove::<f32>(egui::Id::unique(OFFSET)), }); let scrolled = area.show(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; @@ -69,7 +71,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { RightPanel::None => {} } }); - ui.data_mut(|d| d.insert_temp(egui::Id::new(AREA), scrolled.id)); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(AREA), scrolled.id)); }); } @@ -83,11 +85,11 @@ const HOLD: &str = "right-scroll-hold"; /// the Keywords box grew. Set on the scroll area as it starts, so the pass drawn again shows the list /// in place (a scroll asked for during a pass only lands a frame later). fn held_offset(ctx: &egui::Context) -> Option<f32> { - let (grew, asked) = ctx.data_mut(|d| d.remove_temp::<(f32, u64)>(egui::Id::new(HOLD)))?; + let (grew, asked) = ctx.data_mut(|d| d.remove_temp::<(f32, u64)>(egui::Id::unique(HOLD)))?; if asked.checked_add(1) != Some(ctx.cumulative_pass_nr()) { return None; } - let offset = ctx.data(|d| d.get_temp::<f32>(egui::Id::new(OFFSET)))?; + let offset = ctx.data(|d| d.get_temp::<f32>(egui::Id::unique(OFFSET)))?; Some((offset + grew).max(0.0)).filter(|o| o.is_finite()) } @@ -109,8 +111,8 @@ pub fn fold_header(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, title: pub fn fold_title(app: &mut LightcraftApp, ui: &egui::Ui, id: &str, r: Rect, resp: &egui::Response, title: &str) -> bool { let t = Tokens::get(ui.ctx()); let open = !app.ui.section_folded(id); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title)); - register(ui.ctx(), format!("section:{id}"), r); + crate::widgets::announce_disclosure(resp, true, open, title); + register(ui, format!("section:{id}"), r); let p = ui.painter(); if resp.hovered() { p.rect_filled(r, 0.0, t.chrome.gamma_multiply(1.06)); @@ -178,18 +180,18 @@ fn aspect_label(aspect: Option<(u32, u32)>, original: Option<f64>) -> String { /// "Custom" row of the aspect menu: two number fields and an Apply button (`crop.aspect` `[w, h]`). fn custom_aspect(app: &mut LightcraftApp, ui: &mut egui::Ui) { - let key = egui::Id::new("crop-custom-aspect"); + let key = egui::Id::unique("crop-custom-aspect"); let (mut w, mut h): (String, String) = ui.data_mut(|d| d.get_temp(key)).unwrap_or_else(|| ("3".into(), "2".into())); let mut apply = false; ui.horizontal(|ui| { ui.label(crate::i18n::tr("Custom")); let a = ui.add(egui::TextEdit::singleline(&mut w).desired_width(34.0)); crate::widgets::screen_reader_name(ui.ctx(), a.id, crate::i18n::tr("Width")); - register(ui.ctx(), "field:cropCustomW", a.rect); + register(ui, "field:cropCustomW", a.rect); ui.label("×"); let b = ui.add(egui::TextEdit::singleline(&mut h).desired_width(34.0)); crate::widgets::screen_reader_name(ui.ctx(), b.id, crate::i18n::tr("Height")); - register(ui.ctx(), "field:cropCustomH", b.rect); + register(ui, "field:cropCustomH", b.rect); let go = text_button(ui, "cropCustomApply", "Apply", false); apply = go.clicked() || ((a.lost_focus() || b.lost_focus()) && ui.input(|i| i.key_pressed(egui::Key::Enter))); }); @@ -284,7 +286,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // keystroke: no half-typed angles, one undo step .update_while_editing(false), ); - crate::widgets::register(ui.ctx(), "cropAngleField", r.rect); + crate::widgets::register(ui, "cropAngleField", r.rect); // a drag on the field is one undo step, like the slider's if r.drag_started() { let _ = app.run("develop.beginInteraction", json!({"label": "Straighten"})); @@ -293,7 +295,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // apply only a new angle // Esc keeps the old angle, but egui applies the typed text on the frame after the // one where Esc took the focus away: remember the Esc for that frame - let cancel = egui::Id::new("cropAngleFieldEscaped"); + let cancel = egui::Id::unique("cropAngleFieldEscaped"); let escaped = ui.data_mut(|m| m.remove_temp::<bool>(cancel)).unwrap_or(false); if escape && r.lost_focus() { ui.data_mut(|m| m.insert_temp(cancel, true)); @@ -317,7 +319,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { app.ui.tool = if on { String::new() } else { "straighten".into() }; } if text_button(ui, "straightenAuto", crate::i18n::tr("Auto"), false).clicked() { - let _ = app.run("crop.autoStraighten", json!({})); + app.auto_straighten(ui.ctx()); } }); }); @@ -547,7 +549,7 @@ pub(crate) fn tool_overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { egui::Popup::menu(&r).show(|ui| { for m in ToolOverlay::ALL { let item = ui.selectable_label(m == current, crate::i18n::tr(m.label())); - register(ui.ctx(), format!("toolOverlay:{}", m.name()), item.rect); + register(ui, format!("toolOverlay:{}", m.name()), item.rect); if item.clicked() { let _ = app.run("view.toolOverlay", json!({"mode": m.name()})); } @@ -642,7 +644,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.label(egui::RichText::new(crate::i18n::tr_format!("Virtual copy “{name}” of {of}", name = name, of = of)).color(t.text_label)); } ui.add_space(8.0); - if let Some(r) = ui.horizontal(|ui| crate::widgets::stars(ui, "info", p.rating, 20.0)).inner { + if let Some(r) = ui.horizontal(|ui| crate::rating::Rating::new("info", p.rating).show(ui)).inner { let mut params = json!({"rating": r}); crate::panels::compare::target_active(app, &mut params); let _ = app.run("photo.rate", params); @@ -654,7 +656,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr(&format!("{l:?}"))); let key = format!("{l:?}").to_lowercase(); - register(ui.ctx(), format!("label:{key}"), r); + register(ui, format!("label:{key}"), r); let on = p.label == Some(l); ui.painter().circle_filled(r.center(), if on || resp.hovered() { 8.0 } else { 6.5 }, crate::panels::grid::label_color(l)); if on { @@ -674,8 +676,19 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { }); }); divider(ui); - let m = p.meta.clone(); + // with several photos selected: Target Photo shows this photo's values, Selected Photos what + // the selection shares (a field where they differ is empty and says Mixed) + let selected = app.session.selected(); + let several = selected.len() > 1; + let for_selected = several && app.ui.settings.info_selected_photos; + let m = shown_meta(&app.session.catalog, &p, &selected, for_selected); + let mixed = if for_selected { mixed_meta(&app.session.catalog, &selected, &m) } else { Vec::new() }; + // the photos an edit goes to: Target Photo edits the photo it shows + let targets = if several && !for_selected { vec![id] } else { selected.clone() }; padded(ui, |ui| { + if several { + metadata_for(app, ui); + } for (label, key, value, lines) in [ ("Title", "title", &m.title, 1), ("Caption", "caption", &m.caption, 2), @@ -683,15 +696,15 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ("Extended Description", "extendedDescription", &m.extended_description, 3), ("Copyright", "copyright", &m.copyright, 1), ] { - meta_field(app, ui, label, key, value, lines); + meta_field(app, ui, label, key, value, lines, mixed.contains(&key), &targets); } - copyright_status(app, ui, m.copyright_status); + copyright_status(app, ui, m.copyright_status, mixed.contains(&"copyrightStatus"), &targets); for (label, key, value, lines) in [ ("Rights Usage Terms", "usageTerms", &m.usage_terms, 2), ("Copyright Info URL", "copyrightUrl", &m.copyright_url, 1), ("Creator", "creator", &m.creator, 1), ] { - meta_field(app, ui, label, key, value, lines); + meta_field(app, ui, label, key, value, lines, mixed.contains(&key), &targets); } // file: name (rename), path (reveal), capture time (edit) let small = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(crate::i18n::tr(text)).size(11.5).color(t.text_dim)); @@ -740,28 +753,32 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ("State / Province", "state", &m.state), ("Country", "country", &m.country), ] { - meta_field(app, ui, label, key, value, 1); + meta_field(app, ui, label, key, value, 1, mixed.contains(&key), &targets); } // GPS: typed as "lat, lon" (or degrees / minutes / seconds); empty clears it - let gps = m.gps.map(|(la, lo)| format!("{la:.6}, {lo:.6}")).unwrap_or_default(); - let gid = egui::Id::new("info-gps"); + let gps_mixed = mixed.contains(&"gps"); + let gps = if gps_mixed { String::new() } else { m.gps.map(|(la, lo)| format!("{la:.6}, {lo:.6}")).unwrap_or_default() }; + let gid = egui::Id::unique("info-gps"); ui.label(egui::RichText::new("GPS").size(11.5).color(t.text_dim)); - let mut text: String = ui.data(|d| d.get_temp(gid)).unwrap_or_else(|| gps.clone()); - let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(crate::i18n::tr("latitude, longitude")).desired_width(f32::INFINITY)); - crate::widgets::screen_reader_name(ui.ctx(), r.id, "GPS"); - register(ui.ctx(), "field:gps", r.rect); - if r.has_focus() { - ui.data_mut(|d| d.insert_temp(gid, text.clone())); + let mut edit: FieldEdit = ui.data(|d| d.get_temp(gid)).unwrap_or_else(|| FieldEdit::new(&gps, gps_mixed, &targets)); + let hint = crate::i18n::tr(if gps_mixed { MIXED } else { "latitude, longitude" }); + let r = crate::text_field::TextField::singleline("field:gps", &mut edit.text).hint(hint).label("GPS").width(f32::INFINITY).show(ui); + edit.typed |= edit.text != edit.start; + if r.editing { + ui.data_mut(|d| d.insert_temp(gid, edit.clone())); } else { - ui.data_mut(|d| d.remove::<String>(gid)); + ui.data_mut(|d| d.remove::<FieldEdit>(gid)); } - if r.lost_focus() - && text.trim() != gps - && let Err(e) = app.run("photo.setMeta", json!({"gps": text.trim()})) + // Return or leaving saves; Esc gives the edit up + let text = edit.text.trim(); + if r.committed() + && (text != edit.start || edit.clears()) + && let Err(e) = app.run("photo.setMeta", json!({"ids": edit.ids, "gps": text})) { app.toast(ui.ctx(), e); } - if let Some((la, lo)) = m.gps { + // (one photo's place: not shown while the selected photos' places differ) + if let Some((la, lo)) = m.gps.filter(|_| !gps_mixed) { let pretty = format!("{:.5}° {}, {:.5}° {}", la.abs(), if la >= 0.0 { "N" } else { "S" }, lo.abs(), if lo >= 0.0 { "E" } else { "W" }); ui.horizontal(|ui| { ui.label(egui::RichText::new(pretty).size(11.0).color(t.text_dim)); @@ -866,7 +883,7 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { } }); } - // where the camera focused, and how (View ▸ Show Focus Point draws it): only when known; the + // where the camera focused, and how (View ▸ Focus Point draws it): only when known; the // whole card's width, so "AF-C · Expanded Flexible Spot · Face tracking" fits if let Some(text) = focus_text(m.focus.as_ref()) { ui.add_space(3.0); @@ -875,7 +892,7 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { ui.add_space(12.0); ui.label(egui::RichText::new(text).size(12.0).color(t.text)); }); - register(ui.ctx(), "info:focus", r.response.rect); + register(ui, "info:focus", r.response.rect); } }); } @@ -896,44 +913,177 @@ fn human_size(bytes: u64) -> String { } } -/// A labelled metadata text field: the typed text lives in egui memory while focused and is -/// saved (photo.setMeta `key`) when the field loses focus. -/// Copyright Status: Unknown / Copyrighted / Public Domain (`xmpRights:Marked`). -fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcraft_catalog::CopyrightStatus) { +/// What a metadata field shows while the selected photos' values differ (Selected Photos). +const MIXED: &str = "Mixed"; + +/// An Info panel field's edit under way, kept in egui memory between frames. A field saves when +/// its text is not the text the edit started from, so a field left as it was saves nothing, even +/// when what the panel shows changed during the edit. It saves to the photos it edited when the +/// edit started (the selected photos, or Target Photo's photo alone), also when the selection +/// changed since. +#[derive(Clone)] +struct FieldEdit { + text: String, + start: String, + /// The photos the field edited when the edit started (`photo.setMeta` `ids`). + ids: Vec<u64>, + /// The field said Mixed when the edit started. + mixed: bool, + /// Something was typed or deleted since. + typed: bool, +} + +impl FieldEdit { + fn new(value: &str, mixed: bool, targets: &[PhotoId]) -> Self { + let ids = targets.iter().map(|id| id.0).collect(); + FieldEdit { text: value.to_string(), start: value.to_string(), ids, mixed, typed: false } + } + + /// A Mixed field that was typed in and left empty: it clears the field on every selected photo. + fn clears(&self) -> bool { + self.mixed && self.typed + } +} + +/// The Info panel's text fields, by their `photo.setMeta` key. +const META_TEXT_KEYS: [&str; 12] = [ + "title", + "caption", + "altText", + "extendedDescription", + "copyright", + "usageTerms", + "copyrightUrl", + "creator", + "location", + "city", + "state", + "country", +]; + +/// The value of one of [`META_TEXT_KEYS`]. +fn meta_text<'a>(m: &'a lightcraft_catalog::Meta, key: &str) -> Option<&'a str> { + Some(match key { + "title" => &m.title, + "caption" => &m.caption, + "altText" => &m.alt_text, + "extendedDescription" => &m.extended_description, + "copyright" => &m.copyright, + "usageTerms" => &m.usage_terms, + "copyrightUrl" => &m.copyright_url, + "creator" => &m.creator, + "location" => &m.location, + "city" => &m.city, + "state" => &m.state, + "country" => &m.country, + _ => return None, + }) +} + +/// The metadata the Info panel's fields show: the active photo `p`'s, or with `for_selected` +/// (Selected Photos) the active photo's when it is one of the `selected` photos, else the first +/// selected photo's. +pub(crate) fn shown_meta( + catalog: &lightcraft_catalog::Catalog, + p: &lightcraft_catalog::Photo, + selected: &[PhotoId], + for_selected: bool, +) -> lightcraft_catalog::Meta { + if !for_selected || selected.contains(&p.id) { + return p.meta.clone(); + } + selected.iter().find_map(|&id| catalog.photo(id)).map_or_else(|| p.meta.clone(), |q| q.meta.clone()) +} + +/// The Info panel fields (`photo.setMeta` keys, plus `copyrightStatus` and `gps`) where one of +/// the photos `ids` has a value other than `shown`'s, the metadata the panel draws. +pub(crate) fn mixed_meta(catalog: &lightcraft_catalog::Catalog, ids: &[PhotoId], shown: &lightcraft_catalog::Meta) -> Vec<&'static str> { + let mut mixed = Vec::new(); + for m in ids.iter().filter_map(|&id| catalog.photo(id)).map(|p| &p.meta) { + for key in META_TEXT_KEYS { + if !mixed.contains(&key) && meta_text(m, key) != meta_text(shown, key) { + mixed.push(key); + } + } + if !mixed.contains(&"copyrightStatus") && m.copyright_status != shown.copyright_status { + mixed.push("copyrightStatus"); + } + if !mixed.contains(&"gps") && m.gps != shown.gps { + mixed.push("gps"); + } + if mixed.len() == META_TEXT_KEYS.len() + 2 { + break; + } + } + mixed +} + +/// Target Photo / Selected Photos: whose metadata the fields below show while several photos +/// are selected (`view.infoSelectedPhotos`). +fn metadata_for(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::tr("Copyright Status")).size(11.5).color(t.text_dim)); - let r = crate::widgets::combo_box("info-copyright-status").selected_text(crate::i18n::tr(current.label())).show_ui(ui, |ui| { - for st in lightcraft_catalog::CopyrightStatus::ALL { - if ui.selectable_label(st == current, crate::i18n::tr(st.label())).clicked() && st != current { - let _ = app.run("photo.setMeta", json!({"copyrightStatus": st.id()})); + ui.label(egui::RichText::new(crate::i18n::tr("Show Metadata For")).size(11.5).color(t.text_dim)); + ui.horizontal_wrapped(|ui| { + let on = app.ui.settings.info_selected_photos; + for (id, label, selected) in [("infoFor-target", "Target Photo", false), ("infoFor-selected", "Selected Photos", true)] { + if text_button(ui, id, label, on == selected).clicked() && on != selected { + let _ = app.run("view.infoSelectedPhotos", json!({"on": selected})); } } }); - register(ui.ctx(), "field:copyrightStatus", r.response.rect); ui.add_space(6.0); } -fn meta_field(app: &mut LightcraftApp, ui: &mut egui::Ui, label: &str, key: &str, value: &str, lines: usize) { +/// Copyright Status: Unknown / Copyrighted / Public Domain (`xmpRights:Marked`). `mixed`: the +/// selected photos' statuses differ, and any status picked is given to all of them. A status +/// picked goes to the photos `targets`. +fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcraft_catalog::CopyrightStatus, mixed: bool, targets: &[PhotoId]) { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(crate::i18n::tr("Copyright Status")).size(11.5).color(t.text_dim)); + let shown = crate::i18n::tr(if mixed { MIXED } else { current.label() }); + let r = crate::widgets::combo_box("info-copyright-status").selected_text(shown).show_ui(ui, |ui| { + for st in lightcraft_catalog::CopyrightStatus::ALL { + let on = !mixed && st == current; + if ui.selectable_label(on, crate::i18n::tr(st.label())).clicked() && !on { + let ids: Vec<u64> = targets.iter().map(|id| id.0).collect(); + let _ = app.run("photo.setMeta", json!({"ids": ids, "copyrightStatus": st.id()})); + } + } + }); + crate::widgets::name_combo(&r.response, crate::i18n::tr("Copyright Status")); + register(ui, "field:copyrightStatus", r.response.rect); + ui.add_space(6.0); +} + +/// A labeled metadata text field: the typed text lives in egui memory while focused and is +/// saved (photo.setMeta `key`) when the field loses focus. `mixed`: the selected photos' values +/// differ, so the field starts empty and says so, and is saved only when it was typed in (left +/// empty, it clears the field on every selected photo). The edit is saved to the photos `targets`. +#[allow(clippy::too_many_arguments)] +fn meta_field(app: &mut LightcraftApp, ui: &mut egui::Ui, label: &str, key: &str, value: &str, lines: usize, mixed: bool, targets: &[PhotoId]) { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(crate::i18n::tr(label)).size(11.5).color(t.text_dim)); - let id = egui::Id::new(("info-field", key)); - let mut text: String = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| value.to_string()); + let id = egui::Id::unique(("info-field", key)); + let value = if mixed { "" } else { value }; + let mut edit: FieldEdit = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| FieldEdit::new(value, mixed, targets)); let widget = format!("field:{key}"); let field = if lines > 1 { - crate::text_field::TextField::multiline(&widget, &mut text).rows(lines) + crate::text_field::TextField::multiline(&widget, &mut edit.text).rows(lines) } else { - crate::text_field::TextField::singleline(&widget, &mut text) + crate::text_field::TextField::singleline(&widget, &mut edit.text) }; + let field = if mixed { field.hint(crate::i18n::tr(MIXED)) } else { field }; let r = field.label(crate::i18n::tr(label)).width(f32::INFINITY).show(ui); + edit.typed |= edit.text != edit.start; // the typed text outlives frames while it is edited (the photo's value is drawn otherwise) if r.editing { - ui.data_mut(|d| d.insert_temp(id, text.clone())); + ui.data_mut(|d| d.insert_temp(id, edit.clone())); } else { - ui.data_mut(|d| d.remove::<String>(id)); + ui.data_mut(|d| d.remove::<FieldEdit>(id)); } // Return (one line) or leaving saves; Esc gives the edit up - if r.committed() && text != value { - let _ = app.run("photo.setMeta", json!({key: text})); + if r.committed() && (edit.text != edit.start || edit.clears()) { + let _ = app.run("photo.setMeta", json!({"ids": edit.ids, key: edit.text})); } ui.add_space(6.0); } @@ -956,7 +1106,7 @@ fn keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); padded(ui, |ui| { - let kid = egui::Id::new("kw-input"); + let kid = egui::Id::unique("kw-input"); let mut text = ui.data_mut(|d| d.get_temp::<String>(kid).unwrap_or_default()); // the keywords every selected photo has: those only some have are still offered and suggested let selection = app.session.selected(); @@ -965,7 +1115,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { // while the box has the cursor it offers the library's keywords for what is being typed, // right under itself; it stays for a click on one of them, which takes the cursor away let field = crate::text_field::id("field:keyword"); - let oid = egui::Id::new("kw-offers"); + let oid = egui::Id::unique("kw-offers"); let pass = ui.ctx().cumulative_pass_nr(); // (remembered from the last frame: the text the highlight was for and the keyword it was // on, where the offers were drawn, and whether the box was in sight) @@ -1012,13 +1162,18 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { // (after an offer was taken the box starts a new edit, empty: Esc has nothing to bring back) // (asked for on the frame before this one only: a box that wasn't drawn then, its panel // switched away, doesn't claim the cursor whenever it is next drawn) - let bid = egui::Id::new("kw-begin"); + let bid = egui::Id::unique("kw-begin"); let begin = ui.data_mut(|d| d.remove_temp::<u64>(bid)).is_some_and(|asked| asked.checked_add(1) == Some(pass)); + // Add Keywords (⌘K) asks for the cursor too, and for the box to be scrolled into sight + let asked = app.ui.focus_keywords.take().is_some_and(|at| pass <= at.saturating_add(crate::state::FOCUS_KEYWORDS_PASSES)); let r = crate::text_field::TextField::singleline("field:keyword", &mut text) .hint(crate::i18n::tr("Add keyword")) .width(f32::INFINITY) - .begin_edit(begin) + .begin_edit(begin || asked) .show(ui); + if asked { + r.response.scroll_to_me(None); + } let in_sight = ui.clip_rect().contains(r.response.rect.center()); let mut drawn = Rect::NOTHING; // (what isn't drawn can't be taken: Return on the frame the box scrolls out gives nothing) @@ -1081,7 +1236,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.add_space(8.0); // the painter: click photos in the grid to give them (or take away) a keyword ui.horizontal(|ui| { - let pid = egui::Id::new("kw-painter"); + let pid = egui::Id::unique("kw-painter"); let painting = app.ui.keyword_painter.clone(); let mut k: String = ui.data(|d| d.get_temp(pid)).unwrap_or_else(|| painting.clone().unwrap_or_default()); // (fixed while painting: Stop first) @@ -1122,7 +1277,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { let name = names.get(i).unwrap_or(&whole); let r = ui.add(egui::Button::new(egui::RichText::new(format!("+ {name}")).color(t.text_label)).corner_radius(10.0)); let r = if grouped { r.on_hover_text(&whole) } else { r }; - register(ui.ctx(), format!("kwSuggest:{k}"), r.rect); + register(ui, format!("kwSuggest:{k}"), r.rect); if r.clicked() { let _ = app.run("photo.setMeta", json!({"addKeywords": [k]})); } @@ -1139,7 +1294,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { /// while the change does not come from the box itself (the pointer on it, or typing in its field). fn hold_list_in_place(ui: &mut egui::Ui, top: f32) { let height = ui.cursor().top() - top; - let key = egui::Id::new("kw-box-height"); + let key = egui::Id::unique("kw-box-height"); let pass = ui.ctx().cumulative_pass_nr(); // (the height drawn on the pass before: one from an earlier visit to the panel says nothing) let before = ui.data(|d| d.get_temp::<(f32, u64)>(key)).filter(|&(_, drawn)| drawn.checked_add(1) == Some(pass)).map(|(h, _)| h); @@ -1156,7 +1311,7 @@ fn hold_list_in_place(ui: &mut egui::Ui, top: f32) { if on_box || typing { return; } - ui.data_mut(|d| d.insert_temp(egui::Id::new(HOLD), (grew, pass))); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(HOLD), (grew, pass))); // (drawn again at once at the new offset, so the list never shows a frame out of place) ui.ctx().request_discard("the Keyword List holds its place"); } @@ -1187,7 +1342,7 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.separator(); // Edit Set…: the current nine, slot by slot (named, Recent Keywords becomes a set) let edit = ui.button(crate::i18n::tr("Edit Set…")); - register(ui.ctx(), "keywordSetMenu:edit", edit.rect); + register(ui, "keywordSetMenu:edit", edit.rect); if edit.clicked() { let mut slots: Vec<String> = sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect(); @@ -1216,7 +1371,8 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { let _ = app.run("keyword.deleteSet", json!({"name": current})); } }); - register(ui.ctx(), "keywordSetCombo", combo.response.rect); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Keyword Set")); + register(ui, "keywordSetCombo", combo.response.rect); }); let kws: Vec<String> = sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect(); if kws.is_empty() { @@ -1229,7 +1385,7 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { // an empty slot: an idle button, so the others keep their ⌥ keys if k.is_empty() { let r = ui.add_enabled_ui(false, |ui| ui.add_sized([bw, 22.0], egui::Button::new(""))).inner; - register(ui.ctx(), format!("kwSetEmpty:{}", i + 1), r.rect); + register(ui, format!("kwSetEmpty:{}", i + 1), r.rect); if i % 3 == 2 { ui.end_row(); } @@ -1245,11 +1401,11 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { egui::Button::new(egui::RichText::new(short).size(11.5).color(if on { t.text } else { t.text_label })).selected(on).truncate(), ) .on_hover_text(format!("{} — ⌥{}", k.replace('|', " › "), i + 1)); - register(ui.ctx(), format!("kwSet:{}", i + 1), r.rect); + register(ui, format!("kwSet:{}", i + 1), r.rect); if on { - register(ui.ctx(), format!("kwSetOn:{}", i + 1), r.rect); + register(ui, format!("kwSetOn:{}", i + 1), r.rect); } else if some { - register(ui.ctx(), format!("kwSetSome:{}", i + 1), r.rect); + register(ui, format!("kwSetSome:{}", i + 1), r.rect); } if r.clicked() { let _ = app.run("keyword.toggleFromSet", json!({"index": i + 1})); @@ -1271,7 +1427,7 @@ fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } ui.add_space(8.0); // Named (made by you) and Auto (made by LightCraft) versions - let tab_id = egui::Id::new("versions-tab"); + let tab_id = egui::Id::unique("versions-tab"); let mut auto: bool = ui.data(|d| d.get_temp(tab_id)).unwrap_or(false); let named_n = p.versions.iter().filter(|v| !v.auto).count(); let items = [("Named", "named"), ("Auto", "auto")]; @@ -1292,7 +1448,7 @@ fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { for (i, v) in shown.into_iter().rev() { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 58.0), Sense::click()); crate::widgets::announce(&resp, format!("{} {}", crate::i18n::tr("Version"), i + 1)); - register(ui.ctx(), format!("version:{i}"), r); + register(ui, format!("version:{i}"), r); let current = *v.settings == *p.develop; if resp.hovered() { ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.7)); @@ -1403,7 +1559,7 @@ fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { for (i, h) in p.history.iter().enumerate().rev() { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); crate::widgets::announce(&resp, crate::i18n::tr(&h.label)); - register(ui.ctx(), format!("history:{i}"), r); + register(ui, format!("history:{i}"), r); let row = history_row(i, cursor); if row == HistoryRow::Current { ui.painter().rect_filled(r, 3.0, t.pressed); diff --git a/crates/ui-egui/src/panels/rules_editor.rs b/crates/ui-egui/src/panels/rules_editor.rs index d69a8fa43c..509a096eca 100644 --- a/crates/ui-egui/src/panels/rules_editor.rs +++ b/crates/ui-egui/src/panels/rules_editor.rs @@ -51,11 +51,12 @@ fn match_combo(ui: &mut egui::Ui, salt: &str, m: &mut Match) { Match::Any => "any", Match::None => "none", }; - crate::widgets::combo_box(format!("{salt}-match")).width(64.0).selected_text(crate::i18n::tr(label(*m))).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box(format!("{salt}-match")).width(64.0).selected_text(crate::i18n::tr(label(*m))).show_ui(ui, |ui| { for x in [Match::All, Match::Any, Match::None] { ui.selectable_value(m, x, crate::i18n::tr(label(x))); } }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Match")); } fn text_value(ui: &mut egui::Ui, v: &mut Value, width: f32, hint: &str, salt: &str) { @@ -65,7 +66,7 @@ fn text_value(ui: &mut egui::Ui, v: &mut Value, width: f32, hint: &str, salt: &s other => other.to_string(), }; let r = ui.add(egui::TextEdit::singleline(&mut s).hint_text(crate::i18n::tr(hint)).desired_width(width)); - register(ui.ctx(), format!("field:{salt}"), r.rect); + register(ui, format!("field:{salt}"), r.rect); if r.changed() { *v = json!(s); } @@ -149,7 +150,7 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: & let mut unit = stored_unit.to_lowercase(); let mut changed = ui.add(egui::DragValue::new(&mut n).range(1.0..=10_000.0).clamp_existing_to_range(false).speed(0.2).fixed_decimals(0)).changed(); - crate::widgets::combo_box(format!("{salt}-unit")).width(70.0).selected_text(crate::i18n::tr(&unit)).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box(format!("{salt}-unit")).width(70.0).selected_text(crate::i18n::tr(&unit)).show_ui(ui, |ui| { for u in ["hours", "days", "weeks", "months", "years"] { if ui.selectable_label(unit.trim_end_matches('s') == u.trim_end_matches('s'), crate::i18n::tr(u)).clicked() { unit = u.to_string(); @@ -157,6 +158,7 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: & } } }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Unit")); if changed { *v = json!({"n": n.round(), "unit": unit}); } @@ -198,26 +200,31 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: & (Some(Kind::Number), _) => number_value(ui, v, field), (Some(Kind::Choice(c)), _) => { let cur = v.as_str().unwrap_or("").to_string(); - crate::widgets::combo_box(format!("{salt}-choice")).width(120.0).selected_text(crate::i18n::choice_text(field, &cur)).show_ui(ui, |ui| { - for (id, _) in c.iter() { - if ui.selectable_label(cur == *id, crate::i18n::choice_text(field, id)).clicked() { - *v = json!(id); + let combo = crate::widgets::combo_box(format!("{salt}-choice")) + .width(120.0) + .selected_text(crate::i18n::choice_text(field, &cur)) + .show_ui(ui, |ui| { + for (id, _) in c.iter() { + if ui.selectable_label(cur == *id, crate::i18n::choice_text(field, id)).clicked() { + *v = json!(id); + } } - } - }); + }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr(field_label(field).unwrap_or(field))); } (Some(Kind::Bool), _) => { // the catalog's reading of the value ("false" is no); one that is neither yes nor no is // shown as written and kept until a choice replaces it, so the dialog reports it let cur = bool_value(v); let text = cur.map_or_else(|| v.to_string(), |b| crate::i18n::bool_text(b).to_string()); - crate::widgets::combo_box(format!("{salt}-bool")).width(60.0).selected_text(text).show_ui(ui, |ui| { + let combo = crate::widgets::combo_box(format!("{salt}-bool")).width(60.0).selected_text(text).show_ui(ui, |ui| { for b in [true, false] { if ui.selectable_label(cur == Some(b), crate::i18n::bool_text(b)).clicked() { *v = json!(b); } } }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr(field_label(field).unwrap_or(field))); } (Some(Kind::Date), _) => { text_value(ui, v, 120.0, "2026-04 or 2026-04-12", salt); @@ -236,7 +243,7 @@ fn field_menu(ui: &mut egui::Ui, salt: &str, field: &mut String, op: &mut String let mut pick = None; let mut item = |ui: &mut egui::Ui, id: &'static str| { let r = ui.selectable_label(current == id, crate::i18n::tr(field_label(id).unwrap_or(id))); - register(ui.ctx(), format!("ruleFieldItem:{id}:{salt}"), r.rect); + register(ui, format!("ruleFieldItem:{id}:{salt}"), r.rect); if r.clicked() { pick = Some(id); ui.close(); @@ -258,11 +265,12 @@ fn field_menu(ui: &mut egui::Ui, salt: &str, field: &mut String, op: &mut String item(ui, id); } }); - register(ui.ctx(), format!("ruleFieldGroup:{group}:{salt}"), r.response.rect); + register(ui, format!("ruleFieldGroup:{group}:{salt}"), r.response.rect); } pick }); - register(ui.ctx(), format!("ruleField:{salt}"), r.response.rect); + crate::widgets::name_combo(&r.response, crate::i18n::tr("Field")); + register(ui, format!("ruleField:{salt}"), r.response.rect); let Some(Some(id)) = r.inner else { return }; if field == id { return; @@ -287,7 +295,7 @@ fn problem_note(ui: &mut egui::Ui, problem: Option<&Problem>, salt: &str) { let Some(p) = problem else { return }; let t = Tokens::get(ui.ctx()); let r = ui.label(RichText::new(format!("⚠ {}", crate::i18n::problem_text(p))).color(t.caution).small()); - register(ui.ctx(), format!("ruleProblem:{salt}"), r.rect); + register(ui, format!("ruleProblem:{salt}"), r.rect); } /// Edit `rs` in place; `salt` keeps widget ids apart between groups, `path` is where `rs` sits @@ -322,17 +330,19 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: field_menu(ui, &rsalt, field, op, value); let kind = field_kind(field).unwrap_or(Kind::Text); let op_label = ops_for(kind).iter().find(|o| o.0 == op.as_str()).map_or(op.as_str(), |o| o.1).to_string(); - crate::widgets::combo_box(format!("{rsalt}-op")).width(110.0).selected_text(crate::i18n::tr(&op_label)).show_ui(ui, |ui| { - for (id, l) in ops_for(kind) { - if ui.selectable_label(op == id, crate::i18n::tr(l)).clicked() && op != id { - let was_special = matches!(op.as_str(), "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty"); - *op = id.to_string(); - if was_special || matches!(*id, "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty") { - *value = default_value(field, op); + let combo = + crate::widgets::combo_box(format!("{rsalt}-op")).width(110.0).selected_text(crate::i18n::tr(&op_label)).show_ui(ui, |ui| { + for (id, l) in ops_for(kind) { + if ui.selectable_label(op == id, crate::i18n::tr(l)).clicked() && op != id { + let was_special = matches!(op.as_str(), "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty"); + *op = id.to_string(); + if was_special || matches!(*id, "between" | "inLast" | "notInLast" | "isEmpty" | "isNotEmpty") { + *value = default_value(field, op); + } } } - } - }); + }); + crate::widgets::name_combo(&combo.response, crate::i18n::tr("Operator")); value_editor(ui, field, op, value, &rsalt, env); // − and + at the end of the row, after the value however long it is: a // right-to-left layout put them over the value when the row had no room left @@ -340,12 +350,12 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: let buttons = small_button_width(ui, "−") + ui.spacing().item_spacing.x + small_button_width(ui, "+"); ui.add_space((ui.available_width() - buttons).max(0.0)); let del = ui.small_button("−").on_hover_text(crate::i18n::tr("Remove this rule")); - register(ui.ctx(), format!("button:ruleRemove-{rsalt}"), del.rect); + register(ui, format!("button:ruleRemove-{rsalt}"), del.rect); if del.clicked() { remove = Some(i); } let add = ui.small_button("+").on_hover_text(crate::i18n::tr("Add a rule (⌥-click: a group)")); - register(ui.ctx(), format!("button:ruleAdd-{rsalt}"), add.rect); + register(ui, format!("button:ruleAdd-{rsalt}"), add.rect); if add.clicked() { let group = ui.input(|i| i.modifiers.alt) && depth < 3; insert = Some(( @@ -367,7 +377,7 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: if rs.rules.is_empty() || depth == 0 { ui.horizontal(|ui| { let add = ui.small_button(crate::i18n::tr("+ Rule")); - register(ui.ctx(), format!("button:ruleAddEnd-{salt}"), add.rect); + register(ui, format!("button:ruleAddEnd-{salt}"), add.rect); if add.clicked() { rs.rules.push(new_rule()); } diff --git a/crates/ui-egui/src/panels/rules_move.rs b/crates/ui-egui/src/panels/rules_move.rs new file mode 100644 index 0000000000..de5ccc2efd --- /dev/null +++ b/crates/ui-egui/src/panels/rules_move.rs @@ -0,0 +1,413 @@ +//! The move engine behind reordering rules and groups in the smart-album editor +//! ([`super::rules_editor`]): pure functions on a [`RuleSet`], and nothing else. A row is a path of +//! positions from the top list (`[1, 0]`: the first rule of the second rule's group); a place to +//! drop is a path too: the group's path and the position among its rules, counted before the row +//! leaves its old place. +//! +//! [`judge`], [`move_node`] and [`key_dest`] never trust a path: one that leads nowhere changes +//! nothing. A group left empty by a move goes away, and groups nest at most [`MAX_GROUP_DEPTH`] deep. + +use lightcraft_catalog::{Rule, RuleSet}; + +/// Groups nest at most this deep: the editor offers a group only in a list whose depth is below it +/// (the top list is depth 0). +pub const MAX_GROUP_DEPTH: usize = 3; + +/// Where the arrow keys send a row (↑ ↓ ← →). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Dir { + Up, + Down, + /// ← : out of its group. + Out, + /// → : into the group next to it. + In, +} + +/// Why a move is refused (shown, not just ignored). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Refusal { + /// A group dropped inside itself or something in it. + IntoItself, + /// A group dropped where its rules would nest deeper than [`MAX_GROUP_DEPTH`]. + TooDeep, +} + +/// What a move of one row to a place would do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + Moves, + /// Where it already is, or a place or row that isn't there. + Nothing, + Refused(Refusal), +} + +/// The group (or the top list) at `path`. +fn list_at<'a>(rs: &'a RuleSet, path: &[usize]) -> Option<&'a RuleSet> { + let mut list = rs; + for &i in path { + match list.rules.get(i)? { + Rule::Group { group } => list = group, + Rule::Field { .. } => return None, + } + } + Some(list) +} + +fn list_at_mut<'a>(rs: &'a mut RuleSet, path: &[usize]) -> Option<&'a mut RuleSet> { + let mut list = rs; + for &i in path { + match list.rules.get_mut(i)? { + Rule::Group { group } => list = group, + Rule::Field { .. } => return None, + } + } + Some(list) +} + +/// The rule or group at `path`. +fn node_at<'a>(rs: &'a RuleSet, path: &[usize]) -> Option<&'a Rule> { + let (last, parent) = path.split_last()?; + list_at(rs, parent)?.rules.get(*last) +} + +/// How many lists a rule brings: none for a field rule, one more than its deepest group for a group. +fn height(rule: &Rule) -> usize { + match rule { + Rule::Field { .. } => 0, + Rule::Group { group } => 1 + group.rules.iter().map(height).max().unwrap_or(0), + } +} + +fn remove_at(rs: &mut RuleSet, path: &[usize]) -> Option<Rule> { + let (last, parent) = path.split_last()?; + let list = list_at_mut(rs, parent)?; + (*last < list.rules.len()).then(|| list.rules.remove(*last)) +} + +fn insert_at(rs: &mut RuleSet, path: &[usize], rule: Rule) -> Option<()> { + let (last, parent) = path.split_last()?; + let list = list_at_mut(rs, parent)?; + if *last > list.rules.len() { + return None; + } + list.rules.insert(*last, rule); + Some(()) +} + +/// `path` as it reads once the row at `removed` is gone: a later sibling's position drops by one. +/// `false` when `path` runs through the removed row itself. +fn shift_after_removal(path: &mut [usize], removed: &[usize]) -> bool { + let Some((last, parent)) = removed.split_last() else { return true }; + if path.len() <= parent.len() || !path.starts_with(parent) { + return true; + } + let through = path.len() > removed.len(); + let Some(at) = path.get_mut(parent.len()) else { return true }; + if *at > *last { + *at -= 1; + true + } else { + *at != *last || !through + } +} + +/// What moving the row at `from` to the place `dest` would do. +pub fn judge(rs: &RuleSet, from: &[usize], dest: &[usize]) -> Verdict { + let (Some((from_last, from_parent)), Some((dest_last, dest_parent))) = (from.split_last(), dest.split_last()) else { + return Verdict::Nothing; + }; + let Some(node) = node_at(rs, from) else { return Verdict::Nothing }; + if matches!(node, Rule::Group { .. }) && dest_parent.starts_with(from) { + return Verdict::Refused(Refusal::IntoItself); + } + let Some(list) = list_at(rs, dest_parent) else { return Verdict::Nothing }; + if *dest_last > list.rules.len() { + return Verdict::Nothing; + } + // before itself, or after itself: the same place + if dest_parent == from_parent && (dest_last == from_last || *dest_last == from_last.saturating_add(1)) { + return Verdict::Nothing; + } + // a group may not end up deeper than the editor offers, but one that is already deeper (rules + // written by an agent) can still be moved about at its own depth or higher + let h = height(node); + let (now, then) = (from_parent.len() + h, dest_parent.len() + h); + if h > 0 && then > MAX_GROUP_DEPTH && then > now { + return Verdict::Refused(Refusal::TooDeep); + } + Verdict::Moves +} + +/// Moves the row at `from` to the place `dest` (see the module doc), if [`judge`] allows it, and +/// returns where the row is now. Groups it leaves empty go away. All or nothing: `rs` is only +/// replaced by a finished result. +pub fn move_node(rs: &mut RuleSet, from: &[usize], dest: &[usize]) -> Option<Vec<usize>> { + if judge(rs, from, dest) != Verdict::Moves { + return None; + } + let mut next = rs.clone(); + let node = remove_at(&mut next, from)?; + let mut dest = dest.to_vec(); + if !shift_after_removal(&mut dest, from) { + return None; + } + let mut chain = from.get(..from.len().checked_sub(1)?)?.to_vec(); + // (a group the row is going into stays, however empty it is for now) + while !chain.is_empty() && !(dest.len() > chain.len() && dest.starts_with(&chain)) && list_at(&next, &chain).is_some_and(|l| l.rules.is_empty()) { + remove_at(&mut next, &chain)?; + if !shift_after_removal(&mut dest, &chain) { + return None; + } + chain.pop(); + } + insert_at(&mut next, &dest, node)?; + *rs = next; + Some(dest) +} + +/// The place an arrow key sends the row at `from` to, if there is one (the move may still be +/// refused: [`judge`]). +pub fn key_dest(rs: &RuleSet, from: &[usize], dir: Dir) -> Option<Vec<usize>> { + let (&i, parent) = from.split_last()?; + let list = list_at(rs, parent)?; + // a row that isn't there has no place to go (and `i` is then below `len`, so `i + 1` can't overflow) + list.rules.get(i)?; + let at = |n: usize| parent.iter().copied().chain([n]).collect::<Vec<usize>>(); + match dir { + Dir::Up if i > 0 => Some(at(i - 1)), + // the first of a group: out, to just before the group + Dir::Up => (!parent.is_empty()).then(|| parent.to_vec()), + Dir::Down if i + 1 < list.rules.len() => Some(at(i + 2)), + // the last of a group, and ←: out, to just after the group + Dir::Down | Dir::Out => { + let (&g, outer) = parent.split_last()?; + Some(outer.iter().copied().chain([g + 1]).collect()) + } + Dir::In => { + let above = i.checked_sub(1).and_then(|a| match list.rules.get(a)? { + Rule::Group { group } => Some(at(a).into_iter().chain([group.rules.len()]).collect::<Vec<usize>>()), + Rule::Field { .. } => None, + }); + above.or_else(|| match list.rules.get(i + 1)? { + Rule::Group { .. } => Some(at(i + 1).into_iter().chain([0]).collect()), + Rule::Field { .. } => None, + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{Value, json}; + + fn rs(v: Value) -> RuleSet { + serde_json::from_value(v).unwrap() + } + + /// Each rule is named by its rating, each group by `g` and what is in it: `1 2 (3 4) 5`. + fn shape(rs: &RuleSet) -> String { + let parts: Vec<String> = rs + .rules + .iter() + .map(|r| match r { + Rule::Field { value, .. } => value.to_string(), + Rule::Group { group } => format!("({})", shape(group)), + }) + .collect(); + parts.join(" ") + } + + fn rule(n: u32) -> Value { + json!({"field": "rating", "op": "is", "value": n}) + } + + fn group(rules: Vec<Value>) -> Value { + json!({"group": {"match": "any", "rules": rules}}) + } + + fn set(rules: Vec<Value>) -> RuleSet { + rs(json!({"rules": rules})) + } + + fn moved(rules: Vec<Value>, from: &[usize], dest: &[usize]) -> (String, Option<Vec<usize>>) { + let mut r = set(rules); + let at = move_node(&mut r, from, dest); + (shape(&r), at) + } + + #[test] + fn a_rule_moves_down_and_up_in_its_list() { + let list = || vec![rule(1), rule(2), rule(3), rule(4)]; + assert_eq!(moved(list(), &[0], &[3]), ("2 3 1 4".into(), Some(vec![2])), "before the fourth"); + assert_eq!(moved(list(), &[0], &[4]), ("2 3 4 1".into(), Some(vec![3])), "to the end"); + assert_eq!(moved(list(), &[3], &[0]), ("4 1 2 3".into(), Some(vec![0])), "to the top"); + assert_eq!(moved(list(), &[2], &[1]), ("1 3 2 4".into(), Some(vec![1]))); + } + + #[test] + fn a_move_to_where_the_row_already_is_changes_nothing() { + let list = || vec![rule(1), rule(2), rule(3)]; + for dest in [[1], [2]] { + assert_eq!(judge(&set(list()), &[1], &dest), Verdict::Nothing); + assert_eq!(moved(list(), &[1], &dest), ("1 2 3".into(), None)); + } + } + + #[test] + fn a_rule_moves_into_and_out_of_a_group() { + let list = || vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]; + assert_eq!(moved(list(), &[0], &[1, 1]), ("(2 1 3) 4".into(), Some(vec![0, 1])), "into the group, between its rules"); + assert_eq!(moved(list(), &[2], &[1, 2]), ("1 (2 3 4)".into(), Some(vec![1, 2])), "into its end"); + assert_eq!(moved(list(), &[1, 0], &[0]), ("2 1 (3) 4".into(), Some(vec![0])), "out, to the top"); + assert_eq!(moved(list(), &[1, 1], &[3]), ("1 (2) 4 3".into(), Some(vec![3])), "out, to the end"); + } + + #[test] + fn a_group_left_empty_goes_away() { + let list = || vec![rule(1), group(vec![rule(2)]), rule(3)]; + assert_eq!(moved(list(), &[1, 0], &[0]), ("2 1 3".into(), Some(vec![0])), "the group's only rule goes before it"); + assert_eq!(moved(list(), &[1, 0], &[3]), ("1 3 2".into(), Some(vec![2])), "after everything"); + assert_eq!(moved(list(), &[1, 0], &[1]), ("1 2 3".into(), Some(vec![1])), "to the group's own place"); + // the emptied group is inside another: both go + let deep = vec![rule(1), group(vec![group(vec![rule(2)])]), rule(3)]; + assert_eq!(moved(deep, &[1, 0, 0], &[0]), ("2 1 3".into(), Some(vec![0]))); + // into a group, and the old group is gone: the places after it shift + let two = vec![group(vec![rule(1)]), group(vec![rule(2)])]; + assert_eq!(moved(two, &[0, 0], &[1, 1]), ("(2 1)".into(), Some(vec![0, 1]))); + } + + #[test] + fn a_group_moves_whole_and_never_into_itself() { + let list = || vec![group(vec![rule(1), rule(2)]), rule(3), group(vec![rule(4)])]; + assert_eq!(moved(list(), &[0], &[2]), ("3 (1 2) (4)".into(), Some(vec![1]))); + assert_eq!(moved(list(), &[0], &[3]), ("3 (4) (1 2)".into(), Some(vec![2])), "to the end"); + assert_eq!(moved(list(), &[0], &[2, 1]), ("3 (4 (1 2))".into(), Some(vec![1, 1])), "into the other group"); + for dest in [vec![0, 0], vec![0, 1], vec![0, 2]] { + assert_eq!(judge(&set(list()), &[0], &dest), Verdict::Refused(Refusal::IntoItself), "{dest:?}"); + assert_eq!(moved(list(), &[0], &dest), ("(1 2) 3 (4)".into(), None)); + } + let nested = || vec![group(vec![rule(1), group(vec![rule(2)])])]; + assert_eq!(judge(&set(nested()), &[0], &[0, 1, 0]), Verdict::Refused(Refusal::IntoItself), "inside what is inside it"); + } + + #[test] + fn groups_stay_within_the_depth_the_editor_offers() { + // a group holding a group holding a group: three lists below the top one + let tall = group(vec![group(vec![group(vec![rule(1)])])]); + let list = || vec![tall.clone(), group(vec![rule(2)])]; + // into the second group it would be four deep + assert_eq!(judge(&set(list()), &[0], &[1, 0]), Verdict::Refused(Refusal::TooDeep)); + assert_eq!(moved(list(), &[0], &[1, 0]).1, None); + // but beside it is fine, and so is a rule or a small group at any depth + assert_eq!(judge(&set(list()), &[0], &[2]), Verdict::Moves); + let flat = vec![rule(1), group(vec![group(vec![group(vec![rule(2)])])])]; + assert_eq!(judge(&set(flat.clone()), &[0], &[1, 0, 0, 0]), Verdict::Moves, "a rule can go into the deepest list"); + let small = vec![group(vec![rule(1)]), group(vec![group(vec![group(vec![rule(2)])])])]; + assert_eq!(judge(&set(small.clone()), &[0], &[1, 0, 0, 0]), Verdict::Refused(Refusal::TooDeep), "a group can't"); + assert_eq!(judge(&set(small), &[0], &[1, 0, 0]), Verdict::Moves, "one level up it can"); + } + + #[test] + fn a_group_that_is_already_too_deep_can_still_be_reordered() { + let too_deep = group(vec![group(vec![group(vec![group(vec![rule(1)]), group(vec![rule(2)])])])]); + let r = set(vec![too_deep]); + // the two innermost groups swap places: same depth, allowed + assert_eq!(judge(&r, &[0, 0, 0, 0], &[0, 0, 0, 2]), Verdict::Moves); + // moving one of them deeper is not + assert_eq!(judge(&r, &[0, 0, 0, 0], &[0, 0, 0, 1, 0]), Verdict::Refused(Refusal::TooDeep)); + } + + #[test] + fn paths_that_lead_nowhere_change_nothing() { + let r = || set(vec![rule(1), group(vec![rule(2)])]); + for (from, dest) in [ + (vec![], vec![0]), + (vec![0], vec![]), + (vec![5], vec![0]), + (vec![0], vec![9]), + (vec![0], vec![0, 0]), + (vec![0], vec![5, 0]), + (vec![1, 4], vec![0]), + (vec![usize::MAX], vec![0]), + (vec![0], vec![usize::MAX]), + (vec![1], vec![1, usize::MAX]), + ] { + let mut x = r(); + assert_eq!(move_node(&mut x, &from, &dest), None, "{from:?} -> {dest:?}"); + assert_eq!(x, r()); + } + } + + /// Given a path whose last step is past the end of its list (`usize::MAX` too), when an arrow + /// key asks where the row goes, then there is no place, and no index arithmetic overflows. + #[test] + fn arrow_keys_on_a_path_that_leads_nowhere_find_no_place() { + let r = set(vec![rule(1), group(vec![rule(2)])]); + for from in [vec![2], vec![5], vec![usize::MAX], vec![1, 1], vec![1, usize::MAX]] { + for dir in [Dir::Up, Dir::Down, Dir::Out, Dir::In] { + assert_eq!(key_dest(&r, &from, dir), None, "{from:?} {dir:?}"); + } + } + } + + #[test] + fn arrow_keys_move_a_row_one_place() { + let list = || vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]; + let key = |from: &[usize], dir| { + let mut r = set(list()); + let at = key_dest(&r, from, dir).and_then(|d| move_node(&mut r, from, &d)); + (shape(&r), at) + }; + assert_eq!(key(&[0], Dir::Down), ("(2 3) 1 4".into(), Some(vec![1])), "a group is passed, not entered"); + assert_eq!(key(&[2], Dir::Up), ("1 4 (2 3)".into(), Some(vec![1]))); + assert_eq!(key(&[0], Dir::Up), ("1 (2 3) 4".into(), None), "the top stays"); + assert_eq!(key(&[2], Dir::Down), ("1 (2 3) 4".into(), None), "the end stays"); + // at a group's ends, ↑ ↓ carry the row out of it + assert_eq!(key(&[1, 0], Dir::Up), ("1 2 (3) 4".into(), Some(vec![1]))); + assert_eq!(key(&[1, 1], Dir::Down), ("1 (2) 3 4".into(), Some(vec![2]))); + assert_eq!(key(&[1, 0], Dir::Down), ("1 (3 2) 4".into(), Some(vec![1, 1])), "inside, one place down"); + // ← : out, just after the group; at the top level nothing + assert_eq!(key(&[1, 0], Dir::Out), ("1 (3) 2 4".into(), Some(vec![2]))); + assert_eq!(key(&[0], Dir::Out), ("1 (2 3) 4".into(), None)); + // → : into the group above (its end) or below (its start) + assert_eq!(key(&[2], Dir::In), ("1 (2 3 4)".into(), Some(vec![1, 2]))); + assert_eq!(key(&[0], Dir::In), ("(1 2 3) 4".into(), Some(vec![0, 0]))); + let lone = || vec![rule(1), rule(2)]; + let mut r = set(lone()); + assert_eq!(key_dest(&r, &[0], Dir::In), None, "no group beside it"); + assert_eq!(move_node(&mut r, &[0], &[0]), None); + } + + #[test] + fn a_rows_only_rule_going_out_takes_its_group_with_it() { + let list = || vec![group(vec![rule(1)]), rule(2)]; + let mut r = set(list()); + let at = key_dest(&r, &[0, 0], Dir::Down).and_then(|d| move_node(&mut r, &[0, 0], &d)); + assert_eq!((shape(&r), at), ("1 2".into(), Some(vec![0])), "the group would be empty"); + let mut r = set(list()); + let at = key_dest(&r, &[0, 0], Dir::Out).and_then(|d| move_node(&mut r, &[0, 0], &d)); + assert_eq!((shape(&r), at), ("1 2".into(), Some(vec![0])), "← too: just after a group that is gone"); + } + + #[test] + fn a_row_leaving_nested_groups_may_leave_the_group_it_is_going_to_empty() { + let mut r = set(vec![group(vec![group(vec![rule(1)])])]); + assert_eq!(move_node(&mut r, &[0, 0, 0], &[0, 0]), Some(vec![0, 0])); + assert_eq!(shape(&r), "(1)"); + let mut r = set(vec![group(vec![group(vec![rule(1)])])]); + let dest = key_dest(&r, &[0, 0, 0], Dir::Out).unwrap(); + assert!(move_node(&mut r, &[0, 0, 0], &dest).is_some()); + assert_eq!(shape(&r), "(1)"); + } + + #[test] + fn arrow_keys_respect_the_depth_limit() { + let tall = group(vec![group(vec![group(vec![rule(1)])])]); + let r = set(vec![tall.clone(), group(vec![rule(2)])]); + // → would put it in the group below: four deep + let dest = key_dest(&r, &[0], Dir::In).unwrap(); + assert_eq!(judge(&r, &[0], &dest), Verdict::Refused(Refusal::TooDeep)); + } +} diff --git a/crates/ui-egui/src/panels/second.rs b/crates/ui-egui/src/panels/second.rs index 79aa31d1dc..cbdaa2d738 100644 --- a/crates/ui-egui/src/panels/second.rs +++ b/crates/ui-egui/src/panels/second.rs @@ -6,24 +6,31 @@ use egui::{Color32, Rect, pos2, vec2}; use crate::LightcraftApp; use crate::render::Slot; +/// Show the optional second window: an immediate viewport titled "LightCraft — Second Window" +/// whose body draws the active photo fitted. Closing a real window turns the option off; +/// embedded web and headless hosts get a floating window instead. pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if !app.ui.second_window { return; } let vid = egui::ViewportId::from_hash_of("lightcraft-second-window"); let builder = egui::ViewportBuilder::default().with_title("LightCraft — Second Window").with_inner_size([960.0, 640.0]); - ctx.show_viewport_immediate(vid, builder, |ctx, class| { + ctx.show_viewport_immediate(vid, builder, |ui, class| { + // 0.37 passes the viewport's root `Ui` (not a `Context`). Do not enter `root_ui` from it. // (without native windows — web, headless — egui wraps this in a floating window) - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(Color32::BLACK)).show(ctx, |ui| body(app, ui)); - if class != egui::ViewportClass::EmbeddedWindow && ctx.input(|i| i.viewport().close_requested()) { + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(Color32::BLACK)).show(ui, |ui| body(app, ui)); + if class != egui::ViewportClass::EmbeddedWindow && ui.ctx().input(|i| i.viewport().close_requested()) { app.ui.second_window = false; } }); } +/// Draw the second window's content: register `view:secondWindow`, request a loupe render sized +/// for the window (each edge clamped to 64 through the texture-side limit) and paint the active +/// photo fitted, or "No photo selected". fn body(app: &mut LightcraftApp, ui: &mut egui::Ui) { let area = ui.available_rect_before_wrap(); - crate::widgets::register(ui.ctx(), "view:secondWindow", area); + crate::widgets::register(ui, "view:secondWindow", area); ui.allocate_rect(area, egui::Sense::hover()); let Some(id) = app.session.active() else { ui.painter().text( diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index 2f844f4ae9..338d55c009 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -3,7 +3,8 @@ //! //! Changes apply immediately (no OK/Cancel). Where they are stored: //! - **app settings** ([`crate::state::AppSettings`]: startup view, delete confirmation, GPU, -//! preview size, filmstrip/grid badges, last library, monitor profile) and Auto Advance live in +//! preview size, filmstrip/grid badges, last library, monitor profile, whether Import Lightroom +//! Catalog… asks where a catalog goes) and Auto Advance live in //! the UI state, //! saved by the host in its config folder (`ui.json`); //! - **library settings** (import defaults, XMP sidecars, thumbnail cache size, slideshow @@ -36,12 +37,52 @@ const CACHE_SIZES: [u32; 5] = [512, 1024, 2048, 4096, 8192]; const LABEL_W: f32 = 150.0; -/// The dialog body for `tab` (the tab bar switches `tab`). -pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String) { +/// The page of `tab` (the tab bar in [`window`] switches `tab`). +pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &str) { let t = Tokens::get(ui.ctx()); - ui.set_width((ui.ctx().content_rect().width() - 64.0).clamp(240.0, 560.0)); + match tab { + "import" => import_tab(app, ui, &t), + "performance" => performance_tab(app, ui, &t), + "display" => display_tab(app, ui, &t), + "interface" => interface_tab(app, ui, &t), + "slideshow" => slideshow_tab(app, ui, &t, true), + "faces" => super::faces::settings_tab(app, ui, &t), + "denoise" => super::denoise::settings_tab(app, ui, &t), + _ => general_tab(app, ui, &t), + } +} + +/// The widest the Settings window's content gets, and the tallest its pages get: the window is +/// one size on every tab, so it stays where it is as the tabs are gone through. +const PAGE_SIZE: egui::Vec2 = egui::vec2(560.0, 640.0); + +/// The least room in which a page scrolls by itself. In a window with less (far below the +/// desktop minimum), the tabs and the page scroll together in the dialog's own scroll area. +const PAGE_MIN_HEIGHT: f32 = 120.0; + +/// The share of the page's room the pinned slide preview of the Slideshow tab takes, when the page +/// has more room than it needs to keep [`PAGE_MIN_HEIGHT`] for itself. +const PINNED_PREVIEW_SHARE: f32 = 0.4; + +/// What the preview's heading, the one-line hint under the slide, its Photo / Intro / Ending +/// choice and the rule under it take around the slide (at the default spacing, about 82 pt). +const PREVIEW_CHROME: f32 = 82.0; + +/// The Settings window's content: the tab bar, which stays put, above the page of `tab` +/// ([`body`]), which scrolls when it is taller than the room for it, with a scroll handle that +/// shows without the pointer on it. `max_height` is the room the app window leaves for both: the +/// two together never take more, so the scroll area every dialog is drawn in has nothing to +/// scroll (but for a window with less than [`PAGE_MIN_HEIGHT`] for the page, where that area +/// scrolls the two together). Every page gets the same room whatever it holds (but for the pinned +/// preview of Slideshow), and each keeps a scroll position of its own. Nothing here is wider than the window from 640 pt of app window +/// up: a row's controls wrap ([`row`]) and paths are shortened ([`path_label`]). +/// On Slideshow the slide preview is pinned between the tab bar and the page (where the room +/// allows), and comes off that page's room. +pub fn window(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String, max_height: f32) { + ui.set_width((ui.ctx().content_rect().width() - 64.0).clamp(240.0, PAGE_SIZE.x)); + let top = ui.cursor().top(); ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; + ui.spacing_mut().item_spacing = egui::vec2(4.0, 4.0); for (id, label) in TABS { if crate::widgets::text_button(ui, &format!("settingsTab-{id}"), label, tab == id).clicked() { *tab = id.to_string(); @@ -49,17 +90,99 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String) { } }); ui.separator(); - ui.add_space(2.0); - match tab.as_str() { - "import" => import_tab(app, ui, &t), - "performance" => performance_tab(app, ui, &t), - "display" => display_tab(app, ui, &t), - "interface" => interface_tab(app, ui, &t), - "slideshow" => slideshow_tab(app, ui, &t), - "faces" => super::faces::settings_tab(app, ui, &t), - "denoise" => super::denoise::settings_tab(app, ui, &t), - _ => general_tab(app, ui, &t), + // (a point less than the room left, so rounding never makes the dialog's own scroll area scroll) + let room = max_height - (ui.cursor().top() - top) - 1.0; + if room < PAGE_MIN_HEIGHT { + body(app, ui, tab.as_str()); + register(ui, "settings:page", ui.min_rect()); + return; } + let mut height = room.min(PAGE_SIZE.y); + // The slide preview stays above the page on Slideshow: hovering a template in the Template + // Browser previews it there, so it has to stay in view however far down the templates are + // scrolled to. With its heading and choice it takes [`PINNED_PREVIEW_SHARE`] of the room + // (at least the least tall slide); where that leaves less than [`PAGE_MIN_HEIGHT`] for the + // page, it scrolls with the page instead (as in the short window above). + let mut pinned = false; + if tab == "slideshow" { + let slide_h = (height * PINNED_PREVIEW_SHARE - PREVIEW_CHROME).max(super::slide_layout::PREVIEW_MIN_H); + if height - (slide_h + PREVIEW_CHROME) >= PAGE_MIN_HEIGHT { + let before = ui.cursor().top(); + super::slide_layout::preview(app, ui, &Tokens::get(ui.ctx()), slide_h); + ui.add_space(2.0); + ui.separator(); + height = (height - (ui.cursor().top() - before)).max(PAGE_MIN_HEIGHT); + pinned = true; + } + } + // A page that goes on below shows its scroll handle all the time: without it, a page a line + // or two too long looks cut off, not scrollable. + ui.spacing_mut().scroll.dormant_handle_opacity = 0.6; + let page = egui::ScrollArea::vertical() + .id_salt(("settings-page", tab.as_str())) + .max_height(height) + .min_scrolled_height(height) + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_space(2.0); + if pinned { + slideshow_tab(app, ui, &Tokens::get(ui.ctx()), false); + } else { + body(app, ui, tab.as_str()); + } + // (what the page took: wider than the room for it would mean a control is cut off) + register(ui, "settings:page", ui.min_rect()); + }); + register(ui, "settings:pageRoom", page.inner_rect); +} + +/// `path` shortened to fit `max` (as `width` measures it) by dropping leading folders, after +/// either kind of separator, so that its end stays (`…/Pictures/Library`, +/// `…\Pictures\Library`): the end says which folder it is. A last folder too long by itself +/// loses its end ([`crate::widgets::elide_head`]). +fn elide_path(path: &str, max: f32, width: impl Fn(&str) -> f32) -> String { + if width(path) <= max { + return path.to_string(); + } + // (a separator at the very end is not where a name starts: `…/` alone would say nothing) + let end = path.trim_end_matches(['/', '\\']).len(); + let mut rest = path; + while let Some(i) = rest.find(['/', '\\']).filter(|i| path.len() - rest.len() + i + 1 < end) { + let separator = if rest.get(i..).is_some_and(|r| r.starts_with('\\')) { '\\' } else { '/' }; + rest = rest.get(i + 1..).unwrap_or(""); + let shorter = format!("…{separator}{rest}"); + if width(&shorter) <= max { + return shorter; + } + } + let name = rest.trim_end_matches(['/', '\\']); + // (nothing but separators: never an empty label) + if name.is_empty() { "…".to_string() } else { crate::widgets::elide_head(name, max, width) } +} + +/// A folder or file path on one line in the room left in its row (`text:{id}`): shortened from +/// the front when it is too long ([`elide_path`]), with all of it in a tooltip then. `after` is +/// the width of what follows it on the line (a button, a note) and its spacing: the path leaves +/// that room, so those never wrap onto a second line. +fn path_label(ui: &mut egui::Ui, id: &str, path: &str, font: egui::FontId, color: egui::Color32, after: f32) { + let shown = + elide_path(path, (ui.available_width() - after).max(0.0), |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), color).size().x); + // (`truncate` is the last resort, for a room narrower than "…") + let r = ui.add(egui::Label::new(RichText::new(&shown).font(font).color(color)).truncate().show_tooltip_when_elided(false)); + register(ui, format!("text:{id}"), r.rect); + if shown != path { + r.on_hover_text(path); + } +} + +/// The width of `text` in the style `style`, and the gap before it: what a label takes in a row. +fn label_width(ui: &egui::Ui, text: &str, style: egui::TextStyle) -> f32 { + ui.painter().layout_no_wrap(text.to_string(), style.resolve(ui.style()), egui::Color32::WHITE).size().x + ui.spacing().item_spacing.x +} + +/// The same for a button, which has padding either side of its text. +fn button_width(ui: &egui::Ui, text: &str) -> f32 { + label_width(ui, text, egui::TextStyle::Button) + 2.0 * ui.spacing().button_padding.x } pub(super) fn heading(ui: &mut egui::Ui, t: &Tokens, text: &str) { @@ -71,9 +194,17 @@ pub(super) fn row<R>(ui: &mut egui::Ui, t: &Tokens, label: &str, add: impl FnOnc ui.horizontal(|ui| { ui.allocate_ui_with_layout(egui::vec2(LABEL_W, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.set_min_width(LABEL_W); - ui.label(RichText::new(crate::i18n::tr(label)).color(t.text_label)); + // (a label longer than its column wraps in it; it does not push the controls along) + ui.add(egui::Label::new(RichText::new(crate::i18n::tr(label)).color(t.text_label)).wrap()); }); - add(ui) + // The controls wrap in the room beside the label, each further line starting under the + // first control, so a row with many choices grows down and never widens the window. + let wrapped = egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true); + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 24.0), wrapped, |ui| { + ui.spacing_mut().item_spacing.y = 4.0; + add(ui) + }) + .inner }) .inner } @@ -85,7 +216,7 @@ pub(super) fn hint(ui: &mut egui::Ui, t: &Tokens, text: &str) { /// A checkbox addressable as `check:{id}`; true when toggled. pub(super) fn check(ui: &mut egui::Ui, id: &str, value: &mut bool, label: &str) -> bool { let r = ui.checkbox(value, crate::i18n::tr(label)); - register(ui.ctx(), format!("check:{id}"), r.rect); + register(ui, format!("check:{id}"), r.rect); r.changed() } @@ -119,17 +250,17 @@ fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { None => crate::i18n::tr("In memory — nothing is saved").to_string(), }; row(ui, t, crate::i18n::tr("Location"), |ui| { - ui.label(RichText::new(location).color(t.text)); + path_label(ui, "settingsLocation", &location, egui::TextStyle::Body.resolve(ui.style()), t.text, 0.0); }); row(ui, t, "", |ui| { let can = app.services.pick_folder.is_some(); let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Open Library…"))); - register(ui.ctx(), "button:settingsOpenLibrary", r.rect); + register(ui, "button:settingsOpenLibrary", r.rect); if r.clicked() { let _ = app.run("app.openLibrary", json!({})); } let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("New Library…"))); - register(ui.ctx(), "button:settingsNewLibrary", r.rect); + register(ui, "button:settingsNewLibrary", r.rect); if r.clicked() { let _ = app.run("app.newLibrary", json!({})); } @@ -137,12 +268,36 @@ fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { hint(ui, t, crate::i18n::tr("not available here")); } }); + // where libraries are folders to choose from (not in the browser, which keeps one) + if app.services.pick_folder.is_some() { + use crate::state::LaunchLibrary; + row(ui, t, crate::i18n::tr("At launch"), |ui| { + choices( + ui, + "settingsAtLaunch", + &[(LaunchLibrary::Last, "Open the last library"), (LaunchLibrary::Ask, "Ask me")], + &mut app.ui.settings.at_launch, + ); + }); + hint(ui, t, crate::i18n::tr("Ask me lists your recent libraries at launch. Holding Alt (Option on a Mac) as the window appears asks once.")); + } + // File ▸ Import Lightroom Catalog… (#2672): the window that asks where a catalog goes, or not + ui.label(RichText::new(crate::i18n::tr("When importing a Lightroom catalog")).color(t.text_label)); + row(ui, t, "", |ui| { + use crate::state::LightroomImport; + choices( + ui, + "settingsLightroomImport", + &[(LightroomImport::Ask, "Ask where to import it"), (LightroomImport::AlwaysMerge, "Always merge into the open library")], + &mut app.ui.settings.lightroom_import, + ); + }); heading(ui, t, crate::i18n::tr("Startup")); row(ui, t, crate::i18n::tr("Open in"), |ui| { choices( ui, "settingsStartup", - &[(StartupView::Last, "Last view"), (StartupView::Grid, "Photo Grid"), (StartupView::Detail, "Detail")], + &[(StartupView::Last, "Last view"), (StartupView::Grid, "Photo Grid"), (StartupView::Detail, "Detail View")], &mut app.ui.settings.startup_view, ); }); @@ -150,6 +305,8 @@ fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { check(ui, "settings.autoAdvance", &mut app.ui.auto_advance, "Auto Advance: move to the next photo after rating or flagging"); check(ui, "settings.confirmDelete", &mut app.ui.settings.confirm_delete, "Confirm before moving photos to Recently Deleted"); check(ui, "settings.askBeforeMove", &mut app.ui.settings.ask_before_move, "Confirm before moving photos to another folder on disk"); + heading(ui, t, crate::i18n::tr("Dialogs")); + check(ui, "settings.closeDialogsOutside", &mut app.ui.settings.close_dialogs_outside, "Close a dialog by clicking outside it"); heading(ui, t, crate::i18n::tr("External Editing")); row(ui, t, crate::i18n::tr("PhotoCraft"), |ui| { crate::text_field::TextField::singleline("field:photocraftPath", &mut app.ui.settings.photocraft_path) @@ -203,7 +360,7 @@ fn edit_file_rows(ui: &mut egui::Ui, t: &Tokens, id: &str, file: &mut crate::sta // -------------------------------------------------------------------------------------- Import /// A preset picker: `None` = `none_label`. Returns the new choice when it changed. -fn preset_combo(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, current: Option<&str>, none_label: &str) -> Option<Option<String>> { +fn preset_combo(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, label: &str, current: Option<&str>, none_label: &str) -> Option<Option<String>> { let name = |pid: &str| { app.session .presets @@ -222,7 +379,8 @@ fn preset_combo(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, current: Optio out = Some(Some(pid)); } }); - register(ui.ctx(), format!("combo:{id}"), r.response.rect); + crate::widgets::name_combo(&r.response, label); + register(ui, format!("combo:{id}"), r.response.rect); out.filter(|v| v.as_deref() != current) } @@ -246,7 +404,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("Raw defaults")); hint(ui, t, crate::i18n::tr("Settings new raw photos start from. Changing them doesn't touch photos already in the library.")); row(ui, t, crate::i18n::tr("Raw photos"), |ui| { - if let Some(v) = preset_combo(app, ui, "settingsRawPreset", d.raw_preset.as_deref(), "LightCraft Default") { + if let Some(v) = preset_combo(app, ui, "settingsRawPreset", crate::i18n::tr("Raw default"), d.raw_preset.as_deref(), "LightCraft Default") { let _ = app.run("library.preferences", json!({"import": {"rawPreset": v}})); } }); @@ -295,7 +453,8 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { pick = Some(json!({"camera": cam, "preset": pid})); } }); - register(ui.ctx(), format!("combo:{id}"), r.response.rect); + crate::widgets::name_combo(&r.response, crate::i18n::tr("Camera")); + register(ui, format!("combo:{id}"), r.response.rect); if let Some(c) = pick { let _ = app.run("library.preferences", json!({"camera": c})); } @@ -305,7 +464,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } heading(ui, t, crate::i18n::tr("Other images (JPEG, PNG, TIFF, HEIC…)")); row(ui, t, crate::i18n::tr("Non-raw photos"), |ui| { - if let Some(v) = preset_combo(app, ui, "settingsOtherPreset", d.other_preset.as_deref(), "None") { + if let Some(v) = preset_combo(app, ui, "settingsOtherPreset", crate::i18n::tr("Other preset"), d.other_preset.as_deref(), "None") { let _ = app.run("library.preferences", json!({"import": {"otherPreset": v}})); } }); @@ -315,10 +474,10 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { [("copyright", "Copyright", "© 2026 Your Name", d.copyright.clone()), ("creator", "Creator", "Your Name", d.creator.clone())] { row(ui, t, label, |ui| { - let id = egui::Id::new(("settingsMeta", key)); + let id = egui::Id::unique(("settingsMeta", key)); let mut text: String = ui.data(|m| m.get_temp(id)).unwrap_or(value.clone()); let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(hint_text).desired_width(240.0)); - register(ui.ctx(), format!("field:settings.{key}"), r.rect); + register(ui, format!("field:settings.{key}"), r.rect); if r.lost_focus() && text.trim() != value { let _ = app.run("library.preferences", json!({"import": {key: text.trim()}})); } @@ -346,7 +505,8 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } }); - register(ui.ctx(), "combo:settingsMetaPreset", r.response.rect); + crate::widgets::name_combo(&r.response, crate::i18n::tr("Metadata preset")); + register(ui, "combo:settingsMetaPreset", r.response.rect); if let Some(n) = pick { let _ = app.run("library.preferences", json!({"import": {"metadataPreset": n}})); } @@ -366,6 +526,8 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } }); if !cfg!(target_arch = "wasm32") { + heading(ui, t, crate::i18n::tr("Dropped Files")); + check(ui, "settings.importDropped", &mut app.ui.settings.import_dropped_directly, "Import dropped files without review"); heading(ui, t, crate::i18n::tr("Cameras and Cards")); let mut on_card = d.show_on_card; if check(ui, "settings.importOnCard", &mut on_card, "Show the import review when a camera or card is connected") { @@ -374,10 +536,20 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("Auto Import")); hint(ui, t, crate::i18n::tr("Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.")); row(ui, t, crate::i18n::tr("Watched folder"), |ui| { - ui.label(RichText::new(d.auto_folder.clone().unwrap_or_else(|| crate::i18n::tr("Off").into())).color(t.text)); + match &d.auto_folder { + Some(folder) => path_label( + ui, + "settingsAutoFolder", + folder, + egui::TextStyle::Body.resolve(ui.style()), + t.text, + button_width(ui, crate::i18n::tr("Choose…")) + button_width(ui, crate::i18n::tr("Turn Off")), + ), + None => drop(ui.label(RichText::new(crate::i18n::tr("Off")).color(t.text))), + } let can = app.services.pick_folder.is_some(); let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Choose…"))); - register(ui.ctx(), "button:settingsAutoFolder", r.rect); + register(ui, "button:settingsAutoFolder", r.rect); if r.clicked() && let Some(f) = app.services.pick_folder.as_mut().and_then(|f| f()) && let Err(e) = app.run("library.autoImport", json!({"folder": f})) @@ -396,7 +568,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } }); row(ui, t, crate::i18n::tr("Album"), |ui| { - let id = egui::Id::new("auto-album"); + let id = egui::Id::unique("auto-album"); let mut name = ui.data(|m| m.get_temp::<String>(id)).unwrap_or_else(|| d.auto_album.clone().unwrap_or_default()); let r = ui.add(egui::TextEdit::singleline(&mut name).hint_text(crate::i18n::tr("None")).desired_width(180.0)); if r.lost_focus() { @@ -463,7 +635,7 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { .color(t.text), ); let r = ui.button(crate::i18n::tr("Clear Cache")); - register(ui.ctx(), "button:settingsClearCache", r.rect); + register(ui, "button:settingsClearCache", r.rect); if r.clicked() { let _ = app.run("library.clearPreviews", json!({})); } @@ -492,7 +664,7 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { #[cfg(not(target_arch = "wasm32"))] fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { // listing a big folder every frame would be slow: refresh every 2 s and after a change - let cache = egui::Id::new("smart-location"); + let cache = egui::Id::unique("smart-location"); let now = ui.input(|i| i.time); let loc: Value = match ui.data(|d| d.get_temp::<(f64, Value)>(cache)) { Some((at, v)) if now - at < 2.0 => v, @@ -510,8 +682,18 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let available = loc["available"].as_bool().unwrap_or(true); let custom = loc["custom"].as_bool().unwrap_or(false); row(ui, t, crate::i18n::tr("Folder"), |ui| { - let text = format!("{path}{}", if custom { "" } else { " (library default)" }); - ui.add(egui::Label::new(RichText::new(text.clone()).color(if available { t.text } else { t.reject })).truncate()).on_hover_text(text); + path_label( + ui, + "settingsSmartFolder", + &path, + egui::TextStyle::Body.resolve(ui.style()), + if available { t.text } else { t.reject }, + if custom { 0.0 } else { label_width(ui, "(library default)", egui::TextStyle::Body) }, + ); + if !custom { + let r = ui.label(RichText::new("(library default)").color(t.text)); + register(ui, "text:settingsSmartDefault", r.rect); + } }); let (count, bytes) = (loc["count"].as_u64().unwrap_or(0), loc["bytes"].as_u64().unwrap_or(0)); if available { @@ -535,7 +717,7 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ); } // what happens to the previews already built when the folder changes - let mode_id = egui::Id::new("smart-existing"); + let mode_id = egui::Id::unique("smart-existing"); let mut mode: u8 = ui.data(|d| d.get_temp(mode_id)).unwrap_or(0); if count > 0 { row(ui, t, crate::i18n::tr("Existing previews"), |ui| { @@ -550,7 +732,7 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ui.add_space(LABEL_W); if app.services.pick_folder.is_some() { let r = ui.button(crate::i18n::tr("Choose Folder…")); - register(ui.ctx(), "button:settingsSmartChoose", r.rect); + register(ui, "button:settingsSmartChoose", r.rect); if r.clicked() && let Some(dir) = app.services.pick_folder.as_mut().and_then(|f| f()) { @@ -558,7 +740,7 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } let r = ui.add_enabled(custom, egui::Button::new(crate::i18n::tr("Use Library Folder"))); - register(ui.ctx(), "button:settingsSmartReset", r.rect); + register(ui, "button:settingsSmartReset", r.rect); if r.clicked() { result = Some(app.run("library.smartPreviewsLocation", json!({"reset": true, "existing": existing}))); } @@ -603,7 +785,7 @@ fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, "", |ui| { let can = app.services.pick_display_profile.is_some(); let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Choose Profile…"))); - register(ui.ctx(), "button:settingsDisplayProfile", r.rect); + register(ui, "button:settingsDisplayProfile", r.rect); if r.clicked() && let Some(path) = app.services.pick_display_profile.as_mut().and_then(|pick| pick().into_iter().next()) { @@ -612,7 +794,7 @@ fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { // with no profile chosen, previews follow the screen's own profile where the host knows it let none = if app.services.screen_profile.is_some() { crate::i18n::tr("Use Screen Profile") } else { crate::i18n::tr("Use sRGB") }; let r = ui.add_enabled(!app.ui.settings.display_profile.is_empty(), egui::Button::new(none)); - register(ui.ctx(), "button:settingsDisplayProfileNone", r.rect); + register(ui, "button:settingsDisplayProfileNone", r.rect); if r.clicked() { app.ui.settings.display_profile.clear(); } @@ -627,7 +809,7 @@ fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let info = d.describe(); if !screen { row(ui, t, crate::i18n::tr("File"), |ui| { - ui.label(RichText::new(&d.path).size(11.0).color(t.text_dim)); + path_label(ui, "settingsDisplayFile", &d.path, egui::FontId::proportional(11.0), t.text_dim, 0.0); }); } row(ui, t, crate::i18n::tr("Type"), |ui| { @@ -681,7 +863,7 @@ fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { t, crate::i18n::tr("Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened."), ); - heading(ui, t, crate::i18n::tr("Detail")); + heading(ui, t, crate::i18n::tr("Detail View")); check(ui, "settings.navigator", &mut app.ui.navigator, "Show the Navigator while zoomed in"); row(ui, t, crate::i18n::tr("Info overlay"), |ui| { use crate::state::InfoOverlay as I; @@ -691,8 +873,9 @@ fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } /// View ▸ View Options (⌘J), Lightroom Classic's Loupe View tab: whether the info overlay shows and -/// which, and the three lines each of Info 1 and Info 2 shows (`view.viewOptions`). Changes apply -/// as they are made. +/// which, the three lines each of Info 1 and Info 2 shows, which of them shows briefly when the +/// photo changes, and whether the loupe shows its loading and rendering message +/// (`view.viewOptions`). Changes apply as they are made. pub(super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use crate::state::{InfoOverlay as I, LoupeInfo, LoupeInfoField as F}; heading(ui, t, crate::i18n::tr("Loupe View")); @@ -714,20 +897,32 @@ pub(super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Token for f in F::ALL { let key = serde_json::to_value(f).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); let r = ui.selectable_label(line == f, crate::i18n::tr(f.label())); - register(ui.ctx(), format!("button:{id}-{key}"), r.rect); + register(ui, format!("button:{id}-{key}"), r.rect); if r.clicked() { *line = *f; } } }); - register(ui.ctx(), format!("combo:{id}"), r.response.rect); + crate::widgets::name_combo( + &r.response, + &crate::i18n::tr_format!("{title}: {line}", title = crate::i18n::tr(title), line = crate::i18n::tr(line.label())), + ); + register(ui, format!("combo:{id}"), r.response.rect); } let r = ui.add_enabled(*lines != defaults, egui::Button::new(crate::i18n::tr("Use Defaults"))); - register(ui.ctx(), format!("button:viewOptionsDefaults{n}"), r.rect); + register(ui, format!("button:viewOptionsDefaults{n}"), r.rect); if r.clicked() { *lines = defaults; } + // one Info at most shows briefly: ticking one unticks the other + let info = if n == 1 { I::Basic } else { I::Exposure }; + let mut briefly = app.ui.settings.loupe_info.briefly == info; + if check(ui, &format!("viewOptions.briefly{n}"), &mut briefly, "Show briefly when photo changes") { + app.ui.settings.loupe_info.briefly = if briefly { info } else { I::Off }; + } } + heading(ui, t, crate::i18n::tr("General")); + check(ui, "viewOptions.loupeMessages", &mut app.ui.settings.loupe_messages, "Show message when loading or rendering photos"); } // ----------------------------------------------------------------------------------- Slideshow @@ -737,7 +932,7 @@ pub(super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Token fn duration_slider(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, key: &str, value: f64, range: std::ops::RangeInclusive<f64>) { let mut v = value; let r = ui.add(egui::Slider::new(&mut v, range).logarithmic(key == "slideDuration").suffix(" s").max_decimals(1)); - register(ui.ctx(), format!("slider:{id}"), r.rect); + register(ui, format!("slider:{id}"), r.rect); if r.changed() && let Ok(next) = app.session.slideshow.merged(&json!({ key: v })) { @@ -748,51 +943,39 @@ fn duration_slider(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, key: &s } } -/// Width of the Slideshow tab's settings column (the slide preview is beside it). -const SLIDESHOW_COLUMN_W: f32 = 480.0; - -fn slideshow_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { - // the settings scroll on the left, the composed slide stays in view on the right - let top_down = egui::Layout::top_down(egui::Align::Min); - // as tall as the window allows (the dialog's title, tabs and Close button take ~260 pt) - let tall = (ui.ctx().content_rect().height() - 260.0).clamp(300.0, 760.0); - ui.horizontal_top(|ui| { - ui.allocate_ui_with_layout(egui::vec2(SLIDESHOW_COLUMN_W, tall), top_down, |ui| { - ui.set_width(SLIDESHOW_COLUMN_W); - egui::ScrollArea::vertical().id_salt("settingsSlideshowScroll").max_height(tall).auto_shrink([false, true]).show(ui, |ui| { - super::slide_templates::section(app, ui, t); - ui.add_space(6.0); - playback_section(app, ui, t); - ui.add_space(6.0); - super::slide_layout::sections(app, ui, t); - ui.add_space(6.0); - super::slide_overlays::sections(app, ui, t); - ui.add_space(6.0); - super::slide_titles::sections(app, ui, t); - ui.add_space(6.0); - export_section(app, ui, t); - }); - }); - ui.add_space(12.0); - ui.allocate_ui_with_layout(egui::vec2(super::slide_layout::PREVIEW_W, tall), top_down, |ui| { - ui.set_width(super::slide_layout::PREVIEW_W); - super::slide_layout::preview(app, ui, t) - }); - }); +/// The Slideshow tab: the slide preview, then the settings, in one column the width of the page +/// (the page scrolls; a column beside the preview would be wider than the window). Without +/// `with_preview` the preview is left out: [`window`] has pinned it above the page. +fn slideshow_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, with_preview: bool) { + if with_preview { + super::slide_layout::preview(app, ui, t, f32::INFINITY); + ui.add_space(6.0); + } + super::slide_templates::section(app, ui, t); + ui.add_space(6.0); + playback_section(app, ui, t); + ui.add_space(6.0); + super::slide_layout::sections(app, ui, t); + ui.add_space(6.0); + super::slide_overlays::sections(app, ui, t); + ui.add_space(6.0); + super::slide_titles::sections(app, ui, t); + ui.add_space(6.0); + export_section(app, ui, t); } /// Export: PDF, JPEG sequence or video of the slideshow (View ▸ Export Slideshow…). fn export_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("Export")); let running = app.session.slideshow_export.as_ref().is_some_and(|r| r.running()); - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { for (id, label, format) in [ ("slideshowExportPdf", "Export PDF…", "pdf"), ("slideshowExportJpeg", "Export JPEG…", "jpeg"), ("slideshowExportVideo", "Export Video…", "video"), ] { let r = ui.add_enabled(!running, egui::Button::new(crate::i18n::tr(label))); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); if r.clicked() { let _ = app.run("dialog.slideshowExport", json!({"format": format})); } @@ -805,6 +988,11 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::slideshow::{FADE_MAX, SLIDE_MAX, SLIDE_MIN}; heading(ui, t, crate::i18n::tr("Playback")); let s = app.session.slideshow.clone(); + let mut v = s.manual; + if check(ui, "settings.slideshowManual", &mut v, "Manual slideshow") { + let _ = app.run("slideshow.playback", json!({"manual": v})); + } + hint(ui, t, crate::i18n::tr("A manual slideshow shows each slide until → or ← changes it. Exports still use the slide duration.")); row(ui, t, crate::i18n::tr("Slide duration"), |ui| { duration_slider(app, ui, "slideshowSlide", "slideDuration", s.slide_duration, SLIDE_MIN..=SLIDE_MAX) }); @@ -840,7 +1028,7 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { && let Some(mut c) = s.fade_color { let r = egui::color_picker::color_edit_button_srgb(ui, &mut c); - register(ui.ctx(), "button:slideshowFadeColor", r.rect); + register(ui, "button:slideshowFadeColor", r.rect); if r.changed() { let _ = app.run("slideshow.playback", json!({"fadeColor": c})); } @@ -934,7 +1122,7 @@ fn theme_card<V: PartialEq + Copy>( let hovered = ui.ctx().pointer_hover_pos().is_some_and(|p| row.contains(p)); ui.horizontal(|ui| { let r = ui.radio_value(value, *v, crate::i18n::tr(kind.label())); - register(ui.ctx(), format!("radio:theme-{}", kind.id()), r.rect); + register(ui, format!("radio:theme-{}", kind.id()), r.rect); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let favorite = favorites.iter().any(|id| id == kind.id()); let r = ui @@ -942,7 +1130,7 @@ fn theme_card<V: PartialEq + Copy>( .on_hover_text(crate::i18n::tr(if favorite { "Remove from favorites" } else { "Add to favorites" })); r.widget_info(|| { egui::WidgetInfo::labeled( - egui::WidgetType::Button, + egui::Role::Button, true, format!( "{}: {}", @@ -951,14 +1139,9 @@ fn theme_card<V: PartialEq + Copy>( ), ) }); - register(ui.ctx(), format!("button:themeFavorite-{}", kind.id()), r.rect); + register(ui, format!("button:themeFavorite-{}", kind.id()), r.rect); if favorite || hovered { - crate::icons::paint( - ui.painter(), - r.rect.shrink(4.0), - if favorite { crate::icons::Icon::StarFilled } else { crate::icons::Icon::Star }, - if favorite { t.accent } else { t.text_dim }, - ); + crate::rating::paint_star(ui.painter(), r.rect.shrink(4.0), favorite, if favorite { t.accent } else { t.text_dim }); } if r.clicked() { if favorite { @@ -1181,6 +1364,7 @@ fn switch_library(app: &mut LightcraftApp, path: &str) -> Result<Value, String> // or failed switch reopens the same catalog, so its pins stay). app.ui.reference = None; app.ui.compare = None; + app.ui.brief_info = crate::state::BriefInfo::default(); if app.ui.view == crate::state::ViewMode::Reference { app.ui.view = crate::state::ViewMode::PhotoGrid; } @@ -1284,7 +1468,7 @@ fn valid_library_name(s: &str) -> Result<&str, String> { } /// `base` inside `location`, or `base 2`, `base 3`… if that is taken. -fn free_name(location: &std::path::Path, base: &str) -> std::path::PathBuf { +pub(crate) fn free_name(location: &std::path::Path, base: &str) -> std::path::PathBuf { let first = location.join(base); if !first.exists() { return first; @@ -1292,27 +1476,55 @@ fn free_name(location: &std::path::Path, base: &str) -> std::path::PathBuf { (2..1000u32).map(|i| location.join(format!("{base} {i}"))).find(|p| !p.exists()).unwrap_or(first) } -/// `app.recentLibraries {clear?: bool}`: the recently opened libraries, newest first, as -/// `[{path, name, exists, open}]` (`exists: false`: moved or on a disconnected drive). `clear` -/// forgets them all. +/// `app.recentLibraries {remove?: path, clear?: bool}`: the recently opened libraries, newest +/// first, as `[{path, name, exists, checking, open, lastOpened}]`. `exists` is what the last +/// background check found (`false`: moved, on a disconnected drive, not a folder or no longer a +/// library; `null`: not checked yet, or the check couldn't tell — a folder that can't be listed, an +/// unreadable catalog, a lookup or check that failed; `checking` says whether a check is running): the command never +/// looks at a folder itself, as one on an offline network share can take seconds to answer. +/// `lastOpened`: ISO 8601 time, `null` when not known. `remove` forgets that +/// one entry (an error if the list doesn't hold it) and `clear` forgets them all; neither touches +/// anything on disk (issue #1290). pub fn recent_libraries(app: &mut LightcraftApp, p: &Value) -> Result<Value, String> { + match p.get("remove") { + None | Some(Value::Null) => {} + Some(Value::String(path)) => { + if !forget_library(&mut app.ui.settings, path) { + return Err(format!("app.recentLibraries: {path:?} is not in the recent libraries")); + } + app.recent_checks.forget(path); + } + Some(_) => return Err("app.recentLibraries: remove must be a library path (a string)".into()), + } if p.get("clear").and_then(Value::as_bool) == Some(true) { - app.ui.settings.recent_libraries.clear(); + for path in std::mem::take(&mut app.ui.settings.recent_libraries) { + app.recent_checks.forget(&path); + } + app.ui.settings.recent_opened.clear(); } let open = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()); - let list: Vec<Value> = app - .ui - .settings + let (settings, checks) = (&app.ui.settings, &app.recent_checks); + let list: Vec<Value> = settings .recent_libraries .iter() .map(|r| { let d = std::path::Path::new(r); - json!({"path": r, "name": library_name(d), "exists": d.is_dir(), "open": open.as_deref() == Some(d)}) + let exists = checks.exists(r); + json!({"path": r, "name": library_name(d), "exists": exists, "checking": checks.is_checking(r), "open": open.as_deref() == Some(d), "lastOpened": settings.recent_opened.get(r)}) }) .collect(); Ok(Value::Array(list)) } +/// Forget `path` in File ▸ Open Recent Library (and when it was opened); the library itself is +/// left where it is. False if the list didn't hold it. +pub fn forget_library(settings: &mut crate::state::AppSettings, path: &str) -> bool { + let before = settings.recent_libraries.len(); + settings.recent_libraries.retain(|r| r != path); + settings.recent_opened.remove(path); + settings.recent_libraries.len() != before +} + // ---------------------------------------------------------------------------- Display profile /// `app.displayProfile {path?: string | null}`: show previews through this monitor ICC profile @@ -1416,3 +1628,48 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(test)] +mod path_tests { + use super::elide_path; + + /// Width = characters, so a limit of 20 is "20 characters". + fn fit(path: &str, max: usize) -> String { + elide_path(path, max as f32, |s| s.chars().count() as f32) + } + + #[test] + fn a_path_that_fits_is_left_alone() { + assert_eq!(fit("/Users/me/Pictures", 18), "/Users/me/Pictures"); + assert_eq!(fit("", 5), ""); + } + + #[test] + fn leading_folders_go_first_and_the_end_stays() { + assert_eq!(fit("/Users/me/Pictures/Library", 20), "…/Pictures/Library"); + assert_eq!(fit("/Users/me/Pictures/Library", 10), "…/Library"); + } + + /// Windows paths: `Path::display` gives backslashes there. + #[test] + fn a_path_with_backslashes_keeps_its_end_too() { + assert_eq!(fit(r"C:\Users\me\Pictures\Library", 20), r"…\Pictures\Library"); + assert_eq!(fit(r"C:\Users\me/Pictures\Library", 10), r"…\Library"); + } + + #[test] + fn a_last_folder_too_long_by_itself_loses_its_end() { + assert_eq!(fit("/Users/me/a-very-long-folder-name", 8), "a-very-…"); + assert_eq!(fit("no-separator-at-all", 8), "no-sepa…"); + assert_eq!(fit("/Users/Фотографии-из-отпуска", 8), "Фотогра…"); + } + + #[test] + fn a_separator_at_the_end_is_not_where_the_name_starts() { + assert_eq!(fit("/Users/me/Pictures/Library/", 11), "…/Library/"); + assert_eq!(fit("/Users/me/a-very-long-folder-name/", 8), "a-very-…"); + assert_eq!(fit(r"C:\Users\me\Library\", 11), r"…\Library\"); + assert_eq!(fit("///", 2), "…"); + assert_eq!(fit(r"\\server\share\folder", 15), r"…\share\folder"); + } +} diff --git a/crates/ui-egui/src/panels/slide_layout.rs b/crates/ui-egui/src/panels/slide_layout.rs index 62f7626c32..82387f1e61 100644 --- a/crates/ui-egui/src/panels/slide_layout.rs +++ b/crates/ui-egui/src/panels/slide_layout.rs @@ -22,8 +22,10 @@ use crate::widgets::register; /// Seconds the layout must stay unchanged before the preview is rendered again. pub const DEBOUNCE: f64 = 0.15; -/// The preview's width in points. +/// The preview's greatest width in points (less where the room is narrower). pub const PREVIEW_W: f32 = 300.0; +/// The least tall the preview is drawn. +pub const PREVIEW_MIN_H: f32 = 80.0; #[derive(Clone, Copy)] enum Unit { @@ -43,7 +45,7 @@ fn slider(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, key: &str, value Unit::Degrees => (value, -180.0..=180.0, "°"), }; let r = ui.add(egui::Slider::new(&mut v, range).suffix(suffix).max_decimals(1)); - register(ui.ctx(), format!("slider:{id}"), r.rect); + register(ui, format!("slider:{id}"), r.rect); let value = match unit { Unit::Percent => v / 100.0, Unit::Degrees => v, @@ -62,7 +64,7 @@ fn slider(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, key: &str, value fn colour(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, key: &str, value: [u8; 3]) { let mut c = value; let r = egui::color_picker::color_edit_button_srgb(ui, &mut c); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); if r.changed() { set(app, json!({ key: c })); } @@ -130,7 +132,7 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let active = app.session.active(); let mut on = s.background_image.is_some(); let r = ui.add_enabled(on || active.is_some(), egui::Checkbox::new(&mut on, crate::i18n::tr("Background image"))); - register(ui.ctx(), "check:settings.slideshowBackgroundImage", r.rect); + register(ui, "check:settings.slideshowBackgroundImage", r.rect); if r.changed() { set(app, json!({"backgroundImage": if on { active.map(|a| a.0) } else { None }})); } @@ -162,27 +164,49 @@ fn screen_aspect(ctx: &egui::Context) -> f64 { if r.y > 0.0 { (r.x / r.y) as f64 } else { 1.6 } } -/// The small composed slide of the active photo, with the margin guides when they are on. -pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { +/// The small composed slide of the active photo, with the margin guides when they are on. It is +/// at most `max_h` tall (but for [`PREVIEW_MIN_H`], and without counting its heading). +pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f32) { heading(ui, t, "Preview"); // the template the pointer is over in the Template Browser, else the settings let template = super::slide_templates::hovered(ui.ctx()).and_then(|id| app.session.slide_template(&id).ok()); let look = template.as_ref().map_or_else(|| SlideLook::of(&app.session), |t| t.look.clone()); let s = look.layout.clone(); let overlays = look.overlays.clone(); + // The room for the preview is the settings' own shape, whichever template is pointed at: the + // page below it must not move as the pointer goes over the templates (it would leave the + // row it is over). A template of another shape is drawn as large as fits in that room. let ratio = s.aspect.ratio(screen_aspect(ui.ctx())) as f32; - let h = (PREVIEW_W / ratio).clamp(80.0, 320.0); - let (rect, _) = ui.allocate_exact_size(vec2(PREVIEW_W, h), Sense::hover()); - register(ui.ctx(), "slideshow:preview", rect); - let p = ui.painter_at(rect.expand(1.0)); + let own = SlideLook::of(&app.session).layout.aspect.ratio(screen_aspect(ui.ctx())) as f32; + let w = ui.available_width().clamp(1.0, PREVIEW_W); + let room_h = (w / own).clamp(PREVIEW_MIN_H, 320.0).min(max_h.max(PREVIEW_MIN_H)); + let (room, _) = ui.allocate_exact_size(vec2(w, room_h), Sense::hover()); + let (fit_w, fit_h) = if ratio >= w / room_h { (w, w / ratio) } else { (room_h * ratio, room_h) }; + let rect = Rect::from_center_size(room.center(), vec2(fit_w, fit_h)); + let h = rect.height(); + let w = rect.width(); + register(ui, "slideshow:preview", rect); + let p = ui.painter_at(room.expand(1.0)); p.rect_stroke(rect, 0.0, Stroke::new(1.0, t.text_dim.gamma_multiply(0.5)), egui::StrokeKind::Outside); super::slide_titles::preview_choice(ui); if let Some(tpl) = &template { + // (said over the bottom of the preview and not below it, which would move the page) let name = if tpl.builtin { crate::i18n::tr(&tpl.name).to_string() } else { tpl.name.clone() }; - ui.label(egui::RichText::new(crate::i18n::tr_format!("Template preview: {name}", name = name)).size(11.0).color(t.accent)); + let mut said = crate::i18n::tr_format!("Template preview: {name}", name = name).to_string(); if !tpl.description.is_empty() { - hint(ui, t, &tpl.description); + said = format!("{said}\n{}", tpl.description); } + let galley = ui.painter().layout(said, t.font(11.0), Color32::WHITE, (room.width() - 8.0).max(1.0)); + let band = Rect::from_min_size( + pos2(room.left(), (room.bottom() - galley.size().y - 6.0).max(room.top())), + vec2(room.width(), galley.size().y + 6.0), + ); + let paint = ui + .ctx() + .layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("settingsSlideshowTemplateSaid"))) + .with_clip_rect(room.intersect(ui.clip_rect())); + paint.rect_filled(band, 0.0, Color32::from_black_alpha(190)); + paint.galley(pos2(band.left() + 4.0, band.top() + 3.0), galley, Color32::WHITE); } if let Some(title) = super::slide_titles::preview_shows(ui.ctx()) { title_preview(app, ui, t, rect, title, &look); @@ -194,7 +218,7 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { return; }; let ppp = ui.ctx().pixels_per_point(); - let (pw, ph) = (((PREVIEW_W * ppp).round() as usize).max(16), ((h * ppp).round() as usize).max(16)); + let (pw, ph) = (((w * ppp).round() as usize).max(16), ((h * ppp).round() as usize).max(16)); // the overlays and what they show of the photo (its rating, its metadata) change it too let shown = app.session.catalog.photo(id).filter(|_| overlays.any()).map_or(0, |p| { use std::hash::{Hash, Hasher}; @@ -206,7 +230,7 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let overlay_key = if overlays.any() { overlays.pixel_key() ^ shown.rotate_left(5) } else { 0 }; let key = s.pixel_key() ^ id.0.rotate_left(17) ^ ((pw as u64) << 32 | ph as u64) ^ overlay_key.rotate_left(29); let now = ui.input(|i| i.time); - let mem = egui::Id::new("settingsSlideshowPreviewKey"); + let mem = egui::Id::unique("settingsSlideshowPreviewKey"); let (last, since) = ui.ctx().data(|d| d.get_temp::<(u64, f64)>(mem)).unwrap_or((0, f64::NEG_INFINITY)); let current = app.renderer.textures.get(&Slot::SlidePreview).filter(|tex| tex.photo == id); if last != key { @@ -256,7 +280,7 @@ fn title_preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, rect: R let compose = std::sync::Arc::new(lightcraft_engine::slide_title::TitleCompose::new(&look.titles, &look.overlays, title, pw, ph)); let key = compose.key(); let now = ui.input(|i| i.time); - let mem = egui::Id::new("settingsSlideshowTitlePreviewKey"); + let mem = egui::Id::unique("settingsSlideshowTitlePreviewKey"); let (last, since) = ui.ctx().data(|d| d.get_temp::<(u64, f64)>(mem)).unwrap_or((0, f64::NEG_INFINITY)); if last != key { ui.ctx().data_mut(|d| d.insert_temp(mem, (key, now))); diff --git a/crates/ui-egui/src/panels/slide_overlays.rs b/crates/ui-egui/src/panels/slide_overlays.rs index 3824eeb0d0..e9c88f0b32 100644 --- a/crates/ui-egui/src/panels/slide_overlays.rs +++ b/crates/ui-egui/src/panels/slide_overlays.rs @@ -38,7 +38,7 @@ fn slider(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, value: f64, lo: }; let mut v = value * k; let r = ui.add(egui::Slider::new(&mut v, lo * k..=hi * k).suffix(suffix).max_decimals(1)); - register(ui.ctx(), format!("slider:{id}"), r.rect); + register(ui, format!("slider:{id}"), r.rect); let p = wrap(v / k); if r.changed() && let Ok(next) = app.session.slide_overlays.merged(&p) @@ -54,7 +54,7 @@ fn slider(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, value: f64, lo: fn colour(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, value: [u8; 3], wrap: &dyn Fn([u8; 3]) -> Value) { let mut c = value; let r = egui::color_picker::color_edit_button_srgb(ui, &mut c); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); if r.changed() { set(app, wrap(c)); } @@ -71,7 +71,7 @@ fn toggle(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, value: bool, lab /// A one-line text field (`field:{id}`), saved when the edit ends. fn text(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, value: &str, hint: &str, wrap: &dyn Fn(&str) -> Value) { - let mem = egui::Id::new(("slideshow-overlay-field", id)); + let mem = egui::Id::unique(("slideshow-overlay-field", id)); let mut s: String = ui.data(|d| d.get_temp(mem)).unwrap_or_else(|| value.to_string()); let widget = format!("field:{id}"); let r = TextField::singleline(&widget, &mut s).hint(crate::i18n::tr(hint)).width(ui.available_width().clamp(80.0, 260.0)).show(ui); @@ -147,7 +147,7 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let p = s.identity_plate.clone(); let plate = |v: Value| json!({ "identityPlate": v }); if toggle(app, ui, "slideshowPlate", p.enabled, "Identity plate", &|v| plate(json!({"enabled": v}))) { - let mem = egui::Id::new("slideshow-plate-graphic"); + let mem = egui::Id::unique("slideshow-plate-graphic"); let mut graphic = !p.image.is_empty() || ui.data(|d| d.get_temp::<bool>(mem)).unwrap_or(false); let before = graphic; row(ui, t, "Style", |ui| choices(ui, "slideshowPlateStyle", &[(false, "Text"), (true, "Image")], &mut graphic)); diff --git a/crates/ui-egui/src/panels/slide_templates.rs b/crates/ui-egui/src/panels/slide_templates.rs index 51c27d2240..3929be5ed7 100644 --- a/crates/ui-egui/src/panels/slide_templates.rs +++ b/crates/ui-egui/src/panels/slide_templates.rs @@ -17,13 +17,13 @@ use super::settings::{heading, hint}; use crate::LightcraftApp; use crate::text_field::TextField; use crate::theme::Tokens; -use crate::widgets::register; +use crate::widgets::{register, register_response}; /// The user templates list is at most this tall (it scrolls past it). const USER_LIST_H: f32 = 180.0; fn hovered_key() -> egui::Id { - egui::Id::new("settingsSlideshowTemplateHovered") + egui::Id::unique("settingsSlideshowTemplateHovered") } /// The template the pointer is over in the browser (its id), which the preview shows. @@ -43,7 +43,7 @@ enum Pending { } fn pending_key() -> egui::Id { - egui::Id::new("settingsSlideshowTemplatePending") + egui::Id::unique("settingsSlideshowTemplatePending") } fn pending(ctx: &egui::Context) -> Option<Pending> { @@ -129,7 +129,7 @@ fn template_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, tpl: &Te } let w = ui.available_width(); let (rect, resp) = ui.allocate_exact_size(vec2(w, 22.0), Sense::click()); - register(&ctx, format!("template:{}", tpl.id), rect); + register_response(format!("template:{}", tpl.id), rect, &resp); if resp.hovered() || resp.context_menu_opened() { *hovered = Some(tpl.id.clone()); } @@ -151,7 +151,7 @@ fn template_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, tpl: &Te /// A menu entry registered as `button:{id}`. fn item(ui: &mut egui::Ui, id: &str, label: &str, enabled: bool) -> bool { let r = ui.add_enabled(enabled, egui::Button::new(crate::i18n::tr(label))); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); r.clicked() } @@ -228,7 +228,7 @@ pub fn section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { // save the current settings as a new template ui.add_space(4.0); ui.horizontal(|ui| { - let mem = egui::Id::new("settingsSlideshowTemplateNewName"); + let mem = egui::Id::unique("settingsSlideshowTemplateNewName"); let mut name: String = ui.data(|d| d.get_temp(mem)).unwrap_or_default(); let r = TextField::singleline("field:slideshowTemplateName", &mut name).hint(crate::i18n::tr("New template name")).width(180.0).show(ui); let save = crate::widgets::text_button(ui, "slideshowTemplateSave", "Save as Template", false).clicked() diff --git a/crates/ui-egui/src/panels/slide_titles.rs b/crates/ui-egui/src/panels/slide_titles.rs index 257790995e..b3c1034021 100644 --- a/crates/ui-egui/src/panels/slide_titles.rs +++ b/crates/ui-egui/src/panels/slide_titles.rs @@ -20,7 +20,7 @@ use crate::widgets::register; /// Where the preview's choice lives (egui memory): `None` = the photo's slide. fn preview_key() -> egui::Id { - egui::Id::new("settingsSlideshowPreviewShows") + egui::Id::unique("settingsSlideshowPreviewShows") } /// What the Settings preview shows: a title screen, or (`None`) the active photo's slide. @@ -64,7 +64,7 @@ fn slider( ) { let mut v = value * k; let r = ui.add(egui::Slider::new(&mut v, (range.start() * k)..=(range.end() * k)).suffix(suffix).max_decimals(1)); - register(ui.ctx(), format!("slider:{id}"), r.rect); + register(ui, format!("slider:{id}"), r.rect); let p = json!({ t.id(): { key: v / k } }); if r.changed() { if let Ok(next) = app.session.slide_titles.merged(&p) { @@ -81,7 +81,7 @@ fn slider( fn colour(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, t: Title, key: &str, value: [u8; 3]) { let mut c = value; let r = egui::color_picker::color_edit_button_srgb(ui, &mut c); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); if r.changed() { set(app, ui.ctx(), t, key, json!(c)); } @@ -89,7 +89,7 @@ fn colour(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, t: Title, key: & /// The screen's text field (`field:{id}`), saved when the edit ends. fn text(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, t: Title, value: &str) { - let mem = egui::Id::new(("slideshow-title-field", id)); + let mem = egui::Id::unique(("slideshow-title-field", id)); let mut s: String = ui.data(|d| d.get_temp(mem)).unwrap_or_else(|| value.to_string()); let widget = format!("field:{id}"); let r = TextField::singleline(&widget, &mut s).hint(crate::i18n::tr("Title text")).width(ui.available_width().clamp(80.0, 260.0)).show(ui); diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index a0f7ba09f4..cfe0ce6e68 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -1,6 +1,6 @@ //! The slideshow (View ▸ Slideshow, ⌥⌘↩): the photos in view, full screen, played with the //! library's Playback settings (`slideshow.playback`: slide and fade durations, fade colour, -//! random order, repeat, preparing previews in advance). +//! random order, repeat, preparing previews in advance, manual slideshow). //! //! The timeline is [`lightcraft_engine::slideshow::Playback`] (no egui, tested on its own); this //! module renders the slides, draws the frame it asks for and the playback controls. @@ -53,7 +53,7 @@ pub struct Run { } /// `view.slideshow {interval?, seed?, slideDuration?, fadeDuration?, fadeColor?, randomOrder?, -/// repeat?, preparePreviews?}`: play the photos in view from the selected one with the library's +/// repeat?, preparePreviews?, manual?}`: play the photos in view from the selected one with the library's /// playback settings; the keys given change them for this run only (`interval` = slideDuration, /// `seed` fixes the random order). The intro and ending screens that are on (`slideshow.titles`) /// play before the first photo and after the last one. With no photos in view there is nothing @@ -127,7 +127,9 @@ pub fn state(play: &Playback, now: f64) -> Value { "fading": f.from.is_some(), "progress": f.progress, "waitingFor": play.waiting_for().map(|i| i.photo().map_or_else(|| json!(i.title().map(Title::id)), |p| json!(p.0))), + // (null in a manual slideshow: no slide is ever due) "remaining": play.remaining(now), + "manual": play.settings().manual, }) } @@ -154,7 +156,7 @@ pub fn ready(app: &LightcraftApp, item: Item) -> bool { } /// Advance a running slideshow (every frame, before drawing). -pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { +pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { let Some(run) = app.ui.slideshow.as_ref() else { app.renderer.release_slides(&[]); return; @@ -163,7 +165,6 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { end(app); return; } - let now = ctx.input(|i| i.time); let mut play = run.play.clone(); let t = play.tick(now, |id| ready(app, id)); if let Some(run) = app.ui.slideshow.as_mut() { @@ -174,7 +175,7 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { let f = run.play.frame(now); if f.from.is_some() { ctx.request_repaint(); // a fade draws every frame - } else if !run.play.is_paused() { + } else if !run.play.is_paused() && !run.play.settings().manual { ctx.request_repaint_after(std::time::Duration::from_secs_f64(run.play.remaining(now).clamp(0.016, 120.0))); } if run.controls_until > now { @@ -293,7 +294,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // (`ui.pointer` positions are relative to it) app.image_rect = Some(canvas); let Some(run) = app.ui.slideshow.as_ref() else { return }; - let now = ui.input(|i| i.time); + let now = app.tick_now(); let ppp = ui.ctx().pixels_per_point(); let side = super::detail::texture_side(ui.ctx()); let want = wanted(&run.play, now); @@ -367,7 +368,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { draw(frame.current, 1.0); } } - register(ui.ctx(), "slideshow:canvas", canvas); + register(ui, "slideshow:canvas", canvas); controls(app, ui, canvas, now); } diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index e26d1088ff..c1c645a1d6 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -12,14 +12,14 @@ use crate::widgets::{icon_button, register}; /// double-click zooms or restores it. Registered before the bar's widgets so they win the click. fn window_handle(app: &LightcraftApp, ui: &mut egui::Ui, bar: Rect, search_rect: Rect) { use crate::titlebar::{Gesture, WindowState, command_for}; - register(ui.ctx(), "region:titlebar", bar); - let handle = egui::Id::new("titlebar-handle"); + register(ui, "region:titlebar", bar); + let handle = egui::Id::unique("titlebar-handle"); let resp = ui.interact(bar, handle, Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Title bar")); // a press that began on a button or the search field is theirs: dragging off it must not move the window // (while pressing, egui hovers every widget under the pointer; once the drag starts, only the dragged one) let ctx = ui.ctx().clone(); - let memo = egui::Id::new("titlebar-press-on-widget"); + let memo = egui::Id::unique("titlebar-press-on-widget"); if resp.is_pointer_button_down_on() && ctx.input(|i| i.pointer.primary_pressed()) { let hovered = ctx.interaction_snapshot(|s| s.hovered.clone()); let on_widget = @@ -45,6 +45,9 @@ fn window_handle(app: &LightcraftApp, ui: &mut egui::Ui, bar: Rect, search_rect: } } +/// Draw the top bar: the titlebar drag area, the in-window menus when there is no native menu +/// bar, sidebar and back/forward buttons, the centred search field, the filter button with its +/// active count, and the right-side action icons. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); // room for the traffic lights; in full screen they are gone, and the sidebar button sits as far @@ -133,9 +136,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } // filter icon right of the search field let fr = Rect::from_center_size(pos2(sr.right() + 22.0, sr.center().y), vec2(28.0, 28.0)); - let fresp = ui.interact(fr, egui::Id::new("filter-btn"), Sense::click()); + let fresp = ui.interact(fr, egui::Id::unique("filter-btn"), Sense::click()); crate::widgets::announce(&fresp, crate::i18n::tr("Filters")); - register(ui.ctx(), "icon:filter", fr); + register(ui, "icon:filter", fr); let filtering = app.session.filter != Default::default() || app.ui.filter_bar; paint( ui.painter(), @@ -192,9 +195,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ("bell", Icon::Bell, "Activity", "panel.activity"), ] { let r = Rect::from_center_size(pos2(x, full.center().y), vec2(28.0, 28.0)); - let resp = ui.interact(r, egui::Id::new(("top", id)), Sense::click()).on_hover_text(crate::i18n::tr(tip)); + let resp = ui.interact(r, egui::Id::unique(("top", id)), Sense::click()).on_hover_text(crate::i18n::tr(tip)); crate::widgets::announce(&resp, crate::i18n::tr(tip)); - register(ui.ctx(), format!("icon:{id}"), r); + register(ui, format!("icon:{id}"), r); let warn = id == "cloud" && unsaved.is_some(); let colour = if warn { t.caution @@ -208,7 +211,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let c = r.right_top() + vec2(-5.0, 6.0); ui.painter().circle_filled(c, 6.0, t.reject); ui.painter().text(c, Align2::CENTER_CENTER, "!", t.semibold(9.5), t.canvas); - register(ui.ctx(), "indicator:unsaved", r); + register(ui, "indicator:unsaved", r); } // a refusal says why (Import while a Lightroom catalog is coming in) if resp.clicked() @@ -223,16 +226,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let (icon, mode) = appearance_icon(app.ui.settings.appearance_mode); let r = Rect::from_center_size(pos2(x, full.center().y), vec2(28.0, 28.0)); let tip = format!("{}: {}", crate::i18n::tr("Appearance Mode"), crate::i18n::tr(mode)); - let resp = ui.interact(r, egui::Id::new(("top", "appearance")), Sense::click()).on_hover_text(tip.clone()); + let resp = ui.interact(r, egui::Id::unique(("top", "appearance")), Sense::click()).on_hover_text(tip.clone()); crate::widgets::announce(&resp, tip.clone()); - register(ui.ctx(), "icon:appearance", r); + register(ui, "icon:appearance", r); paint(ui.painter(), r.shrink(5.0), icon, if resp.hovered() { t.text } else { t.icon }); if resp.clicked() { let _ = app.run("view.appearance", json!({})); } crate::widgets::context_menu(&resp, |ui| { let settings = ui.button(crate::i18n::tr("Appearance Settings…")); - register(ui.ctx(), "menu:appearanceSettings", settings.rect); + register(ui, "menu:appearanceSettings", settings.rect); if settings.clicked() { let _ = app.run("app.settings", json!({"tab": "interface"})); ui.close(); @@ -246,7 +249,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } for kind in group { let r = ui.selectable_label(app.ui.settings.theme(app.system_theme(ui.ctx())) == *kind, crate::i18n::tr(kind.label())); - register(ui.ctx(), format!("menu:themeFavorite-{}", kind.id()), r.rect); + register(ui, format!("menu:themeFavorite-{}", kind.id()), r.rect); if r.clicked() { let _ = app.run("view.theme", json!({"theme": kind.id()})); ui.close(); diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index e1ef879e26..7f42437b2e 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -144,12 +144,12 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { } let label = if n == 1 { "Name face".to_string() } else { format!("Name {n} faces") }; let b = ui.add_enabled(!chosen.is_empty(), egui::Button::new(label)); - register(ui.ctx(), "unnamed:name", b.rect); + register(ui, "unnamed:name", b.rect); if b.clicked() { submit = Some(chosen); } let c = ui.button(crate::i18n::tr("Clear")); - register(ui.ctx(), "unnamed:clear", c.rect); + register(ui, "unnamed:clear", c.rect); clear = c.clicked() || field.cancelled(); }); // the people already named, matching what is typed (a click names the faces) @@ -162,7 +162,7 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.add_space(super::people::PAD - 4.0); for p in matching { let b = ui.add(egui::Button::new(RichText::new(p.as_str()).color(t.text_label)).frame(false)); - register(ui.ctx(), format!("unnamed:pick:{p}"), b.rect); + register(ui, format!("unnamed:pick:{p}"), b.rect); if b.clicked() { submit = Some(p.clone()); } @@ -204,7 +204,7 @@ pub fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed if !list.ready && list.faces.is_empty() { let r = Rect::from_min_size(pos2(at.x, at.y + 38.0), vec2(120.0, 22.0)); let b = ui.put(r, egui::Button::new(crate::i18n::tr("Open Settings"))); - register(ui.ctx(), "unnamed:openSettings", b.rect); + register(ui, "unnamed:openSettings", b.rect); if b.clicked() { let _ = app.run("app.settings", json!({"tab": "faces"})); } @@ -212,7 +212,7 @@ pub fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed let r = Rect::from_min_size(pos2(right - 130.0, at.y + 12.0), vec2(130.0, 22.0)); let all = app.ui.unnamed_selected.len() == list.faces.len(); let b = ui.put(r, egui::Button::new(crate::i18n::tr(if all { "Select none" } else { "Select all" }))); - register(ui.ctx(), "unnamed:selectAll", b.rect); + register(ui, "unnamed:selectAll", b.rect); if b.clicked() { app.ui.unnamed_selected.clear(); if !all { @@ -228,14 +228,14 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize let t = Tokens::get(ui.ctx()); let key = (f.photo, f.index); let selected = app.ui.unnamed_selected.contains(&key); - let resp = ui.interact(r, egui::Id::new(("unnamed-face", f.photo, f.index)), Sense::click()); + let resp = ui.interact(r, egui::Id::unique(("unnamed-face", f.photo, f.index)), Sense::click()); crate::widgets::announce_selected(&resp, crate::i18n::tr("Unnamed face"), selected); - register(ui.ctx(), format!("unnamed-face:{}:{}", f.photo, f.index), r); + register(ui, format!("unnamed-face:{}:{}", f.photo, f.index), r); // a suggested name along the bottom: a click accepts it for this face (added after the tile, so it wins there) let strip = Rect::from_min_max(pos2(r.left(), r.bottom() - 20.0), r.right_bottom()); - let accept = f.suggestion.as_ref().map(|_| ui.interact(strip, egui::Id::new(("unnamed-accept", f.photo, f.index)), Sense::click())); + let accept = f.suggestion.as_ref().map(|_| ui.interact(strip, egui::Id::unique(("unnamed-accept", f.photo, f.index)), Sense::click())); if let Some(a) = &accept { - register(ui.ctx(), format!("unnamed-accept:{}:{}", f.photo, f.index), a.rect); + register(ui, format!("unnamed-accept:{}:{}", f.photo, f.index), a.rect); } let hovered = resp.hovered() || accept.as_ref().is_some_and(|a| a.hovered()); let p = ui.painter(); diff --git a/crates/ui-egui/src/print_view.rs b/crates/ui-egui/src/print_view.rs index a18e1f6915..4a9940307a 100644 --- a/crates/ui-egui/src/print_view.rs +++ b/crates/ui-egui/src/print_view.rs @@ -105,14 +105,14 @@ fn length(ui: &mut Ui, id: &str, inches: f64, unit: Unit, min_in: f64, max_in: f .max_decimals(decimals(unit)) .suffix(format!(" {}", unit.label())), ); - register(ui.ctx(), format!("drag:{id}"), r.rect); + register(ui, format!("drag:{id}"), r.rect); r.changed().then(|| unit.to_inches(v)) } fn check(ui: &mut Ui, id: &str, label: &str, value: bool) -> Option<bool> { let mut v = value; let r = ui.checkbox(&mut v, crate::i18n::tr(label)); - register(ui.ctx(), format!("check:{id}"), r.rect); + register(ui, format!("check:{id}"), r.rect); r.changed().then_some(v) } @@ -130,7 +130,7 @@ fn choice<V: PartialEq + Copy>(ui: &mut Ui, id: &str, options: &[(V, &str)], cur fn colour(ui: &mut Ui, id: &str, rgb: [u8; 3]) -> Option<[u8; 3]> { let mut c = rgb; let r = ui.color_edit_button_srgb(&mut c); - register(ui.ctx(), format!("color:{id}"), r.rect); + register(ui, format!("color:{id}"), r.rect); (c != rgb).then_some(c) } @@ -141,10 +141,25 @@ fn paper_label(name: &str) -> String { "legal" => "Legal".into(), "tabloid" => "Tabloid".into(), "custom" => "Custom".into(), + // Japanese photo and postcard papers: the customary name and its metric size. + "l" => "L判 (89 × 127 mm)".into(), + "2l" => "2L判 (127 × 178 mm)".into(), + "kg" => "KG判 (102 × 152 mm)".into(), + "postcard" => "はがき (100 × 148 mm)".into(), + "double-postcard" => "往復はがき (148 × 200 mm)".into(), + "6cut" => "六切 (203 × 254 mm)".into(), + "4cut" => "四切 (254 × 305 mm)".into(), + "business-card" => "名刺 (55 × 91 mm)".into(), other => other.replace('x', " × ") + " in", } } +/// The paper the selector shows as current: `custom`, or the canonical name an alias stands for, +/// so a `print.set` with `はがき` still selects the `postcard` option. +fn current_paper(paper: &str) -> &str { + if paper.eq_ignore_ascii_case("custom") { "custom" } else { layout::paper_name(paper).unwrap_or(paper) } +} + /// The dialog's body: the settings column and the page preview side by side. pub fn body(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens) { let ctx = ui.ctx().clone(); @@ -197,6 +212,14 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, if text_button(ui, "printSaveTemplate", "Save", false).clicked() && !pu.template_name.trim().is_empty() { run(app, &ctx, "print.template.save", json!({"name": pu.template_name})); } + if app.services.pick_print_templates.is_some() && text_button(ui, "printTemplateImport", "Import…", false).clicked() { + let paths = app.services.pick_print_templates.as_mut().map(|pick| pick()).unwrap_or_default(); + for path in paths { + if let Some(r) = run(app, &ctx, "print.template.import", json!({"path": path})) { + app.toast(&ctx, crate::i18n::tr_format!("Imported {name}", name = r["name"].as_str().unwrap_or_default())); + } + } + } }); let names: Vec<String> = app.session.print_templates.iter().map(|t| t.name.clone()).collect(); for (i, name) in names.iter().enumerate() { @@ -206,6 +229,15 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, if text_button(ui, &format!("printTemplateDelete-{i}"), "Delete", false).clicked() { run(app, &ctx, "print.template.delete", json!({"name": name})); } + if app.services.save_print_template.is_some() && text_button(ui, &format!("printTemplateExport-{i}"), "Export…", false).clicked() { + let stem = lightcraft_engine::slide_template::file_stem(name).unwrap_or_else(|| "Print Template".into()); + let file = format!("{stem}.{}", lightcraft_engine::print::template::FILE_EXT); + if let Some(path) = app.services.save_print_template.as_mut().and_then(|save| save(&file)) + && let Some(r) = run(app, &ctx, "print.template.export", json!({"name": name, "path": path})) + { + app.toast(&ctx, crate::i18n::tr_format!("Exported to {path}", path = r["path"].as_str().unwrap_or_default())); + } + } if text_button(ui, &format!("printTemplateApply-{i}"), "Apply", false).clicked() { run(app, &ctx, "print.template.apply", json!({"name": name})); pu.page = 0; @@ -252,7 +284,7 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, } let mut pt = im.stroke_width_pt; let r = ui.add(egui::DragValue::new(&mut pt).range(0.0..=36.0).speed(0.05).max_decimals(2).suffix(" pt")); - register(ui.ctx(), "drag:printStrokeWidth", r.rect); + register(ui, "drag:printStrokeWidth", r.rect); if r.changed() { patch(app, &ctx, json!({"image": {"strokeWidthPt": pt}})); } @@ -271,9 +303,9 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, row(ui, t, "Grid", |ui| { let (mut c, mut r) = (g.columns, g.rows); let a = ui.add(egui::DragValue::new(&mut c).range(1..=layout::MAX_GRID).suffix(" cols")); - register(ui.ctx(), "drag:printColumns", a.rect); + register(ui, "drag:printColumns", a.rect); let b = ui.add(egui::DragValue::new(&mut r).range(1..=layout::MAX_GRID).suffix(" rows")); - register(ui.ctx(), "drag:printRows", b.rect); + register(ui, "drag:printRows", b.rect); if a.changed() || b.changed() { patch(app, &ctx, json!({"layout": {"grid": {"columns": c, "rows": r}}})); } @@ -374,15 +406,16 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, heading(ui, t, "Page Setup"); row(ui, t, "Paper", |ui| { - let current = if l.page.paper.eq_ignore_ascii_case("custom") { "custom".to_string() } else { l.page.paper.to_ascii_lowercase() }; - let c = egui::ComboBox::from_id_salt("printPaper").selected_text(paper_label(&current)).show_ui(ui, |ui| { + let current = current_paper(&l.page.paper); + let c = egui::ComboBox::from_id_salt("printPaper").selected_text(paper_label(current)).show_ui(ui, |ui| { for name in layout::paper_names().chain(std::iter::once("custom")) { if ui.selectable_label(current == name, paper_label(name)).clicked() { patch(app, &ctx, json!({"layout": {"page": {"paper": name}}})); } } }); - register(ui.ctx(), "combo:printPaper", c.response.rect); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Paper")); + register(ui, "combo:printPaper", c.response.rect); }); if l.page.paper.eq_ignore_ascii_case("custom") { row(ui, t, "Size", |ui| { @@ -438,7 +471,7 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, row(ui, t, "Resolution", |ui| { let mut ppi = st.job.ppi; let r = ui.add(egui::DragValue::new(&mut ppi).range(72.0..=720.0).speed(1.0).max_decimals(0).suffix(" ppi")); - register(ui.ctx(), "drag:printPpi", r.rect); + register(ui, "drag:printPpi", r.rect); if r.changed() { patch(app, &ctx, json!({"job": {"ppi": ppi}})); } @@ -469,7 +502,7 @@ fn print_job_color(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, color: &Pri let c = egui::ComboBox::from_id_salt("print-profile").width(190.0).selected_text(shown.clone()).show_ui(ui, |ui| { for (space, label) in [(ManagedSpace::Srgb, "Managed by Printer (sRGB)"), (ManagedSpace::AdobeRgb, "Managed by Printer (Adobe RGB)")] { let r = ui.selectable_label(color.profile == managed(space), crate::i18n::tr(label)); - register(ui.ctx(), format!("item:printProfile-{}", to_value(space).as_str().unwrap_or_default()), r.rect); + register(ui, format!("item:printProfile-{}", to_value(space).as_str().unwrap_or_default()), r.rect); if r.clicked() && color.profile != managed(space) { patch_color(app, &ctx, "profile", to_value(managed(space))); } @@ -479,11 +512,12 @@ fn print_job_color(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, color: &Pri } if app.services.pick_display_profile.is_some() { let r = ui.selectable_label(false, crate::i18n::tr("Other…")); - register(ui.ctx(), "item:printProfile-other", r.rect); + register(ui, "item:printProfile-other", r.rect); pick |= r.clicked(); } }); - register(ui.ctx(), "combo:printProfile", c.response.rect); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Profile")); + register(ui, "combo:printProfile", c.response.rect); }); if pick && let Some(path) = app.services.pick_display_profile.as_mut().and_then(|pick| pick().into_iter().next()) { patch_color(app, &ctx, "profile", json!({"kind": "icc", "path": path})); @@ -502,7 +536,7 @@ fn print_job_color(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, color: &Pri row(ui, t, label, |ui| { let mut v = value; let r = ui.add(egui::DragValue::new(&mut v).range(-100.0..=100.0).speed(0.5).max_decimals(0)); - register(ui.ctx(), format!("drag:print{label}"), r.rect); + register(ui, format!("drag:print{label}"), r.rect); if r.changed() { patch_color(app, &ctx, key, json!(v)); } @@ -557,7 +591,6 @@ impl Sheet { } fn preview(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, st: &PrintSettings, ids: &[PhotoId], pages: usize) { - let ctx = ui.ctx().clone(); // room for the page buttons and, for a package, the selected cell's row (which may wrap) let footer = if st.layout.style.is_package() { 104.0 } else { 44.0 }; let size = vec2(ui.available_width(), (ui.available_height() - footer).max(120.0)); @@ -573,7 +606,7 @@ fn preview(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, s let inner = Rect::from_min_max(area.min + vec2(ruler, ruler), area.max).shrink(14.0); let scale = ((inner.width() as f64 / pw).min(inner.height() as f64 / ph) as f32).max(1.0); let sheet = Sheet { page: Rect::from_center_size(inner.center(), vec2(pw as f32, ph as f32) * scale), scale }; - register(&ctx, "print:page", sheet.page); + register(ui, "print:page", sheet.page); painter.rect_filled(sheet.page.translate(vec2(2.0, 3.0)), 0.0, Color32::from_black_alpha(70)); let bg = st.page.background; @@ -623,7 +656,7 @@ fn preview(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, s let mut shown = Vec::new(); for (i, (r, photo)) in cells.iter().enumerate() { let rect = sheet.rect(r); - register(&ctx, format!("print:gridcell:{i}"), rect); + register(ui, format!("print:gridcell:{i}"), rect); shown.extend(paint_cell(app, &painter, t, st, rect, *photo, &sheet, r)); } page_options(&painter, st, &sheet, &shown, pu.page + 1); @@ -636,7 +669,7 @@ fn preview(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, s pu.selected = None; } let label = ui.label(egui::RichText::new(format!("{} {} / {}", crate::i18n::tr("Page"), pu.page + 1, pages)).color(t.text)); - register(ui.ctx(), "print:pageLabel", label.rect); + register(ui, "print:pageLabel", label.rect); if text_button(ui, "printPageNext", "▶", false).clicked() && pu.page + 1 < pages { pu.page += 1; pu.selected = None; @@ -677,8 +710,8 @@ fn package_cells( let photo = if st.layout.style == Style::CustomPackage { c.photo.map(PhotoId).or(first) } else { first }; let rect = sheet.rect(&c.rect); paint_cell(app, painter, t, st, rect, photo, sheet, &c.rect); - let resp = ui.interact(rect, egui::Id::new(("print-cell", c.id)), Sense::click_and_drag()); - register(&ctx, format!("print:cell:{}", c.id), rect); + let resp = ui.interact(rect, egui::Id::unique(("print-cell", c.id)), Sense::click_and_drag()); + register(ui, format!("print:cell:{}", c.id), rect); if resp.clicked() || resp.drag_started() { pu.selected = Some(c.id); } @@ -719,8 +752,8 @@ fn package_cells( painter.rect_stroke(rect, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Outside); let handle = Rect::from_center_size(rect.right_bottom(), Vec2::splat(HANDLE)); painter.rect_filled(handle, 2.0, t.accent); - let resp = ui.interact(handle, egui::Id::new(("print-resize", sel.id)), Sense::drag()); - register(&ctx, format!("print:resize:{}", sel.id), handle); + let resp = ui.interact(handle, egui::Id::unique(("print-resize", sel.id)), Sense::drag()); + register(ui, format!("print:resize:{}", sel.id), handle); if resp.drag_started() { pu.drag = Some(Drag { cell: sel.id, origin: sel.rect, resize: true, press: press_origin(ui, &resp), total: Vec2::ZERO }); } @@ -856,6 +889,8 @@ fn paint_cell( clip.add(egui::Shape::mesh(mesh)); } None => { + // the page is paper in every theme (its colour is the print's, not the theme's), so + // these stay fixed greys: a photo still to come, and an empty cell clip.rect_filled(shown, 0.0, if photo.is_some() { Color32::from_gray(52) } else { Color32::from_gray(200) }); } } @@ -959,5 +994,17 @@ mod tests { assert_eq!(trim(2.5), "2.5"); assert_eq!(paper_label("a4"), "A4"); assert_eq!(paper_label("4x6"), "4 × 6 in"); + // The Japanese photo and postcard papers show their customary name and metric size. + assert_eq!(paper_label("l"), "L判 (89 × 127 mm)"); + assert_eq!(paper_label("postcard"), "はがき (100 × 148 mm)"); + assert_eq!(paper_label("double-postcard"), "往復はがき (148 × 200 mm)"); + assert_eq!(paper_label("6cut"), "六切 (203 × 254 mm)"); + assert_eq!(paper_label("4cut"), "四切 (254 × 305 mm)"); + // The selector resolves an alias stored by print.set to the canonical option. + assert_eq!(current_paper("はがき"), "postcard"); + assert_eq!(current_paper("L判"), "l"); + assert_eq!(current_paper("Custom"), "custom"); + assert_eq!(paper_label(current_paper("はがき")), "はがき (100 × 148 mm)"); + assert_eq!(paper_label(current_paper("a4")), "A4"); } } diff --git a/crates/ui-egui/src/progress.rs b/crates/ui-egui/src/progress.rs new file mode 100644 index 0000000000..ab7ba9603d --- /dev/null +++ b/crates/ui-egui/src/progress.rs @@ -0,0 +1,191 @@ +//! Work in progress, shown one way everywhere: a [`Progress`] bar (a known fraction, or a gentle +//! sweep when nothing is known yet) and a [`spinner`] for short waits beside text or in a busy +//! [`crate::button::Button`]. It replaces `egui::ProgressBar` and `ui.spinner()`. +//! +//! ```ignore +//! Progress::new(Some(done as f32 / total as f32)).label(text).widget("denoise:progress").show(ui); +//! Progress::new(None).label(tr("Starting…")).show(ui); +//! ui.horizontal(|ui| { spinner(ui, 14.0); ui.label(tr("Selecting…")); }); +//! ``` +//! +//! A bar announces itself to screen readers as a progress indicator with its percentage. Motion +//! asks for repaints only while it is on screen. There is no reduced-motion setting in the app, +//! so the motion is kept slow and small: one gentle sweep, one slow turning arc. + +use std::f32::consts::TAU; + +use egui::{Color32, Pos2, Rect, Response, Sense, Shape, Stroke, Ui, pos2, vec2}; + +use crate::theme::Tokens; + +/// A bar in a model row: it leaves the row's Cancel button its place. +pub const ROW_WIDTH: f32 = 260.0; +/// The narrowest a bar that fills the available width is drawn. +const MIN_WIDTH: f32 = 96.0; +/// Height of a bar that carries text. +const HEIGHT_WITH_TEXT: f32 = 18.0; +/// Height of a bar without text. +const HEIGHT_PLAIN: f32 = 6.0; +/// Seconds an indeterminate bar takes to sweep across and back. +const SWEEP_SECONDS: f64 = 1.8; +/// Seconds a spinner takes for one turn. +const TURN_SECONDS: f64 = 1.2; +/// How often moving things redraw. +const FRAME: std::time::Duration = std::time::Duration::from_millis(33); + +/// `fraction` as a number from 0 to 1: NaN counts as nothing done, and out-of-range values stop at +/// the ends. +pub fn clamp_fraction(fraction: f32) -> f32 { + if fraction.is_nan() { 0.0 } else { fraction.clamp(0.0, 1.0) } +} + +/// `done` of `total` as a fraction, or `None` while the total is not known (0): an unknown total +/// is a bar that sweeps, not one stuck at 0 %. +pub fn fraction_of(done: u64, total: u64) -> Option<f32> { + (total > 0).then(|| clamp_fraction(done as f32 / total as f32)) +} + +/// The whole percent a bar says for `fraction`: rounded down, so 100 comes only at exactly 1.0, but +/// with a little slack so a fraction that is exact in decimals (53 of 100, held as 0.52999997) +/// still says 53. A bar's text and its accessible value both come from here, so they agree. +pub fn percent(fraction: f32) -> u32 { + let f = clamp_fraction(fraction); + let whole = (f64::from(f) * 100.0 + 1e-3).floor() as u32; + if f < 1.0 { whole.min(99) } else { 100 } +} + +/// A progress bar, built and then shown with [`Progress::show`]. +#[derive(Clone, Debug)] +pub struct Progress { + fraction: Option<f32>, + label: Option<String>, + widget: Option<String>, + width: Option<f32>, + dimmed: bool, +} + +impl Progress { + /// `Some(fraction)` of the work done (clamped to 0..=1, NaN as 0), or `None` while it is not + /// known how much there is. + pub fn new(fraction: Option<f32>) -> Self { + Progress { fraction: fraction.map(clamp_fraction), label: None, widget: None, width: None, dimmed: false } + } + + /// The fraction drawn, once clamped (`None` for an indeterminate bar). + pub fn fraction(&self) -> Option<f32> { + self.fraction + } + + /// Text on the bar (a percentage, a count, a file's name), already translated. + pub fn label(mut self, text: impl Into<String>) -> Self { + self.label = Some(text.into()); + self + } + + /// Registered under this id for scripts, tests and `ui.clickWidget` (e.g. `progress:samDownload`). + pub fn widget(mut self, id: impl Into<String>) -> Self { + self.widget = Some(id.into()); + self + } + + /// Drawn in the quiet text colour instead of the accent (work that is being stopped). + pub fn dimmed(mut self, dimmed: bool) -> Self { + self.dimmed = dimmed; + self + } + + /// This wide; by default the bar fills the width the layout has left. + pub fn width(mut self, width: f32) -> Self { + self.width = Some(width); + self + } + + /// Show it where the layout puts it. + pub fn show(self, ui: &mut Ui) -> Response { + let t = Tokens::get(ui.ctx()); + let label = self.label.as_deref().filter(|s| !s.is_empty()); + let width = self.width.unwrap_or_else(|| ui.available_size_before_wrap().x.max(MIN_WIDTH)); + let height = if label.is_some() { HEIGHT_WITH_TEXT } else { HEIGHT_PLAIN }; + let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); + resp.widget_info(|| { + let mut info = match label { + Some(l) => egui::WidgetInfo::labeled(egui::Role::ProgressIndicator, ui.is_enabled(), l), + None => egui::WidgetInfo::new(egui::Role::ProgressIndicator), + }; + info.value = self.fraction.map(|f| f64::from(percent(f))); + info + }); + if let Some(w) = &self.widget { + crate::widgets::register(ui, w.clone(), rect); + } + if !ui.is_rect_visible(rect) { + return resp; + } + let p = ui.painter_at(rect); + let radius = height / 2.0; + p.rect_filled(rect, radius, t.inset); + p.rect_stroke(rect, radius, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + let inner = rect.shrink(1.0); + let fill = match self.fraction { + Some(f) => Rect::from_min_size(inner.min, vec2(inner.width() * f, inner.height())), + None => { + // a short bar sweeping across and back, eased so it slows at the ends + let phase = (ui.input(|i| i.time) / SWEEP_SECONDS).fract() as f32; + let eased = 0.5 - 0.5 * (phase * TAU).cos(); + let len = inner.width() * 0.3; + let x = inner.left() + (inner.width() - len) * eased; + ui.ctx().request_repaint_after(FRAME); + Rect::from_min_size(pos2(x, inner.top()), vec2(len, inner.height())) + } + }; + if fill.width() > 0.0 { + p.with_clip_rect(inner).rect_filled(fill, radius - 1.0, if self.dimmed { t.text_dim } else { t.accent }); + } + if let Some(l) = label { + // the text reads on the track in the theme's colour, and in white where the fill is + let font = t.font(11.5); + let on_track = p.layout_no_wrap(l.to_string(), font.clone(), t.text); + let on_fill = p.layout_no_wrap(l.to_string(), font, Color32::WHITE); + let at = pos2(rect.center().x - on_track.size().x / 2.0, rect.center().y - on_track.size().y / 2.0); + let clipped = ui.painter_at(rect); + clipped.galley(at, on_track, t.text); + clipped.with_clip_rect(rect.intersect(fill)).galley(at, on_fill, Color32::WHITE); + } + resp + } +} + +/// The arc a spinner draws at `time` seconds: points on a circle of `radius` around `center`, +/// covering three quarters of the turn and rotating once per [`TURN_SECONDS`]. +fn arc_points(center: Pos2, radius: f32, time: f64) -> Vec<Pos2> { + let start = ((time / TURN_SECONDS).fract() as f32) * TAU; + let steps = 24; + (0..=steps) + .map(|i| { + let a = start + TAU * 0.75 * (i as f32 / steps as f32); + center + vec2(a.cos(), a.sin()) * radius + }) + .collect() +} + +/// Draw a spinner of `size` points centred in `rect`, in `color`, at `time` seconds. Callers that +/// draw by hand (a busy button) use this; it asks for no repaint itself. +pub fn paint_spinner(p: &egui::Painter, rect: Rect, color: Color32, time: f64) { + let size = rect.width().min(rect.height()); + let width = (size / 8.0).max(1.5); + let radius = ((size - width) / 2.0).max(0.5); + p.add(Shape::line(arc_points(rect.center(), radius, time), Stroke::new(width, color))); +} + +/// A small turning arc beside text that says what is being waited for. It is drawn as a vector +/// arc, not a glyph, and asks for repaints only while it is on screen. +pub fn spinner(ui: &mut Ui, size: f32) -> Response { + let t = Tokens::get(ui.ctx()); + let (rect, resp) = ui.allocate_exact_size(vec2(size, size), Sense::hover()); + resp.widget_info(|| egui::WidgetInfo::new(egui::Role::ProgressIndicator)); + if ui.is_rect_visible(rect) { + paint_spinner(ui.painter(), rect, t.text_dim, ui.input(|i| i.time)); + ui.ctx().request_repaint_after(FRAME); + } + resp +} diff --git a/crates/ui-egui/src/rating.rs b/crates/ui-egui/src/rating.rs new file mode 100644 index 0000000000..8b1183eb63 --- /dev/null +++ b/crates/ui-egui/src/rating.rs @@ -0,0 +1,256 @@ +//! One star rating for the whole interface: the clickable row of five stars ([`Rating`]) and the +//! painter-only helpers for stars drawn onto photos and captions ([`paint_rating`], [`paint_star`]). +//! It replaces `widgets::stars` and the private star-painting loops of the grid badge, the film +//! badges, the compare caption and the filter bar. +//! +//! ```ignore +//! if let Some(r) = Rating::new("bottom", photo.rating).show(ui) { … } +//! paint_rating(ui.painter(), pos, 3, RatingSize::Small, color); +//! ``` +//! +//! Hovering a star previews the rating a click would set; clicking the current rating clears it. +//! The row is one Tab stop (the star of the current rating, or the first when unrated); inside it, ← and → +//! lower and raise the rating (0 to 5) and the focus follows. + +use egui::{Color32, Key, Modifiers, Painter, Pos2, Rect, Sense, Ui, pos2, vec2}; + +use crate::icons::{Icon, paint}; +use crate::theme::Tokens; +use crate::widgets::{announce_selected, register}; + +/// Number of stars in a rating. +const STARS: u8 = 5; + +/// How big a rating is drawn. Each size matches one of the renderers it replaced. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RatingSize { + /// Film badges: 8 px stars every 9 px. + Small, + /// Grid badges and compare captions: 12 px stars every 13 px. + Medium, + /// The clickable row (bottom bar, Info panel, filter bar): 14 px stars in 19 px cells. + Large, +} + +impl RatingSize { + /// Side of one painted star. + pub fn icon(self) -> f32 { + match self { + Self::Small => 8.0, + Self::Medium => 12.0, + Self::Large => 14.0, + } + } + + /// Distance from one painted star to the next in [`paint_rating`]. + pub fn step(self) -> f32 { + match self { + Self::Small => 9.0, + Self::Medium => 13.0, + Self::Large => 17.0, + } + } + + /// Side of one clickable cell in a [`Rating`] row. + fn cell(self) -> f32 { + self.step() + 2.0 + } +} + +/// Paint one star (outline or filled) centred in `rect`. +pub fn paint_star(painter: &Painter, rect: Rect, filled: bool, color: Color32) { + paint(painter, rect, if filled { Icon::StarFilled } else { Icon::Star }, color); +} + +/// Paint `rating` filled stars in a row, the first one's left edge at `pos.x` and its vertical centre +/// at `pos.y`. Returns the width the row takes (0 for no stars), so the caller can lay out what follows. +pub fn paint_rating(painter: &Painter, pos: Pos2, rating: u8, size: RatingSize, color: Color32) -> f32 { + let n = rating.min(STARS); + let side = size.icon(); + for i in 0..n { + let left = pos.x + f32::from(i) * size.step(); + paint_star(painter, Rect::from_min_size(pos2(left, pos.y - side / 2.0), vec2(side, side)), true, color); + } + f32::from(n) * size.step() +} + +/// What the stars show once hovering is taken into account: the hovered star's rating previews over +/// the current one. +fn star_lit(i: u8, rating: u8, hover: Option<u8>) -> bool { + i < hover.unwrap_or(rating) +} + +/// The rating a click on star `n` (1 to 5) sets: clicking the current rating clears it. +fn clicked_rating(current: u8, n: u8) -> u8 { + if current == n { 0 } else { n } +} + +/// The rating the arrow keys move to from `current`, if any. +fn nudged_rating(current: u8, left: bool, right: bool) -> Option<u8> { + match (left, right) { + (true, false) if current > 0 => Some(current - 1), + (false, true) if current < STARS => Some(current + 1), + _ => None, + } +} + +/// A row of five stars. Build it, then [`Rating::show`]. +pub struct Rating { + id: String, + rating: u8, + ids_prefix: Option<String>, +} + +impl Rating { + /// A rating of `rating` (0 to 5) whose stars are reachable as `star:{id}:{n}`. + pub fn new(id: impl Into<String>, rating: u8) -> Self { + Self { id: id.into(), rating: rating.min(STARS), ids_prefix: None } + } + + /// Register the stars under `{prefix}{n}` instead of `star:{id}:{n}`, for rows that already have + /// published automation ids (the filter bar's `filter:star3`). + pub fn automation_ids(mut self, prefix: impl Into<String>) -> Self { + self.ids_prefix = Some(prefix.into()); + self + } + + fn widget_id(&self, n: u8) -> String { + match &self.ids_prefix { + Some(prefix) => format!("{prefix}{n}"), + None => format!("star:{}:{n}", self.id), + } + } + + fn star_id(&self, ui: &Ui, i: u8) -> egui::Id { + ui.scope_id().with(("rating-star", &self.id, i)) + } + + /// Draw the row. Returns the new rating when a click or an arrow key changed it. + pub fn show(self, ui: &mut Ui) -> Option<u8> { + let t = Tokens::get(ui.ctx()); + let cell = RatingSize::Large.cell(); + let mut out = None; + let mut hover_n = None; + let mut focused_at = None; + let mut cells = [Rect::NOTHING; STARS as usize]; + // One Tab stop for the row, like a radio group: the star of the current rating (the first when + // unrated), plus whichever star already has the focus so it keeps it + let stop = self.rating.max(1) - 1; + for (i, slot) in (0..STARS).zip(cells.iter_mut()) { + let id = self.star_id(ui, i); + let (r, _) = ui.allocate_exact_size(vec2(cell, cell), Sense::hover()); + let sense = if i == stop || ui.memory(|m| m.has_focus(id)) { Sense::click() } else { Sense::CLICK }; + let resp = ui.interact(r, id, sense); + announce_selected(&resp, format!("{} ★", i + 1), i < self.rating); + register(ui, self.widget_id(i + 1), r); + if resp.hovered() { + hover_n = Some(i + 1); + } + if resp.clicked() { + out = Some(clicked_rating(self.rating, i + 1)); + } + if resp.has_focus() { + focused_at = Some(i); + // ← and → step the rating instead of moving the focus to the neighbouring widget + ui.memory_mut(|m| { + m.set_focus_lock_filter(resp.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() }); + }); + ui.painter().rect_stroke(r.expand(1.0), 6.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Outside); + } + *slot = r; + } + let focused = focused_at.is_some(); + if focused && out.is_none() { + let (left, right) = ui.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::ArrowLeft), i.consume_key(Modifiers::NONE, Key::ArrowRight))); + if left || right { + // egui picked the neighbour to focus from this same key before the lock above could apply (the + // first arrow after Tab): cancel that move + ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); + } + out = nudged_rating(self.rating, left, right); + if let Some(n) = out { + // keep the focus on the star that is now the row's Tab stop + let to = self.star_id(ui, n.max(1) - 1); + ui.memory_mut(|m| m.request_focus(to)); + } else if focused_at != Some(stop) { + // the rating changed from outside (undo, a shortcut, another photo): the focus follows the Tab stop + let to = self.star_id(ui, stop); + ui.memory_mut(|m| m.request_focus(to)); + } + } + // The hovered star also gets the icon-button hover square, so hovering the current rating (where + // the preview looks the same) still shows feedback. + let side = RatingSize::Large.icon(); + for (i, r) in (0..STARS).zip(cells) { + if hover_n == Some(i + 1) { + ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.7)); + } + let filled = star_lit(i, self.rating, hover_n); + paint_star(ui.painter(), Rect::from_center_size(r.center(), vec2(side, side)), filled, if filled { t.star } else { t.icon }); + } + out + } +} + +/// A frameless star toggle for favourites: filled when `favorite`, named `name` for screen readers and as +/// its tooltip, reachable as `widget` (a full automation id). A square one line tall. +pub fn favorite_button(ui: &mut Ui, widget: String, favorite: bool, name: &str) -> egui::Response { + let t = Tokens::get(ui.ctx()); + let side = ui.spacing().interact_size.y; + let (r, resp) = ui.allocate_exact_size(vec2(side, side), Sense::click()); + announce_selected(&resp, name, favorite); + // (rows scrolled out of view can't be clicked) + if ui.is_rect_visible(r) { + register(ui, widget, r); + } + if resp.hovered() { + ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.7)); + } + if resp.has_focus() { + ui.painter().rect_stroke(r.expand(1.0), 6.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Outside); + } + let icon = RatingSize::Medium.icon(); + paint_star(ui.painter(), Rect::from_center_size(r.center(), vec2(icon, icon)), favorite, if favorite { t.star } else { t.icon }); + resp.on_hover_text(name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_hovered_star_previews_its_rating() { + let lit = |rating, hover| (0..STARS).filter(|&i| star_lit(i, rating, hover)).count(); + assert_eq!(lit(2, None), 2, "no hover shows the rating"); + assert_eq!(lit(2, Some(4)), 4); + assert_eq!(lit(5, Some(1)), 1); + assert_eq!(lit(0, Some(3)), 3); + } + + #[test] + fn arrows_stay_between_zero_and_five() { + assert_eq!(nudged_rating(0, true, false), None); + assert_eq!(nudged_rating(5, false, true), None); + assert_eq!(nudged_rating(3, true, false), Some(2)); + assert_eq!(nudged_rating(3, false, true), Some(4)); + assert_eq!(nudged_rating(3, true, true), None); + } + + #[test] + fn rows_scrolled_out_of_view_are_not_registered() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = + ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(300.0, 100.0))), ..Default::default() }, |ui| { + egui::ScrollArea::vertical().max_height(60.0).show(ui, |ui| { + for i in 0..30 { + favorite_button(ui, format!("effectStar:{i}"), false, "Favorite"); + } + }); + }); + out.textures_delta.clear(); + let ids: Vec<String> = crate::widgets::take_registry(&ctx).into_iter().map(|(id, _)| id).collect(); + assert!(ids.contains(&"effectStar:0".to_string()), "{ids:?}"); + assert!(!ids.contains(&"effectStar:29".to_string()), "{ids:?}"); + } +} diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 1ed1071c25..973c0d8b86 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -217,6 +217,8 @@ pub struct Renderer { pub last_main_ms: f64, /// Jobs finished since start (for inspect/perf). pub completed: u64, + /// Finished jobs thrown away because a newer request for their slot had replaced them. + pub discarded: u64, /// Keep a CPU copy of every texture so the UI can be rasterized headlessly (set when the app /// is driven by the control channel). pub keep_pixels: bool, @@ -297,6 +299,7 @@ impl Renderer { live_hdr_histogram: None, last_main_ms: 0.0, completed: 0, + discarded: 0, keep_pixels: false, stages: HashMap::new(), quick_tried: HashMap::new(), @@ -662,6 +665,15 @@ impl Renderer { self.pending.len() } + /// Test seam: make the renderer look busy without starting a job (capture deadlines). + #[cfg(test)] + pub(crate) fn force_in_flight_for_test(&mut self, count: usize) { + self.pending.clear(); + for i in 0..count { + self.pending.insert(Slot::Prefetch((i % 256) as u8), (0, 0)); + } + } + /// Why the last render for `slot` failed (until a render with another key succeeds). pub fn failure(&self, slot: Slot) -> Option<&str> { self.failed.get(&slot).map(|f| f.1.as_str()) @@ -781,9 +793,9 @@ impl Renderer { // wasm: run one job per frame on this thread, timed with the host clock #[cfg(target_arch = "wasm32")] let inline_ms = { - let t0 = crate::now_ms(); + let t0 = crate::monotonic_ms(); self.pool.run_inline(1); - crate::now_ms() - t0 + crate::monotonic_ms() - t0 }; #[cfg(not(target_arch = "wasm32"))] let inline_ms = 0.0; @@ -844,6 +856,7 @@ impl Renderer { && self.shown_ids.get(&slot).is_none_or(|shown| r.request_id > *shown) && r.rendered.is_ok(); if !newer_draft { + self.discarded += 1; continue; } session.accept(&r); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index e7b58a9b52..8ea82f68dc 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -54,22 +54,39 @@ pub fn find_bindable(id: &str) -> Option<&'static Bindable> { /// The shortcut `id` has now: the user's choice (`""` = none), else the declared one. An entry /// that doesn't parse (a hand-edited `ui.json`, a modifier-only key saved by an older build) is -/// ignored. +/// ignored. The declared shortcut yields to a saved entry that gives its key to another known +/// command other than its contextual partner. pub fn binding<'a>(keymap: &'a Keymap, id: &str, default: Option<&'a str>) -> Option<&'a str> { match keymap.get(id) { Some(sc) if sc.is_empty() => None, Some(sc) if parse(sc).is_some() => Some(sc.as_str()), - _ => default, + _ => default.filter(|sc| !assigned_elsewhere(keymap, id, sc)), } } +/// Whether the keymap gives the key `sc` to a known command other than `id` and its contextual +/// partner. +fn assigned_elsewhere(keymap: &Keymap, id: &str, sc: &str) -> bool { + let Some(key) = parse(sc) else { return false }; + saved_keys(keymap) + .any(|(other, k)| other != id && k == key && !CONTEXTUAL.iter().any(|(x, y)| (*x == id && *y == other) || (*y == id && *x == other))) +} + +/// The keys the keymap gives to known commands, with each command's id. Entries for commands this +/// build doesn't know and entries that don't parse are ignored. +pub(crate) fn saved_keys(keymap: &Keymap) -> impl Iterator<Item = (&str, (Modifiers, Key))> { + keymap.iter().filter(|(id, _)| find_bindable(id).is_some()).filter_map(|(id, sc)| Some((id.as_str(), parse(sc)?))) +} + /// The effective shortcut of command `id` (`None` for unknown commands). pub fn shortcut_of<'a>(keymap: &'a Keymap, id: &str) -> Option<&'a str> { find_bindable(id).and_then(|b| binding(keymap, id, b.default)) } -/// Engine commands that intentionally share a key and are disambiguated by context in [`handle`]. -pub const CONTEXTUAL: &[(&str, &str)] = &[("photo.reject", "crop.rotateAspect")]; +/// Engine commands that intentionally share a key and are disambiguated by context in [`handle`]: +/// the X pair by the Crop panel, A by whether it is open (Visualize Spots everywhere, the aspect +/// lock under the Crop panel). +pub const CONTEXTUAL: &[(&str, &str)] = &[("photo.reject", "crop.rotateAspect"), ("view.visualizeSpots", "crop.lockAspect")]; /// Commands other than `id` whose shortcut is the key `sc` (contextual partners excepted). pub fn conflicts(keymap: &Keymap, id: &str, sc: &str) -> Vec<&'static str> { @@ -332,11 +349,10 @@ fn keyboard_owned(app: &LightcraftApp, ctx: &egui::Context) -> bool { [Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown, Key::Enter, Key::Space].iter().any(|key| input.key_pressed(*key)) }); } - let chrome = app - .ui - .docking - .as_ref() - .is_some_and(|workspace| craft_ui::docking::DockArea::new(egui::Id::new("lightcraft-docking")).chrome_has_focus(ctx, &workspace.layout)); + let chrome = + app.ui.docking.as_ref().is_some_and(|workspace| { + craft_ui::docking::DockArea::new(egui::Id::unique("lightcraft-docking")).chrome_has_focus(ctx, &workspace.layout) + }); if !chrome { return true; } @@ -347,12 +363,20 @@ fn keyboard_owned(app: &LightcraftApp, ctx: &egui::Context) -> bool { }) } +/// Dispatch the global shortcut pass. It yields while a dialog, prompt, blocking library window, +/// text field, name edit or shortcut recording owns input, then fires saved command bindings, +/// aliases and fixed photo keys, respecting native menu ownership and open popups. pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { if !matches!(app.ui.dialog, Some(crate::state::Dialog::Shortcuts)) { app.recording_shortcut = None; } - // Dialogs own their keys (including Esc and text editing); background photo actions wait. - if app.ui.dialog.is_some() { + // Dialogs own their keys (including Esc and text editing); background photo actions wait. A + // quit prompt or settings notice owns every key too: its Foreground dim only blocks the + // pointer, so without this a rating or navigation shortcut would still act behind it. The + // blocking library window (error or launch list) owns all app shortcuts for every settled + // frame, not only its shield pass; its own list keys are consumed earlier by + // `library_problem::logic`, and its buttons remain reachable through the control channel. + if app.ui.dialog.is_some() || crate::panels::notices::blocks_input(app) || crate::panels::library_problem::blocks_dialog_input(app) { return; } if app.recording_shortcut.is_none() && app.ui.name_edit.is_none() && crate::panels::person::handle_bulk_key(app, ctx) { @@ -371,8 +395,8 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { // The grid navigation keys act on the photos in view, so they wait while the full-screen preview // covers the grid: a key must not move the selection onto photos nobody can see. let grid_navigation = grid && !app.ui.fullscreen; - // keys the user gave to a command: the fixed bindings below (aliases, ratings) yield to them - let taken: Vec<(Modifiers, Key)> = keymap.values().filter_map(|s| parse(s)).collect(); + // keys the user gave to a known command: the fixed bindings below (aliases, ratings) yield to them + let taken: Vec<(Modifiers, Key)> = saved_keys(keymap).map(|(_, k)| k).collect(); // an open popup (a menu, a date picker's calendar) closes on Esc itself: Esc's command (Back, // which also closes dialogs) waits until nothing is open let popup_open = egui::Popup::is_any_open(ctx); @@ -443,9 +467,10 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { // Auto Advance then moves on (next candidate in Compare, next photo elsewhere) let cull = |app: &mut LightcraftApp, id: &str, mut params: serde_json::Value, advance: bool| { compare::target_active(app, &mut params); + let was = app.session.active(); let ok = app.run(id, params).is_ok(); if ok && (advance || app.ui.auto_advance) { - compare::advance(app); + compare::advance(app, was); } }; for (id, params) in aliased { @@ -621,6 +646,13 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { if f == "crop.rotateAspect" && app.ui.right != crate::state::RightPanel::Crop { continue; } + // A is both Visualize Spots and the crop aspect lock: each key only in its own context + if f == "view.visualizeSpots" && app.ui.right == crate::state::RightPanel::Crop { + continue; + } + if f == "crop.lockAspect" && app.ui.right != crate::state::RightPanel::Crop { + continue; + } // / refreshes the selected spot's source in the Remove tool (the filmstrip elsewhere) if f == "view.filmstrip" && app.ui.right == crate::state::RightPanel::Remove && app.session.active_spot.is_some() { let _ = app.run("spot.refreshSource", json!({})); @@ -631,12 +663,11 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { let _ = app.run("view.maskOverlayColor", json!({})); continue; } - // while cropping: O cycles the guides, Shift+O their orientation, A locks the aspect + // while cropping: O cycles the guides, Shift+O their orientation if app.ui.right == crate::state::RightPanel::Crop { let crop_key = match f.as_str() { "view.maskOverlay" => Some(("view.cropOverlay", json!({}))), "view.cropOverlay" => Some(("view.cropOverlayOrientation", json!({}))), - "view.visualizeSpots" => Some(("crop.aspect", json!({"aspect": "toggle"}))), _ => None, }; if let Some((cmd, p)) = crop_key { @@ -819,6 +850,50 @@ mod tests { } } + /// A saved keymap entry that gives a key to one command (kept from before another command + /// declared that key) wins: the press runs that command alone, and the other command's declared + /// key comes back once the entry is gone. + #[test] + fn a_saved_key_wins_over_another_commands_declared_key() { + use lightcraft_catalog::{Flag, PhotoId}; + let mut h = library(); + h.app.ui.settings.keymap.insert("photo.increaseRating".into(), "P".into()); + assert_eq!(super::shortcut_of(&h.app.ui.settings.keymap, "photo.pick"), None); + assert_eq!(super::conflicts(&h.app.ui.settings.keymap, "view.survey", "P"), vec!["photo.increaseRating"]); + key(&mut h, "P", false); + let photo = h.app.session.catalog.photo(PhotoId(1)).unwrap(); + assert_eq!(photo.rating, 1, "the saved key raised the rating"); + assert_eq!(photo.flag, Flag::None, "Flag as Pick's declared key yielded"); + // with the entry gone, P picks again + h.app.ui.settings.keymap.remove("photo.increaseRating"); + assert_eq!(super::shortcut_of(&h.app.ui.settings.keymap, "photo.pick"), Some("P")); + key(&mut h, "P", false); + assert_eq!(h.app.session.catalog.photo(PhotoId(1)).unwrap().flag, Flag::Pick); + // a contextual partner's saved key does not silence the other side + h.app.ui.settings.keymap.insert("crop.rotateAspect".into(), "X".into()); + assert_eq!(super::shortcut_of(&h.app.ui.settings.keymap, "photo.reject"), Some("X")); + // nor does an entry for a command this build doesn't know + h.app.ui.settings.keymap.insert("no.suchCommand".into(), "U".into()); + assert_eq!(super::shortcut_of(&h.app.ui.settings.keymap, "photo.unflag"), Some("U")); + } + + /// Keymap entries for commands this build doesn't know take no key: an alias, a rating key and + /// a declared shortcut on the same keys keep working. + #[test] + fn junk_keymap_entries_leave_aliases_ratings_and_declared_keys() { + use lightcraft_catalog::{Flag, PhotoId}; + let mut h = library(); + for (id, sc) in [("no.suchCommand", "Shift+X"), ("no.otherCommand", "5"), ("no.thirdCommand", "P")] { + h.app.ui.settings.keymap.insert(id.into(), sc.into()); + } + key(&mut h, "5", false); + assert_eq!(h.app.session.catalog.photo(PhotoId(1)).unwrap().rating, 5, "5 still rates"); + key(&mut h, "P", false); + assert_eq!(h.app.session.catalog.photo(PhotoId(1)).unwrap().flag, Flag::Pick, "P still picks"); + key(&mut h, "X", true); + assert_eq!(h.app.session.catalog.photo(PhotoId(1)).unwrap().flag, Flag::Reject, "Shift+X still rejects"); + } + #[test] fn classic_f6_and_f7_toggle_the_filmstrip_and_left_panel() { let mut h = library(); @@ -924,6 +999,38 @@ mod tests { } } + #[test] + fn culling_keys_go_on_from_a_photo_that_leaves_the_filter() { + // #2312: the filter shows one-star photos; taking photo 2's star off makes photo 3 active, once, with or + // without Shift and Auto Advance, and → goes on from there instead of from the first photo + use lightcraft_catalog::PhotoId; + let one_star = || { + let mut h = library(); + h.app.session.execute("library.selectAll", &json!({})).unwrap(); + h.app.session.execute("photo.rate", &json!({"rating": 1})).unwrap(); + h.app.session.execute("library.filter", &json!({"rating": 1, "ratingOp": "exactly"})).unwrap(); + h.app.session.execute("library.select", &json!({"ids": [2]})).unwrap(); + h + }; + for view in [crate::state::ViewMode::PhotoGrid, crate::state::ViewMode::Detail] { + for (shift, auto) in [(false, false), (true, false), (false, true), (true, true)] { + let mut h = one_star(); + h.app.ui.view = view; + h.app.ui.auto_advance = auto; + key(&mut h, "0", shift); + assert_eq!(h.app.session.catalog.photo(PhotoId(2)).unwrap().rating, 0); + assert_eq!(h.app.session.active(), Some(PhotoId(3)), "{view:?} Shift={shift} Auto Advance={auto}"); + key(&mut h, "right", false); + assert_eq!(h.app.session.active(), Some(PhotoId(4)), "{view:?} Shift={shift} Auto Advance={auto}"); + } + } + // the Photo menu with Auto Advance too + let mut h = one_star(); + h.app.ui.auto_advance = true; + crate::menubar::run_item(&mut h.app, "photo.rate", json!({"rating": 0})).unwrap(); + assert_eq!(h.app.session.active(), Some(PhotoId(3))); + } + #[test] fn color_label_actions_show_feedback_only_after_success() { use lightcraft_catalog::PhotoId; @@ -1128,7 +1235,8 @@ mod tests { } for (i, (k, a)) in ui.iter().enumerate() { for (k2, b) in &ui[i + 1..] { - assert!(k != k2, "{a} and {b} share a key"); + let contextual = CONTEXTUAL.iter().any(|(x, y)| (x == a && y == b) || (x == b && y == a)); + assert!(k != k2 || contextual, "{a} and {b} share a key"); } } for (i, (k, a)) in engine.iter().enumerate() { @@ -1246,7 +1354,7 @@ mod tests { }, |ui| { let ctx = ui.ctx(); - egui::Popup::open_id(ctx, egui::Id::new("issue1771-menu")); + egui::Popup::open_id(ctx, egui::Id::unique("issue1771-menu")); assert!(egui::Popup::is_any_open(ctx)); super::super::handle(&mut h.app, ctx); }, @@ -1317,6 +1425,10 @@ mod relative_rating_tests; #[path = "shortcuts/tests_flag_cycle.rs"] mod flag_cycle_tests; +#[cfg(test)] +#[path = "shortcuts/tests_enable_filters.rs"] +mod enable_filters_tests; + #[cfg(test)] #[path = "shortcuts/tests_filter_bar_key.rs"] mod filter_bar_key_tests; diff --git a/crates/ui-egui/src/shortcuts/tests_enable_filters.rs b/crates/ui-egui/src/shortcuts/tests_enable_filters.rs new file mode 100644 index 0000000000..0f42c3eff5 --- /dev/null +++ b/crates/ui-egui/src/shortcuts/tests_enable_filters.rs @@ -0,0 +1,69 @@ +//! Cmd+L (Library > Enable Filters) switches the filter off and on from the keyboard and the menu. +use egui::{Key, Modifiers}; +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::LightcraftApp; +use crate::state::ViewMode; + +fn app() -> lightcraft_engine::Result<LightcraftApp> { + let mut s = lightcraft_engine::Session::new(); + for id in 1..=3 { + let photo = Photo::new( + PhotoId(id), + Source::File { path: format!("/lightcraft-enable-filters-keys/{id}.jpg") }, + &format!("{id}.jpg"), + "JPEG", + 40, + 30, + "2026-10-23", + ); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) })?; + } + s.execute("library.select", &json!({"ids": [1]}))?; + s.execute("photo.rate", &json!({"ids": [1], "rating": 4}))?; + s.execute("library.filter", &json!({"rating": 4, "text": "1.jpg"}))?; + let mut app = LightcraftApp::new(s, crate::Services { png: None, ..Default::default() }); + app.ui.search = "1.jpg".into(); + Ok(app) +} + +fn press(app: &mut LightcraftApp, ctx: &egui::Context) { + let events = vec![egui::Event::Key { key: Key::L, physical_key: Some(Key::L), pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]; + let mut out = ctx.run_ui( + egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }, + |ui| super::handle(app, ui.ctx()), + ); + out.textures_delta.clear(); +} + +#[test] +fn the_key_is_cmd_l() { + assert_eq!(super::shortcut_of(&Default::default(), "library.toggleFilters"), Some("Cmd+L")); +} + +#[test] +fn cmd_l_switches_the_filter_off_and_on_in_the_grids_and_the_loupe() { + for view in [ViewMode::PhotoGrid, ViewMode::SquareGrid, ViewMode::Detail] { + let mut app = app().unwrap(); + app.ui.view = view; + let ctx = egui::Context::default(); + press(&mut app, &ctx); + assert_eq!(app.session.visible().len(), 3, "{view:?}: off shows every photo"); + assert_eq!(app.ui.search, "", "{view:?}: the search field follows"); + assert_eq!(crate::menubar::checked(&app, "library.toggleFilters"), Some(false)); + press(&mut app, &ctx); + assert_eq!(app.session.visible().len(), 1, "{view:?}: on brings the filter back"); + assert_eq!(app.ui.search, "1.jpg"); + assert_eq!(crate::menubar::checked(&app, "library.toggleFilters"), Some(true)); + } +} + +#[test] +fn the_menu_item_does_the_same() { + let mut app = app().unwrap(); + crate::menubar::run_item(&mut app, "library.toggleFilters", serde_json::Value::Null).unwrap(); + assert_eq!(app.session.visible().len(), 3); + assert_eq!(app.ui.search, ""); + assert_eq!(crate::menubar::shortcut_text("Cmd+L", true), "⌘L"); +} diff --git a/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs b/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs index 41d0b1c2d3..80a904c0e7 100644 --- a/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs +++ b/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs @@ -36,7 +36,7 @@ fn frame(app: &mut LightcraftApp, ctx: &egui::Context, key: Option<Key>, text: O egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }, |ui| { if let Some(text) = text.as_deref_mut() { - ui.add(egui::TextEdit::singleline(text).id(egui::Id::new("filter-bar-key-search"))).request_focus(); + ui.add(egui::TextEdit::singleline(text).id(egui::Id::unique("filter-bar-key-search"))).request_focus(); } super::handle(app, ui.ctx()); }, diff --git a/crates/ui-egui/src/shortcuts/tests_flag_cycle.rs b/crates/ui-egui/src/shortcuts/tests_flag_cycle.rs index d4e6deec5d..109dca6076 100644 --- a/crates/ui-egui/src/shortcuts/tests_flag_cycle.rs +++ b/crates/ui-egui/src/shortcuts/tests_flag_cycle.rs @@ -37,7 +37,7 @@ fn frame(app: &mut LightcraftApp, ctx: &egui::Context, key: Option<(Key, Modifie egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }, |ui| { if let Some(text) = text.as_deref_mut() { - ui.add(egui::TextEdit::singleline(text).id(egui::Id::new("flag-cycle-search"))).request_focus(); + ui.add(egui::TextEdit::singleline(text).id(egui::Id::unique("flag-cycle-search"))).request_focus(); } super::handle(app, ui.ctx()); }, diff --git a/crates/ui-egui/src/shortcuts/tests_relative_ratings.rs b/crates/ui-egui/src/shortcuts/tests_relative_ratings.rs index 8ca2adc1a7..94ec5098b4 100644 --- a/crates/ui-egui/src/shortcuts/tests_relative_ratings.rs +++ b/crates/ui-egui/src/shortcuts/tests_relative_ratings.rs @@ -44,7 +44,7 @@ fn frame(app: &mut LightcraftApp, ctx: &egui::Context, key: Option<Key>, text: O egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }, |ui| { if let Some(text) = text.as_deref_mut() { - ui.add(egui::TextEdit::singleline(text).id(egui::Id::new("relative-rating-search"))).request_focus(); + ui.add(egui::TextEdit::singleline(text).id(egui::Id::unique("relative-rating-search"))).request_focus(); } super::handle(app, ui.ctx()); }, diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8cb37d3ef5..422d907f3a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -166,6 +166,18 @@ pub enum StartupView { Detail, } +/// What the desktop app opens at launch (Settings ▸ General ▸ At launch; issue #1290). `--library` +/// and `LIGHTCRAFT_LIBRARY` come first either way. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LaunchLibrary { + /// The library open when the app last quit (holding Alt/Option as the window appears asks once). + #[default] + Last, + /// A window lists the recent libraries to choose from. + Ask, +} + /// When grid cells show their rating / flag / edited badges. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -247,12 +259,35 @@ impl LoupeInfoField { } /// The three lines each mode of the info overlay shows: Info 1 ([`InfoOverlay::Basic`]) and -/// Info 2 ([`InfoOverlay::Exposure`]). +/// Info 2 ([`InfoOverlay::Exposure`]), and which of them Show Briefly When Photo Changes shows. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct LoupeInfo { pub info1: [LoupeInfoField; 3], pub info2: [LoupeInfoField; 3], + /// Show Briefly When Photo Changes: while the info overlay is off, this Info shows for + /// [`BRIEF_INFO_SECS`] each time the loupe changes to another photo ([`InfoOverlay::Off`]: + /// neither). + pub briefly: InfoOverlay, +} + +/// Passes after Add Keywords within which the Add keyword box takes the cursor (the panel may +/// need a pass to open first). +pub const FOCUS_KEYWORDS_PASSES: u64 = 2; + +/// How long Show Briefly When Photo Changes shows the info overlay (seconds). +pub const BRIEF_INFO_SECS: f64 = 3.0; + +/// When the loupe last changed photo, for Show Briefly When Photo Changes +/// ([`LoupeInfo::briefly`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BriefInfo { + /// The photo the loupe showed last. + pub photo: Option<lightcraft_catalog::PhotoId>, + /// When the loupe changed to it (seconds on egui's clock). + pub since: f64, + /// The brief info overlay shows this frame. + pub shown: bool, } impl LoupeInfo { @@ -264,7 +299,7 @@ impl LoupeInfo { impl Default for LoupeInfo { fn default() -> Self { - LoupeInfo { info1: LoupeInfo::INFO1, info2: LoupeInfo::INFO2 } + LoupeInfo { info1: LoupeInfo::INFO1, info2: LoupeInfo::INFO2, briefly: InfoOverlay::Off } } } @@ -407,6 +442,15 @@ pub struct AppSettings { /// Libraries opened recently, newest first (File ▸ Open Recent Library; at most /// [`RECENT_LIBRARIES`]). pub recent_libraries: Vec<String>, + /// When each recent library was last opened (path → the session clock's ISO 8601 time), for + /// the launch window. A separate key so files from earlier versions, and earlier versions + /// reading this one, keep their list (issue #1290). + #[serde(rename = "recentLibrariesOpened", deserialize_with = "lenient")] + pub recent_opened: std::collections::BTreeMap<String, String>, + /// Open the last library at launch, or ask (a value this version doesn't know reads as the + /// default). + #[serde(deserialize_with = "lenient")] + pub at_launch: LaunchLibrary, pub startup_view: StartupView, /// Ask before moving photos to Recently Deleted. Saved under a new key: earlier versions saved /// `confirmDelete: false` by default (#1239). @@ -415,6 +459,11 @@ pub struct AppSettings { /// Ask before photos dropped on a Folders row move there on disk (the dialog's "Don't ask /// again" turns it off). pub ask_before_move: bool, + /// A click on the dimmed backdrop around a dialog closes it, like Esc (off: a stray click + /// never throws away a dialog's choices). + pub close_dialogs_outside: bool, + /// Photos and folders dropped on the window import at once, without the import review. + pub import_dropped_directly: bool, /// GPU rendering allowed (`app.gpu`). pub gpu: bool, /// Largest long edge (pixels) the user lets the loupe render at; 0 = Automatic (the size it is @@ -432,12 +481,19 @@ pub struct AppSettings { pub photocraft_file: EditFile, /// Memory the caches may hold together, in MB (0 = automatic; `app.memoryBudget`). pub memory_mb: u32, + /// The Info panel's metadata fields with several photos selected: true (the default) shows the + /// values the selected photos share and marks each field where they differ (Selected Photos), + /// false shows the active photo's values (Target Photo) (`view.infoSelectedPhotos`). + pub info_selected_photos: bool, /// Filmstrip: file names above the thumbnails. pub film_names: bool, /// Filmstrip: rating / flag / edited badges on the thumbnails. pub film_badges: bool, /// Grid: when to show the rating / flag / edited badges. pub grid_badges: GridBadges, + /// View ▸ View Options ▸ Show message when loading or rendering photos: the loupe says + /// "Rendering…" while the photo it shows is not the finished render. + pub loupe_messages: bool, /// Shortcuts the user changed (Help ▸ Keyboard Shortcuts): command id → shortcut, `""` = none. pub keymap: crate::shortcuts::Keymap, /// Auto (follow the system), Dark or Light. @@ -455,7 +511,7 @@ pub struct AppSettings { /// The Keywording box: whole keyword paths, or grouped by the keyword they are inside. #[serde(deserialize_with = "lenient")] pub keyword_chips: KeywordChips, - /// View ▸ Show Focus Point: draw the box the camera focused on (`view.focusPoint`). + /// View ▸ Focus Point: draw the box the camera focused on (`view.focusPoint`). pub focus_point: bool, /// View ▸ Zoom to Focus Point: Toggle Zoom (Z) centres the zoomed view on the camera's focus point /// when the photo has one (`view.zoomToFocus`). @@ -463,6 +519,22 @@ pub struct AppSettings { /// View ▸ View Options: the lines the loupe's info overlay shows in Info 1 and Info 2. #[serde(deserialize_with = "lenient")] pub loupe_info: LoupeInfo, + /// File ▸ Import Lightroom Catalog…: ask whether the catalog merges into the open library or + /// gets a new one, or always merge (issue #2672; the window's "Don't ask again" picks that). + #[serde(deserialize_with = "lenient")] + pub lightroom_import: LightroomImport, +} + +/// Where File ▸ Import Lightroom Catalog… puts a catalog (Settings ▸ General ▸ Library). Saved as +/// `"ask"` / `"alwaysMerge"`; anything else in a hand-edited `ui.json` reads as [`Self::Ask`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LightroomImport { + /// A window asks each time: merge into the open library, or create a new library for it. + #[default] + Ask, + /// Merge into the open library without asking (how imports worked before the window). + AlwaysMerge, } impl Default for AppSettings { @@ -470,9 +542,13 @@ impl Default for AppSettings { AppSettings { library_path: String::new(), recent_libraries: Vec::new(), + recent_opened: Default::default(), + at_launch: LaunchLibrary::Last, startup_view: StartupView::Last, confirm_delete: true, ask_before_move: true, + close_dialogs_outside: false, + import_dropped_directly: false, gpu: true, preview_limit: 0, external_editor: String::new(), @@ -480,9 +556,11 @@ impl Default for AppSettings { photocraft_path: String::new(), photocraft_file: EditFile { format: EditFormat::Psd, ..EditFile::default() }, memory_mb: 0, + info_selected_photos: true, film_names: true, film_badges: true, grid_badges: GridBadges::Auto, + loupe_messages: true, keymap: Default::default(), appearance_mode: AppearanceMode::Dark, dark_theme: DarkTheme::Charcoal, @@ -493,6 +571,7 @@ impl Default for AppSettings { focus_point: false, zoom_to_focus: true, loupe_info: LoupeInfo::default(), + lightroom_import: LightroomImport::Ask, } } } @@ -712,6 +791,10 @@ pub struct UiState { /// a later save succeeds). #[serde(skip)] pub unsaved_seen: bool, + /// Help ▸ Debug ▸ Frame Rate (`view.frameRate`): the frame-rate display + /// (`crate::frame_rate`). A debugging aid, never saved; `LIGHTCRAFT_FPS=1` starts with it on. + #[serde(skip)] + pub frame_rate: bool, pub view: ViewMode, pub left_panel: bool, pub right: RightPanel, @@ -805,6 +888,10 @@ pub struct UiState { /// The last person page left: the People view offers a way back to it next to its title. #[serde(skip)] pub last_person: Option<String>, + /// Assisted Culling's burst settings last confirmed (gap in seconds, similarity), for this + /// session; `None` until the dialog is first confirmed (then 10 s, 0.93). + #[serde(skip)] + pub cull_burst: Option<(f32, f32)>, /// "More" faces the user hid with ×, for this session: (photo, region index). #[serde(skip)] pub dismissed_faces: std::collections::HashSet<(u64, usize)>, @@ -826,10 +913,12 @@ pub struct UiState { pub external_edits: Vec<u64>, #[serde(skip)] pub was_focused: bool, - /// When the watched folder was last scanned (egui time). + /// When the watched folder was last scanned (monotonic app time, so a hidden window keeps + /// scanning). #[serde(skip)] pub auto_import_at: f64, - /// When the automatic XMP writes that failed were last tried again (egui time), and how many were waiting then. + /// When the automatic XMP writes that failed were last tried again (monotonic app time), and how + /// many were waiting then. #[serde(skip)] pub sidecar_retry_at: f64, #[serde(skip)] @@ -845,6 +934,11 @@ pub struct UiState { /// Focus the search field on the next frame (Edit → Find…). #[serde(skip)] pub focus_search: bool, + /// Put the cursor in the Keywords panel's Add keyword box (Add Keywords): the egui pass it was + /// asked on. A box drawn more than [`FOCUS_KEYWORDS_PASSES`] passes later doesn't take it, so + /// a request made while the panel can't show expires. + #[serde(skip)] + pub focus_keywords: Option<u64>, /// A mask being renamed in the Masks list: its id and the edited name. #[serde(skip)] pub renaming_mask: Option<(u32, String)>, @@ -856,7 +950,7 @@ pub struct UiState { #[serde(skip)] pub sam_downloading: bool, /// When to start the zoomed-in detail pass of an AI mask (app time) and which mask: set by - /// each click or description, so the pass runs once the clicking stops. + /// each click or description, so the pass runs once the clicking stops (monotonic app time). #[serde(skip)] pub detail_due: Option<(f64, u32)>, /// A mask component being renamed inline: (mask id, component index, name). @@ -967,6 +1061,9 @@ pub struct UiState { pub slideshow: Option<Box<crate::panels::slideshow::Run>>, /// Info overlay on the loupe. pub info_overlay: InfoOverlay, + /// When the loupe last changed photo (View Options' Show Briefly When Photo Changes). + #[serde(skip)] + pub brief_info: BriefInfo, /// The loupe's layout image overlay (View ▸ Loupe Overlay). pub layout_image: LayoutImage, /// Navigator mini map in the loupe while zoomed in. @@ -1174,10 +1271,13 @@ pub enum Dialog { /// Help ▸ What's New. WhatsNew, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best - /// of each burst. + /// of each burst; shots at most `burst_gap` seconds apart and at least `similarity` alike are + /// a burst. Cull { reject_below: f32, pick_best: bool, + burst_gap: f32, + similarity: f32, }, /// Help ▸ System Info: (label, value) rows. DenoiseModel { @@ -1258,6 +1358,29 @@ pub enum Dialog { folder: String, catalog: Option<String>, }, + /// File ▸ Import Lightroom Catalog…: where the catalog at `catalog` goes (issue #2672, see + /// [`crate::lightroom_destination`]). Merge into the open library `library` (`photos` in it), or + /// (`new_library`) create the library `name` in the folder `location`, switch to it and import + /// there. `dont_ask`: merge from now on without asking. `generation`: the library the window + /// was opened for (`Session::library_generation`): another one opened meanwhile isn't merged into. + LightroomDestination { + /// The `.lrcat` file. + catalog: String, + /// The open library's name (its folder's name). + library: String, + /// The photos in the open library. + photos: usize, + /// "Create a new library" is chosen (else "Merge into the open library"). + new_library: bool, + /// The new library's name (prefilled from the catalog's file name). + name: String, + /// The folder the new library goes in (prefilled with the open library's parent folder). + location: String, + /// "Don't ask again (always merge into the open library)". + dont_ask: bool, + /// `Session::library_generation` when the window opened. + generation: u64, + }, /// Save the selected mask's sliders as a mask effect preset: which sliders (`FIELDS` names, /// the colour as `color_sat`), whether it carries Amount and the brush settings. SaveEffect { @@ -1364,6 +1487,7 @@ impl Default for UiState { language: crate::i18n::default_language(), preview_build_seen: None, unsaved_seen: false, + frame_rate: std::env::var("LIGHTCRAFT_FPS").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")), luminance_map_restore: None, view: ViewMode::Detail, left_panel: false, @@ -1410,6 +1534,7 @@ impl Default for UiState { person_page: None, person_from: None, last_person: None, + cull_burst: None, dismissed_faces: Default::default(), unnamed_selected: Default::default(), unnamed_name: String::new(), @@ -1425,6 +1550,7 @@ impl Default for UiState { known_cards: None, search: String::new(), focus_search: false, + focus_keywords: None, renaming_mask: None, describe: None, detail_due: None, @@ -1472,6 +1598,7 @@ impl Default for UiState { keyword_list_selected: None, dragging_keyword: None, info_overlay: InfoOverlay::Off, + brief_info: BriefInfo::default(), layout_image: LayoutImage::default(), navigator: true, settings: AppSettings::default(), @@ -1619,16 +1746,36 @@ mod loupe_info_tests { fn view_options_lines_are_saved_with_the_settings() { let mut settings = AppSettings::default(); settings.loupe_info.info2 = [LoupeInfoField::Lens, LoupeInfoField::None, LoupeInfoField::FileName]; + settings.loupe_info.briefly = InfoOverlay::Exposure; let saved = serde_json::to_value(&settings).unwrap(); assert_eq!(saved["loupeInfo"]["info2"], serde_json::json!(["lens", "none", "fileName"])); + assert_eq!(saved["loupeInfo"]["briefly"], "exposure"); let read: AppSettings = serde_json::from_value(saved).unwrap(); assert_eq!(read.loupe_info, settings.loupe_info); let old: AppSettings = serde_json::from_value(serde_json::json!({"filmNames": false})).unwrap(); assert_eq!(old.loupe_info, LoupeInfo::default()); + // lines saved before Show Briefly When Photo Changes existed are kept, with it off + let lines: AppSettings = serde_json::from_value(serde_json::json!({"loupeInfo": {"info2": ["lens", "none", "fileName"]}})).unwrap(); + assert_eq!(lines.loupe_info.info2, settings.loupe_info.info2); + assert_eq!(lines.loupe_info.briefly, InfoOverlay::Off); let newer: AppSettings = serde_json::from_value(serde_json::json!({"filmNames": false, "loupeInfo": {"info1": ["rating", "fileName", "none"]}})).unwrap(); assert_eq!(newer.loupe_info, LoupeInfo::default()); assert!(!newer.film_names, "the rest of the settings are still read"); } + + /// Show message when loading or rendering photos is on until it is turned off, and is saved + /// with the app's settings. + #[test] + fn the_loading_message_choice_is_saved_with_the_settings() { + assert!(AppSettings::default().loupe_messages); + let old: AppSettings = serde_json::from_value(serde_json::json!({"filmNames": false})).unwrap(); + assert!(old.loupe_messages, "a settings file from before the choice existed keeps the message"); + let settings = AppSettings { loupe_messages: false, ..AppSettings::default() }; + let saved = serde_json::to_value(&settings).unwrap(); + assert_eq!(saved["loupeMessages"], false); + let read: AppSettings = serde_json::from_value(saved).unwrap(); + assert!(!read.loupe_messages); + } } diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rs index 0473a38fa7..3ebf9ce3e1 100644 --- a/crates/ui-egui/src/sync.rs +++ b/crates/ui-egui/src/sync.rs @@ -169,7 +169,7 @@ pub fn body(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) { ui.add_space(6.0); let Some(c) = counts.as_ref() else { ui.horizontal(|ui| { - ui.spinner(); + crate::progress::spinner(ui, 14.0); match progress(app) { Some(ScanStage::Listing(folders, files)) => ui.label(listing_text(folders, files)), Some(ScanStage::Checking(done, total)) if total > 0 => ui.label(format!("{} {done} / {total}", crate::i18n::tr("Scanning…"))), @@ -184,7 +184,7 @@ pub fn body(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) { } let choice = |ui: &mut egui::Ui, on: &mut bool, n: usize, text: String, widget: &str| { let r = ui.add_enabled(n > 0, egui::Checkbox::new(on, text)); - crate::widgets::register(ui.ctx(), widget, r.rect); + crate::widgets::register(ui, widget, r.rect); }; let count = |text: &str, n: usize| format!("{} ({n})", crate::i18n::tr(text)); let dim = |ui: &mut egui::Ui, s: &str| ui.label(egui::RichText::new(s).color(t.text_dim)); diff --git a/crates/ui-egui/src/tests_activity.rs b/crates/ui-egui/src/tests_activity.rs index bce9d2eb1a..4ed2b31783 100644 --- a/crates/ui-egui/src/tests_activity.rs +++ b/crates/ui-egui/src/tests_activity.rs @@ -78,7 +78,7 @@ fn more_than_three_rows_overflow_and_expand() { click(&mut h, "activity:more"); assert_eq!(rows(&h), 5); // expanded, the stack grows to show them all - let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::new("activity-stack"))).expect("the stack is drawn"); + let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::unique("activity-stack"))).expect("the stack is drawn"); for g in &guards { let r = rect(&h, &format!("activity:row:{}", g.id())); assert!(stack.contains_rect(r), "row {} at {r:?} is cut off by the stack at {stack:?}", g.id()); @@ -242,6 +242,14 @@ fn dead_export_worker_leaves_no_row() { /// A folder of `n` stand-in JPEGs and an app whose file probe takes 100 ms each (a slow drive). fn slow_import(tag: &str, n: usize) -> (Headless, std::path::PathBuf) { + gated_import(tag, n, None) +} + +/// Like `slow_import`, and while `gate` is false the probe holds every file after the first batch +/// (`batch_size()` files, which join the catalog together), so a test can act mid-import without +/// racing the 100 ms-per-file clock. The hold gives up after 60 s, so a failed test never leaves +/// the import thread spinning. +fn gated_import(tag: &str, n: usize, gate: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>) -> (Headless, std::path::PathBuf) { let dir = std::env::temp_dir().join(format!("lc-activity-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); @@ -249,8 +257,17 @@ fn slow_import(tag: &str, n: usize) -> (Headless, std::path::PathBuf) { std::fs::write(dir.join(format!("IMG_{i:03}.jpg")), format!("not really a jpeg {i}")).unwrap(); } let mut s = lightcraft_engine::Session::new(); - s.media.file_probe = Some(std::sync::Arc::new(|p: &str| { + s.media.file_probe = Some(std::sync::Arc::new(move |p: &str| { std::thread::sleep(Duration::from_millis(100)); + let index = p.rsplit_once("IMG_").and_then(|(_, n)| n.strip_suffix(".jpg")).and_then(|n| n.parse::<usize>().ok()); + if let (Some(gate), Some(index)) = (&gate, index) + && index >= lightcraft_engine::import::batch_size() + { + let t0 = std::time::Instant::now(); + while !gate.load(std::sync::atomic::Ordering::Acquire) && t0.elapsed() < Duration::from_secs(60) { + std::thread::sleep(Duration::from_millis(1)); + } + } Ok(lightcraft_engine::media::ProbeInfo { width: 60, height: 40, @@ -286,14 +303,17 @@ fn import_cancelled_by_command_reports_cancelled() { /// selects its first photo only if nobody picked something else meanwhile (issue #1446). #[test] fn a_photo_chosen_during_an_import_stays_selected() { - let (mut h, dir) = slow_import("chosen", 20); + let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (mut h, dir) = gated_import("chosen", 20, Some(gate.clone())); crate::import::start_paths(&mut h.app, vec![dir.to_string_lossy().to_string()]).unwrap(); assert!(h.step_until(Duration::from_secs(60), |h| h.app.import.as_ref().is_some_and(|t| t.imported >= 2))); // the newest photo so far, never the import's first let chosen = h.app.session.catalog.photos().map(|p| p.id).max().expect("photos arrived"); let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [chosen.0]}}), T); assert_eq!(r["ok"], true, "{r}"); + // held at the gate until now, so the import cannot have ended however slowly the frames ran assert!(h.app.import.is_some(), "still importing"); + gate.store(true, std::sync::atomic::Ordering::Release); assert!(h.step_until(Duration::from_secs(60), |h| h.app.import.is_none())); assert_eq!(h.app.session.catalog.len(), 20, "all imported"); assert_eq!(h.app.session.selection.active, Some(chosen)); @@ -484,7 +504,7 @@ fn rows_added_later_grow_the_stack() { for _ in 0..5 { h.step(); } - let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::new("activity-stack"))).expect("the stack is drawn"); + let stack = h.view.ctx.memory(|m| m.area_rect(egui::Id::unique("activity-stack"))).expect("the stack is drawn"); for g in [&a, &b, &c] { let r = rect(&h, &format!("activity:row:{}", g.id())); assert!(stack.contains_rect(r), "row {} at {r:?} is cut off by the stack at {stack:?}", g.id()); @@ -495,7 +515,7 @@ fn rows_added_later_grow_the_stack() { fn immediate_library_commands_and_auto_sync_show_completion() { let mut h = demo(); assert!(h.app.run("library.clearPreviews", json!({})).is_ok()); - assert_eq!(h.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("✓ Clear Preview Cache")); + assert_eq!(h.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("✓ Discard Preview Cache")); assert_eq!(h.app.run("develop.autoSync", json!({"on": true})).unwrap()["on"], true); assert_eq!(h.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("Auto Sync: On")); diff --git a/crates/ui-egui/src/tests_album_picker.rs b/crates/ui-egui/src/tests_album_picker.rs index 32cc906fe0..97305cba67 100644 --- a/crates/ui-egui/src/tests_album_picker.rs +++ b/crates/ui-egui/src/tests_album_picker.rs @@ -343,20 +343,12 @@ mod import_review { } } - /// Every shipped locale paints translated destination choices and initializes a translated new name. + /// Every shipped locale paints its own destination choices and names a new album in its language. #[test] fn import_album_picker_localizes_choices_in_every_shipped_language() { use crate::i18n::Locale; let Review { mut h, .. } = review(); for locale in Locale::ALL { - for source in - ["None", "New album", "New album…", "Imported Photos", "Choose an album…", "Search albums", "No albums yet", "No albums match"] - { - assert!(!locale.tr(source).is_empty()); - if *locale != Locale::En { - assert_ne!(locale.tr(source), source, "{locale:?}: {source}"); - } - } let r = h.request("ui.set", json!({"language": locale.code()}), T); assert_eq!(r["ok"], true, "{r}"); assert!(h.settle(SETTLE)); diff --git a/crates/ui-egui/src/tests_canvas_pan.rs b/crates/ui-egui/src/tests_canvas_pan.rs new file mode 100644 index 0000000000..3bb6ec51ed --- /dev/null +++ b/crates/ui-egui/src/tests_canvas_pan.rs @@ -0,0 +1,62 @@ +//! A middle-button drag (the mouse wheel pressed) pans the zoomed photo in Detail whatever tool is +//! active: the healing brush doesn't paint meanwhile, and the hand cursor shows. + +use std::time::Duration; + +use egui::{Event, PointerButton, Pos2, vec2}; +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn spots(h: &Headless) -> usize { + let id = h.app.session.active().expect("active photo"); + h.app.session.develop_of(id).unwrap_or_default().spots.len() +} + +/// Press `button` at `from`, move to `to` over a few frames and release; the cursor seen mid-drag. +fn drag(h: &mut Headless, button: PointerButton, from: Pos2, to: Pos2) -> egui::CursorIcon { + let modifiers = egui::Modifiers::NONE; + h.app.synthetic.push(Event::PointerMoved(from)); + h.app.synthetic.push(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + h.step(); + for i in 1..=6 { + h.app.synthetic.push(Event::PointerMoved(from + (to - from) * (i as f32 / 6.0))); + h.step(); + } + let cursor = h.last_cursor; + h.app.synthetic.push(Event::PointerButton { pos: to, button, pressed: false, modifiers }); + h.step(); + h.step(); + cursor +} + +#[test] +fn a_middle_drag_pans_with_the_healing_brush_and_adds_no_spot() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + for (method, params) in [ + ("ui.set", json!({"view": "detail"})), + ("engine.execute", json!({"command": "panel.remove"})), + ("engine.execute", json!({"command": "view.zoom100"})), + ] { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + } + h.step(); + let at = h.app.image_rect.expect("the photo is shown").center(); + let pan = h.app.ui.pan; + let cursor = drag(&mut h, PointerButton::Middle, at, at + vec2(-150.0, -100.0)); + assert_eq!(cursor, egui::CursorIcon::Grabbing, "the hand shows while panning"); + assert_ne!(h.app.ui.pan, pan, "the middle drag pans"); + assert_eq!(spots(&h), 0, "the healing brush doesn't paint during a middle drag"); + // the left button still paints a spot, and doesn't pan + let pan = h.app.ui.pan; + let at = h.app.image_rect.expect("the photo is shown").center(); + drag(&mut h, PointerButton::Primary, at, at + vec2(40.0, 0.0)); + assert_eq!(spots(&h), 1, "a left drag paints a spot"); + assert_eq!(h.app.ui.pan, pan); +} diff --git a/crates/ui-egui/src/tests_capture_time.rs b/crates/ui-egui/src/tests_capture_time.rs new file mode 100644 index 0000000000..b5903e0535 --- /dev/null +++ b/crates/ui-egui/src/tests_capture_time.rs @@ -0,0 +1,174 @@ +//! Edit Capture Time on a photo whose own capture time doesn't fully read (a Lightroom catalog's +//! `captureTime` is copied verbatim): the preview says so instead of asking for a date the user +//! never typed, and OK leaves the photo as it was and says why. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(60); + +fn set_captured(h: &mut Headless, id: lightcraft_catalog::PhotoId, t: &str) { + h.app.session.catalog.apply(lightcraft_catalog::Op::SetCaptured { id, captured: Some(t.into()) }).unwrap(); +} + +fn painted(h: &Headless, part: &str) -> bool { + h.painted_text().iter().any(|t| t.contains(part)) +} + +fn toast(h: &Headless) -> String { + h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default() +} + +/// Select `ids` with `active` and open Edit Capture Time. +fn open(h: &mut Headless, ids: &[lightcraft_catalog::PhotoId], active: lightcraft_catalog::PhotoId) { + let ids: Vec<u64> = ids.iter().map(|id| id.0).collect(); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": ids, "active": active.0}}), T); + let r = h.request("ui.menu.invoke", json!({"id": "dialog.captureTime"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); +} + +#[test] +fn shift_preview_says_the_photos_capture_time_cant_be_read() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let id = h.app.session.visible_cloned()[0]; + set_captured(&mut h, id, "2026-01-01T10:00:00"); + open(&mut h, &[id], id); + match &mut h.app.ui.dialog { + Some(Dialog::CaptureTime { mode, hours, .. }) => { + *mode = "shift".into(); + *hours = 1; + } + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.settle(SETTLE); + assert!(painted(&h, "2026-01-01 10:00:00 → 2026-01-01 11:00:00"), "a readable time previews its shift: {:?}", h.painted_text()); + + let bad = "2026-01-01T10:00:00 and more"; + set_captured(&mut h, id, bad); + h.settle(SETTLE); + assert!(painted(&h, "can't be read"), "the preview says the photo's time can't be read: {:?}", h.painted_text()); + assert!(!painted(&h, "Enter a date"), "no date was typed, so the preview doesn't ask for one: {:?}", h.painted_text()); + + let r = h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.dialog.is_none(), "OK closes the dialog"); + let toast = toast(&h); + assert!(toast.contains("can't be read"), "OK says the photo was left as it was: {toast:?}"); + assert_eq!(h.app.session.catalog.photo(id).unwrap().captured.as_deref(), Some(bad), "the unreadable time is left as it was"); +} + +#[test] +fn set_mode_refuses_moving_others_by_an_unreadable_time_and_repairs_it_alone() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let ids = h.app.session.visible_cloned(); + let (bad, other) = (ids[0], ids[1]); + let broken = "2026-01-01T10:00:00 and more"; + set_captured(&mut h, bad, broken); + set_captured(&mut h, other, "2026-01-01T12:00:00"); + let open_set = |h: &mut Headless, select: &[lightcraft_catalog::PhotoId]| { + open(h, select, bad); + match &mut h.app.ui.dialog { + Some(Dialog::CaptureTime { mode, time, .. }) => { + *mode = "set".into(); + *time = "2026-01-01 11:00:00".into(); + } + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.settle(SETTLE); + }; + + // with another photo selected, OK can't move it by the unreadable time's change: it says so + // and stays open + open_set(&mut h, &[bad, other]); + let r = h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let toast = toast(&h); + assert!(toast.contains("can't be read"), "OK says why nothing changed: {toast:?}"); + assert!(matches!(h.app.ui.dialog, Some(Dialog::CaptureTime { .. })), "the dialog stays open after the refusal"); + let captured = |h: &Headless, id| h.app.session.catalog.photo(id).unwrap().captured.clone(); + assert_eq!(captured(&h, bad).as_deref(), Some(broken)); + assert_eq!(captured(&h, other).as_deref(), Some("2026-01-01T12:00:00"), "the other photo doesn't move"); + h.request("ui.dialog.cancel", json!({}), T); + + // alone, the preview shows the time it will get, and OK sets it + open_set(&mut h, &[bad]); + let preview = h.painted_text().into_iter().find(|t| t.contains(" → ")).unwrap_or_default(); + assert!(preview.ends_with(" → 2026-01-01 11:00:00"), "the preview shows the time it will get, nothing after: {preview:?}"); + let r = h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.dialog.is_none(), "OK closes the dialog"); + assert_eq!(captured(&h, bad).as_deref(), Some("2026-01-01T11:00:00"), "alone, it gets the time typed"); +} + +/// Errors from the command say why and keep the dialog (and what was typed) open, from its OK +/// button and from the control channel alike; they used to close it without a word. +#[test] +fn errors_are_shown_and_the_dialog_stays_open() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let id = h.app.session.visible_cloned()[0]; + set_captured(&mut h, id, "9999-12-31T12:00:00"); + open(&mut h, &[id], id); + match &mut h.app.ui.dialog { + Some(Dialog::CaptureTime { time, .. }) => *time = "yesterday".into(), + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.settle(SETTLE); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T)["ok"], true); + h.settle(SETTLE); + assert!(toast(&h).contains("not a date"), "OK says the typed time isn't a date: {:?}", toast(&h)); + assert!(matches!(&h.app.ui.dialog, Some(Dialog::CaptureTime { time, .. }) if time == "yesterday"), "the dialog stays open with what was typed"); + + // a shift past year 9999, confirmed through the control channel + match &mut h.app.ui.dialog { + Some(Dialog::CaptureTime { mode, days, .. }) => { + *mode = "shift".into(); + *days = 1; + } + other => panic!("Edit Capture Time is not open: {other:?}"), + } + h.settle(SETTLE); + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_ne!(r["ok"], true, "the shift is refused: {r}"); + assert!(r.to_string().contains("9999"), "{r}"); + assert!(matches!(h.app.ui.dialog, Some(Dialog::CaptureTime { .. })), "ui.dialog.confirm keeps it open too, as the button does"); + assert_eq!(h.app.session.catalog.photo(id).unwrap().captured.as_deref(), Some("9999-12-31T12:00:00")); +} + +/// A capture time that doesn't fully read isn't offered as the time to set: `2026-01-01T10:0` +/// would read as midnight. The field starts empty and the preview asks for a date. +#[test] +fn set_mode_does_not_start_from_an_unreadable_time() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let id = h.app.session.visible_cloned()[0]; + set_captured(&mut h, id, "2026-01-01T10:00:00"); + open(&mut h, &[id], id); + assert!( + matches!(&h.app.ui.dialog, Some(Dialog::CaptureTime { time, .. }) if time == "2026-01-01 10:00:00"), + "a readable time is offered: {:?}", + h.app.ui.dialog + ); + h.request("ui.dialog.cancel", json!({}), T); + + set_captured(&mut h, id, "2026-01-01T10:0"); + open(&mut h, &[id], id); + assert!( + matches!(&h.app.ui.dialog, Some(Dialog::CaptureTime { time, .. }) if time.is_empty()), + "an unreadable time isn't offered: {:?}", + h.app.ui.dialog + ); + assert!(painted(&h, "Enter a date"), "alone, the photo will get the time typed, so the preview asks for one: {:?}", h.painted_text()); +} diff --git a/crates/ui-egui/src/tests_crop_rotate.rs b/crates/ui-egui/src/tests_crop_rotate.rs index 848b1b035d..71368fba21 100644 --- a/crates/ui-egui/src/tests_crop_rotate.rs +++ b/crates/ui-egui/src/tests_crop_rotate.rs @@ -454,3 +454,31 @@ fn a_drag_from_just_inside_a_handle_resizes_not_moves() { assert!(r.x0 > 0.0, "the left edge moved in: {r:?}"); assert!((r.x1 - 1.0).abs() < 1e-6, "the right edge stays: {r:?}"); } + +/// Auto on a photo without a horizon or plumb lines says so, instead of leaving the photo as it is +/// without a word. +#[test] +fn auto_straighten_says_when_it_finds_nothing() { + let dir = std::env::temp_dir().join(format!("lc-ui-auto-straighten-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 64, height: 48, data: vec![[90, 120, 160, 255]; 64 * 48] }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + let path = dir.join("flat.png"); + std::fs::write(&path, bytes).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + for (method, params) in [("ui.set", json!({"view": "detail"})), ("engine.execute", json!({"command": "panel.crop"}))] { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{r}"); + } + h.settle(SETTLE); + let r = h.request("ui.clickWidget", json!({"id": "button:straightenAuto"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0 == "No horizon or vertical lines to level by"), "{:?}", h.app.ui.toast); + assert_eq!(angle(&h), 0.0); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/tests_curve.rs b/crates/ui-egui/src/tests_curve.rs index 4d3b45702e..a658ee9a82 100644 --- a/crates/ui-egui/src/tests_curve.rs +++ b/crates/ui-egui/src/tests_curve.rs @@ -6,6 +6,7 @@ use serde_json::json; use crate::headless::Headless; use crate::{LightcraftApp, Services}; +use lightcraft_pipeline::ParametricCurve; const T: Duration = Duration::from_secs(20); @@ -221,3 +222,370 @@ fn curve_points_from_an_agent_are_stored_in_order() { let c = pts(&develop(&h).curve.green); assert!(c[1].0 < c[2].0, "dragged up to its neighbour, not past it: {c:?}"); } + +/// The settings the parametric graph is drawn from: two neighbouring regions pushed opposite ways, +/// where the raw sum of their bumps folds back on itself before the renderer's running maximum +/// straightens it out. +fn folded_regions() -> lightcraft_develop::ToneCurve { + lightcraft_develop::ToneCurve { shadows: 90.0, darks: -80.0, lights: -70.0, highlights: 60.0, ..Default::default() } +} + +/// The bare sum of the four region bumps is not monotone, so the drawn curve needs the renderer's +/// running maximum: this is the shape that made the graph disagree with the sliders. +#[test] +fn the_parametric_model_is_monotone_where_the_bare_sum_of_bumps_is_not() { + let c = folded_regions(); + let raw = |x: f64| { + let s = [0.0, c.split_shadows / 100.0, c.split_mid / 100.0, c.split_highlights / 100.0, 1.0]; + let amounts = [c.shadows, c.darks, c.lights, c.highlights]; + let mut d = 0.0; + for i in 0..4 { + let (a, b) = (s[i], s[i + 1]); + let (ctr, half) = ((a + b) / 2.0, (b - a) * 0.75 + 0.05); + let t = ((x - ctr) / half).clamp(-1.0, 1.0); + d += amounts[i] / 100.0 * 0.22 * (0.5 + 0.5 * (t * std::f64::consts::PI).cos()); + } + x + d * 4.0 * x * (1.0 - x) + }; + assert!((0..=64).any(|i| raw(i as f64 / 64.0) > raw((i + 1) as f64 / 64.0)), "the shape folds back, or it proves nothing"); + let model = ParametricCurve::new(&c); + let mut prev = f64::MIN; + for i in 0..=256 { + let y = model.at(i as f64 / 256.0); + assert!(y >= prev - 1e-12, "the model never folds back, at {i}: {y} < {prev}"); + prev = y; + } +} + +/// What the graph *paints* is the model the renderer computes from the sliders. They used to be two +/// copies of the formula and the panel's copy was missing the renderer's monotone pass, so the drawn +/// line could fold back while the renderer straightened it: the graph and the sliders below it +/// disagreed. This reads the painted line itself, not the function behind it. +#[test] +fn the_parametric_graph_paints_the_model_the_renderer_uses() { + let mut h = curve_open("parametric"); + let c = folded_regions(); + for (control, value) in [("curve.shadows", c.shadows), ("curve.darks", c.darks), ("curve.lights", c.lights), ("curve.highlights", c.highlights)] { + exec(&mut h, "develop.set", json!({"control": control, "value": value})); + } + h.step(); + h.step(); + let settings = develop(&h).curve; + assert_eq!(settings, c, "the sliders hold the folded shape"); + let graph = curve_graph_rect(&mut h); + let painted = painted_param_curve(&h, graph); + let model = ParametricCurve::new(&c); + let mut checked = 0; + for i in 0..=24 { + let x = i as f64 / 24.0; + let want = model.at(x); + let got = painted(x); + assert!((got - want).abs() < 0.02, "the painted curve is the renderer's at {x}: painted {got}, model {want}"); + checked += 1; + } + assert_eq!(checked, 25); + // and the shape really does fold back before the monotone pass, so this proves something + assert!(model.at(0.6) > model.at(0.3), "the region bumps still bend the curve"); +} + +/// The graph rect as `[left, top, width, height]` plus a reader for the painted curve's height at a +/// graph fraction (0 = the bottom of the graph, 1 = the top). +fn curve_graph_rect(h: &mut Headless) -> [f32; 4] { + let r = h.request("ui.widgets", json!({"filter": "curve"}), T); + let w = r["result"].as_array().unwrap().iter().find(|w| w["id"] == "curve").cloned().unwrap_or_else(|| panic!("curve widget on screen: {r}")); + let v = w["rect"].as_array().unwrap(); + std::array::from_fn(|i| v[i].as_f64().unwrap() as f32) +} + +/// A reader for the height of the painted parametric curve at a graph fraction. The curve is the +/// wide grey path the graph draws; the histogram is a mesh and the grid lines are single segments. +fn painted_param_curve(h: &Headless, r: [f32; 4]) -> impl Fn(f64) -> f64 { + let points = h + .view + .painted_shapes() + .into_iter() + .find_map(|s| match s { + egui::Shape::Path(p) if p.points.len() > 32 && (p.stroke.width - 2.0).abs() < 0.1 => Some(p.points), + _ => None, + }) + .unwrap_or_else(|| panic!("the parametric curve line is painted")); + move |x: f64| { + let want_x = r[0] + x as f32 * r[2]; + let q = points + .iter() + .min_by(|a, b| (a.x - want_x).abs().total_cmp(&(b.x - want_x).abs())) + .copied() + .unwrap_or_else(|| panic!("the curve has points")); + ((r[1] + r[3] - q.y) / r[3]).clamp(0.0, 1.0) as f64 + } +} + +/// The tone the parametric graph paints at `x`, read by value from the painted line. Stepped first +/// so the panel has drawn the state the command left behind. +fn painted_tone(h: &mut Headless, x: f64) -> f64 { + h.step(); + h.step(); + let r = curve_graph_rect(h); + painted_param_curve(h, r)(x) +} + +/// Where the midtones sit on a linear curve: a point well inside the Lights region, so lifting +/// Lights bends the line there. +const MID: f64 = 0.625; + +/// Reset restores the four sliders *and* puts the graph back to the straight diagonal, as one state. +#[test] +fn reset_clears_the_sliders_and_the_graph_together() { + let mut h = curve_open("parametric"); + let straight = painted_tone(&mut h, MID); + assert!((straight - MID).abs() < 0.02, "a fresh parametric curve is the diagonal: {straight}"); + exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 60})); + let bent = painted_tone(&mut h, MID); + assert!(bent > MID + 0.02, "the graph follows the slider up: {bent}"); + let undo_before = h.app.session.undo.len(); + click_widget(&mut h, "button:curveReset", 1); + let c = develop(&h).curve; + assert_eq!(c, lightcraft_develop::ToneCurve::default(), "Reset puts every slider and split back: {c:?}"); + let flat = painted_tone(&mut h, MID); + assert!((flat - MID).abs() < 0.02, "and the graph is the diagonal again: {flat}"); + assert_eq!(h.app.session.undo.len(), undo_before + 1, "Reset is one undo step"); +} + +/// Undo after a Reset brings back both the slider and the graph: the state the graph draws is the +/// state Undo restores, so the two can never be left showing different things. +#[test] +fn undo_restores_the_slider_and_the_graph_together() { + let mut h = curve_open("parametric"); + exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 60})); + let bent = painted_tone(&mut h, MID); + assert!(bent > MID + 0.02, "the graph is bent: {bent}"); + click_widget(&mut h, "button:curveReset", 1); + assert_eq!(develop(&h).curve, lightcraft_develop::ToneCurve::default(), "reset first"); + exec(&mut h, "edit.undo", json!({})); + let c = develop(&h).curve; + assert_eq!(c.lights, 60.0, "Undo brings the slider back: {c:?}"); + let again = painted_tone(&mut h, MID); + assert!(again > MID + 0.02, "and the graph is bent with it, not left flat: {again}"); + // redo puts the diagonal back, and the graph follows that too + exec(&mut h, "edit.redo", json!({})); + assert_eq!(develop(&h).curve, lightcraft_develop::ToneCurve::default(), "redo restores the reset"); + let flat = painted_tone(&mut h, MID); + assert!((flat - MID).abs() < 0.02, "the graph is flat with the sliders: {flat}"); +} + +/// One graph drag that bends several regions at once is one undo step: Ctrl+Z takes back the whole +/// gesture, not the last slider it happened to touch. +#[test] +fn one_graph_drag_that_moves_several_regions_is_one_undo_step() { + let mut h = curve_open("parametric"); + exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 40})); + exec(&mut h, "develop.set", json!({"control": "curve.darks", "value": -40})); + let before = develop(&h).curve; + let undo_before = h.app.session.undo.len(); + // drag the Lights slider's own track, the way a graph handle writes it: begin, live updates, end + exec(&mut h, "develop.beginInteraction", json!({"label": "Parametric Curve"})); + for v in [45, 55, 70, 85] { + exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": v})); + } + exec(&mut h, "develop.endInteraction", json!({})); + let after = develop(&h).curve; + assert_eq!(after.lights, 85.0, "the drag ended at its last value: {after:?}"); + assert_ne!(after, before, "the drag changed the state"); + assert_eq!(h.app.session.undo.len(), undo_before + 1, "the whole drag is one step, not one per frame"); + exec(&mut h, "edit.undo", json!({})); + assert_eq!(develop(&h).curve, before, "undo takes back the whole gesture at once"); +} + +/// The screen point where a drag should grab the curve: graph fraction `fx`, on the line itself. +fn on_curve(r: [f32; 4], c: &lightcraft_develop::ToneCurve, fx: f32) -> [f32; 2] { + let y = ParametricCurve::new(c).at(fx as f64); + [r[0] + fx * r[2], r[1] + (1.0 - y as f32) * r[3]] +} + +/// Dragging the curve itself bends the region under the pointer and moves that region's slider with +/// it, live. The graph draws no handles, so the only thing to grab is the line. +#[test] +fn dragging_the_curve_moves_the_region_slider() { + let mut h = curve_open("parametric"); + exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 60})); + h.step(); + let r = curve_graph_rect(&mut h); + let c = develop(&h).curve; + let undo_before = h.app.session.undo.len(); + // grab the line inside the Lights window (x = 0.625) and pull it down + let [x, y] = on_curve(r, &c, 0.625); + let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y + 0.08 * r[3], "steps": 8}), T); + assert_eq!(d["ok"], true, "{d}"); + h.step(); + let after = develop(&h).curve; + assert!(after.lights < 60.0, "the Lights slider follows the line down: {}", after.lights); + assert!(after.lights > 0.0, "and lands on a value, not at the bottom: {}", after.lights); + assert_eq!((after.shadows, after.darks, after.highlights), (0.0, 0.0, 0.0), "the other regions stay put: {after:?}"); + assert_eq!(after.split_shadows, c.split_shadows, "and the splits are untouched"); + assert_eq!(h.app.session.undo.len(), undo_before + 1, "one undo step for the whole drag"); + // the graph really is redrawn below where the line was + let graph = curve_graph_rect(&mut h); + let painted = painted_param_curve(&h, graph)(0.625); + let before_level = ParametricCurve::new(&c).at(0.625); + assert!(painted < before_level - 0.02, "the painted line followed the drag down: {painted} vs before {before_level}"); + // and Undo takes the whole gesture back to where it started + exec(&mut h, "edit.undo", json!({})); + assert_eq!(develop(&h).curve, c, "undo restores the value the drag started from"); +} + +/// A horizontal drag on the curve (zero vertical motion) changes no region amount, even when +/// neighbouring regions contribute heavily to the curve at the grabbed position (AlexChambers report: +/// Darks=60, Lights=0 grabbed at x=0.51 used to jump Lights to 45 with zero vertical motion). +#[test] +fn a_horizontal_drag_with_zero_vertical_motion_changes_nothing() { + let mut h = curve_open("parametric"); + exec(&mut h, "develop.set", json!({"control": "curve.darks", "value": 60})); + h.step(); + let before = develop(&h).curve; + assert_eq!(before.darks, 60.0); + assert_eq!(before.lights, 0.0); + let r = curve_graph_rect(&mut h); + let [x, y] = on_curve(r, &before, 0.51); + // Drag purely horizontally from x=0.51: dx = 20 px, dy = 0 + let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x + 20.0, "toY": y, "steps": 6}), T); + assert_eq!(d["ok"], true, "{d}"); + h.step(); + let after = develop(&h).curve; + assert_eq!(after.lights, 0.0, "horizontal motion preserves Lights=0: {}", after.lights); + assert_eq!(after.darks, 60.0, "Darks is preserved: {}", after.darks); + assert_eq!(after, before, "horizontal drag changes nothing: {after:?}"); +} + +/// Dragging up bends the region the other way, so the gesture is not just "downwards works". +#[test] +fn dragging_the_curve_up_raises_the_region_slider() { + let mut h = curve_open("parametric"); + let r = curve_graph_rect(&mut h); + let c = develop(&h).curve; + // x = 0.375 is inside the Darks window + let [x, y] = on_curve(r, &c, 0.375); + let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y - 0.08 * r[3], "steps": 8}), T); + assert_eq!(d["ok"], true, "{d}"); + h.step(); + let after = develop(&h).curve; + assert!(after.darks > 0.0, "the Darks slider follows the line up: {}", after.darks); + assert_eq!((after.shadows, after.lights, after.highlights), (0.0, 0.0, 0.0), "the other regions stay put: {after:?}"); + assert!(ParametricCurve::new(&after).at(0.375) > ParametricCurve::new(&c).at(0.375), "the curve is drawn bent up at the Darks region"); +} + +/// Which region a drag moves is decided by where on the line it is grabbed: the same drag gesture +/// four times over grabs four different sliders. +#[test] +fn the_region_dragged_is_the_one_under_the_pointer() { + for (fx, control, region) in + [(0.125_f32, "curve.shadows", 0usize), (0.375, "curve.darks", 1), (0.625, "curve.lights", 2), (0.875, "curve.highlights", 3)] + { + let mut h = curve_open("parametric"); + let r = curve_graph_rect(&mut h); + let c = develop(&h).curve; + assert_eq!(ParametricCurve::new(&c).region_at(fx as f64), region, "x = {fx} belongs to {control}"); + let [x, y] = on_curve(r, &c, fx); + let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y - 0.06 * r[3], "steps": 6}), T); + assert_eq!(d["ok"], true, "{d}"); + h.step(); + let after = develop(&h).curve; + let moved = after.shadows + after.darks + after.lights + after.highlights; + let want = match region { + 0 => after.shadows, + 1 => after.darks, + 2 => after.lights, + _ => after.highlights, + }; + assert!(want > 0.0, "grabbing at {fx} raises {control}: {after:?}"); + assert!((moved - want).abs() < 1e-9, "and nothing else moved: {after:?}"); + } +} + +/// A drag that starts away from the line is not a graph gesture at all: nothing moves and no undo +/// step is made (the graph is not a "click anywhere to bend" surface). +#[test] +fn a_parametric_drag_off_the_line_changes_nothing() { + let mut h = curve_open("parametric"); + exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 40})); + h.step(); + let before = develop(&h).curve; + let undo = h.app.session.undo.len(); + let r = curve_graph_rect(&mut h); + // a corner of the graph, far above the line + let d = h.request( + "ui.drag", + json!({"x": r[0] + 0.06 * r[2], "y": r[1] + 0.06 * r[3], "toX": r[0] + 0.2 * r[2], "toY": r[1] + 0.3 * r[3], "steps": 6}), + T, + ); + assert_eq!(d["ok"], true, "{d}"); + h.step(); + assert_eq!(develop(&h).curve, before, "no control moved"); + assert_eq!(h.app.session.undo.len(), undo, "and no undo step was made"); +} + +/// Hovering the line names the region a press there would move (and offers the grab cursor), so the +/// graph says which slider it is about to change before the drag starts. +#[test] +fn hovering_the_line_names_the_region_it_would_move() { + let mut h = curve_open("parametric"); + exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 60})); + h.step(); + let r = curve_graph_rect(&mut h); + let [x, y] = on_curve(r, &develop(&h).curve, 0.625); + let q = h.request("ui.move", json!({"x": x, "y": y}), T); + assert_eq!(q["ok"], true, "{q}"); + h.step(); + assert_eq!(h.last_cursor, egui::CursorIcon::Grab, "the line offers a grab: {:?}", h.last_cursor); + // the slider rows also paint "Lights", so compare with a frame away from the line + let lights = |h: &Headless| h.painted_text().iter().filter(|t| t.contains("Lights")).count(); + let hovered = lights(&h); + // well above the line there is no grab and no name + let q = h.request("ui.move", json!({"x": x, "y": r[1] + 0.06 * r[3]}), T); + assert_eq!(q["ok"], true, "{q}"); + h.step(); + assert_eq!(h.last_cursor, egui::CursorIcon::Default, "away from the line there is nothing to grab: {:?}", h.last_cursor); + assert!(hovered > lights(&h), "hovering names the slider it would move: {hovered} vs {} away", lights(&h)); +} + +/// A point's level on the region's curve and its slider amount are inverses, so a drag puts the line +/// exactly where the hand is, at whatever point on the graph it was grabbed. A level the region +/// cannot reach saturates rather than jumping. +#[test] +fn a_curve_level_and_its_amount_are_inverses() { + let c = lightcraft_develop::ToneCurve { shadows: 20.0, lights: 40.0, ..Default::default() }; + let model = ParametricCurve::new(&c); + for region in 0..4 { + let centre = model.region_x(region); + let (_, upper) = model.region_window(region); + // the region's window centre, and a point off-centre inside the same window + for x in [centre, centre + (upper - centre) * 0.5] { + for amount in [-100.0, -40.0, 0.0, 30.0, 100.0] { + let level = model.handle_level_at(region, amount, x); + let back = model.amount_at_level(region, level, x); + assert!((back - amount).abs() <= 1.0, "region {region} at {x}: {amount} → {level} → {back}"); + } + } + } + let centre = model.region_x(3); + assert_eq!(model.amount_at_level(3, 1.0, centre), 100.0, "a level above the region's reach saturates high"); + assert_eq!(model.amount_at_level(3, 0.0, centre), -100.0, "and one below saturates low"); +} + +/// The four regions tile the graph: every position belongs to exactly one of them, in order, so a +/// drag anywhere on the line moves exactly one slider and the one the pointer is over. +#[test] +fn the_four_regions_tile_the_graph() { + let model = ParametricCurve::new(&lightcraft_develop::ToneCurve::default()); + assert_eq!(model.region_at(0.0), 0, "black is the darkest region"); + assert_eq!(model.region_at(1.0), 3, "white is the lightest"); + assert_eq!(model.region_at(0.2), 0, "below the first split"); + assert_eq!(model.region_at(0.3), 1, "between the first two splits"); + assert_eq!(model.region_at(0.6), 2); + assert_eq!(model.region_at(0.8), 3); + let mut prev = model.region_at(0.0); + for i in 0..=100 { + let r = model.region_at(i as f64 / 100.0); + assert!(r >= prev, "the regions never go backwards: {r} after {prev}"); + prev = r; + } +} diff --git a/crates/ui-egui/src/tests_dialog_fit.rs b/crates/ui-egui/src/tests_dialog_fit.rs index 52d4128294..e2e9dd4bf2 100644 --- a/crates/ui-egui/src/tests_dialog_fit.rs +++ b/crates/ui-egui/src/tests_dialog_fit.rs @@ -130,7 +130,7 @@ fn long_dialogs_fit_a_short_window() { fn a_dialog_list_shrinks_to_fit_a_short_window() { let mut h = demo([1000.0, 320.0]); open(&mut h, "app.shortcuts"); - let shrink = h.view.ctx.data(|d| d.get_temp::<f32>(egui::Id::new("dialog-list-shrink"))).unwrap_or(0.0); + let shrink = h.view.ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("dialog-list-shrink"))).unwrap_or(0.0); assert!(shrink > 0.0, "the list gave up room"); let dialog = rect(&h, "dialog:window"); assert!(dialog.height() <= 320.0, "{dialog:?}"); diff --git a/crates/ui-egui/src/tests_dialog_settings.rs b/crates/ui-egui/src/tests_dialog_settings.rs new file mode 100644 index 0000000000..c62bc2f594 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_settings.rs @@ -0,0 +1,374 @@ +//! The Settings window is one size in one place whatever tab is open, and lies inside the app +//! window: a row with more choices than fit wraps, a label longer than its column wraps, a long +//! folder path is cut short (its tooltip has all of it), and the tabs stay put while a page scrolls. +//! +//! Before, a wide row widened the whole window: General was 970 points wide and the other tabs +//! about 600, the window moved up and down between tabs, and in a 900 point wide app window the +//! row labels and the Close button of General were cut off at the left. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +/// The app window sizes tried: roomy, the desktop minimum, and smaller than that. +const SIZES: [[f32; 2]; 3] = [[1600.0, 1000.0], [900.0, 560.0], [640.0, 480.0]]; + +fn headless(session: lightcraft_engine::Session, size: [f32; 2]) -> Headless { + let mut h = Headless::new(LightcraftApp::new(session, Services::default()), size, 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn demo(size: [f32; 2]) -> Headless { + headless(lightcraft_engine::Session::with_demo(), size) +} + +/// Given Settings open on `tab`, drawn until its layout has settled. +fn show(h: &mut Headless, tab: &str) { + let r = h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": tab}}), T); + assert_eq!(r["ok"], true, "app.settings {tab}: {r}"); + h.settle(T); + for _ in 0..4 { + h.step(); + } +} + +/// A folder under the system's temporary one, removed again when the test ends, passed or not. +struct TempFolder(std::path::PathBuf); + +impl TempFolder { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("lc-ui-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Self(dir) + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn rect(h: &Headless, id: &str) -> egui::Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +/// The controls the Settings window registers on the tab that is open (and its tab buttons). +fn controls(h: &Headless) -> Vec<(String, egui::Rect)> { + let named = |id: &str| id.split_once(':').is_some_and(|(_, name)| name.starts_with("settings") || name.starts_with("theme")); + h.app.widgets.iter().filter(|(id, _)| named(id)).cloned().collect() +} + +fn same(a: egui::Rect, b: egui::Rect) -> bool { + (a.min - b.min).abs().max_elem() < 0.5 && (a.max - b.max).abs().max_elem() < 0.5 +} + +#[test] +fn the_window_keeps_its_size_and_place_from_tab_to_tab() { + for size in SIZES { + let mut h = demo(size); + // Given the first tab, when every other tab is opened in turn + show(&mut h, "general"); + let first = rect(&h, "dialog:window"); + for (tab, _) in TABS { + show(&mut h, tab); + // Then the window has not moved or changed size + let now = rect(&h, "dialog:window"); + assert!(same(first, now), "{size:?}: Settings is {now:?} on {tab}, and was {first:?} on general"); + } + // And going back to the first tab finds it as it was + show(&mut h, "general"); + assert!(same(first, rect(&h, "dialog:window")), "{size:?}: general again"); + } +} + +#[test] +fn every_tab_keeps_its_controls_inside_the_window() { + for size in SIZES { + let mut h = demo(size); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, h.size); + for (tab, _) in TABS { + // When a tab is opened + show(&mut h, tab); + // Then the Settings window lies inside the app window + let window = rect(&h, "dialog:window"); + assert!(screen.contains_rect(window), "{size:?} {tab}: Settings {window:?} runs off the {screen:?} window"); + // And no control reaches past its left or right edge + // (the page is everything the tab drew, whether or not it has a name of its own; a + // control past the room for it would be clipped there, inside the window's margin) + let (page, room) = (rect(&h, "settings:page"), rect(&h, "settings:pageRoom")); + assert!( + page.left() >= room.left() - 0.5 && page.right() <= room.right() + 0.5, + "{size:?} {tab}: the page {page:?} is wider than the room for it {room:?}" + ); + assert!(window.contains_rect(room), "{size:?} {tab}: the page's room {room:?} is inside Settings {window:?}"); + for (id, r) in controls(&h) { + let within = if id.contains("settingsTab-") { window } else { room }; + assert!(r.left() >= within.left() - 0.5 && r.right() <= within.right() + 0.5, "{size:?} {tab}: {id} {r:?} is outside {within:?}"); + } + } + } +} + +#[test] +fn a_row_of_many_choices_wraps_under_itself() { + // Given an app window too narrow for the languages in one line + let mut h = demo([900.0, 560.0]); + show(&mut h, "general"); + let languages: Vec<egui::Rect> = (0..crate::i18n::Locale::ALL.len()).map(|i| rect(&h, &format!("button:settingsLanguage-{i}"))).collect(); + // Then they take more than one line + let first = languages[0]; + assert!(languages.iter().any(|r| r.top() > first.bottom()), "the languages wrap: {languages:?}"); + // And each further line starts under the first choice, not under the row's label + for r in languages.iter().filter(|r| r.top() > first.bottom()) { + assert!(r.left() >= first.left() - 0.5, "{r:?} starts left of the first language {first:?}"); + } + assert!( + languages.iter().filter(|r| r.top() > first.bottom()).any(|r| (r.left() - first.left()).abs() < 0.5), + "a wrapped line starts at the first choice" + ); +} + +#[test] +fn a_label_longer_than_its_column_leaves_the_controls_in_line() { + // Given Performance, whose "Forget unchanged photos" label is wider than the label column + let mut h = demo([1600.0, 1000.0]); + show(&mut h, "performance"); + // Then its choices start where the choices of a short label do + let (short, long) = (rect(&h, "button:settingsPreview-0"), rect(&h, "button:settingsForgetLocal-0")); + assert!((short.left() - long.left()).abs() < 0.5, "Preview size starts at {} and Forget unchanged photos at {}", short.left(), long.left()); +} + +#[test] +fn a_long_library_folder_is_cut_short_and_its_tooltip_has_all_of_it() { + // Given a library in a folder with a very long path + let base = TempFolder::new("settings-window"); + let dir = + base.0.join("photographs-from-2019-to-2026-kept-on-the-second-external-drive-that-nobody-wants-to-type-twice").join("the-master-library"); + std::fs::create_dir_all(&dir).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&dir, true).unwrap(); + let path = dir.display().to_string(); + + let mut h = headless(session, [1600.0, 1000.0]); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, h.size); + // When Settings opens on General, which shows where the library is + show(&mut h, "general"); + let general = rect(&h, "dialog:window"); + show(&mut h, "display"); + // Then the window is as wide as on a tab without a path + assert!(same(general, rect(&h, "dialog:window")), "General is {general:?} with a long path, Display is {:?}", rect(&h, "dialog:window")); + show(&mut h, "general"); + assert!(screen.contains_rect(general), "Settings {general:?} runs off the {screen:?} window"); + // And the path is cut short, inside the window + let location = rect(&h, "text:settingsLocation"); + let room = rect(&h, "settings:pageRoom"); + assert!(location.right() <= room.right() + 0.5, "the path {location:?} stays inside the room for the page {room:?}"); + let texts = h.painted_text(); + assert!(!texts.iter().any(|text| text.contains(&path)), "the whole path is not drawn in the row"); + // And what is left of it is its end, which says which library this is + let name = "the-master-library"; + assert!(path.ends_with(name)); + assert!( + texts.iter().any(|text| text.starts_with('…') && text.ends_with(name)), + "the row keeps the end of the path: {:?}", + texts.iter().filter(|t| t.contains("library")).collect::<Vec<_>>() + ); + // And resting the pointer on it shows the whole path + assert_eq!(h.request("ui.hoverWidget", json!({"id": "text:settingsLocation"}), T)["ok"], true); + assert!(h.step_until(T, |h| h.painted_text().iter().any(|text| text.contains(&path))), "the tooltip has the whole path"); + + // And the same holds for the folder Auto Import watches, which stays on one line + let watched = h.app.run("library.autoImport", json!({"folder": path})); + assert!(watched.is_ok(), "{watched:?}"); + show(&mut h, "import"); + // (the row is at the foot of the page: scrolled to, so that it is drawn however long the page is) + let window = rect(&h, "dialog:window"); + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..6 { + h.request("ui.scroll", json!({"dy": -400.0}), T); + h.step(); + } + h.settle(T); + let (folder, room) = (rect(&h, "text:settingsAutoFolder"), rect(&h, "settings:pageRoom")); + assert!(room.intersects(folder), "the watched folder {folder:?} is in view in {room:?}"); + assert!(folder.height() < 24.0 && folder.right() <= room.right(), "the watched folder {folder:?} is one line inside {room:?}"); + assert!(h.painted_text().iter().any(|text| text.starts_with('…') && text.ends_with(name)), "and keeps its end"); + // And Choose… stays on that line, inside the room, whatever length the path is cut to: the + // path takes what the button leaves (the folders' names vary, so the cut falls everywhere) + for n in 0..14 { + let path = format!("{path}/{}/{name}", "d".repeat(2 + 3 * n)); + std::fs::create_dir_all(&path).unwrap(); + assert!(h.app.run("library.autoImport", json!({"folder": path})).is_ok()); + h.settle(T); + for _ in 0..4 { + h.step(); + } + let (folder, button) = (rect(&h, "text:settingsAutoFolder"), rect(&h, "button:settingsAutoFolder")); + assert!(button.right() <= room.right() + 0.5, "Choose… {button:?} is inside {room:?} (path of {n})"); + assert!((button.center().y - folder.center().y).abs() < 6.0, "Choose… {button:?} is on the line of the path {folder:?} (path of {n})"); + assert!(folder.right() <= button.left(), "the path {folder:?} ends before Choose… {button:?} (path of {n})"); + } + drop(h); +} + +#[test] +fn library_default_stays_on_the_line_of_the_smart_previews_folder_whatever_its_length() { + // Given libraries whose folder names grow in steps (the smart previews folder is `Smart Previews` in + // each, so its path is cut at a different place every time, and some cut leaves less room than the note needs) + let base = TempFolder::new("settings-smart"); + for n in 0..24 { + let dir = base.0.join(format!("photographs-kept-on-the-second-external-drive-{n}")).join("m".repeat(2 + 3 * n)); + std::fs::create_dir_all(&dir).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&dir, true).unwrap(); + let mut h = headless(session, [1600.0, 1000.0]); + // When Performance is scrolled to the foot of its page + show(&mut h, "performance"); + let window = rect(&h, "dialog:window"); + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..6 { + h.request("ui.scroll", json!({"dy": -400.0}), T); + h.step(); + } + h.settle(T); + // Then "(library default)" stays inside the room, on the line of the path, after it + let room = rect(&h, "settings:pageRoom"); + let (smart, note) = (rect(&h, "text:settingsSmartFolder"), rect(&h, "text:settingsSmartDefault")); + assert!(room.intersects(smart) && room.intersects(note), "the smart previews folder {smart:?} {note:?} is in view in {room:?} (name of {n})"); + assert!(note.right() <= room.right() + 0.5, "(library default) {note:?} is inside {room:?} (name of {n})"); + assert!((note.center().y - smart.center().y).abs() < 6.0, "(library default) {note:?} is on the line of the path {smart:?} (name of {n})"); + assert!(smart.right() <= note.left(), "the path {smart:?} ends before (library default) {note:?} (name of {n})"); + drop(h); + } +} + +#[test] +fn a_short_path_is_shown_whole_and_has_no_tooltip() { + // Given the in-memory library, whose Location is a short sentence + let mut h = demo([1600.0, 1000.0]); + show(&mut h, "general"); + assert!(h.painted_text().iter().any(|text| text == "In memory — nothing is saved"), "it is all there"); + let before = h.painted_text().len(); + // When the pointer rests on it + assert_eq!(h.request("ui.hoverWidget", json!({"id": "text:settingsLocation"}), T)["ok"], true); + let _ = h.step_until(Duration::from_secs(2), |h| h.painted_text().len() > before); + // Then nothing more is drawn: there is nothing a tooltip could add + assert_eq!(h.painted_text().len(), before, "no tooltip for a path that is all there"); +} + +/// How many pixels of `rect` are not `colour` (one pixel per point here). +fn other_than(image: &egui::ColorImage, rect: egui::Rect, colour: egui::Color32) -> usize { + let [w, h] = image.size; + let (x0, x1) = (rect.left().round().max(0.0) as usize, (rect.right().round().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().round().max(0.0) as usize, (rect.bottom().round().max(0.0) as usize).min(h)); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|(x, y)| image.pixels[y * w + x] != colour).count() +} + +#[test] +fn a_page_that_goes_on_below_shows_a_scroll_handle_without_the_pointer_on_it() { + let mut h = demo([900.0, 560.0]); + let chrome = crate::theme::Tokens::get(&h.view.ctx).chrome; + // (the pointer is nowhere near the window) + h.request("ui.move", json!({"x": 5.0, "y": 5.0}), T); + let handle = |h: &Headless| { + let room = rect(h, "settings:pageRoom"); + other_than(&h.paint(), egui::Rect::from_min_max(egui::pos2(room.right() - 6.0, room.top()), room.max), chrome) + }; + // Given Import, which is taller than the room a 560 pt tall app window has for it + show(&mut h, "import"); + assert!(rect(&h, "settings:page").height() > rect(&h, "settings:pageRoom").height()); + // Then a handle is drawn at the page's right edge + assert!(handle(&h) > 40, "Import shows a scroll handle ({} px)", handle(&h)); + // And Display, which fits, has none + show(&mut h, "display"); + assert!(rect(&h, "settings:page").height() <= rect(&h, "settings:pageRoom").height()); + assert_eq!(handle(&h), 0, "Display has nothing to scroll"); +} + +#[test] +fn a_window_too_short_for_a_page_of_its_own_scrolls_tabs_and_page_together() { + // Given an app window far below the desktop minimum + let mut h = demo([900.0, 220.0]); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, h.size); + show(&mut h, "import"); + let window = rect(&h, "dialog:window"); + assert!(screen.contains_rect(window), "Settings {window:?} is inside the {screen:?} window"); + let (tab, page) = (rect(&h, "button:settingsTab-import"), rect(&h, "check:settings.perCamera")); + // When it is scrolled + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..3 { + h.request("ui.scroll", json!({"dy": -120.0}), T); + h.step(); + } + h.settle(T); + // Then the tabs and the page move as one, so every setting can still be reached + let (tab_now, page_now) = (rect(&h, "button:settingsTab-import"), rect(&h, "check:settings.perCamera")); + assert!(page_now.top() < page.top() - 50.0, "the page scrolled: {page:?} -> {page_now:?}"); + assert!(((tab.top() - tab_now.top()) - (page.top() - page_now.top())).abs() < 0.5, "tabs and page moved together"); + assert!(same(window, rect(&h, "dialog:window")), "the window did not move"); +} + +#[test] +fn the_tabs_stay_put_while_a_page_scrolls() { + // Given a page taller than the window has room for + let mut h = demo([900.0, 560.0]); + show(&mut h, "import"); + let window = rect(&h, "dialog:window"); + let tabs: Vec<egui::Rect> = TABS.iter().map(|(id, _)| rect(&h, &format!("button:settingsTab-{id}"))).collect(); + let page_before = rect(&h, "check:settings.perCamera"); + // When the page is scrolled + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..3 { + h.request("ui.scroll", json!({"dy": -120.0}), T); + h.step(); + } + h.settle(T); + // Then the page moved + let page_after = rect(&h, "check:settings.perCamera"); + assert!(page_after.top() < page_before.top() - 50.0, "the page scrolled: {page_before:?} -> {page_after:?}"); + // And the tabs and the window did not + for ((id, _), before) in TABS.iter().zip(tabs) { + assert!(same(before, rect(&h, &format!("button:settingsTab-{id}"))), "tab {id} moved"); + } + assert!(same(window, rect(&h, "dialog:window")), "the window moved"); +} + +#[test] +fn each_tab_remembers_how_far_it_was_scrolled() { + let mut h = demo([900.0, 560.0]); + show(&mut h, "interface"); + let fresh = rect(&h, "button:settingsAppearance-0"); + // Given Import scrolled down + show(&mut h, "import"); + let window = rect(&h, "dialog:window"); + let top = rect(&h, "check:settings.perCamera").top(); + h.request("ui.move", json!({"x": window.center().x, "y": window.center().y}), T); + for _ in 0..3 { + h.request("ui.scroll", json!({"dy": -120.0}), T); + h.step(); + } + h.settle(T); + let scrolled = rect(&h, "check:settings.perCamera").top(); + assert!(scrolled < top - 50.0); + // When another tab is opened, it starts at its top + show(&mut h, "interface"); + let mode = rect(&h, "button:settingsAppearance-0"); + assert!(same(fresh, mode), "Interface is at its top, as when first opened: {fresh:?} -> {mode:?}"); + // And Import is where it was left + show(&mut h, "import"); + assert!((rect(&h, "check:settings.perCamera").top() - scrolled).abs() < 0.5, "Import is where it was left"); + // And it is still there when Settings is closed and opened again (documented in What's New) + assert_eq!(h.request("ui.dialog.cancel", json!({}), T)["ok"], true); + h.settle(T); + show(&mut h, "import"); + assert!((rect(&h, "check:settings.perCamera").top() - scrolled).abs() < 0.5, "Import is where it was left after a reopen"); +} diff --git a/crates/ui-egui/src/tests_dialog_tab.rs b/crates/ui-egui/src/tests_dialog_tab.rs new file mode 100644 index 0000000000..5ffb995801 --- /dev/null +++ b/crates/ui-egui/src/tests_dialog_tab.rs @@ -0,0 +1,153 @@ +//! A dialog's name field takes the keyboard focus once, when the dialog opens: Tab then carries it +//! on to the dialog's other controls (a check box, Cancel, OK) and Shift+Tab back, instead of the +//! field taking it back every frame. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo_with_selection() -> Headless { + let mut session = lightcraft_engine::Session::with_demo(); + session.selection.ids = session.catalog.photos().take(2).map(|p| p.id).collect(); + let mut h = Headless::new(LightcraftApp::new(session, Services::default()), [1400.0, 900.0], 1.0); + h.settle(T); + h +} + +/// The registered widget (`field:…`, `check:…`, `button:…`) that has the keyboard focus. +fn focused(h: &Headless) -> Option<String> { + let id = h.view.ctx.memory(|m| m.focused())?; + let rect = h.view.ctx.read_response(id)?.rect; + h.app.widgets.iter().find(|(_, r)| *r == rect).map(|(w, _)| w.clone()) +} + +fn key(h: &mut Headless, params: serde_json::Value) { + let r = h.request("ui.key", params, T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); +} + +/// Open `dialog`, then Tab through it; the focus order, starting with the field it opens on. +fn tab_order(dialog: Dialog) -> Vec<String> { + let mut h = demo_with_selection(); + h.app.ui.dialog = Some(dialog); + for _ in 0..4 { + h.step(); + } + let mut order = vec![focused(&h).unwrap_or_default()]; + for _ in 0..4 { + key(&mut h, json!({"key": "Tab"})); + order.push(focused(&h).unwrap_or_default()); + } + order +} + +#[test] +fn new_album_opens_on_its_name_and_tab_reaches_the_check_box_cancel_and_ok() { + let order = tab_order(Dialog::NewAlbum { name: "Trip".into(), folder: false, parent: None, include_selected: true }); + assert_eq!(order[..4], ["field:albumName", "check:albumIncludeSelected", "button:dialogCancel", "button:dialogOk"], "{order:?}"); +} + +#[test] +fn new_smart_album_opens_on_its_name_and_tab_reaches_cancel_and_ok() { + let order = tab_order(Dialog::NewSmartAlbum { name: "Rejected".into(), parent: None }); + let (cancel, ok) = (order.iter().position(|w| w == "button:dialogCancel"), order.iter().position(|w| w == "button:dialogOk")); + assert_eq!(order[0], "field:smartAlbumName", "{order:?}"); + assert!(cancel.is_some() && ok.is_some() && cancel < ok, "Cancel then OK are reached by Tab: {order:?}"); +} + +#[test] +fn save_metadata_preset_opens_on_its_name_and_tab_reaches_cancel_and_ok() { + let prompt = Dialog::TextPrompt { + title: "Save Metadata Preset".into(), + hint: "Preset name".into(), + value: String::new(), + command: "metadata.savePreset".into(), + params: json!({}), + key: "name".into(), + }; + let order = tab_order(prompt); + assert_eq!(order[..3], ["field:prompt", "button:dialogCancel", "button:dialogOk"], "{order:?}"); +} + +#[test] +fn shift_tab_goes_back_from_ok_to_the_name() { + let mut h = demo_with_selection(); + h.app.ui.dialog = Some(Dialog::NewAlbum { name: "Trip".into(), folder: false, parent: None, include_selected: true }); + for _ in 0..4 { + h.step(); + } + for _ in 0..3 { + key(&mut h, json!({"key": "Tab"})); + } + assert_eq!(focused(&h).as_deref(), Some("button:dialogOk")); + for _ in 0..3 { + key(&mut h, json!({"key": "Tab", "shift": true})); + } + assert_eq!(focused(&h).as_deref(), Some("field:albumName")); +} + +#[test] +fn the_name_still_takes_typing_and_enter_after_opening() { + let mut h = demo_with_selection(); + h.app.ui.dialog = Some(Dialog::NewAlbum { name: String::new(), folder: false, parent: None, include_selected: false }); + for _ in 0..4 { + h.step(); + } + let r = h.request("ui.text", json!({"text": "Holiday"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + key(&mut h, json!({"key": "Enter"})); + h.settle(T); + assert!(h.app.ui.dialog.is_none(), "Enter confirmed the dialog"); + assert!(h.app.session.catalog.albums().any(|a| a.name == "Holiday"), "the typed name made the album"); +} + +#[test] +fn escape_still_cancels_after_tabbing_away_from_the_name() { + let mut h = demo_with_selection(); + h.app.ui.dialog = Some(Dialog::NewAlbum { name: "Trip".into(), folder: false, parent: None, include_selected: true }); + for _ in 0..4 { + h.step(); + } + key(&mut h, json!({"key": "Tab"})); + key(&mut h, json!({"key": "Escape"})); + assert!(h.app.ui.dialog.is_none(), "Esc closed the dialog"); +} + +#[test] +fn a_click_on_a_check_box_leaves_return_confirming_the_name() { + let mut h = demo_with_selection(); + h.app.ui.dialog = Some(Dialog::NewAlbum { name: "Trip".into(), folder: false, parent: None, include_selected: true }); + for _ in 0..4 { + h.step(); + } + let r = h.request("ui.clickWidget", json!({"id": "check:albumIncludeSelected"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + key(&mut h, json!({"key": "Enter"})); + h.settle(T); + assert!(h.app.ui.dialog.is_none(), "Enter confirmed the dialog after the click"); + assert!(h.app.session.catalog.albums().any(|a| a.name == "Trip")); +} + +#[test] +fn a_refused_return_leaves_the_name_focused_for_the_correction() { + let mut h = demo_with_selection(); + h.app.ui.dialog = Some(Dialog::NewAlbum { name: String::new(), folder: false, parent: None, include_selected: false }); + for _ in 0..4 { + h.step(); + } + key(&mut h, json!({"key": "Enter"})); + h.step(); + assert!(h.app.ui.dialog.is_some(), "an empty name is refused and the dialog stays"); + assert_eq!(focused(&h).as_deref(), Some("field:albumName"), "the field has the focus again"); +} diff --git a/crates/ui-egui/src/tests_dialogs.rs b/crates/ui-egui/src/tests_dialogs.rs index 6581640ec6..2e96b59e79 100644 --- a/crates/ui-egui/src/tests_dialogs.rs +++ b/crates/ui-egui/src/tests_dialogs.rs @@ -85,6 +85,71 @@ fn modal_dialogs_block_background_shortcuts_and_keep_escape() { assert_eq!(h.app.session.catalog.photo(active).unwrap().rating, 5, "closing restores shortcuts"); } +/// Settings → Close a dialog by clicking outside it: a click on the backdrop closes the dialog +/// like Esc, without reaching the panels below; a click inside it, or a drag that ends outside, keeps it. +#[test] +fn a_click_outside_closes_the_dialog_when_settings_allow_it() { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + let active = h.app.session.active().unwrap(); + let rating = h.app.session.catalog.photo(active).unwrap().rating; + h.app.run("dialog.copySettings", json!({})).unwrap(); + h.step(); + // off by default: the background click is blocked and the dialog stays + let r = h.request("ui.clickWidget", json!({"id": "star:bottom:5"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_some(), "a stray click keeps the dialog unless Settings say otherwise"); + h.app.ui.settings.close_dialogs_outside = true; + let r = h.request("ui.clickWidget", json!({"id": "copyGroup:none"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_some(), "a click inside the dialog keeps it"); + let window = h.app.widgets.iter().find(|(id, _)| id == "dialog:window").map(|(_, r)| *r).unwrap(); + let r = h.request("ui.drag", json!({"x": window.center().x, "y": window.center().y, "toX": 10.0, "toY": 10.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_some(), "a drag that ends outside the dialog keeps it"); + let r = h.request("ui.clickWidget", json!({"id": "star:bottom:5"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_none(), "a click on the backdrop closes the dialog"); + assert_eq!(h.app.session.catalog.photo(active).unwrap().rating, rating, "the click doesn't reach the panel below"); + // the click that opens a dialog lands outside its window; a quick one on a slow frame arrives + // pressed and released in that one frame + let gear = h.app.widgets.iter().find(|(id, _)| id == "icon:copyGear").map(|(_, r)| r.center()).unwrap(); + let press = |pressed| egui::Event::PointerButton { pos: gear, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(gear), press(true), press(false)]); + h.step(); + h.step(); + assert!(h.app.ui.dialog.is_some(), "the click that opens a dialog doesn't close it"); + let r = h.request("ui.clickWidget", json!({"id": "star:bottom:5"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_none(), "the next click on the backdrop does"); +} + +/// With a dropdown open in the dialog, a click on the backdrop only closes the dropdown, even when +/// it arrives pressed and released in one frame (the dropdown closes while the dialog is drawn). +#[test] +fn a_click_outside_an_open_dropdown_keeps_the_dialog() { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + h.app.ui.settings.close_dialogs_outside = true; + h.app.run("dialog.export", json!({})).unwrap(); + h.step(); + h.step(); + let r = h.request("ui.clickWidget", json!({"id": "combo:exportPreset"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(egui::Popup::is_any_open(&h.view.ctx), "the preset dropdown is open"); + let at = egui::pos2(10.0, 990.0); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(at), press(true), press(false)]); + h.step(); + h.step(); + assert!(!egui::Popup::is_any_open(&h.view.ctx), "the click closes the dropdown"); + assert!(h.app.ui.dialog.is_some(), "but not the dialog"); +} + #[test] fn modal_dialogs_close_background_menus() { let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); diff --git a/crates/ui-egui/src/tests_docking_acceptance.rs b/crates/ui-egui/src/tests_docking_acceptance.rs index 1dc97892e7..75397d1ccc 100644 --- a/crates/ui-egui/src/tests_docking_acceptance.rs +++ b/crates/ui-egui/src/tests_docking_acceptance.rs @@ -164,7 +164,7 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() { h.app.run("panel.crop", json!({})).unwrap(); h.step(); // The test chooses the renderer's actual registered tab, rather than an arbitrary focus owner. - let id = egui::Id::new("lightcraft-docking").with(("tab", Panel::Tools)); + let id = egui::Id::unique("lightcraft-docking").with(("tab", Panel::Tools)); h.view.ctx.memory_mut(|memory| memory.request_focus(id)); h.step(); key(&mut h, egui::Key::Enter); @@ -186,7 +186,7 @@ fn content_text_edit_retains_command_keys_and_typed_text() { h.app.synthetic.push(Event::Text("dock search".into())); h.step(); assert_eq!(h.app.ui.right, RightPanel::Keywords); - assert_eq!(h.view.ctx.data(|data| data.get_temp::<String>(egui::Id::new("keyword-list-filter"))).as_deref(), Some("dock search")); + assert_eq!(h.view.ctx.data(|data| data.get_temp::<String>(egui::Id::unique("keyword-list-filter"))).as_deref(), Some("dock search")); } #[test] @@ -271,7 +271,7 @@ fn covered_keyword_rejects_hierarchy_move_and_uncovered_target_moves_exact_keywo #[test] fn reset_during_held_divider_drag_keeps_replacement_layout_on_later_movement() { let mut h = app(); - let divider = egui::Id::new("lightcraft-docking").with(("split", Vec::<bool>::new())); + let divider = egui::Id::unique("lightcraft-docking").with(("split", Vec::<bool>::new())); let from = h.view.ctx.read_response(divider).expect("the custom workspace root divider is rendered").rect.center(); let before = h.app.ui.docking.as_ref().unwrap().layout.clone(); h.app.synthetic.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); @@ -303,7 +303,7 @@ fn reset_during_held_divider_drag_keeps_replacement_layout_on_later_movement() { fn held_divider_replacement_route(route: &str) { let mut h = app(); - let divider = egui::Id::new("lightcraft-docking").with(("split", Vec::<bool>::new())); + let divider = egui::Id::unique("lightcraft-docking").with(("split", Vec::<bool>::new())); let from = h.view.ctx.read_response(divider).unwrap().rect.center(); let photos = serde_json::to_value(h.app.session.catalog.photos().map(|photo| photo.as_ref()).collect::<Vec<_>>()).unwrap(); h.app.synthetic.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); diff --git a/crates/ui-egui/src/tests_drop_import.rs b/crates/ui-egui/src/tests_drop_import.rs new file mode 100644 index 0000000000..8b6bf3dfdc --- /dev/null +++ b/crates/ui-egui/src/tests_drop_import.rs @@ -0,0 +1,356 @@ +//! Files dragged from the file manager onto the window: while they hover, the window says what +//! dropping will do; dropping photos or folders opens the import review (unless Settings ▸ Import +//! says to import dropped files directly); a drop while a dialog is open is refused. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-ui-drop-import-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + fn path(&self, rel: &str) -> String { + self.0.join(rel).to_string_lossy().to_string() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn write_png(path: &str, seed: u8) { + let (w, h) = (24usize, 16usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::create_dir_all(std::path::Path::new(path).parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +/// An empty library, a folder `trip` with two photos, a window big enough for the overlay. +fn app(dir: &Scratch) -> Headless { + write_png(&dir.path("trip/a.png"), 1); + write_png(&dir.path("trip/b.png"), 2); + let session = lightcraft_engine::Session::new().with_fs(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1300.0, 900.0], 1.0); + for _ in 0..4 { + h.step(); + } + h +} + +fn drop_files(h: &mut Headless, paths: &[String], hover: bool) { + let r = h.request("ui.dropFiles", json!({"paths": paths, "hover": hover}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..3 { + h.step(); + } +} + +fn overlay(h: &Headless) -> bool { + h.app.widgets.iter().any(|(w, _)| w == "dropOverlay") +} + +fn said(h: &Headless, word: &str) -> bool { + h.painted_text().iter().any(|t| t.contains(word)) +} + +fn photos(h: &Headless) -> usize { + h.app.session.catalog.photos().count() +} + +#[test] +fn hovering_photos_says_they_will_be_reviewed_and_lets_go_when_they_leave() { + let dir = Scratch::new("hover"); + let mut h = app(&dir); + assert!(!overlay(&h), "nothing is dragged over the window"); + drop_files(&mut h, &[dir.path("trip/a.png"), dir.path("trip/b.png")], true); + assert!(overlay(&h), "the window shows where to drop"); + assert!(said(&h, "review 2 items"), "{:?}", h.painted_text()); + drop_files(&mut h, &[], true); + assert!(!overlay(&h), "the files left the window"); +} + +#[test] +fn hovering_presets_says_they_will_be_imported_as_presets() { + let dir = Scratch::new("hover-presets"); + let mut h = app(&dir); + std::fs::write(dir.path("warm.lcpreset"), "{}").unwrap(); + drop_files(&mut h, &[dir.path("warm.lcpreset")], true); + assert!(overlay(&h)); + assert!(said(&h, "1 preset"), "{:?}", h.painted_text()); + assert!(!said(&h, "review"), "presets are not reviewed"); +} + +#[test] +fn hovering_unknown_files_says_only_that_dropping_imports() { + let dir = Scratch::new("hover-unknown"); + let mut h = app(&dir); + drop_files(&mut h, &[String::new()], true); + assert!(overlay(&h)); + assert!(said(&h, "Drop to import"), "{:?}", h.painted_text()); +} + +#[test] +fn dropping_a_folder_opens_the_import_review_and_imports_nothing_yet() { + let dir = Scratch::new("review"); + let mut h = app(&dir); + drop_files(&mut h, &[dir.path("trip")], false); + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens"); + let Some(Dialog::Import { opts }) = &h.app.ui.dialog else { panic!("no import review") }; + assert_eq!(opts.candidates.len(), 2); + assert_eq!(photos(&h), 0, "nothing is imported until the review is confirmed"); + assert!(!overlay(&h), "the files were let go"); +} + +#[test] +fn dropping_imports_directly_when_settings_say_so() { + let dir = Scratch::new("direct"); + let mut h = app(&dir); + h.app.ui.settings.import_dropped_directly = true; + drop_files(&mut h, &[dir.path("trip")], false); + assert!(h.step_until(SETTLE, |h| photos(h) == 2 && h.app.import.is_none()), "both photos arrive"); + assert!(h.app.ui.dialog.is_none(), "no review"); +} + +#[test] +fn a_drop_while_a_dialog_is_open_leaves_the_dialog_and_imports_nothing() { + let dir = Scratch::new("dialog"); + let mut h = app(&dir); + h.app.ui.dialog = Some(Dialog::WhatsNew); + drop_files(&mut h, &[dir.path("trip/a.png")], true); + assert!(overlay(&h), "the window still answers the hover"); + assert!(said(&h, "Close the open dialog"), "{:?}", h.painted_text()); + drop_files(&mut h, &[dir.path("trip")], false); + for _ in 0..30 { + h.step(); + } + assert!(matches!(h.app.ui.dialog, Some(Dialog::WhatsNew)), "the open dialog stays"); + assert!(h.app.scan.is_none() && h.app.import.is_none(), "no scan or import started"); + assert_eq!(photos(&h), 0); + assert!(h.app.ui.toast.is_some(), "the person is told why"); +} + +/// A prompt owns the library and the top layer: a drop while it is up stays queued (it is not +/// imported behind the prompt), and the drop-hover card is not painted above it. +#[test] +fn a_drop_and_its_hover_card_wait_behind_a_notice_prompt() { + let dir = Scratch::new("prompt"); + let mut h = app(&dir); + h.app.notices.push("The settings file could not be read and was reset.".into()); + h.step(); + h.step(); + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:noticeOk"), "the notice is laid out"); + drop_files(&mut h, &[dir.path("trip")], true); + assert!(!overlay(&h), "the drop-hover Tooltip layer must not cover the prompt"); + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:noticeOk"), "the prompt still owns the window"); + drop_files(&mut h, &[dir.path("trip")], false); + assert_eq!(photos(&h), 0, "nothing was imported behind the prompt"); + assert!(h.app.ui.dialog.is_none() && h.app.import.is_none() && h.app.scan.is_none(), "the drop was not handled yet"); + assert_eq!(h.app.dropped_files.len(), 1, "the dropped folder is queued until the prompt is gone"); + assert_eq!(h.app.notices.len(), 1, "the notice is still up"); + let r = h.request("ui.clickWidget", json!({"id": "button:noticeOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.app.notices.is_empty(), "OK dismisses the notice"); + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the queued drop opens its review after the prompt"); + assert_eq!(photos(&h), 0, "the review still imports nothing before it is confirmed"); +} + +/// The scan of a dropped folder finishing while another dialog is open (the face model's licence, Settings…) +/// keeps that dialog; the review opens, with the scan's photos, once it is closed. +#[test] +fn a_finished_scan_waits_for_the_open_dialog_before_opening_the_review() { + let dir = Scratch::new("waits"); + let mut h = app(&dir); + crate::import::open(&mut h.app, vec![dir.path("trip")]).unwrap(); + h.app.ui.dialog = Some(Dialog::WhatsNew); + assert!(h.step_until(SETTLE, |h| h.app.scan.is_none()), "the scan ends"); + for _ in 0..10 { + h.step(); + } + assert!(matches!(h.app.ui.dialog, Some(Dialog::WhatsNew)), "the dialog the person had open stays"); + h.app.ui.dialog = None; + assert!(h.step_until(T, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens once the dialog is closed"); + let Some(Dialog::Import { opts }) = &h.app.ui.dialog else { panic!("no import review") }; + assert_eq!(opts.candidates.len(), 2, "the scan's photos were kept"); +} + +/// A scan that finishes behind Settings, which then opens another library: the review of the first +/// library's scan doesn't open over the second one once Settings closes, and nothing is imported into it. +#[test] +fn a_waiting_review_is_dropped_when_another_library_opens() { + let dir = Scratch::new("switch"); + let mut h = app(&dir); + crate::import::open(&mut h.app, vec![dir.path("trip")]).unwrap(); + h.app.ui.dialog = Some(Dialog::Settings { tab: "general".into() }); + assert!(h.step_until(SETTLE, |h| h.app.scan.is_none()), "the scan ends"); + h.step(); + let stale = h.app.review_pending.clone().expect("the review waits behind Settings"); + h.app.run("app.openLibrary", json!({"path": dir.path("other")})).unwrap(); + h.app.ui.dialog = None; + for _ in 0..10 { + h.step(); + } + assert!(h.app.ui.dialog.is_none(), "no review from the other library opens"); + assert!(h.app.review_pending.is_none()); + // a review confirmed after the switch (an agent holding it) imports nothing either + assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &stale).is_err()); + for _ in 0..10 { + h.step(); + } + assert!(h.app.import.is_none(), "nothing is imported"); + assert_eq!(photos(&h), 0); +} + +/// A review waiting behind another dialog counts as an import in progress: a direct drop meanwhile is +/// refused, and the review's OK never replaces an import that runs when it is confirmed. +#[test] +fn a_waiting_review_never_replaces_a_running_import() { + let dir = Scratch::new("pending-running"); + let mut h = app(&dir); + h.app.ui.settings.import_dropped_directly = true; + write_png(&dir.path("more/c.png"), 3); + crate::import::open(&mut h.app, vec![dir.path("trip")]).unwrap(); + h.app.ui.dialog = Some(Dialog::WhatsNew); + assert!(h.step_until(SETTLE, |h| h.app.scan.is_none()), "the scan ends"); + h.step(); + assert!(h.app.review_pending.is_some(), "the review waits behind the dialog"); + assert!(crate::import::start_paths(&mut h.app, vec![dir.path("more")]).is_err(), "no second import starts"); + assert!(h.app.import.is_none()); + h.app.ui.dialog = None; + h.step(); + let Some(review) = h.app.ui.dialog.clone() else { panic!("the review opens once the dialog is closed") }; + assert!(matches!(review, Dialog::Import { .. })); + // an import that started anyway (a Local folder browse, say) is the one that runs + h.app.import = Some(crate::import::ImportTask::new(vec![dir.path("more")], json!({"mode": "add"}), 0, false)); + assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &review).is_err(), "the review's OK is refused"); + assert_eq!(h.app.import.as_ref().map(|t| t.total), Some(1), "the running import stays"); + assert!(h.step_until(SETTLE, |h| h.app.import.is_none()), "it runs to the end"); + assert_eq!(photos(&h), 1, "only the running import's photo arrives"); +} + +/// A drop while an import runs would open a review whose OK replaces the running import: it is +/// refused instead, and the card says so. +#[test] +fn a_drop_while_an_import_runs_is_refused() { + let dir = Scratch::new("running"); + let mut h = app(&dir); + write_png(&dir.path("more/c.png"), 3); + let _scan = crate::import::stall_scan(&mut h.app); + drop_files(&mut h, &[dir.path("more/c.png")], true); + assert!(said(&h, "An import is running"), "{:?}", h.painted_text()); + assert!(!said(&h, "review"), "{:?}", h.painted_text()); + drop_files(&mut h, &[dir.path("more")], false); + for _ in 0..30 { + h.step(); + } + assert!(h.app.ui.dialog.is_none(), "no review opened"); + assert!(h.app.scan.is_some() && h.app.import.is_none(), "the running scan was left alone and nothing else started"); + assert!(h.app.ui.toast.is_some(), "the person is told why"); + assert_eq!(photos(&h), 0); +} + +/// An import that is running stays the one that runs: a direct drop doesn't start a second. +#[test] +fn a_direct_drop_while_an_import_runs_is_refused_too() { + let dir = Scratch::new("running-direct"); + let mut h = app(&dir); + h.app.ui.settings.import_dropped_directly = true; + write_png(&dir.path("more/c.png"), 3); + let _scan = crate::import::stall_scan(&mut h.app); + drop_files(&mut h, &[dir.path("more")], false); + assert!(h.app.import.is_none(), "no second import"); + assert!(h.app.ui.toast.is_some()); +} + +/// A Local folder browse scan counts too: a review-first drop would be rejected by `open`, and a +/// direct drop would be replaced when the browse completes. +#[test] +fn a_drop_while_a_browse_scan_runs_is_refused_in_both_modes() { + for direct in [false, true] { + let dir = Scratch::new("running-browse"); + let mut h = app(&dir); + h.app.ui.settings.import_dropped_directly = direct; + write_png(&dir.path("more/c.png"), 3); + let _scan = crate::import::stall_scan_of(&mut h.app, true); + drop_files(&mut h, &[dir.path("more/c.png")], true); + assert!(said(&h, "An import is running"), "{:?}", h.painted_text()); + drop_files(&mut h, &[dir.path("more")], false); + for _ in 0..30 { + h.step(); + } + assert!(h.app.ui.dialog.is_none() && h.app.import.is_none(), "direct={direct}: nothing started"); + assert!(h.app.scan.is_some(), "the browse was left alone"); + assert!(h.app.ui.toast.is_some(), "the person is told why"); + } +} + +/// While a Lightroom catalog import is pending the drop is refused, and the card says so instead of +/// promising a review. +#[test] +fn hovering_photos_while_a_lightroom_import_is_pending_says_they_will_be_refused() { + let dir = Scratch::new("lightroom"); + let mut h = app(&dir); + let _task = crate::lightroom_import::stall_import(&mut h.app); + drop_files(&mut h, &[dir.path("trip")], true); + assert!(said(&h, "Finish Lightroom catalog import"), "{:?}", h.painted_text()); + assert!(!said(&h, "review"), "{:?}", h.painted_text()); + drop_files(&mut h, &[dir.path("trip")], false); + assert!(h.app.ui.dialog.is_none(), "no review opened"); + assert!(h.app.ui.toast.is_some(), "the person is told why"); + assert_eq!(photos(&h), 0); +} + +/// A script is not told `ok` for the part of a `paths` list that was strings. +#[test] +fn drop_files_with_a_non_string_path_is_rejected_and_drops_nothing() { + let dir = Scratch::new("badpaths"); + let mut h = app(&dir); + let r = h.request("ui.dropFiles", json!({"paths": [dir.path("trip"), 7]}), T); + assert_eq!(r["ok"], false, "{r}"); + for _ in 0..30 { + h.step(); + } + assert!(h.app.ui.dialog.is_none(), "nothing was dropped"); + assert_eq!(photos(&h), 0); +} + +/// No library open yet (the window of a library that failed to open, or the launch list): the +/// card says the photos wait, and a drop keeps them for the library chosen instead of importing +/// them into the session that library replaces. +#[test] +fn photos_dropped_with_no_library_open_wait_for_one() { + let dir = Scratch::new("no-library"); + let mut h = app(&dir); + h.app.library_problem = Some(crate::panels::library_problem::LibraryProblem::new(dir.path("Gone"), "not found")); + std::fs::write(dir.path("warm.lcpreset"), "{}").unwrap(); + drop_files(&mut h, &[dir.path("trip/a.png"), dir.path("warm.lcpreset")], true); + assert!(said(&h, "once a library is open"), "{:?}", h.painted_text()); + assert!(said(&h, "drop the presets again") && !said(&h, "1 preset"), "{:?}", h.painted_text()); + drop_files(&mut h, &[], true); + drop_files(&mut h, &[dir.path("trip/a.png"), dir.path("trip/b.png")], false); + assert_eq!(h.app.library_problem.as_ref().map(|p| p.pending_import.len()), Some(2)); + assert!(h.app.ui.dialog.is_none() && h.app.import.is_none(), "no review, no import into the temporary session"); + assert_eq!(photos(&h), 0); + // a preset belongs to a library: refused, not imported into the session the library replaces + h.app.ui.toast = None; + drop_files(&mut h, &[dir.path("warm.lcpreset")], false); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("drop the presets again"), "{toast}"); +} diff --git a/crates/ui-egui/src/tests_focus_point.rs b/crates/ui-egui/src/tests_focus_point.rs index f93dd4f7b4..efd7f5716c 100644 --- a/crates/ui-egui/src/tests_focus_point.rs +++ b/crates/ui-egui/src/tests_focus_point.rs @@ -1,4 +1,4 @@ -//! Headless tests of the camera's focus point (#1480): View ▸ Show Focus Point draws the box where the +//! Headless tests of the camera's focus point (#1480): View ▸ Focus Point draws the box where the //! camera focused, through the user's rotation and crop; Toggle Zoom (Z) centres on it; the Info panel //! names the focus mode. diff --git a/crates/ui-egui/src/tests_folder_drop.rs b/crates/ui-egui/src/tests_folder_drop.rs index 1b6536242c..b7a5151317 100644 --- a/crates/ui-egui/src/tests_folder_drop.rs +++ b/crates/ui-egui/src/tests_folder_drop.rs @@ -95,7 +95,7 @@ fn release(h: &mut Headless, at: Pos2) { /// What the dragged label says this frame instead of the count, if a drop target set it. fn hint(h: &Headless) -> Option<String> { - h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::new("drag-photos-hint"))).map(|(_, text)| text) + h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))).map(|(_, text)| text) } /// Click a widget the way a person does (press and release on it). diff --git a/crates/ui-egui/src/tests_grading.rs b/crates/ui-egui/src/tests_grading.rs index f6903550c6..cd1f190cf5 100644 --- a/crates/ui-egui/src/tests_grading.rs +++ b/crates/ui-egui/src/tests_grading.rs @@ -375,3 +375,125 @@ fn wheel_rim_is_fully_saturated_and_the_centre_neutral() { let (hi, lo) = (p.r().max(p.g()).max(p.b()), p.r().min(p.g()).min(p.b())); assert!(hi - lo <= 40 && lo >= 100, "centre is not a neutral grey: {p:?}"); } + +// ------------------------------------------------------------------ the held pointer (issue #1899) + +fn pointer_event(h: &mut Headless, e: egui::Event) { + h.events.push(e); + h.step(); +} + +fn button(h: &mut Headless, at: egui::Pos2, pressed: bool) { + let e = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + pointer_event(h, e); +} + +/// Press the midtones wheel at `at` and move the pointer 10 to the right, far enough to make it +/// a drag; where the pointer is then. +fn start_wheel_drag(h: &mut Headless, at: egui::Pos2) -> egui::Pos2 { + pointer_event(h, egui::Event::PointerMoved(at)); + button(h, at, true); + let to = at + egui::vec2(10.0, 0.0); + pointer_event(h, egui::Event::PointerMoved(to)); + h.step(); + to +} + +fn cursor_moves(h: &Headless) -> Vec<egui::Pos2> { + h.window_commands + .iter() + .filter_map(|c| match c { + egui::ViewportCommand::CursorPosition(p) => Some(*p), + _ => None, + }) + .collect() +} + +#[test] +fn a_held_wheel_follows_the_mouses_motion_not_where_the_pointer_sits() { + use crate::panels::edit::wheel_pick; + let mut h = demo(); + let rad = wheel_radius(&h, "midtones"); + set_wheel(&mut h, "midtones", 0.0, 0.0); + let c = widget(&h, "wheel:midtones").unwrap().center(); + let held = start_wheel_drag(&mut h, c + egui::vec2(rad * 0.4, 0.0)); + // the pointer stays where it is (macOS locks it there) while the mouse goes on moving up + for _ in 0..5 { + pointer_event(&mut h, egui::Event::MouseMoved(egui::vec2(0.0, -rad * 0.1))); + } + let (hue, sat) = wheel_value(&h, "midtones"); + let (want_hue, want_sat) = wheel_pick(held + egui::vec2(0.0, -rad * 0.5) - c, rad, None); + assert!((hue - want_hue.round() as f64).abs() <= 1.0 && (sat - want_sat.round() as f64).abs() <= 1.0, "{hue} {sat} vs {want_hue} {want_sat}"); + assert!(hue > 30.0, "the puck went up with the mouse: {hue}"); + button(&mut h, held, false); +} + +#[test] +fn a_wheel_drag_hides_the_pointer_and_releasing_puts_it_back_where_it_was_pressed() { + let mut h = demo(); + let rad = wheel_radius(&h, "midtones"); + set_wheel(&mut h, "midtones", 0.0, 0.0); + let press = widget(&h, "wheel:midtones").unwrap().center() + egui::vec2(rad * 0.3, rad * 0.2); + let at = start_wheel_drag(&mut h, press); + let far = at + egui::vec2(-rad * 0.6, -rad * 0.9); + pointer_event(&mut h, egui::Event::PointerMoved(far)); + assert_eq!(h.last_cursor, egui::CursorIcon::None, "hidden while the wheel is dragged"); + assert!(cursor_moves(&h).is_empty(), "nothing moves the pointer before the release"); + button(&mut h, far, false); + h.step(); + assert_eq!(cursor_moves(&h), [press], "back where the button went down"); + assert_ne!(h.last_cursor, egui::CursorIcon::None, "shown again"); + #[cfg(target_os = "macos")] + assert_eq!( + h.window_commands.iter().filter(|c| matches!(c, egui::ViewportCommand::CursorGrab(_))).collect::<Vec<_>>(), + [&egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked), &egui::ViewportCommand::CursorGrab(egui::CursorGrab::None)], + "locked for the drag, unlocked at the end" + ); + // a click is not a drag: the pointer stays visible where it is + h.window_commands.clear(); + let r = h.request("ui.clickWidget", json!({"id": "wheel:midtones"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.window_commands.is_empty(), "{:?}", h.window_commands); +} + +#[test] +fn escape_or_losing_focus_gives_the_pointer_back_mid_drag() { + let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for let_go in [esc, egui::Event::WindowFocused(false)] { + let mut h = demo(); + let rad = wheel_radius(&h, "midtones"); + set_wheel(&mut h, "midtones", 0.0, 0.0); + let press = widget(&h, "wheel:midtones").unwrap().center() + egui::vec2(rad * 0.3, 0.0); + let at = start_wheel_drag(&mut h, press); + assert_eq!(h.last_cursor, egui::CursorIcon::None, "{let_go:?}: hidden while dragged"); + pointer_event(&mut h, let_go.clone()); + h.step(); + assert_ne!(h.last_cursor, egui::CursorIcon::None, "{let_go:?}: shown again"); + assert_eq!(cursor_moves(&h), [press], "{let_go:?}: back where it was pressed"); + // the rest of the drag no longer moves the puck, and the pointer stays visible + let before = wheel_value(&h, "midtones"); + pointer_event(&mut h, egui::Event::PointerMoved(at + egui::vec2(-rad * 0.5, -rad * 0.5))); + assert_eq!(wheel_value(&h, "midtones"), before, "{let_go:?}"); + assert_ne!(h.last_cursor, egui::CursorIcon::None, "{let_go:?}"); + button(&mut h, at, false); + h.step(); + assert_eq!(cursor_moves(&h), [press], "{let_go:?}: given back once"); + } +} + +#[test] +fn a_wheel_that_goes_away_mid_drag_gives_the_pointer_back() { + let mut h = demo(); + let rad = wheel_radius(&h, "midtones"); + let press = widget(&h, "wheel:midtones").unwrap().center() + egui::vec2(rad * 0.3, 0.0); + start_wheel_drag(&mut h, press); + assert_eq!(h.last_cursor, egui::CursorIcon::None); + // the flyout closes under the drag: no wheel is drawn to let go of the pointer itself + h.app.ui.toggle_flyout("grading"); + h.step(); + h.step(); + assert!(widget(&h, "wheel:midtones").is_none()); + assert_ne!(h.last_cursor, egui::CursorIcon::None); + assert_eq!(cursor_moves(&h), [press]); +} diff --git a/crates/ui-egui/src/tests_histogram_drag.rs b/crates/ui-egui/src/tests_histogram_drag.rs new file mode 100644 index 0000000000..e6fd7138d8 --- /dev/null +++ b/crates/ui-egui/src/tests_histogram_drag.rs @@ -0,0 +1,295 @@ +//! The histogram's tonal zones, as in Lightroom Classic: dragging one sideways moves its Basic +//! control (one undo step for the whole drag), the zone locks at the press, a double-click resets +//! that control, and hovering highlights the zone and names it in the readout under the plot. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// The zones' controls, left to right (`panels::histogram::ZONES`). +const CONTROLS: [&str; 5] = ["light.blacks", "light.shadows", "light.exposure", "light.highlights", "light.whites"]; + +/// The demo library in Detail with the Edit panel (the histogram sits first) on a selected photo. +fn edit_panel() -> Headless { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + let id = h.app.session.visible_cloned()[0].0; + let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [id]}}), T); + assert_eq!(r["ok"], true, "{r}"); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +fn widget(h: &Headless, id: &str) -> Option<egui::Rect> { + h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +fn rect(h: &Headless, id: &str) -> egui::Rect { + widget(h, id).unwrap_or_else(|| panic!("no widget {id} on screen")) +} + +fn value(h: &Headless, control: &str) -> f64 { + let id = h.app.session.active().unwrap_or_else(|| panic!("no active photo")); + let spec = lightcraft_develop::controls::find(control).unwrap_or_else(|| panic!("no control {control}")); + lightcraft_develop::controls::get(&h.app.session.develop_of(id).unwrap_or_default(), control).unwrap_or(spec.default) +} + +/// Every zone's control, left to right. +fn values(h: &Headless) -> Vec<f64> { + CONTROLS.iter().map(|c| value(h, c)).collect() +} + +/// Set a control through the engine, as a slider would. +fn set(h: &mut Headless, control: &str, v: f64) { + h.app.run("develop.set", json!({"control": control, "value": v})).unwrap_or_else(|e| panic!("develop.set {control}: {e}")); +} + +/// Let the harness clock pass `seconds`, running frames. egui closes its double-click window when +/// the next click comes more than 0.3 s later *and* more than 6 points away; its triple-click +/// window is twice that, and two clicks in another zone right after two in one are close enough to +/// the second click to count as a triple click of it — which no longer reports `double_clicked`. +fn after(h: &mut Headless, seconds: f64) { + let until = h.time() + seconds; + while h.time() < until { + h.step(); + } +} + +/// Drag from a fraction `fx` across the histogram: `fy` 0.5 is inside the plot, `dx` in points. +fn drag(h: &mut Headless, fx: f32, dx: f32, shift: bool) { + let p = json!({"id": "histogram", "fx": fx, "fy": 0.5, "dx": dx, "steps": 8, "shift": shift}); + let r = h.request("ui.dragWidget", p.clone(), T); + assert_eq!(r["ok"], true, "{p}: {r}"); + h.settle(SETTLE); +} + +/// A double-click on the histogram at `fx` (the plot's own rows, `fy` 0.5). +fn double_click(h: &mut Headless, fx: f32) { + let r = h.request("ui.clickWidget", json!({"id": "histogram", "fx": fx, "fy": 0.5, "count": 2}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); +} + +/// Hover the histogram at `fx` and let the frame settle. +fn hover(h: &mut Headless, fx: f32) { + let r = h.request("ui.hoverWidget", json!({"id": "histogram", "fx": fx, "fy": 0.5}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); +} + +/// Dragging one zone moves that control: a sideways travel of the plot's width sweeps its whole +/// range, and the whole drag is one undo step. +#[test] +fn dragging_the_exposure_zone_moves_the_exposure_in_one_undo_step() { + let mut h = edit_panel(); + let w = rect(&h, "histogram").width(); + let undo = h.app.session.undo.len(); + drag(&mut h, 0.5, w * 0.05, false); + // a twentieth of the plot: a twentieth of ±5 EV + let exposure = value(&h, "light.exposure"); + assert!((exposure - 0.5).abs() <= 0.02, "a twentieth of the plot is a twentieth of the range: {exposure}"); + assert_eq!(h.app.session.undo.len() - undo, 1, "one undo step for the whole drag"); + assert!(h.app.session.interaction.is_none(), "the interaction is closed on the release"); + assert!(h.app.ui.dragging_control.is_none(), "no control is left dragged"); + let mut others = values(&h); + others.remove(2); + assert_eq!(others, [0.0, 0.0, 0.0, 0.0], "the zones the drag crossed are untouched"); + // one undo brings the exposure back + let r = h.request("engine.execute", json!({"command": "edit.undo"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(value(&h, "light.exposure"), 0.0); +} + +/// The zone a press landed in stays locked for the whole drag: dragging from Exposure across the +/// Shadows and Blacks zones still only moves the Exposure. +#[test] +fn the_zone_locks_at_the_press_however_far_the_drag_travels() { + let mut h = edit_panel(); + let w = rect(&h, "histogram").width(); + let undo = h.app.session.undo.len(); + drag(&mut h, 0.5, -w * 0.4, false); + let exposure = value(&h, "light.exposure"); + assert!((exposure + 4.0).abs() <= 0.02, "four tenths of the plot to the left is −4 EV: {exposure}"); + assert_eq!((value(&h, "light.shadows"), value(&h, "light.blacks")), (0.0, 0.0), "the zones crossed stay untouched"); + assert_eq!(h.app.session.undo.len() - undo, 1, "still one undo step"); +} + +/// Dragging left lowers the zone's control and dragging right raises it; a drag past either end +/// clamps at that control's range (the zones' own specs, ±100 for the four, ±5 EV for Exposure). +#[test] +fn a_drag_lowers_and_clamps_at_the_controls_range() { + let mut h = edit_panel(); + let w = rect(&h, "histogram").width(); + drag(&mut h, 0.5, -w * 0.2, false); + assert!((value(&h, "light.exposure") + 2.0).abs() <= 0.02, "{}", value(&h, "light.exposure")); + // the Blacks zone, dragged right across the whole plot and beyond: clamped at +100 + drag(&mut h, 0.08, w * 0.9, false); + assert_eq!(value(&h, "light.blacks"), 100.0); + drag(&mut h, 0.92, -w * 2.0, false); + assert_eq!(value(&h, "light.whites"), -100.0); +} + +/// Shift is a tenth of the travel, as on the sliders. +#[test] +fn shift_drags_a_tenth_as_far() { + let mut h = edit_panel(); + let w = rect(&h, "histogram").width(); + drag(&mut h, 0.5, w * 0.1, false); + let plain = value(&h, "light.exposure"); + assert!((plain - 1.0).abs() <= 0.02, "{plain}"); + set(&mut h, "light.exposure", 0.0); + drag(&mut h, 0.5, w * 0.1, true); + let fine = value(&h, "light.exposure"); + assert!((fine - 0.1).abs() <= 0.02, "a tenth of {plain}: {fine}"); +} + +/// A double-click in a zone puts that zone's control back to its default in one undo step, leaving +/// the other zones' controls alone. +#[test] +fn double_clicking_a_zone_resets_that_control_in_one_undo_step() { + let mut h = edit_panel(); + set(&mut h, "light.exposure", 1.25); + set(&mut h, "light.shadows", 40.0); + let undo = h.app.session.undo.len(); + double_click(&mut h, 0.5); + assert_eq!(value(&h, "light.exposure"), 0.0, "the Exposure zone is reset"); + assert_eq!(value(&h, "light.shadows"), 40.0, "only the zone that was clicked"); + assert_eq!(h.app.session.undo.len() - undo, 1, "one undo step"); + // the Shadows zone (0.15–0.35) resets its own control, once the double-click window has passed + after(&mut h, 0.7); + double_click(&mut h, 0.25); + assert_eq!(value(&h, "light.shadows"), 0.0); + // a click on the histogram toggles the clipping warnings (as before this feature): the two + // clicks of a double-click toggle them twice, so the state is where it started + assert!(!h.app.ui.show_clipping); +} + +/// The strip under the plot — the readout and the EXIF line — is not a zone: a drag there leaves +/// every control alone. +#[test] +fn a_drag_below_the_plot_leaves_the_tones_alone() { + let mut h = edit_panel(); + let w = rect(&h, "histogram").width(); + let undo = h.app.session.undo.len(); + let p = json!({"id": "histogram", "fx": 0.5, "fy": 0.97, "dx": w * 0.2, "steps": 6}); + let r = h.request("ui.dragWidget", p.clone(), T); + assert_eq!(r["ok"], true, "{p}: {r}"); + h.settle(SETTLE); + assert_eq!(values(&h), [0.0; 5], "no zone was dragged"); + assert_eq!(h.app.session.undo.len(), undo, "and nothing was recorded"); + assert!(h.app.session.interaction.is_none(), "no interaction was opened"); +} + +/// A drag that starts on a clipping chevron (shadows or highlights) changes no develop tone: the +/// chevrons are clipping controls, not tonal zones, even though they sit inside the plot. +#[test] +fn a_drag_starting_on_a_clipping_chevron_changes_no_develop_value() { + let mut h = edit_panel(); + let undo = h.app.session.undo.len(); + // Drag starting on the shadow clipping indicator (which sits over the Blacks zone) + let p = json!({"id": "histogram:shadows", "dx": 40.0, "steps": 8}); + let r = h.request("ui.dragWidget", p.clone(), T); + assert_eq!(r["ok"], true, "{p}: {r}"); + h.settle(SETTLE); + assert_eq!(values(&h), [0.0; 5], "dragging from the shadow chevron moves no tone"); + assert_eq!(h.app.session.undo.len(), undo, "and leaves undo alone"); + assert!(h.app.session.interaction.is_none(), "no interaction was opened"); + + // Drag starting on the highlight clipping indicator (which sits over the Whites zone) + let p = json!({"id": "histogram:highlights", "dx": -40.0, "steps": 8}); + let r = h.request("ui.dragWidget", p.clone(), T); + assert_eq!(r["ok"], true, "{p}: {r}"); + h.settle(SETTLE); + assert_eq!(values(&h), [0.0; 5], "dragging from the highlight chevron moves no tone"); + assert_eq!(h.app.session.undo.len(), undo, "undo remains untouched"); + assert!(h.app.session.interaction.is_none(), "no interaction was opened"); +} + +/// Hovering a zone highlights it (the band covers that zone's share of the plot) and names it with +/// its value in the readout; off the histogram both are gone. +#[test] +fn hovering_a_zone_highlights_it_and_shows_its_name_and_value() { + let mut h = edit_panel(); + let hist = rect(&h, "histogram"); + set(&mut h, "light.shadows", 25.0); + hover(&mut h, 0.25); + let band = rect(&h, "histogram:zone"); + let share = |x: f32| hist.left() + hist.width() * x; + assert!(band.left() >= share(0.14) && band.right() <= share(0.36), "the Shadows band: {band:?} in {hist:?}"); + assert!(h.painted_text().iter().any(|t| t == "Shadows: +25"), "{:?}", h.painted_text()); + // the Exposure zone, with its EV unit + hover(&mut h, 0.5); + let band = rect(&h, "histogram:zone"); + assert!(band.left() >= share(0.34) && band.right() <= share(0.66), "the Exposure band: {band:?}"); + assert!(h.painted_text().iter().any(|t| t == "Exposure: 0.00 EV"), "{:?}", h.painted_text()); + // the pointer off the histogram: no band, no zone readout (the EXIF line is back) + let r = h.request("ui.move", json!({"x": 600.0, "y": 500.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert!(widget(&h, "histogram:zone").is_none(), "the highlight is gone"); + assert!(!h.painted_text().iter().any(|t| t.starts_with("Shadows: ")), "{:?}", h.painted_text()); +} + +/// The pointer over the histogram says the zones can be dragged sideways; elsewhere the canvas' +/// own cursor is back. +#[test] +fn the_cursor_over_the_histogram_offers_a_sideways_drag() { + let mut h = edit_panel(); + hover(&mut h, 0.5); + assert_eq!(h.last_cursor, egui::CursorIcon::ResizeHorizontal); + let r = h.request("ui.move", json!({"x": 600.0, "y": 500.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_ne!(h.last_cursor, egui::CursorIcon::ResizeHorizontal); +} + +/// A drag dispatches as it goes, with the interaction held open, so the draft render follows it +/// live; nothing is committed until the release, which lands the whole drag as one undo step. +#[test] +fn a_drag_dispatches_live_and_commits_on_the_release() { + let mut h = edit_panel(); + let before = h.app.session.undo.len(); + let hist = rect(&h, "histogram"); + let from = egui::pos2(hist.left() + hist.width() * 0.5, hist.top() + hist.height() * 0.5); + let to = from + egui::vec2(hist.width() * 0.1, 0.0); + // a press and its moves with no release: the drag is still going when the frames below run + h.app.synthetic.push(egui::Event::PointerMoved(from)); + h.app.synthetic.push(egui::Event::PointerButton { + pos: from, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + for i in 1..=6 { + h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 6.0))); + } + for _ in 0..12 { + h.step(); + } + let exposure = value(&h, "light.exposure"); + assert!(exposure > 0.4, "the exposure followed the drag while it was still going: {exposure}"); + assert!(h.app.session.interaction.is_some(), "the drag holds the interaction open"); + assert_eq!(h.app.ui.dragging_control.as_deref(), Some("light.exposure"), "the drag names the control it moves, as the sliders do"); + assert_eq!(h.app.session.undo.len(), before, "nothing is committed mid-drag"); + // the release: one undo step for the whole drag, and the interaction is closed + h.app.synthetic.push(egui::Event::PointerButton { + pos: to, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.settle(SETTLE); + assert!(h.app.session.interaction.is_none(), "the release commits the interaction"); + assert!(h.app.ui.dragging_control.is_none(), "and no control is left dragged"); + assert_eq!(h.app.session.undo.len() - before, 1, "the whole drag is one undo step"); +} diff --git a/crates/ui-egui/src/tests_keymap.rs b/crates/ui-egui/src/tests_keymap.rs index 92997d941d..6e784de1a4 100644 --- a/crates/ui-egui/src/tests_keymap.rs +++ b/crates/ui-egui/src/tests_keymap.rs @@ -103,6 +103,27 @@ fn a_key_given_to_a_command_overrides_a_fixed_key() { assert_eq!(before, after, "the rating key must not fire too"); } +/// A declared key that yields to another command's saved key can be taken back with ↺. +#[test] +fn restore_takes_back_a_declared_key_another_command_holds() { + use crate::shortcuts::shortcut_of; + let mut h = demo(); + h.app.ui.settings.keymap.insert("photo.increaseRating".into(), "P".into()); + assert_eq!(shortcut_of(&h.app.ui.settings.keymap, "photo.pick"), None); + h.app.run("app.shortcuts", json!({})).unwrap(); + h.step(); + h.step(); + click(&mut h, "check:shortcuts.showAll"); + click(&mut h, "field:shortcutsSearch"); + assert_eq!(h.request("ui.text", json!({"text": "flag as pick"}), T)["ok"], true); + h.step(); + h.step(); + click(&mut h, "button:shortcutReset-photo.pick"); + assert_eq!(shortcut_of(&h.app.ui.settings.keymap, "photo.pick"), Some("P")); + assert_eq!(shortcut_of(&h.app.ui.settings.keymap, "photo.increaseRating"), None); + assert!(h.app.ui.settings.keymap.is_empty(), "{:?}", h.app.ui.settings.keymap); +} + /// Open the editor, filtered to `search`, and start recording for `id`. fn record(h: &mut Headless, search: &str, id: &str) { if h.app.ui.dialog.is_none() { @@ -176,6 +197,51 @@ fn shift_insert_pastes_plainly() { assert_eq!(h.app.ui.dialog, None, "no Paste Selected Settings"); assert_eq!(h.app.session.undo.len(), undo + 1, "the settings were pasted"); } + +/// ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V) copy and paste metadata, as in Lightroom Classic's Library, +/// both as key presses and as the clipboard events Windows and Linux turn them into; the edit +/// settings clipboard is left alone. +#[test] +fn cmd_alt_shift_c_and_v_copy_and_paste_metadata() { + let mut h = demo(); + let ids: Vec<_> = h.app.session.visible().iter().copied().take(2).collect(); + let (a, b) = (ids[0], ids[1]); + let title = |h: &Headless, id| h.app.session.catalog.photo(id).unwrap().meta.title.clone(); + h.app.run("library.select", json!({"ids": [a.0]})).unwrap(); + h.app.run("photo.setMeta", json!({"title": "Dawn", "creator": "Me"})).unwrap(); + h.app.run("library.select", json!({"ids": [b.0]})).unwrap(); + h.app.run("photo.setMeta", json!({"title": "Other"})).unwrap(); + let chord = json!({"cmd": true, "alt": true, "shift": true}); + let press = |h: &mut Headless, k: &str| { + let mut p = chord.clone(); + p["key"] = json!(k); + let r = h.request("ui.key", p, T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + }; + + h.app.run("library.select", json!({"ids": [a.0]})).unwrap(); + press(&mut h, "C"); + assert_eq!(h.app.session.meta_clipboard.as_ref().map(|m| m["title"].clone()), Some(json!("Dawn")), "the key copied the metadata"); + h.app.run("library.select", json!({"ids": [b.0]})).unwrap(); + press(&mut h, "V"); + assert_eq!(title(&h, b), "Dawn", "the key pasted the metadata"); + assert_eq!(h.app.session.catalog.photo(b).unwrap().meta.creator, "Me"); + + h.app.session.meta_clipboard = None; + h.app.run("photo.setMeta", json!({"title": "Other"})).unwrap(); + let all = egui::Modifiers::COMMAND | egui::Modifiers::ALT | egui::Modifiers::SHIFT; + h.app.run("library.select", json!({"ids": [a.0]})).unwrap(); + h.events.extend([egui::Event::ModifiersChanged(all), egui::Event::Copy]); + h.settle(SETTLE); + assert!(h.app.session.meta_clipboard.is_some(), "the Copy event with ⌥⇧ held copied the metadata"); + h.app.run("library.select", json!({"ids": [b.0]})).unwrap(); + h.events.extend([egui::Event::ModifiersChanged(all), egui::Event::Paste("text".into())]); + h.settle(SETTLE); + assert_eq!(title(&h, b), "Dawn", "the Paste event with ⌥⇧ held pasted the metadata"); + assert!(h.app.session.clipboard.is_none(), "no edit settings were copied"); + assert_eq!(h.app.ui.dialog, None, "no Paste Selected Settings"); +} /// The opening release can carry both physical shortcut keys and the replacement text. #[test] fn opening_numeric_release_keeps_keys_in_the_editor() { @@ -453,3 +519,51 @@ fn cmd_o_does_not_fire_while_a_dialog_is_open() { press(&mut h, "O", &["cmd"]); assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); } + +/// The crop aspect lock is a first-class row of Help - Keyboard Shortcuts: A, listed in the +/// editor like any other command, sharing the key with Visualize Spots as a contextual pair. +#[test] +fn lock_aspect_ratio_is_a_listed_row_on_a() { + use crate::shortcuts::{CONTEXTUAL, Keymap, bindable, shortcut_of}; + let b = bindable().iter().find(|b| b.id == "crop.lockAspect").expect("crop.lockAspect is mappable"); + assert_eq!(b.label, "Lock Aspect Ratio"); + assert_eq!(b.default, Some("A")); + assert_eq!(shortcut_of(&Keymap::new(), "crop.lockAspect"), Some("A")); + assert!(CONTEXTUAL.contains(&("view.visualizeSpots", "crop.lockAspect")), "A is disambiguated by context"); + // the editor lists it: the row is on screen and records keys for it + let mut h = demo(); + record(&mut h, "lock", "crop.lockAspect"); + key(&mut h, "Escape", false); + assert_eq!(shortcut_of(&h.app.ui.settings.keymap, "crop.lockAspect"), Some("A"), "Esc cancels the recording: A stays"); + key(&mut h, "Escape", false); + assert!(h.app.ui.dialog.is_none()); +} + +/// A is the aspect lock while the Crop panel is open — Visualize Spots, the other A, must not take +/// the panel or turn its view on — and outside the panel A opens Visualize Spots as usual. The lock +/// is the tool's own (a fresh photo starts locked to its shape and the toggle may only record +/// "free", leaving the raw develop aspect untouched), so the test reads `crop_tool_aspect`. +#[test] +fn a_is_the_aspect_lock_under_crop_and_visualize_spots_elsewhere() { + use crate::state::RightPanel; + let mut h = demo(); + let aspect = |h: &Headless| h.app.crop_tool_aspect(); + let spots_before = h.app.ui.visualize_spots; + h.app.run("panel.crop", json!({})).unwrap(); + h.step(); + h.step(); + assert_eq!(h.app.ui.right, RightPanel::Crop); + let before = aspect(&h); + key(&mut h, "A", false); + assert_eq!(h.app.ui.right, RightPanel::Crop, "Visualize Spots must not take the panel"); + assert_eq!(h.app.ui.visualize_spots, spots_before, "nor turn its view on"); + assert_ne!(aspect(&h), before, "A toggles the aspect lock"); + key(&mut h, "A", false); + assert_eq!(aspect(&h), before, "A toggles it back"); + // outside the panel the same key is Visualize Spots again + h.app.ui.right = RightPanel::None; + key(&mut h, "A", false); + assert_eq!(h.app.ui.right, RightPanel::Remove, "A opens Remove with the visualization"); + assert!(h.app.ui.visualize_spots, "Visualize Spots is on"); + assert_eq!(aspect(&h), before, "and the aspect is untouched"); +} diff --git a/crates/ui-egui/src/tests_keyword_list.rs b/crates/ui-egui/src/tests_keyword_list.rs index bdeaef0dcc..579d79867b 100644 --- a/crates/ui-egui/src/tests_keyword_list.rs +++ b/crates/ui-egui/src/tests_keyword_list.rs @@ -456,8 +456,8 @@ fn ticking_a_keyword_keeps_the_list_in_place() { assert!(box_moved, "the box changed height (the list was held, not left alone)"); } -/// At the top of the panel the box is in sight: a ticked keyword's chip pushes the list down, -/// as before. +/// At the top of the panel the box is in sight: adding keyword chips pushes the list down +/// without scrolling the panel. Checkbox interaction is covered separately above. #[test] fn at_the_top_the_box_grows_in_sight() { let (mut h, ids) = keywords_panel_at([1400.0, 640.0]); @@ -465,7 +465,10 @@ fn at_the_top_the_box_grows_in_sight() { let (title, box_top) = (rect(&h, "keywordList:topLevel"), rect(&h, "field:keyword")); for k in ["aaa1", "aaa2", "aaa3", "aaa4", "aaa5", "aaa6"] { run(&mut h, "keyword.create", json!({"name": k})); - ask(&mut h, "ui.clickWidget", json!({"id": format!("keywordCheck:{k}")})); + // Growing chips eventually push later rows outside this short viewport. Add through + // the command so this layout regression never relies on clicking a clipped checkbox. + run(&mut h, "photo.setMeta", json!({"ids": ids, "addKeywords": [k]})); + assert!(ids.iter().all(|id| keywords_of(&h, *id).iter().any(|keyword| keyword == k)), "{k} was added to both photos"); } assert_eq!(rect(&h, "field:keyword"), box_top, "the panel stays at its top"); assert!(rect(&h, "keywordList:topLevel").top() > title.top(), "the chips pushed the list down"); diff --git a/crates/ui-egui/src/tests_keyword_set.rs b/crates/ui-egui/src/tests_keyword_set.rs index 4667f53674..4874a58a95 100644 --- a/crates/ui-egui/src/tests_keyword_set.rs +++ b/crates/ui-egui/src/tests_keyword_set.rs @@ -160,3 +160,20 @@ fn save_as_a_new_set_keeps_the_original() { assert_eq!(names, ["Recent Keywords", "Weddings", "Ceremonies"]); assert_eq!(s["current"], "Ceremonies"); } + +/// ⌥0 / ⌥⇧0 (Alt+0 / Alt+Shift+0) go to the next and the previous keyword set, as in Lightroom +/// Classic's Library, and ⌥1 then applies the new set's first keyword. +#[test] +fn alt_0_and_alt_shift_0_cycle_the_keyword_sets() { + let mut h = keywords_panel(); + h.app.session.execute("keyword.saveSet", &json!({"name": "Weddings", "keywords": ["ceremony"]})).unwrap(); + h.app.session.execute("keyword.useSet", &json!({"name": "Recent Keywords"})).unwrap(); + h.settle(SETTLE); + ask(&mut h, "ui.key", json!({"key": "0", "alt": true})); + assert_eq!(sets(&mut h)["current"], "Weddings", "⌥0: the next set"); + ask(&mut h, "ui.key", json!({"key": "1", "alt": true})); + let id = h.app.session.selected()[0]; + assert!(h.app.session.catalog.photo(id).unwrap().meta.keywords.iter().any(|k| k == "ceremony"), "⌥1 applied the set's keyword"); + ask(&mut h, "ui.key", json!({"key": "0", "alt": true, "shift": true})); + assert_eq!(sets(&mut h)["current"], "Recent Keywords", "⌥⇧0: the previous set"); +} diff --git a/crates/ui-egui/src/tests_keywording.rs b/crates/ui-egui/src/tests_keywording.rs index 95b02967c5..754a5ababe 100644 --- a/crates/ui-egui/src/tests_keywording.rs +++ b/crates/ui-egui/src/tests_keywording.rs @@ -108,6 +108,55 @@ fn the_add_keyword_box_pastes_adds_and_gives_up() { assert!(ids.iter().all(|id| !keywords_of(&h, *id).contains(&"harbour".to_string())), "Esc gave it up"); } +/// ⌘K (Ctrl+K) is Add Keywords: it shows the Keywords panel, opens Keywording when it is folded +/// shut, and puts the cursor in the Add keyword box, so what is typed next goes to the selection. +#[test] +fn cmd_k_puts_the_cursor_in_the_add_keyword_box() { + let (mut h, ids) = two_selected(); + ask(&mut h, "ui.clickWidget", json!({"id": "section:keywording"})); + ask(&mut h, "ui.set", json!({"right": "none"})); + ask(&mut h, "ui.key", json!({"key": "K", "cmd": true})); + assert_eq!(h.app.ui.right, crate::state::RightPanel::Keywords, "the Keywords panel"); + assert!(!h.app.ui.section_folded("keywording") && has(&h, "field:keyword"), "Keywording is open"); + assert!(h.view.ctx.memory(|m| m.has_focus(crate::text_field::id("field:keyword"))), "the box has the cursor"); + ask(&mut h, "ui.text", json!({"text": "harbour"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert!(ids.iter().all(|id| keywords_of(&h, *id).contains(&"harbour".to_string())), "typed and given to both"); + assert!(!h.view.ctx.memory(|m| m.has_focus(crate::text_field::id("field:keyword"))), "Return gave up the cursor"); + ask(&mut h, "ui.key", json!({"key": "K", "cmd": true})); + assert_eq!(h.app.ui.right, crate::state::RightPanel::Keywords, "pressed again: the panel stays"); + assert!(h.view.ctx.memory(|m| m.has_focus(crate::text_field::id("field:keyword"))), "and the cursor is back in the box"); +} + +/// With no photo, ⌘K shows the Keywords panel and its note; selecting photos afterwards doesn't put the +/// cursor in the Add keyword box. +#[test] +fn cmd_k_without_a_photo_leaves_the_cursor_alone() { + let (mut h, ids) = two_selected(); + ask(&mut h, "engine.execute", json!({"command": "library.select", "params": {"ids": []}})); + assert!(h.app.session.active().is_none(), "no active photo"); + ask(&mut h, "ui.set", json!({"right": "none"})); + ask(&mut h, "ui.key", json!({"key": "K", "cmd": true})); + assert_eq!(h.app.ui.right, crate::state::RightPanel::Keywords, "the Keywords panel"); + assert!(!has(&h, "field:keyword"), "no box without a photo"); + ask(&mut h, "engine.execute", json!({"command": "library.select", "params": {"ids": ids}})); + assert!(has(&h, "field:keyword")); + assert!(!h.view.ctx.memory(|m| m.has_focus(crate::text_field::id("field:keyword"))), "the box waits for a click"); +} + +/// An Add Keywords request the box wasn't drawn for in time (the panel couldn't show) expires: a +/// later draw of the box leaves the cursor alone. +#[test] +fn a_stale_add_keywords_request_leaves_the_cursor_alone() { + let (mut h, _) = two_selected(); + ask(&mut h, "ui.set", json!({"right": "keywords"})); + assert!(has(&h, "field:keyword")); + h.app.ui.focus_keywords = Some(h.view.ctx.cumulative_pass_nr().saturating_sub(crate::state::FOCUS_KEYWORDS_PASSES + 1)); + h.step(); + assert_eq!(h.app.ui.focus_keywords, None, "the request is used up"); + assert!(!h.view.ctx.memory(|m| m.has_focus(crate::text_field::id("field:keyword"))), "the box waits for a click"); +} + /// The keyword set's buttons say whether the selection has each keyword, as their ⌥1–⌥9 toggle it /// on the selection: on when every selected photo has it, partly on when only some do. #[test] @@ -196,6 +245,38 @@ fn the_active_photo_alone_is_the_selection() { assert!(has(&h, "keywordCheck:beach")); } +/// Given a selection with a keyword that is inside others, when the Keyword List is shown, then +/// every keyword above it carries a dot in its box (also folded, where the keyword itself is out +/// of sight), and its own box is the one that is ticked. A keyword above it that the selection +/// has itself shows its tick and no dot; a keyword with nothing applied inside shows neither. +#[test] +fn a_keyword_shows_that_one_inside_it_is_applied() { + let (mut h, ids) = two_selected(); + ask(&mut h, "engine.execute", json!({"command": "photo.setMeta", "params": {"ids": ids, "addKeywords": ["travel|Italy|Rome"]}})); + h.settle(SETTLE); + // folded: `travel` is the only row of the three, and says there is something inside + assert!(has(&h, "keywordRow:travel") && !has(&h, "keywordRow:travel|Italy"), "folded"); + assert!(has(&h, "keywordInside:travel")); + assert!(!has(&h, "keywordInside:beach") && !has(&h, "keywordInside:Weddings"), "nothing is inside these"); + // the dot sits in the keyword's own box + let rect = |h: &Headless, id: &str| h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap(); + assert!(rect(&h, "keywordCheck:travel").contains_rect(rect(&h, "keywordInside:travel"))); + // opened down to it: each level above has the dot, the keyword itself the tick + h.app.ui.keyword_list_open.extend(["travel".to_string(), "travel|italy".to_string()]); + h.settle(SETTLE); + assert!(has(&h, "keywordInside:travel") && has(&h, "keywordInside:travel|Italy")); + assert!(has(&h, "keywordRow:travel|Italy|Rome") && !has(&h, "keywordInside:travel|Italy|Rome")); + // a keyword the selection has itself shows its own state: the tick, or the dash when only some photos have it + ask(&mut h, "engine.execute", json!({"command": "photo.setMeta", "params": {"ids": ids, "addKeywords": ["travel"]}})); + ask(&mut h, "engine.execute", json!({"command": "photo.setMeta", "params": {"ids": [ids[0]], "addKeywords": ["travel|Italy"]}})); + h.settle(SETTLE); + assert!(!has(&h, "keywordInside:travel") && !has(&h, "keywordInside:travel|Italy")); + // with nothing selected nothing is applied, inside or not + ask(&mut h, "engine.execute", json!({"command": "library.select", "params": {"ids": []}})); + h.settle(SETTLE); + assert!(has(&h, "keywordRow:travel") && !h.app.widgets.iter().any(|(w, _)| w.starts_with("keywordInside:"))); +} + /// Esc in the Add keyword box gives back what it held before this edit, as every text field does: /// text left there by an earlier edit stays. #[test] diff --git a/crates/ui-egui/src/tests_launch_library.rs b/crates/ui-egui/src/tests_launch_library.rs new file mode 100644 index 0000000000..448bb735ad --- /dev/null +++ b/crates/ui-egui/src/tests_launch_library.rs @@ -0,0 +1,1029 @@ +//! Issue #1290: what opens at launch. Settings ▸ General ▸ At launch opens the last library or +//! asks with a window listing the recent ones (greyed out with the reason when they can't be +//! opened); Alt/Option held as the window appears asks once; one recent entry can be forgotten from +//! File ▸ Open Recent Library, the window and `app.recentLibraries {remove}`. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::library_problem::{ALT_SECONDS, Launch, LibraryProblem, launch_plan}; +use crate::state::{AppSettings, LaunchLibrary}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +/// A fresh scratch folder for one test. +fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-ui-launch-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A library on disk at `dir` (written, then closed: as left by an earlier run). +fn make_library(dir: &Path) -> String { + let mut s = lightcraft_engine::Session::new().with_fs(); + s.open_library(dir, false).unwrap(); + s.close_library().unwrap(); + drop(s); + assert!(lightcraft_engine::library::is_library(dir)); + dir.to_string_lossy().into_owned() +} + +/// Enough frames for a synthetic click (move, press, release) and what it starts. +fn settle(h: &mut Headless) { + for _ in 0..6 { + h.step(); + } +} + +/// The widget `id` was drawn in the last frame. +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +/// `Some(s)` as a path, for the launch plan's arguments. +fn path(s: &str) -> Option<PathBuf> { + Some(PathBuf::from(s)) +} + +/// `--library`, then `LIGHTCRAFT_LIBRARY`, then the setting; `--memory` never asks. +#[test] +fn the_launch_plan_puts_the_flag_and_the_variable_before_the_setting() { + let ask = AppSettings { at_launch: LaunchLibrary::Ask, library_path: "/last".into(), ..AppSettings::default() }; + let last = AppSettings { library_path: "/last".into(), recent_libraries: vec!["/last".into(), "/older".into()], ..AppSettings::default() }; + let fresh = AppSettings::default(); + let open = |dir: &str, alt_asks| Launch::Open { dir: path(dir), alt_asks }; + // --library, then LIGHTCRAFT_LIBRARY, whatever the setting says; neither asks on Alt + for s in [None, Some(&ask), Some(&last)] { + assert_eq!(launch_plan(false, path("/flag"), path("/env"), s, path("/default")), open("/flag", false)); + assert_eq!(launch_plan(false, None, path("/env"), s, path("/default")), open("/env", false)); + } + // Ask me asks, with or without a recent list + assert_eq!(launch_plan(false, None, None, Some(&ask), path("/default")), Launch::Ask); + let ask_empty = AppSettings { at_launch: LaunchLibrary::Ask, ..AppSettings::default() }; + assert_eq!(launch_plan(false, None, None, Some(&ask_empty), None), Launch::Ask); + // Open the last library: the last one, else the default place; Alt can still ask + assert_eq!(launch_plan(false, None, None, Some(&last), path("/default")), open("/last", true)); + assert_eq!(launch_plan(false, None, None, Some(&fresh), path("/default")), open("/default", true)); + assert_eq!(launch_plan(false, None, None, None, path("/default")), open("/default", true)); + assert_eq!(launch_plan(false, None, None, None, None), Launch::Open { dir: None, alt_asks: true }); + // --memory never asks and opens no folder + assert_eq!(launch_plan(true, None, None, Some(&ask), path("/default")), Launch::Open { dir: None, alt_asks: false }); + assert_eq!(launch_plan(true, path("/flag"), None, Some(&last), None), Launch::Open { dir: None, alt_asks: false }); +} + +/// Each listed library is checked when the window opens; the last one opened is selected. +#[test] +fn the_list_checks_each_library_and_selects_the_last_one() { + let dir = temp("choose"); + let (a, b, held, plain) = (dir.join("A"), dir.join("B"), dir.join("Held"), dir.join("Plain")); + let (a, b, held_path) = (make_library(&a), make_library(&b), make_library(&held)); + std::fs::create_dir_all(&plain).unwrap(); + std::fs::write(plain.join("notes.txt"), b"not a library").unwrap(); + let file = dir.join("a-file.txt"); + std::fs::write(&file, b"a file").unwrap(); + let (gone, plain, file) = + (dir.join("Gone").to_string_lossy().into_owned(), plain.to_string_lossy().into_owned(), file.to_string_lossy().into_owned()); + // another program has it open: listing doesn't take locks, so it is found when opened + let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&held_path), "another LightCraft").unwrap(); + + let mut settings = AppSettings { + recent_libraries: vec![gone.clone(), held_path.clone(), a.clone(), plain.clone(), file.clone(), b.clone()], + library_path: b.clone(), + ..AppSettings::default() + }; + settings.recent_opened.insert(b.clone(), "2026-10-20T08:30:00".into()); + let p = LibraryProblem::choose(&settings); + assert!(!p.saves_nothing(), "the launch list is not a temporary session: removals are saved"); + let c = p.chooser.as_ref().unwrap(); + let why: Vec<Option<&str>> = c.libraries.iter().map(|l| l.unavailable.as_deref()).collect(); + assert!(why[0].unwrap().contains("Not found"), "{why:?}"); + assert_eq!(why[1], None, "a lock is not probed: {why:?}"); + assert_eq!(why[2], None); + assert!(why[3].unwrap().contains("no LightCraft library"), "{why:?}"); + assert!(why[4].unwrap().contains("not a library folder"), "{why:?}"); + assert_eq!(why[5], None); + assert_eq!(c.selected, Some(5), "the last library opened"); + assert_eq!(c.libraries[5].opened.as_deref(), Some("2026-10-20T08:30:00")); + assert_eq!(c.libraries[2].opened, None, "no time known"); + let json = p.to_json(); + assert_eq!(json["chooser"]["libraries"][0]["available"], false); + assert_eq!(json["chooser"]["selected"], 5); + + // the last library can't be opened: the first one that can is selected + settings.library_path = plain.clone(); + assert_eq!(LibraryProblem::choose(&settings).chooser.unwrap().selected, Some(1)); + // none can: the first row, Open greyed out + settings.recent_libraries = vec![gone.clone(), file.clone()]; + assert_eq!(LibraryProblem::choose(&settings).chooser.unwrap().selected, Some(0)); + // an empty list selects nothing + settings.recent_libraries.clear(); + let c = LibraryProblem::choose(&settings).chooser.unwrap(); + assert!(c.libraries.is_empty() && c.selected.is_none()); + assert!(LibraryProblem::new("/x", "e").saves_nothing(), "the failed-library window still saves nothing"); + drop(lock); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Every file under `dir`: relative path → (contents, length, modification time). +fn snapshot(dir: &Path) -> std::collections::BTreeMap<PathBuf, (Option<Vec<u8>>, u64, std::time::SystemTime)> { + let mut out = std::collections::BTreeMap::new(); + let mut todo = vec![dir.to_path_buf()]; + while let Some(d) = todo.pop() { + for e in std::fs::read_dir(&d).unwrap() { + let p = e.unwrap().path(); + let m = std::fs::metadata(&p).unwrap(); + if m.is_dir() { + todo.push(p.clone()); + } + let (bytes, len) = if m.is_file() { (contents(&p), m.len()) } else { (Some(Vec::new()), 0) }; + out.insert(p.strip_prefix(dir).unwrap().to_path_buf(), (bytes, len, m.modified().unwrap())); + } + } + out +} + +/// The bytes of the file `p`, or `None` for a lock file that a [`lightcraft_catalog::LibraryLock`] +/// holds on Windows: there `LockFileEx` locks the file's bytes, and reading them through another +/// handle fails with os error 33 (`ERROR_LOCK_VIOLATION`). Such a file is compared by its length +/// and modification time only. +fn contents(p: &Path) -> Option<Vec<u8>> { + match std::fs::read(p) { + Ok(bytes) => Some(bytes), + Err(e) if cfg!(windows) && e.raw_os_error() == Some(33) && p.file_name().is_some_and(|n| n == lightcraft_catalog::lock::LOCK) => None, + Err(e) => panic!("{}: {e}", p.display()), + } +} + +/// Listing the recent libraries (and drawing the window) writes nothing into any of them: no +/// lock file, no owner file, nothing modified — free, held by another program or not a library. +#[test] +fn listing_the_libraries_leaves_every_folder_byte_identical() { + let dir = temp("readonly"); + let (free, fresh, held) = (dir.join("Free"), dir.join("Fresh"), dir.join("Held")); + let (free, held_path) = (make_library(&free), make_library(&held)); + // a library whose lock files were never made (copied over from elsewhere, say) + let fresh_path = make_library(&fresh); + for f in [lightcraft_catalog::lock::LOCK, lightcraft_catalog::lock::OWNER] { + let _ = std::fs::remove_file(fresh.join(f)); + } + std::fs::create_dir_all(dir.join("Plain")).unwrap(); + let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&held_path), "another LightCraft").unwrap(); + let recent = vec![free.clone(), fresh_path.clone(), held_path.clone(), dir.join("Plain").to_string_lossy().into_owned()]; + let before = snapshot(&dir); + // (mtime granularity: a write in the same instant would still change contents or add files) + let settings = AppSettings { recent_libraries: recent.clone(), library_path: free.clone(), ..AppSettings::default() }; + let p = LibraryProblem::choose(&settings); + assert_eq!(snapshot(&dir), before, "checking the rows must not create or change any file"); + assert!(p.chooser.as_ref().unwrap().libraries.iter().take(3).all(|l| l.unavailable.is_none())); + let mut h = asking(recent, &free, None); + settle(&mut h); + assert!(has(&h, "libraryRecent:2")); + drop(h); + assert_eq!(snapshot(&dir), before, "listing must not create or change any file"); + assert!(!fresh.join(lightcraft_catalog::lock::LOCK).exists() && !fresh.join(lightcraft_catalog::lock::OWNER).exists()); + drop(lock); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The app as the desktop host starts it with *Ask me*: no library open, the list showing. +fn asking(recent: Vec<String>, last: &str, picked: Option<String>) -> Headless { + let session = lightcraft_engine::Session::new().with_fs(); + // (an encoder for the screenshots LIGHTCRAFT_TEST_SHOTS asks for) + let png = |img: &lightcraft_raster::Rgba8| { + lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default() + }; + let services = Services { + png: Some(Box::new(png)), + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = LightcraftApp::new(session, services); + app.ui.settings.recent_libraries = recent; + app.ui.settings.library_path = last.to_string(); + app.ui.settings.at_launch = LaunchLibrary::Ask; + if let Some(p) = picked { + app.services.pick_folder = Some(Box::new(move || Some(p.clone()))); + } + app.library_problem = Some(LibraryProblem::choose(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + settle(&mut h); + h +} + +/// The window lists every recent library, greys out a missing one and opens the chosen one. +#[test] +fn the_window_lists_the_libraries_and_opens_the_chosen_one() { + let dir = temp("window"); + let (a, b) = (make_library(&dir.join("Alpha")), make_library(&dir.join("Beta"))); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + let mut h = asking(vec![a.clone(), gone.clone(), b.clone()], &a, None); + assert!(h.app.session.library.is_none(), "nothing opened before the choice"); + for id in ["libraryRecent:0", "libraryRecent:1", "libraryRecent:2", "button:libraryOpen", "button:libraryOpenAnother", "button:libraryNew"] { + assert!(has(&h, id), "{id}"); + } + assert!(has(&h, "button:libraryQuit") && has(&h, "button:libraryForget")); + assert!(!has(&h, "button:libraryRetry"), "not the failed-library window"); + if let Some(p) = std::env::var_os("LIGHTCRAFT_TEST_SHOTS") { + let r = h.request("ui.screenshot", json!({"path": Path::new(&p).join("launch-list.png").to_string_lossy(), "headless": true}), T); + assert_eq!(r["ok"], true, "{r}"); + } + let inspect = h.request("ui.inspect", json!({}), T); + let c = &inspect["result"]["libraryProblem"]["chooser"]; + assert_eq!(c["selected"], 0, "{c}"); + assert_eq!(c["libraries"][1]["available"], false, "{c}"); + + // ↓ onto the missing one: Return does nothing there (Open is greyed out) + assert_eq!(h.request("ui.key", json!({"key": "ArrowDown"}), T)["ok"], true); + settle(&mut h); + assert_eq!(h.app.library_problem.as_ref().unwrap().chooser.as_ref().unwrap().selected, Some(1)); + h.request("ui.key", json!({"key": "Enter"}), T); + settle(&mut h); + assert!(h.app.session.library.is_none() && h.app.library_problem.is_some()); + // ↓ again, then Open: Beta opens and the window goes away + h.request("ui.key", json!({"key": "ArrowDown"}), T); + settle(&mut h); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryOpen"}), T)["ok"], true); + settle(&mut h); + assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(b.clone())); + assert!(h.app.library_problem.is_none()); + assert!(!has(&h, "button:libraryOpen")); + assert_eq!(h.app.ui.settings.library_path, b); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Return opens the selection; a library taken meanwhile stays listed with the reason. +#[test] +fn return_opens_the_selected_library_and_a_failure_says_why() { + let dir = temp("return"); + let (a, b) = (make_library(&dir.join("Alpha")), make_library(&dir.join("Beta"))); + let mut h = asking(vec![a.clone(), b.clone()], &b, None); + assert_eq!(h.app.library_problem.as_ref().unwrap().chooser.as_ref().unwrap().selected, Some(1)); + // another program takes Beta after the window opened: Open says so and keeps the window + let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&b), "another LightCraft").unwrap(); + h.request("ui.key", json!({"key": "Enter"}), T); + settle(&mut h); + assert!(h.app.session.library.is_none()); + let p = h.app.library_problem.as_ref().unwrap(); + assert!(p.error.contains("already open in another LightCraft"), "who has it: {}", p.error); + assert!(p.chooser.as_ref().unwrap().libraries[1].unavailable.is_some(), "greyed out now"); + drop(lock); + // ↑ to Alpha, Return: it opens + h.request("ui.key", json!({"key": "ArrowUp"}), T); + settle(&mut h); + h.request("ui.key", json!({"key": "Enter"}), T); + settle(&mut h); + assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(a)); + assert!(h.app.library_problem.is_none()); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Quit and Esc quit without opening anything. +#[test] +fn quit_and_esc_quit_from_the_window() { + let dir = temp("quit"); + let a = make_library(&dir.join("Alpha")); + let mut h = asking(vec![a.clone()], &a, None); + h.request("ui.key", json!({"key": "Escape"}), T); + settle(&mut h); + assert!(h.quit_requested(), "Esc quits when no library is open"); + assert!(h.app.session.library.is_none(), "and opens nothing"); + drop(h); + + let mut h = asking(vec![a.clone()], &a, None); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryQuit"}), T)["ok"], true); + settle(&mut h); + assert!(h.quit_requested()); + assert!(h.app.session.library.is_none()); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Open Another… runs the folder dialog of `app.openLibrary`, also with an empty list. +#[test] +fn open_another_asks_for_a_folder_and_an_empty_list_still_offers_it() { + let dir = temp("another"); + let other = make_library(&dir.join("Elsewhere")); + let mut h = asking(Vec::new(), "", Some(other.clone())); + assert!(has(&h, "indicator:noRecentLibraries")); + assert!(!has(&h, "libraryRecent:0")); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryOpenAnother"}), T)["ok"], true); + settle(&mut h); + assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(other.clone())); + assert!(h.app.library_problem.is_none()); + assert_eq!(h.app.ui.settings.recent_libraries.first(), Some(&other), "remembered once opened"); + drop(h); + + // without a folder dialog (the browser) Open Another… and New Library… are greyed out + let mut h = asking(Vec::new(), "", None); + h.request("ui.clickWidget", json!({"id": "button:libraryOpenAnother"}), T); + h.request("ui.clickWidget", json!({"id": "button:libraryNew"}), T); + settle(&mut h); + assert!(h.app.library_problem.is_some() && h.app.ui.dialog.is_none()); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// New Library… asks for a name in front of the window; command-line photos go into it. +#[test] +fn new_library_from_the_window_asks_for_a_name_and_the_list_returns_if_cancelled() { + let dir = temp("newlib"); + let a = make_library(&dir.join("Alpha")); + let mut h = asking(vec![a.clone()], &a, Some(dir.to_string_lossy().into_owned())); + // a photo given on the command line waits for the library chosen + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 3, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + let photo = dir.join("a.png"); + std::fs::write(&photo, png).unwrap(); + h.app.library_problem.as_mut().unwrap().pending_import = vec![photo.to_string_lossy().into_owned()]; + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryNew"}), T)["ok"], true); + settle(&mut h); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::TextPrompt { .. })), "{:?}", h.app.ui.dialog); + assert!(!has(&h, "button:libraryOpen"), "the name prompt is in front"); + h.request("ui.dialog.cancel", json!({}), T); + settle(&mut h); + assert!(has(&h, "button:libraryOpen"), "the list is back"); + // what the prompt's OK runs: the library is made where the folder dialog says, and opens + h.app.run("app.newLibrary", json!({"name": "Fresh"})).unwrap(); + settle(&mut h); + assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.clone()), Some(dir.join("Fresh"))); + assert!(h.app.library_problem.is_none()); + h.step_until(T, |h| h.app.import.is_none() && h.app.session.catalog.len() == 1); + assert_eq!(h.app.session.catalog.len(), 1, "the command-line photo is imported into the new library"); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Remove from List in the window forgets the selected entry and deletes nothing. +#[test] +fn remove_from_list_forgets_one_library_and_deletes_nothing() { + let dir = temp("forget"); + let (a, b) = (make_library(&dir.join("Alpha")), make_library(&dir.join("Beta"))); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + let mut h = asking(vec![a.clone(), gone.clone(), b.clone()], &a, None); + h.app.ui.settings.recent_opened.insert(gone.clone(), "2026-01-01T00:00:00".into()); + // the window: the missing one can be selected and removed + h.request("ui.clickWidget", json!({"id": "libraryRecent:1"}), T); + settle(&mut h); + assert_eq!(h.app.library_problem.as_ref().unwrap().chooser.as_ref().unwrap().selected, Some(1)); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryForget"}), T)["ok"], true); + settle(&mut h); + assert_eq!(h.app.ui.settings.recent_libraries, [a.clone(), b.clone()]); + assert!(!h.app.ui.settings.recent_opened.contains_key(&gone), "its time goes too"); + let c = h.app.library_problem.as_ref().unwrap().chooser.clone().unwrap(); + assert_eq!(c.libraries.len(), 2); + assert_eq!(c.selected, Some(1)); + // removing an existing library leaves its folder and catalog alone + h.request("ui.clickWidget", json!({"id": "button:libraryForget"}), T); + settle(&mut h); + assert_eq!(h.app.ui.settings.recent_libraries, vec![a.clone()]); + assert!(lightcraft_engine::library::is_library(Path::new(&b)), "nothing is deleted on disk"); + settle(&mut h); + assert!(!has(&h, "libraryRecent:1")); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// File ▸ Open Recent Library's items. +fn open_recent(app: &LightcraftApp) -> Vec<crate::menubar::MenuNode> { + use crate::menubar::MenuNode; + let bar = crate::menubar::menu_bar(app); + let file = &bar.iter().find(|(t, _)| t == "File").unwrap().1; + match file.iter().find(|n| matches!(n, MenuNode::Submenu { label, .. } if label == "Open Recent Library")) { + Some(MenuNode::Submenu { children, .. }) => children.clone(), + _ => panic!("no Open Recent Library submenu in {file:?}"), + } +} + +/// File ▸ Open Recent Library ▸ Remove from List and `app.recentLibraries {remove}`. +#[test] +fn open_recent_library_and_the_command_remove_one_entry() { + use crate::menubar::MenuNode; + let dir = temp("menu"); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(dir.join("first"), false).unwrap(); + let mut app = LightcraftApp::new(session, Services::default()); + let (first, gone) = (dir.join("first").to_string_lossy().into_owned(), dir.join("gone").to_string_lossy().into_owned()); + app.ui.settings.recent_libraries = vec![first.clone(), gone.clone(), "/elsewhere/third".into()]; + + let items = open_recent(&app); + let Some(MenuNode::Submenu { children, .. }) = items.iter().find(|n| matches!(n, MenuNode::Submenu { label, .. } if label == "Remove from List")) + else { + panic!("no Remove from List in {items:?}") + }; + assert_eq!(children.len(), 3, "every entry, missing ones too"); + let MenuNode::Item { id, params, label, enabled, .. } = &children[1] else { panic!("{children:?}") }; + assert_eq!((id.as_str(), params, *enabled), ("app.recentLibraries", &json!({"remove": gone}), true)); + assert!(label.starts_with("gone — "), "{label}"); + assert_eq!(crate::menubar::display_item_label(id, params, label), label, "a path is never translated"); + // what clicking it runs + let list = app.run(id, params.clone()).unwrap(); + assert_eq!(list.as_array().unwrap().len(), 2); + assert_eq!(app.ui.settings.recent_libraries, [first.clone(), "/elsewhere/third".to_string()]); + + // the command: the open library can be forgotten too (it stays open), and nothing is deleted + let list = app.run("app.recentLibraries", json!({"remove": first})).unwrap(); + // (no frame ran: nothing checked yet, so `exists` is not known; the command never looks itself) + assert_eq!(list, json!([{"path": "/elsewhere/third", "name": "third", "exists": null, "checking": false, "open": false, "lastOpened": null}])); + assert!(app.session.library.is_some() && lightcraft_engine::library::is_library(&dir.join("first"))); + let e = app.run("app.recentLibraries", json!({"remove": first})).unwrap_err(); + assert!(e.contains("not in the recent libraries"), "{e}"); + let e = app.run("app.recentLibraries", json!({"remove": 3})).unwrap_err(); + assert!(e.contains("remove must be"), "{e}"); + app.run("app.recentLibraries", json!({"remove": "/elsewhere/third"})).unwrap(); + // an empty list has nothing to remove + let items = open_recent(&app); + assert!(!items.iter().any(|n| matches!(n, MenuNode::Submenu { .. })), "{items:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `atLaunch` and `recentLibrariesOpened` round-trip, and older or odd files still load. +#[test] +fn the_setting_and_the_open_times_are_kept_in_the_settings_file() { + // files from earlier versions: no key, the default; a value from a later version: the default + let old: crate::UiState = serde_json::from_str(r#"{"settings": {"recentLibraries": ["/a"], "startupView": "detail"}}"#).unwrap(); + assert_eq!(old.settings.at_launch, LaunchLibrary::Last); + assert!(old.settings.recent_opened.is_empty()); + assert_eq!(old.settings.recent_libraries, ["/a"]); + let odd: crate::UiState = + serde_json::from_str(r#"{"settings": {"atLaunch": "someday", "recentLibrariesOpened": 7, "startupView": "detail"}}"#).unwrap(); + assert_eq!(odd.settings.at_launch, LaunchLibrary::Last); + assert!(odd.settings.recent_opened.is_empty()); + assert_eq!(odd.settings.startup_view, crate::state::StartupView::Detail, "the rest of the file still loads"); + + let mut ui = crate::UiState::default(); + ui.settings.at_launch = LaunchLibrary::Ask; + ui.settings.recent_libraries = vec!["/a".into()]; + ui.settings.recent_opened.insert("/a".into(), "2026-10-23T09:00:00".into()); + let saved = serde_json::to_value(&ui).unwrap(); + assert_eq!(saved["settings"]["atLaunch"], "ask"); + assert_eq!(saved["settings"]["recentLibraries"], json!(["/a"]), "the list keeps its old shape"); + assert_eq!(saved["settings"]["recentLibrariesOpened"], json!({"/a": "2026-10-23T09:00:00"})); + let back: crate::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(back.settings, ui.settings); +} + +/// The Settings choice and `ui.set` change the setting; an opened library gets its time. +#[test] +fn settings_choose_ask_me_and_opening_a_library_records_when() { + let dir = temp("settings"); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(dir.join("first"), false).unwrap(); + let mut app = LightcraftApp::new(session, Services::default()); + app.services.pick_folder = Some(Box::new(|| None)); + app.ui.settings.recent_opened.insert("/forgotten".into(), "2020-01-01T00:00:00".into()); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + settle(&mut h); + let first = dir.join("first").to_string_lossy().into_owned(); + // the session clock's time (tests: a fixed one), only for listed libraries + assert_eq!(h.app.ui.settings.recent_opened.get(&first).map(String::as_str), Some("2026-09-30T12:00:00")); + assert!(!h.app.ui.settings.recent_opened.contains_key("/forgotten")); + + h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": "general"}}), T); + settle(&mut h); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:settingsAtLaunch-1"}), T)["ok"], true); + settle(&mut h); + assert_eq!(h.app.ui.settings.at_launch, LaunchLibrary::Ask); + h.request("ui.clickWidget", json!({"id": "button:settingsAtLaunch-0"}), T); + settle(&mut h); + assert_eq!(h.app.ui.settings.at_launch, LaunchLibrary::Last); + // also through ui.set, as scripts change settings + let r = h.request("ui.set", json!({"settings": {"atLaunch": "ask"}}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(h.app.ui.settings.at_launch, LaunchLibrary::Ask); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The app as the host starts it with *Open the last library*: `first` open, Alt watched. +fn opened_last(dir: &Path) -> (Headless, String, String) { + let (first, second) = (make_library(&dir.join("first")), make_library(&dir.join("second"))); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&first, false).unwrap(); + let mut app = LightcraftApp::new(session, Services::default()); + app.ui.settings.recent_libraries = vec![first.clone(), second.clone()]; + app.ui.settings.library_path = first.clone(); + app.alt_asks_for_library = true; + (Headless::new(app, [1300.0, 900.0], 1.0), first, second) +} + +/// Alt held as the window appears shows the list once over the open library; Esc keeps it. +#[test] +fn alt_held_as_the_window_appears_asks_once_over_the_last_library() { + let dir = temp("alt"); + let (mut h, first, _) = opened_last(&dir); + settle(&mut h); + assert!(h.app.library_problem.is_none(), "no Alt: the last library, no window"); + h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + settle(&mut h); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).expect("the list shows"); + assert_eq!(c.selected, Some(0)); + assert!(c.over.is_some(), "over the library that opened"); + assert!(c.libraries[0].unavailable.is_none(), "the open library itself can be chosen"); + assert!(has(&h, "button:libraryOpen")); + // Esc keeps the library that opened + h.request("ui.key", json!({"key": "Escape"}), T); + settle(&mut h); + assert!(!h.quit_requested(), "Esc doesn't quit while a library is open"); + assert!(h.app.library_problem.is_none()); + assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(first.clone())); + // once only + h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + settle(&mut h); + assert!(h.app.library_problem.is_none()); + drop(h); + + // choosing another library from it switches to that one + let dir2 = temp("alt-switch"); + let (mut h, _, second2) = opened_last(&dir2); + h.app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + settle(&mut h); + h.request("ui.key", json!({"key": "ArrowDown"}), T); + settle(&mut h); + h.request("ui.key", json!({"key": "Enter"}), T); + settle(&mut h); + assert_eq!(h.app.session.library.as_ref().map(|l| l.dir.to_string_lossy().into_owned()), Some(second2)); + assert!(h.app.library_problem.is_none()); + drop(h); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&dir2); +} + +/// The Alt watch ends after the first seconds and needs the host to arm it. +#[test] +fn alt_is_only_watched_while_the_window_first_appears_and_when_armed() { + let frame = |app: &mut LightcraftApp, ctx: &egui::Context, time: f64, alt: bool| { + let modifiers = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; + let raw = egui::RawInput { time: Some(time), events: vec![egui::Event::ModifiersChanged(modifiers)], ..Default::default() }; + ctx.run_ui(raw, |ui| crate::panels::library_problem::logic(app, ui.ctx())).textures_delta.clear(); + }; + let new_app = |armed| { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + app.alt_asks_for_library = armed; + app + }; + // too late: the watch ends, a later Alt does nothing + let (mut app, ctx) = (new_app(true), egui::Context::default()); + frame(&mut app, &ctx, ALT_SECONDS + 0.5, false); + assert!(!app.alt_asks_for_library); + frame(&mut app, &ctx, ALT_SECONDS + 0.6, true); + assert!(app.library_problem.is_none()); + // not armed (--library, LIGHTCRAFT_LIBRARY, --memory, the browser) + let (mut app, ctx) = (new_app(false), egui::Context::default()); + frame(&mut app, &ctx, 0.1, true); + assert!(app.library_problem.is_none()); + // armed, in time + let (mut app, ctx) = (new_app(true), egui::Context::default()); + frame(&mut app, &ctx, 0.1, false); + assert!(app.alt_asks_for_library && app.library_problem.is_none()); + frame(&mut app, &ctx, 0.2, true); + assert!(app.library_problem.as_ref().is_some_and(|p| p.chooser.is_some())); + assert!(!app.alt_asks_for_library); +} + +/// A check that waits until the test lets it go (a network share whose server is gone), then +/// answers like the real one for a missing folder. `release` lets every waiting check go. +fn slow_checks() -> ( + crate::panels::library_problem::RecentChecks, + std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>, + std::sync::Arc<std::sync::atomic::AtomicUsize>, +) { + let gate = std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (g, n) = (gate.clone(), calls.clone()); + let checks = crate::panels::library_problem::RecentChecks::with_check(move |p| { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let (lock, cv) = &*g; + let open = lock.lock().unwrap(); + // (bounded: a test that forgets to release still ends) + let _unused = cv.wait_timeout_while(open, Duration::from_secs(10), |open| !*open).unwrap(); + (!Path::new(p).exists()).then_some(crate::panels::library_problem::Unavailable::NotFound) + }); + (checks, gate, calls) +} + +/// Let every check waiting in [`slow_checks`] answer. +fn release(gate: &std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>) { + let (lock, cv) = &**gate; + *lock.lock().unwrap() = true; + cv.notify_all(); +} + +/// Review of #2701: the launch list never waits on a folder. Its rows show "Checking…" while a +/// worker looks (the activity stack lists it), the window keeps drawing frames meanwhile, and the +/// answers grey out a missing library and move the selection to one that can be opened. +#[test] +fn a_slow_check_never_holds_the_launch_window() { + let dir = temp("slow"); + let a = make_library(&dir.join("A")); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.settings.recent_libraries = vec![gone.clone(), a.clone()]; + app.ui.settings.library_path = gone.clone(); + let (checks, gate, _) = slow_checks(); + app.recent_checks = checks; + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let t0 = std::time::Instant::now(); + settle(&mut h); + assert!(t0.elapsed() < Duration::from_secs(5), "frames went on while the check waited: {:?}", t0.elapsed()); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap(); + assert!(c.libraries.iter().all(|l| l.checking && l.unavailable.is_none()), "{c:?}"); + assert_eq!(c.selected, Some(0), "the last library opened, until the answers say otherwise"); + assert!(h.painted_text().iter().any(|t| t == "Checking…"), "{:?}", h.painted_text()); + assert!(h.app.session.activity.list().iter().any(|t| t.label == "Checking recent libraries"), "the activity stack lists the check"); + + release(&gate); + let done = + h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking))); + assert!(done, "the answers came back"); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap(); + assert!(c.libraries[0].unavailable.as_deref().is_some_and(|w| w.contains("Not found")), "{c:?}"); + assert_eq!(c.libraries[1].unavailable, None); + assert_eq!(c.selected, Some(1), "the first library that can be opened, once known"); + assert!(h.app.session.activity.list().iter().all(|t| t.label != "Checking recent libraries"), "the row goes with the check"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Answers that arrive after the person moved the highlight leave it where they put it. +#[test] +fn late_answers_keep_the_row_the_person_chose() { + let dir = temp("touched"); + let a = make_library(&dir.join("A")); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.settings.recent_libraries = vec![a.clone(), gone.clone()]; + app.ui.settings.library_path = a.clone(); + let (checks, gate, _) = slow_checks(); + app.recent_checks = checks; + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + settle(&mut h); + h.request("ui.key", json!({"key": "ArrowDown"}), T); + settle(&mut h); + release(&gate); + h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking))); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap(); + assert_eq!(c.selected, Some(1), "still the row moved to, though it can't be opened"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// File ▸ Open Recent Library is rebuilt every frame: it never looks at a folder itself. A +/// library is greyed out only once a worker found it missing, and each path is checked once. +#[test] +fn the_recent_menu_takes_its_answers_from_a_worker() { + use crate::menubar::MenuNode; + let dir = temp("menu-worker"); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.settings.recent_libraries = vec![gone.clone()]; + let (checks, gate, calls) = slow_checks(); + app.recent_checks = checks; + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let enabled = |h: &Headless| match open_recent(&h.app).first() { + Some(MenuNode::Item { enabled, .. }) => *enabled, + other => panic!("{other:?}"), + }; + for _ in 0..30 { + h.step(); + assert!(enabled(&h), "not known yet: kept enabled (opening says why if it can't)"); + } + release(&gate); + assert!(h.step_until(T, |h| !h.app.recent_checks.is_running() && h.app.recent_checks.is_known(&gone)), "answered"); + for _ in 0..30 { + h.step(); + } + assert!(!enabled(&h), "found missing: greyed out"); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1, "checked once, not every frame"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The reasons are put into words on the UI thread, in the interface language (the worker that +/// found them has none of its own). +#[test] +fn the_reasons_are_in_the_interface_language() { + let dir = temp("lang"); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.language = crate::i18n::Locale::Fr; + app.ui.settings.recent_libraries = vec![gone.clone()]; + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + assert!( + h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking))) + ); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap(); + let why = c.libraries[0].unavailable.clone().unwrap_or_default(); + let english = "Not found: moved, renamed or on a disconnected drive"; + crate::i18n::set_language(crate::i18n::Locale::Fr); + assert_eq!(why, crate::i18n::tr(english), "translated on the UI thread"); + assert_ne!(why, english, "the French catalog has this reason"); + crate::i18n::set_language(crate::i18n::Locale::En); + let _ = std::fs::remove_dir_all(&dir); +} + +/// One drive that never answers doesn't hold the others: each path has its own worker, and the +/// row that waits says the drive isn't answering once it takes long. +#[test] +fn one_hung_drive_doesnt_hold_the_other_libraries() { + let dir = temp("hung"); + let a = make_library(&dir.join("A")); + let hung = dir.join("Hung").to_string_lossy().into_owned(); + let gate = std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let g = gate.clone(); + let h_path = hung.clone(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(move |p| { + if p == h_path { + let (lock, cv) = &*g; + let open = lock.lock().unwrap(); + let _unused = cv.wait_timeout_while(open, Duration::from_secs(10), |open| !*open).unwrap(); + } + None + }); + app.ui.settings.recent_libraries = vec![hung.clone(), a.clone()]; + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let a_done = h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| !c.libraries[1].checking)); + assert!(a_done, "the reachable library answered while the other one hangs"); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap(); + assert!(c.libraries[0].checking, "the hung one is still checking"); + release(&gate); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A check whose worker dies (a panic) ends as "couldn't be checked" instead of leaving the row, +/// and every later check, waiting forever. +#[test] +fn a_check_that_dies_doesnt_leave_the_list_waiting() { + let dir = temp("dies"); + let a = make_library(&dir.join("A")); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(|_| panic!("a check that dies")); + app.ui.settings.recent_libraries = vec![a.clone()]; + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let done = h.step_until(T, |h| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| !c.libraries[0].checking)); + assert!(done, "the row stopped waiting"); + assert!(!h.app.recent_checks.is_running(), "no check is left running"); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap(); + assert!(c.libraries[0].unavailable.as_deref().is_some_and(|w| w.contains("couldn't be checked")), "{c:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library found missing comes back once it is opened again (a drive plugged back in): the +/// menu no longer greys it out. +#[test] +fn opening_a_library_clears_an_old_missing_answer() { + use crate::menubar::MenuNode; + let dir = temp("back"); + let a = make_library(&dir.join("A")); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.settings.recent_libraries = vec![a.clone()]; + app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(|_| Some(crate::panels::library_problem::Unavailable::NotFound)); + let ctx = egui::Context::default(); + crate::panels::library_problem::logic(&mut app, &ctx); + assert!(crate::tasks::wait(&mut app, &ctx, T), "checked"); + assert_eq!(app.recent_checks.exists(&a), Some(false), "found missing (the drive was disconnected)"); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.app.run("app.openLibrary", json!({"path": a})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert!(matches!(open_recent(&h.app).first(), Some(MenuNode::Item { enabled: true, .. })), "{:?}", open_recent(&h.app)); + assert_eq!(h.app.recent_checks.reason(&a), None); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #2701: a library that fails to open from the launch window because another program +/// has it is there all the same. The row shows the open's error, but the menu keeps it enabled and +/// `app.recentLibraries` says it exists; an unreadable catalog doesn't say the library is gone +/// either (`exists: null`). +#[test] +fn a_failed_open_or_an_unreadable_catalog_doesnt_mark_a_library_missing() { + use crate::menubar::MenuNode; + let dir = temp("held"); + let held = make_library(&dir.join("Held")); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.settings.recent_libraries = vec![held.clone()]; + app.ui.settings.library_path = held.clone(); + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + let answered = + |h: &Headless| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some_and(|c| c.libraries.iter().all(|l| !l.checking)); + assert!(h.step_until(T, answered)); + assert_eq!(h.app.recent_checks.exists(&held), Some(true)); + // another program has it: Open from the launch window fails + let lock = lightcraft_catalog::LibraryLock::acquire(Path::new(&held), "another LightCraft").unwrap(); + settle(&mut h); + let r = h.request("ui.clickWidget", json!({"id": "button:libraryOpen"}), T); + assert_eq!(r["ok"], true, "{r} {:?}", h.app.widgets.iter().map(|(w, _)| w.clone()).filter(|w| w.contains("library")).collect::<Vec<_>>()); + settle(&mut h); + let c = h.app.library_problem.as_ref().and_then(|p| p.chooser.clone()).unwrap(); + assert!(c.libraries[0].unavailable.is_some(), "the row shows why it didn't open: {c:?}"); + assert!(h.step_until(T, |h| !h.app.recent_checks.is_running() && h.app.recent_checks.is_known(&held)), "checked again"); + assert_eq!(h.app.recent_checks.exists(&held), Some(true), "a failed open doesn't mark it missing"); + let list = h.app.run("app.recentLibraries", json!({})).unwrap(); + assert_eq!(list[0]["exists"], true, "{list}"); + assert!(matches!(open_recent(&h.app).first(), Some(MenuNode::Item { enabled: true, .. })), "{:?}", open_recent(&h.app)); + drop(lock); + + // an unreadable catalog: not known to be gone + h.app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(|_| { + Some(crate::panels::library_problem::Unavailable::CatalogUnreadable("denied".into())) + }); + assert!(h.step_until(T, |h| h.app.recent_checks.is_known(&held) && !h.app.recent_checks.is_running())); + assert_eq!(h.app.run("app.recentLibraries", json!({})).unwrap()[0]["exists"], serde_json::Value::Null); + assert!(matches!(open_recent(&h.app).first(), Some(MenuNode::Item { enabled: true, .. }))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Photos dropped on the launch list wait for the library chosen (CodeRabbit on #2689): before, +/// they went into the session the library then replaced, and were gone from view. +#[test] +fn photos_dropped_on_the_launch_list_go_into_the_library_chosen() { + let dir = temp("drop"); + let a = make_library(&dir.join("Alpha")); + let mut h = asking(vec![a.clone()], &a, None); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 3, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + let photo = dir.join("a.png"); + std::fs::write(&photo, png).unwrap(); + // frames with nothing dropped (the drop code runs every frame) hold nothing and say nothing + settle(&mut h); + assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); + let ctx = h.view.ctx.clone(); + assert_eq!(crate::panels::library_problem::hold_dropped(&mut h.app, &ctx, Vec::new()), Some(Vec::new())); + assert!(h.app.ui.toast.is_none(), "an empty drop says nothing: {:?}", h.app.ui.toast); + let photos = vec![photo.to_string_lossy().into_owned()]; + assert!(crate::panels::library_problem::holds_drops(&h.app)); + assert_eq!(crate::panels::library_problem::hold_dropped(&mut h.app, &ctx, photos.clone()), None, "held while no library is open"); + assert_eq!(h.app.library_problem.as_ref().map(|p| p.pending_import.clone()), Some(photos.clone())); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("once a library is open")), "{:?}", h.app.ui.toast); + assert_eq!(h.app.session.catalog.len(), 0, "nothing goes into the session the library replaces"); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:libraryOpen"}), T)["ok"], true); + settle(&mut h); + h.step_until(T, |h| h.app.import.is_none() && h.app.session.catalog.len() == 1); + assert_eq!(h.app.session.catalog.len(), 1, "the dropped photo is imported into the library opened"); + // with a library open, a drop is the usual import + assert!(!crate::panels::library_problem::holds_drops(&h.app)); + assert_eq!(crate::panels::library_problem::hold_dropped(&mut h.app, &ctx, photos.clone()), Some(photos)); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A lookup that fails without saying the library is gone (here a parent folder it may not read; +/// a network share that timed out is the same) is "couldn't check", not "not found": the entry +/// isn't greyed out in File ▸ Open Recent Library (CodeRabbit on #2689). +#[cfg(unix)] +#[test] +fn a_failed_lookup_doesnt_mark_a_recent_library_missing() { + use std::os::unix::fs::PermissionsExt; + /// Gives the folder its permissions back and removes the test's folder, also when an assertion + /// fails (a folder left at mode 000 can't be removed). + struct Cleanup(std::path::PathBuf, std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = std::fs::set_permissions(&self.1, std::fs::Permissions::from_mode(0o755)); + let _ = std::fs::remove_dir_all(&self.0); + } + } + let dir = temp("lookup"); + let locked = dir.join("Locked"); + let _cleanup = Cleanup(dir.clone(), locked.clone()); + let inside = make_library(&locked.join("Inside")); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + if std::fs::read_dir(&locked).is_ok() { + // running as root (some CI containers): the mode bits don't stop it, so no lookup fails + lightcraft_testkit::skip!(System, "a folder with no permissions can still be read (running as root)"); + return; + } + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.settings.recent_libraries = vec![inside.clone(), gone.clone()]; + let mut h = Headless::new(app, [900.0, 600.0], 1.0); + let answered = h.step_until(T, |h| h.app.recent_checks.is_known(&inside) && h.app.recent_checks.is_known(&gone)); + assert!(answered); + assert_eq!(h.app.recent_checks.exists(&gone), Some(false), "a library that isn't there is missing"); + assert_eq!(h.app.recent_checks.exists(&inside), None, "one that couldn't be looked at isn't"); + let why = h.app.recent_checks.reason(&inside).map(|w| w.text()).unwrap_or_default(); + assert!(why.starts_with("This library couldn't be checked:"), "{why}"); + // nor is a folder that is there but refuses to be listed (permissions, macOS privacy) + use crate::panels::library_problem::Unavailable; + assert!(!Unavailable::Unreadable("denied".into()).is_missing() && !Unavailable::LookupFailed("timed out".into()).is_missing()); + assert!(Unavailable::NotFound.is_missing()); + drop(h); +} + +/// A library found is asked about again when the window comes back to the front, not on a timer: a +/// timer would wake every external drive and network share in the list over and over. One not +/// found is looked for again on its own (a drive plugged back in with the app in front). +#[test] +fn recent_libraries_are_checked_again_only_when_the_window_comes_back() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let dir = temp("recheck"); + let a = make_library(&dir.join("A")); + let gone = dir.join("Gone").to_string_lossy().into_owned(); + let (calls, gone_calls) = (std::sync::Arc::new(AtomicUsize::new(0)), std::sync::Arc::new(AtomicUsize::new(0))); + let (c, g, gone_path) = (calls.clone(), gone_calls.clone(), gone.clone()); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(move |p| { + if p == gone_path { + g.fetch_add(1, Ordering::SeqCst); + return Some(crate::panels::library_problem::Unavailable::NotFound); + } + c.fetch_add(1, Ordering::SeqCst); + None + }) + .recheck_after(Duration::ZERO); + app.ui.settings.recent_libraries = vec![a.clone(), gone.clone()]; + let mut h = Headless::new(app, [900.0, 600.0], 1.0); + assert!(h.step_until(T, |h| h.app.recent_checks.exists(&a) == Some(true))); + assert!(h.step_until(T, |_| gone_calls.load(Ordering::SeqCst) >= 3), "the one not found is looked for again on its own"); + // focused all along, every answer "old": nothing is asked again + for _ in 0..30 { + h.step(); + } + assert_eq!(calls.load(Ordering::SeqCst), 1, "no check on a timer"); + // the window went to the back and comes to the front again + h.app.recent_checks.focused = false; + assert!(h.step_until(T, |_| calls.load(Ordering::SeqCst) == 2), "asked again when the window comes back"); + for _ in 0..10 { + h.step(); + } + assert_eq!(calls.load(Ordering::SeqCst), 2, "once"); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library the launch list showed as not found comes back to it once found again (a drive plugged +/// back in while the list is up): the row waits for the new check instead of keeping its old answer +/// (FredApps on #2689, #2774). +#[test] +fn a_library_found_again_comes_back_to_the_launch_list() { + found_again(false); +} + +/// The same when every frame is laid out twice (`request_discard`): an answer applied in a frame is +/// visible through all of its passes, and scheduling does not ask about it again in that frame. +#[test] +fn a_library_found_again_comes_back_to_the_launch_list_across_a_multipass_frame() { + found_again(true); +} + +fn found_again(multipass: bool) { + use std::sync::atomic::{AtomicBool, Ordering}; + let dir = temp(if multipass { "found-again-multipass" } else { "found-again" }); + let a = make_library(&dir.join("A")); + let plugged = std::sync::Arc::new(AtomicBool::new(false)); + let p = plugged.clone(); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.recent_checks = crate::panels::library_problem::RecentChecks::with_check(move |_| { + (!p.load(Ordering::SeqCst)).then_some(crate::panels::library_problem::Unavailable::NotFound) + }) + .recheck_after(Duration::ZERO); + app.ui.settings.recent_libraries = vec![a.clone()]; + app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + if multipass { + // The existing context hook egui calls at the start of every pass: ask for the second layout + // pass on every pass 0 (which egui otherwise does only for e.g. a Grid sizing change). + h.view.ctx.on_begin_pass( + "test: force a second layout pass", + std::sync::Arc::new(|ui: &mut egui::Ui| { + if ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("test: force a second layout pass"); + } + }), + ); + let passes = h.view.ctx.cumulative_pass_nr(); + h.step(); + assert_eq!(h.view.ctx.cumulative_pass_nr() - passes, 2, "the hook forced the second pass"); + } + let row = |h: &Headless| h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).map(|c| c.libraries[0].clone()).unwrap(); + assert!( + h.step_until(T, |h| { + let r = row(h); + !r.checking && r.unavailable.is_some() + }), + "not found first" + ); + plugged.store(true, Ordering::SeqCst); + assert!( + h.step_until(T, |h| { + let r = row(h); + !r.checking && r.unavailable.is_none() + }), + "found again: it can be opened, {:?}", + row(&h) + ); + drop(h); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/tests_library_problem.rs b/crates/ui-egui/src/tests_library_problem.rs index 10783ff156..dc7a037a47 100644 --- a/crates/ui-egui/src/tests_library_problem.rs +++ b/crates/ui-egui/src/tests_library_problem.rs @@ -16,6 +16,63 @@ fn has(h: &Headless, id: &str) -> bool { h.app.widgets.iter().any(|(w, _)| w == id) } +/// A settings notice owns the frame: the launch list / library-error window is another +/// `Foreground` area and must not be drawn above the prompt or consume its keys. +#[test] +fn a_notice_prompt_hides_the_library_problem_window_and_takes_its_keys() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.app.library_problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + h.step(); + h.step(); + assert!(has(&h, "button:libraryRetry"), "the library problem window is shown without a prompt"); + h.app.notices.push("The settings file could not be read and was reset.".into()); + h.step(); + h.step(); + assert!(has(&h, "button:noticeOk"), "the settings notice is laid out"); + assert!(!has(&h, "button:libraryRetry"), "the library problem window is not drawn above the prompt"); + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.notices.is_empty(), "Escape safely dismissed the notice"); + assert!(!h.app.ui.quit, "the prompt's Escape did not reach the library window"); + assert!(has(&h, "button:libraryRetry"), "the library problem window returns after the prompt"); +} + +/// The launch list's own arrow/Return/Escape handling must stay still while a settings notice is +/// up. Use a real chooser: with the old error window this assertion could never reach +/// `chooser_keys` at all. +#[test] +fn a_notice_prompt_over_the_launch_list_takes_escape_without_quitting_it() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + app.ui.settings.recent_libraries = vec!["/no/such/library-one".into(), "/no/such/library-two".into()]; + app.ui.settings.library_path = "/no/such/library-one".into(); + app.library_problem = Some(LibraryProblem::choose(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + assert!(has(&h, "button:libraryOpen"), "the launch list is shown without a prompt"); + let selected = h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).map(|c| c.selected); + h.app.notices.push("The settings file could not be read and was reset.".into()); + h.step(); + h.step(); + assert!(has(&h, "button:noticeOk"), "the settings notice is laid out"); + assert!(!has(&h, "button:libraryOpen"), "the launch list is not drawn above the prompt"); + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert!(h.app.notices.is_empty(), "Escape safely dismissed the notice"); + assert!(!h.quit_requested(), "the prompt's Escape did not reach the launch list"); + assert!(h.app.library_problem.is_some(), "the launch list stays"); + assert_eq!( + h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).map(|c| c.selected), + selected, + "the prompt's Escape did not move the launch-list selection" + ); + assert!(has(&h, "button:libraryOpen"), "the launch list returns after the prompt"); +} + #[test] fn unopenable_library_asks_instead_of_running_a_demo() { let dir = std::env::temp_dir().join(format!("lc-ui-libproblem-{}", std::process::id())); @@ -101,3 +158,657 @@ fn unopenable_library_asks_instead_of_running_a_demo() { drop(h); let _ = std::fs::remove_dir_all(&dir); } + +/// Pressing the dim raises its egui area. The blocking window must be moved back above it, or its +/// own buttons are covered: the click then reports a no-op success and the state never changes. +#[test] +fn a_backdrop_press_keeps_the_library_window_above_its_dim() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1000.0, 760.0], 1.0); + h.app.library_problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + assert!(h.settle(Duration::from_secs(20)), "the library window settles"); + assert!(has(&h, "button:libraryTemporary"), "the window is laid out"); + // Outside the centred window: on the full-screen dim, which egui raises when pressed. + let at = egui::pos2(10.0, 10.0); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(at), press(true), press(false)]); + h.step(); + h.step(); + assert!(h.app.library_problem.as_ref().is_some_and(|p| !p.dismissed), "the backdrop itself chose nothing"); + let r = h.request("ui.clickWidget", json!({"id": "button:libraryTemporary"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!( + h.app.library_problem.as_ref().is_some_and(|p| p.dismissed), + "the window's own button made the actual state change after the backdrop press" + ); + assert!(!has(&h, "button:libraryRetry"), "Continue Without Saving removed the blocking window"); +} + +/// The library window is another foreground modal over Settings: its raw Escape and outside-click +/// handlers must stay still while it is on screen, then the dialog keeps its ordinary behaviour. +#[test] +fn the_library_window_blocks_settings_escape_and_the_backdrop() { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 900.0], + 1.0, + ); + h.step(); + assert!(h.app.run("app.settings", json!({})).is_ok(), "Settings opens"); + assert!(h.settle(Duration::from_secs(20)), "Settings settles"); + h.app.ui.settings.close_dialogs_outside = true; + h.app.library_problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + assert!(h.settle(Duration::from_secs(20)), "the library window settles"); + assert!(has(&h, "button:libraryRetry"), "the library window is laid out"); + // Escape belongs to the window, not to Settings behind it (the window has no Escape action + // for this error; the launch list handles its own keys separately). + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Escape closed Settings behind the library window"); + assert!(h.app.library_problem.is_some(), "the library window stayed"); + // The outside-click preference reads raw pointer events without asking the layer, so it must + // be gated too. The dim swallows the click itself. + let at = egui::pos2(10.0, 890.0); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(at), press(true), press(false)]); + h.step(); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "the backdrop click closed Settings behind the library window"); + // Positive control: with the library window gone, Settings' own Escape works again. + h.app.library_problem = None; + h.step(); + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_none(), "Escape closes Settings without the library window"); +} + +/// A dialog opened before the launch list (Settings) is not the list's own New Library prompt: +/// the list stays visible above it and keeps owning Escape, instead of vanishing and letting the +/// unrelated dialog's raw handlers run. +#[test] +fn an_unrelated_open_dialog_does_not_own_the_launch_list_or_its_barrier() { + let settings = crate::state::AppSettings { + recent_libraries: vec!["/no/such/library-one".into()], + library_path: "/no/such/library-one".into(), + ..Default::default() + }; + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 900.0], + 1.0, + ); + h.settle(T); + assert!(h.app.run("app.settings", json!({})).is_ok(), "Settings opens first"); + h.step(); + let mut problem = LibraryProblem::choose(&settings); + if let Some(c) = problem.chooser.as_mut() { + c.over = Some(h.app.session.library_generation()); + } + h.app.library_problem = Some(problem); + h.step(); + h.step(); + assert!(has(&h, "button:libraryOpen"), "the launch list stays above the unrelated Settings dialog"); + assert!(crate::panels::library_problem::blocks_dialog_input(&h.app), "the launch list owns input over an unrelated dialog"); + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.library_problem.is_none(), "the launch list's own Escape kept the open library"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Escape did not close Settings behind the launch list"); +} + +/// The launch list's own Escape is not a Settings raw handler: with no notice prompt blocking it, +/// it still quits from an empty list (the library chooser's long-standing behaviour). +#[test] +fn the_launch_list_still_quits_on_escape_without_a_notice() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + app.ui.settings.recent_libraries = vec!["/no/such/library-one".into(), "/no/such/library-two".into()]; + app.ui.settings.library_path = "/no/such/library-one".into(); + app.library_problem = Some(LibraryProblem::choose(&app.ui.settings)); + let mut h = Headless::new(app, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + assert!(has(&h, "button:libraryOpen"), "the launch list is shown without a prompt"); + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.quit_requested(), "the launch list's own Escape still quits when no notice blocks it"); +} + +/// A blocking library window created after `raw_input_hook` must not let the background text +/// field swallow the same frame's host text before the new modal area has settled. The same +/// sequence without the window is the positive control. +fn creation_frame_drops_background_text(problem: LibraryProblem, button: &str) { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 760.0], 1.0); + h.settle(T); + let r = h.request("ui.clickWidget", json!({"id": "field:search"}), T); + assert_eq!(r["ok"], true, "the search field takes focus: {r}"); + let r = h.request("ui.text", json!({"text": "base"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(h.app.ui.search, "base"); + + h.events.push(egui::Event::Text("leak".into())); + let mut problem = Some(problem); + h.set_after_raw_input_hook(move |app| app.library_problem = problem.take()); + h.step(); + assert_eq!(h.app.ui.search, "base", "the new library window's creation frame dropped the background text"); + assert!(!h.view.ctx.text_edit_focused(), "the background text field's focus was surrendered"); + h.step(); + assert!(has(&h, button), "the blocking window is laid out after its shield pass"); + + // Positive control: without the window, the same focused field receives text in one frame. + h.app.library_problem = None; + h.step(); + let r = h.request("ui.clickWidget", json!({"id": "field:search"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.events.push(egui::Event::Text("after".into())); + h.step(); + assert_eq!(h.app.ui.search, "baseafter", "ordinary background text input still works"); +} + +#[test] +fn library_error_and_chooser_creation_frames_drop_background_text() { + let settings = crate::state::AppSettings { + recent_libraries: vec!["/no/such/library-one".into()], + library_path: "/no/such/library-one".into(), + ..Default::default() + }; + creation_frame_drops_background_text(LibraryProblem::new("/no/such/library", "a test error"), "button:libraryRetry"); + creation_frame_drops_background_text(LibraryProblem::choose(&settings), "button:libraryOpen"); +} + +/// The library barrier removes events that `raw_input_hook` already injected. Like the prompt +/// barrier, it must fail the owning gesture; otherwise `ui.text`, `ui.hoverWidget` and synthetic +/// paste can report `ok: true` for input no panel ever saw. The window is created after the hook, +/// exactly as `alt_at_launch` or a command drawn late in the frame can do. +fn creation_after_raw_input_cancels_injected_text(problem: LibraryProblem) { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + let (tx, rx) = std::sync::mpsc::channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.text".into(), json!({"text": "leak"}), tx).expect("the text gesture is admitted"); + h.step(); // resolve: one Text event is queued + assert_eq!(h.app.synthetic.len(), 1, "the text gesture is ready to inject"); + let mut problem = Some(problem); + h.set_after_raw_input_hook(move |app| app.library_problem = problem.take()); + h.step(); // raw hook injects; the hook creates the window; the barrier drops the batch + let reply = rx.try_recv().expect("the dropped gesture answers"); + assert_eq!(reply["ok"], false, "the library barrier must not report a false success: {reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("blocking library window"), "{reply}"); + assert!(h.app.synthetic.is_empty(), "the dropped text batch left nothing queued"); + assert!(h.app.pending_gestures.is_empty(), "the dropped gesture was canceled, not kept"); +} + +#[test] +fn library_error_and_chooser_creation_after_raw_input_cancel_an_injected_gesture() { + let settings = crate::state::AppSettings { + recent_libraries: vec!["/no/such/library-one".into()], + library_path: "/no/such/library-one".into(), + ..Default::default() + }; + creation_after_raw_input_cancels_injected_text(LibraryProblem::new("/no/such/library", "a test error")); + creation_after_raw_input_cancels_injected_text(LibraryProblem::choose(&settings)); +} + +/// `alt_at_launch` creates the chooser from `logic`, after `raw_input_hook` injected this frame's +/// synthetic batch. That later creation path must cancel the dropped gesture too. +#[test] +fn alt_launch_creation_after_raw_input_cancels_an_injected_gesture() { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + let (tx, rx) = std::sync::mpsc::channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.text".into(), json!({"text": "leak"}), tx).expect("the text gesture is admitted"); + h.step(); + assert_eq!(h.app.synthetic.len(), 1); + h.app.alt_asks_for_library = true; + h.time = 0.1; // stay inside the Alt-at-launch watch window regardless of settle time + h.events.push(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.step(); // raw hook injects Text, then alt_at_launch creates the chooser and its barrier drops it + assert!(h.app.library_problem.as_ref().and_then(|p| p.chooser.as_ref()).is_some(), "Alt at launch opened the chooser"); + let reply = rx.try_recv().expect("the dropped gesture answers"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("blocking library window"), "{reply}"); + assert!(h.app.synthetic.is_empty() && h.app.pending_gestures.is_empty()); +} + +/// A held host press over a background control in the same frame as a library window created +/// after `raw_input_hook` is released by the window's first pass; its later release must not +/// become a background click. +#[test] +fn a_held_background_press_is_released_when_a_library_window_appears_after_raw_input() { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 900.0], + 1.0, + ); + h.step(); + assert!(h.app.run("app.settings", json!({})).is_ok(), "Settings opens"); + assert!(h.settle(T), "Settings settles"); + let id = "check:settings.confirmDelete"; + let at = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| rect.center()).expect("the checkbox is on screen"); + let before = h.app.ui.settings.confirm_delete; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(at), press(true)]); + h.set_after_raw_input_hook(|app| app.library_problem = Some(LibraryProblem::new("/no/such/library", "a test error"))); + h.step(); + assert!(h.app.library_problem.is_some(), "the library window is shown"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the creation pass released the held press"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the press did not reach Settings"); + h.events.push(press(false)); + h.step(); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the release did not become a background click"); + assert!(h.app.library_problem.is_some(), "the release did not activate the background control"); +} + +/// A library window first seen after `raw_input_hook` drops wheel, key and background pointer +/// input already accepted for the pass. Observed on egui's actual input state, not on the event +/// list the barrier edits. +#[test] +fn a_library_window_first_seen_after_begin_pass_drops_background_input() { + let mut h = + Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), [800.0, 600.0], 1.0); + h.settle(T); + let _ = pass_log(&mut h); + let at = egui::pos2(30.0, 40.0); + h.events.extend([ + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, 2.0), + phase: egui::TouchPhase::Start, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }, + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + egui::Event::ModifiersChanged(egui::Modifiers::NONE), + ]); + let mut problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + h.set_after_raw_input_hook(move |app| app.library_problem = problem.take()); + h.step(); + assert!(h.app.library_problem.is_some(), "the window was created after this pass's raw input"); + let (down, keys, scroll) = h.view.ctx.input(|i| (i.pointer.any_down(), i.keys_down.clone(), i.smooth_scroll_delta)); + assert!(!down, "the held background pointer press was released"); + assert!(keys.is_empty(), "the background key press was dropped: {keys:?}"); + assert_eq!(scroll, egui::Vec2::ZERO, "wheel scrolling was cleared"); + assert!(!h.view.ctx.input(|i| i.key_pressed(egui::Key::A)), "the dropped key press is not reported to panels"); + // The creation frame is a dedicated shield pass that egui discards, then the background pass. + assert_eq!( + pass_log(&mut h), + vec![crate::panels::library_problem::LibraryPass::Shield, crate::panels::library_problem::LibraryPass::Background], + "the creation frame draws only the window and is discarded before the background pass" + ); +} + +/// A Touch Start in one pass and its End/Cancel in a pass where a library window appears after +/// `raw_input_hook` must leave egui's own touch state empty: `begin_pass` processes the release +/// before the barrier filters the events. Asserting that the End/Cancel events merely survive the +/// filter would not prove the private touch state this protects. +fn touch_release_clears_egui_touch_state_when_the_library_window_appears_after_begin_pass(phase: egui::TouchPhase) { + let mut h = + Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), [800.0, 600.0], 1.0); + h.settle(T); + let at = egui::pos2(30.0, 40.0); + let touch = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: at, force: None }; + h.events.push(touch(egui::TouchPhase::Start)); + h.step(); + assert!(h.view.ctx.input(|i| i.any_touches()), "the touch is down before the window appears"); + let mut problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + h.set_after_raw_input_hook(move |app| app.library_problem = problem.take()); + h.events.push(touch(phase)); + h.step(); + assert!(h.app.library_problem.is_some(), "the window was created after this pass's raw input"); + assert!(!h.view.ctx.input(|i| i.any_touches()), "{phase:?} must clear egui's own touch state, not only stay in the filtered event batch"); +} + +#[test] +fn touch_end_and_cancel_clear_egui_touch_state_when_the_library_window_appears_after_begin_pass() { + touch_release_clears_egui_touch_state_when_the_library_window_appears_after_begin_pass(egui::TouchPhase::End); + touch_release_clears_egui_touch_state_when_the_library_window_appears_after_begin_pass(egui::TouchPhase::Cancel); +} + +fn select_first_photo(h: &mut Headless) -> lightcraft_catalog::PhotoId { + let photo = h.app.session.visible_cloned()[0]; + let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [photo.0]}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + photo +} + +fn press_rating(h: &mut Headless, key: egui::Key) { + for pressed in [true, false] { + h.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }); + } +} + +fn rating(h: &Headless, photo: lightcraft_catalog::PhotoId) -> u8 { + h.app.session.catalog.photo(photo).expect("the selected photo").rating +} + +/// Take the recorded library-barrier passes (clearing them). A shielded return frame must be +/// visible here even while the global shortcut guard would also keep the rating shortcut from +/// acting: the sequence itself is what these regressions protect. +fn pass_log(h: &mut Headless) -> Vec<crate::panels::library_problem::LibraryPass> { + std::mem::take(&mut h.app.library_passes) +} + +/// The frame that just ran returned from a hidden/unsettled blocking window: it must first be a +/// dedicated shield pass that is discarded, then a background pass. The next frame must be +/// ordinary (no repeated transition). Removing the shield pass, its discard or its settlement +/// changes this sequence; the rating shortcut alone would still stay blocked. +fn assert_shielded_return(h: &mut Headless, what: &str) { + use crate::panels::library_problem::LibraryPass; + assert_eq!( + pass_log(h), + vec![LibraryPass::Shield, LibraryPass::Background], + "{what}: the return frame must shield (and discard) the window's first pass, then draw the background" + ); + h.step(); + assert_eq!(pass_log(h), vec![LibraryPass::Background], "{what}: once settled, later frames draw normally without re-shielding"); +} + +/// A notice dismissed after the error window was already settled must shield the first frame that +/// draws the window again. A background rating shortcut injected on that frame would otherwise act +/// through the still-focused/background state while egui's hit test uses the previous pass. +#[test] +fn a_notice_dismissal_shields_the_library_windows_first_return_frame() { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + let photo = select_first_photo(&mut h); + let before = rating(&h, photo); + h.app.library_problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + h.step(); + h.step(); + assert!(has(&h, "button:libraryRetry"), "the error window is settled"); + h.app.notices.push("The settings file could not be read and was reset.".into()); + h.step(); + h.step(); + assert!(has(&h, "button:noticeOk") && !has(&h, "button:libraryRetry"), "the notice hides the settling window"); + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); + assert!(h.app.notices.is_empty(), "Escape dismissed the notice"); + // The dismissal happened during the draw; this clears that frame's background-only record. + let _ = pass_log(&mut h); + // This is the first frame in which the window is drawn again. The shortcut must be dropped. + press_rating(&mut h, egui::Key::Num5); + h.step(); + assert_eq!(rating(&h, photo), before, "the first return frame did not let a shortcut act behind the library window"); + assert_shielded_return(&mut h, "notice dismissal"); + assert!(has(&h, "button:libraryRetry"), "the window is back"); + // A settled blocking window keeps owning the keyboard: shortcuts stay blocked on later frames. + press_rating(&mut h, egui::Key::Num5); + h.step(); + h.step(); + assert_eq!(rating(&h, photo), before, "a settled library window did not block a background rating shortcut"); + // Positive control: once the blocking window is dismissed, the same shortcut works. + h.app.library_problem = None; + h.step(); + press_rating(&mut h, egui::Key::Num5); + h.step(); + h.step(); + assert_eq!(rating(&h, photo), 5, "ordinary shortcuts work once the blocking window is gone"); +} + +/// A library window created while a notice is up has never drawn its own shielded pass. Dismissing +/// the notice must not settle it from a frame where it was hidden by the prompt. +#[test] +fn a_library_window_created_under_a_notice_shields_the_first_frame_after_dismissal() { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + let photo = select_first_photo(&mut h); + let before = rating(&h, photo); + h.app.notices.push("The settings file could not be read and was reset.".into()); + h.step(); + h.step(); + assert!(has(&h, "button:noticeOk")); + let mut problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + h.set_after_raw_input_hook(move |app| app.library_problem = problem.take()); + h.step(); + assert!(has(&h, "button:noticeOk") && !has(&h, "button:libraryRetry"), "the prompt still owns the frame"); + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); + assert!(h.app.notices.is_empty()); + let _ = pass_log(&mut h); + press_rating(&mut h, egui::Key::Num5); + h.step(); + assert_eq!(rating(&h, photo), before, "the first frame after dismissal was shielded"); + assert_shielded_return(&mut h, "window created under a notice"); + assert!(has(&h, "button:libraryRetry"), "the window is drawn after its shield pass"); +} + +/// Closing New Library's own name dialog returns the launch list. The list was hidden for the +/// dialog, so the first pass that draws it again must be shielded rather than settling from the +/// dialog-closing pass. +#[test] +fn closing_the_new_library_dialog_shields_the_launch_lists_first_return_frame() { + let settings = crate::state::AppSettings { + recent_libraries: vec!["/no/such/library-one".into()], + library_path: "/no/such/library-one".into(), + ..Default::default() + }; + let mut h = Headless::new( + LightcraftApp::new( + lightcraft_engine::Session::with_demo(), + Services { png: None, pick_folder: Some(Box::new(|| -> Option<String> { None })), ..Default::default() }, + ), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + let photo = select_first_photo(&mut h); + let before = rating(&h, photo); + h.app.library_problem = Some(LibraryProblem::choose(&settings)); + h.settle(T); + assert!(has(&h, "button:libraryOpen"), "the launch list is settled"); + assert!(h.app.run("app.newLibrary", json!({})).is_ok(), "New Library opens its name prompt"); + h.step(); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::TextPrompt { .. })), "the name dialog is open"); + assert!(!has(&h, "button:libraryOpen"), "the launch list yields to the dialog it opened"); + let cancel = h + .app + .widgets + .iter() + .rev() + .find(|(id, _)| id == "button:dialogCancel") + .map(|(_, rect)| rect.center()) + .expect("the dialog's Cancel is on screen"); + let press = |pressed| egui::Event::PointerButton { pos: cancel, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(cancel), press(true), press(false)]); + h.step(); + assert!(h.app.ui.dialog.is_none(), "Cancel closed the New Library name dialog"); + // The dialog-closing frame drew the list but must not settle it. + let _ = pass_log(&mut h); + press_rating(&mut h, egui::Key::Num5); + h.step(); + assert_eq!(rating(&h, photo), before, "the launch list's first return frame is shielded"); + assert_shielded_return(&mut h, "New Library dialog cancel"); + assert!(has(&h, "button:libraryOpen"), "the launch list is back"); + // Positive control: dismissing the blocking window restores ordinary shortcuts. + h.app.library_problem = None; + h.step(); + press_rating(&mut h, egui::Key::Num5); + h.step(); + h.step(); + assert_eq!(rating(&h, photo), 5, "ordinary shortcuts work once the launch list is gone"); +} + +/// The banner's Open Library… reopens the window from inside the draw pass, after the background +/// panels already consumed this frame's input. The next frame must be the shielded first frame. +#[test] +fn the_banner_reopen_shields_the_first_input_frame() { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + let photo = select_first_photo(&mut h); + let before = rating(&h, photo); + h.app.library_problem = Some(LibraryProblem { dismissed: true, ..LibraryProblem::new("/no/such/library", "a test error") }); + h.step(); + h.step(); + assert!(has(&h, "indicator:temporarySession"), "the temporary-session banner is shown"); + let reopen = h + .app + .widgets + .iter() + .rev() + .find(|(id, _)| id == "button:libraryReopen") + .map(|(_, rect)| rect.center()) + .expect("the banner button is on screen"); + let press = |pressed| egui::Event::PointerButton { pos: reopen, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(reopen), press(true), press(false)]); + h.step(); + assert!(h.app.library_problem.as_ref().is_some_and(|p| !p.dismissed), "the banner reopened the window"); + assert!(has(&h, "button:libraryRetry")); + // The reopen happened late in that draw, after its own background pass began. + let _ = pass_log(&mut h); + press_rating(&mut h, egui::Key::Num5); + h.step(); + assert_eq!(rating(&h, photo), before, "input on the frame after a banner reopen was shielded"); + assert_shielded_return(&mut h, "banner reopen"); + assert!(has(&h, "button:libraryRetry"), "the window is back after its shield pass"); + // Positive control: dismissing the blocking window restores ordinary shortcuts. + h.app.library_problem = None; + h.step(); + press_rating(&mut h, egui::Key::Num5); + h.step(); + h.step(); + assert_eq!(rating(&h, photo), 5, "ordinary shortcuts work once the window is gone"); +} + +/// The chooser's own New Library text prompt is not a background barrier: `visible_mode` is None +/// while the dialog is open, so clipboard paste must reach that dialog's focused field. +#[test] +fn clipboard_pastes_into_the_launch_lists_own_text_prompt() { + let settings = crate::state::AppSettings { + recent_libraries: vec!["/no/such/library-one".into()], + library_path: "/no/such/library-one".into(), + ..Default::default() + }; + let mut h = Headless::new( + LightcraftApp::new( + lightcraft_engine::Session::with_demo(), + Services { png: None, pick_folder: Some(Box::new(|| -> Option<String> { None })), ..Default::default() }, + ), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + h.app.library_problem = Some(LibraryProblem::choose(&settings)); + h.settle(T); + assert!(h.app.run("app.newLibrary", json!({})).is_ok(), "New Library opens its name prompt"); + h.step(); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::TextPrompt { .. })), "the name dialog is open"); + assert!(!crate::panels::library_problem::blocks_dialog_input(&h.app), "a dialog opened by the launch list is not a background barrier"); + h.view.clipboard = "pasted-name".into(); + let r = h.request("ui.clipboard", json!({"action": "paste"}), T); + assert_eq!(r["ok"], true, "the chooser's own prompt accepts a paste: {r}"); + h.step(); + let Some(crate::state::Dialog::TextPrompt { value, .. }) = &h.app.ui.dialog else { + panic!("the name dialog closed unexpectedly"); + }; + assert!(value.contains("pasted-name"), "the paste reached the chooser's own text field: {value:?}"); +} + +/// The blocking library window owns input while it is on screen, including over an unrelated +/// dialog it did not open. Disabling only the dialog widgets that handle pointer input is not +/// enough: `dialog_field` must not take the focus back, or egui's text edit keeps consuming host +/// text into the draft behind the window. Several settled barrier frames must stay inert, and the +/// same field must accept typing again once the window is gone. +#[test] +fn a_settled_library_window_keeps_a_background_dialogs_text_draft_unchanged() { + let mut h = Headless::new( + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + h.app.ui.dialog = Some(crate::state::Dialog::NewAlbum { name: "Trip".into(), folder: false, parent: None, include_selected: false }); + for _ in 0..4 { + h.step(); + } + assert!(h.view.ctx.text_edit_focused(), "the dialog's field takes the focus while it is the top modal"); + h.app.library_problem = Some(LibraryProblem::new("/no/such/library", "a test error")); + assert!(h.settle(T), "the library window settles over the dialog"); + assert!(has(&h, "button:libraryRetry"), "the library window is laid out"); + assert!(crate::panels::library_problem::blocks_dialog_input(&h.app), "the library window owns input"); + assert!(!h.view.ctx.text_edit_focused(), "the background dialog's field must not regain the focus behind the library window"); + for text in ["leak", "ed", "-draft"] { + h.events.push(egui::Event::Text(text.into())); + h.step(); + let draft = match &h.app.ui.dialog { + Some(crate::state::Dialog::NewAlbum { name, .. }) => name.as_str(), + other => panic!("the background New Album dialog is still open: {other:?}"), + }; + assert_eq!(draft, "Trip", "host text on a settled library-barrier frame must not mutate the dialog draft"); + } + assert!(!h.view.ctx.text_edit_focused(), "several settled barrier frames still leave the field unfocused"); + // Positive control: with the library window gone, the same field takes focus and typing again. + h.app.library_problem = None; + assert!(h.settle(T), "the dialog settles once the library window is gone"); + assert!(!crate::panels::library_problem::blocks_dialog_input(&h.app), "there is no barrier now"); + assert!(h.view.ctx.text_edit_focused(), "the dialog's field is usable again"); + h.events.push(egui::Event::Text("Holiday".into())); + h.step(); + let draft = match &h.app.ui.dialog { + Some(crate::state::Dialog::NewAlbum { name, .. }) => name.as_str(), + other => panic!("the New Album dialog is still open: {other:?}"), + }; + assert_eq!(draft, "Holiday", "typing reaches the dialog once the library barrier is gone"); +} + +/// The launch list's own New Library name prompt is not a background dialog: `visible_mode` is +/// None while it is open, so the dialog must stay enabled and `dialog_field` must keep giving it +/// the focus and accept host text. +#[test] +fn typing_reaches_the_launch_lists_own_new_library_prompt() { + let settings = crate::state::AppSettings { + recent_libraries: vec!["/no/such/library-one".into()], + library_path: "/no/such/library-one".into(), + ..Default::default() + }; + let mut h = Headless::new( + LightcraftApp::new( + lightcraft_engine::Session::with_demo(), + Services { png: None, pick_folder: Some(Box::new(|| -> Option<String> { None })), ..Default::default() }, + ), + [1200.0, 760.0], + 1.0, + ); + h.settle(T); + h.app.library_problem = Some(LibraryProblem::choose(&settings)); + h.settle(T); + assert!(h.app.run("app.newLibrary", json!({})).is_ok(), "New Library opens its name prompt"); + h.step(); + h.step(); + assert!(!crate::panels::library_problem::blocks_dialog_input(&h.app), "the launch list's own prompt is not a background barrier"); + assert!(h.view.ctx.text_edit_focused(), "the prompt's name field has the focus"); + h.events.push(egui::Event::Text("Fresh".into())); + h.step(); + let Some(crate::state::Dialog::TextPrompt { value, command, .. }) = &h.app.ui.dialog else { + panic!("the New Library name dialog closed unexpectedly"); + }; + assert_eq!(command, "app.newLibrary"); + assert_eq!(value, "Fresh", "typing reaches the launch list's own text prompt"); +} diff --git a/crates/ui-egui/src/tests_lifecycle_037.rs b/crates/ui-egui/src/tests_lifecycle_037.rs new file mode 100644 index 0000000000..bfb08f1b49 --- /dev/null +++ b/crates/ui-egui/src/tests_lifecycle_037.rs @@ -0,0 +1,2226 @@ +//! 0.37 lifecycle regressions: the app clock, one-consumer queues, one pending synthetic batch, +//! parent-salted panel state, bundled monochrome emoji, and bounded/stale-safe screenshot capture. + +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use crate::headless::Headless; +use crate::render::{Slot, Tex}; +use crate::{ControlResponse, LightcraftApp, MAX_PENDING_SHOTS, MAX_SHOT_BYTES, PendingShot, Services, ShotGeometry}; +use lightcraft_engine::slideshow::Item; + +fn app() -> LightcraftApp { + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }) +} + +fn raw(size: egui::Vec2) -> egui::RawInput { + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() } +} + +fn key_event(key: egui::Key, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers } +} + +fn pointer_event(pos: egui::Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE } +} + +fn accesskit_action(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId) -> egui::Event { + egui::Event::AccessKitActionRequest(egui::accesskit::ActionRequest { + action, + target_tree: egui::accesskit::TreeId::ROOT, + target_node, + data: None, + }) +} + +fn viewport_raw(size: egui::Vec2, visible: bool) -> egui::RawInput { + let mut raw = raw(size); + raw.viewports.entry(egui::ViewportId::ROOT).or_default().minimized = Some(!visible); + raw.viewports.entry(egui::ViewportId::ROOT).or_default().occluded = Some(false); + raw +} + +fn reply_channel() -> (Sender<ControlResponse>, Receiver<ControlResponse>) { + channel() +} + +fn geometry(width: f32, height: f32) -> ShotGeometry { + ShotGeometry { viewport: egui::vec2(width, height), pixels_per_point: 1.0, zoom: 1.0, epoch: 0 } +} + +fn shot_bytes_for(width: usize, height: usize) -> usize { + width * height * std::mem::size_of::<egui::Color32>() +} + +/// One layout pass whose texture delta is consumed. 0.37's `TexturesDelta` panics when a non-empty +/// delta is dropped, so a test that only inspects input/state must still acknowledge the font atlas +/// the pass produced. `HeadlessView::run` does this with `TexturesDelta::apply`; a bare +/// `Context::run_ui` has no renderer, so clearing the delta is the explicit handling. +fn frame(ctx: &egui::Context, raw: egui::RawInput, ui: impl FnMut(&mut egui::Ui)) { + let mut output = ctx.run_ui(raw, ui); + output.textures_delta.clear(); +} + +/// An app whose screenshot encoder writes through the real file path and records the pixels it saw. +fn app_with_screenshot_files() -> (LightcraftApp, Arc<Mutex<Option<(usize, usize, Vec<u8>)>>>) { + let mut app = app(); + let seen = Arc::new(Mutex::new(None)); + let recorder = Arc::clone(&seen); + app.services.png = Some(Box::new(move |img: &lightcraft_raster::Rgba8| { + *recorder.lock().unwrap() = Some((img.width, img.height, img.as_bytes())); + vec![0x89, b'P', b'N', b'G'] + })); + app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.services.write_new = Some(Box::new(|path: &str, bytes: &[u8]| lightcraft_engine::export::write_file_new(path, bytes))); + (app, seen) +} + +fn temp_png(name: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!("lightcraft-{name}-{}.png", std::process::id())); + let _ = std::fs::remove_file(&path); + path +} + +/// Bind a pending request to the geometry/library generation a real issue would have used. +fn issue_into_slot(ctx: &egui::Context, shot: &mut PendingShot, issued: ShotGeometry, library: u64) -> egui::ScreenshotCallback { + let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES); + shot.slot = Some(slot); + shot.sent_at_ms = Some(0.0); + shot.issued = Some(issued); + shot.issued_library = library; + callback +} + +#[test] +fn bundled_faces_include_monochrome_emoji() { + // 0.37 moved the monochrome emoji faces behind `monochrome_emoji_fonts`, and `default_fonts` + // is no longer an egui default. Both come from the root `egui` features (kittest's own + // dev-dependencies do not propagate), so this test fails if either is lost. + let definitions = crate::theme::font_definitions(&[]); + for name in ["Hack", "Ubuntu-Light", "egui-icons", "NotoEmoji-Regular", "emoji-icon-font"] { + assert!(definitions.font_data.contains_key(name), "bundled face {name} is missing: {:?}", definitions.font_data.keys().collect::<Vec<_>>()); + } + let ctx = egui::Context::default(); + ctx.set_fonts(definitions); + // `Fonts` needs a first pass for its pixels-per-point before `fonts_mut` may inspect glyphs. + frame(&ctx, raw(egui::vec2(240.0, 120.0)), |ui| { + // U+1F600 and U+1F44D are in the bundled font cmaps. The older bundled subset + // does not contain U+1F642, so it cannot serve as a feature-wiring oracle. + ui.label("😀👍"); + }); + let font = egui::FontId::proportional(16.0); + assert!(ctx.fonts_mut(|f| f.has_glyph(&font, '\u{1F600}')), "😀 must be paintable from the bundled faces"); + assert!(ctx.fonts_mut(|f| f.has_glyph(&font, '\u{1F44D}')), "👍 must be paintable from the bundled faces"); +} + +#[test] +fn resizable_side_stores_panel_state_under_the_parent_salted_key() { + let ctx = egui::Context::default(); + let raw = raw(egui::vec2(1000.0, 700.0)); + frame(&ctx, raw, |ui| { + crate::panels::resizable_side(ui, true, "side-test", egui::Frame::NONE, 260.0, crate::state::LEFT_WIDTH, 300.0, |ui| { + ui.label("side"); + }); + }); + let modern = ctx.viewport_id().root_ui_id().with("side-test"); + assert!( + egui::containers::panel::PanelState::load(&ctx, modern).is_some(), + "0.37 stores panel state under parent_ui.scope_id().with_salt(id_salt)" + ); + assert!( + egui::containers::panel::PanelState::load(&ctx, egui::Id::unique("side-test")).is_none(), + "an already-built Id must not be salted a second time (the 0.36 exact-Id key)" + ); +} + +#[test] +fn legacy_panel_state_is_dropped_once_and_modern_keys_survive() { + let (ctx, mut app) = (egui::Context::default(), app()); + let state = || egui::containers::panel::PanelState { outer_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(10.0, 10.0)) }; + let modern = ctx.viewport_id().root_ui_id(); + let salts = ["top_bar", "bottom_bar", "tool_strip", "library-problem-banner"]; + for salt in salts { + let legacy = egui::Id::unique(salt); + ctx.data_mut(|d| d.insert_persisted(legacy, state())); + ctx.data_mut(|d| d.insert_persisted(modern.with(salt), state())); + } + frame(&ctx, raw(egui::vec2(800.0, 600.0)), |_| {}); + app.logic(&ctx); + for salt in salts { + let legacy = egui::Id::unique(salt); + assert!(egui::containers::panel::PanelState::load(&ctx, legacy).is_none(), "the dead 0.36 key for {salt} is removed"); + assert!(egui::containers::panel::PanelState::load(&ctx, modern.with(salt)).is_some(), "the 0.37 parent-salted key for {salt} is not touched"); + } +} + +#[test] +fn capture_admission_bounds_count_and_bytes_before_issue() { + let (ctx, mut app) = (egui::Context::default(), app()); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + for _ in 0..MAX_PENDING_SHOTS { + let (tx, _rx) = reply_channel(); + app.admit_shot(&ctx, None, false, tx).expect("admission within all limits"); + } + let per_image = shot_bytes_for(100, 100); + assert_eq!(app.shot_bytes, MAX_PENDING_SHOTS * per_image); + let (tx, _rx) = reply_channel(); + assert!(app.admit_shot(&ctx, None, false, tx).is_err(), "a fifth request is refused before issue"); + // The count gate runs before geometry admission. Free the four slots so the next check reaches + // the byte branch instead of answering the count error again. + app.pending_screenshots.clear(); + app.shot_bytes = 0; + + // An image over the per-image cap is refused, and nothing is reserved for it. The geometry is + // inside the texture limit (16 384 × 2 049), so this exercises the byte branch, not `pixels()`. + let before = app.shot_bytes; + app.last_shot_geometry = Some(geometry(16_384.0, 2_049.0)); + let (tx, _rx) = reply_channel(); + let error = app.admit_shot(&ctx, None, false, tx).expect_err("128 MiB + one row is over the per-image cap"); + assert!(error.contains("134283264"), "the error names the image size: {error}"); + assert!(error.contains("134217728"), "the error names the per-image cap: {error}"); + assert_eq!(app.shot_bytes, before, "a refused request reserves no bytes"); + + // Two 100 MB surfaces fit the 128 MiB per-image cap, but a third would exceed the 256 MiB + // aggregate budget (completed-but-undrained images stay counted). + let (ctx, mut app) = (egui::Context::default(), self::app()); + app.last_shot_geometry = Some(geometry(5000.0, 5000.0)); + for _ in 0..2 { + let (tx, _rx) = reply_channel(); + app.admit_shot(&ctx, None, false, tx).expect("100 MB is under the per-image cap"); + } + let (tx, _rx) = reply_channel(); + assert!(app.admit_shot(&ctx, None, false, tx).is_err(), "the aggregate budget bounds a third image"); + assert_eq!(app.shot_bytes, 200_000_000); +} + +#[test] +fn texture_limit_and_missing_surface_have_distinct_admission_errors() { + let (ctx, mut app) = (egui::Context::default(), app()); + app.max_texture_side = 1024; + app.last_shot_geometry = Some(geometry(1200.0, 100.0)); + let (tx, _rx) = reply_channel(); + let error = app.admit_shot(&ctx, None, false, tx).expect_err("wider than the host's texture limit"); + assert!(error.contains("1200×100") && error.contains("1024"), "the error names the surface and the host limit: {error}"); + assert_eq!(app.shot_bytes, 0); + + app.last_shot_geometry = Some(geometry(0.0, 0.0)); + let (tx, _rx) = reply_channel(); + let error = app.admit_shot(&ctx, None, false, tx).expect_err("no laid-out surface"); + assert!(error.contains("no usable surface size"), "the error names the missing layout, not the texture limit: {error}"); + assert_eq!(app.shot_bytes, 0); +} + +#[test] +fn stale_geometry_completion_is_rejected_before_any_write() { + let (ctx, mut app) = (egui::Context::default(), app()); + let path = temp_png("stale-shot"); + let (tx, rx) = reply_channel(); + let issued = ShotGeometry { epoch: 7, ..geometry(100.0, 100.0) }; + app.last_shot_geometry = Some(issued); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path"); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + let library = app.shot_document_generation(); + let callback = { + let shot = app.pending_screenshots.last_mut().expect("pending"); + issue_into_slot(&ctx, shot, ShotGeometry { epoch: 7, ..geometry(100.0, 100.0) }, library) + }; + callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE))); + // The window changed size while the callback was in flight: the image belongs to a stale + // generation and must be retried, never written. + app.last_shot_geometry = Some(ShotGeometry { epoch: 8, ..geometry(100.0, 100.0) }); + app.collect_screenshots(&ctx); + assert_eq!(app.pending_screenshots.len(), 1, "the request is retried"); + assert!(app.pending_screenshots[0].slot.is_none(), "the stale slot is dropped"); + assert!(!path.exists(), "a stale image is never written"); + assert!(rx.try_recv().is_err(), "a retry replies only when it succeeds or times out"); + assert_eq!(app.shot_bytes, shot_bytes_for(100, 100), "the reservation is kept for the retry"); +} + +#[test] +fn a_completed_capture_writes_once_and_releases_its_reservation() { + let (ctx, mut app, seen) = { + let (app, seen) = app_with_screenshot_files(); + (egui::Context::default(), app, seen) + }; + let path = temp_png("happy-shot"); + let (tx, rx) = reply_channel(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path"); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + let issued = geometry(100.0, 100.0); + let generation = app.shot_document_generation(); + let callback = { + let shot = app.pending_screenshots.last_mut().expect("pending"); + issue_into_slot(&ctx, shot, issued, generation) + }; + callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::from_rgb(1, 2, 3)))); + app.collect_screenshots(&ctx); + + let reply = rx.try_recv().expect("exactly one reply"); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["width"], 2); + assert_eq!(reply["result"]["height"], 2); + assert_eq!(std::fs::read(&path).expect("the file is written"), vec![0x89, b'P', b'N', b'G']); + let seen = seen.lock().unwrap().clone().expect("the encoder ran"); + assert_eq!((seen.0, seen.1), (2, 2)); + assert_eq!(seen.2, vec![1, 2, 3, 255, 1, 2, 3, 255, 1, 2, 3, 255, 1, 2, 3, 255]); + assert!(app.pending_screenshots.is_empty()); + assert_eq!(app.shot_bytes, 0, "success returns the reservation"); + assert!(rx.try_recv().is_err(), "one reply, not two"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn a_capture_completed_after_a_catalog_edit_is_still_written() { + // Catalog edits bump `catalog.revision` on every op; that is content, not document identity. + // Binding the capture to it retried once per edit and could only end in a timeout. + let (ctx, mut app, _seen) = { + let (app, seen) = app_with_screenshot_files(); + (egui::Context::default(), app, seen) + }; + let path = temp_png("edited-shot"); + let (tx, rx) = reply_channel(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path"); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + let generation = app.shot_document_generation(); + let issued = geometry(100.0, 100.0); + let callback = { + let shot = app.pending_screenshots.last_mut().expect("pending"); + issue_into_slot(&ctx, shot, issued, generation) + }; + app.session.catalog.revision = app.session.catalog.revision.wrapping_add(1); + assert_eq!(app.shot_document_generation(), generation, "an edit is not a new library"); + callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE))); + app.collect_screenshots(&ctx); + let reply = rx.try_recv().expect("one reply"); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(path.exists()); + assert_eq!(app.shot_bytes, 0); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn an_image_larger_than_its_reservation_is_grown_and_written() { + // Wayland has no `inner_rect`, so on a hidden tick the reservation can be based on the old + // content rect while the compositor returns the resized surface. A legal image is not an error. + let (ctx, mut app, _seen) = { + let (app, seen) = app_with_screenshot_files(); + (egui::Context::default(), app, seen) + }; + let path = temp_png("grown-shot"); + let (tx, rx) = reply_channel(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("pin the path"); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + let issued = geometry(100.0, 100.0); + let generation = app.shot_document_generation(); + let callback = { + let shot = app.pending_screenshots.last_mut().expect("pending"); + issue_into_slot(&ctx, shot, issued, generation) + }; + callback.complete(Arc::new(egui::ColorImage::filled([200, 200], egui::Color32::WHITE))); + app.collect_screenshots(&ctx); + let reply = rx.try_recv().expect("one reply"); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["width"], 200); + assert_eq!(app.shot_bytes, 0, "the grown reservation is released too"); + assert!(path.exists()); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn a_surface_that_grew_past_the_per_image_cap_is_refused_by_issue() { + let (ctx, mut app) = (egui::Context::default(), app()); + app.set_simulated_clock(Some(0.0)); + app.ui_passes = 3; + app.fonts_ready = true; + app.last_shot_geometry = Some(geometry(5000.0, 5000.0)); + let (tx, rx) = reply_channel(); + app.admit_shot(&ctx, None, false, tx).expect("100 MB is admitted"); + app.set_simulated_clock(Some(1.0)); + app.ui_passes = 6; + // The window grew after admission: 7000² × 4 = 196 MB, over the 128 MiB per-image cap. + app.last_shot_geometry = Some(geometry(7000.0, 7000.0)); + app.issue_screenshots(&ctx); + let reply = rx.try_recv().expect("the refusal is a reply"); + assert_eq!(reply["ok"], false, "{reply}"); + let error = reply["error"].as_str().unwrap_or_default(); + assert!(error.contains("196000000"), "the error names the new image, not the delta: {error}"); + assert!(error.contains("134217728"), "{error}"); + assert!(app.pending_screenshots.is_empty()); + assert_eq!(app.shot_bytes, 0); +} + +#[test] +fn timeout_replies_once_and_a_late_callback_is_inert() { + let (ctx, mut app) = (egui::Context::default(), app()); + app.set_simulated_clock(Some(0.0)); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let (tx, rx) = reply_channel(); + app.admit_shot(&ctx, None, false, tx).expect("admitted"); + let issued = geometry(100.0, 100.0); + let generation = app.shot_document_generation(); + let callback = { + let shot = app.pending_screenshots.last_mut().expect("pending"); + issue_into_slot(&ctx, shot, issued, generation) + }; + app.set_simulated_clock(Some(10.0)); + app.collect_screenshots(&ctx); + let reply = rx.try_recv().expect("the timeout reply"); + assert_eq!(reply["ok"], false); + assert!(reply["error"].as_str().unwrap_or_default().contains("timed out"), "{reply}"); + assert!(app.pending_screenshots.is_empty()); + assert_eq!(app.shot_bytes, 0, "a timed-out request returns its reservation"); + // The renderer may still deliver the cancelled one-shot: it finds no slot and changes nothing. + callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE))); + app.collect_screenshots(&ctx); + assert!(rx.try_recv().is_err(), "no second reply"); + assert_eq!(app.shot_bytes, 0); +} + +#[test] +fn a_busy_renderer_cannot_turn_a_settled_capture_into_a_timeout() { + let (tx, _rx) = reply_channel(); + let shot = PendingShot { + token: 1, + target: None, + reply: tx, + headless: false, + admitted_passes: 3, + not_before_ms: 120.0, + force_ms: 3000.0, + deadline_ms: 5120.0, + sent_at_ms: None, + reserved: 1, + slot: None, + issued: None, + issued_library: 0, + }; + assert!(!crate::shot_ready(100.0, &shot, false, 6), "settle time has not passed"); + assert!(crate::shot_ready(200.0, &shot, false, 6), "an idle renderer captures as soon as it is settled"); + assert!(!crate::shot_ready(200.0, &shot, true, 6), "a busy renderer still waits for the settle window"); + assert!(crate::shot_ready(3000.0, &shot, true, 6), "the forced instant captures the current frame anyway"); +} + +#[test] +fn a_silent_compositor_falls_back_to_the_headless_capture_once() { + let (ctx, mut app) = (egui::Context::default(), app()); + frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + app.set_simulated_clock(Some(0.0)); + app.last_shot_geometry = Some(geometry(160.0, 100.0)); + app.ui_passes = 6; + let (tx, rx) = reply_channel(); + app.admit_shot(&ctx, None, false, tx).expect("a windowed request is admitted"); + let issued = geometry(160.0, 100.0); + let generation = app.shot_document_generation(); + let callback = { + let shot = app.pending_screenshots.last_mut().expect("pending"); + issue_into_slot(&ctx, shot, issued, generation) + }; + app.ui_passes = 9; + // Two seconds after the command went out, no compositor frame has arrived. + app.set_simulated_clock(Some(2.5)); + app.issue_screenshots(&ctx); + let reply = rx.try_recv().expect("the fallback answers"); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(app.pending_screenshots.is_empty()); + assert_eq!(app.shot_bytes, 0); + // The canceled compositor callback may still fire; it must not produce a second reply. + callback.complete(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::WHITE))); + app.collect_screenshots(&ctx); + assert!(rx.try_recv().is_err(), "one reply from the fallback"); +} + +#[test] +fn a_busy_renderer_still_answers_a_headless_capture_at_the_forced_instant() { + let (ctx, mut app) = (egui::Context::default(), app()); + // Install fonts and reach the "ready" state a real host has after its setup frame. + frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready, "fonts are installed for the shadow frame"); + app.set_simulated_clock(Some(0.0)); + app.last_shot_geometry = Some(geometry(160.0, 100.0)); + app.ui_passes = 10; + let (tx, rx) = reply_channel(); + app.admit_shot(&ctx, None, true, tx).expect("a headless request is admitted"); + app.ui_passes = 13; + app.renderer.force_in_flight_for_test(1); + app.set_simulated_clock(Some(1.0)); + app.issue_screenshots(&ctx); + assert!(rx.try_recv().is_err(), "a busy renderer defers the capture before the forced instant"); + assert_eq!(app.pending_screenshots.len(), 1); + app.set_simulated_clock(Some(4.0)); + app.issue_screenshots(&ctx); + let reply = rx.try_recv().expect("the forced instant answers, it does not time out"); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(app.pending_screenshots.is_empty()); + assert_eq!(app.shot_bytes, 0, "the grown/shrunk reservation is released"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +struct TestDropped(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl egui::DroppedFile for TestDropped { + fn path(&self) -> &std::path::Path { + &self.0 + } + + fn bytes(&self) -> Result<Vec<u8>, String> { + Ok(vec![]) + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn one_synthetic_batch_until_a_completed_pass_and_drops_wait_for_the_ui_phase() { + let ctx = egui::Context::default(); + let mut app = app(); + app.fonts_ready = true; + app.synthetic.push(egui::Event::PointerMoved(egui::pos2(4.0, 4.0))); + let mut first = raw(egui::vec2(800.0, 600.0)); + app.raw_input_hook(&ctx, &mut first); + assert_eq!(first.events.len(), 1, "one pointer move is injected"); + assert!(app.synthetic_in_flight); + let mut second = raw(egui::vec2(800.0, 600.0)); + app.raw_input_hook(&ctx, &mut second); + assert!(second.events.is_empty(), "no second step while the first waits for a UI pass"); + + // Drops are queued by the hook even while a batch is in flight, but only the UI phase takes them. + second.dropped_files.push(Arc::new(TestDropped(std::env::temp_dir().join("lightcraft-drop.txt")))); + app.raw_input_hook(&ctx, &mut second); + assert_eq!(app.dropped_files.len(), 1); + frame(&ctx, raw(egui::vec2(800.0, 600.0)), |_| {}); + app.logic(&ctx); + app.logic(&ctx); + assert_eq!(app.dropped_files.len(), 1, "a hidden logic tick never replays the drop"); + assert_eq!(app.take_dropped_files().len(), 1, "the UI phase takes the queued drop exactly once"); + assert!(app.dropped_files.is_empty()); + + // A completed, nondiscarded app pass (not a bare `run_ui` closure) ends the in-flight batch, so + // the next host frame injects the next synthetic step. This fails if `finish_ui_pass` stops + // clearing the gate. + frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| app.ui(ui)); + assert!(!app.synthetic_in_flight, "a completed UI pass consumed the batch"); + app.synthetic.push(egui::Event::PointerMoved(egui::pos2(9.0, 9.0))); + let mut third = raw(egui::vec2(800.0, 600.0)); + app.raw_input_hook(&ctx, &mut third); + assert_eq!(third.events.len(), 1, "the next batch is injected after the completed pass"); +} + +#[test] +fn first_headless_frame_runs_logic_and_uses_its_simulated_clock() { + let mut h = Headless::new(app(), [800.0, 600.0], 1.0); + assert_eq!(h.time(), 0.0); + h.step(); + assert!(h.app.styled, "the first frame at t=0 runs logic and installs fonts"); + assert_eq!(h.app.tick_now(), 0.0, "the app clock follows the headless host's simulated time"); + h.step(); + h.step(); + assert!(h.app.fonts_ready, "fonts are ready after the setup pass"); + assert_eq!(h.app.ui_passes, 2, "exactly the two steps after the setup pass were laid out"); + assert!(h.app.tick_now() > 0.0, "the simulated clock advanced with the steps"); +} + +#[test] +fn import_ticks_once_per_host_frame_and_once_per_hidden_tick() { + let ctx = egui::Context::default(); + let seen = std::cell::RefCell::new(Vec::new()); + frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| { + seen.borrow_mut().push(crate::import_tick_allowed(ui.ctx())); + if seen.borrow().len() == 1 { + ui.ctx().request_discard("test: force a second layout pass"); + } + }); + assert_eq!(*seen.borrow(), vec![true, false], "the first pass commits import batches; the discarded re-run does not"); + + let hidden = viewport_raw(egui::vec2(800.0, 600.0), false); + let mut allowed = false; + let _ = ctx.run_logic(&hidden, |ctx| allowed = crate::import_tick_allowed(ctx)); + assert!(allowed, "a hidden logic tick reports pass index 0 and must still commit import batches"); +} + +#[test] +fn hidden_slideshow_pauses_and_keeps_its_remaining_time() { + let (ctx, mut app) = (egui::Context::default(), app()); + app.set_simulated_clock(Some(10.0)); + let started = crate::panels::slideshow::start( + &mut app, + &serde_json::json!({"slideDuration": 2.0, "fadeDuration": 0.0, "randomOrder": false, "repeat": false}), + 10.0, + ); + assert!(started.is_ok(), "the demo library has slides: {started:?}"); + // Every slide is "ready": without the hidden gate, 10 hidden seconds would advance the show. + for id in app.session.visible_cloned() { + let tex = ctx.load_texture(format!("slide-{}", id.0), egui::ColorImage::filled([2, 2], egui::Color32::WHITE), Default::default()); + app.renderer + .textures + .insert(Slot::Slide(Item::Photo(id)), Tex { key: 0, photo: id, tex, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }); + } + let first = app.ui.slideshow.as_ref().unwrap().play.current(); + let selection = app.session.active(); + app.set_simulated_clock(Some(10.5)); + let remaining = app.ui.slideshow.as_ref().unwrap().play.remaining(10.5); + assert!(remaining > 0.0); + let pending_before = app.renderer.pending_slots(); + + let hidden = viewport_raw(egui::vec2(800.0, 600.0), false); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + assert!(app.ui.slideshow.as_ref().unwrap().play.is_paused(), "hiding auto-pauses playback"); + app.set_simulated_clock(Some(20.0)); + let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx)); + { + let play = &app.ui.slideshow.as_ref().unwrap().play; + assert_eq!(play.current(), first, "a hidden slideshow does not advance"); + assert!((play.remaining(20.0) - remaining).abs() < 1e-6, "the slide keeps its remaining time while hidden"); + } + assert_eq!(app.session.active(), selection, "a hidden slideshow does not move the selection"); + assert_eq!(app.renderer.pending_slots(), pending_before, "a hidden slideshow requests no new slide renders"); + + let visible = viewport_raw(egui::vec2(800.0, 600.0), true); + app.set_simulated_clock(Some(20.0)); + let _ = ctx.run_logic(&visible, |ctx| app.logic(ctx)); + let play = &app.ui.slideshow.as_ref().unwrap().play; + assert!(!play.is_paused(), "showing the window resumes playback"); + assert_eq!(play.current(), first); + assert!((play.remaining(20.0) - remaining).abs() < 1e-6, "resuming does not skip the hidden minutes"); +} + +#[test] +fn text_field_inherits_ime_delete_surrounding_bytes_exactly() { + // The pinned 0.37 fork sends winit's incoming byte deletion as + // `ImeEvent::DeleteSurroundingBytes`; the app's `TextField` wraps the built-in `TextEdit`, + // so it must apply the range exactly (not extend it to a grapheme cluster). + let ctx = egui::Context::default(); + let id = crate::text_field::id("ime-bytes"); + let mut text = String::from("abc"); + let pass = |events: Vec<egui::Event>, text: &mut String| { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), events, ..Default::default() }; + frame(&ctx, raw, |ui| { + ui.memory_mut(|memory| memory.request_focus(id)); + let _ = crate::text_field::TextField::singleline("ime-bytes", text).show(ui); + }); + }; + pass(vec![], &mut text); + pass(vec![], &mut text); + let mut state = egui::text_edit::TextEditState::load(&ctx, id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(3)))); + state.store(&ctx, id); + pass(vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 0 })], &mut text); + assert_eq!(text, "a", "the reported UTF-8 range is deleted exactly"); + + // The same path must not split a multi-byte codepoint when the IME reports its whole width. + let mut text = String::from("aé🙂z"); + pass(vec![], &mut text); + pass(vec![], &mut text); + let mut state = egui::text_edit::TextEditState::load(&ctx, id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(3)))); // after 🙂 + state.store(&ctx, id); + pass(vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 4, after_bytes: 0 })], &mut text); + assert_eq!(text, "aéz", "the whole emoji is removed without touching the combining-free neighbours"); +} + +#[test] +fn text_field_ime_commit_replaces_the_selection() { + let ctx = egui::Context::default(); + let id = crate::text_field::id("ime-commit"); + let mut text = String::from("abc"); + let pass = |events: Vec<egui::Event>, text: &mut String| { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), events, ..Default::default() }; + frame(&ctx, raw, |ui| { + ui.memory_mut(|memory| memory.request_focus(id)); + let _ = crate::text_field::TextField::singleline("ime-commit", text).show(ui); + }); + }; + pass(vec![], &mut text); + pass(vec![], &mut text); + let mut state = egui::text_edit::TextEditState::load(&ctx, id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(2)))); + state.store(&ctx, id); + pass(vec![egui::Event::Ime(egui::ImeEvent::Commit("é".into()))], &mut text); + assert_eq!(text, "éc", "the committed text replaces the selected range once"); +} + +fn shot_dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-shot-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).expect("temp screenshot folder"); + d +} + +/// Complete one admitted capture whose slot is bound to the current geometry. +fn complete_admitted(ctx: &egui::Context, app: &mut LightcraftApp, image: egui::ColorImage) { + let generation = app.shot_document_generation(); + let issued = geometry(100.0, 100.0); + let callback = { + let shot = app.pending_screenshots.last_mut().expect("pending"); + issue_into_slot(ctx, shot, issued, generation) + }; + callback.complete(Arc::new(image)); + app.collect_screenshots(ctx); +} + +#[test] +fn a_new_file_at_an_absent_screenshot_path_survives() { + let dir = shot_dir("absent-race"); + let path = dir.join("shot.png"); + let (mut app, _seen) = app_with_screenshot_files(); + let ctx = egui::Context::default(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let (tx, rx) = reply_channel(); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("the path is free"); + assert!(target.was_absent()); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + // A photo (or any other file) appears at the path while the capture is queued. + std::fs::write(&path, b"new original").expect("created while queued"); + complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE)); + let reply = rx.try_recv().expect("one reply"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("appeared"), "{reply}"); + assert_eq!(std::fs::read(&path).expect("the new file is still there"), b"new original"); + assert_eq!(app.shot_bytes, 0, "the reservation is released on refusal"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_absent_screenshot_path_that_becomes_a_hard_link_to_an_original_survives() { + let dir = shot_dir("absent-original"); + let original = dir.join("IMG_1.jpg"); + let path = dir.join("shot.png"); + std::fs::write(&original, b"original").expect("original"); + let (mut app, _seen) = app_with_screenshot_files(); + let ctx = egui::Context::default(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let (tx, rx) = reply_channel(); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("the path is free"); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + std::fs::hard_link(&original, &path).expect("an imported hard link appears while queued"); + complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE)); + let reply = rx.try_recv().expect("one reply"); + assert_eq!(reply["ok"], false, "{reply}"); + assert_eq!(std::fs::read(&original).expect("original survives"), b"original"); + assert_eq!(std::fs::read(&path).expect("the link still names the original"), b"original"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_existing_allowed_screenshot_file_is_still_overwritten() { + let dir = shot_dir("existing-allowed"); + let path = dir.join("shot.png"); + std::fs::write(&path, b"old screenshot").expect("old file"); + let (mut app, _seen) = app_with_screenshot_files(); + let ctx = egui::Context::default(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let (tx, rx) = reply_channel(); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("ordinary existing file"); + assert!(!target.was_absent()); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE)); + let reply = rx.try_recv().expect("one reply"); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(std::fs::read(&path).expect("written"), vec![0x89, b'P', b'N', b'G']); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(unix)] +#[test] +fn a_screenshot_parent_retargeted_while_queued_is_not_written() { + use std::os::unix::fs::symlink; + + let dir = shot_dir("parent-retargeted"); + let admitted = dir.join("admitted"); + let unexpected = dir.join("unexpected"); + let link = dir.join("destination"); + std::fs::create_dir(&admitted).expect("admitted destination folder"); + std::fs::create_dir(&unexpected).expect("unexpected destination folder"); + symlink(&admitted, &link).expect("destination folder link"); + let path = link.join("shot.png"); + let (mut app, seen) = app_with_screenshot_files(); + let ctx = egui::Context::default(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let (tx, rx) = reply_channel(); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("free path through a folder link"); + assert!(target.was_absent()); + assert!(app.session.revalidate_write_target(&target).is_ok(), "an unchanged folder link is a valid destination"); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + + // The path's spelling is unchanged, but it now resolves to another folder while the real + // capture is pending. Re-checking only the saved resolved folder would allow this write. + std::fs::remove_file(&link).expect("unlink only the test folder link"); + symlink(&unexpected, &link).expect("retarget within the test temp folder"); + complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE)); + + let reply = rx.try_recv().expect("one reply"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("destination folder changed"), "{reply}"); + assert!(!admitted.join("shot.png").exists(), "the refused capture writes nothing to the admitted folder"); + assert!(!unexpected.join("shot.png").exists(), "the refused capture writes nothing to the retargeted folder"); + assert!(seen.lock().unwrap().is_none(), "a changed destination is refused before encoding"); + assert!(app.pending_screenshots.is_empty()); + assert_eq!(app.shot_bytes, 0, "the refused capture releases its reservation"); + assert!(rx.try_recv().is_err(), "the refused capture has exactly one reply"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(unix)] +#[test] +fn an_existing_screenshot_target_replaced_while_queued_is_not_overwritten() { + let dir = shot_dir("existing-replaced"); + let path = dir.join("shot.png"); + let keep = dir.join("keep.png"); + let other = dir.join("other.png"); + std::fs::write(&path, b"old screenshot").expect("old file"); + let (mut app, _seen) = app_with_screenshot_files(); + let ctx = egui::Context::default(); + app.last_shot_geometry = Some(geometry(100.0, 100.0)); + let (tx, rx) = reply_channel(); + let target = app.session.pin_write_target(&path.to_string_lossy()).expect("ordinary existing file"); + app.admit_shot(&ctx, Some(target), false, tx).expect("admitted"); + // Keep the admitted inode alive, then replace the directory entry with a different file. + std::fs::hard_link(&path, &keep).expect("keep the admitted inode"); + std::fs::write(&other, b"new file").expect("new file"); + std::fs::rename(&other, &path).expect("replace the entry"); + complete_admitted(&ctx, &mut app, egui::ColorImage::filled([2, 2], egui::Color32::WHITE)); + let reply = rx.try_recv().expect("one reply"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("changed"), "{reply}"); + assert_eq!(std::fs::read(&path).expect("the replacing file survives"), b"new file"); + assert_eq!(std::fs::read(&keep).expect("the admitted file survives"), b"old screenshot"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn ui_scroll_carries_validated_unit_phase_and_source() { + let (mut app, ctx) = (app(), egui::Context::default()); + let outcome = crate::control::gesture_events( + &mut app, + &ctx, + "ui.scroll", + &serde_json::json!({"source": "wheel", "unit": "line", "phase": "start", "dy": 1.0}), + ) + .expect("a wheel line step is valid"); + assert_eq!(outcome.result, serde_json::Value::Null); + assert!(outcome.target.is_none(), "scrolling has no widget target to revalidate"); + match app.synthetic.first().expect("one wheel event") { + egui::Event::MouseWheel { unit, phase, source, .. } => { + assert_eq!(*unit, egui::MouseWheelUnit::Line); + assert_eq!(*phase, egui::TouchPhase::Start); + assert_eq!(*source, egui::MouseWheelSource::Wheel); + } + other => panic!("expected a wheel event, got {other:?}"), + } + + app.synthetic.clear(); + crate::control::gesture_events( + &mut app, + &ctx, + "ui.scroll", + &serde_json::json!({"source": "trackpad", "unit": "point", "phase": "end", "dy": -12.0}), + ) + .expect("a trackpad end event is valid"); + match app.synthetic.first().expect("one wheel event") { + egui::Event::MouseWheel { unit, phase, source, .. } => { + assert_eq!(*unit, egui::MouseWheelUnit::Point); + assert_eq!(*phase, egui::TouchPhase::End); + assert_eq!(*source, egui::MouseWheelSource::Trackpad); + } + other => panic!("expected a wheel event, got {other:?}"), + } + + // Omitted keys keep the pre-0.37 request meaning. + app.synthetic.clear(); + crate::control::gesture_events(&mut app, &ctx, "ui.scroll", &serde_json::json!({"dy": 3.0})).expect("defaults are valid"); + match app.synthetic.first().expect("one wheel event") { + egui::Event::MouseWheel { unit, phase, source, .. } => { + assert_eq!(*unit, egui::MouseWheelUnit::Point); + assert_eq!(*phase, egui::TouchPhase::Move); + assert_eq!(*source, egui::MouseWheelSource::Unknown); + } + other => panic!("expected a wheel event, got {other:?}"), + } + + // An invalid value is an error and queues nothing. + app.synthetic.clear(); + let error = crate::control::gesture_events(&mut app, &ctx, "ui.scroll", &serde_json::json!({"unit": "notch"})).expect_err("unknown unit"); + assert!(error.contains("unit"), "{error}"); + assert!(app.synthetic.is_empty()); +} + +#[test] +fn synthetic_pointer_requests_bound_clicks_and_drag_steps() { + let (mut app, ctx) = (app(), egui::Context::default()); + app.widgets.push(("bounded:test".into(), egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(20.0, 20.0)))); + let max_clicks = crate::control::MAX_CLICKS; + let max_steps = crate::control::MAX_DRAG_STEPS; + + for (method, params) in [ + ("ui.clickWidget", serde_json::json!({"id": "bounded:test", "count": u64::MAX})), + ("ui.click", serde_json::json!({"x": 1.0, "y": 1.0, "count": u64::MAX})), + ] { + app.synthetic.clear(); + crate::control::gesture_events(&mut app, &ctx, method, &params).expect("a huge click count is bounded, not refused"); + assert_eq!(app.synthetic.len(), 1 + 2 * max_clicks as usize, "{method}: one move and two events per click"); + let presses = app.synthetic.iter().filter(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. })).count(); + assert_eq!(presses, max_clicks as usize, "{method}: the click count is capped"); + } + + for (method, params) in [ + ("ui.dragWidget", serde_json::json!({"id": "bounded:test", "toX": 50.0, "toY": 50.0, "steps": u64::MAX})), + ("ui.drag", serde_json::json!({"x": 1.0, "y": 1.0, "toX": 50.0, "toY": 50.0, "steps": u64::MAX})), + ] { + app.synthetic.clear(); + crate::control::gesture_events(&mut app, &ctx, method, &params).expect("a huge drag step count is bounded, not refused"); + assert_eq!(app.synthetic.len(), 3 + max_steps as usize, "{method}: press, release and the capped moves"); + let moves = app.synthetic.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(); + assert_eq!(moves, 1 + max_steps as usize, "{method}: the step count is capped"); + } +} + +#[test] +fn a_gesture_never_uses_the_previous_widget_registry() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + app.widgets.push(("stale:test".into(), egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(10.0, 10.0)))); + let (tx, rx) = reply_channel(); + app.admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "stale:test"}), tx).expect("admitted"); + assert!(rx.try_recv().is_err(), "nothing is answered at admission"); + // A completed pass replaces the registry; the stale id is not in the fresh one. + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + let reply = rx.try_recv().expect("the resolution error answers once"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("no widget"), "{reply}"); + assert!(app.pending_gestures.is_empty()); + assert!(app.synthetic.is_empty()); +} + +#[test] +fn a_gesture_cancels_when_the_view_changes_before_the_fresh_layout() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + let (tx, rx) = reply_channel(); + app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({"x": 10.0, "y": 10.0}), tx).expect("admitted"); + // the app opens in Detail, so a cancellation test must move to a genuinely different view + app.ui.view = crate::state::ViewMode::PhotoGrid; + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + let reply = rx.try_recv().expect("the cancel error answers once"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("canceled"), "{reply}"); + assert!(app.synthetic.is_empty()); +} + +#[test] +fn a_widget_gesture_cancels_if_its_target_moves_between_resolution_and_the_press() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + // Resolve a click against a completed layout at the widget's old place. + app.widgets.push(("moving:test".into(), egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(30.0, 20.0)))); + let (tx, rx) = reply_channel(); + app.admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "moving:test"}), tx).expect("admitted"); + app.layout_epoch = app.layout_epoch.wrapping_add(1); + app.resolve_pending_gestures(&ctx); + assert_eq!(app.synthetic.len(), 3, "move, press and release are queued"); + assert!(rx.try_recv().is_err(), "nothing is answered at resolution"); + // The first pass consumes the move; the pointer now rests at the resolved point. + let mut next = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut next); + assert!(next.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(p) if *p == egui::pos2(25.0, 20.0)))); + app.synthetic_in_flight = false; + // The next completed layout puts the widget somewhere else. egui would attribute the press + // in the following pass to whatever sits at the old coordinates; fail closed instead. + app.widgets = vec![("moving:test".into(), egui::Rect::from_min_size(egui::pos2(100.0, 10.0), egui::vec2(30.0, 20.0)))]; + let mut next = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut next); + assert!(next.events.is_empty(), "no press is delivered at the stale point"); + assert!(app.synthetic.is_empty(), "the rest of the canceled click is dropped"); + let reply = rx.try_recv().expect("the moved target answers once"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("moving:test"), "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("nothing was retargeted"), "{reply}"); + assert!(app.pending_gestures.is_empty()); +} + +#[test] +fn a_maximum_step_drag_is_delivered_past_the_five_second_stall_limit() { + let mut h = Headless::new(app(), [900.0, 650.0], 1.0); + h.step(); + h.step(); + assert!(h.app.fonts_ready); + // A capped drag is delivered one event per host frame. At 1/60 s each the whole gesture takes + // far longer than GESTURE_TIMEOUT_MS, so only a deadline refreshed by real progress lets it + // finish; the old absolute deadline failed it (and every queued gesture) halfway through. + let r = h.request( + "ui.drag", + serde_json::json!({ + "x": 30.0, + "y": 30.0, + "toX": 30.0, + "toY": 30.0, + "steps": crate::control::MAX_DRAG_STEPS, + }), + Duration::from_secs(90), + ); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.time() > 5.0, "the drag's simulated delivery outlived the old 5 s deadline: {}", h.time()); + assert!(h.app.pending_gestures.is_empty()); + assert!(h.app.synthetic.is_empty()); +} + +#[test] +fn a_click_on_a_control_under_a_nonmodal_overlay_is_refused_without_activating_the_overlay() { + let mut h = Headless::new(app(), [1400.0, 900.0], 1.0); + let photo = h.app.session.visible_cloned()[0]; + let t = Duration::from_secs(20); + assert_eq!(h.request("engine.execute", serde_json::json!({"command": "library.select", "params": {"ids": [photo.0]}}), t)["ok"], true); + assert_eq!(h.request("ui.set", serde_json::json!({"view": "detail", "right": "edit"}), t)["ok"], true); + h.app.ui.open_sections = vec!["light".to_string()]; + assert!(h.settle(Duration::from_secs(60)), "the edit panel settles"); + let id = "slider:light.exposure"; + assert!(h.app.widgets.iter().any(|(widget, _)| widget == id), "{id} is on screen"); + let before = h.app.session.develop_of(photo).expect("its develop settings").light.exposure; + // The quit prompt's Foreground dim and window own the pointer (and the notice barrier also + // covers the control channel's own hit check). The settings slider remains registered + // underneath it, and its rect still contains the press point. + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + assert!(h.app.widgets.iter().any(|(widget, _)| widget == "button:quitCancel"), "the overlay is shown"); + let r = h.request("ui.clickWidget", serde_json::json!({"id": id}), Duration::from_secs(20)); + assert_eq!(r["ok"], false, "{r}"); + let error = r["error"].as_str().unwrap_or_default(); + assert!(error.contains(id), "{r}"); + assert!(error.contains("no longer visible"), "{r}"); + assert!(error.contains("nothing was retargeted"), "{r}"); + assert!(h.app.quit_prompt.is_some(), "the click did not activate (or dismiss) the overlay"); + let r = h.request("ui.dragWidget", serde_json::json!({"id": id, "dx": 12.0, "steps": 4}), Duration::from_secs(20)); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap_or_default().contains("before its press"), "{r}"); + let after = h.app.session.develop_of(photo).expect("its develop settings").light.exposure; + assert_eq!(after, before, "the covered slider did not change"); + assert!(h.app.quit_prompt.is_some(), "the drag did not activate (or dismiss) the overlay"); + assert!(h.app.pending_gestures.is_empty()); + assert!(h.app.synthetic.is_empty()); +} + +/// The release ownership check must not reject an ordinary unobstructed click, including a click +/// on a sub-rect of a larger widget (the bottom rating row registers each star, not the row's +/// interactive centre). This is the positive control the hover-only probe lacked. +#[test] +fn an_unobstructed_click_on_a_subrect_reaches_the_widget() { + let mut h = Headless::new(app(), [1400.0, 900.0], 1.0); + let photo = h.app.session.visible_cloned()[0]; + let t = Duration::from_secs(20); + assert_eq!(h.request("engine.execute", serde_json::json!({"command": "library.select", "params": {"ids": [photo.0]}}), t)["ok"], true); + assert_eq!(h.request("ui.set", serde_json::json!({"view": "detail", "right": "edit"}), t)["ok"], true); + assert!(h.settle(Duration::from_secs(60)), "the detail view settles"); + let id = "star:bottom:2"; + assert!(h.app.widgets.iter().any(|(widget, _)| widget == id), "{id} is on screen"); + assert!(h.app.widget_hits.iter().any(|(widget, _)| widget == id), "{id} has a probe"); + let r = h.request("ui.clickWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_eq!(h.app.session.catalog.photo(photo).expect("the photo").rating, 2, "the sub-rect click reached the rating row"); +} + +/// A non-modal overlay that appears after the press must cancel the click before its release and +/// must not turn the release into an overlay click; the pointer is released away from the target. +#[test] +fn an_overlay_that_appears_after_the_press_cancels_the_release() { + let mut h = Headless::new(app(), [1000.0, 760.0], 1.0); + h.step(); + let t = Duration::from_secs(20); + assert_eq!(h.request("ui.key", serde_json::json!({"key": ",", "cmd": true}), t)["ok"], true); + assert!(h.settle(Duration::from_secs(60)), "the Settings dialog settles"); + let id = "check:settings.confirmDelete"; + let target = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect).expect("the checkbox is on screen"); + let before = h.app.ui.settings.confirm_delete; + let (tx, rx) = reply_channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.clickWidget".into(), serde_json::json!({"id": id}), tx).expect("the click is admitted"); + h.step(); // resolve: move, press and release are queued + h.step(); // the move is consumed + h.step(); // the press is consumed: the pointer is now down + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the press reached egui"); + // Let the prompt complete its sizing pass while the release waits, as it does when it opens + // between two host frames. A prompt now cancels the gesture at its appearance, before the + // release is delivered; the release must still end the held press without a click. + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.app.synthetic_in_flight = true; + h.step(); + assert!(!h.app.synthetic_in_flight, "the prompt's pass completed"); + assert!(h.app.widgets.iter().any(|(widget, _)| widget == "button:quitCancel"), "the prompt is laid out"); + h.step(); // the release is refused; the pointer cleanup releases the held press + let reply = rx.try_recv().expect("the canceled click answers"); + assert_eq!(reply["ok"], false, "{reply}"); + let error = reply["error"].as_str().unwrap_or_default(); + assert!(error.contains("modal prompt appeared"), "{reply}"); + assert!(error.contains("before its input was delivered"), "{reply}"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the canceled press was released"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the covered checkbox did not change"); + assert_eq!( + h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect), + Some(target), + "the target stayed where it was; nothing was retargeted" + ); + assert!(h.app.quit_prompt.is_some(), "the prompt was not activated"); + // Remove the overlay: the same target is clickable again (a positive control after refusal). + h.app.quit_prompt = None; + assert!(h.settle(Duration::from_secs(60)), "the Settings dialog settles after the overlay"); + let r = h.request("ui.clickWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_eq!(h.app.ui.settings.confirm_delete, !before, "the unobstructed click reached the checkbox"); +} + +/// A canceled click on a drag-sensing control must not keep the pointer down or move it. The old +/// cleanup moved 8 px to suppress the click, which could start a drag and change a slider/curve. +#[test] +fn canceling_a_pressed_slider_releases_it_without_dragging_it() { + let mut h = Headless::new(app(), [1400.0, 900.0], 1.0); + let photo = h.app.session.visible_cloned()[0]; + let t = Duration::from_secs(20); + assert_eq!(h.request("engine.execute", serde_json::json!({"command": "library.select", "params": {"ids": [photo.0]}}), t)["ok"], true); + assert_eq!(h.request("ui.set", serde_json::json!({"view": "detail", "right": "edit"}), t)["ok"], true); + h.app.ui.open_sections = vec!["light".to_string()]; + assert!(h.settle(Duration::from_secs(60)), "the edit panel settles"); + let id = "slider:light.exposure"; + let target = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect).expect("the slider is on screen"); + let before = h.app.session.develop_of(photo).expect("its develop settings").light.exposure; + let (tx, rx) = reply_channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.clickWidget".into(), serde_json::json!({"id": id}), tx).expect("the click is admitted"); + h.step(); // resolve: move, press and release are queued + h.step(); // the move is consumed + h.step(); // the press is consumed: the pointer is now down + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the press reached egui"); + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.app.synthetic_in_flight = true; + h.step(); // the prompt's pass completes while the release waits + assert!(!h.app.synthetic_in_flight); + h.step(); // the release is refused; cleanup resets the pointer before the next pass + let reply = rx.try_recv().expect("the canceled click answers"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("modal prompt appeared"), "{reply}"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the canceled press was released without a move"); + assert_eq!(h.app.session.develop_of(photo).expect("its develop settings").light.exposure, before, "cleanup did not drag the slider"); + assert_eq!( + h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect), + Some(target), + "the target stayed where it was; nothing was retargeted" + ); + assert!(h.app.quit_prompt.is_some(), "the prompt was not activated"); + assert!(h.app.pending_gestures.is_empty()); + assert!(h.app.synthetic.is_empty()); +} + +/// A non-prompt `Foreground` window that appears after the press (the launch list / library error) +/// makes the target invisible too: the release is refused rather than clicking through it. +#[test] +fn a_nonprompt_overlay_that_appears_after_the_press_cancels_the_release() { + let mut h = Headless::new(app(), [1000.0, 760.0], 1.0); + h.step(); + let t = Duration::from_secs(20); + assert_eq!(h.request("ui.key", serde_json::json!({"key": ",", "cmd": true}), t)["ok"], true); + assert!(h.settle(Duration::from_secs(60)), "the Settings dialog settles"); + let id = "check:settings.confirmDelete"; + let target = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect).expect("the checkbox is on screen"); + let before = h.app.ui.settings.confirm_delete; + let (tx, rx) = reply_channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.clickWidget".into(), serde_json::json!({"id": id}), tx).expect("the click is admitted"); + h.step(); // resolve: move, press and release are queued + h.step(); // the move is consumed + h.step(); // the press is consumed: the pointer is now down + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the press reached egui"); + // Draw the non-prompt overlay while the release waits. Its creation barrier cancels the + // queued release before the later stale-target visibility check can deliver it. + h.app.library_problem = Some(crate::panels::library_problem::LibraryProblem::new("/no/such/library", "test error")); + h.app.synthetic_in_flight = true; + h.step(); + assert!(!h.app.synthetic_in_flight, "the overlay's pass completed"); + assert!(h.app.widgets.iter().any(|(widget, _)| widget == "button:libraryRetry"), "the library window is laid out"); + h.step(); + let reply = rx.try_recv().expect("the canceled click answers"); + assert_eq!(reply["ok"], false, "{reply}"); + let error = reply["error"].as_str().unwrap_or_default(); + assert!(error.contains("ui.clickWidget canceled: a blocking library window appeared"), "{reply}"); + assert!(error.contains("before its input was delivered"), "{reply}"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the canceled press was released"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the covered checkbox did not change"); + assert_eq!( + h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect), + Some(target), + "the target stayed where it was; nothing was retargeted" + ); + assert!(h.app.library_problem.is_some(), "the overlay was not activated"); + h.app.library_problem = None; + assert!(h.settle(Duration::from_secs(60)), "Settings settles after the overlay"); + let r = h.request("ui.clickWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_eq!(h.app.ui.settings.confirm_delete, !before, "the unobstructed click reached the checkbox"); +} + +/// The library-problem dim is above a `Middle` Settings dialog: a control-channel click on the +/// covered checkbox is refused instead of being delivered through the dim. This is the direct +/// `ui.clickWidget` counterpart of the press/release cancellation above. +#[test] +fn a_library_problem_overlay_blocks_a_control_click_in_settings() { + let mut h = Headless::new(app(), [1000.0, 760.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + assert!(h.settle(Duration::from_secs(60)), "Settings settles"); + let id = "check:settings.confirmDelete"; + let before = h.app.ui.settings.confirm_delete; + h.app.library_problem = Some(crate::panels::library_problem::LibraryProblem::new("/no/such/library", "test error")); + assert!(h.settle(Duration::from_secs(60)), "the library problem window settles"); + assert!(h.app.widgets.iter().any(|(widget, _)| widget == "button:libraryRetry"), "the library window is laid out"); + let r = h.request("ui.clickWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], false, "{r}"); + let error = r["error"].as_str().unwrap_or_default(); + assert!(error.contains(id), "{r}"); + assert!(error.contains("no longer visible"), "{r}"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the covered checkbox did not change"); + assert!(h.app.library_problem.is_some(), "the overlay was not activated"); + // Positive control: the same control works once the covering window is gone. + h.app.library_problem = None; + assert!(h.settle(Duration::from_secs(60)), "Settings settles after the overlay"); + let r = h.request("ui.clickWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_eq!(h.app.ui.settings.confirm_delete, !before, "the unobstructed click reached the checkbox"); +} + +/// A quit prompt over Settings owns the pointer even when Settings asks for outside clicks: the +/// raw backdrop handler must not close the dialog it cannot see. Dismissing the prompt with its +/// own button keeps Settings and does not replay the backdrop press into it. +#[test] +fn a_quit_prompt_over_settings_blocks_the_outside_click_and_keeps_the_dialog() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Settings is open"); + h.app.ui.settings.close_dialogs_outside = true; + let confirm_delete = h.app.ui.settings.confirm_delete; + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + assert!(h.app.widgets.iter().any(|(id, _)| id == "button:quitCancel"), "the prompt is laid out"); + // The prompt's first completed frame is already the real, interactable layer: no sizing pass + // (which egui makes invisible and non-interactable) may leak a release into Settings below. + let cancel = h.app.widgets.iter().find(|(id, _)| id == "button:quitCancel").map(|(_, r)| r.center()).expect("the Cancel rect"); + assert!(h.view.ctx.layer_id_at(cancel) == crate::panels::notices::prompt_layer(&h.app), "the prompt owns its first settled button click"); + // Outside both the prompt and Settings, with the outside-click preference on. + let at = egui::pos2(10.0, 890.0); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(at), press(true), press(false)]); + h.step(); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "the backdrop click did not close Settings"); + assert!(h.app.quit_prompt.is_some(), "the backdrop click did not dismiss the prompt"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "the raw click did not reach a Settings control"); + // A backdrop press raises its area; the prompt must stay above it, and its Cancel must work. + let r = h.request("ui.clickWidget", serde_json::json!({"id": "button:quitCancel"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.quit_prompt.is_none(), "Cancel dismissed the prompt"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "dismissing the prompt kept Settings"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "the prompt click did not reach Settings"); +} + +/// Escape and Return are the prompt's safe Cancel, not Settings' dismissal/confirmation. The +/// dialog and its Settings stay exactly as they were, then keep their normal Escape afterwards. +#[test] +fn a_quit_prompt_takes_safe_keyboard_cancel_without_closing_settings() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Settings is open"); + let confirm_delete = h.app.ui.settings.confirm_delete; + for key in ["Escape", "Enter"] { + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + let r = h.request("ui.key", serde_json::json!({"key": key}), t); + assert_eq!(r["ok"], true, "{key}: {r}"); + assert!(h.app.quit_prompt.is_none(), "{key} safely dismissed the prompt"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "{key} did not close Settings behind the prompt"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "{key} did not change Settings"); + } + // Positive control: the dialog's own Escape still works once no prompt owns it. + let r = h.request("ui.key", serde_json::json!({"key": "Escape"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.ui.dialog.is_none(), "Escape closes Settings without a prompt"); +} + +/// The prompt's buttons are reachable with Tab/Shift+Tab and activate with Space. Focus is real +/// egui focus on the actual button responses, not a separate keyboard-only path. +#[test] +fn prompt_tab_shift_tab_and_space_reach_cancel() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + let confirm_delete = h.app.ui.settings.confirm_delete; + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + let cancel_id = + h.app.widget_hits.iter().rev().find(|(id, _)| id == "button:quitCancel").map(|(_, hit)| hit.id).expect("Cancel has a real response"); + let anyway_id = + h.app.widget_hits.iter().rev().find(|(id, _)| id == "button:quitAnyway").map(|(_, hit)| hit.id).expect("Quit Anyway has a real response"); + assert_eq!(h.view.ctx.memory(|m| m.focused()), Some(cancel_id), "the safe Cancel starts focused"); + assert_eq!(h.request("ui.key", serde_json::json!({"key": "Tab"}), t)["ok"], true); + assert_eq!(h.view.ctx.memory(|m| m.focused()), Some(anyway_id), "Tab moved to Quit Anyway"); + assert!(h.app.quit_prompt.is_some(), "Tab did not activate anything"); + assert_eq!(h.request("ui.key", serde_json::json!({"key": "Tab", "shift": true}), t)["ok"], true); + assert_eq!(h.view.ctx.memory(|m| m.focused()), Some(cancel_id), "Shift+Tab moved back to Cancel"); + assert_eq!(h.request("ui.key", serde_json::json!({"key": "Space"}), t)["ok"], true); + assert!(h.app.quit_prompt.is_none(), "Space activated the focused safe Cancel"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Cancel kept Settings"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "the prompt key did not reach Settings"); +} + +/// Raw screen coordinates at a settled prompt button still work. Pointer state is hidden from the +/// background during each pass, but the real press is preserved for the next frame's release. +#[test] +fn raw_pointer_at_a_settled_prompt_button_activates_it() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + let confirm_delete = h.app.ui.settings.confirm_delete; + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + let cancel = h.app.widgets.iter().rev().find(|(id, _)| id == "button:quitCancel").map(|(_, rect)| rect.center()).expect("the Cancel rect"); + h.events.extend([egui::Event::PointerMoved(cancel), pointer_event(cancel, true)]); + h.step(); + assert!(h.app.quit_prompt.is_some(), "the press alone does not dismiss the prompt"); + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the real press survives for its release"); + h.events.push(pointer_event(cancel, false)); + h.step(); + assert!(h.app.quit_prompt.is_none(), "the release activated the settled prompt button"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Cancel kept Settings"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "the raw click did not reach Settings"); +} + +/// AccessKit Focus and Click target the prompt's actual button node. An action at a covered +/// Settings control is dropped, so it can neither focus nor activate the background. +#[test] +fn prompt_accepts_targeted_accesskit_and_rejects_background_actions() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + let confirm_delete = h.app.ui.settings.confirm_delete; + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + let cancel_id = + h.app.widget_hits.iter().rev().find(|(id, _)| id == "button:quitCancel").map(|(_, hit)| hit.id).expect("Cancel has a real response"); + let checkbox_node = h + .app + .widget_hits + .iter() + .rev() + .find(|(id, _)| id == "check:settings.confirmDelete") + .map(|(_, hit)| hit.id.accesskit_id()) + .expect("the covered checkbox has a response"); + h.events.push(accesskit_action(egui::accesskit::Action::Click, checkbox_node)); + h.step(); + assert!(h.app.quit_prompt.is_some(), "a background AccessKit Click did not dismiss the prompt"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "a background AccessKit Click did not change Settings"); + h.events.push(accesskit_action(egui::accesskit::Action::Focus, cancel_id.accesskit_id())); + h.events.push(accesskit_action(egui::accesskit::Action::Click, cancel_id.accesskit_id())); + h.step(); + assert!(h.app.quit_prompt.is_none(), "the prompt's own AccessKit node activated Cancel"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "AccessKit Cancel kept Settings"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "the AccessKit action did not reach Settings"); + // The control still answers normally after the prompt is gone. + let r = h.request("ui.clickWidget", serde_json::json!({"id": "check:settings.confirmDelete"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_eq!(h.app.ui.settings.confirm_delete, !confirm_delete, "Settings is usable again"); +} + +/// A prompt created in the same host frame as a raw press/release must shield it. A press that +/// began before the prompt is released by the creation barrier, without becoming a background +/// click after the prompt settles. +#[test] +fn a_new_prompt_shields_raw_pointer_and_cancels_a_held_press() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + let id = "check:settings.confirmDelete"; + let at = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| rect.center()).expect("the checkbox is on screen"); + let before = h.app.ui.settings.confirm_delete; + // Press and release in the prompt's creation frame. + h.events.extend([egui::Event::PointerMoved(at), pointer_event(at, true), pointer_event(at, false)]); + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + assert!(h.app.quit_prompt.is_some(), "the raw click did not dismiss the prompt"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the creation-frame click did not reach Settings"); + // Dismiss that prompt, then start a press over Settings before a new prompt appears. + assert_eq!(h.request("ui.key", serde_json::json!({"key": "Escape"}), Duration::from_secs(20))["ok"], true); + h.step(); + h.events.extend([egui::Event::PointerMoved(at), pointer_event(at, true)]); + h.step(); + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the pre-prompt press reached egui"); + h.events.push(pointer_event(at, false)); + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the prompt creation cancelled the held press"); + assert!(h.app.quit_prompt.is_some(), "the pre-prompt release did not activate the prompt"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the press-before-prompt became a click in Settings"); +} + +/// A prompt can be created after `raw_input_hook`, when eframe's `logic` runs. The prompt barrier +/// must then drop wheel/new-touch/pointer input that egui already accepted for the pass, before +/// any panel reads it, while a touch End still clears egui's private touch state. +#[test] +fn a_prompt_first_seen_after_begin_pass_drops_wheel_touch_and_background_pointer_input() { + let ctx = egui::Context::default(); + let mut app = app(); + app.fonts_ready = true; + let at = egui::pos2(30.0, 40.0); + let mut input = raw(egui::vec2(800.0, 600.0)); + input.events = vec![ + key_event(egui::Key::A, true, egui::Modifiers::NONE), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, 2.0), + phase: egui::TouchPhase::Start, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }, + egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase: egui::TouchPhase::Start, pos: at, force: None }, + egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase: egui::TouchPhase::End, pos: at, force: None }, + egui::Event::PointerMoved(at), + pointer_event(at, true), + egui::Event::ModifiersChanged(egui::Modifiers::NONE), + ]; + let mut output = ctx.run_ui(input, |ui| { + app.quit_prompt = Some(crate::QuitPrompt::Tasks("tasks".into())); + assert!(crate::panels::notices::prepare_ui_pass(&mut app, ui.ctx()), "the prompt is first seen after begin_pass"); + let events = ui.ctx().input(|i| i.events.clone()); + assert!( + events.iter().all(|event| !matches!( + event, + egui::Event::Key { .. } + | egui::Event::Touch { phase: egui::TouchPhase::Start | egui::TouchPhase::Move, .. } + | egui::Event::MouseWheel { .. } + | egui::Event::PointerMoved(_) + | egui::Event::PointerButton { .. } + )), + "background input must not survive the prompt's creation pass: {events:?}" + ); + assert!( + events.iter().any(|event| matches!(event, egui::Event::Touch { phase: egui::TouchPhase::End, .. })), + "a touch End must still clear egui's private touch state: {events:?}" + ); + assert!(events.iter().any(|event| matches!(event, egui::Event::ModifiersChanged(_))), "modifier changes still reach egui"); + assert!(!ui.ctx().input(|i| i.pointer.any_down()), "the pointer is not left down"); + assert_eq!(ui.ctx().input(|i| i.smooth_scroll_delta), egui::Vec2::ZERO, "wheel scrolling is cleared"); + }); + output.textures_delta.clear(); +} + +/// A held host press in the same frame as a prompt created after `raw_input_hook` is released by +/// the prompt's first pass, not delivered to the covered control when the release arrives. +#[test] +fn a_prompt_created_after_raw_input_hook_shields_a_held_background_press() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + let id = "check:settings.confirmDelete"; + let at = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| rect.center()).expect("the checkbox is on screen"); + let before = h.app.ui.settings.confirm_delete; + h.events.extend([egui::Event::PointerMoved(at), pointer_event(at, true)]); + h.set_after_raw_input_hook(|app| app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into()))); + h.step(); + assert!(h.app.quit_prompt.is_some(), "the prompt is shown"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the creation pass released the held press"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the press did not reach Settings"); + h.events.push(pointer_event(at, false)); + h.step(); + assert!(h.app.quit_prompt.is_some(), "the release did not activate the prompt"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the release did not become a background click"); +} + +/// A synthetic press already delivered when `raw_input_hook` runs, then a prompt created by logic +/// before the UI pass: the whole in-flight batch was not seen by a panel and must fail, not report +/// success after the prompt filters it. +#[test] +fn a_synthetic_press_already_delivered_is_canceled_by_a_prompt_created_after_raw_input_hook() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + assert!(h.settle(Duration::from_secs(60)), "the Settings dialog settles before its target rect is captured"); + let id = "check:settings.confirmDelete"; + let target = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect).expect("the checkbox is on screen"); + let before = h.app.ui.settings.confirm_delete; + let (tx, rx) = reply_channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.clickWidget".into(), serde_json::json!({"id": id}), tx).expect("the click is admitted"); + h.step(); // resolve: move, press and release are queued + h.step(); // the move is consumed + h.step(); // the press is consumed: the pointer is now down + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the press reached egui"); + assert!(!h.app.synthetic.is_empty(), "the release is queued"); + h.set_after_raw_input_hook(|app| app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into()))); + h.step(); // the hook creates the prompt after the release was injected for this pass + let reply = rx.try_recv().expect("the canceled click answers"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("modal prompt appeared"), "{reply}"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the canceled press was released"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the filtered release did not reach Settings"); + assert_eq!( + h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| *rect), + Some(target), + "the target stayed where it was; nothing was retargeted" + ); + assert!(h.app.quit_prompt.is_some(), "the prompt was not activated"); + assert!(h.app.pending_gestures.is_empty()); + assert!(h.app.synthetic.is_empty()); +} + +/// Raw `ui.click`, `ui.drag` and `ui.pointer` at a settled prompt are delivered to the prompt's +/// backdrop, not to the covered Settings control or image. The dialog, its control and the image +/// stay unchanged. +#[test] +fn raw_background_gestures_at_a_settled_prompt_do_not_reach_the_covered_view() { + let mut h = Headless::new(app(), [1400.0, 900.0], 1.0); + let photo = h.app.session.visible_cloned()[0]; + let t = Duration::from_secs(20); + assert_eq!(h.request("engine.execute", serde_json::json!({"command": "library.select", "params": {"ids": [photo.0]}}), t)["ok"], true); + assert_eq!(h.request("ui.set", serde_json::json!({"view": "detail", "right": "edit"}), t)["ok"], true); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + assert!(h.settle(Duration::from_secs(60)), "the detail view and Settings settle"); + let image = h.app.image_rect.expect("the detail image is on screen"); + let at = image.min + egui::vec2(12.0, 12.0); + let before = h.app.ui.settings.confirm_delete; + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + h.step(); + assert!(h.app.widgets.iter().any(|(widget, _)| widget == "button:quitCancel"), "the prompt is settled"); + let click = h.request("ui.click", serde_json::json!({"x": at.x, "y": at.y}), t); + assert_eq!(click["ok"], true, "{click}"); + h.step(); + let drag = h.request("ui.drag", serde_json::json!({"x": at.x, "y": at.y, "toX": at.x + 30.0, "toY": at.y + 20.0, "steps": 4}), t); + assert_eq!(drag["ok"], true, "{drag}"); + h.step(); + let pointer = h.request( + "ui.pointer", + serde_json::json!({"events": [ + {"kind": "down", "x": 0.05, "y": 0.05}, + {"kind": "move", "x": 0.08, "y": 0.08}, + {"kind": "up", "x": 0.08, "y": 0.08} + ]}), + t, + ); + assert_eq!(pointer["ok"], true, "{pointer}"); + h.step(); + assert!(h.app.quit_prompt.is_some(), "the raw background gestures did not dismiss the prompt"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the raw gestures did not reach Settings"); + assert_eq!(h.app.image_rect, Some(image), "the raw pointer gestures did not pan, zoom or drag the image"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Settings is still open"); +} + +/// Releases are not keyboard actions, but egui needs them to clear `keys_down`. A prompt must keep +/// the release (and the held key must not survive the prompt) even though it drops every press. +#[test] +fn a_prompt_keeps_key_releases_and_clears_held_keys() { + let ctx = egui::Context::default(); + let mut app = app(); + app.fonts_ready = true; + app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + let mut raw = raw(egui::vec2(800.0, 600.0)); + raw.events.push(key_event(egui::Key::Backslash, false, egui::Modifiers::NONE)); + app.raw_input_hook(&ctx, &mut raw); + assert!( + raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Backslash, pressed: false, .. })), + "the prompt's raw filter kept the key release for keys_down" + ); + // A held background key is cleared at the prompt transition, not left asserted under it. + let mut h = Headless::new(app, [800.0, 600.0], 1.0); + h.step(); + h.view.ctx.input_mut(|i| { + i.keys_down.insert(egui::Key::Backslash); + }); + h.events.push(key_event(egui::Key::Backslash, false, egui::Modifiers::NONE)); + h.step(); + assert!(!h.view.ctx.input(|i| i.key_down(egui::Key::Backslash)), "the release cleared the held key under the prompt"); +} + +/// A synthetic drag whose press already reached egui is aborted when a prompt appears: its queued +/// moves/release are discarded, the pointer is released without a click, and the slider is intact. +#[test] +fn a_prompt_aborts_an_in_progress_synthetic_drag() { + let mut h = Headless::new(app(), [1400.0, 900.0], 1.0); + let photo = h.app.session.visible_cloned()[0]; + let t = Duration::from_secs(20); + assert_eq!(h.request("engine.execute", serde_json::json!({"command": "library.select", "params": {"ids": [photo.0]}}), t)["ok"], true); + assert_eq!(h.request("ui.set", serde_json::json!({"view": "detail", "right": "edit"}), t)["ok"], true); + h.app.ui.open_sections = vec!["light".to_string()]; + assert!(h.settle(Duration::from_secs(60)), "the edit panel settles"); + let id = "slider:light.exposure"; + let before = h.app.session.develop_of(photo).expect("its develop settings").light.exposure; + let (tx, rx) = reply_channel(); + h.app + .admit_gesture(&h.view.ctx.clone(), "ui.dragWidget".into(), serde_json::json!({"id": id, "dx": 40.0, "steps": 20}), tx) + .expect("the drag is admitted"); + h.step(); // resolve: move, press and many moves are queued + h.step(); // move + h.step(); // press + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the drag press reached egui"); + assert!(!h.app.synthetic.is_empty(), "the drag still has queued moves"); + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + let reply = rx.try_recv().expect("the aborted drag answers"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("modal prompt appeared"), "{reply}"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the drag's pointer was released"); + assert_eq!(h.app.session.develop_of(photo).expect("its develop settings").light.exposure, before, "the drag did not continue under the prompt"); + assert!(h.app.synthetic.is_empty(), "the rest of the drag was dropped"); + assert!(h.app.pending_gestures.is_empty()); + assert!(h.app.quit_prompt.is_some(), "the drag did not dismiss the prompt"); +} + +/// Changing from a Tasks prompt to an Unsaved prompt, or from one settings notice to the next, +/// is a new prompt. Its creation frame must shield pointer input even though the old prompt was +/// already settled. +#[test] +fn prompt_queue_and_kind_transitions_shield_the_first_frame() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + let id = "check:settings.confirmDelete"; + let at = h.app.widgets.iter().rev().find(|(widget, _)| widget == id).map(|(_, rect)| rect.center()).expect("the checkbox is on screen"); + let before = h.app.ui.settings.confirm_delete; + // A raw click resolved before the prompt exists must be refused before its first event, not + // land in the prompt's creation frame or be replayed after it goes away. + let (tx, rx) = reply_channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.click".into(), serde_json::json!({"x": at.x, "y": at.y}), tx).expect("the raw click is admitted"); + h.step(); + assert!(!h.app.synthetic.is_empty(), "the raw click is queued"); + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("tasks".into())); + h.step(); + let reply = rx.try_recv().expect("the pre-prompt raw click answers"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("modal prompt appeared"), "{reply}"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the queued raw click did not reach Settings"); + // Tasks -> Unsaved in the same host frame as a raw click on the covered checkbox. + h.events.extend([egui::Event::PointerMoved(at), pointer_event(at, true), pointer_event(at, false)]); + h.app.quit_prompt = Some(crate::QuitPrompt::Unsaved("unsaved".into())); + h.step(); + assert!(matches!(h.app.quit_prompt, Some(crate::QuitPrompt::Unsaved(_))), "the new prompt is shown"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the transition frame did not click Settings"); + // Dismiss Unsaved, then switch from one settings notice to the next in a pointer frame. + assert_eq!(h.request("ui.key", serde_json::json!({"key": "Escape"}), Duration::from_secs(20))["ok"], true); + h.app.notices = vec!["first notice".into()]; + h.step(); + h.step(); + h.events.extend([egui::Event::PointerMoved(at), pointer_event(at, true), pointer_event(at, false)]); + h.app.notices = vec!["second notice".into()]; + h.step(); + assert_eq!(h.app.notices, vec!["second notice".to_string()], "the queued notice is still shown"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "the notice transition did not click Settings"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Settings survived both transitions"); +} + +/// A prompt with no dialog must still stop global shortcuts. The rating key is a background +/// photo action, not part of the prompt. +#[test] +fn a_quit_prompt_blocks_global_rating_shortcuts() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + let photo = h.app.session.visible_cloned()[0]; + assert_eq!(h.request("engine.execute", serde_json::json!({"command": "library.select", "params": {"ids": [photo.0]}}), t)["ok"], true); + h.step(); + // Positive control: the same key rates the photo while no prompt is up. + let r = h.request("ui.key", serde_json::json!({"key": "4"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_eq!(h.app.session.catalog.photo(photo).expect("the photo").rating, 4, "the rating key works without a prompt"); + let before = h.app.session.catalog.photo(photo).expect("the photo").rating; + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + let r = h.request("ui.key", serde_json::json!({"key": "5"}), t); + assert_eq!(r["ok"], false, "the prompt blocked the key, so it must not report a delivered shortcut: {r}"); + assert!(r["error"].as_str().unwrap_or_default().contains("modal prompt"), "{r}"); + assert_eq!(h.app.session.catalog.photo(photo).expect("the photo").rating, before, "no rating behind the prompt"); + assert!(h.app.quit_prompt.is_some(), "the shortcut did not dismiss the prompt"); + assert!(h.app.pending_gestures.is_empty() && h.app.synthetic.is_empty(), "the blocked key left no queued input"); +} + +/// A settled prompt drops text and scroll input, and the control channel must report that refusal +/// instead of a false success: neither event has a prompt meaning. The prompt stays up. +#[test] +fn a_settled_prompt_rejects_blocked_text_and_scroll_gestures() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + for (method, params) in [("ui.text", serde_json::json!({"text": "x"})), ("ui.scroll", serde_json::json!({"dx": 0.0, "dy": 30.0}))] { + let r = h.request(method, params, t); + assert_eq!(r["ok"], false, "{method}: {r}"); + assert!(r["error"].as_str().unwrap_or_default().contains("modal prompt"), "{method}: {r}"); + assert!(h.app.quit_prompt.is_some(), "{method} did not dismiss the prompt"); + assert!(h.app.pending_gestures.is_empty() && h.app.synthetic.is_empty(), "{method} left queued input"); + } +} + +/// The settings-notice path uses the same barrier and window: it blocks the dialog below it (both +/// pointer and the outside-click preference), and its own OK dismisses it without closing Settings. +#[test] +fn a_settings_notice_blocks_background_input_and_its_ok_button_works() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "Settings is open"); + h.app.ui.settings.close_dialogs_outside = true; + let confirm_delete = h.app.ui.settings.confirm_delete; + h.app.notices.push("The settings file could not be read and was reset.".into()); + h.step(); + assert!(h.app.widgets.iter().any(|(id, _)| id == "button:noticeOk"), "the notice is laid out"); + assert!(h.app.widgets.iter().any(|(id, _)| id == "check:settings.confirmDelete"), "the covered checkbox is laid out"); + // A covered Settings control cannot be clicked, and a backdrop click cannot close Settings. + let r = h.request("ui.clickWidget", serde_json::json!({"id": "check:settings.confirmDelete"}), t); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(h.app.ui.settings.confirm_delete, confirm_delete, "the covered checkbox did not change"); + let at = egui::pos2(10.0, 890.0); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.events.extend([egui::Event::PointerMoved(at), press(true), press(false)]); + h.step(); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "the backdrop click did not close Settings"); + assert!(!h.app.notices.is_empty(), "the backdrop click did not dismiss the notice"); + // OK dismisses only the notice; Settings survives and becomes usable again. + let r = h.request("ui.clickWidget", serde_json::json!({"id": "button:noticeOk"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.notices.is_empty(), "OK dismissed the notice"); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { .. })), "dismissing the notice kept Settings"); + let r = h.request("ui.clickWidget", serde_json::json!({"id": "check:settings.confirmDelete"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_eq!(h.app.ui.settings.confirm_delete, !confirm_delete, "the checkbox works again after the notice"); +} + +#[test] +fn clipping_changed_between_the_move_and_press_is_seen_in_the_latest_registry() { + let mut h = Headless::new(app(), [1400.0, 900.0], 1.0); + let photo = h.app.session.visible_cloned()[0]; + let t = Duration::from_secs(20); + assert_eq!(h.request("engine.execute", serde_json::json!({"command": "library.select", "params": {"ids": [photo.0]}}), t)["ok"], true); + assert_eq!(h.request("ui.set", serde_json::json!({"view": "detail", "right": "edit"}), t)["ok"], true); + assert!(h.settle(Duration::from_secs(60)), "the detail view settles"); + let id = "star:bottom:2"; + let (tx, rx) = reply_channel(); + h.app.admit_gesture(&h.view.ctx.clone(), "ui.clickWidget".into(), serde_json::json!({"id": id}), tx).expect("the click is admitted"); + h.step(); // resolve: move, press and release are queued + h.step(); // the move is consumed + // The latest completed pass clipped the widget without moving it to another layer. Only the + // clipped rect in the registry knows that; `read_response` before `begin_pass` can still see + // the pass before the registry that was just published. + let hit = &mut h.app.widget_hits.iter_mut().rev().find(|(widget, _)| widget == id).expect("the target has a probe").1; + hit.interact_rect = egui::Rect::NOTHING; + h.step(); // the press is refused instead of being delivered to the clipped target + let reply = rx.try_recv().expect("the clipped click answers"); + assert_eq!(reply["ok"], false, "{reply}"); + let error = reply["error"].as_str().unwrap_or_default(); + assert!(error.contains("no longer visible"), "{reply}"); + assert!(error.contains("before its press"), "{reply}"); + assert!(h.app.pending_gestures.is_empty()); + assert!(h.app.synthetic.is_empty()); +} + +#[test] +fn a_timeout_cancels_only_its_own_gesture_and_preserves_a_later_queue() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + app.widgets = vec![ + ("first:test".into(), egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(30.0, 20.0))), + ("second:test".into(), egui::Rect::from_min_size(egui::pos2(60.0, 10.0), egui::vec2(30.0, 20.0))), + ]; + let (tx1, rx1) = reply_channel(); + let (tx2, rx2) = reply_channel(); + app.admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "first:test"}), tx1).expect("the first click is admitted"); + app.admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "second:test"}), tx2).expect("the second click is admitted"); + app.layout_epoch = app.layout_epoch.wrapping_add(1); + app.resolve_pending_gestures(&ctx); + assert_eq!(app.synthetic.len(), 6, "move, press and release for each click"); + // The first gesture stalls after its events were queued; the second was resolved behind it and + // has its own deadline. A timeout must remove only the first gesture's unsent prefix. + app.pending_gestures[0].deadline_ms = 0.0; + app.reply_delivered_gestures(); + let reply1 = rx1.try_recv().expect("the stalled first gesture answers"); + assert_eq!(reply1["ok"], false, "{reply1}"); + assert!(reply1["error"].as_str().unwrap_or_default().contains("timed out before the UI consumed its last event"), "{reply1}"); + assert_eq!(app.synthetic.len(), 3, "the later gesture's events are preserved"); + assert!(rx2.try_recv().is_err(), "the later gesture is still waiting"); + assert_eq!(app.pending_gestures.len(), 1); + assert_eq!(app.pending_gestures[0].target.as_ref().map(|target| target.id.as_str()), Some("second:test")); +} + +#[test] +fn queued_pointer_cleanup_requests_a_repaint_without_a_synthetic_event() { + let mut app = app(); + app.synthetic.clear(); + app.pointer_cleanup = true; + assert!(app.synthetic.is_empty()); + assert!(app.queued_input_needs_repaint(), "the pending cleanup alone must ask for the frame that injects it"); + // A timeout after the last synthetic batch is drained can queue cleanup inside finish_ui_pass; + // that pass itself has to ask for the frame that delivers it. + let ctx = egui::Context::default(); + app.finish_ui_pass(&ctx); + assert!(ctx.has_requested_repaint(), "finish_ui_pass requested the cleanup frame"); + app.pointer_cleanup = false; + assert!(!app.queued_input_needs_repaint()); +} + +#[test] +fn a_moved_widget_cancels_before_its_first_event_and_leaves_a_later_gesture_queued() { + let mut h = Headless::new(app(), [1000.0, 760.0], 1.0); + h.step(); + let t = Duration::from_secs(20); + let r = h.request("ui.key", serde_json::json!({"key": ",", "cmd": true}), t); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.settle(Duration::from_secs(60)), "the Settings dialog settles"); + assert!(h.app.widgets.iter().any(|(id, _)| id == "check:settings.confirmDelete")); + assert!(h.app.widgets.iter().any(|(id, _)| id == "button:settingsStartup-2")); + + let (tx1, rx1) = reply_channel(); + let (tx2, rx2) = reply_channel(); + let ctx = h.view.ctx.clone(); + h.app + .admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "check:settings.confirmDelete"}), tx1) + .expect("the first click is admitted"); + h.app + .admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "button:settingsStartup-2"}), tx2) + .expect("the second click is admitted"); + // This completed pass resolves both against the same registry and queues move, press, release + // for each. + h.step(); + assert!(rx1.try_recv().is_err(), "nothing is answered at resolution"); + assert!(rx2.try_recv().is_err(), "nothing is answered at resolution"); + assert_eq!(h.app.synthetic.len(), 6, "both gestures are queued"); + + // Before the first event the first target's latest rect moves (the second target stays put). + let moved = egui::Rect::from_min_size(egui::pos2(900.0, 700.0), egui::vec2(10.0, 10.0)); + let entry = h.app.widgets.iter_mut().rev().find(|entry| entry.0 == "check:settings.confirmDelete").expect("the first target is registered"); + entry.1 = moved; + // The first event's injection now cancels only the head; the second gesture's three events must + // stay at the front of the queue. + h.step(); + let reply1 = rx1.try_recv().expect("the canceled first gesture answers"); + assert_eq!(reply1["ok"], false, "{reply1}"); + let error = reply1["error"].as_str().unwrap_or_default(); + assert!(error.contains("before its first event"), "{reply1}"); + assert!(error.contains("nothing was retargeted"), "{reply1}"); + assert_eq!(h.app.synthetic.len(), 3, "the later gesture's events are preserved"); + assert!(rx2.try_recv().is_err(), "the later gesture is still waiting"); + + for _ in 0..8 { + h.step(); + } + let reply2 = rx2.try_recv().expect("the later gesture is delivered"); + assert_eq!(reply2["ok"], true, "{reply2}"); + assert_eq!(h.app.ui.settings.startup_view, crate::state::StartupView::Detail, "the second click ran"); + assert!(h.app.pending_gestures.is_empty()); +} + +#[test] +fn a_click_whose_target_vanishes_after_the_press_fails_and_releases_the_pointer() { + let mut h = Headless::new(app(), [1000.0, 760.0], 1.0); + h.step(); + let t = Duration::from_secs(20); + let r = h.request("ui.key", serde_json::json!({"key": ",", "cmd": true}), t); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.settle(Duration::from_secs(60)), "the Settings dialog settles"); + let before = h.app.ui.settings.confirm_delete; + + let (tx, rx) = reply_channel(); + h.app + .admit_gesture(&h.view.ctx.clone(), "ui.clickWidget".into(), serde_json::json!({"id": "check:settings.confirmDelete"}), tx) + .expect("the click is admitted"); + h.step(); // resolve: move, press, release are queued + h.step(); // the move is consumed + h.step(); // the press is consumed: the pointer is now down + assert!(h.view.ctx.input(|i| i.pointer.any_down()), "the press reached egui"); + + // The widget vanishes between press and release (the click's own effect or a layout change). + h.app.widgets.retain(|(id, _)| id != "check:settings.confirmDelete"); + h.step(); // the release is refused, and a safe release is injected for the down pointer + let reply = rx.try_recv().expect("the canceled click answers"); + assert_eq!(reply["ok"], false, "{reply}"); + let error = reply["error"].as_str().unwrap_or_default(); + assert!(error.contains("disappeared before its release"), "{reply}"); + assert!(error.contains("nothing was retargeted"), "{reply}"); + assert!(!h.view.ctx.input(|i| i.pointer.any_down()), "the canceled press was released"); + assert_eq!(h.app.ui.settings.confirm_delete, before, "no click was delivered"); + assert!(h.app.pending_gestures.is_empty()); + assert!(h.app.synthetic.is_empty()); +} + +#[test] +fn a_discarded_layout_does_not_publish_its_widget_registry() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(800.0, 600.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + let kept = egui::Rect::from_min_size(egui::pos2(1.0, 2.0), egui::vec2(3.0, 4.0)); + let discarded = egui::Rect::from_min_size(egui::pos2(5.0, 6.0), egui::vec2(7.0, 8.0)); + app.widgets = vec![("kept:test".into(), kept)]; + app.next_widgets = vec![("discarded:test".into(), discarded)]; + let mut passes = 0; + let mut output = ctx.run_pass(raw(egui::vec2(800.0, 600.0)), |ctx| { + if passes == 0 { + ctx.request_discard("test: throw this layout away"); + app.finish_ui_pass(ctx); + } + passes += 1; + }); + output.textures_delta.clear(); + assert!(passes > 1, "egui reran the discarded layout"); + assert_eq!(app.widgets, vec![("kept:test".into(), kept)], "the discarded registry was not published"); + assert!(app.next_widgets.is_empty()); +} + +#[test] +fn a_gesture_replies_only_after_the_completed_pass_consumed_its_event() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + app.ui.view = crate::state::ViewMode::Detail; + let (tx, rx) = reply_channel(); + app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({"x": 12.0, "y": 14.0}), tx).expect("admitted"); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + assert_eq!(app.synthetic.len(), 1, "resolution queued the event"); + assert!(rx.try_recv().is_err(), "not answered before the UI consumed it"); + let mut next = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut next); + assert!(next.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_))), "the event is injected next frame"); + frame(&ctx, next, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + let reply = rx.try_recv().expect("the delivery reply"); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(app.pending_gestures.is_empty()); +} + +#[test] +fn a_delivered_gesture_may_change_the_state_it_acted_on() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + let (tx, rx) = reply_channel(); + app.admit_gesture(&ctx, "ui.key".into(), serde_json::json!({"key": "j", "cmd": true}), tx).expect("admitted"); + // The first completed pass resolves the key against the Detail layout and queues it. + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + assert!(!app.synthetic.is_empty(), "the key is queued"); + // The pass that consumes it opens the dialog: that is the gesture doing its job, not drift. + let mut next = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut next); + frame(&ctx, next, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + assert_eq!(app.ui.dialog, Some(crate::state::Dialog::ViewOptions)); + let reply = rx.try_recv().expect("the delivered gesture answers"); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(app.pending_gestures.is_empty()); +} + +#[test] +fn a_gesture_cancels_when_the_view_changes_before_its_batch_is_injected() { + let ctx = egui::Context::default(); + let mut app = app(); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| app.logic(ui.ctx())); + app.logic(&ctx); + assert!(app.fonts_ready); + let (tx, rx) = reply_channel(); + app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({"x": 10.0, "y": 10.0}), tx).expect("admitted"); + frame(&ctx, raw(egui::vec2(1000.0, 700.0)), |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + assert_eq!(app.synthetic.len(), 1, "resolution queued the event"); + // A hidden logic tick changes what the queued pointer event would mean before a visible + // pass consumes it: fail closed instead of injecting it into the new view. + app.ui.view = crate::state::ViewMode::PhotoGrid; + let mut next = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut next); + assert!(next.events.is_empty(), "no stale event reaches the new view"); + assert!(app.synthetic.is_empty()); + let reply = rx.try_recv().expect("the cancel error answers once"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("canceled"), "{reply}"); + assert!(app.pending_gestures.is_empty()); +} + +fn queued_shot(sent_at_ms: Option<f64>) -> PendingShot { + let (tx, _rx) = reply_channel(); + PendingShot { + token: 1, + target: None, + reply: tx, + headless: false, + admitted_passes: 0, + not_before_ms: 0.0, + force_ms: 0.0, + deadline_ms: 10_000.0, + sent_at_ms, + reserved: 1, + slot: None, + issued: None, + issued_library: 0, + } +} + +#[test] +fn hidden_paint_requests_only_queued_shots_not_issued_ones() { + let mut app = app(); + app.pending_screenshots.push(queued_shot(Some(1.0))); + assert!(!app.needs_ui_pass_while_hidden(), "an issued screenshot forces its own paint"); + app.pending_screenshots.clear(); + app.pending_screenshots.push(queued_shot(None)); + assert!(app.needs_ui_pass_while_hidden(), "a queued/settling screenshot needs a UI pass"); + app.pending_screenshots.clear(); + app.synthetic.push(egui::Event::PointerMoved(egui::Pos2::ZERO)); + assert!(app.needs_ui_pass_while_hidden(), "a gesture step needs a UI pass"); +} + +#[test] +fn disclosure_rows_publish_expanded_not_toggled() { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut seen = Vec::new(); + frame(&ctx, raw(egui::vec2(400.0, 300.0)), |ui| { + let (resp, _) = crate::widgets::section_header(ui, "test-section", "Light", true, None); + seen.push(ui.ctx().accesskit_node_builder(resp.id, |node| node.is_expanded()).flatten()); + }); + frame(&ctx, raw(egui::vec2(400.0, 300.0)), |ui| { + let (resp, _) = crate::widgets::section_header(ui, "test-section", "Light", false, None); + seen.push(ui.ctx().accesskit_node_builder(resp.id, |node| node.is_expanded()).flatten()); + }); + assert_eq!(seen, vec![Some(true), Some(false)], "the disclosure reports Expanded, not Toggled"); +} + +/// `ui.hoverWidget` obeys the same clipped/covered-target contract as a press: a hover whose +/// widget was clipped before delivery is refused, as is one under the non-modal library window. +#[test] +fn hover_widget_refuses_clipped_and_covered_targets() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + let t = Duration::from_secs(20); + h.step(); + assert!(h.app.run("app.settings", serde_json::json!({})).is_ok(), "Settings opens"); + assert!(h.settle(Duration::from_secs(60)), "Settings settles"); + let id = "check:settings.confirmDelete"; + assert!(h.app.widget_hits.iter().any(|(widget, _)| widget == id), "{id} has a probe"); + + let (tx, rx) = reply_channel(); + let ctx = h.view.ctx.clone(); + h.app.admit_gesture(&ctx, "ui.hoverWidget".into(), serde_json::json!({"id": id}), tx).expect("the hover is admitted"); + h.step(); // resolve: the pointer move is queued, not consumed + assert!(rx.try_recv().is_err(), "nothing is answered at resolution"); + // The latest completed registry says the widget has no clipped interaction area. The hover + // must fail before its first pointer move, like a press at the same stale point. + if let Some(hit) = h.app.widget_hits.iter_mut().rev().find(|(widget, _)| widget == id) { + hit.1.interact_rect = egui::Rect::NOTHING; + } + h.step(); + let reply = rx.try_recv().expect("the clipped hover answers"); + assert_eq!(reply["ok"], false, "{reply}"); + let error = reply["error"].as_str().unwrap_or_default(); + assert!(error.contains("no longer visible"), "{reply}"); + assert!(error.contains("before its first event"), "{reply}"); + assert!(h.app.pending_gestures.is_empty() && h.app.synthetic.is_empty()); + + // Positive control: the next pass publishes the real clipped rect again. + let r = h.request("ui.hoverWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], true, "an unobstructed hover still works: {r}"); + + // The library window is a non-modal overlay (its dim is the modal layer). A target below it + // must be refused before a pointer move is queued, then work again after the window closes. + h.app.library_problem = Some(crate::panels::library_problem::LibraryProblem::new("/no/such/library", "test error")); + assert!(h.settle(Duration::from_secs(60)), "the library window settles"); + assert!(h.app.widgets.iter().any(|(widget, _)| widget == "button:libraryRetry"), "the library window is laid out"); + let r = h.request("ui.hoverWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap_or_default().contains(id), "{r}"); + h.app.library_problem = None; + assert!(h.settle(Duration::from_secs(60)), "Settings settles after the overlay"); + let r = h.request("ui.hoverWidget", serde_json::json!({"id": id}), t); + assert_eq!(r["ok"], true, "the same hover works once the overlay is gone: {r}"); +} + +/// A system paste request is a viewport command, not a synthetic event, so the prompt/library +/// barrier cannot filter it later. It must be refused while either newly-created barrier owns the +/// pass, and still work normally without one. +#[test] +fn a_system_paste_under_a_new_barrier_is_refused() { + let mut h = Headless::new(app(), [1200.0, 760.0], 1.0); + let t = Duration::from_secs(20); + h.settle(Duration::from_secs(60)); + let r = h.request("ui.clickWidget", serde_json::json!({"id": "field:search"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.view.clipboard = "blocked".into(); + let ctx = h.view.ctx.clone(); + + for (barrier, message) in [ + (Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())), "modal prompt"), + (None, "blocking library window"), + ] { + if barrier.is_some() { + h.app.quit_prompt = barrier; + } else { + h.app.library_problem = Some(crate::panels::library_problem::LibraryProblem::new("/no/such/library", "test error")); + } + let (tx, rx) = reply_channel(); + h.app.admit_gesture(&ctx, "ui.clipboard".into(), serde_json::json!({"action": "paste"}), tx).expect("the paste is admitted"); + h.app.layout_epoch = h.app.layout_epoch.wrapping_add(1); + h.app.resolve_pending_gestures(&ctx); + let reply = rx.try_recv().expect("the blocked paste answers"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains(message), "{reply}"); + assert!(h.app.pending_gestures.is_empty() && h.app.synthetic.is_empty()); + h.app.quit_prompt = None; + h.app.library_problem = None; + } + + // Positive control: with no barrier, the host clipboard answers and the focused field changes. + h.step(); + h.view.clipboard = "allowed".into(); + let r = h.request("ui.clipboard", serde_json::json!({"action": "paste"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert_eq!(h.app.ui.search, "allowed", "an ordinary system paste still reaches the focused field"); +} + +/// A canceled synthetic press must not overwrite a real host modifier change that arrived in the +/// same frame, later cleanup must not clear that still-held host modifier, and a host release must +/// not leave stale synthetic ownership that suppresses the next synthetic Shift gesture. +#[test] +fn synthetic_modifier_ownership_follows_host_changes_across_frames() { + let ctx = egui::Context::default(); + let mut app = app(); + app.fonts_ready = true; + // The synthetic gesture held Alt; its cleanup is in flight when the real host presses Shift. + app.synthetic_mods = egui::Modifiers::ALT; + app.synthetic_mods_release = true; + app.pointer_cleanup = true; + let mut input = raw(egui::vec2(1000.0, 700.0)); + input.events.push(egui::Event::ModifiersChanged(egui::Modifiers::SHIFT)); + app.raw_input_hook(&ctx, &mut input); + assert_eq!(input.events, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT)], "the host's Shift press survives cleanup"); + assert_eq!(app.host_mods, egui::Modifiers::SHIFT, "the host state is tracked separately"); + assert_eq!(app.synthetic_mods, egui::Modifiers::NONE, "the canceled gesture no longer owns modifiers"); + assert!(!app.synthetic_mods_release); + + // A later synthetic cleanup with no host event must restore the still-held Shift, not NONE. + app.synthetic_mods = egui::Modifiers::ALT; + app.synthetic_mods_release = true; + app.pointer_cleanup = true; + let mut input = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut input); + assert_eq!( + input.events, + vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT)], + "cleanup restored the physical Shift rather than clearing it" + ); + assert_eq!(app.host_mods, egui::Modifiers::SHIFT); + assert_eq!(app.synthetic_mods, egui::Modifiers::NONE); + + // A plain synthetic event carrying NONE likewise must not clear the host's Shift. + app.synthetic.push(egui::Event::Text("plain".into())); + let mut input = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut input); + assert!( + !input.events.iter().any(|e| matches!(e, egui::Event::ModifiersChanged(_))), + "a NONE synthetic event did not announce NONE: {:?}", + input.events + ); + assert!(input.events.iter().any(|e| matches!(e, egui::Event::Text(text) if text == "plain"))); + app.synthetic_in_flight = false; + + // The host releases Shift. Any stale synthetic ownership would now suppress a later gesture. + let mut input = raw(egui::vec2(1000.0, 700.0)); + input.events.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + app.raw_input_hook(&ctx, &mut input); + assert_eq!(app.host_mods, egui::Modifiers::NONE); + assert_eq!(app.synthetic_mods, egui::Modifiers::NONE); + + // The next synthetic gesture that carries Shift must announce it. + app.synthetic.push(key_event(egui::Key::A, true, egui::Modifiers::SHIFT)); + app.synthetic.push(key_event(egui::Key::A, false, egui::Modifiers::SHIFT)); + let mut input = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut input); + assert!( + input.events.iter().any(|e| matches!(e, egui::Event::ModifiersChanged(m) if *m == egui::Modifiers::SHIFT)), + "the fresh synthetic Shift gesture announces its modifier: {:?}", + input.events + ); + assert_eq!(app.synthetic_mods, egui::Modifiers::SHIFT); + app.synthetic_in_flight = false; + + // Its release returns to the host's state (NONE), not a stale synthetic Shift. + let mut input = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut input); + assert_eq!(input.events, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + assert_eq!(app.synthetic_mods, egui::Modifiers::NONE); + + // Positive control: with no host change, cleanup still releases synthetic modifiers to the + // host's last known (NONE) state. + app.synthetic_mods = egui::Modifiers::ALT; + app.synthetic_mods_release = true; + app.pointer_cleanup = true; + let mut input = raw(egui::vec2(1000.0, 700.0)); + app.raw_input_hook(&ctx, &mut input); + assert_eq!(input.events, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + assert_eq!(app.synthetic_mods, egui::Modifiers::NONE); + assert!(!app.synthetic_mods_release); +} diff --git a/crates/ui-egui/src/tests_lightroom_destination.rs b/crates/ui-egui/src/tests_lightroom_destination.rs new file mode 100644 index 0000000000..b2def730b3 --- /dev/null +++ b/crates/ui-egui/src/tests_lightroom_destination.rs @@ -0,0 +1,426 @@ +//! Issue #2672: before File ▸ Import Lightroom Catalog… starts, a window asks whether the catalog +//! merges into the open library or goes into a new library (named after the catalog, next to the +//! open one), unless Settings (or the window's "Don't ask again") says to always merge. +//! +//! The catalogs here are fake (`.lrcat` files that aren't SQLite): what is checked is where the +//! import is started, which library is open when it starts, and that the read then fails cleanly. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::state::{Dialog, LightroomImport}; +use crate::{LightcraftApp, Services, UiState}; + +const T: Duration = Duration::from_secs(20); + +/// A folder of its own per test: `Library` (a LightCraft library, demo photos in it unless +/// `empty`) and `Lightroom/Travel.lrcat` (a fake catalog) side by side. +struct Fixture { + /// The test's own folder. + root: PathBuf, + /// `root/Library`. + lib: PathBuf, + /// `root/Lightroom/Travel.lrcat`. + lrcat: PathBuf, +} + +impl Fixture { + /// Make the folders and the fake catalog (an earlier run's leftovers removed). + fn new(tag: &str) -> Fixture { + let root = std::env::temp_dir().join(format!("lc-ui-lrdest-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let lr = root.join("Lightroom"); + std::fs::create_dir_all(&lr).unwrap(); + let lrcat = lr.join("Travel.lrcat"); + std::fs::write(&lrcat, b"not really SQLite").unwrap(); + Fixture { lib: root.join("Library"), root, lrcat } + } + + /// The desktop app on `Library`, with a folder dialog (for Choose…) and screenshots. + fn app(&self, empty: bool) -> Headless { + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&self.lib, !empty).unwrap(); + let png = |img: &lightcraft_raster::Rgba8| { + lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default() + }; + // (a folder dialog for the window's Choose…, and what a screenshot needs) + let services = Services { + pick_folder: Some(Box::new(|| None)), + png: Some(Box::new(png)), + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut h = Headless::new(LightcraftApp::new(session, services), [1200.0, 800.0], 1.0); + h.step(); + h + } + + /// The catalog's path as text. + fn lrcat(&self) -> String { + self.lrcat.to_string_lossy().into_owned() + } +} + +impl Drop for Fixture { + /// Remove the folders. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } +} + +/// The widget `id` was drawn last frame. +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +/// Click the widget `id` through the control channel, then draw a frame. +fn click(h: &mut Headless, id: &str) { + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{id}: {r}"); + h.step(); +} + +/// The open library's folder. +fn open_dir(h: &Headless) -> Option<PathBuf> { + h.app.session.library.as_ref().map(|l| l.dir.clone()) +} + +/// The window's state: (new library chosen, name, location, don't ask). +fn destination(h: &Headless) -> Option<(bool, String, String, bool)> { + match &h.app.ui.dialog { + Some(Dialog::LightroomDestination { new_library, name, location, dont_ask, .. }) => { + Some((*new_library, name.clone(), location.clone(), *dont_ask)) + } + _ => None, + } +} + +/// Let the import of the fake catalog end (it fails to read) and return what it reported. +fn import_ends(h: &mut Headless, lrcat: &Path) -> Value { + assert!(h.step_until(T, |h| h.app.lightroom.is_none()), "the import never ended"); + let last = h.app.lightroom_last.clone().unwrap_or_default(); + assert_eq!(last["path"], json!(lrcat), "the import was of this catalog: {last}"); + last +} + +/// A headless screenshot into `$LIGHTCRAFT_TEST_SHOTS`, when it is set. +fn shot(h: &mut Headless, name: &str) { + if let Some(p) = std::env::var_os("LIGHTCRAFT_TEST_SHOTS") { + let r = h.request("ui.screenshot", json!({"path": Path::new(&p).join(name).to_string_lossy(), "headless": true}), T); + assert_eq!(r["ok"], true, "{r}"); + } +} + +/// The window appears before anything starts, with its choices; Merge imports into the open library. +#[test] +fn the_window_asks_and_merge_imports_into_the_open_library() { + let f = Fixture::new("merge"); + let mut h = f.app(false); + let photos = h.app.session.catalog.len(); + assert!(photos > 0); + + let r = h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + assert_eq!(r, json!({"asking": true, "path": f.lrcat(), "into": "new"})); + h.step(); + h.step(); + // a library with photos: the window opens on a new library, named after the catalog, next to the open one + assert_eq!(destination(&h), Some((true, "Travel".into(), f.root.to_string_lossy().into_owned(), false))); + for id in [ + "radio:lightroomDestination-open", + "radio:lightroomDestination-new", + "field:lightroomLibraryName", + "field:lightroomLibraryLocation", + "button:lightroomLibraryChoose", + "check:lightroomDontAsk", + "button:dialogOk", + "button:dialogCancel", + ] { + assert!(has(&h, id), "{id} is missing"); + } + assert!(h.app.lightroom.is_none() && h.app.lightroom_last.is_none(), "nothing starts before the answer"); + shot(&mut h, "lightroom-destination-2672.png"); + + // Merge into the open library + click(&mut h, "radio:lightroomDestination-open"); + assert_eq!(destination(&h).map(|d| d.0), Some(false)); + click(&mut h, "button:dialogOk"); + assert!(destination(&h).is_none()); + assert!(h.app.lightroom.is_some() || h.app.lightroom_last.is_some(), "the import started"); + import_ends(&mut h, &f.lrcat); + assert_eq!(open_dir(&h), Some(f.lib.clone()), "into the library open before"); + assert_eq!(h.app.session.catalog.len(), photos); + assert!(!f.root.join("Travel").exists(), "no library was made"); + assert_eq!(h.app.ui.settings.lightroom_import, LightroomImport::Ask, "it asks again next time"); +} + +/// Create a new library: it is made next to the open one, named after the catalog, and opened +/// before the import starts there. +#[test] +fn create_a_new_library_opens_it_before_the_import_starts() { + let f = Fixture::new("new"); + let mut h = f.app(false); + h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + h.step(); + h.step(); + assert_eq!(destination(&h).map(|d| d.0), Some(true)); + // ui.dialog.confirm answers what the window's button does + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + let new = f.root.join("Travel"); + let result = &r["result"]; + assert_eq!(result["library"]["path"], json!(new.to_string_lossy()), "{r}"); + assert_eq!(result["library"]["name"], "Travel", "{r}"); + assert_eq!(result["path"], json!(f.lrcat()), "{r}"); + // the new library is the open one, and it was when the import started (the import's + // snapshot is taken in the same call, after the switch) + assert_eq!(open_dir(&h), Some(new.clone())); + assert!(lightcraft_engine::library::is_library(&new)); + assert_eq!(h.app.ui.settings.library_path, new.to_string_lossy(), "opened at the next launch"); + assert!(h.app.ui.settings.recent_libraries.contains(&f.lib.to_string_lossy().into_owned()), "the old one is a recent library"); + import_ends(&mut h, &f.lrcat); + assert_eq!(open_dir(&h), Some(new)); +} + +/// Cancel: no import, no library made, the open library stays. +#[test] +fn cancel_does_nothing() { + let f = Fixture::new("cancel"); + let mut h = f.app(false); + h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + h.step(); + h.step(); + assert!(destination(&h).is_some()); + click(&mut h, "button:dialogCancel"); + assert!(h.app.ui.dialog.is_none()); + assert!(h.app.lightroom.is_none() && h.app.lightroom_last.is_none()); + assert_eq!(open_dir(&h), Some(f.lib.clone())); + assert!(!f.root.join("Travel").exists()); +} + +/// An empty library has nothing to merge with: the window opens on Merge. +#[test] +fn an_empty_library_opens_the_window_on_merge() { + let f = Fixture::new("empty"); + let mut h = f.app(true); + let r = h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + assert_eq!(r["into"], "open", "{r}"); + h.step(); + assert!(matches!(&h.app.ui.dialog, Some(Dialog::LightroomDestination { new_library: false, photos: 0, .. })), "{:?}", h.app.ui.dialog); + // (the window in French, which translates it: the language is this test thread's own) + if std::env::var_os("LIGHTCRAFT_TEST_SHOTS").is_some() { + h.app.run("app.language.french", json!({})).unwrap(); + h.step(); + h.step(); + shot(&mut h, "lightroom-destination-empty-fr-2672.png"); + h.app.run("app.language.english", json!({})).unwrap(); + } +} + +/// "Always merge into the open library" imports without the window. +#[test] +fn always_merge_skips_the_window() { + let f = Fixture::new("always"); + let mut h = f.app(false); + h.app.ui.settings.lightroom_import = LightroomImport::AlwaysMerge; + let r = h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + assert_eq!(r["running"], true, "{r}"); + h.step(); + assert!(destination(&h).is_none()); + import_ends(&mut h, &f.lrcat); + assert_eq!(open_dir(&h), Some(f.lib.clone())); +} + +/// "Don't ask again" (with Merge only) sets "Always merge", which is saved in `ui.json`. +#[test] +fn dont_ask_again_merges_from_then_on_and_is_saved() { + let f = Fixture::new("dontask"); + let mut h = f.app(false); + h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + h.step(); + h.step(); + // greyed out while a new library is chosen: it only speaks of merging + click(&mut h, "check:lightroomDontAsk"); + assert_eq!(destination(&h).map(|d| d.3), Some(false)); + click(&mut h, "radio:lightroomDestination-open"); + click(&mut h, "check:lightroomDontAsk"); + assert_eq!(destination(&h).map(|d| d.3), Some(true)); + click(&mut h, "button:dialogOk"); + assert_eq!(h.app.ui.settings.lightroom_import, LightroomImport::AlwaysMerge); + import_ends(&mut h, &f.lrcat); + // saved with the UI state (ui.json) and read back + let saved = serde_json::to_string(&h.app.ui).unwrap(); + assert!(saved.contains(r#""lightroomImport":"alwaysMerge""#), "{saved}"); + let back: UiState = serde_json::from_str(&saved).unwrap(); + assert_eq!(back.settings.lightroom_import, LightroomImport::AlwaysMerge); + // the next import doesn't ask + let r = h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + assert_eq!(r["running"], true, "{r}"); + assert!(destination(&h).is_none()); + import_ends(&mut h, &f.lrcat); +} + +/// Settings written before the setting existed, or hand-edited, ask (the default). +#[test] +fn old_and_odd_settings_files_ask() { + let old: UiState = serde_json::from_str(r#"{"settings": {"startupView": "detail"}}"#).unwrap(); + assert_eq!(old.settings.lightroom_import, LightroomImport::Ask); + let odd: UiState = serde_json::from_str(r#"{"settings": {"lightroomImport": "sometimes", "startupView": "detail"}}"#).unwrap(); + assert_eq!(odd.settings.lightroom_import, LightroomImport::Ask); + assert_eq!(odd.settings.startup_view, crate::state::StartupView::Detail, "the rest of the file still loads"); +} + +/// Settings ▸ General ▸ When importing a Lightroom catalog switches between the two. +#[test] +fn settings_general_switches_the_question_off_and_on() { + let f = Fixture::new("settings"); + let mut h = f.app(false); + h.app.run("app.settings", json!({})).unwrap(); + h.step(); + h.step(); + click(&mut h, "button:settingsLightroomImport-1"); + assert_eq!(h.app.ui.settings.lightroom_import, LightroomImport::AlwaysMerge); + shot(&mut h, "settings-lightroom-import-2672.png"); + click(&mut h, "button:settingsLightroomImport-0"); + assert_eq!(h.app.ui.settings.lightroom_import, LightroomImport::Ask); +} + +/// A new library's folder must be new or empty (File ▸ New Library…'s rule): the window says so +/// and stays open to pick another name; nothing is imported and the library stays. +#[test] +fn a_folder_that_isnt_empty_is_refused_and_the_window_stays() { + let f = Fixture::new("notempty"); + std::fs::create_dir_all(f.root.join("Travel")).unwrap(); + std::fs::write(f.root.join("Travel").join("notes.txt"), b"mine").unwrap(); + let mut h = f.app(false); + h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + h.step(); + h.step(); + // the free name is offered… + assert_eq!(destination(&h).map(|d| d.1), Some("Travel 2".to_string())); + // …but the user types the taken one + if let Some(Dialog::LightroomDestination { name, .. }) = h.app.ui.dialog.as_mut() { + *name = "Travel".into(); + } + click(&mut h, "button:dialogOk"); + assert!(destination(&h).is_some(), "the window stays to be corrected"); + let toast = h.app.ui.toast.clone().map(|t| t.0).unwrap_or_default(); + assert!(toast.contains("isn't empty"), "{toast}"); + assert_eq!(open_dir(&h), Some(f.lib.clone())); + assert!(h.app.lightroom.is_none() && h.app.lightroom_last.is_none()); + // the same through the control channel + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], false, "{r}"); + assert!(destination(&h).is_some()); +} + +/// `into` acts without asking (agents, scripts); bad params are refused before anything happens. +#[test] +fn into_acts_without_the_window() { + let f = Fixture::new("into"); + let mut h = f.app(false); + for bad in [json!({"path": f.lrcat(), "into": "elsewhere"}), json!({"path": f.lrcat(), "into": "new", "location": "relative/dir"})] { + let err = h.app.run("file.importLightroom", bad.clone()).unwrap_err(); + assert!(err.contains("file.importLightroom"), "{bad}: {err}"); + } + // a catalog that isn't there doesn't leave an empty library behind + let missing = f.root.join("Gone.lrcat"); + let err = h.app.run("file.importLightroom", json!({"path": missing.to_string_lossy(), "into": "new"})).unwrap_err(); + assert!(err.contains("no Lightroom catalog"), "{err}"); + assert!(!f.root.join("Gone").exists()); + assert!(destination(&h).is_none() && h.app.lightroom_last.is_none()); + + let elsewhere = f.root.join("Libraries"); + let r = h + .app + .run("file.importLightroom", json!({"path": f.lrcat(), "into": "new", "name": "Trips", "location": elsewhere.to_string_lossy()})) + .unwrap(); + assert_eq!(r["library"]["name"], "Trips", "{r}"); + assert_eq!(open_dir(&h), Some(elsewhere.join("Trips"))); + assert!(destination(&h).is_none()); + import_ends(&mut h, &f.lrcat); + + // a new library while another import runs: refused before anything is made + let r = h.app.run("file.importLightroom", json!({"path": f.lrcat(), "into": "open"})).unwrap(); + assert_eq!(r["running"], true, "{r}"); + let err = h.app.run("file.importLightroom", json!({"path": f.lrcat(), "into": "new", "name": "Again"})).unwrap_err(); + assert!(err.contains("already running"), "{err}"); + assert!(!elsewhere.join("Again").exists()); + // and the window isn't shown for an answer that couldn't be carried out + assert!(h.app.run("file.importLightroom", json!({"path": f.lrcat()})).is_err()); + assert!(destination(&h).is_none()); + import_ends(&mut h, &f.lrcat); + assert_eq!(open_dir(&h), Some(elsewhere.join("Trips"))); +} + +/// A session in memory (no library on disk) has nothing to put a new library next to: it merges +/// without asking, as before. +#[test] +fn a_library_in_memory_merges_without_asking() { + let f = Fixture::new("memory"); + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), [1200.0, 800.0], 1.0); + h.step(); + let r = h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + assert_eq!(r["running"], true, "{r}"); + assert!(destination(&h).is_none()); + import_ends(&mut h, &f.lrcat); +} + +/// Another library opened while the window was up (an agent, the control channel): the window +/// doesn't merge into it. +#[test] +fn merge_is_refused_when_another_library_was_opened_meanwhile() { + let f = Fixture::new("stale"); + let mut h = f.app(false); + h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + h.step(); + click(&mut h, "radio:lightroomDestination-open"); + let other = f.root.join("Other"); + let dialog = h.app.ui.dialog.take(); + h.app.run("app.openLibrary", json!({"path": other.to_string_lossy()})).unwrap(); + let stale = dialog.clone(); + h.app.ui.dialog = dialog; + h.step(); + click(&mut h, "button:dialogOk"); + assert!(h.app.ui.dialog.is_none(), "the window closes: the library it named is gone"); + // confirm's own error, not the last toast: another notice (the library switch's, on macOS) + // can replace the toast before it is read + let stale = stale.unwrap(); + let err = crate::lightroom_destination::confirm(&mut h.app, &stale).unwrap_err(); + assert!(err.contains("nothing was imported"), "{err}"); + assert!(h.app.lightroom.is_none() && h.app.lightroom_last.is_none()); + assert_eq!(open_dir(&h), Some(other)); +} + +/// The same for *Create a new library* (CodeRabbit on #2685): a window left over from before a +/// library switch makes no library and imports nothing. +#[test] +fn a_new_library_is_refused_when_another_library_was_opened_meanwhile() { + let f = Fixture::new("stale-new"); + let mut h = f.app(false); + h.app.run("file.importLightroom", json!({"path": f.lrcat()})).unwrap(); + h.step(); + click(&mut h, "radio:lightroomDestination-new"); + let other = f.root.join("Other"); + let dialog = h.app.ui.dialog.take(); + let target = match &dialog { + Some(crate::state::Dialog::LightroomDestination { name, location, .. }) => std::path::Path::new(location).join(name), + _ => panic!("the destination window is up"), + }; + h.app.run("app.openLibrary", json!({"path": other.to_string_lossy()})).unwrap(); + let stale = dialog.clone(); + h.app.ui.dialog = dialog; + h.step(); + click(&mut h, "button:dialogOk"); + assert!(h.app.ui.dialog.is_none(), "the window closes: the library it named is gone"); + // confirm's own error, not the last toast: another notice (the library switch's, on macOS) + // can replace the toast before it is read + let stale = stale.unwrap(); + let err = crate::lightroom_destination::confirm(&mut h.app, &stale).unwrap_err(); + assert!(err.contains("nothing was imported"), "{err}"); + assert!(h.app.lightroom.is_none() && h.app.lightroom_last.is_none()); + assert_eq!(open_dir(&h), Some(other)); + assert!(!target.exists(), "no library was made at {}", target.display()); +} diff --git a/crates/ui-egui/src/tests_masking.rs b/crates/ui-egui/src/tests_masking.rs index a1e5846e40..c8d6d6c2ea 100644 --- a/crates/ui-egui/src/tests_masking.rs +++ b/crates/ui-egui/src/tests_masking.rs @@ -295,6 +295,21 @@ fn radial_body_drag_keeps_resize_and_rotation_handles() { } } +#[test] +fn mask_overlay_color_refuses_anything_but_six_hex_digits() { + let mut h = detail("panel.masking"); + exec(&mut h, "view.maskOverlayColor", json!({"color": "#2870f0"})); + for bad in ["#+f+f+f", "+12345", "#-0-0-0", "##ffffff"] { + let r = h.request("engine.execute", json!({"command": "view.maskOverlayColor", "params": {"color": bad}}), T); + assert_eq!(r["ok"], false, "{bad:?} is not a colour: {r}"); + assert_eq!(h.app.ui.mask_overlay_color, [0x28, 0x70, 0xf0], "{bad:?} leaves the overlay colour alone"); + } + exec(&mut h, "view.maskOverlayColor", json!({"color": "e63228"})); + assert_eq!(h.app.ui.mask_overlay_color, [0xe6, 0x32, 0x28]); + exec(&mut h, "view.maskOverlayColor", json!({"color": [10, 20, 30]})); + assert_eq!(h.app.ui.mask_overlay_color, [10, 20, 30]); +} + #[test] fn mask_overlay_keys_and_pins() { use lightcraft_pipeline::{MaskView, Overlay}; @@ -348,6 +363,63 @@ fn mask_overlay_keys_and_pins() { h.settle(SETTLE); } +/// #2210: Ctrl+Shift+O (the all-masks overlay) draws the white outline of every visible +/// Radial/Linear mask, not just the selected one — but only the selected mask registers +/// `maskHandle:` elements, so nothing else becomes draggable. +#[test] +fn all_masks_overlay_outlines_every_visible_mask_but_only_the_selected_one_is_draggable() { + let mut h = detail("panel.masking"); + // Two visible radial masks; mask 2 ends up selected (mask.add selects the new one). + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.3, 0.5], "rx": 0.12, "ry": 0.12})); + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.7, 0.5], "rx": 0.12, "ry": 0.12})); + exec(&mut h, "view.maskOverlayAll", json!({})); + assert!(h.app.ui.mask_overlay_all); + assert_eq!(h.app.session.active_mask, Some(2)); + // Pins add their own <maskPin:…> elements; keep them out of the handle count. + exec(&mut h, "view.maskPins", json!({"show": false})); + h.settle(SETTLE); + + let handles_of = |h: &Headless, id: usize| h.app.widgets.iter().filter(|(w, _)| w.starts_with(&format!("maskHandle:{id}:"))).count(); + // The selected mask keeps its 4 edge handles and its rotation grip. + assert_eq!(handles_of(&h, 2), 5, "the selected mask keeps its handles"); + // The other visible mask draws its outline but registers no handle: it is not draggable. + assert_eq!(handles_of(&h, 1), 0, "an unselected mask must not become draggable"); + // …while a mask with no components has nothing to outline and nothing to grab either. + exec(&mut h, "mask.add", json!({"kind": "luminanceRange"})); + exec(&mut h, "mask.addComponent", json!({"kind": "radial", "op": "add", "center": [0.5, 0.8], "rx": 0.08, "ry": 0.08})); + assert_eq!(h.app.session.active_mask, Some(3)); + assert_eq!(handles_of(&h, 1), 0); + h.settle(SETTLE); +} + +/// #2210: the outlines of *unselected* masks are painted, not registered as widgets, so the way to +/// observe them is the rendered pixels. With the all-masks overlay on, the unselected mask's +/// ellipse edge must carry white stroke pixels the photo alone does not have. +#[test] +fn all_masks_overlay_paints_the_outline_of_an_unselected_mask() { + let mut h = detail("panel.masking"); + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.3, 0.5], "rx": 0.12, "ry": 0.12})); + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.7, 0.5], "rx": 0.12, "ry": 0.12})); + assert_eq!(h.app.session.active_mask, Some(2)); + exec(&mut h, "view.maskPins", json!({"show": false})); + + // Sample the whole canvas: the outline is white (alpha 170) over the photo, so the overlay adds + // near-white pixels along the unselected mask's ellipse edge. + let white_pixels = |h: &mut Headless, on: bool| -> usize { + let overlay = h.app.ui.mask_overlay_all; + if overlay != on { + exec(h, "view.maskOverlayAll", json!({})); + } + assert_eq!(h.app.ui.mask_overlay_all, on); + h.settle(SETTLE); + let px = h.view.paint(&Default::default()); + px.pixels.iter().filter(|p| p.r() > 200 && p.g() > 200 && p.b() > 200).count() + }; + let off = white_pixels(&mut h, false); + let on = white_pixels(&mut h, true); + assert!(on > off, "the unselected mask's outline must add white pixels: off {off}, on {on}"); +} + /// #518: holding the brush still, however long, paints the same feathered spot as a quick press. #[test] fn holding_the_brush_still_does_not_harden_the_spot() { @@ -1120,6 +1192,29 @@ fn edit_in_external_editor_opens_the_copy() { h.settle(SETTLE); } +/// An editor that won't open the copy: the copy is in the library already, so the command succeeds +/// with `failed` set and a toast saying why, instead of an error a script would retry (and make +/// another copy each time). +#[test] +fn edit_in_reports_an_editor_that_wont_open_without_failing() { + let dir = std::env::temp_dir().join(format!("lc-ui-ext-fail-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let services = Services { png: None, open_with: Some(Box::new(|_: &str, _: &str| Err("the editor quit".into()))), ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + h.app.ui.settings.external_editor = "PhotoCraft".into(); + let n = h.app.session.catalog.len(); + let r = h.request("engine.execute", json!({"command": "photo.editInExternal", "params": {"dir": dir.to_string_lossy()}}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["failed"], "the editor quit", "{r}"); + assert_eq!(h.app.session.catalog.len(), n + 1, "the copy stays in the library"); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("the editor quit"), "{toast}"); + let _ = std::fs::remove_dir_all(&dir); + h.settle(SETTLE); +} + /// Edit in PhotoCraft: a PSD copy (what PhotoCraft saves back to), handed to "PhotoCraft" for /// the host to find; when the host can't find it, no copy is made. #[test] @@ -1152,6 +1247,12 @@ fn edit_in_photocraft_opens_a_psd_copy() { let r = h.request("engine.execute", params.clone(), T); assert_eq!(r["ok"], false, "{r}"); assert_eq!((h.app.session.catalog.len(), opened.lock().unwrap().len()), (n, 0), "no copy without PhotoCraft"); + // and it says so, however it was asked for (menu, shortcut, context menu) + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(!toast.is_empty(), "the missing editor is reported"); + h.app.ui.toast = None; + let r = h.app.run("photo.editInPhotoCraft", json!({})); + assert!(r.is_err() && h.app.ui.toast.is_some(), "{r:?} {:?}", h.app.ui.toast); installed.store(true, std::sync::atomic::Ordering::SeqCst); let r = h.request("engine.execute", params, T); assert_eq!(r["ok"], true, "{r}"); diff --git a/crates/ui-egui/src/tests_menubar.rs b/crates/ui-egui/src/tests_menubar.rs index 758ac595ab..a67796de86 100644 --- a/crates/ui-egui/src/tests_menubar.rs +++ b/crates/ui-egui/src/tests_menubar.rs @@ -18,7 +18,14 @@ fn app(size: [f32; 2]) -> Headless { } fn widget(h: &Headless, id: &str) -> Option<egui::Rect> { - h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) + h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// The scroll viewport clips a menu row independently of the popup's outer rectangle, which +/// also contains its scroll arrows. Target the portion a real pointer can reach. +fn visible_rect(h: &Headless, id: &str) -> Option<egui::Rect> { + let hit = h.app.widget_hits.iter().rev().find(|(w, _)| w == id)?.1; + Some(h.view.ctx.layer_transform_to_global(hit.layer_id).map_or(hit.interact_rect, |t| t * hit.interact_rect)) } fn widgets_with(h: &Headless, prefix: &str) -> Vec<(String, egui::Rect)> { @@ -44,6 +51,7 @@ fn no_menu_or_submenu_covers_the_menu_bar() { // scrolled menu's submenus must open upward. let sizes = [[1280.0, 703.0], [1160.0, 560.0]]; let mut submenus = 0; + let mut clipped_rows = 0; for size in sizes { for top in ["Photo", "File", "View"] { let what = format!("{size:?} {top}"); @@ -57,7 +65,16 @@ fn no_menu_or_submenu_covers_the_menu_bar() { let level = widget(&h, "menu-level:1").unwrap_or_else(|| panic!("{what}: menu")); let rows: Vec<String> = widgets_with(&h, "menusub:").into_iter().filter(|(_, r)| level.contains_rect(*r)).map(|(id, _)| id).collect(); for row in rows { - let r = h.request("ui.hoverWidget", json!({"id": row}), T); + let full = widget(&h, &row).unwrap_or_else(|| panic!("{what}: no {row}")); + let visible = visible_rect(&h, &row).unwrap_or_else(|| panic!("{what}: no hit area for {row}")); + assert!(full.is_positive() && visible.is_positive(), "{what}: {row} has no visible portion"); + let at = visible.center(); + if !visible.contains(full.center()) { + clipped_rows += 1; + } + let fx = (at.x - full.left()) / full.width(); + let fy = (at.y - full.top()) / full.height(); + let r = h.request("ui.hoverWidget", json!({"id": row, "fx": fx, "fy": fy}), T); assert_eq!(r["ok"], true, "{what}: {r}"); h.settle(SETTLE); if widget(&h, "menu-level:2").is_none() { @@ -69,6 +86,7 @@ fn no_menu_or_submenu_covers_the_menu_bar() { } } assert!(submenus >= 6, "opened {submenus} submenus"); + assert!(clipped_rows > 0, "exercise a row whose geometric centre is clipped away"); } #[test] diff --git a/crates/ui-egui/src/tests_merge_preview.rs b/crates/ui-egui/src/tests_merge_preview.rs new file mode 100644 index 0000000000..09419758de --- /dev/null +++ b/crates/ui-egui/src/tests_merge_preview.rs @@ -0,0 +1,74 @@ +//! Headless tests of the Photo Merge dialog's preview: click to zoom in, drag to pan, click to fit. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(120); + +fn rect(h: &Headless, id: &str) -> egui::Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +fn press(h: &mut Headless, pos: egui::Pos2, pressed: bool) { + h.app.synthetic.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); +} + +fn click_at(h: &mut Headless, pos: egui::Pos2) { + h.app.synthetic.push(egui::Event::PointerMoved(pos)); + press(h, pos, true); + press(h, pos, false); + h.settle(T); +} + +#[test] +fn a_click_on_the_merge_preview_zooms_in_and_a_drag_pans() { + let dir = std::env::temp_dir().join(format!("lc-merge-zoom-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut paths = Vec::new(); + for (i, bytes) in lightcraft_merge::synth::bracket_dngs(1600, 1200, &[-2.0, 0.0, 2.0]).unwrap().into_iter().enumerate() { + let p = dir.join(format!("IMG_{i}.dng")); + std::fs::write(&p, bytes).unwrap(); + paths.push(p.to_string_lossy().to_string()); + } + let mut session = lightcraft_engine::Session::new().with_fs(); + let r = session.execute("library.import", &json!({"paths": paths})).unwrap(); + let ids: Vec<u64> = r["imported"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + session.execute("library.select", &json!({"ids": ids})).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1200.0, 800.0], 1.0); + h.settle(T); + crate::merge::open(&mut h.app, "merge.hdr").unwrap(); + assert!(h.step_until(T, |h| h.app.merge.preview.is_some() && h.app.merge.preview_task.is_none()), "the preview rendered"); + h.settle(T); + assert_eq!(h.app.merge.zoom, None, "the preview opens fitted"); + + let area = rect(&h, "merge.preview"); + // right of and above the middle: a point of the fitted image whatever its aspect + let at = area.center() + egui::vec2(area.width() * 0.2, area.height() * -0.1); + click_at(&mut h, at); + let (u, v) = h.app.merge.zoom.expect("the click zoomed in"); + assert!(u > 0.55 && v < 0.5, "zoomed in on the point clicked ({u}, {v})"); + + // drag left: the image follows the pointer, so a point further right comes to the middle + let from = area.center(); + let to = from - egui::vec2(60.0, 0.0); + h.app.synthetic.push(egui::Event::PointerMoved(from)); + press(&mut h, from, true); + h.step(); + for i in 1..=6 { + h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 6.0))); + h.step(); + } + press(&mut h, to, false); + h.settle(T); + let (u2, v2) = h.app.merge.zoom.expect("still zoomed in after a drag"); + assert!(u2 > u + 0.01 && (v2 - v).abs() < 1e-3, "the drag panned right ({u}, {v}) → ({u2}, {v2})"); + + click_at(&mut h, area.center()); + assert_eq!(h.app.merge.zoom, None, "a second click fits the preview again"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/tests_model_setup.rs b/crates/ui-egui/src/tests_model_setup.rs index 1366b745a9..22c4ca7f92 100644 --- a/crates/ui-egui/src/tests_model_setup.rs +++ b/crates/ui-egui/src/tests_model_setup.rs @@ -90,7 +90,7 @@ fn amount(app: &LightcraftApp, id: PhotoId) -> f64 { app.session.develop_of(id).unwrap().enhance.denoise } fn resume(app: &mut LightcraftApp) { - model_setup::pump(app, &egui::Context::default()); + model_setup::pump(app, &egui::Context::default(), app.tick_now()); } #[test] diff --git a/crates/ui-egui/src/tests_open_lightroom.rs b/crates/ui-egui/src/tests_open_lightroom.rs index cddfa2bef5..d97f9d0e81 100644 --- a/crates/ui-egui/src/tests_open_lightroom.rs +++ b/crates/ui-egui/src/tests_open_lightroom.rs @@ -1,6 +1,6 @@ //! Issue #891: File ▸ Open Library… given a Lightroom Classic catalog folder doesn't make a //! LightCraft library inside it. The library open now stays, and a dialog offers Import Lightroom -//! Catalog… with the catalog found, which starts the import of that `.lrcat`. +//! Catalog… with the catalog found, which asks where that `.lrcat` goes (#2672), then imports it. use std::time::Duration; @@ -47,6 +47,7 @@ fn open_library_on_a_lightroom_catalog_offers_its_import() { pick_folder: Some(Box::new(move || Some(picked.clone()))), png: Some(Box::new(png)), write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + write_new: Some(Box::new(lightcraft_engine::export::write_file_new)), ..Default::default() }; let mut h = Headless::new(LightcraftApp::new(session, services), [1200.0, 800.0], 1.0); @@ -84,12 +85,23 @@ fn open_library_on_a_lightroom_catalog_offers_its_import() { assert_eq!(r["lightroomCatalog"], json!(lrcat.to_string_lossy()), "{r}"); h.step(); h.step(); - // Import Lightroom Catalog…: the import of that catalog starts (no file dialog), into the - // library open now. (This fake catalog then fails to read: only its path matters here.) + // Import Lightroom Catalog…: no file dialog, the window that asks where that catalog goes + // (#2672) takes its place, as File ▸ Import Lightroom Catalog… does + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T)["ok"], true); + h.step(); + assert!( + matches!(&h.app.ui.dialog, Some(Dialog::LightroomDestination { catalog, .. }) if *catalog == lrcat.to_string_lossy()), + "{:?}", + h.app.ui.dialog + ); + // Merge: the import of that catalog starts, into the library open now. (This fake catalog + // then fails to read: only its path matters here.) + assert_eq!(h.request("ui.clickWidget", json!({"id": "radio:lightroomDestination-open"}), T)["ok"], true); + h.step(); assert_eq!(h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T)["ok"], true); h.step(); // A fast read failure can already have replaced the offer with its lasting result. - assert!(!matches!(h.app.ui.dialog, Some(Dialog::LightroomCatalog { .. }))); + assert!(!matches!(h.app.ui.dialog, Some(Dialog::LightroomCatalog { .. } | Dialog::LightroomDestination { .. }))); assert!(h.step_until(T, |h| h.app.lightroom.is_none())); assert!(matches!(&h.app.ui.dialog, Some(Dialog::LightroomResult { summary, first: None, .. }) if summary.contains("failed"))); let last = h.app.lightroom_last.clone().unwrap_or_default(); diff --git a/crates/ui-egui/src/tests_preset_favorites.rs b/crates/ui-egui/src/tests_preset_favorites.rs new file mode 100644 index 0000000000..0dc9900ea0 --- /dev/null +++ b/crates/ui-egui/src/tests_preset_favorites.rs @@ -0,0 +1,81 @@ +//! Issue #1999: starred presets are listed in a Favorites section at the top of the Presets panel, +//! as starred profiles are in the Profile browser, and stay in their own group too. + +use crate::{LightcraftApp, Services, headless::Headless}; +use serde_json::json; + +/// A headless app on the demo library with the Presets panel open and laid out. +fn app() -> Headless { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + h.app.run("panel.presets", json!({})).unwrap(); + for _ in 0..5 { + h.step(); + } + h +} + +/// Where the widget registered as `id` was drawn in the last frame, if it was. +fn rect(h: &Headless, id: &str) -> Option<egui::Rect> { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// The topmost preset group header on screen (the Favorites header is `presetFavorites`). +fn first_group(h: &Headless) -> String { + let groups = h.app.widgets.iter().filter(|(w, _)| w.starts_with("presetGroup:") || w == "presetFavorites"); + groups.min_by(|a, b| a.1.top().total_cmp(&b.1.top())).map(|(w, _)| w.clone()).unwrap() +} + +/// Starring two presets makes a Favorites section the first header, listing them in list order +/// right under it, while each stays in its own group too. +#[test] +fn starred_presets_are_listed_in_favorites_on_top() { + let mut h = app(); + assert!(rect(&h, "presetFavorites").is_none(), "no section while nothing is starred"); + let first = h.app.session.presets.first().map(|p| p.id.clone()).unwrap(); + let last = h.app.session.presets.last().map(|p| p.id.clone()).unwrap(); + h.app.run("preset.favorite", json!({"id": last})).unwrap(); + h.app.run("preset.favorite", json!({"id": first})).unwrap(); + for _ in 0..3 { + h.step(); + } + assert_eq!(first_group(&h), "presetFavorites"); + let header = rect(&h, "presetFavorites").unwrap(); + // in list order, right under the header + let a = rect(&h, &format!("presetFavorite:{first}")).unwrap(); + let b = rect(&h, &format!("presetFavorite:{last}")).unwrap(); + assert!(header.bottom() <= a.top() && a.top() < b.top(), "{header:?} {a:?} {b:?}"); + // still in its own group + assert!(rect(&h, &format!("preset:{first}")).is_some()); + // unstarring the last one removes the section + for id in [&first, &last] { + h.app.run("preset.favorite", json!({"id": id})).unwrap(); + } + for _ in 0..3 { + h.step(); + } + assert!(rect(&h, "presetFavorites").is_none()); +} + +/// A user group named "Favorites" or "favorites" keeps its own header, apart from the section's: a +/// click aimed at either id lands on the right row (the widget lookup takes the last match). +#[test] +fn user_groups_named_favorites_keep_their_own_header() { + let mut h = app(); + let id = h.app.session.presets.first().map(|p| p.id.clone()).unwrap(); + h.app.run("preset.favorite", json!({"id": id})).unwrap(); + for group in ["Favorites", "favorites"] { + h.app.run("preset.create", json!({"name": format!("Mine in {group}"), "group": group})).unwrap(); + } + for _ in 0..3 { + h.step(); + } + let section = rect(&h, "presetFavorites").unwrap(); + for group in ["Favorites", "favorites"] { + let id = format!("presetGroup:{group}"); + let user = rect(&h, &id).unwrap_or_else(|| panic!("the user's {group:?} group is listed")); + assert_ne!(user, section, "{id} is its own row"); + assert_eq!(h.app.widgets.iter().filter(|(w, _)| *w == id).count(), 1, "{id} names one row"); + } + assert_eq!(h.app.widgets.iter().filter(|(w, _)| w == "presetFavorites").count(), 1); +} diff --git a/crates/ui-egui/src/tests_preview_limit.rs b/crates/ui-egui/src/tests_preview_limit.rs index 070921256b..e87e523551 100644 --- a/crates/ui-egui/src/tests_preview_limit.rs +++ b/crates/ui-egui/src/tests_preview_limit.rs @@ -284,6 +284,25 @@ mod in_the_loupe { assert_eq!(h.app.region_view.map(|r| r.settings), Some(plain.settings), "back to the plain window"); } + // Given a diagnostic overlay (Visualize Spots), when I zoom to 1:1, then the visible part is a + // window render carrying the overlay, over a canvas-sized whole frame, as without it + #[test] + fn visualize_spots_at_one_to_one_is_a_window() { + let (mut h, native) = detail(); + h.request("engine.execute", json!({"command": "view.zoom100"}), T); + h.settle(SETTLE); + let plain = h.app.region_view.expect("a window render without the overlay"); + let r = h.request("ui.menu.invoke", json!({"id": "view.visualizeSpots"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.visualize_spots); + let main = rendered_long_edge(&h); + assert!(main <= 2560 && main < native, "native {native}: the whole-frame render is {main}"); + let spots = h.app.region_view.expect("a window render with the overlay"); + assert_eq!(spots.full.0.max(spots.full.1), native, "cut from the photo's own pixels"); + assert_ne!(spots.settings, plain.settings, "the overlay is part of the window's look"); + } + // Given the user capped the preview at 1600 px, then 1:1 is rendered no larger than that #[test] fn an_explicit_limit_still_caps_one_to_one() { @@ -530,13 +549,16 @@ mod in_the_loupe { assert!(main <= small, "the draft is {main} px, a small one at most {small}"); } - // Given soft proofing (rendered on the CPU even with a GPU), a drag drafts small (#330) + // Given soft proofing against an output-device profile (rendered on the CPU even with a GPU), a + // drag drafts small (#330); proofs into an output space run on the GPU like any render #[test] fn a_soft_proofed_drag_drafts_small() { // the GPU device up front (the loupe never waits for it): with one, this is the case where // the GPU is there and the render still goes to the CPU let _ = lightcraft_engine::gpu::available(); let (mut h, _) = detail(); + let lut = lightcraft_pipeline::ProofLut::new(2, vec![[0.5, 0.5, 0.5, 0.0]; 8]).expect("a valid table"); + h.app.ui.proof.profile = lightcraft_pipeline::register_proof_profile(0x5eed_9f01, lut); h.app.ui.soft_proof = true; h.settle(SETTLE); let (main, small) = drag_exposure(&mut h); diff --git a/crates/ui-egui/src/tests_print.rs b/crates/ui-egui/src/tests_print.rs index 28838f4093..25f7014ee1 100644 --- a/crates/ui-egui/src/tests_print.rs +++ b/crates/ui-egui/src/tests_print.rs @@ -214,6 +214,50 @@ fn templates_save_apply_and_delete_from_the_dialog() { assert!(h.app.session.print_templates.is_empty()); } +#[test] +fn templates_export_and_import_from_the_dialog() { + let dir = std::env::temp_dir().join(format!("lightcraft-ui-print-templates-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Sheet 5x6.lcprint").to_string_lossy().to_string(); + let suggested = Arc::new(Mutex::new(Vec::<String>::new())); + let names = suggested.clone(); + let (save_to, pick) = (file.clone(), file.clone()); + let services = Services { + save_print_template: Some(Box::new(move |name: &str| { + names.lock().unwrap().push(name.to_string()); + Some(save_to.clone()) + })), + pick_print_templates: Some(Box::new(move || vec![pick.clone()])), + ..Default::default() + }; + let mut h = demo(services); + open_print(&mut h); + click(&mut h, "button:printStyle-1"); + cmd(&mut h, "print.set", json!({"layout": {"grid": {"columns": 5, "rows": 6}}})); + h.app.ui.print.template_name = "Sheet 5x6".into(); + click(&mut h, "button:printSaveTemplate"); + click(&mut h, "button:printTemplateExport-0"); + assert_eq!(*suggested.lock().unwrap(), vec!["Sheet 5x6.lcprint".to_string()]); + assert!(std::path::Path::new(&file).is_file()); + click(&mut h, "button:printTemplateImport"); + let names: Vec<&str> = h.app.session.print_templates.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(names, ["Sheet 5x6", "Sheet 5x6 (2)"]); + assert_eq!(h.app.session.print_templates[1].settings, h.app.session.print_templates[0].settings); + assert!(has(&h, "button:printTemplateExport-1"), "the imported template is listed"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn template_files_need_the_hosts_file_dialogs() { + let mut h = demo(Services::default()); + open_print(&mut h); + h.app.ui.print.template_name = "Plain".into(); + click(&mut h, "button:printSaveTemplate"); + assert!(has(&h, "button:printTemplateApply-0")); + assert!(!has(&h, "button:printTemplateExport-0"), "no save dialog: no Export…"); + assert!(!has(&h, "button:printTemplateImport"), "no open dialog: no Import…"); +} + #[test] fn print_to_pdf_picks_a_file_and_runs_in_the_background() { let asked = Arc::new(Mutex::new(Vec::<crate::pick::PickRequest>::new())); diff --git a/crates/ui-egui/src/tests_progress.rs b/crates/ui-egui/src/tests_progress.rs new file mode 100644 index 0000000000..09e9234a0c --- /dev/null +++ b/crates/ui-egui/src/tests_progress.rs @@ -0,0 +1,284 @@ +//! Progress bars, spinners and busy buttons: the fraction is always a sane number, a bar is +//! announced as progress with its percentage and reachable by its id, a busy button is announced +//! busy, ignores clicks and keeps its width, and a thumbnail's placeholder stands apart from what +//! it sits on in every theme. + +use egui::{Pos2, Rect, pos2, vec2}; + +use crate::button::{Button, contrast}; +use crate::icons::Icon; +use crate::progress::{Progress, clamp_fraction, fraction_of, spinner}; +use crate::theme::{ThemeKind, Tokens}; + +/// What a screen reader gets for one node. +#[derive(Debug, Clone, PartialEq)] +struct Node { + role: String, + label: String, + busy: bool, + value: Option<f64>, +} + +/// Run three frames of `draw` (pointer `events` in the second); return the nodes of the last +/// frame with an accessibility tree, the automation ids registered in the last frame, and what +/// `draw` returned. +fn frames<T: Default>(events: Vec<egui::Event>, mut draw: impl FnMut(&mut egui::Ui) -> T) -> (Vec<Node>, Vec<(String, Rect)>, T) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let (mut nodes, mut ids, mut last) = (Vec::new(), Vec::new(), T::default()); + for frame in 0..3 { + let raw = egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), + events: if frame == 1 { events.clone() } else { Vec::new() }, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| last = draw(ui)); + out.textures_delta.clear(); + ids = crate::widgets::take_registry(&ctx); + if let Some(update) = out.platform_output.accesskit_update.take() { + nodes = update + .nodes + .iter() + .map(|(_, n)| Node { + role: format!("{:?}", n.role()), + label: n.label().unwrap_or_default().to_string(), + busy: n.is_busy(), + value: n.numeric_value(), + }) + .collect(); + } + } + (nodes, ids, last) +} + +#[test] +fn the_fraction_is_always_between_nothing_and_all() { + assert_eq!(clamp_fraction(f32::NAN), 0.0); + assert_eq!(clamp_fraction(-3.0), 0.0); + assert_eq!(clamp_fraction(7.5), 1.0); + assert_eq!(clamp_fraction(f32::INFINITY), 1.0); + assert_eq!(clamp_fraction(f32::NEG_INFINITY), 0.0); + assert_eq!(clamp_fraction(0.25), 0.25); + assert_eq!(Progress::new(Some(f32::NAN)).fraction(), Some(0.0)); + assert_eq!(Progress::new(Some(2.0)).fraction(), Some(1.0)); + assert_eq!(Progress::new(None).fraction(), None); +} + +#[test] +fn an_unknown_total_is_an_indeterminate_bar_not_an_empty_one() { + assert_eq!(fraction_of(0, 0), None); + assert_eq!(fraction_of(5, 0), None); + assert_eq!(fraction_of(0, 10), Some(0.0)); + assert_eq!(fraction_of(5, 10), Some(0.5)); + assert_eq!(fraction_of(20, 10), Some(1.0)); +} + +#[test] +fn a_bar_is_progress_with_a_value_and_reachable_by_its_id() { + let (nodes, ids, _) = frames(Vec::new(), |ui| { + Progress::new(Some(0.42)).label("Making the denoised picture… 42%").widget("denoise:progress").show(ui); + }); + let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("no progress node: {nodes:?}")); + assert_eq!(bar.label, "Making the denoised picture… 42%"); + assert_eq!(bar.value, Some(42.0)); + assert!(ids.iter().any(|(id, r)| id == "denoise:progress" && r.width() > 0.0), "{ids:?}"); +} + +#[test] +fn an_indeterminate_bar_says_progress_without_a_value_and_is_drawn() { + let (nodes, ids, width) = frames(Vec::new(), |ui| Progress::new(None).label("Starting…").widget("p:x").show(ui).rect.width()); + let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); + assert_eq!(bar.value, None); + assert!(ids.iter().any(|(id, _)| id == "p:x")); + assert!(width >= 96.0, "fills the width the layout has"); +} + +#[test] +fn a_bar_fills_the_layout_unless_given_a_width() { + let (_, _, (fill, fixed, tiny_room)) = frames(Vec::new(), |ui| { + let fill = Progress::new(Some(0.5)).show(ui).rect.width(); + let fixed = Progress::new(Some(0.5)).width(150.0).show(ui).rect.width(); + let tiny_room = ui.scope(|ui| { + ui.set_max_width(40.0); + Progress::new(Some(0.5)).show(ui).rect.width() + }); + (fill, fixed, tiny_room.inner) + }); + assert!(fill > 300.0, "fills: {fill}"); + assert_eq!(fixed, 150.0); + assert!(tiny_room >= 96.0, "never a sliver: {tiny_room}"); +} + +#[test] +fn a_spinner_takes_the_room_it_is_given() { + let (_, _, size) = frames(Vec::new(), |ui| spinner(ui, 14.0).rect.size()); + assert_eq!(size, vec2(14.0, 14.0)); +} + +fn click_at(at: Pos2) -> Vec<egui::Event> { + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, + ] +} + +#[test] +fn a_busy_button_ignores_clicks_and_is_announced_busy() { + let place = Rect::from_min_size(Pos2::ZERO, vec2(120.0, 30.0)); + let click = |busy: bool| { + let mut clicked = false; + let (nodes, _, ()) = frames(click_at(pos2(40.0, 15.0)), |ui| clicked |= Button::new("Analyze").busy(busy).show_at(ui, place).clicked()); + (nodes, clicked) + }; + let (nodes, clicked) = click(true); + assert!(!clicked, "a busy button does nothing"); + let node = nodes.iter().find(|n| n.role == "Button" && n.label == "Analyze").unwrap_or_else(|| panic!("{nodes:?}")); + assert!(node.busy, "announced busy"); + + let (nodes, clicked) = click(false); + assert!(clicked, "the same button, not busy, is clicked"); + assert!(!nodes.iter().any(|n| n.busy), "{nodes:?}"); +} + +#[test] +fn a_busy_button_stays_reachable_by_the_keyboard() { + let place = Rect::from_min_size(Pos2::ZERO, vec2(120.0, 30.0)); + let mut asked = false; + let (_, _, focused) = frames(Vec::new(), |ui| { + let r = Button::new("Analyze").busy(true).show_at(ui, place); + if !std::mem::replace(&mut asked, true) { + r.request_focus(); + } + r.has_focus() + }); + assert!(focused, "focus is kept while it works"); +} + +#[test] +fn a_button_keeps_its_width_while_busy() { + for (text, icon) in [("Analyze", None), ("Analyze", Some(Icon::Trash)), ("", Some(Icon::Trash))] { + for small in [false, true] { + let (_, _, (idle, busy)) = frames(Vec::new(), |ui| { + let mut make = |b: bool| { + let mut btn = if text.is_empty() { Button::icon_only(Icon::Trash, "Remove") } else { Button::new(text) }; + if let Some(i) = icon { + btn = btn.icon(i); + } + if small { + btn = btn.small(); + } + btn.busy(b).show(ui).rect.size() + }; + (make(false), make(true)) + }); + assert_eq!(idle, busy, "{text:?} {icon:?} small={small}"); + } + } +} + +#[test] +fn the_thumbnail_placeholder_stands_apart_in_every_theme() { + for kind in ThemeKind::ALL { + let t = Tokens::for_kind(kind); + for (name, behind) in [("grid", t.grid_bg), ("cell", t.cell), ("selected cell", t.cell_selected), ("canvas", t.canvas)] { + let c = contrast(t.skeleton, behind); + // the light themes' surfaces are close together, so the placeholder has to be set + // further off them to read at all + let floor = if matches!(kind, ThemeKind::Silver | ThemeKind::Paper) { 1.15 } else { 1.1 }; + assert!(c >= floor, "{kind:?}: the placeholder on the {name} is {c:.2}:1"); + } + let mark = contrast(t.text, t.skeleton); + assert!(mark >= 3.0, "{kind:?}: the failure mark on the placeholder is {mark:.2}:1"); + } +} + +#[test] +fn a_failed_filmstrip_thumbnail_is_announced_with_its_reason() { + let spoken = |failed: bool| { + let (nodes, _, _) = frames(Vec::new(), |ui| { + let resp = ui.interact(Rect::from_min_size(pos2(10.0, 10.0), vec2(120.0, 80.0)), egui::Id::unique("film-test"), egui::Sense::click()); + crate::widgets::announce(&resp, crate::panels::detail::film_spoken("IMG_0001.jpg", failed)); + }); + nodes.into_iter().find(|n| n.role == "Button").map(|n| n.label) + }; + assert_eq!(spoken(false).as_deref(), Some("IMG_0001.jpg")); + assert_eq!(spoken(true).as_deref(), Some("IMG_0001.jpg, This photo can't be opened")); +} + +#[test] +fn a_failed_filmstrip_thumbnail_without_a_file_name_has_no_leading_comma() { + assert_eq!(crate::panels::detail::film_spoken("", true), "This photo can't be opened"); + assert_eq!(crate::panels::detail::film_spoken("", false), ""); +} + +#[test] +fn the_sam_bar_keeps_its_name_and_height_while_the_size_is_unknown() { + let (nodes, _, (known, unknown)) = frames(Vec::new(), |ui| { + let known = crate::panels::masking::sam_download_bar(ui, 5, 10, 200.0).rect.height(); + let unknown = crate::panels::masking::sam_download_bar(ui, 0, 0, 200.0).rect.height(); + (known, unknown) + }); + assert_eq!(known, unknown); + let bars: Vec<_> = nodes.iter().filter(|n| n.role == "ProgressIndicator").collect(); + assert_eq!(bars.len(), 2, "{nodes:?}"); + assert!(bars.iter().all(|b| b.label.starts_with("SAM 3")), "{bars:?}"); +} + +#[test] +fn the_denoise_bars_keep_their_widths_in_a_wide_container() { + let (_, ids, (detail, settings, unknown)) = frames(Vec::new(), |ui| { + let detail = crate::panels::denoise::detail_bar(ui, 3, 10).rect.width(); + let settings = crate::panels::denoise::settings_bar(ui, 3, 10, "Denoising a.jpg: 3 of 10 tiles".into()).rect.width(); + let unknown = crate::panels::denoise::detail_bar(ui, 0, 0).rect.width(); + (detail, settings, unknown) + }); + assert_eq!((detail, settings, unknown), (240.0, 380.0, 240.0)); + assert!(ids.iter().any(|(id, _)| id == "denoise:settingsProgress")); +} + +#[test] +fn the_denoise_bar_label_and_its_accessible_value_agree() { + // the number drawn on the bar is the one announced, and exact decimals stay exact + for (done, total, says) in + [(3, 7, 42.0), (53, 100, 53.0), (59, 100, 59.0), (29, 100, 29.0), (99, 100, 99.0), (100, 100, 100.0), (999, 1000, 99.0)] + { + let (nodes, _, _) = frames(Vec::new(), |ui| { + crate::panels::denoise::detail_bar(ui, done, total); + }); + let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); + let shown: f64 = bar.label.rsplit(' ').next().unwrap().trim_end_matches('%').parse().unwrap(); + assert_eq!((shown, bar.value), (says, Some(says)), "{done}/{total}: {bar:?}"); + } +} + +#[test] +fn the_sam_bar_text_and_its_accessible_value_agree() { + for (done, total, says) in [(53, 100, 53.0), (59, 100, 59.0), (29, 100, 29.0), (999, 1000, 99.0), (100, 100, 100.0)] { + let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::masking::sam_download_bar(ui, done, total, 200.0).rect.width()); + let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); + assert_eq!(bar.label, format!("SAM 3: {says} %"), "{done}/{total}"); + assert_eq!(bar.value, Some(says), "{done}/{total}"); + } +} + +#[test] +fn an_activity_bar_is_named_after_its_task() { + let task = lightcraft_engine::activity::TaskInfo { + id: 1, + kind: "export", + label: "Exporting".into(), + done: 3, + total: 25, + unit: lightcraft_engine::activity::Unit::Count, + detail: String::new(), + cancellable: true, + cancelling: false, + age_ms: 600, + }; + let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::activity::bar(ui, &task, 200.0).rect.width()); + let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); + assert_eq!(bar.label, "Exporting"); + assert_eq!(bar.value, Some(12.0)); +} diff --git a/crates/ui-egui/src/tests_quit_unsaved.rs b/crates/ui-egui/src/tests_quit_unsaved.rs index ef6fa8da48..f703c24a67 100644 --- a/crates/ui-egui/src/tests_quit_unsaved.rs +++ b/crates/ui-egui/src/tests_quit_unsaved.rs @@ -106,6 +106,44 @@ fn quitting_with_unsaved_changes_asks_first() { assert!(h.app.quit_confirmed && crate::panels::notices::may_close(&mut h.app)); } +/// "Try Saving Again" can recreate the identical unsaved prompt. It is still a new prompt: its +/// first frame is shielded and focus goes back to the safe Cancel, never the Retry button that was +/// just used. +#[test] +fn retrying_an_unsaved_prompt_resets_focus_to_safe_cancel() { + let store = Unplugged::default(); + let mut s = lightcraft_engine::Session::new(); + let stores = LibraryStores { dir: "unplugged".into(), catalog: Box::new(store.clone()), files: Box::new(MemStore::new()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + let app = LightcraftApp::new(s, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + h.step(); + store.fail.store(true, Ordering::SeqCst); + let r = h.request("engine.execute", json!({"command": "album.create", "params": {"name": "Kept"}}), T); + assert_eq!(r["ok"], false, "{r}"); + assert!(!crate::panels::notices::may_close(&mut h.app), "retried, still failing: ask"); + h.step(); + h.step(); + let focused = |h: &Headless| h.view.ctx.memory(|m| m.focused()); + let cancel = h.app.widget_hits.iter().rev().find(|(w, _)| w == "button:quitCancel").map(|(_, hit)| hit.id).expect("Cancel has a real response"); + let retry = h.app.widget_hits.iter().rev().find(|(w, _)| w == "button:quitRetry").map(|(_, hit)| hit.id).expect("Retry has a real response"); + assert_eq!(focused(&h), Some(cancel), "the safe Cancel starts focused"); + assert_eq!(h.request("ui.key", json!({"key": "Tab"}), T)["ok"], true); + assert_eq!(focused(&h), Some(retry), "Tab moved focus to Retry"); + // Activate Retry; the drive is still unplugged, so the same prompt is recreated. + assert_eq!(h.request("ui.key", json!({"key": "Space"}), T)["ok"], true); + h.step(); + h.step(); + assert!(matches!(h.app.quit_prompt, Some(crate::QuitPrompt::Unsaved(_))), "the retried save still asks"); + let cancel_after = + h.app.widget_hits.iter().rev().find(|(w, _)| w == "button:quitCancel").map(|(_, hit)| hit.id).expect("the new Cancel has a real response"); + let retry_after = + h.app.widget_hits.iter().rev().find(|(w, _)| w == "button:quitRetry").map(|(_, hit)| hit.id).expect("the new Retry has a real response"); + assert_ne!(cancel_after, retry_after); + assert_eq!(focused(&h), Some(cancel_after), "the recreated prompt reset focus to safe Cancel"); + assert!(!h.app.quit_confirmed, "nothing quit"); +} + #[test] fn damaged_settings_file_is_shown() { let files = MemStore::new(); diff --git a/crates/ui-egui/src/tests_rating.rs b/crates/ui-egui/src/tests_rating.rs new file mode 100644 index 0000000000..d473508d3c --- /dev/null +++ b/crates/ui-egui/src/tests_rating.rs @@ -0,0 +1,238 @@ +//! The star rating: clicking sets the rating, clicking the current one clears it, the row is one +//! Tab stop, the arrow keys step it, and screen readers hear every star. + +use egui::{Pos2, Rect, vec2}; + +use crate::rating::Rating; + +/// Draw `build` for a few frames. After the first, click the centre of star `click` (1 to 5) if given, +/// then press `keys`. Returns every value `build` reported and the AccessKit +/// (role, name) pairs. +fn drive(click: Option<u8>, keys: &[egui::Key], build: impl Fn(&mut egui::Ui) -> Option<u8>) -> (Vec<u8>, Vec<(String, String)>) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let mut reported = Vec::new(); + let mut nodes = Vec::new(); + let mut rects: Vec<(String, Rect)> = Vec::new(); + for frame in 0..6 { + let mut events = Vec::new(); + if frame == 1 + && let Some(n) = click + { + let want = format!("star:t:{n}"); + let at = rects.iter().find(|(id, _)| *id == want).map(|(_, r)| r.center()).unwrap_or(Pos2::ZERO); + events.push(egui::Event::PointerMoved(at)); + events.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + events.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + } + // one key per frame from the third on, so Tab has moved the focus before an arrow arrives + if frame >= 2 + && let Some(k) = keys.get(frame - 2) + { + events.push(egui::Event::Key { key: *k, physical_key: Some(*k), pressed: true, repeat: false, modifiers: Default::default() }); + } + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 200.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(v) = build(ui) { + reported.push(v); + } + }); + out.textures_delta.clear(); + let seen = crate::widgets::take_registry(&ctx); + if rects.is_empty() { + rects = seen; + } + if let Some(update) = out.platform_output.accesskit_update.take() { + nodes = update.nodes.iter().map(|(_, n)| (format!("{:?}", n.role()), n.label().unwrap_or_default().to_string())).collect(); + } + } + (reported, nodes) +} + +fn row(rating: u8) -> Rating { + Rating::new("t", rating) +} + +#[test] +fn clicking_a_star_sets_that_rating() { + let (got, _) = drive(Some(4), &[], |ui| row(2).show(ui)); + assert_eq!(got, vec![4]); +} + +#[test] +fn clicking_the_current_rating_clears_it() { + let (got, _) = drive(Some(3), &[], |ui| row(3).show(ui)); + assert_eq!(got, vec![0]); +} + +#[test] +fn hovering_alone_changes_nothing() { + // the preview is only painted; the rating is reported on click + let (got, _) = drive(None, &[], |ui| row(2).show(ui)); + assert!(got.is_empty()); +} + +/// How many stars `Rating::show` paints filled (in the star colour) after the pointer has moved to +/// the centre of star `hover` (1 to 5), if given. A filled star is ten triangles of one colour. +fn filled_stars(rating: u8, hover: Option<u8>) -> usize { + fn count(shape: &egui::Shape, colour: egui::Color32) -> usize { + match shape { + egui::Shape::Path(path) => usize::from(path.fill == colour), + egui::Shape::Vec(shapes) => shapes.iter().map(|shape| count(shape, colour)).sum(), + _ => 0, + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let colour = crate::theme::Tokens::get(&ctx).star; + let mut at = None; + let mut filled = 0; + for frame in 0..4 { + let mut events = Vec::new(); + if frame >= 1 + && let Some(at) = at + { + events.push(egui::Event::PointerMoved(at)); + } + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 200.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let _ = row(rating).show(ui); + }); + out.textures_delta.clear(); + let seen = crate::widgets::take_registry(&ctx); + if let (Some(n), true) = (hover, frame == 0) { + let want = format!("star:t:{n}"); + at = seen.iter().find(|(id, _)| *id == want).map(|(_, r)| r.center()); + assert!(at.is_some(), "star {n} is registered"); + } + filled = out.shapes.iter().map(|clipped| count(&clipped.shape, colour)).sum::<usize>() / 10; + } + filled +} + +#[test] +fn hovering_a_star_paints_the_rating_a_click_would_set() { + // the row shows 2 filled stars; the pointer over star 4 shows 4, and over star 1 shows 1 + assert_eq!(filled_stars(2, None), 2); + assert_eq!(filled_stars(2, Some(4)), 4); + assert_eq!(filled_stars(2, Some(1)), 1, "hovering a lower star previews the lower rating"); +} + +#[test] +fn a_screen_reader_hears_every_star_with_its_state() { + let (_, nodes) = drive(None, &[], |ui| row(2).show(ui)); + for n in 1..=5 { + let name = format!("{n} ★"); + assert!(nodes.iter().any(|(role, label)| role == "Button" && *label == name), "{name}: {nodes:?}"); + } +} + +#[test] +fn the_arrow_keys_step_the_rating_of_a_focused_star() { + // Tab focuses the first star; the row shows 3, so → asks for 4 and ← for 2 + let (got, _) = drive(None, &[egui::Key::Tab, egui::Key::ArrowRight], |ui| row(3).show(ui)); + assert_eq!(got, vec![4], "{got:?}"); + let (got, _) = drive(None, &[egui::Key::Tab, egui::Key::ArrowLeft], |ui| row(3).show(ui)); + assert_eq!(got, vec![2], "{got:?}"); +} + +#[test] +fn arrow_keys_do_nothing_when_no_star_is_focused() { + let (got, _) = drive(None, &[egui::Key::ArrowRight], |ui| row(3).show(ui)); + assert!(got.is_empty(), "{got:?}"); +} + +/// Feed the shown rating back each frame, with other focusable widgets on both sides. +fn step_with_neighbours(start: u8, keys: &[egui::Key]) -> Vec<u8> { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let rating = std::cell::Cell::new(start); + let mut seen = Vec::new(); + // a key every frame, Tab then an arrow straight away + for frame in 0..keys.len() + 3 { + let mut events = Vec::new(); + if let Some(k) = frame.checked_sub(1).and_then(|f| keys.get(f)) { + events.push(egui::Event::Key { key: *k, physical_key: Some(*k), pressed: true, repeat: false, modifiers: Default::default() }); + } + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + ui.horizontal(|ui| { + let _ = ui.button("left neighbour"); + if let Some(r) = row(rating.get()).show(ui) { + rating.set(r); + } + let _ = ui.button("right neighbour"); + }); + }); + out.textures_delta.clear(); + seen.push(rating.get()); + } + seen +} + +#[test] +fn arrows_keep_stepping_between_other_focusable_widgets() { + use egui::Key::*; + // Tab, Tab: the left neighbour, then star 1 + let seen = step_with_neighbours(5, &[Tab, Tab, ArrowLeft, ArrowLeft, ArrowLeft, ArrowLeft, ArrowLeft]); + assert_eq!(seen.last(), Some(&0), "{seen:?}"); + let seen = step_with_neighbours(0, &[Tab, Tab, ArrowRight, ArrowRight, ArrowRight, ArrowRight, ArrowRight, ArrowLeft]); + assert_eq!(seen.last(), Some(&4), "{seen:?}"); +} + +#[test] +fn a_rating_row_is_one_tab_stop() { + use egui::Key::Tab; + // left neighbour, one stop for the five stars, right neighbour: the third Tab is already past the row + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut focused = Vec::new(); + for frame in 0..5 { + let events = if frame >= 1 { + vec![egui::Event::Key { key: Tab, physical_key: Some(Tab), pressed: true, repeat: false, modifiers: Default::default() }] + } else { + Vec::new() + }; + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() }; + let mut right = None; + let mut out = ctx.run_ui(raw, |ui| { + ui.horizontal(|ui| { + let _ = ui.button("left neighbour"); + let _ = row(3).show(ui); + right = Some(ui.button("right neighbour").id); + }); + }); + out.textures_delta.clear(); + focused.push(right.is_some_and(|id| ctx.memory(|m| m.has_focus(id)))); + } + // frames 1 to 3 press Tab: left neighbour, the row, right neighbour + assert_eq!(focused, vec![false, false, false, true, false], "{focused:?}"); +} + +#[test] +fn a_rating_changed_from_outside_moves_the_focus_to_the_tab_stop() { + use egui::Key::Tab; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let rating = std::cell::Cell::new(2u8); + let mut stars_focused = Vec::new(); + for frame in 0..5 { + // frame 1: Tab focuses the row's stop (star 2); frame 2: the rating changes elsewhere to 5 + if frame == 2 { + rating.set(5); + } + let events = if frame == 1 { + vec![egui::Event::Key { key: Tab, physical_key: Some(Tab), pressed: true, repeat: false, modifiers: Default::default() }] + } else { + Vec::new() + }; + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let _ = row(rating.get()).show(ui); + stars_focused = (0..5).map(|i| ctx.memory(|m| m.has_focus(ui.scope_id().with(("rating-star", "t", i as u8))))).collect(); + }); + out.textures_delta.clear(); + } + assert_eq!(stars_focused, vec![false, false, false, false, true], "{stars_focused:?}"); +} diff --git a/crates/ui-egui/src/tests_scroll.rs b/crates/ui-egui/src/tests_scroll.rs index dd999108a0..da61d4836f 100644 --- a/crates/ui-egui/src/tests_scroll.rs +++ b/crates/ui-egui/src/tests_scroll.rs @@ -215,6 +215,7 @@ fn notch(h: &mut Headless, dy: f32) { unit: egui::MouseWheelUnit::Line, delta: egui::vec2(0.0, dy), phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, modifiers: egui::Modifiers::NONE, }); h.step(); diff --git a/crates/ui-egui/src/tests_slideshow.rs b/crates/ui-egui/src/tests_slideshow.rs index 24aa0d7281..7dc8ae4005 100644 --- a/crates/ui-egui/src/tests_slideshow.rs +++ b/crates/ui-egui/src/tests_slideshow.rs @@ -16,9 +16,13 @@ const T: Duration = Duration::from_secs(20); const SETTLE: Duration = Duration::from_secs(120); fn grid() -> Headless { + grid_sized([1000.0, 700.0]) +} + +fn grid_sized(size: [f32; 2]) -> Headless { let services = Services { png: None, ..Default::default() }; let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); - let mut h = Headless::new(app, [1000.0, 700.0], 1.0); + let mut h = Headless::new(app, size, 1.0); h.step(); h } @@ -47,6 +51,10 @@ fn photo_up(h: &Headless) -> PhotoId { play(h).current_photo().expect("a photo is up") } +fn rect_json(r: egui::Rect) -> serde_json::Value { + json!([r.left(), r.top(), r.width(), r.height()]) +} + fn slides_held(h: &Headless) -> usize { h.app.renderer.textures.keys().filter(|s| matches!(s, Slot::Slide(_))).count() } @@ -77,6 +85,17 @@ fn slideshow_advances_pauses_and_ends() { h.settle(SETTLE); } +#[test] +fn turning_off_the_full_screen_preview_frees_the_slides() { + let mut h = grid(); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "preparePreviews": false})); + assert!(h.step_until(SETTLE, |h| slides_held(h) > 0), "a slide is rendered"); + let r = run(&mut h, "view.fullScreenPreview", json!({})); + assert_eq!(r["fullscreen"], false); + assert!(!h.app.ui.fullscreen && h.app.ui.slideshow.is_none(), "the toggle ends the slideshow"); + assert_eq!(slides_held(&h), 0, "slide textures freed"); +} + #[test] fn next_slides_are_prepared_before_they_are_due() { let mut h = grid(); @@ -150,6 +169,46 @@ fn arrows_cut_and_repeat_off_ends_after_the_last_slide() { h.settle(SETTLE); } +#[test] +fn a_manual_slideshow_waits_for_the_arrow_keys() { + let mut h = grid(); + let photos = h.app.session.visible_cloned(); + // the library setting, as the Settings checkbox sets it + run(&mut h, "slideshow.playback", json!({"manual": true})); + let r = run(&mut h, "view.slideshow", json!({"interval": 0.5, "fadeDuration": 0})); + assert_eq!(r["settings"]["manual"], true, "{r}"); + // once the first two slides are rendered, and far longer than the slide duration: the first + // photo stays up + assert!(h.step_until(SETTLE, |h| has_slide(h, photos[0]) && has_slide(h, photos[1])), "the slides are rendered"); + for _ in 0..120 { + h.step(); + } + assert_eq!(photo_up(&h), photos[0], "nothing advances on its own"); + let r = h.request("ui.key", json!({"key": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(photo_up(&h), photos[1]); + assert_eq!(h.app.session.active(), Some(photos[1]), "the selection follows"); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert_eq!((s["manual"].clone(), s["remaining"].clone()), (json!(true), json!(null)), "{s}"); + run(&mut h, "slideshow.end", json!({})); + assert!(h.app.ui.slideshow.is_none()); + // off again: it advances by itself + run(&mut h, "slideshow.playback", json!({"manual": false})); + run(&mut h, "view.slideshow", json!({"interval": 0.5, "fadeDuration": 0})); + let up = photo_up(&h); + assert!(h.step_until(SETTLE, |h| h.app.ui.slideshow.as_ref().is_some_and(|r| r.play.current_photo() != Some(up)))); + run(&mut h, "slideshow.end", json!({})); + // the Settings checkbox turns it on + run(&mut h, "view.slideshowOptions", json!({})); + h.step(); + reveal(&mut h, "check:settings.slideshowManual"); + let r = h.request("ui.clickWidget", json!({"id": "check:settings.slideshowManual"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.session.slideshow.manual, "the checkbox goes through slideshow.playback"); + h.settle(SETTLE); +} + #[test] fn random_order_starts_at_the_selection_and_is_fixed_by_the_seed() { let order = |seed: u64| { @@ -233,15 +292,45 @@ fn playback_settings_drive_the_slideshow_and_bad_ones_are_refused() { run(&mut h, "view.slideshowOptions", json!({})); h.step(); assert!(h.app.widgets.iter().any(|(w, _)| w == "check:settings.slideshowRandom")); + // The preview render is a layout input too: wait for the selected photo's real slide before + // scrolling and clicking, so its completion cannot move the checkbox between those steps. + let preview = h.app.session.active().expect("the demo library has a selected photo"); + assert!( + h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::SlidePreview).is_some_and(|t| t.photo == preview)), + "the real preview is rendered" + ); // (below the Templates at the top of the tab) - reveal(&mut h, "check:settings.slideshowRandom"); + let validated = reveal(&mut h, "check:settings.slideshowRandom"); let r = h.request("ui.clickWidget", json!({"id": "check:settings.slideshowRandom"}), T); assert_eq!(r["ok"], true, "{r}"); - h.step(); + assert_eq!(r["result"]["rect"], rect_json(validated), "the click used the rect reveal validated"); assert!(h.app.session.slideshow.random_order, "the checkbox goes through slideshow.playback"); h.settle(SETTLE); } +#[test] +fn a_click_on_a_control_scrolled_out_of_the_settings_page_is_refused() { + // A compact window leaves the lower controls of the Slideshow settings page outside the + // scrolled page room, but they are still laid out and registered. + let mut h = grid_sized([1000.0, 560.0]); + run(&mut h, "view.slideshowOptions", json!({})); + assert!(h.settle(SETTLE), "the settings page settles"); + let target = latest_widget_rect(&h, "check:settings.slideshowRandom").expect("the checkbox is registered"); + let hit = crate::control::widget_hit(&h.app, "check:settings.slideshowRandom").expect("the checkbox has an egui hit owner"); + assert!( + !crate::control::widget_target_visible(&h.view.ctx, Some(hit), target.center()), + "the random-order checkbox is clipped out of the page: {target:?}" + ); + // Its centre is clipped out, so egui would not hit it. Clicking by id must fail closed rather + // than pressing whatever is at those coordinates. + let r = h.request("ui.clickWidget", json!({"id": "check:settings.slideshowRandom"}), T); + assert_eq!(r["ok"], false, "{r}"); + let error = r["error"].as_str().unwrap_or_default(); + assert!(error.contains("check:settings.slideshowRandom"), "{r}"); + assert!(error.contains("nothing was retargeted"), "{r}"); + assert!(!h.app.session.slideshow.random_order, "the clipped control was not clicked"); +} + #[test] fn a_photo_deleted_while_it_plays_does_not_stall_the_slideshow() { let mut h = grid(); @@ -258,26 +347,85 @@ fn a_photo_deleted_while_it_plays_does_not_stall_the_slideshow() { h.settle(SETTLE); } -/// Scroll the Settings ▸ Slideshow column until widget `id` is in view (near its top): the -/// sections are taller than the dialog. -fn reveal(h: &mut Headless, id: &str) { - let find = |h: &Headless, w: &str| h.app.widgets.iter().find(|(i, _)| i == w).map(|(_, r)| *r); +/// The latest registry entry for `id`, as [`crate::control::widget_rect`] looks it up (the last +/// registered rect wins). +fn latest_widget_rect(h: &Headless, id: &str) -> Option<egui::Rect> { + h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +fn in_page_room(room: egui::Rect, widget: egui::Rect) -> bool { + widget.center().y >= room.top() + 10.0 && widget.center().y <= room.bottom() - 10.0 +} + +/// egui 0.37 smooths wheel deltas over several frames (and ends the action after a short idle). +/// Do not measure or click until the Settings page has really stopped scrolling. +fn wait_for_scroll_settled(h: &mut Headless) { + for _ in 0..600 { + if !h.view.ctx.input(|i| i.is_scrolling()) { + return; + } + h.step(); + } + panic!("the Settings page kept scrolling"); +} + +/// The widget's latest rect once the whole rect (not just its centre) has stayed unchanged for +/// three completed passes. A pinned widget is allowed above the page; a page widget must still be +/// inside the page's room. +fn settled_revealed(h: &mut Headless, id: &str, pinned: bool) -> egui::Rect { + let mut last = None; + let mut stable = 0; + for _ in 0..240 { + h.step(); + let Some(now) = latest_widget_rect(h, id) else { + last = None; + stable = 0; + continue; + }; + let room = latest_widget_rect(h, "settings:pageRoom").expect("the Slideshow settings are open"); + let in_place = if pinned { now.bottom() <= room.top() } else { in_page_room(room, now) }; + if !in_place || h.view.ctx.input(|i| i.is_scrolling()) { + last = Some(now); + stable = 1; + continue; + } + if last == Some(now) { + stable += 1; + if stable >= 3 { + return now; + } + } else { + stable = 1; + } + last = Some(now); + } + panic!("{id} never settled in view"); +} + +/// Scroll the Settings ▸ Slideshow page until widget `id` is in view (in the middle of the room +/// for the page): the sections are taller than the dialog. (The slide preview and its choice are pinned +/// above the page and are in view already.) Returns the settled rect that the click will use. +fn reveal(h: &mut Headless, id: &str) -> egui::Rect { + // (the preview and its Photo / Intro / Ending choice are pinned above the page: always in + // view, never scrolled to) + let pinned = id == "slideshow:preview" || id.starts_with("button:settingsSlideshowPreviewShows-"); for _ in 0..40 { h.step(); - let col = find(h, "slideshow:preview").expect("the Slideshow settings are open"); - let dy = match find(h, id) { - Some(w) if w.center().y >= col.top() + 10.0 && w.center().y <= col.top() + 340.0 => return, - Some(w) => (col.top() + 80.0 - w.center().y).clamp(-500.0, 500.0), + wait_for_scroll_settled(h); + let room = latest_widget_rect(h, "settings:pageRoom").expect("the Slideshow settings are open"); + let in_view = latest_widget_rect(h, id).is_some_and(|w| if pinned { w.bottom() <= room.top() } else { in_page_room(room, w) }); + if in_view { + return settled_revealed(h, id, pinned); + } + let dy = match latest_widget_rect(h, id) { + Some(w) => (room.center().y - w.center().y).clamp(-500.0, 500.0), None => -300.0, }; - // (the pointer over the settings column, left of the preview) - let r = h.request("ui.hoverWidget", json!({"id": "slideshow:preview", "fx": -1.0, "fy": 0.5}), T); + let r = h.request("ui.hoverWidget", json!({"id": "settings:pageRoom"}), T); assert_eq!(r["ok"], true, "{r}"); let r = h.request("ui.scroll", json!({"dy": dy}), T); assert_eq!(r["ok"], true, "{r}"); - for _ in 0..8 { - h.step(); - } + wait_for_scroll_settled(h); } panic!("{id} never came into view"); } @@ -373,9 +521,19 @@ fn settings_shows_the_slide_layout_and_a_live_preview() { run(&mut h, "slideshow.layout", json!({"margins": 0.2, "backdropColor": "#00ff00"})); assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::SlidePreview).map(|t| t.key) != before)); h.step(); - let rect = h.app.widgets.iter().find(|(id, _)| id == "slideshow:preview").map(|(_, r)| *r).unwrap(); - let img = h.paint(); - let c = painted(&img, (rect.left() + 3.0) as usize, (rect.center().y) as usize); + // (the preview is pinned above the page: in view already) + reveal(&mut h, "slideshow:preview"); + // (painted once the new preview is on screen: one frame isn't always enough on a loaded machine) + let t0 = std::time::Instant::now(); + let c = loop { + let rect = h.app.widgets.iter().find(|(id, _)| id == "slideshow:preview").map(|(_, r)| *r).unwrap(); + let img = h.paint(); + let c = painted(&img, (rect.left() + 3.0) as usize, (rect.center().y) as usize); + if (c[1] > 200 && c[0] < 60) || t0.elapsed() > T { + break c; + } + h.step(); + }; assert!(c[1] > 200 && c[0] < 60, "the green backdrop in the preview margin: {c:?}"); h.settle(SETTLE); } @@ -592,6 +750,7 @@ fn settings_shows_the_titles_and_the_preview_shows_a_title_screen() { assert_eq!(crate::panels::slide_titles::preview_shows(&h.view.ctx), Some(lightcraft_engine::slideshow::Title::Intro)); run(&mut h, "slideshow.titles", json!({"intro": {"color": "#ff8000", "content": "none"}})); assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::SlidePreview).is_some_and(|t| t.photo == PhotoId(0)))); + reveal(&mut h, "slideshow:preview"); assert!(h.step_until(SETTLE, |h| { let rect = h.app.widgets.iter().find(|(id, _)| id == "slideshow:preview").map(|(_, r)| *r).unwrap(); let img = h.paint(); @@ -606,6 +765,7 @@ fn settings_shows_the_titles_and_the_preview_shows_a_title_screen() { h.step(); assert!(has(&h, "field:slideshowIntroText")); // back to the photo's slide + reveal(&mut h, "button:settingsSlideshowPreviewShows-0"); let r = h.request("ui.clickWidget", json!({"id": "button:settingsSlideshowPreviewShows-0"}), T); assert_eq!(r["ok"], true, "{r}"); assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&Slot::SlidePreview).is_some_and(|t| t.photo == first))); @@ -643,6 +803,8 @@ fn template_browser_previews_on_hover_applies_and_manages_user_templates() { let before = SlideLook::of(&h.app.session); let r = h.request("ui.hoverWidget", json!({"id": "template:builtin:gallery-wall"}), T); assert_eq!(r["ok"], true, "{r}"); + // (the pointer is over the row one frame after it moved there, and the page has settled the next) + h.step(); h.step(); assert_eq!(crate::panels::slide_templates::hovered(&h.view.ctx).as_deref(), Some("builtin:gallery-wall")); let grey = |h: &Headless| { @@ -655,16 +817,19 @@ fn template_browser_previews_on_hover_applies_and_manages_user_templates() { assert_eq!(SlideLook::of(&h.app.session), before, "hovering changes nothing"); assert!(h.app.session.slide_templates_previous.is_none()); // a click applies it + reveal(&mut h, "template:builtin:gallery-wall"); let r = h.request("ui.clickWidget", json!({"id": "template:builtin:gallery-wall"}), T); assert_eq!(r["ok"], true, "{r}"); h.step(); assert!(h.app.session.slide_overlays.rating_stars.enabled && h.app.session.slide_layout.stroke_border); assert!(has(&h, "template:previous"), "Previous settings appear"); // save as a template of our own + reveal(&mut h, "field:slideshowTemplateName"); let r = h.request("ui.clickWidget", json!({"id": "field:slideshowTemplateName"}), T); assert_eq!(r["ok"], true, "{r}"); let r = h.request("ui.text", json!({"text": "Holiday / 2026"}), T); assert_eq!(r["ok"], true, "{r}"); + reveal(&mut h, "button:slideshowTemplateSave"); let r = h.request("ui.clickWidget", json!({"id": "button:slideshowTemplateSave"}), T); assert_eq!(r["ok"], true, "{r}"); h.step(); @@ -673,6 +838,7 @@ fn template_browser_previews_on_hover_applies_and_manages_user_templates() { assert!(has(&h, "template:user:Holiday _ 2026")); // update it from its menu with changed settings run(&mut h, "slideshow.layout", json!({"backdropColor": "#123456"})); + reveal(&mut h, "template:user:Holiday _ 2026"); let r = h.request("ui.clickWidget", json!({"id": "template:user:Holiday _ 2026", "button": "right"}), T); assert_eq!(r["ok"], true, "{r}"); h.step(); @@ -685,6 +851,7 @@ fn template_browser_previews_on_hover_applies_and_manages_user_templates() { h.step(); assert_eq!(h.app.session.slide_template("user:Holiday _ 2026").unwrap().look.layout.backdrop_color, [0x12, 0x34, 0x56]); // rename it in place + reveal(&mut h, "template:user:Holiday _ 2026"); let r = h.request("ui.clickWidget", json!({"id": "template:user:Holiday _ 2026", "button": "right"}), T); assert_eq!(r["ok"], true, "{r}"); h.step(); @@ -703,6 +870,7 @@ fn template_browser_previews_on_hover_applies_and_manages_user_templates() { h.step(); assert!(has(&h, "template:user:Summer"), "{:?}", h.app.session.slide_templates().templates.iter().map(|t| t.id.clone()).collect::<Vec<_>>()); // delete it (after confirming) + reveal(&mut h, "template:user:Summer"); let r = h.request("ui.clickWidget", json!({"id": "template:user:Summer", "button": "right"}), T); assert_eq!(r["ok"], true, "{r}"); h.step(); @@ -716,6 +884,7 @@ fn template_browser_previews_on_hover_applies_and_manages_user_templates() { h.step(); assert!(!dir.join("Summer.json").exists()); // back to the settings before Gallery Wall + reveal(&mut h, "template:previous"); let r = h.request("ui.clickWidget", json!({"id": "template:previous"}), T); assert_eq!(r["ok"], true, "{r}"); h.step(); @@ -723,3 +892,25 @@ fn template_browser_previews_on_hover_applies_and_manages_user_templates() { h.settle(SETTLE); let _ = std::fs::remove_dir_all(dir); } + +/// Hovering a template in the Template Browser previews it in the slide preview, so the preview +/// must be in view while the templates (further down the page) are: it is pinned above the page, +/// under the tab bar, and does not scroll away with it. +#[test] +fn the_slide_preview_stays_in_view_while_the_templates_are_browsed() { + // (900 x 560 is the least the desktop app's window is) + for size in [[1000.0, 700.0], [900.0, 560.0]] { + let mut h = grid_sized(size); + run(&mut h, "view.slideshowOptions", json!({})); + h.step(); + let find = |h: &Headless, w: &str| h.app.widgets.iter().find(|(i, _)| i == w).map(|(_, r)| *r); + let tabs = find(&h, "button:settingsTab-slideshow").expect("the tab bar"); + // down to the last section of the page: the templates are far above the preview's old place + reveal(&mut h, "button:slideshowExportPdf"); + let preview = find(&h, "slideshow:preview").expect("the preview is still drawn"); + let room = find(&h, "settings:pageRoom").unwrap(); + assert!(preview.height() > 40.0, "{size:?}: {preview:?}"); + assert!(preview.top() >= tabs.bottom(), "{size:?}: under the tab bar, not scrolled up behind it: {preview:?} {tabs:?}"); + assert!(preview.bottom() <= room.top() + 1.0, "{size:?}: above the page, not in it: {preview:?} {room:?}"); + } +} diff --git a/crates/ui-egui/src/tests_switch_library.rs b/crates/ui-egui/src/tests_switch_library.rs index 2ea310b048..e2e4f4d115 100644 --- a/crates/ui-egui/src/tests_switch_library.rs +++ b/crates/ui-egui/src/tests_switch_library.rs @@ -75,6 +75,18 @@ fn switching_libraries_dismisses_the_previous_lightroom_result() { let _ = std::fs::remove_dir_all(dir); } +/// Photo IDs are local to a library: the brief info overlay's last photo is forgotten, so a photo +/// in the new library with the same ID shows the info again. +#[test] +fn switching_libraries_restarts_the_brief_info_overlay() { + let dir = temp("switch-brief-info"); + let mut app = app_in(&dir); + app.ui.brief_info = crate::state::BriefInfo { photo: Some(lightcraft_catalog::PhotoId(1)), since: 5.0, shown: true }; + app.run("app.newLibrary", json!({"path": dir.to_string_lossy(), "name": "Second"})).unwrap(); + assert_eq!(app.ui.brief_info, crate::state::BriefInfo::default()); + let _ = std::fs::remove_dir_all(dir); +} + fn recent_submenu(app: &LightcraftApp) -> Vec<crate::menubar::MenuNode> { use crate::menubar::MenuNode; let bar = crate::menubar::menu_bar(app); @@ -163,6 +175,10 @@ fn missing_recent_libraries_are_greyed_out_and_pruned_and_the_list_is_capped() { let mut app = app_in(&dir); let gone = dir.join("gone").to_string_lossy().into_owned(); app.ui.settings.recent_libraries = vec![gone.clone()]; + // the menu takes what a background check found (issue #1290 review): let it answer first + let ctx = egui::Context::default(); + crate::panels::library_problem::logic(&mut app, &ctx); + assert!(crate::tasks::wait(&mut app, &ctx, std::time::Duration::from_secs(20)), "the check answered"); let disabled = recent_submenu(&app) .iter() .any(|n| matches!(n, crate::menubar::MenuNode::Item { params, enabled: false, .. } if params["path"] == gone.as_str())); @@ -254,3 +270,22 @@ fn library_names_must_work_as_folder_names_on_every_system() { assert_eq!(app.session.library.as_ref().unwrap().dir, dir.join("Trip 2026")); let _ = std::fs::remove_dir_all(&dir); } + +/// The web build's page title names the active photo (a host embedding the page reads it to know +/// which document a drop opened), with • while changes are not yet in storage (issue #2397). +#[test] +fn page_title_names_the_active_photo_and_unsaved_changes() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + let ids = app.session.visible_cloned(); + let name = |app: &LightcraftApp, id: lightcraft_catalog::PhotoId| app.session.catalog.photo(id).unwrap().file_name.clone(); + app.run("library.select", json!({"ids": [ids[0].0]})).unwrap(); + assert_eq!(app.page_title(false), format!("{} — LightCraft", name(&app, ids[0]))); + assert_eq!(app.page_title(true), format!("{} • — LightCraft", name(&app, ids[0]))); + app.run("library.select", json!({"ids": [ids[1].0]})).unwrap(); + assert_eq!(app.page_title(false), format!("{} — LightCraft", name(&app, ids[1]))); + // no photo: the window title + let empty = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + assert!(empty.session.active().is_none()); + assert_eq!(empty.page_title(false), "LightCraft"); + assert_eq!(empty.page_title(true), "LightCraft •"); +} diff --git a/crates/ui-egui/src/text_field.rs b/crates/ui-egui/src/text_field.rs index aed99f4d89..f59be23dc8 100644 --- a/crates/ui-egui/src/text_field.rs +++ b/crates/ui-egui/src/text_field.rs @@ -65,7 +65,7 @@ pub struct TextField<'a> { /// The egui id of the field registered as `widget`, to give it the focus (⌘F to search). pub fn id(widget: &str) -> egui::Id { - egui::Id::new("lc-text-field").with(widget) + egui::Id::unique("lc-text-field").with(widget) } /// Whether the field had an unfinished edit on the immediately preceding egui pass. @@ -162,6 +162,12 @@ impl<'a> TextField<'a> { self } + /// Draw the field and return its response, any ending this frame, and whether an edit is + /// under way. Per-frame state keeps the pre-edit text for Esc, the selection across the + /// context menu, and select-on-focus; single-line Enter ends the edit, and focus loss ends it + /// except when the focus went to the field's own menu (a choice from the menu resumes the + /// edit). The menu offers cut/copy/paste/select-all (paste is omitted on the web; egui also + /// handles their keyboard shortcuts), and a field not drawn on the previous pass starts clean. pub fn show(self, ui: &mut Ui) -> TextFieldResponse { let id = id(self.widget); let mut memo: Memo = ui.data_mut(|d| d.get_temp(id.with("memo"))).unwrap_or_default(); @@ -191,6 +197,16 @@ impl<'a> TextField<'a> { Action::Refocus => {} } } + // A field focused by the previous pass (a dialog asks after drawing it) must already + // select its text on the pass that carries the first keystroke: egui processes text + // inside `ui.add`, before the after-add branch below could select, leaving the new text + // inserted into the old. A press may go on to drag a selection, so it keeps the + // after-add path; an edit already under way keeps its pre-edit text for Esc. + let focused_at_start = ui.memory(|m| m.has_focus(id)); + if focused_at_start && memo.before.is_none() && self.select_on_focus && !ui.input(|i| i.pointer.any_down()) { + memo.before = Some(self.text.clone()); + select_all(ui.ctx(), id, self.text); + } let name = self.label.clone().or_else(|| self.hint.clone()); let mut edit = if self.multiline { egui::TextEdit::multiline(self.text) } else { egui::TextEdit::singleline(self.text) }; edit = edit.id(id); @@ -210,7 +226,7 @@ impl<'a> TextField<'a> { edit = edit.text_color(color); } if let Some(align) = self.align { - edit = edit.horizontal_align(align); + edit = edit.align(egui::Align2([align, egui::Align::Min])); } if let Some(margin) = self.margin { edit = edit.margin(margin); @@ -236,7 +252,7 @@ impl<'a> TextField<'a> { state.cursor.set_char_range(selection); state.store(ui.ctx(), id); } - crate::widgets::register(ui.ctx(), self.widget, response.rect); + crate::widgets::register(ui, self.widget, response.rect); // egui's own focus: `Response::has_focus` is also false while the window is in the // background (another app in front), which neither ends nor restarts an edit let focused = ui.memory(|m| m.has_focus(id)); @@ -382,7 +398,7 @@ fn menu(ui: &mut Ui, widget: &str, id: egui::Id, text: &str, action: &mut Option } let button = egui::Button::new(crate::i18n::tr(label)).shortcut_text(crate::menubar::shortcut_text(shortcut, mac)); let r = ui.add_enabled(enabled, button); - crate::widgets::register(ui.ctx(), format!("{widget}:{key}"), r.rect); + crate::widgets::register(ui, format!("{widget}:{key}"), r.rect); if r.clicked() { *action = Some(a); ui.close(); @@ -433,6 +449,12 @@ mod tests { } fn frame(&mut self, events: Vec<Event>) { + self.frame_with(events, false); + } + + /// A frame that asks for the field's focus after drawing it, as a dialog does, so the + /// focus takes effect on the next frame. + fn frame_with(&mut self, events: Vec<Event>, focus_after: bool) { self.time += 1.0 / 60.0; let mut raw = HeadlessView::raw_input(egui::vec2(400.0, 300.0), 1.0, self.time, events); raw.focused = self.window_focused; @@ -445,6 +467,9 @@ mod tests { let r = TextField::singleline(FIELD, text).width(200.0).select_on_focus(select).show(ui); endings.extend(r.ending); *editing = r.editing; + if focus_after { + ui.memory_mut(|m| m.request_focus(id(FIELD))); + } }); self.widgets = crate::widgets::take_registry(&self.view.ctx); } @@ -699,6 +724,25 @@ mod tests { assert_eq!(rig.text, "Kyoto"); } + /// A field focused by the pass before (a dialog asks for focus after drawing it) selects its + /// text before egui handles the first keystroke of the pass the focus takes effect, so that + /// keystroke replaces the text instead of being inserted into it. + #[test] + fn text_typed_on_the_first_focused_pass_replaces_the_whole_text() { + let mut rig = Rig::new("LightCraft Library"); + rig.select_on_focus = true; + // the dialog draws the field, then asks for its focus: effective on the next pass + rig.frame_with(vec![], true); + assert!(rig.view.ctx.memory(|m| m.has_focus(id(FIELD))), "focused for the next pass"); + // the pass the focus takes effect already carries the text + rig.frame(vec![Event::Text("Fresh".into())]); + assert_eq!(rig.text, "Fresh", "the first keystroke replaced the selected text"); + // the text from before the edit is still what Esc gives back + rig.key(Key::Escape, Modifiers::NONE); + assert_eq!(rig.text, "LightCraft Library"); + assert_eq!(rig.endings, vec![Ending::Escape]); + } + /// Esc after using the menu still gives back the text from before the whole edit. #[test] fn escape_after_the_menu_gives_back_the_original_text() { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 57ee987d1d..e55008efdb 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -44,6 +44,9 @@ pub struct Tokens { pub grid_bg: Color32, pub cell: Color32, pub cell_selected: Color32, + /// A thumbnail's place while its picture is still being made: static, apart from the grid, the + /// cells and the canvas in every theme. + pub skeleton: Color32, pub divider: Color32, pub inset: Color32, pub field: Color32, @@ -125,6 +128,7 @@ impl Default for Tokens { grid_bg: Color32::from_rgb(0x0f, 0x0f, 0x0f), cell: Color32::from_rgb(0x1c, 0x1c, 0x1c), cell_selected: Color32::from_rgb(0x2d, 0x2d, 0x2d), + skeleton: Color32::from_rgb(0x25, 0x25, 0x25), divider: Color32::from_rgb(0x1c, 0x1c, 0x1c), inset: Color32::from_rgb(0x23, 0x23, 0x23), field: Color32::from_rgb(0x22, 0x22, 0x22), @@ -172,6 +176,7 @@ impl Tokens { grid_bg: rgb(0x080808), cell: rgb(0x121212), cell_selected: rgb(0x262626), + skeleton: rgb(0x1d1d1d), divider: rgb(0x0e0e0e), inset: rgb(0x181818), field: rgb(0x161616), @@ -189,6 +194,7 @@ impl Tokens { grid_bg: rgb(0xd9d9d9), cell: rgb(0xcbcbcb), cell_selected: rgb(0xb4b4b4), + skeleton: rgb(0xa6a6a6), divider: rgb(0xc4c4c4), inset: rgb(0xdcdcdc), field: rgb(0xf6f6f6), @@ -219,6 +225,7 @@ impl Tokens { grid_bg: rgb(0xf2f2f2), cell: rgb(0xe8e8e8), cell_selected: rgb(0xd2d2d2), + skeleton: rgb(0xbcbcbc), divider: rgb(0xe0e0e0), inset: rgb(0xf0f0f0), field: rgb(0xffffff), @@ -379,7 +386,7 @@ pub const WHEEL_STRIP_SHARE: f32 = 1.0 / 3.0; pub const WHEEL_ZOOM_PER_POINT: f32 = 40.0 / 200.0 / WHEEL_LINE_POINTS; fn theme_id() -> egui::Id { - egui::Id::new("lightcraft-theme") + egui::Id::unique("lightcraft-theme") } /// The theme `ctx` is styled with (none before the first [`apply_kind`]). diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs new file mode 100644 index 0000000000..5e159a0f44 --- /dev/null +++ b/crates/ui-egui/src/updates_ui.rs @@ -0,0 +1,188 @@ +//! Software updates, background check at startup, and startup prompt modal. + +use serde_json::Value; + +use crate::LightcraftApp; + +#[cfg(not(target_arch = "wasm32"))] +use craft_update::updater::{Action, Status, Updater}; + +pub(crate) struct Runtime { + #[cfg(not(target_arch = "wasm32"))] + updater: Updater, + /// The desktop app turns the check at start on; tests and the web build leave it off. + #[cfg(not(target_arch = "wasm32"))] + startup_check: bool, + #[cfg(not(target_arch = "wasm32"))] + check_requested: bool, + /// The context of the last frame, to wake the UI when a check is queued from a menu callback. + #[cfg(not(target_arch = "wasm32"))] + repaint: Option<egui::Context>, + pub(crate) manual_window_open: bool, + pub(crate) status_message: Option<String>, +} + +impl Default for Runtime { + fn default() -> Self { + Self { + #[cfg(not(target_arch = "wasm32"))] + updater: Updater::new(&craft_update::suite::LIGHTCRAFT, env!("CARGO_PKG_VERSION")), + #[cfg(not(target_arch = "wasm32"))] + startup_check: false, + #[cfg(not(target_arch = "wasm32"))] + check_requested: false, + #[cfg(not(target_arch = "wasm32"))] + repaint: None, + manual_window_open: false, + status_message: None, + } + } +} + +impl LightcraftApp { + /// Whether the app asks for a newer release when it starts (off until the desktop app turns it on). + #[cfg(not(target_arch = "wasm32"))] + pub fn set_startup_update_check(&mut self, on: bool) { + self.updates_rt.startup_check = on; + } +} + +/// The update prompt owns the keyboard while it is open: shortcuts must not reach the library behind it. +pub(crate) fn blocks_input(app: &LightcraftApp) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + app.updates_rt.updater.prompt_open() + } + #[cfg(target_arch = "wasm32")] + { + let _ = app; + false + } +} + +pub(crate) fn check(app: &mut LightcraftApp) -> Result<Value, String> { + #[cfg(not(target_arch = "wasm32"))] + { + app.updates_rt.check_requested = true; + if let Some(ctx) = &app.updates_rt.repaint { + ctx.request_repaint(); + } + Ok(Value::Null) + } + #[cfg(target_arch = "wasm32")] + { + app.updates_rt.manual_window_open = true; + app.updates_rt.status_message = Some("Update check is not supported in the web browser.".into()); + Ok(Value::Null) + } +} + +pub(crate) fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + { + let rt = &mut app.updates_rt; + rt.repaint = Some(ctx.clone()); + if std::mem::take(&mut rt.check_requested) { + rt.updater.check_now(ctx); + } else if rt.startup_check { + rt.updater.check_at_start(ctx); + } + rt.updater.tick(ctx); + } + #[cfg(target_arch = "wasm32")] + let _ = (app, ctx); +} + +pub(crate) fn show(app: &mut LightcraftApp, ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + { + // The restart helper is scheduled before the app closes, so no update starts over unsaved work. + let clean = app.session.unsaved().is_none(); + match app.updates_rt.updater.show_if(ctx, clean) { + Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), + Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + Action::None => {} + } + // The window answers Help ▸ Check for Updates, so it follows the updater's status. + let rt = &mut app.updates_rt; + (rt.manual_window_open, rt.status_message) = match rt.updater.status() { + Status::Idle => (false, None), + Status::Checking => (true, Some(crate::i18n::tr("Checking for updates…").to_string())), + Status::UpToDate => ( + true, + Some( + crate::i18n::tr("LightCraft {version} is currently the newest version available.") + .replace("{version}", env!("CARGO_PKG_VERSION")), + ), + ), + Status::Failed(e) => (true, Some(crate::i18n::tr("Could not check for updates:\n{error}").replace("{error}", e))), + }; + } + + if app.updates_rt.manual_window_open { + let mut open = true; + egui::Window::new(crate::i18n::tr("LightCraft Updates")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + if let Some(msg) = &app.updates_rt.status_message { + ui.label(msg); + } + ui.add_space(8.0); + if ui.button(crate::i18n::tr("OK")).clicked() { + app.updates_rt.manual_window_open = false; + } + }); + if !open { + app.updates_rt.manual_window_open = false; + } + } + + // Closing the window dismisses the outcome it showed. + #[cfg(not(target_arch = "wasm32"))] + if !app.updates_rt.manual_window_open { + app.updates_rt.updater.dismiss_status(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use lightcraft_engine::Session; + + #[test] + fn default_runtime_is_idle() { + let rt = Runtime::default(); + assert!(!rt.manual_window_open); + #[cfg(not(target_arch = "wasm32"))] + { + assert!(!rt.startup_check); + assert!(!rt.updater.prompt_open()); + assert_eq!(rt.updater.status(), &Status::Idle); + } + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn startup_prompt_shows_and_closes() { + let mut app = LightcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + let release = craft_update::Release { + tag: "v99.0.0".into(), + version: craft_update::parse_version("99.0.0"), + name: "LightCraft 99.0.0".into(), + html_url: "https://github.com/storytold/lightcraft/releases/tag/v99.0.0".into(), + ..Default::default() + }; + app.updates_rt.updater.offer(release); + + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + show(&mut app, ui.ctx()); + }); + output.textures_delta.clear(); + assert!(app.updates_rt.updater.prompt_open()); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 2db3f885ea..eb5e62589f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -9,7 +9,7 @@ use crate::icons::{Icon, paint}; use crate::theme::Tokens; /// Standard dropdown chevrons, including settings, import/export and rule editors. -pub fn combo_box(id: impl egui::AsIdSalt) -> egui::ComboBox { +pub fn combo_box(id: impl egui::AsIdSalt) -> egui::ComboBox<'static> { egui::ComboBox::from_id_salt(id) .icon(|ui, rect, visuals, _| { paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Icon::ChevronDown, visuals.fg_stroke.color); @@ -17,6 +17,13 @@ pub fn combo_box(id: impl egui::AsIdSalt) -> egui::ComboBox { .popup_style(list_style.into()) } +/// Name a dropdown for screen readers. egui 0.37's `ComboBox::from_id_salt` publishes only the +/// selected text as the node's value, so an otherwise unlabelled combo has no accessible name and +/// the strict kittest check rejects it. Call this on the response returned by `show_ui`. +pub fn name_combo(response: &egui::Response, label: &str) { + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, response.enabled(), label)); +} + /// A dropdown's list and its submenus: items without the resting border of a button, as egui's /// own menus draw them. An unhovered item gives up its border's width of padding, so with one it /// grew 2 points when hovered, and the longest name of a list sized to it wrapped (#2354). @@ -26,7 +33,9 @@ fn list_style(style: &mut egui::Style) { /// A native button with a vector arrow beside its text; egui reserves the icon's space. pub fn arrow_button<'a>(ui: &mut Ui, text: impl egui::IntoAtoms<'a>, icon: Icon, leading: bool) -> Response { - let id = ui.next_auto_id().with("arrow"); + // 0.37 atoms take a local `IdSalt` (not a root `Id`); the button reports the custom atom's + // rect under the same salt. + let id = egui::IdSalt::new(("lc-arrow", ui.next_auto_id())); let mut atoms = text.into_atoms(); let arrow = egui::Atom::custom(id, vec2(16.0, 16.0)); if leading { @@ -70,29 +79,111 @@ pub fn context_menu_close(response: &Response, default: egui::PopupCloseBehavior // ------------------------------------------------------------------ automation registry -#[derive(Clone, Default)] -pub struct Registry(pub Vec<(String, Rect)>); +/// The real egui widget that owns a registered automation rectangle. +/// +/// Automation ids are names for scripts; egui hit-tests widget [`egui::Id`]s in a [`egui::LayerId`]. +/// [`register`] records a small non-interactive probe with the registered rect so the control +/// channel can ask egui itself whether that rectangle owns the pointer, rather than guessing from +/// unrelated interactive rectangles. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WidgetHit { + pub id: egui::Id, + pub layer_id: egui::LayerId, + /// The widget's clipped interaction rectangle in its layer's local coordinates, recorded in + /// the same pass as the registration. Delivery checks this instead of calling + /// `Context::read_response` before the next pass: at that point `read_response` can still see + /// the pass before the registry that was just published. + pub interact_rect: Rect, +} -/// Record a widget's automation id and screen rect for this frame. -pub fn register(ctx: &egui::Context, id: impl Into<String>, rect: Rect) { +#[derive(Clone, Default)] +pub struct Registry { + pub rects: Vec<(String, Rect)>, + pub hits: Vec<(String, WidgetHit)>, + /// How many times each automation id was registered in this pass (for stable duplicate probe + /// ids). A map keeps registration linear; scanning `rects` would make a pass O(N²). + occurrences: std::collections::HashMap<String, usize>, +} + +/// Record a widget's automation id and screen rect for this frame, and register a hover probe at +/// the same rectangle in the current UI layer. +/// +/// The probe senses hover only (no click or drag), so it never takes a click from the widget it +/// describes. It records the current UI layer and its clipped `Response::interact_rect` in the +/// same pass, and the control channel asks egui for the top-most interactable layer at the point. +/// A probe below a non-modal foreground/dim overlay is therefore refused without ever pressing the +/// overlay. A point below the top modal dialog is instead left to egui's modal routing: the dialog +/// consumes it, or a click on the backdrop closes the dialog, and no background widget is pressed. +pub fn register(ui: &egui::Ui, id: impl Into<String>, rect: Rect) { + let ctx = ui.ctx(); + let registry = egui::Id::unique("lc-registry"); let id = id.into(); - ctx.data_mut(|d| d.get_temp_mut_or_default::<Registry>(egui::Id::new("lc-registry")).0.push((id, rect))); + // Stable across frames even when unrelated widgets come and go: the probe id names the + // automation id (and a duplicate occurrence of the same id in this pass), not its position. + let duplicate = ctx.data_mut(|d| { + let registry = d.get_temp_mut_or_default::<Registry>(registry); + let occurrence = registry.occurrences.entry(id.clone()).or_insert(0); + let duplicate = *occurrence; + *occurrence = occurrence.saturating_add(1); + duplicate + }); + let hit = rect.is_finite().then(|| { + let id = egui::Id::unique(("lc-automation-hit", id.as_str(), duplicate)); + let response = ui.interact(rect, id, egui::Sense::hover()); + WidgetHit { id, layer_id: response.layer_id, interact_rect: response.interact_rect } + }); + ctx.data_mut(|d| { + let registry = d.get_temp_mut_or_default::<Registry>(registry); + registry.rects.push((id.clone(), rect)); + if let Some(hit) = hit { + registry.hits.push((id, hit)); + } + }); +} + +/// Record a widget whose real egui [`egui::Response`] is available. More precise than +/// [`register`]'s hover probe: the response carries the widget's own id, layer and clipped +/// geometry, and remains a valid automation target when disabled (`ui.clickWidget` on a disabled +/// control is a successful no-op, which is the documented automation semantics). +pub fn register_response(id: impl Into<String>, rect: Rect, response: &egui::Response) { + let id = id.into(); + let ctx = response.ctx.clone(); + ctx.data_mut(|d| { + let registry = d.get_temp_mut_or_default::<Registry>(egui::Id::unique("lc-registry")); + registry.rects.push((id.clone(), rect)); + registry.hits.push((id, WidgetHit { id: response.id, layer_id: response.layer_id, interact_rect: response.interact_rect })); + }); +} + +/// Record painted geometry that has no interactive egui widget of its own (a preview image, a +/// drop card). `ui.clickWidget` will not press it: there is no widget hit to own the press. +pub fn register_geometry(ctx: &egui::Context, id: impl Into<String>, rect: Rect) { + let id = id.into(); + ctx.data_mut(|d| d.get_temp_mut_or_default::<Registry>(egui::Id::unique("lc-registry")).rects.push((id, rect))); } /// Esc was handled this frame by something nested (an open popup closed on it): containers such /// as dialogs shouldn't close too. Keyed to the frame, so it lapses by itself on the next one. pub fn take_escape(ctx: &egui::Context) { let frame = ctx.cumulative_frame_nr(); - ctx.data_mut(|d| d.insert_temp(egui::Id::new("lc-escape-taken"), frame)); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("lc-escape-taken"), frame)); } /// Whether [`take_escape`] was called this frame. pub fn escape_taken(ctx: &egui::Context) -> bool { - ctx.data(|d| d.get_temp::<u64>(egui::Id::new("lc-escape-taken"))) == Some(ctx.cumulative_frame_nr()) + ctx.data(|d| d.get_temp::<u64>(egui::Id::unique("lc-escape-taken"))) == Some(ctx.cumulative_frame_nr()) } +/// Take this pass's registered rectangles and their egui hit owners. The app publishes both only +/// for a completed, nondiscarded pass. +pub fn take_registries(ctx: &egui::Context) -> (Vec<(String, Rect)>, Vec<(String, WidgetHit)>) { + let registry = ctx.data_mut(|d| std::mem::take(d.get_temp_mut_or_default::<Registry>(egui::Id::unique("lc-registry")))); + (registry.rects, registry.hits) +} + +/// Take only the registered rectangles (for unit tests that inspect layout). pub fn take_registry(ctx: &egui::Context) -> Vec<(String, Rect)> { - ctx.data_mut(|d| std::mem::take(&mut d.get_temp_mut_or_default::<Registry>(egui::Id::new("lc-registry")).0)) + take_registries(ctx).0 } // ------------------------------------------------------------------ preview-only raws @@ -143,8 +234,8 @@ pub fn preview_only_notice(ui: &mut Ui, key: &str, reason: &str) -> bool { }) .response; let r = r.on_hover_text(crate::i18n::tr_format!("Decoder: {reason}", reason = reason)); - r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, crate::i18n::tr("Preview only: editing the camera's embedded JPEG"))); - register(ui.ctx(), format!("notice:previewOnly:{key}"), r.rect); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::tr("Preview only: editing the camera's embedded JPEG"))); + register(ui, format!("notice:previewOnly:{key}"), r.rect); reload } @@ -262,7 +353,7 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_ let pad_r = 22.0; let label_rect = Rect::from_min_size(pos2(row.left() + pad_l, row.top() + 4.0), vec2(w - pad_l - pad_r, 18.0)); let track_rect = Rect::from_min_max(pos2(row.left() + pad_l, row.top() + 22.0), pos2(row.right() - pad_r, row.top() + 40.0)); - let id = ui.id().with(spec.id); + let id = ui.scope_id().with(spec.id); let resp = ui.interact(track_rect.expand2(vec2(8.0, 2.0)), id, if enabled { Sense::click_and_drag() } else { Sense::hover() }); // Keyboard focus survives leaving the row; vertical wheel edits need a fresh click or drag // in it (at most one slider is armed: `wheel_slider_key`). @@ -324,14 +415,14 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_ let reset_hint = crate::i18n::tr_format!("{name} — double-click to reset it", name = label_text); let label_resp = if enabled { label_resp.on_hover_text(reset_hint.as_str()) } else { label_resp }; crate::widgets::announce(&label_resp, crate::i18n::tr_format!("Reset {name}", name = label_text.clone())); - register(ui.ctx(), format!("sliderLabel:{}", spec.id), label_rect); - register(ui.ctx(), format!("slider:{}", spec.id), track_rect); + register(ui, format!("sliderLabel:{}", spec.id), label_rect); + register(ui, format!("slider:{}", spec.id), track_rect); // the value: click it to type an exact one, drag it sideways to scrub (over the label, so it // takes the click) let value_rect = Rect::from_min_max(pos2(label_rect.right() - 64.0, label_rect.top()), label_rect.max); let value_resp = ui.interact(value_rect, id.with("value"), if enabled { Sense::click_and_drag() } else { Sense::hover() }); crate::widgets::announce(&value_resp, format!("{label_text}: {}", crate::i18n::tr("Click to type a value, drag to change it"))); - register(ui.ctx(), format!("sliderValue:{}", spec.id), value_rect); + register(ui, format!("sliderValue:{}", spec.id), value_rect); // say that an exact value can be typed here (issue #534: an exact crop angle was hard to find) let value_resp = if enabled { value_resp.on_hover_text(crate::i18n::tr("Click to type a value, drag to change it")) } else { value_resp }; let typing_id = id.with("typing"); @@ -618,14 +709,24 @@ pub fn nudged(spec: &ControlSpec, value: f64, steps: f64) -> f64 { (((value + unit * steps) / step).round() * step).clamp(spec.min, spec.max) } +/// Announce a disclosure row with AccessKit's real `Expanded` state. +/// +/// egui 0.37's `WidgetInfo::selected` maps to AccessKit `Toggled`; a custom disclosure row must +/// publish `Expanded` instead (the built-in `CollapsingHeader` does this through +/// `accesskit_node_builder`). Use one helper so section headers, flyouts and fold titles agree. +pub(crate) fn announce_disclosure(resp: &egui::Response, enabled: bool, expanded: bool, label: impl ToString) { + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, enabled, label.to_string())); + resp.ctx.accesskit_node_builder(resp.id, |node| node.set_expanded(expanded)); +} + /// Collapsible section header ("› Light"). Returns the response (click toggles). pub fn section_header(ui: &mut Ui, id: &str, title: &str, open: bool, enabled: Option<bool>) -> (Response, Option<bool>) { let title = crate::i18n::tr(title); let t = Tokens::get(ui.ctx()); let w = ui.available_width(); let (r, resp) = ui.allocate_exact_size(vec2(w, 52.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title)); - register(ui.ctx(), format!("section:{id}"), r); + announce_disclosure(&resp, true, open, title); + register(ui, format!("section:{id}"), r); let p = ui.painter(); if ui.rect_contains_pointer(r) { p.rect_filled(r, 0.0, t.chrome.gamma_multiply(1.06)); @@ -641,9 +742,9 @@ pub fn section_header(ui: &mut Ui, id: &str, title: &str, open: bool, enabled: O && (ui.rect_contains_pointer(r) || !on) { let eye = Rect::from_center_size(pos2(r.right() - 34.0, r.center().y), vec2(18.0, 18.0)); - let er = ui.interact(eye, ui.id().with(("eye", id)), Sense::click()); + let er = ui.interact(eye, ui.scope_id().with(("eye", id)), Sense::click()); crate::widgets::announce_selected(&er, crate::i18n::tr("Show / hide"), on); - register(ui.ctx(), format!("sectionEye:{id}"), eye); + register(ui, format!("sectionEye:{id}"), eye); paint(ui.painter(), eye, Icon::Eye, if on { t.icon } else { t.text_disabled }); if !on { ui.painter().line_segment([eye.left_bottom(), eye.right_top()], Stroke::new(1.5, t.text_disabled)); @@ -670,9 +771,9 @@ pub fn flyout_row(ui: &mut Ui, id: &str, title: &str, icon: Icon, open: bool) -> let w = ui.available_width(); let (outer, _) = ui.allocate_exact_size(vec2(w, 40.0), Sense::hover()); let r = Rect::from_min_max(pos2(outer.left() + 16.0, outer.top() + 4.0), pos2(outer.right() - 16.0, outer.bottom() - 4.0)); - let resp = ui.interact(r, ui.id().with(("flyout", id)), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, title)); - register(ui.ctx(), format!("flyout:{id}"), r); + let resp = ui.interact(r, ui.scope_id().with(("flyout", id)), Sense::click()); + announce_disclosure(&resp, true, open, title); + register(ui, format!("flyout:{id}"), r); let p = ui.painter(); p.rect_filled(r, 4.0, if resp.hovered() { t.hover.gamma_multiply(0.8) } else { t.inset }); let tile = Rect::from_min_size(pos2(r.left() + 4.0, r.top() + 4.0), vec2(r.height() - 8.0, r.height() - 8.0)); @@ -696,8 +797,8 @@ pub fn text_button(ui: &mut Ui, id: &str, label: &str, active: bool) -> Response let galley = ui.painter().layout_no_wrap(label.to_string(), font, t.text); let size = vec2((galley.size().x + 18.0).max(37.0), 24.0); let (r, resp) = ui.allocate_exact_size(size, Sense::click()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, active, label)); - register(ui.ctx(), format!("button:{id}"), r); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, label)); + register(ui, format!("button:{id}"), r); let fill = if active { t.pressed } else if resp.hovered() { @@ -728,7 +829,7 @@ pub fn segmented(ui: &mut Ui, id: &str, items: &[(&str, &str)], active: Option<u let i = row_i * per_row + j; let (r, resp) = ui.allocate_exact_size(vec2(seg_w, 24.0), Sense::click()); crate::widgets::announce_selected(&resp, label.to_string(), active == Some(i)); - register(ui.ctx(), format!("button:{id}-{key}"), r); + register(ui, format!("button:{id}-{key}"), r); let fill = if active == Some(i) { t.pressed } else if resp.hovered() { @@ -753,8 +854,8 @@ pub fn icon_button(ui: &mut Ui, id: &str, icon: Icon, size: egui::Vec2, active: let tooltip = crate::i18n::tr(tooltip); let t = Tokens::get(ui.ctx()); let (r, resp) = ui.allocate_exact_size(size, if enabled { Sense::click() } else { Sense::hover() }); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, active, tooltip)); - register(ui.ctx(), format!("icon:{id}"), r); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, active, tooltip)); + register(ui, format!("icon:{id}"), r); let p = ui.painter(); let sq = Rect::from_center_size(r.center(), vec2(32.0f32.min(size.x), 32.0f32.min(size.y))); if active { @@ -776,41 +877,6 @@ pub fn icon_button(ui: &mut Ui, id: &str, icon: Icon, size: egui::Vec2, active: if !tooltip.is_empty() { resp.on_hover_text(tooltip) } else { resp } } -/// Star rating row (5 stars); returns a new rating when clicked (clicking the current rating clears). -pub fn stars(ui: &mut Ui, id: &str, rating: u8, size: f32) -> Option<u8> { - let t = Tokens::get(ui.ctx()); - let mut out = None; - let mut hover_n = None; - let mut rects = [Rect::NOTHING; 5]; - for (i, slot) in (0..5u8).zip(rects.iter_mut()) { - let (r, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click()); - crate::widgets::announce_selected(&resp, format!("{} ★", i + 1), i < rating); - register(ui.ctx(), format!("star:{id}:{}", i + 1), r); - if resp.hovered() { - hover_n = Some(i + 1); - } - if resp.clicked() { - out = Some(if rating == i + 1 { 0 } else { i + 1 }); - } - *slot = r; - } - // Hover previews the rating a click would set: stars 1..=hovered light up. The hovered star also gets the - // icon_button hover square, so hovering the current rating (where the preview looks the same) still shows feedback. - for (i, r) in (0..5u8).zip(rects) { - if hover_n == Some(i + 1) { - ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.7)); - } - let filled = star_lit(i, rating, hover_n); - paint(ui.painter(), r.shrink(size * 0.12), if filled { Icon::StarFilled } else { Icon::Star }, if filled { t.star } else { t.icon }); - } - out -} - -/// Whether the star at zero-based index `i` is drawn filled: the hovered star's rating previews over the current one. -fn star_lit(i: u8, rating: u8, hover: Option<u8>) -> bool { - i < hover.unwrap_or(rating) -} - /// A borderless dropdown button: `text` followed by a painted chevron (no font glyph needed). pub fn dropdown(ui: &mut Ui, id: &str, text: &str, font: egui::FontId, color: Color32) -> Response { dropdown_within(ui, id, text, font, color, f32::INFINITY) @@ -824,8 +890,8 @@ pub fn dropdown_within(ui: &mut Ui, id: &str, text: &str, font: egui::FontId, co let elided = galley.elided; let size = vec2(galley.size().x + 20.0, galley.size().y.max(20.0)); let (r, resp) = ui.allocate_exact_size(size, Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, text)); - register(ui.ctx(), format!("dropdown:{id}"), r); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, text)); + register(ui, format!("dropdown:{id}"), r); let c = if resp.hovered() { t.text } else { color }; ui.painter().galley(pos2(r.left(), r.center().y - galley.size().y / 2.0), galley, c); paint(ui.painter(), Rect::from_center_size(pos2(r.right() - 10.0, r.center().y), vec2(16.0, 16.0)), Icon::ChevronDown, c); @@ -849,16 +915,6 @@ mod tests { assert!(preview_only_explanation("unsupported CR3").contains("unsupported CR3")); } - /// Issue #647: hovering a star previews the rating a click would set. - #[test] - fn hovered_star_previews_its_rating() { - let lit = |rating, hover| (0..5u8).filter(|&i| star_lit(i, rating, hover)).count(); - assert_eq!(lit(2, None), 2, "no hover shows the rating"); - assert_eq!(lit(2, Some(4)), 4); - assert_eq!(lit(5, Some(1)), 1); - assert_eq!(lit(0, Some(3)), 3); - } - #[test] fn nudges_are_a_sensible_step() { let spec = |id, min, max, step| ControlSpec { @@ -1004,13 +1060,13 @@ pub(crate) fn screen_reader_name(ctx: &egui::Context, id: egui::Id, name: &str) /// A hand-drawn clickable area (an icon, a tile, a row) announced as a button named `name`. pub(crate) fn announce(resp: &egui::Response, name: impl Into<String>) { let name = name.into(); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, resp.enabled(), name.clone())); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, resp.enabled(), name.clone())); } /// The same for one that is on or off (a toggle, a selected row or swatch). pub(crate) fn announce_selected(resp: &egui::Response, name: impl Into<String>, selected: bool) { let name = name.into(); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, resp.enabled(), selected, name.clone())); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, resp.enabled(), selected, name.clone())); } /// `r`, named `name` for screen readers: a plain egui field or slider whose caption is drawn @@ -1064,12 +1120,12 @@ mod numeric_entry_tests; mod slider_reset_tests; fn focused_slider_key() -> egui::Id { - egui::Id::new("lightcraft-focused-slider") + egui::Id::unique("lightcraft-focused-slider") } /// The slider a click or drag armed for vertical wheel edits, if any. fn wheel_slider_key() -> egui::Id { - egui::Id::new("lightcraft-wheel-slider") + egui::Id::unique("lightcraft-wheel-slider") } /// Whether the widget with keyboard focus is a develop slider selected by a click, drag or Tab. diff --git a/crates/ui-egui/src/widgets/tests_numeric_entry.rs b/crates/ui-egui/src/widgets/tests_numeric_entry.rs index eb2e3c9b81..0bd49abaec 100644 --- a/crates/ui-egui/src/widgets/tests_numeric_entry.rs +++ b/crates/ui-egui/src/widgets/tests_numeric_entry.rs @@ -206,6 +206,7 @@ fn leaving_a_slider_disarms_wheel_edits_until_it_is_selected_again() { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, 120.0), phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, modifiers: Modifiers::NONE, }; h.frame(vec![Event::PointerMoved(inside)]); @@ -232,7 +233,13 @@ fn leaving_a_slider_disarms_wheel_edits_until_it_is_selected_again() { let before_sideways = h.value; h.frame(vec![ Event::PointerMoved(inside), - Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(120.0, 0.0), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE }, + Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(120.0, 0.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: Modifiers::NONE, + }, ]); for _ in 0..40 { h.frame(vec![]); @@ -270,7 +277,13 @@ fn leaving_the_row_during_a_drag_keeps_dragging_but_release_disarms_the_wheel() let released = h.value; h.frame(vec![ Event::PointerMoved(inside), - Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, -120.0), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE }, + Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -120.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: Modifiers::NONE, + }, ]); for _ in 0..40 { h.frame(vec![]); @@ -294,6 +307,7 @@ fn a_drag_that_leaves_and_ends_back_in_the_row_disarms_the_wheel() { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, 120.0), phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, modifiers: Modifiers::NONE, }]); for _ in 0..40 { @@ -308,6 +322,7 @@ fn leaving_and_returning_within_one_frame_still_disarms_the_wheel() { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, 120.0), phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, modifiers: Modifiers::NONE, }; // a slow frame merges the moves out of the row and back (or out of the window and back) diff --git a/crates/ui-egui/tests/accessibility.rs b/crates/ui-egui/tests/it/accessibility.rs similarity index 100% rename from crates/ui-egui/tests/accessibility.rs rename to crates/ui-egui/tests/it/accessibility.rs diff --git a/crates/ui-egui/tests/docking_workflows.rs b/crates/ui-egui/tests/it/docking_workflows.rs similarity index 100% rename from crates/ui-egui/tests/docking_workflows.rs rename to crates/ui-egui/tests/it/docking_workflows.rs diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs new file mode 100644 index 0000000000..4b9fa7eb7a --- /dev/null +++ b/crates/ui-egui/tests/it/main.rs @@ -0,0 +1,5 @@ +//! The integration tests, one module per file, linked into one test binary. +//! `tests/shutdown.rs` stays a binary of its own: it closes the GPU for the whole process. + +mod accessibility; +mod docking_workflows; diff --git a/docs/ai-masks.md b/docs/ai-masks.md index b01fd9e425..84e082163b 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -238,7 +238,7 @@ wait and return the result (when built with the `sam` feature; the default CLI h the model on the CPU from the start. - Hostile documents: a selection keeps at most 4 detail patches (when read and when rendered), each at most 1024² logits; more than 64 clicks are never sent to the model. -- Accuracy: `crates/segment/tests/reference.rs` compares every stage against the Python +- Accuracy: `crates/segment/tests/it/reference.rs` compares every stage against the Python reference (`tools/sam3_reference.py`); on Metal the backbone matches to 7e-5 relative error and masks to ~5e-5. f16 was tried and rejected (overflow, ~7 % faster). - The engine feature `sam` (on in the desktop app, off for web and CLI) gates the model; without diff --git a/docs/architecture.md b/docs/architecture.md index 7d1b7a3aeb..aec9a51a20 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (`cargo xtask ci` reports the machine and skipped tests; `testkit`) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (`cargo xtask ci`: one integration-test binary per crate, doctests apart, one WASM check) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 How LightCraft is built today. The longer design document (`plan/architecture.md`) is local-only (`plan/` is gitignored); this page is the committed, current summary. Sizes are Rust lines counted @@ -63,6 +63,16 @@ dispatch by id, and headless snapshots render the UI without a window. `assets` (every asset attributed, no Adobe formats) and the WASM build. Other workflows build and test FreeBSD and Windows ARM64, lint packaging, and build releases. +The tests run under `cargo test --workspace --lib --bins --tests`, or `cargo nextest run` with the +same targets when `LIGHTCRAFT_NEXTEST=1` is set and cargo-nextest is installed; doctests run after +them with `cargo test --workspace --doc`. `cargo test` is the default because the demo library's +generated scenes are cached per process, and nextest's process per test regenerates them. +Examples are left out of the test build (clippy `--all-targets` still +checks them). Each crate links its integration tests into one binary, `tests/it/main.rs` with one +module per file (`cargo test -p <crate> --test it <module>::`); a test that changes state for its +whole process (a global allocator, closing the GPU) keeps a binary of its own in `tests/`. The WASM +build is one `cargo check --target wasm32-unknown-unknown --keep-going` over the wasm-safe crates. + `ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored `gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build; xtask has no wgpu), the corpus and `CRAFT_FONTS_DIR`. Tests @@ -77,5 +87,6 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Quality gates: one integration-test binary per crate, doctests apart, nextest on request, one WASM check | | 2026-10-11 | minor | Quality gates: the CI machine probe, visible skips (`testkit`) and `target/ci/report.json` | | 2026-10-10 | major | Created from the code (crate sizes, layers, data model, rendering, control, gates) | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dd41bcdb81..3b4c7ed954 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -10,7 +10,9 @@ ``` Requests are answered on the UI thread between frames (timeout 60 s). A request is given up -if the app has not started it and draws no frame for 5 s. The reply is then `{"ok": false, "error": "the app drew no frame for 5 s, …"}`, +if the app has not started it and draws no frame for 5 s. Synthetic pointer input is fed one event +per frame; the same 5 s limit is a delivery stall, restarted whenever the app consumes a batch, so a +many-step drag on a slow frame is not cut off while an app that stops drawing still fails. The reply is then `{"ok": false, "error": "the app drew no frame for 5 s, …"}`, and the app never runs that request later, so a retry doesn't do it twice. This happens on Wayland when the window is on a hidden workspace or minimized: the compositor sends no frame callbacks, so the app's loop is paused. Keep the window on screen while you drive it, or use @@ -79,19 +81,20 @@ filmstrip is visible. | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | | `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:<id>`, ✕ = `activity:cancel:<id>`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | -| `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks) / `{id, toX?, toY?, dx?, dy?, steps?}` / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews) | -| `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points | +| `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks; `count` is capped at 16) / `{id, toX?, toY?, dx?, dy?, steps?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | +| `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply) | | `ui.pointer` | `{events: [{kind: down\|drag\|up, x, y}], alt?, shift?, cmd?}` | Gesture in normalized image coordinates (Detail view) | -| `ui.key` | `{key, cmd?, shift?, alt?, ctrl?}` | Key press | +| `ui.key` | `{key, cmd?, shift?, alt?, ctrl?}` | Key press; while a prompt is up only its Tab/Shift+Tab, Enter, Space and Escape are delivered, every other key is dropped | | `ui.text` | `{text}` | Text input | -| `ui.clipboard` | `{action: cut\|copy\|paste, text?}` | Cut, copy or paste in the focused text field, as the system does for ⌘X / ⌘C / ⌘V; `paste` pastes `text`, or the system clipboard without it. Refused when no text field has the focus (outside one, ⌘C / ⌘V are the commands `develop.copy` / `develop.paste`). In the desktop app cut and copy write the system clipboard. `ui.inspect` → `copied` is the text the UI last put on the clipboard | -| `ui.scroll` | `{dx, dy, cmd?, ctrl?, shift?, alt?}` | Wheel / two-finger scroll at the current pointer; pans over the image, modifier-scroll zooms | +| `ui.clipboard` | `{action: cut\|copy\|paste, text?}` | Cut, copy or paste in the focused text field, as the system does for ⌘X / ⌘C / ⌘V; `paste` pastes `text`, or the system clipboard without it. Refused when no text field has the focus (outside one, ⌘C / ⌘V are the commands `develop.copy` / `develop.paste`). In the desktop app cut and copy write the system clipboard. Refused while a prompt or the blocking library window owns input, including a window in its creation frame. A `paste` without `text` queues egui's `RequestPaste` viewport command for the host: egui 0.37 gives that command no completion/correlation id, and egui-winit emits a later `Event::Paste` only for non-empty text (or a `PasteImage` fallback; asynchronous clipboard reads finish later), so the reply confirms the request was queued in egui, not that the host dispatched it or that it was delivered; a barrier created after the request can drop that later event. `paste` with `text` is synthetic and is canceled like other injected input. `ui.inspect` → `copied` is the text the UI last put on the clipboard | +| `ui.scroll` | `{dx, dy, source?, unit?, phase?, cmd?, ctrl?, shift?, alt?}` | Wheel / two-finger scroll at the current pointer; pans over the image, modifier-scroll zooms. `source` is `unknown` (default), `wheel`, `trackpad` or `momentum`; `unit` is `point` (default), `line` or `page`; `phase` is `move` (default), `start`, `end` or `cancel`. Wheel/line events drive the grid/filmstrip one-third wheel step and the loupe's notch zoom; trackpad/momentum phases drive kinetic scrolling and rubber-band boundaries. Invalid values are refused and queue nothing | | `ui.zoom` | `{factor}` | Pinch zoom at the current pointer (positive scale multiplier; 1 = unchanged). Position it first with `ui.move` or `ui.hoverWidget` | | `ui.set` | partial UI state, e.g. `{"view": "detail"}` | Resulting UI state | | `ui.dialog.confirm` / `ui.dialog.cancel` | — | Close the open dialog (confirm runs its action; Synchronize Folder on a folder that is up to date answers `{"upToDate": true}` and starts nothing) | | `ui.resize` | `{width, height}` | Resize the window | +| `ui.dropFiles` | `{paths: [..], hover?}` | Files dragged from the file manager. `hover: true` makes every following frame report `paths` as hovered over the window (the drop card appears, `ui.widgets` lists `dropOverlay`) until another `ui.dropFiles` replaces them; `{paths: [], hover: true}` ends the hover. Without `hover` the files are dropped: the hover ends and the next frame receives them as dropped files, exactly as an OS drop arrives (photos and folders open the import review, or import at once with Settings ▸ Import ▸ Import dropped files without review). An empty path stands for a file whose path the platform doesn't tell | | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | -| `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:<pane>`, `compare:renderFailed:<pane>`) | +| `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:<pane>`, `compare:renderFailed:<pane>`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | | `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | @@ -134,6 +137,12 @@ x1, y1}, mode?, area?, tracking?}`, normalized to the upright photo (absent when file, on a background job (activity kind `focus`); `wait: true` returns the run's counts when done. The app calls `focus.pump {pace}` every frame to drive it. +With several photos selected, the Info panel's Show Metadata For is `view.infoSelectedPhotos {on?}` (no `on`, or +`on: null`, toggles; any other value that is not true or false is refused; replies `{on}`; +`settings.infoSelectedPhotos`): off (Target Photo) shows the active photo's values and saves edits to it alone, on (Selected Photos, the default) +shows the values the selected photos share, leaves each text field and GPS where they differ empty with a Mixed hint, +and shows Mixed as the Copyright Status when the statuses differ. + The interface theme is `view.appearance {mode?: "auto" | "light" | "dark"}` (no mode: the next one, Auto → Light → Dark → Auto, like the top bar's `icon:appearance` button) and `view.theme {theme: "charcoal" | "midnight" | "silver" | "paper"}`, which picks a theme and fixes the mode to its family. @@ -165,7 +174,42 @@ catalog, a missing drive), the session starts empty and in memory — never with to do: `ui.inspect` → `libraryProblem` is `{path, error, temporarySession, pendingImport}` (else `null`); its buttons are `button:libraryRetry`, `button:libraryChoose`, `button:libraryTemporary` (Continue Without Saving) and `button:libraryQuit`. A temporary session shows a banner (`indicator:temporarySession`, `button:libraryReopen`) and -writes nothing. `app.openLibrary` opening a library ends it. +writes nothing. `app.openLibrary` opening a library ends it. `pendingImport` counts the files waiting for a +library: those given on the command line, and photos dropped on the window while it (or the launch list below) is +up (desktop app); they are imported into the library that opens, or into the temporary session. Presets dropped +then are refused with a toast. + +### Choosing the library at launch + +With Settings ▸ General ▸ At launch set to Ask me (`ui.set {"settings": {"atLaunch": "ask"}}`; `"last"`, the +default, opens the last library), or Alt/Option held during the first 2 s after the window appears, the desktop app +shows a window listing the recent libraries (issue #1290). `--library` and `LIGHTCRAFT_LIBRARY` skip it, and so does +`--memory`; `lightcraft-cli` never shows it. `ui.inspect` → `libraryProblem.chooser` is `{libraries: [{path, +lastOpened, available, checking, reason}], selected, libraryOpen}` (else `null`; `libraryOpen: true` when it was opened +over the last library with Alt). Each library is checked read-only on a worker thread of its own, never on the UI +thread (the folder and its catalog file are looked at, never locked or written, so a library another program has +open shows as available and Open reports who has it in `libraryProblem.error`). `checking: true` until its check +answers (the row says *Checking…*, then that the drive isn't answering after 5 s); `available` is `false` only +once a check found a `reason`, so a row still checking can be opened. The selection starts on the last library and +moves to the first one that can be opened once every check has answered, unless it was moved meanwhile. Each row is the widget `libraryRecent:<index>`; the buttons are `button:libraryOpen`, +`button:libraryOpenAnother` (the folder dialog of `app.openLibrary`), `button:libraryNew` (`app.newLibrary`), +`button:libraryForget` (Remove from List) and `button:libraryQuit`; `ui.key` ArrowUp / ArrowDown move the selection, +Enter opens it and Escape quits (over an open library: closes the window and keeps it). `app.openLibrary {path}` +opening a library ends it. While it shows, the settings are saved as usual (a removal is kept). + +`app.recentLibraries` returns `[{path, name, exists, checking, open, lastOpened}]`. `exists` is what the last +background check found (`false`: moved, on a disconnected drive, not a folder or no longer a library; `null`: not +checked yet, or the check couldn't tell, e.g. a folder that can't be listed, an unreadable catalog or a lookup that +failed) and `checking` whether one +is running: the command never looks at a folder itself. A failed open never marks a library missing (another program +may have it). Recent libraries are checked in the +background when the app starts (the first 8) and when the launch window opens; one not found is looked for again every +30 s (a drive plugged back in), the others only when the window comes back to the front (a timer would wake external +drives and shares). File ▸ Open Recent Library greys out only an entry a check found missing (not there, not a folder, +no library in it); an unreadable catalog, a folder that refuses to be listed, a failed open or a lookup that failed +(a share that timed out) doesn't grey it out. `lastOpened`: ISO 8601, `null` when not known; kept in `ui.json` → +`settings.recentLibrariesOpened`. `{remove: path}` forgets one entry (an error if the list +doesn't hold it) and `{clear: true}` (or `app.clearRecentLibraries`) all of them; nothing on disk is touched. ### Open Library on a Lightroom catalog @@ -173,12 +217,29 @@ writes nothing. `app.openLibrary` opening a library ends it. folder (it holds a `*.lrcat`), one of its `*.lrdata` / `*.lrcat-data` folders or `Backups/`, the `.lrcat` itself or its `-wal` / `-shm` / `.lock` files, it keeps the library open now and returns `{opened: false, lightroomCatalog: <the .lrcat found, or null>, path}`; the window shows a dialog whose `button:dialogOk` (Import Lightroom Catalog…, or -`ui.dialog.confirm`) runs `file.importLightroom` with that catalog (no catalog found: it asks for one) and -`button:dialogCancel` (`ui.dialog.cancel`) does nothing. A folder that is a LightCraft library (`catalog.snap` / `catalog.log`) always +`ui.dialog.confirm`) runs `file.importLightroom` with that catalog (no catalog found: it asks for one), which then +asks where the catalog goes when `settings.lightroomImport` is `"ask"` (next section), and `button:dialogCancel` (`ui.dialog.cancel`) does nothing. A folder that is a LightCraft library (`catalog.snap` / `catalog.log`) always opens as one. With no library open (the library problem window) it is an error instead. The engine refuses the same places (`EngineError::LightroomCatalog`, so `lightcraft-cli --library` and `mcp --library` too). `library.importLightroom {status: true}` reports the catalog's `path` after the task ends as well as while it runs. +### Import Lightroom Catalog: where the catalog goes + +`file.importLightroom {path?, into?, name?, location?}` (File ▸ Import Lightroom Catalog…, issue #2672). With `into` +it acts without asking: `"open"` imports into the library open now (`library.importLightroom`); `"new"` creates the +library `name` (default: the catalog's file name without `.lrcat`, or `Travel 2`… when taken) in the folder +`location` (a full path; default: the open library's parent folder) under `app.newLibrary`'s rules, opens it and +imports there, returning the import's start with `library: {path, name, photos}`. A catalog file that isn't there is +refused before anything is made; so is a new library while an import runs. Without `into`, a library on disk with +`settings.lightroomImport` `"ask"` (the default) opens a window and returns `{asking: true, path, into}` (`into`: the +choice it opens with, `"open"` when the library is empty, else `"new"`). Its widgets: +`radio:lightroomDestination-open`, `radio:lightroomDestination-new`, `field:lightroomLibraryName`, +`field:lightroomLibraryLocation`, `button:lightroomLibraryChoose` (where there is a folder dialog), `check:lightroomDontAsk` (with Merge only; sets +`"alwaysMerge"`), `button:dialogOk` / `ui.dialog.confirm` (which stays open on an error such as a folder that isn't +empty) and `button:dialogCancel`. With `"alwaysMerge"` (`ui.set {"settings": {"lightroomImport": "alwaysMerge"}}`, +or Settings ▸ General `button:settingsLightroomImport-0|1`), or in a session in memory, it imports into the open +library without asking. + ## External controllers External apps can use this channel to send commands and poll the running desktop app for feedback @@ -273,8 +334,9 @@ lightcraft-cli snapshot --library DIR --script tour.jsonl -o shot.png Headless screenshot dimensions must be finite and at least one logical point, with a finite, positive scale. Rounded output must be at least one pixel per edge, at most 16,384 pixels -per edge and 64 million pixels in total. `snapshot` and `ui.resize` reject requests outside -these limits before layout or rasterization; supplied resize dimensions must be numbers. +per edge and 33,554,432 pixels in total (128 MiB of RGBA, the per-image screenshot +budget). `snapshot` and `ui.resize` reject requests outside these limits before layout or +rasterization; supplied resize dimensions must be numbers. An interface zoom (egui's zoom factor; the keyboard never changes it — ⌘= / ⌘− / ⌘0 zoom the photo, issue #566) changes text and control sizes while preserving the snapshot viewport's requested physical pixel dimensions. Later `ui.resize` requests use current egui points; validation diff --git a/docs/cr3.md b/docs/cr3.md index b133dfe6ac..b53647c7da 100644 --- a/docs/cr3.md +++ b/docs/cr3.md @@ -39,7 +39,7 @@ decoded. ## Variant status The supported and rejected CRX coding variants. Every rejection is an explicit `RawError::Unsupported` whose -text is part of the contract: `crates/raw/tests/cr3_variants.rs` rebuilds each variant as a synthetic CR3 +text is part of the contract: `crates/raw/tests/it/cr3_variants.rs` rebuilds each variant as a synthetic CR3 fixture and asserts the exact string, and that header probing (`probe_info`, the import path) and full decoding fail with the same error, because the engine shows that reason when it falls back to the embedded preview. The same tests decode a control fixture at both edges of each accepted range, so a rejection can @@ -87,7 +87,7 @@ CMP1 bit depth. A lossless sample outside the bit depth is still corrupt data. Other unverified coding variants return explicit unsupported errors (the table above lists them all). Header probing validates the same coding variants and tile/plane layout as full decoding. -`crates/raw/tests/cr3_corpus.rs` checks every full-sensor sample against a +`crates/raw/tests/it/cr3_corpus.rs` checks every full-sensor sample against a black-box reference, before cropping or colour processing. Public CC0 files are downloaded by `cargo xtask corpus --download` and kept outside version control. The exact inputs and reference hashes are: @@ -194,7 +194,7 @@ All 110 CR3 files on raw.pixls.us (2026-10-12, every one CC0, 31 folders) decode falls back to the preview, so none of them uses a CRX variant the decoder refuses (vertical C-RAW tiles, partial-subband or rounded-plane coding, multi-tile 0x200, adaptive low-frequency gains) or a CR3 sRAW / mRAW. HEIF stills are separate `.HIF` files, not CR3. One file per body is pinned in -`canon_cr3_bodies_decode_like_the_camera_jpeg` (`crates/raw/tests/cr3_corpus.rs`; URLs and SHA-256 in +`canon_cr3_bodies_decode_like_the_camera_jpeg` (`crates/raw/tests/it/cr3_corpus.rs`; URLs and SHA-256 in `RAW_SAMPLES`, `xtask/src/main.rs`): EOS-1D X Mark III, 90D, 250D, 850D, M200, M50 Mark II, M6 Mark II, R, R3, R5, R6, R6 Mark II, R6 Mark III, R7, R10, RP, R50, R50 V and PowerShot G5 X Mark II, G7 X Mark III, SX70 HS and V1, C-RAW where the body has a CC0 C-RAW sample. No external decoder was run: the sensor diff --git a/docs/denoise.md b/docs/denoise.md index 7c3f5138f5..64354e805a 100644 --- a/docs/denoise.md +++ b/docs/denoise.md @@ -117,8 +117,8 @@ Fresh checks can be run using an already installed model and CC0 raw samples: ```text LC_DENOISE_MODEL=<model.onnx> cargo test --release -p lightcraft-gpu --lib real_model_on_the_gpu_matches_cpu -- --ignored --nocapture -LC_DENOISE_MODEL=<model.onnx> LC_DENOISE_RAW=<corpus/raw> cargo test --release -p lightcraft-engine --features rawnind-model --test denoise_cpu -- --ignored --nocapture -LC_DENOISE_MODEL=<model.onnx> LC_DENOISE_RAW=<corpus/raw> cargo test --release -p lightcraft-engine --features rawnind-model --test denoise_real -- --ignored --nocapture +LC_DENOISE_MODEL=<model.onnx> LC_DENOISE_RAW=<corpus/raw> cargo test --release -p lightcraft-engine --features rawnind-model --test it denoise_cpu:: -- --ignored --nocapture +LC_DENOISE_MODEL=<model.onnx> LC_DENOISE_RAW=<corpus/raw> cargo test --release -p lightcraft-engine --features rawnind-model --test it denoise_real:: -- --ignored --nocapture ``` ## Another computer's graphics card diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md new file mode 100644 index 0000000000..6606d4e888 --- /dev/null +++ b/docs/egui-037-migration-plan.md @@ -0,0 +1,1552 @@ +# LightCraft: egui 0.37 migration plan + +Current reconciliation (2026-10-25): this tree incorporates main `31ec62cd0387abecd8f2a2da034aee591447897d`. Managed CI `egui037-light-main31-ci-20261025-0829` passed all eight stages, including strict lint, HEIF and WASM checks: 5,086 passing test executions, zero failures and 42 ignored across 89 summaries. The prerequisite report separately identifies 149 tests that returned without exercising their checks (corpus 137, models 8, fonts 2, GPU 1, system 1); these are coverage gaps. Independent reconciliation review found no source blocker; its stale-status and pending-CI findings are addressed by this record. Native/browser GUI, platform, packaging/licence coverage and paired performance checks remain open. Human review and human merge are required; publication needs separate approval. + +Historical landing status before this reconciliation, 2026-10-25: the migration integrates main `38f8d2508700fa4938295e865d3fc21be07266ba` and uses egui `6d518fc799681571963842f95b55a6b68431b15a`, winit `a517b3846ee8457d84ee4975110bfda6797c44dc` and craft-ui `25da1314d443171b4adeaad2cd9454b273f35c6f`. Cargo.lock SHA-256 is `6336b4aa2ac9df57cb8feaafb097b30fa7228ef427f5e213fac1a2a7875e4181`; the independent craft-docpath pin remains selected in the lockfile. Release workflows use craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`. + +Fresh static review verified preservation of the captured main and the final dependency graph. The final managed CI run `egui037-lightcraft-library-frame-ci-20261025-0551` passed all eight stages. Including its focused library tests, the log records 5,083 passing test executions, zero failures and 42 ignored across 142 summaries. The CI prerequisite report separately identifies 149 tests that returned without exercising their checks (corpus137, models8, fonts2, GPU1, system1); these are coverage gaps. Earlier passing counts below qualify their historical snapshots only. The icon-font attribution URL now identifies the selected egui source; font bytes are unchanged. Visible GUI, browser/platform runtime, native IME, final packages and paired performance remain separate acceptance gates. Human review and human merge are required. + +The review packet separately records inherited default-font notice coverage and Inter licence staging gaps. Nix font-pin drift is fixed as described below; the other inherited gaps are not established as fixed by the migration or by source-level notice routing checks. + +Current status note (2026-10-25): `flake.nix` now points at craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`, matching CI, the release workflow and the standalone packaging helpers, and `flake.lock` was regenerated by Nix 2.26.3 using `nix flake update craft-fonts` against the canonical GitHub revision. Only the craft-fonts node changed; nixpkgs stayed pinned. Linux x86_64 flake evaluation passed with `nix flake check --no-build --no-write-lock-file` (job `egui037-lightcraft-nix-eval-20261025-0495`). No Nix package build, executed formatting derivation, or other architecture is claimed. The inherited gaps above (egui default-font licence coverage for Hack, Ubuntu-Light and NotoEmoji-Regular; the Inter OFL packaging omission) are not migration-introduced, and this landing updates the craft-fonts notices and attribution text only. + +Font notice and Inter staging follow-up (2026-10-25): the inherited gaps above are now addressed at +source level only. `NOTICE` reproduces the pinned upstream texts verbatim for Hack Regular (MIT and the +Bitstream Vera License), Ubuntu Light (Ubuntu Font Licence 1.0) and Noto Emoji Regular (SIL OFL 1.1), +next to the existing egui-icons/emoji-icon-font block; `assets/ATTRIBUTION.md` gains rows for +`epaint_default_fonts::HACK_REGULAR`, `UBUNTU_LIGHT` and `NOTO_EMOJI_REGULAR`; `packaging/env.sh` +`copy_font_licences` now always stages `assets/fonts/OFL-Inter.txt` as `OFL-Inter.txt` before the optional +craft-fonts OFLs (Linux, macOS app and CLI, FreeBSD and web use it), and the Flatpak from-source manifest +installs it directly. The release Flatpak bundle repackages the Linux tarball and so inherits its documents; +Windows and Nix already staged Inter. Managed staging checks verified the three upstream licence texts +byte-for-byte in `NOTICE`, copied Inter with and without an optional craft-fonts input, and confirmed +that a missing Inter licence makes staging fail. These checks exercise the shared document-copy helper; +actual release artifacts (deb/rpm/tar, macOS app and CLI, FreeBSD, web zip, Flatpak, MSI/portable zip, Nix) +and their installed notice contents remain unverified. + +Library-check results now remain visible for the frame in which they arrive, so a zero-delay refresh cannot immediately replace a fresh missing-library answer. The scheduling fence uses the root UI frame number across all layout passes; focused regressions cover the single-pass and forced-multipass cases with isolated temporary directories. Fresh static review accepted the delivery-frame behavior. + +The original planning and earlier qualification record follows. Its pins, hashes, paths and passing counts are historical. + + +## Current implementation status — 2026-10-24 + +The implementation is now pinned to egui `173cc7375d35dc5fbc5b5d0994fdf787f547c5d1`, +winit `ae48c756a3b81125eb796c0cc6dccf60990d1181`, craft-libs +`c488caa9fbc2fb1a86e4674887e9b80b598ebbfa`, craft-fonts +`b076417b5880bd4154bd22f00695b1d28c6bea83` and craft-i18n +`e5bfe19b95d30f50f250985bdc3aeec47c05af09`. Cargo-generated lock SHA-256: +`2b6c3550997fd4962df7865ec038cc409604aafaaf2267fa416ad9d98df91da9`. +These are exact local reviewed revisions; public fetchability still requires the separately +approved foundation publication. Earlier planning and source-only validation statements below +are historical and are superseded by this status. + +The mandatory `cargo xtask ci` passed all eight stages (fmt, strict clippy, HEIF, tests, +parity, layers, assets and WASM). Its log reports 4,747 passing test invocations, zero failures +and 40 ignored tests. The CI prerequisite report separately lists 149 checks that returned +without exercising their checks: corpus 137, models 8, fonts 2, GPU 1 and system 1. These are +coverage gaps, not qualified behavior. Canonical source identities were resolved through local +mirrors; no public remote-fetch acceptance is claimed. + +Fresh review and regression coverage include capture-parent symlink retargeting: completion +re-resolves the lexical parent and refuses a changed destination before encoding or writing. +The two standalone packaging helpers now default to the same craft-fonts pin as release CI; +explicit font-directory overrides and existing checkouts retain their behavior. + +The current-main integration includes `4ae3089420cb57d4c839e51a735d4f48271cbf17` and +preserves its catalog hardening and other changes. Independent review caught a bad-chain +memoization error: a descendant visited before a broken ancestor could be detached unnecessarily. +The repair caches only proven valid chains and removes the offending parent edge, preserving +valid descendants. Regressions cover child-before-cycle, child-before-missing-parent and a valid +513-folder chain through actual catalog snapshot/reopen paths. All nine focused catalog repair +tests passed before the full eight-stage CI run on the merged source. The only formatting change +after the source review wraps one let-chain condition; the lockfile remains unchanged. + +Actual visible UI, native platform/IME/PRIMARY, browser behavior, final release-package notices +and paired performance acceptance remain open. This application branch has not been published. + +## Historical plan and review revisions + +Status: **Revision R3.2** — R3.1 plus the 2026-10-24 implementation-status amendments: +control-gesture delivery no longer re-checks the state snapshot after the gesture's own event has +applied (freshness is still checked before resolution and immediately before injection), every +dropdown now publishes a semantic accessible name, and the craft-libs reference moved to the local +`3832c47…` reconciliation base. The R3.1 concrete implementation notes for control-gesture +delivery, screenshot path identity, `ui.scroll` units/phases, the hidden-paint predicate and +disclosure `Expanded` state remain in force. R3 replaced +R2 (SHA-256 `385e46055494cc24b58e41ee08982c876eb423df314b0abffcdc28ac81cf9d24`) after the +independent review in `plan-reviews/lightcraft-v2.md`. Every review finding is resolved inline in the section +that owns it; §13 records each disposition, including the parts rejected. No production code, +manifest, lockfile, test, asset or build was changed and **no test, build, benchmark or GUI run was +performed for R3**: every source statement below is static inspection of the pinned trees. No +executed-validation, GPU-pass or browser-pass claim was made at that planning stage. + +No push, pull request, release, tag, comment or other publication is authorized. Every future push +or new pull request needs explicit human approval of the exact content and the validation results +first. + +This plan covers only `storytold/lightcraft` at +`23e181283cb448205d865e8cd288b56afe987986` (branch `codex/egui-037-plan-20261022` in the assigned +checkout). It does not migrate the egui fork, winit, craft-libs or a sibling app; those are separate +plans, separate review units and separate publication gates. + +The root `AGENTS.md`/`CLAUDE.md` and the nested `docs/user/AGENTS.md`/`CLAUDE.md` were read. This +plan changes no user documentation, asset, contributor metadata or build artefact; the only file it +adds is this plan. + +The historical diagnostics in +`/home/codex/work/ssd2/task-evidence/egui037-audit-20261022/{fork,stock}/lightcraft.errors` and +`lightcraft.log` are clues from an earlier checkout. They are not current source, not a build of this +checkout and not acceptance evidence. They show 17 library errors and 26 library-test errors plus +243 warnings from the fork trial; the source audit below found additional semantic changes (panel +IDs, capture correlation, dropped-file replay) that a compiler diagnostic cannot show. + +## 1. Exact baseline and provenance + +| Item | Revision or value | +|---|---| +| LightCraft source baseline | `23e181283cb448205d865e8cd288b56afe987986` (`Release 0.13.0`) | +| LightCraft lockfile | `Cargo.lock`, format version 4 | +| LightCraft Rust baseline | workspace `rust-version = "1.90"`; `lightcraft-ui-egui` declares `1.95`; inspection toolchain `rustc 1.99.0` | +| Current egui family | `egui`, `epaint`, `ecolor`, `emath`, `eframe`, `egui-wgpu`, `egui-winit`, `egui_glow`, `epaint_default_fonts`, `egui_kittest` all `0.36.2` | +| Current winit | `0.30.13` from crates.io, checksum `a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d` | +| Current accessibility/test stack | `accesskit 0.24.1`, `accesskit_consumer` 0.35/0.36/0.38, `kittest 0.4.0`, `egui_kittest 0.36.2` | +| craft-libs reconciliation base | `3832c47ef68a0e6214f2c1e85f3526b6adcb686e` | Current local shared-library tree and the base for the implemented port; it already carries PR 199's egui 0.37 API update, while the CL-2F capture helper remains uncommitted and is a publication gate. The exact reachable publish pin is still a central-publication gate | +| craft-libs historical inspection | `49190884278f16c9a9f5823d7698a8ffb5deb062`; PR 199 `8614e4a` + README `1764bca` | Earlier base and hunks; retained as history only. The port shape is already contained in the `3832c47…` base | +| Target upstream release | egui `0.37.0`, peeled commit `841a328ba2dd8f6996beb7189ebb7fc00e668a2a`; the annotated tag object SHA is not the commit SHA | +| Comparison-only egui tree | `aiongg/egui` `craft/0.37` at `a4f9a17f64a6bae61350fb85804c9df0d9865916` (E1–E21) | +| Comparison-only winit tree | `aiongg/winit` `craft/0.30.13-lang` at `8b35388bd719e8cc86a95971ba0bc026c9a8f058`; storytold base `ffae5198770d7730e718043f035a772b7dbc3b1b` | +| craft-libs stale trees | PR 199 head `b68de8c5f4f1c060904d211a7b1320aa0f7bce78` and audit merge `ec8840af8c5fda695cf195cdd05e5ae078415c07` | Evidence only, not mergeable trees: they omit current `craft-platform` and revert security/settings/docking/printer fixes | +| Language work | craft-libs issue/PR 198 is a separate proposal, not a merged dependency and not included here | + +**Pin policy for this consumer.** `a4f9a17f` (egui) and `8b35388b` (winit) are *comparison and +inspection* references only. LightCraft must pin the final reviewed **storytold** egui and winit +revisions by immutable full SHA **once the fork and winit series are published**. Those revisions do +not exist yet, so this plan states no SHA for them and does not guess one. Every stage that needs +them is explicitly blocked (§9, §10). LightCraft's production dependency is the complete reviewed +and published storytold egui **P8** revision: E1–E21 plus **P2b** (E4 regular/PRIMARY with bounded +asynchronous W15P transfer completion), **P7** held-key release pairing, **P7b/E21b** outgoing IME +surrounding text, and **P7c** (the selected #8763/#8748 fixes and justified performance fixes). Its +companion is the complete published storytold winit revision with **W15P** and the **W27** IME +lifecycle. No stock 0.37 or intermediate fork stage is a production dependency; stock 0.37 is only +the measurement control. A published revision missing any of these is not acceptable for the stages +named below. + +## 2. Dependency and entry-point inventory + +All manifests in the checkout were inspected: + +- root `Cargo.toml` (`[workspace]`, `[workspace.dependencies]`, `[workspace.lints]`, profiles); +- `apps/lightcraft/Cargo.toml`, `apps/lightcraft-cli/Cargo.toml`, + `apps/lightcraft-web/Cargo.toml`; +- all 29 `crates/*/Cargo.toml` and `xtask/Cargo.toml`. + +There is one workspace, one lockfile, no nested workspace, no Cargo `vendor/` directory and no +`[patch]` section today. `crates/raw/src/vendor/` is a set of in-tree raw-decoder modules (Sony, +Nikon, Canon, Fujifilm, …), not a Cargo vendor directory and not egui-related; it is preserved and +out of scope. There are no vendored egui/winit/egui-wgpu copies. `.cargo/config.toml` only defines +the `xtask` alias. `egui_extras` is declared in the workspace but unused and absent from the lock +graph; do not add it to production just to patch it. `egui_plot`, `egui_dock` and +`egui_inspection` are unused. `craft-ui` is the only shared UI dependency; `craft-docpath` is not +egui-related. + +| Target | egui entry point | Notes | +|---|---|---| +| `lightcraft` (native) | `apps/lightcraft/src/main.rs:60` `impl eframe::App`; `logic` calls `LightCraftApp::logic`, `ui` calls `LightCraftApp::ui` | eframe features `default_fonts`, `wgpu`, `glow`, `accesskit`, `wayland`, `x11` today; native menu, GPU probe/fallback, control server (`MAX_CONNECTIONS = 16`, `MAX_LINE = 4 MiB`) | +| `lightcraft-web` | `apps/lightcraft-web/src/web.rs:652` `impl eframe::App for WebApp`; `start` at `:726` | eframe `default_fonts`, `glow`; browser-loaded Chinese face; workers; OPFS/IndexedDB; `command()` → `LightcraftApp::run`, **no control server** | +| `lightcraft-cli` | `apps/lightcraft-cli/src/main.rs`: `snapshot` at `:767`, `render`, `mcp` | headless `Headless`/`HeadlessView`; no eframe | +| `lightcraft-ui-egui` | `crates/ui-egui/src/lib.rs:1077` `LightCraftApp::logic`, `:1441` `LightCraftApp::ui`; `headless.rs:133` `HeadlessView::run`, `headless.rs:311` `Headless::step` | the UI crate and its integration tests | +| `crates/ui-egui/tests` | `accessibility.rs`, `docking_workflows.rs`, `shutdown.rs` | kittest harnesses and AccessKit assertions | +| examples | `drag_latency`, `grid_bench`, `open_timeline`, `thumb_request_bench` | existing UI/perf harnesses | + +Platform-specific declarations that must stay coherent with the selected winit/egui: + +- `apps/lightcraft` has direct `winit = "0.30"` with `x11` only on + `cfg(all(unix, not(target_os = "macos")))`; +- `apps/lightcraft` has `rfd` only on non-wasm; `zbus` only on Linux; `muda`, `objc2`, + `objc2-app-kit`, `objc2-foundation` only on macOS; +- `apps/lightcraft-web` puts eframe/egui/wasm-bindgen/web-sys under `cfg(target_arch = "wasm32")`; +- `lightcraft-ui-egui` has `rust-version = "1.95"` and dev-dependency `egui_kittest` with + `wgpu` and `snapshot`. + +### 2.1 Feature policy (explicit, per root) + +egui 0.37 has **no default `default_fonts`** (`egui/Cargo.toml`: `default_fonts` off by default), +and 0.37 moved the monochrome emoji faces out of `default_fonts` into +`monochrome_emoji_fonts` (`epaint/src/text/font_definitions.rs:127-183` inserts +`NotoEmoji-Regular`/`emoji-icon-font` only under that cfg). eframe 0.37's default feature set +includes `clipboard`, and its `egui-winit` dependency is `default-features = false`, so an app that +turns eframe defaults off must add `clipboard` itself (`eframe/Cargo.toml:142-144`; +`egui-winit/Cargo.toml:44-46`, `clipboard.rs`). + +| Root | Features after migration | Why | +|---|---|---| +| workspace `egui` | `default-features = false`, `features = ["default_fonts", "monochrome_emoji_fonts"]` | every resolution root needs the bundled faces: CLI snapshot, headless harnesses and unit tests never see eframe's features. Monochrome emoji are needed because user keywords/filenames carry emoji (`tests_keywording.rs:558-583` uses `🙂`) and 0.36's `default_fonts` supplied them. The workspace feature is what supplies LightCraft roots; `egui_kittest`'s own dev-dependency enables them only for upstream kittest's tests and does not propagate | +| `lightcraft` (native) | eframe: `default_fonts`, `clipboard`, `wgpu`, `glow`, `accesskit`, `wayland`, `x11`; egui: workspace `monochrome_emoji_fonts` | `clipboard` restores the real OS clipboard; without it egui-winit simulates an in-process clipboard and cut/copy/paste, `RequestPaste` and the E4/W15P Wayland path are unavailable | +| `lightcraft-web` | eframe: `default_fonts`, `glow`; egui: workspace `monochrome_emoji_fonts` | browser clipboard is not the egui-winit `clipboard` feature; the browser path is qualified separately | +| `lightcraft-cli`, `lightcraft-ui-egui` | inherit the workspace `egui` features | headless rendering and kittest must resolve the same faces | + +`monochrome_emoji_fonts` adds roughly 1 MB to the binary (its own doc comment); the size impact is a +measured deliverable for both native and WASM (§7.2). Adding both faces must not weaken +`MissingGlyphPolicy`: production stays `Tofu`, kittest keeps its `Panic` default. + +**kittest does not supply these faces.** Its normal `[dependencies] egui` uses the workspace entry +with `default-features = false`; only `egui_kittest`'s own `[dev-dependencies]` enables +`default_fonts`/`monochrome_emoji_fonts` (`egui_kittest/Cargo.toml:39-42,65-68`), and a dependency's +dev-dependencies do not propagate to consumers. LightCraft's workspace/root feature selection is +therefore what gives every CLI, headless and kittest root its faces; verify each produced graph with +`cargo tree -e features`, as §5.3 requires. + +Current source/test gates (source-declared, not executed here): thousands of `#[test]` annotations; +`cargo xtask ci` runs fmt, clippy `--workspace --all-targets -D warnings`, the HEIF feature check, +`cargo test --workspace`, GPU probe/backends, `parity`, `layers`, `assets` and the wasm check +(`xtask/src/main.rs:295-366`). CI matrix files also cover FreeBSD (with craft-fonts), Nix, Windows +ARM64, packaging and release. `assets/ATTRIBUTION.md` matches every image, font, icon and media +path; migration screenshots stay in task evidence rather than the repository unless separately +approved and attributed. + +## 3. What actually changes in 0.37 (and what does not) + +The app already receives a root `egui::Ui` through `App::ui` and `Context::run_ui` on 0.36.2, and +`App::logic`/`App::ui` already exist in 0.36.2. Do not describe that split or root-Ui pass-through as +introduced by 0.37, and do not mechanically rewrite `update` into `ui` where no `update` exists. +`eframe 0.36.2` already calls `app.logic(ui.ctx())` before `app.ui(ui)` in each pass and calls +`run_logic` when hidden; the 0.37 source at `a4f9a17f` has the same shape (see §4.1). The real +incompatibilities and semantic risks are these. In the table, `egui/src/...` means +`crates/egui/src/...` in the egui checkout, and `egui_kittest/src/...` means +`crates/egui_kittest/src/...`; LightCraft paths remain repository-relative. + +| Change | Effect in LightCraft | Source anchor | +|---|---|---| +| `WidgetType` replaced by `accesskit::Role` (`egui::Role`), alias deprecated | `WidgetInfo` constructors and tests must use roles; `CollapsingHeader` becomes `DisclosureTriangle`, `SelectableLabel` becomes `Button`, `Checkbox` becomes `CheckBox` | `egui/src/lib.rs` 0.37 role alias/table; PR #8555 | +| `Id::new` deprecated in favor of `Id::unique`; `AsIdSalt`/`IdSalt` are explicit | **221** `egui::Id::new` occurrences on 218 lines plus **three** bare `Id::new` calls (`menu_level.rs:19`, `canvas_keys.rs:15,20`, imported with `use egui::Id`) and **8** `Ui::id()` calls; the remaining `*Id::new` spellings are `LayerId`/`FontId`/`TextureId`, unrelated. `Id::new` and `Id::unique` hash identically, so persisted egui state does not reset | `egui/src/id.rs`; `egui/src/ui.rs:363-381`; PRs #8534/#8586/#8542 | +| `Panel` constructors take `impl AsIdSalt`; panel ID is `parent_ui.scope_id().with_salt(self.id_salt)`, and `Panel::new` stores `IdSalt::new(id_salt)` | This is a **semantic change** from 0.36's exact `Id`. Code that removes/reads `PanelState` must use the same parent-salted key, computed from the original salt source. Passing an already-built `IdSalt` to `Panel::left/right` hashes it **again** (`IdSalt::new(IdSalt)` is a distinct salt — the id_salt.rs unit test `debug_format_nested_salt` proves nesting is not identity) | `egui/src/containers/panel.rs:284-300, 974-975`; `egui/src/id_salt.rs`; PR #8592 | +| `default_fonts` is no longer an `egui`/`epaint` default; monochrome emoji moved behind `monochrome_emoji_fonts` | The CLI, headless harnesses and any graph without eframe's features lose the bundled faces and the monochrome emoji; `FontDefinitions::default()` becomes empty and the font-count test changes meaning | `egui/Cargo.toml`; `epaint/src/text/font_definitions.rs:127-183`; PR #8583; §2.1 | +| eframe `clipboard` is a separate feature | Turning eframe defaults off silently selects egui-winit's simulated clipboard | `eframe/Cargo.toml:142-144,168-170`; `egui-winit/src/clipboard.rs` | +| `ViewportCommand::Screenshot` takes a one-shot `ScreenshotCallback`; `UserData`/`Event::Screenshot` are gone | `issue_screenshots`/`collect_screenshots` move to the CL-2F completion slot; the callback runs on the renderer thread, is `Send + 'static`, and must not touch app state | `egui/src/data/screenshot_callback.rs`; `viewport.rs`; PR #8489 | +| `Event::MouseWheel` gains `source: MouseWheelSource` | Every initializer in `control.rs`, tests, examples and headless helpers needs a source; use `Unknown` for the control channel | `egui/src/data/input/event.rs:171-195`; `mouse_wheel_source.rs` | +| `scroll_area::State.offset` is private; `clamped_offset`/`unclamped_offset` are the API | `menu_level` reads `.offset` and writes `st.offset.y`; `right` reads `.offset`. Use `clamped_offset()` for reads and a next-frame scroll target for writes; no private-field workaround | `egui/src/containers/scroll_area.rs:100-148` | +| Kinetic scrolling/rubber-banding and `MouseWheelSource` are new | Menu/wheel/scroll behavior can differ; `ui.scroll` must carry a source; tests cover wheel vs trackpad/momentum and overscroll | `scroll_area.rs` 0.37 | +| `ComboBox` is `ComboBox<'a>`; `Atom::custom` takes `IdSalt`; `WidgetAtomResponse::rect` takes `IdSalt` | `widgets::combo_box` needs a named lifetime; `arrow_button` uses `IdSalt::new("arrow")` consistently | `containers/combo_box.rs:45-101`; `atomics/atom.rs:98`; `atomics/widget_atom.rs:228-240` | +| `Ui::id` renamed `scope_id`; `UiBuilder::id` renamed `scope_id` | Replace the 8 `ui.id()` uses; child UIs use `scope_id`; `id_salt` remains for local children | `ui.rs:363-381`; `ui_builder.rs:59-82` | +| `Role`/AccessKit tree and strict kittest checks | kittest 0.37 panics on an input widget with no accessible name and on a missing glyph; `HarnessBuilder` defaults are `missing_glyph_policy: Panic`, `check_accessibility: true`, and the check runs after every settle and before every snapshot | `egui_kittest/src/builder.rs:46-60`; `accessibility.rs:26-42`; PRs #8589/#8611 | +| TextEdit click-away selection regression in 0.37 | `text_field`'s custom Cut/Copy menu and toolbar actions that read the selection can see a collapsed range; keep the existing memo/store logic and add the #8763 regression | upstream #8763, open; PR #8764 open/unmerged | +| `Style` defaults are roomier, TextEdit layout changes | LightCraft pins spacing/button padding/corner radii in `theme::apply_kind`, but menus, tooltips, scrollbars and plain dialogs can shift; review geometry/pixels, never auto-refresh | PRs #8617/#8445; `theme.rs:397-448` | +| PRIMARY selection support | New middle-click paste and PRIMARY publishing; verify separately from the normal clipboard, through E4 + W15P | PR #8428; E4; #8657 | +| `egui_extras`/`egui_kittest` have independent version numbers | Do not infer versions from `egui`; `egui_plot` is unused | crate manifests at `0.37.0` | + +Not a 0.37 migration item: `Context::root_ui`/`run_pass` (new in 0.37) are not needed by LightCraft's +`App::ui`, which already receives the root `Ui`. Never call `ctx.root_ui` from inside `run_ui`, +`App::ui` or `root_ui`; upstream #8535 documents the panic. Use the passed `&mut Ui`. Likewise, do +not claim `App::logic` is new or replace `App::ui` with a `Context` bridge. + +## 4. Concrete source design + +### 4.1 How the hosts actually call the app + +Verified statically at `a4f9a17f` (and unchanged in shape from 0.36.2): + +- **Native** (`eframe/src/native/epi_integration.rs`): `App::logic` and `App::ui` are both called + **inside** the `Context::run_ui` closure, so both run **once per layout pass** (a discard can + produce more than one). `raw_input_hook` is called once per host `update`, before `run_ui` (and + before `run_logic` on a hidden logic-only update), not per pass. +- **Web** (`eframe/src/web/app_runner.rs`): the same — `logic` then `ui` inside the `run_ui` + closure, per pass. +- **Headless** (`crates/ui-egui/src/headless.rs:320-325`): `Headless::step` calls + `HeadlessView::run(raw, |ui| { app.logic(ui.ctx()); app.ui(ui) })`, which is + `ctx.run_ui(raw, …)`; again per pass. +- **Hidden**: the integration calls `Context::run_logic`, which updates only window/focus state; + events, input time and layout remain from the last UI pass. +- After a completed `run_ui`, `current_pass_index()` is **0** (`ContextImpl::end_pass` takes the + output with `mem::take`; `run_dyn` restores the count only immediately before the next pass, and + `run_logic` does not restore an old index). During a second pass it is 1, 2, …. +- `ViewportInfo::visible()` derives from minimized/occluded and is `None` when unknown. **A hidden + window can still run a full UI pass**: `egui-winit`'s `ActionRequested::Screenshot` and + `PaintWhileHidden` both report `wants_paint()`, and eframe treats that as `is_visible` for the + pass (`wgpu_integration.rs:687-704`, `glow_integration.rs:680-693`). In that forced paint + `visible()` still reports `Some(false)`. + +Consequences: (a) `visible()` and fresh egui time are **not** a way to tell UI work from logic work; +(b) `current_pass_index() == 0` is a valid *known-UI-boundary* test for "first pass of this +`run_ui`", and it is also true during `run_logic`, so a hidden tick is never suppressed by it; (c) a +second pass has empty input events (`InputState::begin_pass` replaces events with `new.events`), so +event-driven code cannot run twice, while time/state-gated code can. + +### 4.2 The tick contract (no `TickPhase`, no visibility classifier) + +R1's `TickPhase { First, Later, Hidden }` and its time/visibility classification are **removed**. +They had no defined first-call, `visible() == None` or forced-hidden-paint branch, and their +stale-`current_pass_index` rationale was false. The replacement is a small, explicit split with a +monotonic clock and consumed queues: + +```rust +impl LightcraftApp { + /// Background/queue work. Called before layout on every host pass (native and web + /// inside `run_ui`, headless in `Headless::step`) and from `Context::run_logic` + /// while hidden. It may read `ctx.input(|i| i.viewport())` and `i.raw.focused` only + /// (those `RawInput` fields are refreshed by `run_logic`; `i.focused` and `i.time` + /// are not). Never events, dropped files or keys. + pub fn logic(&mut self, ctx: &egui::Context) { + i18n::set_language(self.ui.language); + panels::library_problem::logic(self); + panels::notices::logic(self); + if ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + } + let now = self.tick_now(); // monotonic; see 4.3 + self.drain_control(ctx); // control_rx.take() + try_recv: consumed once + self.renderer.poll(ctx, &mut self.session); + merge::poll(self, ctx); + import::poll_scan(self, ctx); + sync::poll(self, ctx); + sync::poll_run(self, ctx); + tasks::poll(self, ctx); + import::tick(self, ctx, now); // time-gated; second pass is a no-op + lightroom_import::tick(self, ctx, now); + recheck::tick(self, now); + self.slideshow_tick(ctx, now); + self.auto_import(ctx, now); + self.retry_sidecars(ctx, now); + self.scan_devices(ctx, now); + self.preview_build_status(ctx, now); + self.save_status(ctx, now); + self.pump_background_queues(ctx, now); // faces/denoise/model/focus worker results + self.collect_captures(ctx); // completion slot: take once + self.issue_captures(ctx, now); // admit/issue; deadlines use `now` + self.session.persist_if_dirty(); + if !self.synthetic.is_empty() { + ctx.request_repaint(); // visible gesture steps + } + if self.needs_paint_while_hidden(ctx) { // pending gesture, queued capture or settle + ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden); + } + } + + /// Input and once-per-layout-frame work: the known UI phase. + fn ui_pass(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + if ctx.current_pass_index() == 0 { + self.take_dropped_files(); // from the queue filled once by raw_input_hook + self.pump_ui_input(&ctx); // the input-reading halves of faces/denoise + self.update_perf(&ctx); + } + self.sync_theme(&ctx); + self.apply_settings(&ctx); + if self.fonts_ready { + shortcuts::handle(self, &ctx); // fresh events only + } + self.check_external_editor(&ctx); + self.resolve_pending_gestures(); // after this pass's layout, see 4.4/4.5 + } +} +``` + +Rules that the implementation and its tests must keep: + +1. **One consumer per queue.** `drain_control` takes `control_rx` out, drains with `try_recv`, + puts it back; replies are sent exactly once. The screenshot slot is `take`n once. Worker results + carry a generation id and are applied once. There is no "run the queue again" path. +2. **`current_pass_index() == 0` guards once-per-host-frame work**: dropped-file consumption, + input-reading halves (`pump_ui_input`) and perf update, and `import::tick`'s batch commit. A + hidden `run_logic` also reports index 0, so the same gate lets import work advance on a hidden + tick. It is *not* the gate for the other background timers: Lightroom import, slideshow, + auto-import, sidecar retry, device scan, recheck, toasts and autosave live in `logic` behind + monotonic deadlines. A wall-clock gate cannot substitute for the pass index: a discarded first + pass that takes longer than the throttle would re-run it inside the same host frame. Where an + operation needs "how many frames have actually run", use `Context::cumulative_frame_nr()` (one + per `run_ui`), not the pass index and not `cumulative_pass_nr`. +3. **Input lives in the UI phase.** `shortcuts::handle`, dropped-file handling and the + external-editor focus check move out of `logic_inner` into `ui_pass`. A hidden `run_logic` tick + can no longer re-read the last pass's `dropped_files` (today it would spawn the same import + again) and cannot consume a queued key. +4. **Only refreshed window state is safe in `logic`.** `run_logic` refreshes + `RawInput::viewports`/`RawInput::focused` only; `InputState::focused`, `InputState::time` and + events stay from the last pass. Read `i.viewport()`/`i.raw.focused` in `logic`, and `i.focused`/ + `i.time` only in the UI phase. +5. **No freshness inference from visibility.** `Some(false)` + a running `App::ui` is a normal forced + paint (pending screenshot or `RequestPaintWhileHidden`); `None` is normal for headless and + `RawInput::default()`. Visibility must not be used to tell UI work from logic work. It *is* + used deliberately for user-facing pacing: a minimized/occluded (`Some(false)`) slideshow pauses + instead of advancing and requesting full-size slide renders, and resumes with its remaining + time on unhide (P2.5 in the post-port review). +6. **First call / first frame.** `tick_now` is initialised at construction and every timer is an + `Option`/deadline comparison that is true on the first tick, so `Headless::step` at time `0.0` + and `ctx.run_ui(RawInput::default(), …)` (whose input time is `prev + predicted_dt`, not 0) both + run their first logic work. Add explicit tests for both, plus `visible() == None` and a forced + hidden paint (§6.1). +7. **No `will_discard` prediction.** A later widget may request a discard after logic has already + run; correctness comes from one-consumer queues and idempotent side effects, not from guessing. + +### 4.3 Hidden-time accounting: one monotonic clock, painting stays egui time + +`run_logic` leaves `ctx.input(i.time)` frozen, so any timer read from it in `logic` is stale. +Introduce an app clock and use it for everything that must progress while hidden: + +```rust +/// Seconds since the app was constructed. Monotonic (`web_time::Instant`): never goes +/// backwards, even when the window is restored after hours hidden. +fn tick_now(&self) -> f64; +``` + +- Use `tick_now` for: `import::tick` (additionally gated by `current_pass_index() == 0` so a + discarded pass cannot commit twice), `lightroom_import::tick`, `recheck`, slideshow playback + (`panels/slideshow.rs:157-183`; auto-paused while `ViewportInfo::visible() == Some(false)`), + auto-import (`lib.rs:1154-1187`), sidecar retry + (`lib.rs:1190-1214`), device scan, screen-profile refresh (`lib.rs:1316-1322`), + denoise/faces/focus/model timers, autosave/prefs cadence, capture settle/fallback/timeout + deadlines, and **toast expiry**. Each stores a next deadline and advances it only when + `now >= deadline`, so a second pass in the same host frame is a no-op. +- Toasts: store the deadline as a monotonic app-clock value; `save_status` (`lib.rs:785-808`), + `preview_build_status` (`lib.rs:756-781`) and `panels::toast` (`panels/mod.rs:80`) read + `tick_now`, not `ctx.input(i.time)`. A hidden toast then keeps its remaining time instead of + expiring the instant the window is shown. +- Keep egui time for painting, animation, gestures and widget interaction (all of which only run in + the UI phase). +- The web host's `safety::take_notices` (`apps/lightcraft-web/src/web.rs:654-656`) runs in `logic` + and today uses `ctx.input(|i| i.time)`; give it the same monotonic deadline. +- `Headless` exposes its simulated time through the same clock (a test hook; the current + `Headless::time` starts at `0.0`). + +### 4.4 Duplicate-work inventory (narrowed) + +The second pass has **empty events**, so `shortcuts::handle`, dropped-file handling and +`collect_screenshots`-style event scans cannot run twice from one gesture. The real duplicate +candidates are state/time-gated calls that `logic` runs on every pass (a monotonic deadline makes +the second pass in a host frame a no-op), and one call that is literally duplicated today: + +- `panels::faces::pump` is called twice in one pass (`lib.rs:1139` and `:1228`); +- `import::tick`, `lightroom_import::tick`, slideshow timers, auto-import, sidecar retry, device + scan, recheck and the toast/status updates are time-gated, so a slow second pass could fire them + again; +- `WebApp::run_inbox` and `load_originals` drain queues on every call (correct — they are consumed + queues), while `import_dropped` re-reads `raw.dropped_files` on every call and must not run in a + hidden tick or a later pass; it moves to the UI phase and consumes an app queue filled once in + `raw_input_hook`. +- `panels::denoise::pump` (`denoise.rs:45-52`) and `panels::faces::pump` (`faces.rs:705-712`) + read `ctx.input` keys/pointer/`i.time` to pace background work. Split each into + `pump_background` (download/index worker results, monotonic deadlines — safe in `logic`, including + hidden) and `pump_ui_input` (fresh key/pointer activity and its timestamp — UI phase only). A + hidden tick must never pace work from the previous pass's pointer state. +- `WebApp::save` stays guarded by its own `last_save` deadline, now on the monotonic clock. + +There is no evidence that event-driven handlers need multi-pass guards, so do not add them. + +### 4.5 Control gestures while hidden (geometry, paint requests, one reply) + +Today `ui.clickWidget`/`ui.dragWidget`/`ui.hoverWidget` read `app.widgets` from the previous pass, +`ui.pointer` maps through the previous `app.image_rect`, and `raw_input_hook` injects one pointer +event (or one up-to-release key run) per host frame. A hidden request can therefore click stale +geometry, and a multi-event gesture can stall after one `RequestPaintWhileHidden`. + +New contract: + +- **Geometry is resolved only after a fresh layout.** Control requests that need geometry are + admitted into a `pending_gestures` list with their original params and `admitted_epoch = + layout_epoch`; `layout_epoch` (a monotonic counter, not a hash) is incremented at the **end** of + every completed `App::ui` pass. A request resolves, using that pass's `app.widgets`/ + `app.image_rect`, at the end of the first pass where `layout_epoch > admitted_epoch`. If no UI + pass has happened since admission, the request stays pending and the app sends `ViewportCommand::RequestPaintWhileHidden` (when + `ctx.input(|i| i.viewport().visible()) != Some(true)`) so the next host iteration paints. + If the session has never laid out a UI, reply with an explicit "no current UI frame" error at the + deadline instead of inventing geometry. +- **One unapplied step survives repeated hidden ticks.** `raw_input_hook` is called before + `run_ui` and before `run_logic` (`epi_integration.rs:338-365,413-430`), so a hidden logic-only tick + can invoke it. The hook injects at most one queued gesture step and marks it in flight; it must + not inject another step until a completed UI pass (tracked by a UI-pass counter incremented at the + end of `ui_pass`, never by `visible()`) has consumed that step. The step remains in eframe's + `pending_raw_input` across hidden ticks unchanged. This prevents two hidden ticks from batching a + press and release into one later pass, and preserves key-press-through-release semantics. +- **Each gesture step keeps painting.** While `synthetic` is non-empty (a drag has many moves; a + click is move+down+up) the app sends `RequestPaintWhileHidden` again after each step is consumed, + so hidden gestures complete instead of waiting for the user. The hook still injects only one + pointer move or one key sequence per host update. +- **Exactly one reply, after delivery.** The reply is deferred until the gesture's final synthetic + event has been injected into a UI pass (a `pending_gesture.delivered` flag set at the end of that + pass), or until the monotonic deadline, when it replies with an error. A dropped sender gets no + reply; a canceled/closed request is removed before replying. This makes a successful reply mean + "the UI saw the gesture", not "events were queued". +- `ui.key`, `ui.text` and `ui.scroll` need no geometry but do need a UI pass to be consumed + (`ctx.request_repaint()` alone only runs `run_logic` while hidden), so they follow the same + request-paint/one-reply pattern. +- `ui.screenshot` is **not** a gesture, but it has two phases. Once the + `ViewportCommand::Screenshot` is processed, `ActionRequested::Screenshot::wants_paint()` makes the + integration paint a hidden window. A capture that is merely queued or settling in `logic` has not + reached that phase: while hidden it needs `RequestPaintWhileHidden` from `logic` (the same + predicate as pending gestures) to reach a UI pass that issues the command. Test both the + issued-command forced paint and the queued/settling hidden case; do not expect a missing + issued-command paint to fail. + +**Implementation amendment (2026-10-24, before code).** The app owns the queue described above: + +- `layout_epoch` is a `u64` incremented once at the end of every **completed, nondiscarded** + `App::ui` pass (the same place `ui_passes` advances). `PendingGesture` records `admitted_epoch`, + an admission-time `GestureFrame` (view, active photo, library generation, dialog discriminant, + left/right/presets/filmstrip switches), a monotonic `deadline_ms`, the original method and params, + its reply sender, and the computed result once resolved. At most 32 may be pending; a 33rd is + refused by a normal control error. The deadline is 5 s from admission (`GESTURE_TIMEOUT_MS`). +- `ui.clickWidget`, `ui.dragWidget`, `ui.hoverWidget`, `ui.pointer`, `ui.move`, `ui.click`, + `ui.drag`, `ui.key`, `ui.text`, `ui.scroll`, `ui.zoom` and `ui.clipboard` are queued. Their + existing parsing/event construction moves to one `control::gesture_events(&mut app, ctx, method, + params)` function, called **only after** a completed layout newer than admission. Widget ids and + `app.image_rect` therefore always come from that fresh pass, never the previous registry. A + widget that no longer exists, a missing image rect, an invalid key/unit/phase or a removed text + focus answers once with the existing error, after that fresh pass (not at admission). +- Resolution happens in `finish_ui_pass` after `layout_epoch += 1`. Before computing geometry the + request's `GestureFrame` must still equal the current frame. A view, active-document, library, + dialog or panel-layout change between admission and resolution cancels the request with one + error instead of retargeting the new UI. The per-frame `layout_epoch` advance that makes the + layout fresh is expected and is not itself a cancellation. A request that never sees a completed + UI pass (hidden with no paint) answers `no completed UI frame` at its deadline. +- Resolution appends the gesture's synthetic events and marks the request resolved. It is **not** + answered yet. The reply is sent when `app.synthetic` is empty after a completed nondiscarded pass + (for a zero-event action such as a clipboard paste request, after the next completed pass), so + `{"ok": true}` means the UI consumed the last event. A hidden run keeps sending + `RequestPaintWhileHidden` while any gesture is unresolved or resolved-but-undelivered; a visible + run keeps `request_repaint`. +- The queue is fail-closed on timeout: the request is removed, its reply error is sent once, and + queued synthetic input is cleared so a late event cannot click after an error. This can discard + another queued gesture's still-undelivered events; those requests are answered with their own + timeout/cancel error rather than being retargeted. The queue is intentionally not a general + scheduler: immediate commands (`engine.execute`, `ui.set`, `ui.inspect`, `ui.resize`, + `ui.zoomFactor`, screenshot admission) keep their current direct semantics. +- Limit: the `GestureFrame` cancellation covers the navigation/modal/panel state that can change the + meaning of an automation id. It cannot prove that a widget with the same id kept the same + semantic target across an arbitrary catalog refresh inside the same frame; the fresh layout and + the explicit view/document snapshot are the contract, not a per-widget identity guarantee. + +### 4.6 Screenshot capture: the shared CL-2F weak completion slot + +Anchors: `crates/ui-egui/src/lib.rs:909-987` (`drain_control`, `issue_screenshots`), +`:1034-1057` (`collect_screenshots`), `:1502-1525` (`PendingShot`), `control.rs:432-439`, +`headless.rs:133-174` and `:310-349`. + +craft-libs selects one narrow completion-slot helper (`crates/ui/src/capture.rs`, CL-2) after the +DesignCraft and GridCraft adapters, then freezes the public API (CL-2F). LightCraft is one of the +craft-ui capture consumers and **adopts that helper** rather than keeping the local +`mpsc::Receiver`/token design; names and signatures come from the reviewed CL-2F revision, not from +this document. Every creative capture consumer adopts the CL-2F completion contract: +`craft-ui-consumers-exact.json` shows eleven apps whose TOML declares `craft-ui` (LightCraft among +them). All eleven require craft-libs **CL-1** and the frozen **CL-2F** API in the same atomic +dependency stage as egui/winit; only DesignCraft/GridCraft pilot the provisional CL-2 API, and their +adapters land before CL-2F freezes it. DeckCraft, FigCraft and ArtCraft Native use +contract-compatible local adapters without adding the crate, and all fourteen capture consumers +remain in scope. (The earlier "thirteen craft-ui consumers" wording was wrong; it is not repeated +here.) + +LightCraft's adapter (app-owned policy, shared completion transport): + +- **One record per admitted request**, owned by the app: monotonic request id, path, reply sender, + `headless`, admission/deadlines (settle ≥3 painted frames and ≥120 ms; compositor fallback 2 s; + hard timeout after admission), frames waited, reserved bytes, and a snapshot of capture-time + geometry (`content_rect`, `viewport_pixels`, `pixels_per_point`, UI zoom). "Frames" means host + frames (`Context::cumulative_frame_nr()`, incremented once per `run_ui`), not passes, so a + multipass frame counts once and does not make a screenshot fire early. Take the geometry from the + refreshed viewport information (`i.viewport().inner_rect`, `native_pixels_per_point`) when present, + otherwise from the last laid-out content rect; a hidden window has no new layout, so both are the + last known size, and the reserved bytes are revalidated against the returned image. +- **Issue** with a callback holding **only** a `Weak` reference to the app-owned completion slot; + the app owns the strong slot and a live, owner-specific completion waker. The callback receives + pixels only: no `Context` clone, no `&mut LightCraftApp`, no encoding, file I/O or command + execution. On completion it locks the slot, stores the image, unlocks, and only then invokes the + waker; it never wakes itself from inside the lock or re-enters the app. A late or canceled + callback finds no upgradable slot and is a no-op. The renderer owns the callback until it fires, + so this is not a `Context` reference cycle; `Weak` lets cancel/close drop the app state and makes + a late result harmless. A pending capture keeps `request_repaint_after(16 ms)`, which also runs + `run_logic` on a hidden native window, so the woken poll collects completion while hidden. +- **Completion**: take the slot once, release the byte reservation with a checked subtraction, and + bind the image to the **issuance** UI geometry, DPI and zoom epoch. Any change to logical viewport + size, surface pixels, `pixels_per_point` or UI zoom between issue and save cancels and retries (or + replies with an error at the deadline) — even if the geometry changes back to the original values + before the image arrives. Never combine old pixels with new geometry, and never accept an image + merely because its dimensions happen to match. Reject an image larger than the reservation and + release its bytes, then encode/write on the UI thread and reply exactly once. Derive the effective + scale from the returned image dimensions and the recorded logical viewport (E2 surface fitting can + shrink the image); record that with the result. Additive result fields (`scale`, `viewport`) are + optional and backward compatible. +- **Admission is bounded before issue** using the shared capture defaults: at most **4** + outstanding requests, at most **128 MiB** per image, and at most **256 MiB** aggregate reserved + in-flight/completed bytes. App-specific caps may be stricter, never looser. Require + `0 < width,height <= max_texture_side` (16 384 at inspection), compute the reservation with + checked `width * height * 4` before issuing, and revalidate it after any geometry/DPI/zoom change + before issue. Reserve the **worst surface the request can produce** — the full logical viewport × + `pixels_per_point` × UI zoom × 4 bytes — not the smaller E2-fitted size, and keep + completed-but-not-yet-drained images counted until they are taken (in-flight and completed bytes + are both checked before issue). The renderer's own readback allocation is accounted separately in + peak RSS; a post-callback size check alone does not bound peak memory. +- **Cancel/close/drop/timeout**: remove the record first; the late callback's `upgrade()` fails and + the image is dropped with no second reply and no panic. On shutdown all reservations return to + zero. Tests assert retained bytes reach zero after drain/cancel. + +**Implementation amendment (2026-10-24, before code): path identity at write time.** Admission pins +the destination as a `WriteTarget` owned by the app record: +`WriteTargetState::Absent` (the directory entry did not exist) or `Existing(FileIdentity)` (device +and inode on Unix; canonical path, length and creation time on Windows, whose volume/file-index +metadata is still unstable; canonical/len/mtime elsewhere; taken from `symlink_metadata` so a link +replacement is a different entry). Admission +still runs the library `OriginalGuard`. Immediately before encoding/writing, **both** the renderer +callback completion and the CPU/headless fallback call `revalidate_write_target`: +- an `Absent` target must still be absent; a file created after admission (ordinary file, imported + original, hard link or symlink) is refused, never replaced; +- an `Existing` target must still be the same directory entry and must pass `OriginalGuard` again + against the current catalog, so a photo imported at that path while the capture was queued is + refused; +- an existing allowed screenshot destination keeps its normal overwrite behavior. +An absent destination is written through the new host `write_new` service +(`lightcraft_engine::export::write_file_new` → `safe_file::write_new`): it prepares a complete temp +file and publishes it with `create_new`/hard-link semantics, so the final TOCTOU window cannot +replace a file that appeared. The bounded temp file is encoded bytes only. An existing destination +uses the existing atomic writer after revalidation. Failure to configure `write_new` for an absent +target is an explicit error (fail closed), not a fallback to the destructive writer. Limits: an +existing destination can still be swapped by another process in the instant between revalidation +and the atomic rename; closing that would require an OS conditional-replace primitive. The lexical parent is now re-resolved before completion and compared with its admitted +canonical parent; a retargeted directory symlink is refused. The deterministic tests cover an absent +path that becomes an ordinary file, an absent path that becomes a catalogued original through a +hard link, an existing original/symlink refused at admission, an existing allowed overwrite, and an +existing target replaced by a new entry while queued, and a parent symlink retargeted between +admission and completion (neither destination receives a screenshot). +- **Both headless entry points change**: `HeadlessView::run` retains `ViewportCommand::Screenshot` + callbacks and calls `callback.complete(Arc::new(self.paint()))` after the pass; `Headless::step` + deletes its `ViewportCommand::Screenshot(user_data)` arm (it no longer compiles in 0.37) and no + longer pushes `Event::Screenshot`. Completion happens exactly once, in the headless host. +- `headless_host` remains the CLI/headless flag; `WebApp` does not set it, and the web path has no + control server (§4.11, §8). +- Boundary: the shared piece is only the completion slot. Request ids, paths, settle delays, + deadlines, reply schema and `Services.write/png` stay LightCraft policy in + `lightcraft-ui-egui`; do not grow a generic screenshot framework in craft-ui for LightCraft. + +### 4.7 Panels, IDs and docking + +Anchors: `crates/ui-egui/src/panels/mod.rs:52-77` (`resizable_side`), +`panels/bottombar.rs:24,371`, `panels/strip.rs:19`, `panels/topbar.rs:57`, +`panels/library_problem.rs:169`, `crates/ui-egui/src/docking.rs:430`, `shortcuts.rs:339`. + +`resizable_side` must pass the **original salt source** to the panel and derive the persisted key +from the same parent scope: + +```rust +// `Panel::new` stores `IdSalt::new(id)`; `Panel::id` is `parent_ui.scope_id().with_salt(store)`. +// `Id::with(salt)` is exactly `with_salt(IdSalt::new(salt))`, so this is the panel's real key. +let pid = ui.scope_id().with_salt(egui::IdSalt::new(id)); +ui.ctx().data_mut(|d| d.remove::<egui::containers::panel::PanelState>(pid)); +let panel = if left { egui::Panel::left(id) } else { egui::Panel::right(id) }; +// ... show ... +if !ui.ctx().is_being_dragged(pid.with("__resize")) { + return None; +} +``` + +Why this exact form: `Panel::left(salt)` with an already-built `IdSalt` would store +`IdSalt::new(salt)` and derive `parent.scope_id().with_salt(IdSalt::new(salt))`, which is not the +`pid` above. The `resize_widget_id` is `panel_id.with("__resize")`, so the drag check matches only +when `pid` is the panel's real key. Do **not** add a public `panel_state_id()`-style method to +production code: the mapping is a local detail, and a public helper would invite callers to use a key +that the panel never stores. Tests derive the key themselves from the same `parent_ui.scope_id()` and +salt, or assert on the returned response rect and the `panel:*` widget registration. + +Scope of the risk, honestly: at this revision `resizable_side` has **no production caller** (the +shipped side panels are craft-ui `DockArea` panels and the `Panel::top/bottom/right` bars). The bug +is latent, not user-visible today; fix it anyway, and keep the mutation test so a future caller +cannot reintroduce it. The `bottombar` fixture currently reads +`PanelState::load(&ctx, Id::new("bottom_bar"))` (`bottombar.rs:371`); under 0.37 the key is +`ctx.viewport_id().root_ui_id().with_salt(IdSalt::new("bottom_bar"))` in that harness (the fixture +shows the panel in the root `Ui`), or read the response rect instead. Audit every +`Panel::top/bottom/left/right` id whose value is persisted or queried; fixed-size bars can keep +string salts, but tests must not assume the old exact key. + +The first compatibility PR also migrates the old panel state explicitly: 0.36 stored +`PanelState` under the exact `Id`, 0.37 stores it under the parent-salted key, so old entries are +unreachable. Do not try to read them: at start, remove the legacy exact-`Id` `PanelState` entries for +the known panel salts (`top_bar`, `bottom_bar`, `tool_strip`, `library-problem-banner` and any +`resizable_side` caller) with `data_mut(|d| d.remove::<PanelState>(legacy_id))`, document the one-time +panel-width/layout reset in the stage notes, and assert in a test that the new keys are used. No +user-visible document, workspace JSON, catalog or XMP data is migrated; this is egui memory only. + +Second window: it already uses `ctx.show_viewport_immediate`, and `CentralPanel::show` takes +`&mut Ui` in both 0.36.2 and 0.37, so this is not a 0.37 rewrite. Verify under 0.37 that embedded and +native callbacks both register `view:secondWindow`, render the active photo and close correctly. +`#8748` (running an overdue window's UI without painting so deferred children open/close while the +root is hidden) is closed upstream but **not present** in the inspected fork source (no +`PassMode::Overdue`): P7c in the required P8 revision owns the selected fix. The second window while +the root is hidden/minimized remains an explicit real-platform test, not an assumed fix. Do not call +`root_ui` from the viewport callback. + +Docking stays `craft_ui::docking::DockArea`. LightCraft is an LTR application and must state that +policy explicitly at both call sites (`docking.rs:430`, `shortcuts.rs:339`) with the reviewed +`DockArea::direction(DockDirection::LeftToRight)` builder from craft-libs §7.7 (exact name from the +reviewed revision). Defaults must not be relied on. Persisted split first/second, axes, ratios, +floating rectangles and logical tab order must be unchanged, and painting, clipping, hit testing, +AccessKit order and drag insertion must use the same rectangles. `UiState.docking` format is not +migrated; verify save/reopen and `ui.dock` behavior in `tests/docking_workflows.rs`, plus that LTR +geometry is byte-identical to the current behavior. + +### 4.8 Fonts, language, accessibility + +Anchors: `crates/ui-egui/src/theme.rs:260-332` (`install_fonts_with_chinese`, +`font_definitions_with_chinese`), `i18n.rs:218-223`, `text_field.rs:180-235`, +`widgets.rs:1004-1020`, `tests/accessibility.rs`, `tests_keywording.rs:558-583`. + +- Enable `default_fonts` **and** `monochrome_emoji_fonts` on the workspace `egui` dependency, and + keep eframe defaults off in both apps while adding native `clipboard` (§2.1). This is a LightCraft + root/workspace decision, not inherited from kittest: kittest's normal `egui` dependency is + `default-features = false`, and only its own private dev-dependencies enable the fonts, which do + not propagate. Verify every root (native, CLI/headless, kittest, wasm) resolves them through + `cargo tree -e features`/`cargo metadata`, not through the lockfile (§5.3); a consumer test root + without the workspace features would otherwise see an empty `FontDefinitions::default()`. +- Tests: assert `FontDefinitions::default()` contains `Hack`, `Ubuntu-Light`, `egui-icons`, + `NotoEmoji-Regular` and `emoji-icon-font` (`epaint/src/text/font_definitions.rs:128-159`; the + family key is `Ubuntu-Light`, not `Ubuntu`); assert U+1F642 `🙂` and U+1F44D `👍` are paintable in + the Proportional family and that an emoji keyword/filename renders without tofu; keep the existing + font-count relation (`theme.rs:700-705` compares against `FontDefinitions::default()`, so adding + the two default emoji faces keeps the relation valid — re-check, do not silently update). +- Font fixtures for measurement/edge cases come from the egui plan §10.6 pins: craft-fonts + `2481a8a324b986a45954e90045ed1f8f2efaaf3c` (Arabic/Thai/CJK SC/Japanese, manifest-recorded + SHA256 + OFL) and the test-only Hebrew variable font and Noto Color Emoji v2.047 with their + recorded SHA256 and licences. Fetch them into the task's fixture directory; **copy no font file + into this repository** and do not add them to `assets/ATTRIBUTION.md` (nothing new is committed). + `CRAFT_FONTS_DIR` stays the app's font input; a future bundled font belongs in craft-fonts. +- Keep `egui_system_font_provider`/`system_fonts` off unless a separate measured decision adopts the + startup/coverage trade-off: the product policy is bundled Inter + craft-fonts and must stay + deterministic. #8512's startup cost is a separate workload if that decision is revisited. +- Production `MissingGlyphPolicy` stays `Tofu`; kittest keeps `Panic` (`HarnessBuilder` defaults in + 0.37 are `missing_glyph_policy: Panic`, `check_accessibility: true`). **All** existing harnesses + are therefore strict from the first green compatibility stage: every unnamed input and every + missing glyph must be fixed (names via `Response::labelled_by`/`accessible_name`/ + `ui.label_inputs_by`, real fallback faces), never by disabling the check globally. A deliberate + tofu/unnamed probe opts out locally in that test only. +- Wire the fork's `Context::set_language` (`context.rs:2629`) from `i18n::language()` on start and + when it changes, so the AccessKit root language and bidi runs follow the locale. Command ids, + catalog data and user strings stay logical; this is presentation only. The in-process i18n + remains the source of truth. Do not import craft-libs #198 or any font asset. +- Keep `TextField`'s custom menu and selection memo; add the #8763 click-away regression (§6.3). + +### 4.9 Text input, IME, RTL, clipboard and PRIMARY + +- `Event::MouseWheel` initializers in `control.rs`, `headless.rs`, examples and tests get + `source: egui::MouseWheelSource::Unknown`; `ui.scroll` accepts optional + `"source": "unknown"|"wheel"|"trackpad"|"momentum"`, `"unit": "point"|"line"|"page"` and + `"phase": "start"|"move"|"end"|"cancel"`. Omitted values keep the pre-0.37 request meaning: + `Unknown`, `Point`, `Move`. Every value is validated before an event is queued; an invalid value + is a control error and changes nothing. This lets tests drive the grid/filmstrip + `MouseWheelUnit::Line` path and trackpad/momentum `TouchPhase::Start`/`End` cycles, which the + point/move-only API could not represent. `docs/control-protocol.md` documents the three optional + keys. Unit tests assert wheel/line/start, trackpad/point/end and the backward-compatible omitted + defaults. +- `raw_input_hook` keeps the §4.5 one-step-per-UI-pass contract; a logic-only tick must not drain + another step. `Event::PasteImage` and `MiddleClickPaste` are not app shortcuts — `keymap.rs`'s + recorder ignores them. +- **E21b/P7b is a new blocking prerequisite, not existing E21 behaviour.** Candidate egui-winit + never calls `WindowExtWayland::set_ime_surrounding_text`, and `egui::IMEOutput` carries no logical + text. The complete shared contract is in egui plan P7b and `ime-surrounding-gap.md`; LightCraft + must take all of it, not a weaker subset: + - owner/context-generation identity is present even when surrounding text is **Unavailable**. An + available **empty** document is distinct from unavailable and is sent explicitly as an empty + payload, not omitted; + - changing owner or available/unavailable support clears the cached text and commits the + protocol's disable/enable boundary (not merely empty text); same-owner ordinary updates preserve + composition; the old preedit is canceled, not inserted into the new editor; there is no + cross-window bleed; + - the final completed pass's descriptor, including an authoritative `None`, is what + `PlatformOutput::append` uses (replace `ime.or(self.ime)`); descriptor, owner and payload are + one atomic value; + - focus epochs and protocol serials are tracked separately: a current-epoch `done` with a + mismatched serial applies incoming edits **once** and defers outgoing state until a matching + serial; an obsolete owner/epoch invalidates its pending batch. Never drop valid incoming edits; + - the payload is bounded (≤4000 UTF-8 bytes, valid boundaries, preedit excluded, byte + cursor/anchor, explicit unavailable when a selection cannot fit) and the **new** payload path + allocates no full-document clone. Existing `TextEdit` change-detection/undo clones are a + separately measured baseline, not rewritten here; + - built-in `TextEdit` produces the payload after delete/commit/cursor updates (logical model + text, preedit removed, byte indices remapped) and the Wayland adapter sends it through W27. + LightCraft has no custom `IMEOutput` producer: its `TextField` wraps the built-in `TextEdit` and + other panels use `TextEdit` directly, so it **inherits** the producer and must test the inherited + behaviour. The family's custom editors (FilmCraft `panels/graphics.rs` and the others in + `ime-surrounding-gap.md`) need real logical-model/preedit/UTF-8-index adapters before family + acceptance; `None` placeholders are not a completed port. +- IME tests: outgoing surrounding text immediately after deletion-only and delete+commit batches; + preedit excluded; reversed selection; supplementary/combining/RTL text; cursor movement; a very + long line and an over-limit selection (explicit unavailable, not a truncated claim); available + empty vs unavailable; field and two-window switches; owner transition with committed + disable/enable; password/no-IME clears; focus loss/reset/late serial; a current-epoch serial + mismatch applying incoming edits once while outgoing waits, and a stale-epoch batch discarded; + multi-pass final output including authoritative `None`. One native Wayland + Vietnamese/predictive trace checks the outgoing protocol plus editor text and one undo + transaction. +- Bidi: a mixed Arabic/Hebrew + Latin filename and keyword stays logical in catalog/XMP while + painted text/caret/selection follow visual order, with no double bidi and no tofu when the + craft-fonts face is present. The UI stays LTR; do not enable `Style::right_to_left`. +- Clipboard: native `clipboard` feature (§2.1), normal cut/copy/paste through `ui.clipboard`, the + text-field menu, and PRIMARY middle-click. E4 and **W15P** are one compatibility unit: the + inspected E4 uses an arboard fallback and does not provide the required winit-owned per-seat + PRIMARY path. Require the complete P8/W15P revision: PRIMARY has its own protocol object on the + existing connection/event queue (SCTK 0.19.2 `PrimarySelectionManagerState`/device/source/offer; + never a second regular `wl_data_device`), and accepts a fresh trigger serial from **either a + pointer press or keyboard focus** on the focused seat — do not impose a keyboard-only rule. + Selection claims are synchronous while the trigger serial is fresh; serving and transfer are + asynchronous. P2b replaces blocking reads/writes on the egui event path with caller-owned bounded + async transfer handles: a total **2 s** deadline (not a per-`WouldBlock` poll timeout), a + **16 MiB** byte cap, at most **four** read workers and **two** writer workers with queue depth + **8**, an owner-specific live completion waker, and cancellation/discard of stale results when + focus, target, owner or input generation changes. Test on wlroots/KWin/Mutter: keyboard- and + pointer-triggered selection with valid per-seat serials, middle-click paste, password exclusion, + no reclaim of an unchanged selection, owner/seat change, empty/absent offer, self-paste, slow + trickle, oversized offer, cancellation, and UI event-loop responsiveness during a slow transfer. + A compositor limitation is recorded, not papered over with a control-channel substitute. + +### 4.10 GPU and renderer behavior + +Anchors: `apps/lightcraft/src/window_gpu.rs:104-200` (`choose`, `base_options`, `probe`), +`main.rs:917-940`, `crates/ui-egui/src/softpaint.rs`, `crates/ui-egui/src/render.rs`. + +- Keep the Windows probe/fallback design: DX12 → Vulkan → GL → glow, with error scopes and a + non-panicking wgpu error handler. `Renderer::new(device, format, RendererOptions)` is unchanged in + the inspected source; re-run the probe tests and the Windows startup matrix. +- E2/E3 (surface fit and configure/renderer error scopes) are required for very large or + multi-monitor surfaces; test a window larger than the device limit via + `LIGHTCRAFT_GPU_LIMITS=webgpu` and the fork's unit tests. A surface failure must be a typed error + and the next renderer/CPU fallback, never a panic. +- #8736 (DX12 FXC shader-compile cost) is measured as its **own** workload: the probe's pipeline + construction and eframe's first frame separately, fresh processes. A clamp-only shader change is + not a valid fix (it changes Repeat/MirroredRepeat semantics); evaluate the upstream/float-`select` + or pipeline-constant design with equivalent wrap tests. +- #8731 (plain-text tessellation) is its **own** workload: a text-heavy fixture (grid metadata, + menu labels, panel rows) with mixed color-glyph rows, baseline/stock-0.37/fork. Do not cache or + alter texture wrap/filter semantics to hide it. +- Photo textures remain `TextureOptions::LINEAR`; `softpaint`'s CPU mirror preserves nearest vs + linear per `ImageDelta` and texture wrap. kittest uses `RendererOptions::PREDICTABLE`; check + #8441's nearest-filter fix did not change preview/texture semantics. +- On DPI/zoom/resize, verify textures are updated/freed, the screenshot size contract stays + `viewport_pixels`/`resized_viewport`, and the softpaint shadow context uses the same UI zoom. + +### 4.11 Host adapters and persistence + +- Native `App::logic` becomes `self.0.logic(ctx);` then the native menu and `PrefsWriter::tick` + (both on the monotonic clock). `App::ui` stays one `self.0.ui(ui)`. Do not call `self.0.logic` + again from `ui`. `PrefsWriter::tick` must not record `Seen::of` window geometry from a hidden + `run_logic` pass whose `content_rect` is stale: keep the last known placement. +- Web `WebApp::logic`: `safety::take_notices` (monotonic), `run_inbox` (every call: consumed queue), + `load_originals` (every call: drains a queue), the worker budget, then `self.app.logic(ctx)`, then + `save` (own monotonic deadline), then the bench step (UI phase). `WebApp::ui` remains one + `self.app.ui(ui)` plus the first-frame log. `import_dropped` moves into the UI phase and consumes + the queue filled once by `WebApp::raw_input_hook`, so neither a later pass nor a hidden tick can + re-import the same drop. +- Keep `raw_input_hook` once per host frame; it takes synthetic events and dropped files into + app-owned queues, and the in-flight step gate in §4.5 prevents repeated logic-only ticks from + draining more than one synthetic step. Do not move injection into `ui`, where it would repeat on multipass. +- Keep `PrefsWriter` and `UiState` JSON unchanged. The only visible ID change is egui memory/panel + layout; `UiState` docking, settings, recent libraries, keymap and library catalog formats are not + migrated. Test edit → save → close → reopen and undo semantics with the existing library tests. + +## 5. Dependency graph, pin and lockfile acceptance + +### 5.1 Intended graph + +```text +lightcraft / lightcraft-web / lightcraft-cli / lightcraft-ui-egui + -> egui 0.37.0 (published storytold revision, immutable SHA) + + epaint, epaint_default_fonts, ecolor, emath + -> eframe 0.37.0, egui-winit, egui-wgpu, egui_glow + -> egui_kittest 0.37.0 (dev) -> kittest 0.5.0 (registry), accesskit 0.25.x + -> winit 0.30.13 (published storytold revision, immutable SHA) + -> craft-ui from the reviewed craft-libs revision (stock-egui-0.37 source compatible, CL-2F) +``` + +An incompatible `craft-ui` bump in any consumer is part of the same atomic dependency stage as the +egui/winit graph; never a separate version step that leaves the suite half-migrated. + +Root `[patch.crates-io]` must name every used package at the same full SHA: `egui`, `eframe`, +`egui-winit`, `egui-wgpu`, `egui_glow`, `egui_kittest`, `epaint`, `epaint_default_fonts`, `ecolor`, +`emath`, and `winit`. Add `egui_extras` only if it enters the graph. Do not patch `egui_plot`, +`egui_dock`, `egui_inspection` or `egui_system_font_provider` unless used. Never use a branch name +or a machine-local path in a publishable manifest. + +`craft-ui`'s own `[patch]` does not propagate: LightCraft's root patch is what gives +`eframe`/`egui-winit` the fork. A graph that resolves `winit` from crates.io while `egui-winit` +expects the fork API is a failure. `craft-ui` must compile against the stock egui 0.37 source API +(PR 199's role/`scope_id`/`IdSalt` edits) so the shared crate stays publishable; fork-only APIs stay +out of craft-ui. Pin `craft-ui` to the reviewed craft-libs revision and verify its `serde` feature +under LightCraft's root patch. + +### 5.2 craft-libs: use the reconciled base, never the stale trees + +- Current local shared-library base: `3832c47ef68a0e6214f2c1e85f3526b6adcb686e`. It already + carries the egui 0.37 API port (the historical `8614e4a` shape and the `1764bca` README hunk); + those commits and the earlier `49190884278f16c9a9f5823d7698a8ffb5deb062` main are history, not + the base to apply again. +- PR 199 head `b68de8c5f4f1c060904d211a7b1320aa0f7bce78` and the audit merge + `ec8840af8c5fda695cf195cdd05e5ae078415c07` miss `craft-platform` and revert newer + security/settings/docking/printer fixes. Never merge either as a tree. +- Keep the `craft_ui::capture::CaptureSlot` consumer adapter on the reconciled base, preserve + every newer fix, and re-run craft-ui's own tests and visual fixtures after the port. The CL-2F + helper and the exact immutable publish SHA remain central-publication gates; neither is guessed + here. + +### 5.3 Checks + +Add an `xtask` dependency check (for example `xtask/src/deps.rs`, invoked by `cargo xtask ci` +before clippy). The check takes its expected graph from a mode/fixture: L1 runs it in 0.36.2 +baseline mode and is green today; L2a flips the expected graph to the 0.37 P8 graph in the same +atomic dependency commit. The negative fixtures run in both modes. `Cargo.lock` records packages, +versions and sources but **not resolved features**, so it can only prove identity: + +- lockfile/metadata identity: exactly one `egui`/`epaint` family source and one `winit` source, all + at the expected git URL and full revision; no registry copy beside them; `craft-ui` and + `craft-docpath` at the reviewed revision, not a branch or a path; +- resolved features from `cargo metadata` + `cargo tree -e features` for every accepted root + (native, headless/CLI, tests, wasm): `egui` has `default_fonts` and `monochrome_emoji_fonts`; + native `eframe` has `clipboard`; the wasm root does not accidentally pull `wgpu`; `craft-ui`'s + features resolve as intended. Record the raw output in the evidence; +- negative fixtures, each of which must fail: missing patch, branch pin, second registry `egui`, old + `craft-ui`, machine-local path, feature-less `egui` (the last one only through the + metadata/tree mechanism — a lockfile-only check cannot catch it); +- `wasm-bindgen` in the lock matches the CLI (`xtask/src/web.rs` already checks this). + +Run `cargo tree -d`, `cargo tree -i egui@0.37.0`, `cargo tree -i winit@0.30.13`, +`cargo metadata --locked`, `cargo check --locked --workspace --all-targets` and the wasm graph under +the same pin in managed jobs (§7.1). A clean checkout must fetch every approved revision and pass +`--locked` without local overrides. Recheck remote heads before merge; an immutable SHA is required +even if the remote branch moved. Record the lockfile SHA-256 and keep the 0.36.2 lockfile for +rollback. `accesskit` moves to 0.25.x, `kittest` to 0.5.0; review that churn. Nix's `cargoLock`/ +`allowBuiltinFetchGit` must fetch the git sources; run `nix build` if available, otherwise record +the explicit unavailable gate. + +## 6. Regression assertions + +### 6.1 Functional and lifecycle + +- **One command/undo step per user action under multipass.** Use the existing + `right.rs:1161` `request_discard` path plus a test-only forced discard, press one rating/flag key, + and assert one catalog op/undo entry, one toast, one repaint request and identical settings. + Repeat through the control channel. +- **Control gesture delivery and screenshot paint predicate (implementation amendment).** A queued + `ui.clickWidget` with a stale registry answers only after a completed fresh layout; an id that + disappears answers once; a view/dialog/document change between admission and resolution answers + once with a cancel error; a hidden gesture receives `RequestPaintWhileHidden` while unresolved or + undelivered and replies only after its last synthetic event is consumed; a 5 s deadline answers + once and clears the queued events. A screenshot that is only queued/settling (`sent_at_ms == + None`) requests a hidden paint; one already issued (`sent_at_ms == Some`) does not, while its + 2 s compositor fallback and hard timeout checks still run every logic tick. +- **Hidden logic continues.** Repeated `ctx.run_logic` calls while hidden advance + import/Lightroom-import/recheck/task/autosave/persist/retry/slideshow work, do not consume a queued + key/text/drop, and do not replay the last pass's dropped files. A hidden tick that invokes + `raw_input_hook` leaves one queued synthetic step in flight; repeated hidden ticks must not inject + further steps or batch press+release, and the next full pass consumes exactly one. Cover: a + completed multipass frame followed by hidden ticks (`current_pass_index() == 0` each time, so + nothing is skipped); `visible() == Some(false)`; a forced hidden paint with pending input and with + a pending screenshot; restore with buffered events (each consumed once); a worker completion + between passes. +- **First frames.** `Headless::step` at simulated time `0.0` runs logic and lays out; a harness that + calls `ctx.run_ui(egui::RawInput::default(), …)` runs logic; `visible() == None` is treated as + normal; the first forced hidden paint processes input. +- **Screenshot capture.** Two outstanding requests get their own image and exactly one reply; a + queued/settling hidden request receives `RequestPaintWhileHidden` before issue while an issued + screenshot forces its own paint; + complete out of order; drop/cancel then complete the callback (no reply/file/panic; reservation + back to zero); 2 s compositor fallback and hard timeout; an issued hidden-window request completes + via the screenshot's own forced paint while a queued/settling one first needs the paint request; + headless request completes through `HeadlessView::run` and + `Headless::step` (both, once); a resize between issue and completion retries or errors rather than + mixing geometry; oversized dimensions are rejected before issue. +- **Control gestures while hidden.** `ui.clickWidget`, `ui.dragWidget`, `ui.pointer` with + `space: "image"`, and a multi-step drag each complete while the viewport reports hidden, using the + first fresh layout after admission, send a paint request per step, and reply exactly once after + the last event was delivered. A widget that no longer exists replies with an error once. +- **Save/reopen.** Edit exposure/keywords/mask, save/persist, close, reopen the same synthetic + library; assert document meaning, selection/workspace and undo. Assert `UiState` JSON round-trips + and docking/floating geometry survives unchanged. +- **Docking and second window.** Real drag → float → close → reopen and `ui.dock` invalid requests + preserve the selected tool/layout (`tests/docking_workflows.rs`); explicit LTR direction leaves + saved rectangles and tab order unchanged; the embedded second window renders the active photo and + closes; the native second window focus/close/reopen is a real-platform test. + +### 6.2 Geometry, hit-testing and pixels + +At 1400×900 and 900×700, scales 1.0/1.5/2.0, dark/light themes: + +- top bar 42 pt, bottom bar 48 pt, tool strip 48 pt, default side widths from `UiState`; panel order + top → banner → strip → central → side panels; canvas rect equals the remaining rect within 0.5 pt; +- dragging the left/right inner edge by ±120 pt changes the stored width within 2 pt and the + registered `panel:*` rect within 1 pt; the photo area never falls below `MIN_PHOTO_WIDTH`; +- the `resizable_side` test asserts the drag edge is live through the corrected `pid` (and fails if + the panel is constructed with a pre-hashed `IdSalt`); +- grid/filmstrip/menu scroll offsets and hit rects agree after wheel, drag and resize; menu arrows + scroll and stop at bounds; +- dialogs are centered and fit; a long translated title/label does not overflow (`tests_dialog_fit`, + `tests_labels`, `tests_masking_layout`). + +Pixel comparisons use 1600×1000 at 1× and 2×, deterministic `Session::with_demo()` and pinned fonts. +Keep reviewed baselines in task evidence, never `UPDATE_SNAPSHOTS=force`; compare with a predeclared +metric: region geometry exact ±0.5 pt; count of pixels differing by >2 LSB and mean absolute +difference per region; a change in the top bar, side panels, canvas or menu requires review. +Determinism alone is not acceptance. + +### 6.3 Accessibility and keyboard + +- The strict kittest checks are on in every harness from L2a: no unnamed input, no missing glyph. + Extend `tests/accessibility.rs` to the roles `is_input` uses (`DisclosureTriangle`, `Splitter`, + `Tab`, inputs) and to the second-window embedded tree. Sliders have value/range; dialogs have + titles; hidden controls disappear. + Custom disclosure rows use the actual 0.37 API: `WidgetInfo::labeled(Role::DisclosureTriangle, + enabled, label)` plus `ctx.accesskit_node_builder(resp.id, |node| node.set_expanded(open))`. + They must not use `WidgetInfo::selected`, which fills AccessKit `Toggled` rather than `Expanded`. + A unit test asserts `is_expanded()` is `true`/`false` for `widgets::section_header`; the same + helper is used by `widgets::flyout_row`, the panel fold headers and the sidebar section headers. + (An accessibility-tree run over the Edit/Keywords views remains part of the broader accessibility + suite, not this focused state test.) +- Tab order stays top-to-bottom in panels; screen-reader Increment/Decrement/SetValue and + Enter/Space/arrow actions trigger the same commands as the pointer. +- Focus/edit/drag state does not transfer when the language changes, a panel hides, rows are + inserted, or a menu opens. `Id::unique` preserves `Id::new`'s hash, but a wrong `IdSalt`/`scope_id` + in a container can still move state. +- Text field: select range → click-away action uses that range (#8763); Esc restores; Return/away + commit; IME preedit/commit/cancel one edit/undo; bidi caret/selection in logical and visual order; + emoji keyword/filename renders without tofu. + +### 6.4 Mutation/negative controls + +Bounded probes that fail before the fix, kept as unit-level negative tests where cheap: + +- a capture slot completed for the wrong request: no file/reply; a late callback after cancel: no + reply/panic and released bytes; +- a deliberately duplicated command path under `request_discard`: the one-undo test fails when the + first-pass guard is removed; +- `resizable_side` with the old exact `Id` or a pre-hashed `IdSalt`: the drag test fails to see the + resize widget / does not store the width; +- one unnamed input in a scratch kittest harness: `check_accessibility` panics; +- one unsupported glyph: `MissingGlyphPolicy::Panic` panics and `Tofu` does not; +- a hidden `ui.clickWidget` while the widget registry is stale: the request resolves only after a + fresh layout (test fails if the old geometry is used). + +## 7. Performance protocol + +### 7.1 Baseline, candidate and control + +Build the baseline `23e18128`, the **stock** 0.37 control and the fork candidate in separate managed +`task.py run --kind build` allocations with distinct source/evidence paths (§8). Use the same Rust +toolchain (`1.99.0` at inspection), `--release`, same features (`denoise` default; `heif` separately), +same `CRAFT_FONTS_DIR` revision (craft-fonts `2481a8a`), same corpus files, same profile (including +`debug = "line-tables-only"`), same renderer/driver, viewport and DPI. Record full commit, lock +SHA-256, resolved features, fonts, fixtures, OS, CPU, RAM, GPU adapter/driver, renderer backend, DPI +and whether the GPU is enabled. Alternate execution order; never benchmark concurrently with a build +or another noisy workload. + +Fixtures: `Session::with_demo()` (deterministic), a 10,000-photo synthetic library from the +`grid_bench` generator, and the pinned 24 MP corpus raw (`cargo xtask corpus --download`; gitignored). +No corpus or `CRAFT_FONTS_DIR` was present at inspection, so these are explicit prerequisites. + +**Comparisons.** Report baseline 0.36.2 → candidate, and stock 0.37 → candidate wherever an +equivalent workflow exists in stock 0.37, so a fork-induced regression is not confused with a +0.37-induced one. The stock control uses the same fixtures, profile, fonts and environment. + +### 7.2 Operations and sample counts + +- **Warmups**: at least **10** warmup iterations per steady operation, discarded. +- **Steady operations**: at least **30** timed iterations (slider drag, menus, control operations, + opening photos), 10 repetitions for cold/warm open. +- **Startup**: **20** fresh processes per side, to first UI frame and to thumbnails settled; + separate process start, renderer/probe construction, font setup and first frame. +- **Frame distributions**: at least **1,000 actual painted frames** before any p50/p95/p99 claim + (not synthetic logic ticks, not 20/30/50 samples), counted from `Context::cumulative_frame_nr()` + or the equivalent painted-frame counter. Report median/p95/p99 with the actual frame count. +- **Grid**: `grid_bench` 200 and 10,000 photos, 60 unchanged frames, both grid modes, 1× and 2×; + median/p95, per-frame UI allocations, cells visited, layout rebuilds. +- **Slider drag**: `drag_latency` on the 24 MP raw, 27 controls, `TICKS=30`, CPU and GPU separate; + median/p95 draft texture latency and full render after release. Existing budgets: ≤16 ms draft, + ≤60 ms loupe; export ≤1 s/24 MP JPEG. +- **Thumbnails/menus**: `thumb_request_bench` with blocked rendering for allocation counts; a long + menu open with wheel/arrow scroll, 1,000 actual frames. +- **Opening photos**: `open_timeline` with pinned raws, warm and cold, 10 repetitions. +- **Control/UI operations**: `ui.screenshot` (headless), `ui.inspect`, grid scroll and panel drag, + measured request → reply over 30 samples. +- **Separate workloads, never one blended number**: (a) **#8731 text tessellation** — text-heavy + fixture, plain text vs mixed color glyphs; (b) **#8736 DX12** — fresh-process pipeline/probe + construction and first frame on Windows DX12; (c) **#8512 font startup** — font discovery/setup + time in a fresh process with and without the bundled faces. +- **Idle**: 60 s visible and 60 s minimized/hidden; process CPU time, `cumulative_frame_nr` (an + additive `perf.frames` only in the instrumentation stage), repaint count, GPU work and RSS. A new + busy loop or a repaint while hidden beyond requested work is a failure. +- **Web**: `cargo xtask web` **raw and compressed WASM size** (raw, gzip, brotli; separately record + the effect of `monochrome_emoji_fonts`), `?bench` first frame, thumbnails, eight slider steps and + release render, 10 fresh page loads per side, one browser/version and a software/ANGLE equivalent + if available. + +Record peak RSS, allocation/texture-upload counters, cold vs warm caches and idle CPU separately. + +### 7.3 Predeclared acceptance and noise policy + +Shared suite thresholds (do not loosen them): investigate a repeatable **>5 % median** or +**>10 % p95** latency regression, **>5 % peak-RSS increase**, any new idle busy loop/repaint, any +missed slider/loupe/export budget, or a visual/document regression. App-specific gates may be +stricter. Apply a documented noise floor: for sub-millisecond values require the relative increase +to exceed 0.05 ms or corroborate with stable instruction/allocation counts. The **stock 0.37 +equivalent control** is required in the first report and for every regression decision, so a +0.37-induced change is not attributed to the fork; stock 0.37 remains a control, never a production +stage. Reject noisy comparisons as inconclusive and rerun; **do not widen thresholds** after seeing a +failure. #8731/#8736/#8512 figures are upstream reports, not our measurements; compile duration is +not UI performance. + +## 8. Platform evidence and provisioning gates + +Every row is a **provisioned environment gate**, not a claim that the current host or a previous run +passes. A row without provisioned hardware/OS/browser is recorded as unresolved, never as a pass. + +| Platform | Required workflow | Acceptance | +|---|---|---| +| Linux X11 | Managed native run of the exact candidate with `--control PORT`, control script, native screenshot, edited/saved/reopened library; both themes, 1×/2×; renderer recorded. Requires a real X11 session (none is inherited by this server shell) | Real window; CPU and available GPU reported separately | +| Linux Wayland | Same on a named compositor (wlroots/KWin/Mutter) provisioned for the task; clipboard/PRIMARY, drop, IME, hidden second window | E4 + W15P matrix from §4.9; any compositor limitation recorded if reproduced | +| Windows | Owned `craft-windows` clone (own disk, UEFI, TPM, ports, 128 GiB reservation), native build of the exact candidate, visible grid/detail/edit workflow, screenshots, save/reopen, FXC/DX12 probe, software-renderer baseline and real GPU if present | Start-up/first frame measured; no panic/black window; DX12→Vulkan→GL fallback | +| Web | `cargo xtask web --serve` in a provisioned browser environment; browser automation drives observable `command(...)` actions (thumbnail/detail/slider/save state) and captures the canvas with the **browser's** screenshot facility; console errors checked; `?bench` | Real browser workflow; wasm module and CJK/emoji assets present; not just `cargo check`. There is no control server and `ui.screenshot` is not a `LightcraftApp::run` command (`web.rs:609-644` → `self.app.run`), so a browser capture is the only screenshot path unless a separate reviewed download/writer API is added | +| FreeBSD | Repo workflow with craft-fonts, if a runner is provisioned | Compile/test evidence or explicit unresolved gate | +| macOS | Real macOS hardware (not cross-compilation) for menu/IME/Metal/GL/termination/AccessKit teardown | Separate unresolved blocker | + +No claim is made that this server has no GPU: read-only inspection finds an i915 PCI `8086:3E96` +render device and readable/writable `/dev/dri/renderD128`. That is **availability evidence only**, +not a qualified Vulkan/OpenGL/compositor result. No display session is inherited, and Windows +baseline rendering remains software-rendered. + +Headless rendering is not proof of native focus, IME, file picker, compositor clipboard, screen +reader or GPU presentation. A windowed `ui.screenshot` that logs the "rendering headlessly" fallback +does not satisfy native acceptance. + +## 9. Reviewable PR stages, dependency DAG and rollback + +```text +P0 (external; BLOCKED until published) + storytold egui immutable revision P8: E1-E21 + P2b (E4 regular/PRIMARY with bounded + async W15P transfer) + P7 held-key pairing + P7b/E21b + P7c (#8763/#8748 and + justified perf fixes), reviewed and published + storytold winit immutable revision: complete W15P + W27 lifecycle (+ W15/W25/W26 series) + craft-libs CL-1 revision, then CL-2 provisional capture slot + CL-2 -> DesignCraft/GridCraft adapters -> CL-2F API freeze + | +L1 baseline harness/instrumentation + baseline-aware xtask dependency check + evidence scripts + (0.36.2 expected-graph mode; works today; no product UI change, no new pins) + | +L2a coherent graph + compile migration (manifests, lock, patch, Id/Role/scope/ComboBox/Event + source, default_fonts + monochrome_emoji_fonts + native clipboard, CL-2F screenshot + callback/admission/drain/timeout/basic reply handling, scroll offset read/write, strict kittest naming/glyph fixes, all -D warnings) + -- atomic; no unbuildable intermediate commit on main. BLOCKED on P0. + | +L2b lifecycle/root-UI hardening (tick split, monotonic clock, dropped-file queue, panel IDs, + hidden gesture queue, CL-2F capture stress tests, both headless hosts, second-window/docking tests) + -- needs CL-2F (DesignCraft/GridCraft are the CL-2 pilots). + | +L2c fonts/accessibility/language/IME/clipboard hardening (set_language, #8763, E21b/W27 tests, + W15P/E4 PRIMARY matrix) + | +L2d measured visual/perf acceptance, docs updates, platform evidence and final review +``` + +P0 is **explicitly blocked**: the final approved storytold immutable SHAs are unknown until the fork +and winit series are published, and this plan does not invent them. `a4f9a17f`/`8b35388b` are used +only to inspect behavior. L2a–L2d cannot be prepared as merge-ready changes until P0 exists. +L1 can start now in 0.36.2 expected-graph mode; L2a switches the dependency check to the 0.37 P8 +graph. L2a is one atomic dependency stage: the complete egui/winit P8 graph plus the required +craft-ui revision (CL-1 and CL-2F for the eleven `craft-ui` consumers; DesignCraft/GridCraft CL-2 +pilot adapters precede CL-2F). Any incompatible existing craft-ui bump belongs in that same atomic +stage. Stock 0.37 is only the measurement control, not a production stage. + +Expected file ownership: L1 adds `xtask/src/deps.rs` (plus dispatch), test/bench harness scripts +under `tools/egui037/` and non-product tests; L2a changes `Cargo.toml`, `Cargo.lock`, the three app +manifests, `crates/ui-egui/Cargo.toml` and the mechanical compile sites in +`crates/ui-egui/src/{lib.rs,widgets.rs,control.rs,headless.rs,menu_level.rs,panels/*}` plus +`apps/lightcraft/src/main.rs` where an API changed; L2b owns `lib.rs`, `panels/mod.rs`, +`panels/{faces,denoise}.rs`, `panels/second.rs`, `headless.rs`, `control.rs`, +`apps/lightcraft/src/main.rs`, `apps/lightcraft-web/src/web.rs` and lifecycle tests; L2c owns +`theme.rs`, `i18n.rs`, `text_field.rs`, `widgets.rs`, `tests/accessibility.rs` and the +IME/clipboard tests; L2d owns only reviewed visual/perf evidence and progress documentation. + +L2b–L2d are separate dependent PRs; they may be implemented on separate branches after L2a but merge +one at a time, re-running `cargo xtask ci` after each merge. Do not land a dependency bump that +leaves `main` unbuildable, and do not combine unrelated cleanup with the migration. + +Rollback is the whole previous coherent set, not an egui version string: revert the stage range and +restore the 0.36.2 manifests/lockfile plus craft-ui `5c874d51...` and registry winit `0.30.13`; keep +the old lockfile, patch block, package IDs and source SHA in evidence; keep fork/winit/craft-libs +revisions reachable. No persistence migration: `UiState`, catalog journal/snapshot, XMP, presets and +library paths are unchanged; only egui memory/panel layout may reset. No release, tag, branch +deletion or cache cleanup until the migration is abandoned or complete and evidence is preserved. + +## 10. Blocking unknowns and acceptance criteria + +1. **Published pins (blocking).** The final approved storytold egui **P8** (including P2b, P7, + P7b/E21b and P7c) and the completed winit (W15P + W27) immutable revisions do not exist until the + fork/winit series is published and reviewed; no SHA is assumed here. Stages L2a–L2d are blocked + on them. `a4f9a17f`/`8b35388b` are comparison references only; no stock or intermediate stage is + a production dependency. +2. **E21b/P7b (blocking).** The complete shared contract — owner identity even when unavailable, + available-empty distinct and explicitly sent, committed disable/enable clear, latest-pass + authoritative `None`, current-epoch serial mismatch applying incoming edits once while outgoing + waits, stale-epoch invalidation, bounded ≤4000-byte payload with no full-document clone — plus the + `TextEdit` producer and W27 adapter is not in the inspected candidate. LightCraft's built-in + `TextEdit` consumers inherit it, and the family's custom producers (e.g. FilmCraft + `panels/graphics.rs`) need their own logical-model adapters before family acceptance. +3. **W15P + E4 + P2b (blocking for native PRIMARY).** The inspected E4 has an arboard fallback, not + the required winit-owned per-seat PRIMARY path. Require the complete published P8/W15P revision + with bounded asynchronous transfers (2 s total deadline, 16 MiB, four readers/two writers/queue + 8, owner-specific waker, stale-result cancellation), pointer- or keyboard-triggered fresh serials + and the §4.9 native matrix. +4. **craft-libs CL-1/CL-2F.** The capture slot exists only as a provisional CL-2 API until + published; LightCraft requires the frozen CL-2F API, which only exists after the + DesignCraft/GridCraft pilot adapters. The port sits on the reconciled + `3832c47ef68a0e6214f2c1e85f3526b6adcb686e` base; PR 199's head and the audit merge are stale + trees and `8614e4a`/`1764bca` are already contained in that base. +5. **Hidden viewport children.** #8748's overdue-UI behavior is not in the inspected fork; P7c is + required to carry the selected fix. The second window while the root is hidden/minimized still + needs native Wayland/Windows evidence. +6. **DX12 startup (#8736)** and **text tessellation (#8731)** are open upstream reports; measure on + our fixtures as separate workloads and require a semantics-preserving fix if thresholds are + breached. **#8512** is a separate font-startup workload, not a reason to enable system fonts. +7. **Strict kittest findings.** The number and identity of unnamed inputs/missing glyphs under 0.37 + is unknown until the first L2a run; they are real fixes, not a reason to disable the checks. +8. **Fonts.** Whether the bundled faces cover every shipped locale and script fixture without system + fonts is a measured gate; CJK tests skip without `CRAFT_FONTS_DIR`, which is not release + acceptance. Monochrome emoji add ~1 MB; measure native and WASM size. +9. **PRIMARY/clipboard on GNOME/Mutter** needs a real compositor; a control-channel paste is not a + substitute. +10. **macOS**: no real hardware evidence for menu, IME, Metal/GL, termination or AccessKit teardown; + an explicit rollout blocker, not a pass. +11. **Web workflow**: no control server and no `ui.screenshot` command; browser capture plus + observable `command` state is the acceptance path unless a separate download/writer API is + separately reviewed and approved. +12. **Visual deltas**: 0.37 style/scrollbar/menu changes may alter reviewed screenshots; no bulk + golden refresh. +13. **Lock/feature drift**: `accesskit`/`kittest` movement, `wasm-bindgen` CLI matching, Nix git + fetching and a second `egui`/`winit` source must pass the dependency check. +14. **Performance environment**: no display session, corpus or fonts are guaranteed on this host; + Linux/Windows/browser results need the managed resources in §7/§8. The i915 render node is + availability evidence only. + +Acceptance requires a fresh independent adversarial review of this plan, then of each implementation +at its exact revision, with resolved findings and hashes recorded. It also requires all repository +gates, selected features, native Windows/Linux and browser workflows, the measured before/after +report, accessibility and visual review, and explicit human publication approval. No unresolved +correctness finding is downgraded to "later". + +## 11. Research references (primary sources; proposals distinguished from merged behavior) + +- egui 0.37 changelog and release commit + [`841a328b`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/CHANGELOG.md); + the inspected suite branch is `a4f9a17f64a6bae61350fb85804c9df0d9865916`, not `main`. +- Lifecycle: [`epi_integration.rs`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/crates/eframe/src/native/epi_integration.rs), + [`app_runner.rs`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/crates/eframe/src/web/app_runner.rs), + [`context.rs`](https://github.com/emilk/egui/blob/841a328ba2dd8f6996beb7189ebb7fc00e668a2a/crates/egui/src/context.rs). +- Callback screenshots: PR #8489, `crates/egui/src/data/screenshot_callback.rs` (merged). +- Roles: PR #8555; `egui/src/lib.rs` role table (merged). +- IDs/scope: PRs #8534, #8586, #8590, #8542; `id.rs`, `id_salt.rs`, `ui.rs`, `ui_builder.rs` (merged). +- Panel salts: PR #8592; `containers/panel.rs` (merged). +- Root UI/run pass: PR #8535; `context.rs` (`root_ui` panic documented) (merged). +- Default fonts / emoji features: PR #8583; `egui/Cargo.toml`, `epaint/src/text/font_definitions.rs`. +- Strict accessibility/missing glyphs: PRs #8589, #8611, #8601; `egui_kittest` source. +- PRIMARY selection: PR #8428 (merged); Wayland clipboard #8657 (open draft) and winit #4729 (open), + paired with E4/W15P. +- Bidi/RTL: #8577 (open) and the fork's E5/E12/E13/E16/E17/E20/E21 series. +- TextEdit click-away selection: issue #8763, PR #8764 (open/unmerged at inspection). +- Text tessellation: issue #8731 (open); DX12 FXC pipeline: issue #8736 (open); system-font startup: + #8512 discussion. +- Hidden/overdue viewport children: issue #8748 (closed upstream; absent from the inspected fork). +- IME surrounding text gap: `ime-surrounding-gap.md` and the egui plan §E21b/P7b, winit W27. + +## 12. Evidence to preserve + +Retain: the baseline/candidate/control commit IDs, lock SHA-256 and package/source tables, +`cargo tree -d`/`-i` and `cargo tree -e features` output, `cargo xtask ci` reports and test +counts/skips, dependency-check negative fixtures, accessibility tree dumps, reviewed +baseline/candidate screenshots and geometry JSON, performance raw samples and summaries (with +environment and separate #8731/#8736/#8512 workloads), native/browser/Windows logs and screenshots, +the exact published egui/winit/craft-libs revisions and their tests, and this plan's reviewed hash. +Do not preserve build targets as evidence; they are rebuildable and are cleaned only after all checks +and deliverables are saved. + +## 13. Review disposition record + +### 13.1 R1 review (`lightcraft-v1.md`) + +| # | Finding | Disposition | Resolved in | +|---|---|---|---| +| 1 | `Panel::left(salt)` double-hashes; `pid` mismatch | **Accepted.** `Panel::new` stores `IdSalt::new(id_salt)` and `Panel::id` = `parent_ui.scope_id().with_salt(store)`; `IdSalt::new(IdSalt)` is a distinct salt (`id_salt.rs` nested-salt test). Fixed to pass the original source and derive `pid` with `with_salt(IdSalt::new(id))`; no public panel-state-id helper. Impact narrowed: the helper has no production caller at inspection, so the defect is latent today. | §3, §4.7 | +| 2 | eframe `clipboard` feature missing | **Accepted.** Add `clipboard` to the native app and assert it through resolved features; headless clipboard is not native acceptance. | §2.1, §4.9, §5.3 | +| 3 | `TickPhase` has no first-frame/`None`/forced-hidden branch; stale-index premise false | **Accepted, with two sub-claims rejected.** The stale-index claim and the `has_visible_pass` contradiction are correct. The specific example "`RawInput::default()` has time 0" is wrong: `InputState::begin_pass` uses `new.time.unwrap_or(prev + predicted_dt)`, so the input time is `predicted_dt`; the real zero-time first frame is `HeadlessView::raw_input(..., time = 0.0)`. The classifier is removed entirely rather than patched, so both cases are covered. | §4.1, §4.2, §6.1 | +| 4 | Hidden geometry-dependent controls use stale geometry; one paint request cannot carry a gesture | **Accepted.** Geometry resolves only after a fresh `layout_epoch`; each gesture step requests a hidden paint; exactly one reply, after delivery. | §4.5, §6.1 | +| 5 | `default_fonts` loses 0.36 emoji faces | **Accepted.** Enable `monochrome_emoji_fonts`; tests cover `🙂`/`👍` and the emoji keyword fixture; ~1 MB size is measured. | §2.1, §4.8, §7.2 | +| 6 | E4 does not provide the winit-owned PRIMARY path | **Accepted.** W15P is a prerequisite with the full native matrix; no limitation is recorded as "solved". | §1, §4.9, §10 | +| 7 | E21b/W27 outgoing IME surrounding text missing | **Accepted.** Added as a blocking prerequisite with the built-in-`TextEdit` inheritance tests and the family custom-producer requirement (FilmCraft graphics etc.). | §4.9, §10 | +| 8 | Web cannot invoke `ui.screenshot` | **Accepted.** Web `command()` only reaches `LightcraftApp::run`; browser capture plus observable commands is the workflow; no new app API unless separately reviewed. | §4.11, §8, §10 | +| 9 | A `Cargo.lock` check cannot assert features | **Accepted.** Identity from lock/metadata; features from `cargo metadata` + `cargo tree -e features`; feature-less fixture targets that mechanism. | §5.3 | +| 10 | `DockArea::direction` unspecified | **Accepted.** Explicit LTR policy at both call sites with unchanged persisted geometry/tab order. | §4.7, §6.1 | +| 11 | Screenshot design does not adopt the shared completion slot | **Accepted.** LightCraft requires the frozen CL-2F helper; request paths/deadlines/replies stay app-owned. | §4.6, §9 | +| 12 | Hidden-time accounting misses toasts/status and faces/denoise input | **Accepted.** One monotonic clock for toasts/status/timers; faces/denoise split into background drain vs UI-phase input. | §4.3, §4.4 | +| 13 | Duplicate-work claim overbroad; web inbox table contradiction | **Accepted with correction.** A second pass has empty events (`InputState::begin_pass`), so event handlers cannot duplicate; the real duplicates are time-gated ticks and the double `faces::pump`. Web inbox runs every `logic` call, dropped files only in the UI phase. | §4.2, §4.4, §4.11 | +| 14 | `Headless::step` still has the removed `Event::Screenshot` arm | **Accepted.** Both `HeadlessView::run` and `Headless::step` are updated; exactly one completion. | §4.6 | +| 15 | Count/factual issues (`221` id calls; web inbox table) | **Accepted.** 221 `egui::Id::new` occurrences (218 lines) plus three bare `Id::new`, and 8 `ui.id()` calls verified in this checkout; the table/text disagreement is removed. | §3, §4.4 | + +### 13.2 R2 review (`lightcraft-v2.md`) + +| # | Finding | Disposition | Resolved in | +|---|---|---|---| +| 1 | Hidden timers placed in `ui_pass` where hidden `run_logic` cannot reach them | **Accepted.** `import`/`lightroom_import`/`recheck`/slideshow/auto-import/sidecar/device/toast/autosave ticks were moved back to `logic`, with monotonic deadlines so a second pass is a no-op; only UI input/drop/perf work stays behind `current_pass_index() == 0`. | §4.2, §4.3, §4.4, §6.1 | +| 2 | E21b/W27 omission of owner/serial/epoch rules | **Accepted.** Restated the complete P7b/W27 contract: owner identity while unavailable, available-empty sent explicitly, committed disable/enable clear, latest-pass authoritative `None`, current-epoch mismatch applies incoming once and defers outgoing, stale epochs invalidate, bounded payload without a new full-document clone. | §4.9, §6.3, §10 | +| 3 | W15P required without bounded async transfer | **Accepted.** P2b is now part of the P8 prerequisite: 2 s total deadline, 16 MiB cap, four readers/two writers/queue 8, owner waker and stale cancellation, with slow/canceled-transfer and responsiveness tests. | §1, §4.9, §6.3, §10 | +| 4 | PRIMARY matrix is keyboard-only | **Accepted.** Fresh pointer-press or keyboard-focus serials are both valid; keyboard-only is explicitly rejected, and middle-click paste is tested. | §4.9, §10 | +| 5 | Hidden synthetic input can accumulate in `pending_raw_input` | **Accepted.** Hook may run in logic-only, so it injects at most one step and marks it in flight until a completed UI pass consumes it; no second injection from repeated hidden ticks and no press/release collapse. | §4.5, §6.1 | +| 6 | L1 cannot both run on 0.36.2 and enforce the 0.37 check | **Accepted.** The dependency check is baseline-aware; L1 runs in 0.36.2 expected-graph mode, and L2a flips it to the P8 graph atomically. | §5.3, §9 | +| 7 | Counts/detail inaccuracies | **Accepted, normalized.** This checkout has 218 `egui::Id::new` lines plus three bare `Id::new` calls (221 lines, 224 occurrences; the review's line/occurrence wording was slightly mixed). The font key is `Ubuntu-Light`; the `logic` doc comment now matches per-pass host calls; the weak-slot reason is corrected (the renderer owns the callback, so this is not a `Context` cycle). | §2.1, §3, §4.2, §4.6, §4.8 | + + +## Local implementation update — 2026-10-23 + +The user clarified that reviewed plans remain local and implementation proceeds before publication. The earlier requirement to publish/land this plan first is superseded; pushes and PR publication still require explicit approval. + +Canonical `storytold/lightcraft` `main` now resolves to `d5e639b3d1ad079c39a924c1b65d0a96ee2134ac`. The owned checkout was fast-forwarded to this revision. Earlier baseline SHAs and line anchors above are retained as historical review evidence; use this new revision and its exact lockfile for current-main integration and paired measurements. The original refs remain reachable. + +No migration API redesign required by this delta; preserve the merged packaging, test and chrono changes where present. + +The complete static delta review and exact old/new object identities are retained in the task evidence: `canonical-diffs-refresh-20261023.json` and `overnight-consumer-review-20261023.md`. This amendment claims no new build, native GUI or performance acceptance. + +## Local implementation — stage L2a/L2b source migration (2026-10-23) + +Status: **source changes only, not validated here.** No build, test, `cargo metadata`, fmt, +clippy, GUI, browser, Windows or performance run was made in this worktree. The parent runs the +managed jobs listed at the end. This section records exactly what changed and what is still +open; it is not acceptance evidence. + +### Dependency and feature stage (L2a) + +- Workspace `egui` is now `0.37` with `default-features = false` and + `features = ["default_fonts", "monochrome_emoji_fonts"]`; `eframe` and `egui_kittest` are `0.37` + (`egui_extras` is declared at `0.37` although LightCraft still does not use it). +- Native `eframe` adds the separate 0.37 `clipboard` feature; web keeps `default_fonts` + `glow`. +- The workspace feature choice is what gives the CLI/headless and kittest roots their faces: + `egui_kittest`'s own dev-dependencies do not propagate. `tests_lifecycle_037` asserts the + `Hack`, `Ubuntu-Light`, `egui-icons`, `NotoEmoji-Regular` and `emoji-icon-font` faces and that + U+1F642/U+1F44D are paintable. +- No final storytold SHA, `[patch]` entry or lockfile was invented. The parent supplies the local + path patch from `../PLANNING-CONTRACT.md` / `local-integration-config.toml` and generates the + lockfile. `crates/raw/src/vendor/` is untouched. + +### API migration + +- `egui::Id::new` → `egui::Id::unique` (same hash, so egui state does not reset) and `Ui::id()` → + `Ui::scope_id()` across the UI crate and tests. +- `WidgetType` → `egui::Role` with the documented variant mapping (`CollapsingHeader` → + `DisclosureTriangle`, `SelectableLabel` → `Button`, `ComboBox` stays `ComboBox`). +- `Panel` salts: `resizable_side` now passes the original salt to `Panel::left/right`, derives the + persisted key with `ui.scope_id().with(id)`, and checks the resize drag on that key (the old code + passed a prebuilt `Id` and would be salted twice). 0.36 exact-`Id` `PanelState` entries for + `top_bar`, `bottom_bar`, `tool_strip` and `library-problem-banner` are removed once at startup; + this resets only egui panel memory, never `UiState`, docking JSON, catalog or XMP data. +- `ScrollArea::State.offset` is private: menu arrows store a one-frame `vertical_scroll_offset` + target, and the right panel reads `clamped_offset()`. +- `Event::MouseWheel` initializers carry `source`; `ui.scroll` accepts optional + `"source"`, `"unit"` and `"phase"` with the validated values and defaults from §4.9. +- `ComboBox` has the documented lifetime; atoms take `IdSalt` (`Atom::custom`, + `WidgetAtomResponse::rect`). +- `ViewportCommand::Screenshot` now uses the one-shot callback and `Event::Screenshot`/`UserData` + are gone. Both headless entry points answer the callback with their painted frame exactly once. +- The fork's `Context::set_language` is fed from `i18n::language()` (the AccessKit root language + and bidi runs follow the UI locale; command ids and user data stay logical). + +### Lifecycle and capture stage (L2b) + +- `LightcraftApp` now has a monotonic `AppClock` (`web_time::Instant`, never `i.time` or + `Date.now` for timing; `now_ms` remains wall-clock only for `library-restored-<ms>` names). + Headless hosts feed it their simulated time; the first `Headless::step` runs at 0.0. +- `logic` keeps queues, worker polls and time-gated work. Import committing is gated on + `current_pass_index() == 0` (once per host frame, and once per hidden logic tick), not on the + clock; all other hidden-relevant timers (Lightroom import, slideshow, auto-import, sidecar retry, screen profile, denoise/faces/focus/model, + autosave/prefs, toasts, captures) use the app clock. +- `ui` is split into `ui_pass` (first pass only: fresh input, dropped files, external-editor focus, + shortcuts, perf) and `draw_window` (presentation), then `finish_ui_pass` (completed, nondiscarded + pass; clears the synthetic in-flight gate). A hidden `run_logic` never reaches it. +- Dropped files are taken once in `raw_input_hook` into an app queue and consumed only in the UI + phase; web consumes the same queue in `WebApp::ui` (it needs `bytes_async`). Native and web tests + cover that a hidden logic tick leaves the queue intact. +- `raw_input_hook` injects at most one synthetic batch, refuses to inject before fonts are ready, + marks the batch in flight until a completed pass consumes it, and keeps a hidden window painting + with `RequestPaintWhileHidden` while a batch, settlement or queued capture is pending. +- Screenshot capture adopts `craft_ui::capture::CaptureSlot` (CL-2 local tree): four outstanding + requests, 128 MiB per image, 256 MiB aggregate including completed-not-drained images, admission + before issue, fresh native viewport geometry, a three-completed-frame/120 ms settle, a forced + capture at 3 s even while renders are in flight, a 2 s compositor fallback and an 8.12 s + admission deadline (settle + forced capture + fallback + headless settle). The strong slot stays in the app request + record; the callback only holds a weak slot and never writes files or touches app state. A + completion from an older geometry epoch or library generation is retried, never written; an + image larger than its reservation is rejected; a cancel/timeout/late callback releases its bytes + with a checked subtraction and replies once. +- Web `Bench::step`, `WebApp` notices/save and the native `PrefsWriter` use the monotonic clock. + The native menu and window-watch no longer record a hidden pass's stale content rect. + +### IME inventory and next step + +LightCraft has no custom `egui::IMEOutput` producer: `TextField` wraps the built-in `TextEdit` and +every other editor uses `TextEdit`, so it will inherit the P7b/E21b logical-model/preedit/UTF-8 +producer once the reviewed egui revision is pinned. No `None` placeholder was added. The next step +is to re-run the P7b outgoing-surrounding-text cases (deletion-only and delete+commit, preedit +excluded, reversed selection, supplementary/RTL text, over-limit selection, available-empty vs +unavailable, window/owner switch, password clear, stale serial) against that pinned revision. The +incoming byte-deletion path is the built-in `TextEdit` path and is not reimplemented here; +`tests_lifecycle_037` asserts that `TextField` applies `ImeEvent::DeleteSurroundingBytes` +exactly (the pinned fork's winit byte-range event). + +### Tests added (source only) + +`crates/ui-egui/src/tests_lifecycle_037.rs`: + +- bundled monochrome emoji + explicit font-feature gate; +- parent-salted panel state (and no legacy exact-`Id` state); +- capture admission count/per-image/aggregate bounds before issue; +- stale-geometry completion rejected before any file write, reservation retained for retry; +- one synthetic batch until a completed pass, and dropped files waiting for the UI phase; +- first headless frame at simulated time 0 and the app clock following the host. + +### Unresolved prerequisites and validation + +- Final published storytold egui P8 (E1–E21 + P2b + P7 + P7b/E21b + P7c) and winit W15P/W27 + revisions, and the reviewed craft-libs CL-1/CL-2F revisions, do not exist as pins here. +- This source stage calls `craft_ui::capture::CaptureSlot` (the provisional CL-2 module in the + local craft-libs tree). The parent must provide a craft-ui revision that actually contains that + module; if CL-2F renames or changes it, the thin app adapter in `crates/ui-egui/src/lib.rs` must + be updated rather than copied into a second helper. +- Native PRIMARY (W15P/E4), E21b/W27 outgoing IME, #8748 deferred viewport children and #8763 are + inherited from those pins; none is claimed. +- The explicit LTR `DockArea::direction(DockDirection::LeftToRight)` policy is not added here: + the reviewed craft-ui revision in the local tree has no `direction` builder yet. Add it in the + same dependency stage that freezes CL-1/CL-2F; persisted splits, axes, ratios, floating + rectangles and logical tab order must stay unchanged. +- `accesskit` 0.24 → 0.25 and `kittest` 0.4 → 0.5 churn is not pinned here; check that the + Linux `zbus = "=5.19.0"` pin still resolves to one zbus source, and that `wasm-bindgen` in the + generated lock matches the CLI. +- `RequestPaintWhileHidden` has no web support in the shared fork: the browser path is unqualified + and remains a pending fork fix. Headless rendering is not native focus/IME/picker evidence. +- Strict kittest naming/missing-glyph checks may surface unnamed inputs or glyph gaps; those are + real fixes, not reasons to disable the checks. +- Visual/style deltas from roomier 0.37 defaults, Windows software rendering, macOS and native + compositor/PRIMARY evidence are still separate gates. +- Control gestures (`ui.pointer`, `ui.clickWidget`, `ui.dragWidget`, and the other input methods) + now resolve only after a completed fresh layout and reply only after the final nondiscarded pass + consumed their last event; the 5 s deadline is the fail-closed fallback. Limits are recorded in + §4.5: cancellation covers the admission-time view/document/dialog/panel snapshot, not a + per-widget semantic identity across an arbitrary catalog refresh in the same frame, and a + timeout clears queued synthetic input rather than removing one gesture's events individually. + +### Baseline backports and performance operations + +- Backports this consumer depends on but does not own: egui P7c (#8763 click-away selection, + #8748 overdue viewport children, the semantics-preserving text-tessellation fix) and E21b/P7b; + winit W27 outgoing IME lifecycle and W15P bounded PRIMARY; craft-libs PR 199's API-port hunks + (`Role`/`scope_id`/`IdSalt`) and the CL-2F capture helper on current main, never the stale PR + tree. +- Performance operations to measure after the pins exist, each as its own workload: menu/panel + text tessellation (#8731), DX12/FXC first-pipeline startup (#8736), system-font startup only if + the font policy is revisited (#8512), capture settle/issue overhead and hidden idle repaint/CPU. + Record raw samples and the environment; do not treat compile time as UI performance or refresh + visual goldens in bulk. + +### Parent-managed validation commands + +Use one new resource (for example `egui037-lightcraft-candidate-20261023`) and a fresh job id per +command. `--locked` only after the parent generates the lockfile. + +```sh +python3 /home/codex/work/maintenance/task.py run \ + --job-id egui037-lightcraft-20261023-check-01 --kind build \ + --task egui037-lightcraft-candidate-20261023 \ + --source "$PWD" --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/lightcraft-candidate \ + -- cargo check --workspace --all-targets +python3 /home/codex/work/maintenance/task.py run \ + --job-id egui037-lightcraft-20261023-lifecycle-01 --kind build \ + --task egui037-lightcraft-candidate-20261023 \ + --source "$PWD" --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/lightcraft-candidate \ + -- cargo test -p lightcraft-ui-egui --lib tests_lifecycle_037 +python3 /home/codex/work/maintenance/task.py run \ + --job-id egui037-lightcraft-20261023-ci-01 --kind build \ + --task egui037-lightcraft-candidate-20261023 \ + --source "$PWD" --evidence /home/codex/work/ssd2/task-evidence/egui037-migration-20261022/lightcraft-candidate \ + -- cargo xtask ci +``` + +Then inspect every `status`, record `cargo tree -e features` for the native, CLI/headless, kittest +and wasm roots, run the accessibility/docking integration tests and the `cargo xtask web` browser +workflow, and only afterwards consider the measured before/after workloads (menu text tessellation, +DX12/FXC startup, capture settle cost, hidden idle repaint). Do not refresh visual goldens in bulk. + +## Post-port review repairs (2026-10-23) + +Source-only repair of `egui037-lightcraft-postport-review-20261023-root-v1.md`. No build, test, +fmt, clippy, `cargo metadata`, GUI, browser, Windows or performance run was made here; the parent +submits the managed jobs. + +- **P1.1**: the four bare `Context::run_ui` statements in `tests_lifecycle_037.rs` bind their + `FullOutput` (`let _ = …`) so `-D warnings` no longer sees `unused_must_use`. +- **P2.1**: a settled capture is issued at a forced instant (`SHOT_FORCE_BUSY_MS`, three seconds + from admission) even when `renderer.in_flight()` or the merge is busy; the hard deadline (five + seconds) stays the only timeout path. `shot_ready` is a pure helper with a busy-renderer test. +- **P2.2**: capture identity is the library generation only. `catalog.revision` (bumped by every + applied edit/import/keyword op) no longer invalidates an in-flight image; the test applies one + catalog op between issue and completion and still writes the image. +- **P2.3**: a surface that grows after admission is checked as an *image* against the 128 MiB + per-image cap and only its growth against the 256 MiB aggregate. The old code compared the delta + to the per-image cap and named the delta as the image. +- **P2.4**: a completion larger than its reservation but within the per-image cap is treated as a + stale reservation (Wayland has no `inner_rect`), re-reserved and written, not rejected. +- **P2.5**: a slideshow auto-pauses while `ViewportInfo::visible() == Some(false)`, requests no + playback repaint, and resumes on unhide with the slide's remaining time preserved. This replaces + the 0.36 behavior where `i.time` froze while hidden. +- **P2.6**: the “0.37 has no `visible()`” rationale was wrong. `lib.rs` and + `apps/lightcraft/src/main.rs` now use `ViewportInfo::visible()`; §4.1/§4.2 above are corrected. +- **P3.1**: `import::tick` is gated by `current_pass_index() == 0` (once per host frame, and once + per hidden logic tick), not by a wall-clock throttle. The wall-clock comment was false. +- **P3.2**: the app retains the host's last `RawInput::max_texture_side` (default 16 384) and reports + “no usable surface” and “over the host's per-side texture limit” as distinct admission errors. +- **P3.3**: screenshot encoding no longer makes the extra flat RGBA `Vec` copy; `Rgba8::from_pixels` + fills the image's own buffer once. `MAX_SHOT_WORKING_SET_BYTES` documents the bound: reserved + images (≤ 256 MiB) + one `Rgba8` copy + encoded PNG (each ≤ 128 MiB) + 64 KiB zlib/framing slack. + Encoding stays on the UI thread, one image at a time. The MCP layer's decode/base64 transient is + outside the app process path and remains bounded by its own 1600 px default. +- **P3.4**: `apps/lightcraft-web/src/bench.rs` now measures `first_frame_ms` and `thumbs_done_ms` + from `WebApp` construction (`monotonic_ms()` origin), not navigation start. Old + `lightcraft-bench` samples are therefore not comparable; record the origin with every sample. + `web.rs`'s “first UI frame at perf_now()” log is a different origin in the same file and is + diagnostic only. +- **P3.5**: `Headless::step` no longer carries a second `ViewportCommand::Screenshot` completion + arm; `HeadlessView::run` is the only headless completion point. +- **P4**: the AccessKit language is cached instead of allocating through `Context::language()` on + every logic pass; the wasm drop branch names `WebApp` as the queue consumer; the legacy panel + eviction comment now says the old keys are unreachable anyway and only keeps egui memory tidy, + with a test that the four legacy keys are removed and the parent-salted keys survive. + +Still open from the review: P3.3's MCP decode/base64 transient (documented, not reserved), the +web `RequestPaintWhileHidden` gap, #8748/#8763/E21b/W15P/W27, strict kittest findings, and all +runtime/visual/performance acceptance. The tests above are deterministic source oracles, not +runtime evidence. + +## Review-test repairs — 2026-10-24 (source only) + +The managed review-test job `egui037-lightcraft-candidate-20261024-review-tests-13` reported +1155 library passes, 106 failures, 4 ignored, plus 7 of 8 integration tests and the shutdown test +passing. Grouping the failures gave two root causes, repaired here without relaxing a check: + +- **Gesture delivery re-checked its own effect.** `reply_delivered_gestures` compared the + admission-time view/document/dialog/panel snapshot again after the batch had been consumed. Every + click or key whose purpose is to change that state (opening a dialog, leaving the grid, closing a + dialog, selecting another photo) was answered with “changed before delivery” although the input + had done its job. Delivery now requires only that a completed, nondiscarded pass consumed the + batch. Freshness stays fail-closed twice: at resolution (a later completed layout must match the + admission snapshot) and in `drop_gestures_stale_before_injection` immediately before a waiting + gesture's first batch is injected, so a hidden logic tick cannot retarget it; later batches of + the same gesture may see its own partial effect, and a concurrently queued gesture is checked + when its events reach the head. A changed snapshot before the fresh layout still cancels, and a + stale pre-injection batch is cleared and answered with an error. +- **Unlabelled dropdowns.** egui 0.37's `ComboBox::from_id_salt` publishes the selected text as the + node's value but no accessible name, and kittest 0.37's strict accessibility check rejects it. + `widgets::name_combo` now gives every dropdown a semantic label (copyright status, keyword set, + proof profile, denoise limit, smart-album match/field/operator/value, export/contact-sheet/import/ + settings/credits/print dropdowns), so no strict check was disabled. + +One lifecycle test assumed the app opened in the photo grid while `UiState` defaults to Detail, so +its “view changed” setup was a no-op; it now changes to PhotoGrid explicitly. New regression tests +cover a delivered gesture that opens a dialog (stays `ok`) and a view change between resolution and +injection (answers once with `canceled` and injects nothing). + +No build, test, fmt, clippy, GUI, browser, Windows or performance run was made for this amendment; +the parent runs the managed jobs. The 106 failures and the ComboBox finding are the only failures +inspected in that output; any further finding is reported separately rather than folded in here. diff --git a/docs/focus-points.md b/docs/focus-points.md index 61c562b039..2171a7c151 100644 --- a/docs/focus-points.md +++ b/docs/focus-points.md @@ -6,7 +6,7 @@ zooms to it, so checking whether the subject is sharp takes one key while cullin ## Using it -- **View ▸ Show Focus Point** (⌥F; `view.focusPoint {on?}`) draws the camera's AF frame as green corner brackets in +- **View ▸ Focus Point** (⌥F; `view.focusPoint {on?}`) draws the camera's AF frame as green corner brackets in Detail, Compare and Survey. It follows Rotate, flips and the crop; a point cropped away is not drawn. Off by default; the choice is saved with the app's settings. - **View ▸ Zoom to Focus Point** (`view.zoomToFocus {on?}`, on by default): Toggle Zoom (Z or Space) zooms in diff --git a/docs/fuji-lens-corrections.md b/docs/fuji-lens-corrections.md index 365c98e983..2546ef2cfd 100644 --- a/docs/fuji-lens-corrections.md +++ b/docs/fuji-lens-corrections.md @@ -161,5 +161,5 @@ before demosaicing would be needed. vignette gain on the X-T4's real arrays, and the X-T4 geometry against its measured free fit. - `crates/raw/src/vendor/raf.rs`: a synthetic RAF through header and full decode, only for validated models, and a DNG round trip. -- `crates/raw/tests/corpus.rs` `fuji_embedded_lens_tables_follow_the_validated_models`: the corpus' `raf-fuji-*` files, +- `crates/raw/tests/it/corpus.rs` `fuji_embedded_lens_tables_follow_the_validated_models`: the corpus' `raf-fuji-*` files, or any folder of RAFs in `LIGHTCRAFT_FUJI` (the pixls set: 129 decoded, 88 warps, 98 vignette gains). diff --git a/docs/gaps.md b/docs/gaps.md index be411a2050..42d9d437b6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -23,11 +23,11 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 6 B | **Compressed ORF** (every Olympus / OM body since ~2008) | measured: 66 of 78 Olympus / OM models preview-only; `orf.rs` refuses; OM bucket 3% of photographers, 3% of them fully work | +2.6 points; best gain per hour of any raw gap (~0.2) | 8–15 | [raw-parity](raw-parity.md#compressed-orf-a-clean-room-starting-point) (the two Olympus patents that describe the method) | | 7 | **Nikon High Efficiency NEF** (HE / HE★ on Z 8, Z 9, Z 6III, Z f, Z50II, Z5II when set to HE) | named and preview only (#193); needs a pure-Rust JPEG XS decoder | +1.1 points (only shots taken in HE; lossless works on the same bodies); low gain per hour (~0.04), so not a beta blocker | 20–40 | [raw-parity](raw-parity.md) | | 8 B | **No lens profile database** (LR-EDIT-OPTICS-PROFILE): only DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`) | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | -| 9 B | **Tests don't run in CI on macOS, Windows or Linux x64**: only FreeBSD runs `cargo test`; the others build packages | `.github/workflows/` (freebsd, packaging-lint, release, windows-arm64); the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU | regressions reach users on the main platforms; `cargo xtask ci` runs only locally | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | +| 9 B | **Tests don't run in CI on macOS or Windows**: Linux x64 runs `cargo xtask ci` on every PR and push to main (`.github/workflows/ci.yml`) and FreeBSD runs `cargo test`; the others build packages | `.github/workflows/` (ci, freebsd, packaging-lint, release, windows-arm64); the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU; macOS / Windows jobs: #1148 | regressions in `cfg(target_os)` code reach macOS and Windows users | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | | 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 551 of 1,446 Adobe models verified (38%), ~85% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 regression (#702); F828 SRF now discovered and imported as preview-only, sensor decoding still missing, DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) | | 11 | **Enhance: Raw Details, Super Resolution; AI denoise without shippable weights or X-Trans** | ENH rows 0%; denoise Bayer only, RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; nobody gets it out of the box | 30–60 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | | 12 | **Content-aware / generative remove, detect distractions, reflections removal** | REM rows 75%; patch synthesis missing | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) | -| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | +| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672) | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | | 14 | **HDR display** (EDR / Windows HDR); the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read). HLG AVIF export done; the display's SDR/HDR decision is tested, blocked on eframe's 8-bit surface | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) | | 15 | **Print module**: identity plate / watermark / photo info overlays, Cut Guides for the packages, Custom Package Auto Layout, printer-driver Page Setup and direct printing, JPEG file output (the Print dialog writes a colour-managed PDF) | LRC-PRINT rows | Classic users who print | 15–25 | [target-app-parity](target-app-parity.md#features) | | 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP / BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) | @@ -35,7 +35,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 18 | **Video**: playback, trim, global edits, export | VID rows 0% | users who mix stills and clips | 25–45 | [target-app-parity](target-app-parity.md#features) | | 19 | **Plug-in ecosystem**: no Lightroom SDK equivalent (export / publish plug-ins, metadata plug-ins) | ⬜ | pro workflows built on plug-ins (LR/Enfuse, Jeffrey's exporters, Negative Lab Pro) | 40–80 + owner decision | [target-app-parity](target-app-parity.md#by-dimension) | | 20 | **Long-tail raw formats**: compressed SRW, ARQ pixel shift, IIQ, Hasselblad compression, X3F, CRW, ERF, KDC, DCR, MEF, GPR, old FinePix (MRW decodes since 2026-10-18) | raw-parity.md | small user share each | 40–80 | [raw-parity](raw-parity.md) | -| 21 | **Localization**: 10 of 16 shipped languages partial (de, es, fr, ja, uk now 97–99% of catalog messages and id every message but What's New, awaiting native review; pt-BR, ru, zh-hans, zh-hant 74–92%), lower-layer errors English; Hindi, Arabic, Korean, Vietnamese absent; no RTL or complex shaping | measured from catalogs | non-English users see mixed English | 40–70 (shipped to full); 135–239 (four new) | [localization-parity](localization-parity.md) | +| 21 | **Localization**: 10 of 16 shipped languages partial (de, es, fr, ja, uk now 97–99% of catalog messages and id every message but What's New, awaiting native review; pt-BR, ru, zh-hans, zh-hant 74–92%), lower-layer errors English; Hindi, Arabic, Korean, Vietnamese absent; no RTL or complex shaping; exports add Thai glyphs only (#2052), with horizontal mark positioning still incomplete and Arabic fallback deferred until joining and bidi exist | measured from catalogs | non-English users see mixed English | 40–70 (shipped to full); 135–239 (four new) | [localization-parity](localization-parity.md) | | 23 | **Accessibility**: AccessKit tree audited by a test; canvas handles, spots and mask pins by keyboard; left: brush and red-eye by keyboard, a session with a real screen reader | LR-BEHAV-ACCESS 🟡 | blind and low-vision users | 2–4 | [ui-parity](ui-parity.md) | | 22 | **Pen pressure on macOS / Linux tablets** (brush size and flow follow pressure where winit reports a pen force), OS monitor profiles on Windows (Linux reads colord's, macOS the screen's), follow-window colour on Linux / Windows | hardware-parity.md | brush users with tablets; multi-monitor setups | 11–22 | [hardware-parity](hardware-parity.md) | | 24 | **Brush live preview and masking feel** (#517, #518); Feather / Edge mask refinement (15.5) | issues | masking feels slower than Lightroom | 8–12 | [ui-parity](ui-parity.md) | @@ -43,7 +43,8 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 26 | **Performance at scale**: 85k-photo library opens in 1.7–4.7 s; 100k grid test pending; colour NR at half resolution; at 100k photos stack and album lookups are indexed (an "In a Stack" or "Album" smart album counts in ~14 ms, was 0.6–2.7 s) | ROADMAP log, gpu-pipeline.md | large-catalog users | 15–30 | [target-app-parity](target-app-parity.md#by-dimension) | | 27 | **Windows / Linux runtime coverage**: the Windows x64 installer is verified on Windows 11 (0.9.1: install and upgrade end on the completion page, a custom folder is kept, Launch works, removal is clean), but uninstalling from Settings → Apps ends with no confirmation (#892, #931); GPU path proven on Apple and on one AMD GPU on Linux (Radeon 8060S, Vulkan); NVIDIA, Intel and DX12 unverified; the Linux riscv64 tarball (new in 0.6.0, #844) is cross-compiled and never run beyond a QEMU smoke test | ROADMAP, issues, `release.yml` | non-Mac users find bugs first | 13–27 | [hardware-parity](hardware-parity.md) | | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | -| 28 | **Small Classic shortcuts and keys**: ⌘L (Enable Filters), Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | +| 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | +| 30 | **Multi-select metadata editing in the UI**: `photo.setMeta` already iterates all selected photos, so the engine applies changes to every target. The Info panel's Show Metadata For choice (Target Photo / Selected Photos) shows the values the selected photos share and marks each field where they differ as Mixed; the All Metadata dialog still shows one photo's values with no "mixed" indication | standard in Lightroom Classic's multi-select Info panel | anyone editing metadata on a batch (copyright, keywords, custom fields) | 1–3 | [ui-parity](ui-parity.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -51,7 +52,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Gaps by kind - **Feature:** 5, 8, 11, 12, 13, 15, 16, 18, 19, 29 -- **UI / UX:** 4, 23, 24, 28 +- **UI / UX:** 4, 23, 24, 28, 30 - **File format:** 2, 6, 7, 10, 13, 20, 25 (raw ones in [raw-parity.md](raw-parity.md)) - **Hardware:** 14, 17, 22, 27 - **Localization:** 21 @@ -60,6 +61,10 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) +- 2026-10-22: saving XMP preserves foreign namespaces even when they use `lc:` or `xmp:` prefixes; importing them no longer interprets their properties as native settings or ratings. Parser, merge and save-command regressions cover the correction; no ranked gap or readiness estimate changes. + +- 2026-10-22: PSD/PSB imports and metadata readers now expose embedded EXIF resource 1058 and XMP resource 1060 for capture dates, GPS and All Metadata (#2519); imported PSD edit copies retain their capture date, and the `removeLocation` Original-export guard sees embedded PSD/PSB GPS. No ranked gap or headline feature count closes. + - 2026-10-20: the import review album picker follows the sidebar folder hierarchy and searches album paths (#2362, LR-IMP-ADD-DIALOG), retaining None/New album and existing destination IDs. This closes a usability subgap; no ranked gap or headline feature count closes. - 2026-10-12: original-pixel detail at 100% (gap 4, LR-VIEW-ZOOM, #323): soft proofing gets zoom windows like @@ -79,13 +84,26 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Gap 28: ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V on Windows and Linux) copy and paste metadata; no key leaves the entry; hours unchanged | +| 2026-10-24 | minor | Gap 30 shrinks: the Info panel's Show Metadata For (Target Photo / Selected Photos, `view.infoSelectedPhotos`) shows the selected photos' shared values and marks fields that differ as Mixed; the All Metadata dialog remains; 1–3 h (was 4–8) | +| 2026-10-23 | minor | Gap 13: before a Lightroom catalog import the app asks whether it merges into the open library or goes into a new one (opt-out in Settings, #2672); hours unchanged | +| 2026-10-22 | patch | Gap 28: View shows the current grid-cycle key beside Photo Grid and Square Grid (#2500); no new binding and no change to the remaining shortcut gap or hours | +| 2026-10-22 | minor | Gap 15: the Print page setup and PDF gain the Japanese photo and postcard paper sizes (L判 89×127, 2L判 127×178, KG判 102×152, はがき 100×148, 往復はがき 148×200, 六切 203×254, 四切 254×305, 名刺 55×91 mm), by their customary names; gap not closed | +| 2026-10-22 | minor | #2052: Thai glyphs added to shared export text; gap 21 retains Thai mark positioning, Arabic joining and bidi limits. No ranked gap closes; estimates unchanged | +| 2026-10-24 | minor | LR-LIB-SMARTALBUM: relative-date views and source totals expire on the session-clock minute, including nested smart albums; ranked gaps and readiness counts unchanged | +| 2026-10-22 | patch | XMP namespace-prefix collisions no longer overwrite foreign metadata; ranked gaps and estimates unchanged | +| 2026-10-22 | patch | Issue #2519: PSD/PSB EXIF resource 1058 and XMP resource 1060 now use the common metadata extractor, and `.psb` files are accepted by import; no ranked gap or readiness count changes | +| 2026-10-22 | minor | Gap 30 added: multi-select metadata editing — Info panel and All Metadata dialog show one photo's values with no mixed-value indication | | 2026-10-21 | minor | Gap 28 shrinks: F8 shows / hides the right panel (`view.rightPanel`); rating `[` `]`, flag cycling and F1 help were already bound, so the entry lists only filter-bar keys, Tab / ⇧Tab and F5; 2–4 h (was 4–8) | | 2026-10-20 | minor | #2362: import destination albums use the shared hierarchy/search picker instead of a flat name list; existing import workflows retained; ranked gaps/readiness counts unchanged | +| 2026-10-19 | minor | Gap 9 shrinks: `.github/workflows/ci.yml` runs `cargo xtask ci` on Linux x64 for every PR and push to main; macOS and Windows remain | | 2026-10-19 | minor | Gap 21: Indonesian (`id`) shipped with every catalog message but What's New; four new languages left (Hindi, Arabic, Korean, Vietnamese), 135–239 h | | 2026-10-19 | minor | Gap 27: the released 0.9.1 x64 MSI is tested on Windows 11 Pro 24H2 (a fresh install and an upgrade from 0.8.0 end on the completion page, so #790 is fixed; the upgrade keeps a custom folder; Launch starts the app; removal leaves nothing behind); uninstalling from Settings → Apps still ends with no confirmation (#892, #931); hours unchanged | | 2026-10-18 | patch | Gap 1: six X-Trans CMOS 4 Fujifilm bodies (X-T30 …) take the X-T3's spectral matrices instead of the neutral matrix | | 2026-10-15 | minor | Gap 15 shrinks: the Page panel's Page Options (Page Numbers, Page Info, Crop Marks) print on Single Image and Contact Sheet pages; identity plate, watermark, photo info, Cut Guides, direct printing and JPEG output remain | +| 2026-10-14 | minor | Gap 4 follow-up: the diagnostic overlays (Visualize Spots, Point Color range, HDR range) render zoom windows too; soft proofing runs on the GPU | | 2026-10-12 | minor | Gap 10: SR2/SRF folder discovery fixed; F828 imports as preview-only. Sensor decoding remains a gap; readiness scores unchanged | +| 2026-10-23 | minor | Gap 28: ⌘L / Ctrl+L (Library ▸ Enable Filters) puts the filter aside and brings it back as it was; the entry drops ⌘L; hours unchanged | | 2026-10-15 | minor | Gap 28: `\` shows / hides the Filter Bar in the grids; the entry drops `[` `]` (#509), flag cycling (#1490) and F1 (Help), already on main; ⌘L is the filter-bar key left; hours unchanged | | 2026-10-14 | minor | Gap 26: at 100k photos stack and album lookups are indexed, so an "In a Stack" or "Album" smart album counts in ~14 ms (was 0.6–2.7 s); open time unchanged | | 2026-10-14 | minor | Gap 10: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277) | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index b580c243a9..f88f81c390 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -4,6 +4,10 @@ The CPU pipeline (`crates/pipeline`) is the reference ("oracle"). `lightcraft-gp evaluates the same stages with wgpu compute shaders (WGSL) on Metal / Vulkan / DX12. Everything is pure Rust (wgpu, naga); the drivers are the system's. No GL backend is compiled in. +CPU fast guided-filter allocation measurements and reproduction commands are documented in +[guided-filter-memory.md](guided-filter-memory.md). That optimization retains the full-size base +and does not change the GPU's coefficient buffers. + Warped geometry uses a CPU-computed coverage bit mask for the source boundary. The CPU reference evaluates that boundary in double precision; GPU float rounding otherwise can turn a blank edge pixel into a photo pixel. The mask @@ -101,7 +105,8 @@ or worked around with `LIGHTCRAFT_GPU_BACKEND`. **The window's renderer and its fallback (Windows).** Before the window opens, each renderer is probed in order: DX12, Vulkan, GL, then eframe's OpenGL renderer (glow). A probe creates a device and builds egui's pipeline inside wgpu error scopes, so a driver that cannot compile egui's shaders ("The parameter is -incorrect. (0x80070057)" in `egui_pipeline`) is logged and skipped instead of killing the app. The renderer +incorrect. (0x80070057)" in `egui_pipeline`) is logged and skipped instead of killing the app; no pop-up +unless that renderer was forced (#1624). The renderer that worked is remembered in the settings folder (`window-renderer`); a start that dies before the window is up leaves `window-init.marker`, and the next start (relaunched automatically, at most 4 times) tries that renderer last. `LIGHTCRAFT_GPU_BACKEND=dx12 | vulkan | gl | glow` (or `WGPU_BACKEND`) forces one; DX12 stays @@ -161,6 +166,8 @@ walks the drive. (log luminance, dark channel, guided-filter steps, white balance, luminance / colour NR, airlight sampling), `mask` (linear / radial / luminance / colour range / brush shapes, combine, finalize), `finish` (the whole per-pixel stage) — each mirrors a named CPU function. +- Soft proofing against an output space (`RenderRequest::proof`, with its destination and display gamut + warnings) runs in `finish`; a proof against an output-device profile (its 3D table) renders on the CPU. - Per-stage hybrid: defringe and spot removal (rare, CPU-only for now) download the resampled image, run on the CPU and upload; heuristic mask shapes (Sky, Subject, Background, …) and brushes of more than 4096 dabs are evaluated on the CPU and uploaded; sources over the buffer limit are resampled @@ -229,7 +236,7 @@ passes on as `RenderResult::gpu_fallback`; an export carries it as `Exported::gp each file of an `app.export` batch result has `gpuFallback` when its render fell back (issue #675). **Reproducing a smaller GPU:** `LIGHTCRAFT_GPU_LIMITS=webgpu` (or `downlevel`) creates the device with 128 MiB storage bindings / 256 MiB buffers, `LIGHTCRAFT_GPU_LIMITS=<n>` with n MiB / 2n MiB. -Tests inject failures with `lightcraft_gpu::inject_fault` (`crates/gpu/tests/fallback.rs`, +Tests inject failures with `lightcraft_gpu::inject_fault` (`crates/gpu/tests/it/fallback.rs`, `export_falls_back_to_the_cpu_when_gpu_work_is_lost`). The fault is thread-local, and so are its consequences: a simulated fatal failure stops GPU use on the injecting thread only (`available()` false, `unavailable_reason()` set there), until `reset_failures()`, which undoes nothing else — a @@ -237,7 +244,7 @@ real failure still stops the whole process. Such a test asserts on its own rende `last_fallback()`, so it can run beside other tests rendering on the GPU (issue #675). ## Correctness: CPU oracle and equivalence tests -`crates/gpu/tests/equivalence.rs` renders the same settings on both and compares 8-bit sRGB: +`crates/gpu/tests/it/equivalence.rs` renders the same settings on both and compares 8-bit sRGB: bounds **mean |Δ| < 0.5 LSB and max |Δ| ≤ 3 LSB** per channel. Measured (Apple M4 Pro, Metal): **max 1 LSB, mean ≤ 0.0003 LSB** for every case — 26 settings cases (all tone/colour/effects tools, 3 vignette styles, grain, curves, grading, B&W, WB, NR, crop/straighten/flip, lens + perspective, @@ -254,12 +261,19 @@ cut back after the readback. The tests skip (pass with a note) when no adapter e non-Apple GPU verified: all 16 tests pass, 135 compared cases. 124 differ by max 1 LSB, 10 are bit-identical, and one (the point colour range overlay) has max 2 LSB on 0.0002% of pixels. Worst mean 0.0003 LSB. That is the same picture as on Metal, inside the bounds -(`cargo test -p lightcraft-gpu --release --test equivalence -- --nocapture`). +(`cargo test -p lightcraft-gpu --release --test it equivalence:: -- --nocapture`). Remaining differences come from f32 vs f64 coordinate math, fast-math transcendental functions on Metal and summation order in the box filters — all far below one 8-bit step. ## Measurements +**In the app:** Help ▸ Debug ▸ Frame Rate (`view.frameRate`, `{show?}`; `LIGHTCRAFT_FPS=1` +starts with it on, never saved) draws frames per second, each frame's UI CPU time against its +time spent waiting (for vsync, or for the GPU), the latest whole-frame and zoom-window render +times, the render queue, renders thrown away as superseded, the GPU adapter and its memory, and a +graph of the last frames with a tick where a render arrived. Once a second it logs the same +numbers (`fps-hud:`), so a scripted drag (`ui.dragWidget`) can be measured from the log. + `render_bench` on `corpus/raw/arw-sony-a7m3-compressed.arw` (24 MP; loupe = 2560 px preview → 1920×1280), min of 7 runs, wall clock, on a heavily shared machine (load average 60–110 on 14 cores, so CPU numbers are pessimistic; the GPU numbers are less affected): diff --git a/docs/guided-filter-memory.md b/docs/guided-filter-memory.md new file mode 100644 index 0000000000..de0fe1b62a --- /dev/null +++ b/docs/guided-filter-memory.md @@ -0,0 +1,53 @@ +# CPU fast guided-filter memory + +`local::guided_fast` computes blurred coefficients on the same reduced grid as before, then +samples them while applying `a * p + b`. It keeps the raster resizer's weights, boundary +normalization and horizontal-then-vertical accumulation order. Odd dimensions therefore use +their actual reduced/full dimension ratios. Four coefficient row pairs and one bias row are cached +per active 32-row band; adjacent output rows reuse their horizontal samples. + +The two full-resolution coefficient planes and their resize intermediates are gone. The returned +full-resolution base remains: downstream CPU tone mapping and the spatial-plane cache need it. +The step-1 filter, Box reduction, Gaussian coefficients, V2's median input, process selection and +Draft sigma cap are unchanged. The GPU implementation is unchanged; this reduces CPU memory only. + +## Reproduce + +The dev-only example includes the previous materialized algorithm and uses the workspace's +existing `dhat` allocator. No allocator or profiling dependency is added to product builds. + +```sh +cargo build --release -p lightcraft-pipeline --example guided_memory +RAYON_NUM_THREADS=1 target/release/examples/guided_memory old 6000 4000 120 15 +RAYON_NUM_THREADS=1 target/release/examples/guided_memory new 6000 4000 120 15 +RAYON_NUM_THREADS=1 target/release/examples/guided_memory old 6000 4000 120 1 --heap +RAYON_NUM_THREADS=1 target/release/examples/guided_memory new 6000 4000 120 1 --heap +``` + +If `CARGO_TARGET_DIR` is set, use that directory instead of `target` for the executable. +Arguments are mode, width, height, integer sigma and timing iterations. The example warms up +before measurement; `--heap` counts one filter call with the source allocated beforehand. +Time the runs without `--heap`: allocation profiling significantly changes timings. It reports +the minimum wall time; on a shared machine repeat when other builds/renders have stopped. +Use `LIGHTCRAFT_PROFILE=1` and `cargo xtask bench` for broader pipeline measurements. + +## Observed allocation and time + +Measured 2026-10-16 UTC, macOS aarch64, Rust 1.96.0, release build, one Rayon thread. Bytes are +requested heap bytes counted by dhat, not process RSS. Timings are minimums of 15 unprofiled +calls on a shared machine with concurrent builds; they are indicative, not a speed guarantee. + +| Dimensions / sigma / step | Old peak bytes | New peak bytes | Old total allocated bytes | New total allocated bytes | Old / new wall ms | +|---|---:|---:|---:|---:|---:| +| 6000 × 4000 / 120 / 16 | 289,125,000 | 97,780,856 | 313,083,488 | 135,643,856 | 42.135 / 45.131 | +| 1601 × 1067 / 24 / 8 | 20,822,412 | 7,331,172 | 25,102,604 | 11,562,560 | 3.359 / 3.121 | + +The 24 MP result saves about 191 MB of peak allocation (66%). Its **96,000,000-byte output is +included**; its **96,000,000-byte input is excluded**. Application RGB images, log luminance, +V2 median input and its construction temporaries, other spatial planes and caches also remain +outside this isolated measurement. More Rayon threads can hold more band scratch concurrently. +This is not a bound on total pipeline memory. + +Regression tests compare the sampled result exactly against materialized bilinear resizes for +empty/singleton/one-dimensional, odd/even and multiple-band images; flat fields, signed texture, +edges and impulses; small/full and reduced filters; and median tone bases. diff --git a/docs/library-shortcuts.md b/docs/library-shortcuts.md index 211b00b76e..98ae0558a9 100644 --- a/docs/library-shortcuts.md +++ b/docs/library-shortcuts.md @@ -17,6 +17,10 @@ Select photos in Photo Grid or Square Grid, then use: | `Cmd`/`Ctrl` + `↑` / `↓` | Raise / lower flag status (reject < unflagged < pick; stops at either end) | | `Shift` + `0`–`9`, `P`, `X` or `U` | Apply the action and select the next photo | | `\` (backslash) | Show / hide the Filter Bar | +| ⌘K / Ctrl+K | Add Keywords: show the Keywords panel with the cursor in its Add keyword box | +| ⌘L / Ctrl+L | Enable Filters: switch the filter off and on | +| ⌘⌥⇧C / Ctrl+Alt+Shift+C | Copy Metadata: copy the active photo's metadata | +| ⌘⌥⇧V / Ctrl+Alt+Shift+V | Paste Metadata: paste the copied metadata on the selected photos | Enter opens the active photo without changing the selection. Text fields, dialogs and open popups keep the key; a custom Enter binding takes precedence. Enter has no additional action in Detail. @@ -82,7 +86,18 @@ Survey and Reference, and leave text fields alone, so the search box still types commands (`view.thumbSizeUp`, `view.thumbSizeDown`, reachable from the control channel and MCP, which return `{"size"}`); the size is saved with the other interface settings. -Public behaviour references, checked 2026-10-08 (thumbnail size: 2026-10-13): +## Keyword sets + +`⌥1`–`⌥9` (`Alt+1`–`Alt+9` on Windows and Linux) add or remove the current keyword set's keywords on +the selected photos. `⌥0` makes the next keyword set current and `⌥⇧0` the previous one (`Alt+0` / +`Alt+Shift+0`), in the order of the Keywords panel's Keyword Set menu: Recent Keywords, then the saved +sets. After the last set comes Recent Keywords again, and before Recent Keywords comes the last set; +with no saved sets the keys leave Recent Keywords current. The shortcut list does not say what happens +past either end; wrapping around is LightCraft's choice. The same steps are the Next / Previous +Keyword Set commands (`keyword.nextSet`, `keyword.previousSet`), which return what `keyword.sets` +returns, and both keys can be reassigned in Help → Keyboard Shortcuts. + +Public behavior references, checked 2026-10-08 (thumbnail size: 2026-10-13; keyword sets: 2026-10-24): - [Lightroom Classic keyboard shortcuts](https://helpx.adobe.com/lightroom-classic/help/keyboard-shortcuts.html) - [Lightroom Classic flagging, labelling and rating](https://helpx.adobe.com/lightroom-classic/help/flag-label-rate-photos.html) diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 441becd15e..cd5df6b85d 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -6,7 +6,41 @@ and a C SQLite runtime are not required. The source database is read-only, inclu File → Open Library… given a Lightroom catalog folder (or an `.lrdata` / `.lrcat-data` folder, or the `.lrcat`) doesn't make a LightCraft library there: it offers this import instead, with the catalog found -(`crates/engine/src/lightroom_folder.rs`, issue #891). `lightcraft-cli --library` refuses those places too. +(`crates/engine/src/lightroom_folder.rs`, issue #891), and then asks where the catalog goes as described next +(unless the question is turned off, below). +`lightcraft-cli --library` refuses those places too. + +**Where the catalog goes.** Before the import starts, the desktop app asks where the catalog goes (issue #2672), +unless Settings says to always merge (*Turning the question off*, below): + +- **Merge into the open library "<name>" (N photos)**: the catalog's photos, collections and edits join the ones + already in the library open now (the library's name is its folder's name). +- **Create a new library**: named after the catalog file (`Travel.lrcat` → "Travel", or "Travel 2" when a + "Travel" folder is already there) and placed next to the open library (in its parent folder); both can be + changed (Choose… picks the folder). LightCraft creates and opens it as File → New Library… does (the folder + must be new or empty; it is refused while another import runs), then imports the catalog into it. The library + left behind stays in File → Open Recent Library. +- **Cancel** does nothing. + +The window opens on *Merge* when the open library has no photos (there is nothing to merge with) and on *Create a +new library* when it has some. + +**Turning the question off.** Settings → General → Library → *When importing a Lightroom catalog*: *Ask where to +import it* (the default) or *Always merge into the open library* (how imports always worked before). The window's +*Don't ask again (always merge into the open library)* checkbox, offered with *Merge*, picks the second; the window +says where to turn the question back on. The choice is an app setting (`ui.json`, `settings.lightroomImport`: +`"ask"` or `"alwaysMerge"`); a settings file without it asks. + +A session with no library on disk (in memory, e.g. after Continue Without Saving) has nothing to put a new library +next to: the catalog merges into it without asking, as before. + +**Scripts and agents.** The app command `file.importLightroom {path?, into?, name?, location?}` (control channel, +`lightcraft-cli mcp --connect`) chooses without the window: `into: "open"` merges, `into: "new"` creates the library +`name` (default: the catalog's name) in the folder `location` (default: the open library's parent folder; a full +path), opens it and imports. Without `into` it shows the window (and returns `{asking: true, path, into}`, `into` +being the choice the window opens with) or merges when the setting says so. A catalog path that doesn't exist is +refused before a new library is made. The engine command `library.importLightroom` always imports into the library +open now. Equivalent commands: @@ -15,8 +49,8 @@ lightcraft-cli run --library "LightCraft Library" library.inspectLightroom path= lightcraft-cli run --library "LightCraft Library" library.importLightroom path="Lightroom Catalog.lrcat" ``` -Import adds records to the currently open LightCraft library; it does not create a separate -folder named after the Lightroom catalog. The desktop result stays open until dismissed and +The import itself (`library.importLightroom`, `lightcraft-cli run`) adds records to the currently open LightCraft +library; only the desktop window above can make a new library for it first. The desktop result stays open until dismissed and shows the destination library, the number of records added, missing originals and warnings. **Show in Library** opens All Photos, clears filters and selects an imported record. Errors stay readable in the same result window. If another dialog is open, the result waits until that dialog closes. The result diff --git a/docs/localization-cs.md b/docs/localization-cs.md index 52fad4542b..c3ed1ddcf4 100644 --- a/docs/localization-cs.md +++ b/docs/localization-cs.md @@ -46,8 +46,9 @@ ani anglické zdrojové řetězce. Rozložení panelů a seznamu jazyků je beze ## Ověření a revize Testy `i18n::tests` ověřují registraci příkazu, přepínání přes nabídku a řídicí kanál, -uložení jazyka, pokrytí katalogů, placeholdery, neutrální formulace počtů, datum, čas -a české glyfy. Překladové šablony kontroluje také Rust při sestavení. +uložení jazyka, placeholdery, datum, čas a české glyfy. Překladové šablony kontroluje také +Rust při sestavení. Chybějící překlady se zobrazují anglicky a vypisuje je +`i18n::tests::translation_gaps_report`; žádný test kvůli nim neselže. Při jazykové korektuře doporučujeme zkontrolovat „asistované třídění“, „sada“ pro Stack, „bodová barva“, „měkký nátisk“ a názvy kreativních přednastavení. diff --git a/docs/localization-de.md b/docs/localization-de.md index 0ceb3b45b2..b31e9eff53 100644 --- a/docs/localization-de.md +++ b/docs/localization-de.md @@ -16,6 +16,32 @@ werden nicht übersetzt. Die vorhandenen Inter-Schriften enthalten die deutschen für Deutsch ist kein zusätzlicher Font-Download nötig. Beschreibungen für SAM 3 werden unverändert an das Modell übergeben; die Beispiele verwenden dessen englische Begriffe. +## Begriffe + +Eine Durchsicht aller Oberflächentexte und Meldungen (2026-10-24, mit einem Agenten erstellt und +von einem Muttersprachler stichprobenartig geprüft; die Versionshinweise nicht) hat diese Begriffe +festgelegt. Neue Texte verwenden sie ebenfalls: + +| Englisch | Deutsch | Anmerkung | +|---|---|---| +| Panel | Bedienfeld | wie in Lightroom; **Bereich** bleibt für Abschnitte (Sections) der Seitenleiste | +| Sidecar | Begleitdatei (XMP-Begleitdatei) | | +| Slide | Dia | passend zu „Diashow“ | +| Crop | Zuschnitt, zuschneiden | | +| Flag / Pick / Reject | Markierung / ausgewählt / abgelehnt | | +| Label (Color Label) | Farbmarkierung | nie nur „Markierung“, das ist die Ausgewählt/Abgelehnt-Kennzeichnung | +| Tint | Tönung | wie in Lightroom; „Tonung“ nur für Tonungsvorgaben wie Sepiatonung | +| Clipping | Beschneidung | wie Lightroom („Lichter-/Tiefenbeschneidung“); „Beschnitt“ ist ein Druckbegriff | +| Shutter Speed | Verschlusszeit | | +| Upright | Perspektivkorrektur | | +| Smart Album | Smart-Album | | +| Activity stack | Aktivitätsstapel | | + +Typografie: Gedankenstrich mit Leerzeichen als Halbgeviertstrich (` – `), Auslassungspunkte +ohne Leerzeichen direkt am Wort (`Importieren…`), deutsche Anführungszeichen („…“). „Ihre“ +nur, wo es eindeutig „von ihnen“ heißt; die Anrede ist *du*, ein Satz mit „Ihre Fotos“ am +Anfang liest sich sonst wie die Sie-Form. + ## Wartung und Prüfung Feste Texte: `crates/ui-egui/locales/de.json`. Meldungen mit Werten: @@ -29,8 +55,8 @@ cargo test -p lightcraft-ui-egui i18n::tests LIGHTCRAFT_LANGUAGE=de lightcraft-cli snapshot --demo -o deutsch.png --size 1600x1000 ``` -Die Tests prüfen Katalogabdeckung, Platzhalter, Sprachwechsel per Menü und Steuerkanal, -Speicherung, Datumsformate, unveränderte Benutzernamen und gerenderte Texte sowie Umlaute -und ß. Ein weiterer Render-Test prüft die Schaltflächenbreiten; der Importtest prüft +Die Tests prüfen Platzhalter, Sprachwechsel per Menü und Steuerkanal, Speicherung, +Datumsformate, unveränderte Benutzernamen und gerenderte Texte sowie Umlaute und ß. Fehlende +Übersetzungen erscheinen auf Englisch; `i18n::tests::translation_gaps_report` listet sie auf. Ein weiterer Render-Test prüft die Schaltflächenbreiten; der Importtest prüft auch den Sprachwechsel nach der Hintergrundprüfung der Quellen. Akzeptierte Sprachangaben umfassen `de`, `de-DE`, `de_AT.UTF-8` und `de-CH`; gespeichert wird stets `de`. Weitere Hinweise stehen in [localization.md](localization.md). diff --git a/docs/localization-fi.md b/docs/localization-fi.md index d80a2e1ccd..fcb89d7844 100644 --- a/docs/localization-fi.md +++ b/docs/localization-fi.md @@ -52,8 +52,9 @@ englanniksi. Käännös ei muuta kirjastotietoja eikä englanninkielisiä lähde ## Testaus `i18n::tests` tarkistaa komennon rekisteröinnin, vaihdon valikosta ja ohjauskanavasta, -kielen tallennuksen, luetteloiden kattavuuden, paikkamerkit, määrämuodot, päivämäärän, ajan ja -suomen kirjaimet. Rust tarkistaa muotoilumallit käännösvaiheessa. +kielen tallennuksen, paikkamerkit, päivämäärän, ajan ja suomen kirjaimet. Rust tarkistaa +muotoilumallit käännösvaiheessa. Puuttuvat käännökset näkyvät englanniksi, ja +`i18n::tests::translation_gaps_report` luettelee ne; mikään testi ei epäonnistu niiden takia. Kielentarkistuksessa kannattaa katsoa erityisesti: ”Väriluokittelu” (Color Grading), ”Valoalueet / Valkoiset” (Highlights / Whites), ”Näyttövedos” (Soft Proofing), diff --git a/docs/localization-ka.md b/docs/localization-ka.md index 4d517c6ca4..e26f6e4a43 100644 --- a/docs/localization-ka.md +++ b/docs/localization-ka.md @@ -19,7 +19,7 @@ not translated. Descriptions for SAM 3 go to the model unchanged. ## Georgian script Mkhedruli has no upper and lower case: `i18n::upper_first` leaves Georgian letters alone, and the -interface never uses Mtavruli (a test checks the whole catalog). Commands are verbal nouns. Counts +interface never uses Mtavruli. Commands are verbal nouns. Counts are count-neutral, noun first (`იმპორტირებულია ფოტო: 3`); English plural endings are dropped with `{:.0}`. Dates read `კვირა, 20.09.2026` (`{weekday}, {day:02}.{month:02}.{year}`), months `09.2026`. @@ -73,7 +73,7 @@ cargo test -p lightcraft-ui-egui i18n::tests -- --nocapture LIGHTCRAFT_LANGUAGE=ka lightcraft-cli snapshot --demo -o georgian.png --size 1600x1000 ``` -The tests check catalog coverage, placeholders, switching language by menu and control channel, -saving, the `ka` locale tags, dates, count wording, the absence of Mtavruli and that sentence case -keeps Georgian lowercase. More notes are in +The tests check placeholders, switching language by menu and control channel, saving, the `ka` +locale tags, dates and that sentence case keeps Georgian lowercase. Messages Georgian lacks show in +English; `i18n::tests::translation_gaps_report` lists them. More notes are in [localization.md](localization.md). diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 41669e4b78..7813b62575 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,12 +1,12 @@ # Localization parity -> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-20 · **Change:** minor (German form of address: *du*; Indonesian and Finnish interface catalogs added; Italian: every interface string translated, native-speaker corrections; Vietnamese shipped; previously minor: de, es, fr, ja, uk catalogs filled; re-measured; Italian and Georgian interface catalogs added) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-24 · **Change:** minor (German: interface strings and formats messages reviewed, terms fixed in localization-de.md; German form of address: *du*; Indonesian and Finnish interface catalogs added; Italian: every interface string translated, native-speaker corrections; Vietnamese shipped; previously minor: de, es, fr, ja, uk catalogs filled; re-measured; Italian and Georgian interface catalogs added) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 How far each interface language is from `full`. How to add or maintain a language is in [localization.md](localization.md); per-language notes are in `localization-<code>.md` ([zh-hans](localization-zh-hans.md), [zh-hant](localization-zh-hant.md), [ja](localization-ja.md), [pt-br](localization-pt-br.md), [es](localization-es.md), [de](localization-de.md), -[ru](localization-ru.md), [fi](localization-fi.md), [ka](localization-ka.md), [id](localization-id.md), [vi](localization-vi.md)). +[ru](localization-ru.md), [fi](localization-fi.md), [ka](localization-ka.md), [id](localization-id.md), [vi](localization-vi.md), [pl](localization-pl.md)). ## The target @@ -37,7 +37,7 @@ scripts `Latn`, `Cyrl`, `Hans`, `Hant`, `Jpan` only. The UI is egui, which has n and no complex-script shaping, so Arabic (RTL, joining) and Devanagari (conjuncts, reordering) cannot render correctly today. -Native-speaker review: no catalog has had a formal review. Several catalogs have edits from community +Native-speaker review: no catalog has had a full formal review; German's interface strings and formats messages have (2026-10-24, What's New not). Several catalogs have edits from community contributors whose commits only touch that language (ja, zh-hans, zh-hant, fr, de, ru, uk, pt-br); that is promising but is not recorded as review, so the column says `no (community edits)`. @@ -58,11 +58,11 @@ string follows that. | 7 | Portuguese (Brazil) | `pt-br` | 1,966 / 2,304 (85%) | as zh-hans | Latin | no (community edits) | partial | 6–10 h | | 8 | Indonesian | `id` | 2,555 / 2,555 (100%; 2026-10-19: every plain and formats message any catalog has, plus 69 command labels; What's New left in English) | as zh-hans | Latin (Inter covers it) | no (written with an agent; native-speaker pass pending) | partial (target: not shipped) | 2–4 h (native review, lower-layer errors) | | 9 | Japanese | `ja` | 2,383 / 2,398 (99%; 2026-10-12) | as zh-hans; vertical export watermarks | Jpan via craft-fonts (BIZ UDPGothic / UDMincho); IME through winit | no (community edits) | partial | 2–4 h (native review, lower-layer errors) | -| 10 | German | `de` | 3,644 / 3,754 (97%; 2026-10-16: every interface message and every What's New line except 59: the distinct What's New lines whose English text has a ▸ menu path have no German entry yet and wait for #2016; the rest are words spelled the same) | as zh-hans; What's New translated line by line | Latin | no (community edits) | partial | 2–4 h (native review, lower-layer errors) | +| 10 | German | `de` | 3,644 / 3,754 (97%; 2026-10-16: every interface message and every What's New line except 59: the distinct What's New lines whose English text has a ▸ menu path have no German entry yet and wait for #2016; the rest are words spelled the same) | as zh-hans; What's New translated line by line | Latin | partly (2026-10-24: every interface string and formats message, reviewed with an agent and spot-checked by a native speaker; What's New lines not reviewed) | partial | 1–2 h (What's New review, lower-layer errors) | | 11 | Korean | `ko` | 0 (0%) | none | **no Korean (Hangul) face**: needs a non-Adobe OFL face in craft-fonts (Noto CJK is allowed only for Chinese) | no | none | 14–22 h | | 12 | Vietnamese | `vi` | 2,471 / 2,471 (100% key coverage of current union; intentional English like `ISO`/`OK` kept) | menus, panels, dialogs, presets, profiles, dates, formats; lower-layer errors English | Latin with stacked diacritics (Inter) | no (community contribution) | partial (catalog complete; lower-layer errors English) | 1–3 h | -## Other languages LightCraft ships (4) +## Other languages LightCraft ships (7) | Language | Code | UI strings translated | Script | Native review | Status | To `full` | |---|---|---:|---|---|---|---:| @@ -72,8 +72,9 @@ string follows that. | Italian | `it` | 2,628 / 3,278 (80%, measured 2026-10-15; every interface string is translated, the other 650 are What's New lines, left in English) | Latin (Inter) | partly (written with an agent; corrections and the 2026-10-15 additions by a native speaker) | partial (lower-layer errors English) | 3–5 h | | Georgian | `ka` | 2,398 / 2,398 (100%: every plain and formats message any catalog has on 2026-10-12, plus the 27 display labels and 397 What's New lines no other catalog translates) | Geor: no craft-fonts face yet (boxes until one is available) | yes (native speaker) | partial (lower-layer errors English) | 2–4 h (+ a Georgian face) | | Finnish | `fi` | 2,610 / 3,308 (79%, measured 2026-10-17: 2,313 plain + 297 formats; the rest is What's New) | Latin (Inter) | yes (written with an agent; native-speaker review by @roopeg) | partial (lower-layer errors English) | 3–5 h | +| Polish | `pl` | 2,159 messages + 291 formats; every format message translated (2026-10-15) | Latin (Inter) | no (AI-drafted; follow-up by a native speaker) | partial (lower-layer errors English) | 2–4 h (full native review) | -Target languages LightCraft lacks: Korean, Dutch, Polish, Swedish, Norwegian Bokmål, Thai +Target languages LightCraft lacks: Korean, Dutch, Norwegian Bokmål, Thai (Thai needs shaping and line breaking without spaces). Each Latin-script one is ~10–16 h; Thai ~20–35 h on top of the shaping work. @@ -90,9 +91,9 @@ Target languages LightCraft lacks: Korean, Dutch, Polish, Swedish, Norwegian Bok ## Totals -- Bring the 10 shipped non-English catalogs to `full`: ~55–90 h (incl. the shared work). +- Bring the shipped non-English catalogs to `full` (17 on 2026-10-23; the estimate was made for 10): ~55–90 h (incl. the shared work). - Add the 5 missing key languages: ~145–255 h, most of it RTL and complex shaping in egui. -- Reach the target's 16 languages: + ~50–85 h (Dutch, Polish, Swedish, Norwegian, Thai). +- Reach the target's 16 languages: + ~30–55 h (Dutch, Norwegian, Thai; Polish and Swedish ship). ## Revision history @@ -100,6 +101,7 @@ Target languages LightCraft lacks: Korean, Dutch, Polish, Swedish, Norwegian Bok |---|---|---| | 2026-10-19 | minor | Indonesian interface catalog (`id`): every plain and formats message any catalog has, plus 69 command labels; What's New left in English | | 2026-10-17 | minor | Finnish interface catalog (`fi`): 2,610 of 3,308 messages (2,313 plain + 297 formats), What's New left in English | +| 2026-10-15 | minor | Polish row added: the format messages still in English translated, counts made right for every number, dates day.month.year ([localization-pl.md](localization-pl.md)) | | 2026-10-15 | trivial | Italian (`it`): 339 interface messages and 60 format strings that were missing or still in English translated (2,628 of 3,278; only What's New left in English); native-speaker corrections: Exposure → *Esposizione*, Sharpening → *Nitidezza*, Preset → *Preset*, blurry → *sfocate* | | 2026-10-13 | minor | Remeasured denominator (2,222 plain + 249 formats = 2,471); Vietnamese catalog complete at 2,471/2,471 (status partial: lower-layer errors still English) | | 2026-10-12 | minor | Italian interface catalog (`it`): 2,201 of 2,398 messages, What's New left in English | @@ -108,4 +110,5 @@ Target languages LightCraft lacks: Korean, Dutch, Polish, Swedish, Norwegian Bok | 2026-10-10 | major | Created: per-language counts measured from the catalogs, the twelve key languages, script support, estimates | | 2026-10-12 | minor | de, es, fr, ja and uk catalogs filled to every message another catalog knows (agent translations, native review welcome); those rows re-measured against the current 2,398 messages. Other rows keep their 2026-10-10 counts (open PRs for pt-BR, ru, zh) | | 2026-10-16 | minor | German (`de`): 217 interface strings and 862 What's New lines added (agent translations, native review welcome); re-measured 2,572 → 3,644 of 3,754 messages (80% → 97%). The denominator grew because German now translates What's New lines no other catalog has; other rows keep their earlier counts | +| 2026-10-24 | minor | German (`de`): interface strings and formats messages reviewed (agent-prepared, spot-checked by a native speaker); 108 messages corrected (Tönung, Beschneidung, Farbmarkierung vs. Markierung, Bedienfeld, Begleitdatei, Dia, en dash and ellipsis spacing, ambiguous *Ihre*); terms listed in localization-de.md; native review column `partly`, estimate 1–2 h | | 2026-10-20 | minor | German (`de`) speaks to the user with *du*; the 11 messages that used *Sie* changed, no count changes | diff --git a/docs/localization-pl.md b/docs/localization-pl.md new file mode 100644 index 0000000000..445dbcf639 --- /dev/null +++ b/docs/localization-pl.md @@ -0,0 +1,56 @@ +# Polski + +Język polski (`pl`, English name **Polish**, nazwa natywna **Polski**) włącza się przez **Edytuj → Język → +Polski** albo **Ustawienia → Ogólne → Język**. Zmiana działa od razu i jest zapamiętywana przy kolejnym +uruchomieniu. Polecenie to `app.language.polish`; kanał sterowania przyjmuje `ui.set {"language":"pl"}` +oraz znaczniki `pl-PL` i `pl_PL.UTF-8`. Bez okna można ustawić `LIGHTCRAFT_LANGUAGE=pl`. + +Katalogi `crates/ui-egui/locales/pl.json` i `pl-formats.json` dodał #1100 (tłumaczenie przygotowane +z pomocą AI). Uzupełnienie opisane niżej również przygotowano z pomocą AI; przygotował je rodzimy +użytkownik języka polskiego (@lewandowskit). Profesjonalny tłumacz nie robił jeszcze korekty. + +## Konwencje + +- Menu: Plik, Edytuj, Widok, Zdjęcie, Okno, Pomoc. +- Library = Biblioteka, Develop = Wywoływanie, Preset = Ustawienie wstępne, Stack = Stos, + Masking = Maskowanie, Virtual Copy = Kopia wirtualna, Filmstrip = Pasek zdjęć. +- Clarity = Przejrzystość, Dehaze = Usuń zamglenie, Vibrance = Dynamika, Saturation = Nasycenie. +- Highlights = Światła, Shadows = Cienie, Whites = Biele, Blacks = Czernie. +- Cudzysłowy polskie: „…”. Ścieżki menu w tekstach: `Edytuj → Cofnij`. +- Data ma postać `20.09.2026` (dzień.miesiąc.rok), nagłówek dnia `Niedziela, 20.09.2026`, + miesiąca `09.2026`; czas 24-godzinny (`16:04:05`). +- **Liczby i rzeczowniki.** Polski ma trzy formy liczby mnogiej (1 zdjęcie, 2 zdjęcia, 5 zdjęć), + a mechanizm katalogów rozróżnia tylko „jeden” i „wiele”. Dlatego liczba stoi po rzeczowniku: + „Zaimportowane zdjęcia: 22”, „Usuń zdjęcia (3)”, „Oczekujące zdjęcia: 2”. Taka forma jest + poprawna dla każdej liczby. Angielska końcówka liczby mnogiej jest pochłaniana przez `{:.0}` + (jak w [localization.md](localization.md)). Po przyimku z dopełniaczem („z 10 zdjęć”, „dla 3 + zaznaczonych zdjęć”) liczba może stać przed rzeczownikiem, bo forma jest wtedy zawsze ta sama. +- Komunikaty `{n} {noun}` (np. w panelu Odszumianie AI) mają postać `{noun}: {n}`, a obie formy + rzeczownika (`photo waiting` / `photos waiting`) tłumaczą się tak samo. +- Font Inter dołączony do aplikacji zawiera wszystkie polskie litery i cudzysłowy; inny font + nie jest potrzebny. + +## Uzupełnienie (2026-10-15) + +- Przetłumaczono 40 komunikatów `pl-formats.json`, które były jeszcze po angielsku (ustawienia + efektów masek, szablony pokazu slajdów, import katalogu Lightroom, słowa kluczowe, osoby, + scalanie panoram, komunikat o nieoczekiwanym zakończeniu programu) i 2, w których zmieniono + tylko strzałkę. +- Poprawiono 25 komunikatów, w których liczba stała przed rzeczownikiem w dopełniaczu i dla + 2–4, 22–24… dawała błędną formę („Usuń 2 zdjęć”), oraz `{} failed`, gdzie `{}` jest nazwą + zadania, a nie liczbą. +- Daty: `{month} {year}` i `{weekday}, {day} {month} {year}` mają postać dzień.miesiąc.rok + zamiast „20 9 2026”. + +Katalog ma 2 159 zwykłych komunikatów i 291 szablonów formatów. Komunikaty, których nie ma w +katalogu, oraz techniczne błędy niższych warstw wyświetlają się po angielsku. + +## Weryfikacja + +Test `i18n::tests::polish_switches_formats_dates_and_reads_every_count` sprawdza przełączanie +z menu i kanału sterowania, zapamiętanie języka, znaczniki `pl-*`, daty, czas, liczby 0–111 +(w tym 2–4 i 22–25) w liczonych komunikatach, nazwy użytkownika pozostawione bez zmian oraz +polskie znaki w fontach interfejsu. Zgodność placeholderów sprawdza +`catalogs_agree_on_placeholders_and_report_gaps`. + +Postęp dodawania języków opisuje [localization.md](localization.md). diff --git a/docs/localization-vi.md b/docs/localization-vi.md index 2bd6c74e05..02862bc4c0 100644 --- a/docs/localization-vi.md +++ b/docs/localization-vi.md @@ -66,8 +66,9 @@ LIGHTCRAFT_LANGUAGE=vi lightcraft-cli snapshot --demo -o vi.png --size 1600x1000 LIGHTCRAFT_LANGUAGE=vi lightcraft-cli snapshot --demo -o vi-narrow.png --size 1280x800 ``` -Các test tiếng Việt bắt buộc phủ catalog union, nhãn lệnh/control/Settings/Smart Album, -đổi ngôn ngữ, lưu `vi`, formats, ngày, dữ liệu người dùng, và glyph dấu. +Các test tiếng Việt kiểm tra đổi ngôn ngữ, lưu `vi`, formats, ngày, dữ liệu người dùng và glyph +dấu. Chuỗi còn thiếu hiện bằng tiếng Anh và được `i18n::tests::translation_gaps_report` liệt kê; +không test nào thất bại vì thiếu bản dịch. ## Nguồn dịch (clean-room) diff --git a/docs/localization-zh-hans.md b/docs/localization-zh-hans.md index e874315827..bf41dfed57 100644 --- a/docs/localization-zh-hans.md +++ b/docs/localization-zh-hans.md @@ -34,5 +34,6 @@ LightCraft 的界面支持英语、简体中文、繁体中文(台湾)和日 `LIGHTCRAFT_LANGUAGE=zh-hans lightcraft-cli snapshot ...` 可以渲染中文界面用于检查。 -翻译是否完整、两种目录的键与占位符是否一致、字形是否齐全,都由 +两种目录的占位符是否一致、字形是否齐全,由 `cargo test -p lightcraft-ui-egui i18n::tests` 验证(字形检查只在指定 `CRAFT_FONTS_DIR` 时实际执行)。 +缺少的译文显示为英文,由 `i18n::tests::translation_gaps_report` 列出,不会让测试失败。 diff --git a/docs/localization.md b/docs/localization.md index 94abfe236a..b878a5de28 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -2,21 +2,20 @@ The interface ships in the language it is written in (English) plus every language in the table in `crates/ui-egui/src/i18n.rs`. Today that is English, Simplified Chinese (`zh-hans`), Traditional -Chinese (`zh-hant`, Taiwan), Japanese (`ja`), Brazilian Portuguese (`pt-br`), Spanish (`es`), German (`de`), Russian (`ru`), French (`fr`), Ukrainian (`uk`), Czech (`cs`), Georgian (`ka`), Swedish (`sv`), Finnish (`fi`), Indonesian (`id`) and Vietnamese (`vi`). This file is the reference for **adding or maintaining a language**; the per-language notes +Chinese (`zh-hant`, Taiwan), Japanese (`ja`), Brazilian Portuguese (`pt-br`), Spanish (`es`), German (`de`), Russian (`ru`), French (`fr`), Ukrainian (`uk`), Czech (`cs`), Italian (`it`), Georgian (`ka`), Swedish (`sv`), Finnish (`fi`), Indonesian (`id`), Vietnamese (`vi`) and Polish (`pl`). This file is the reference for **adding or maintaining a language**; the per-language notes are in [`localization-zh-hans.md`](localization-zh-hans.md), [`localization-zh-hant.md`](localization-zh-hant.md), [`localization-ja.md`](localization-ja.md), [`localization-pt-br.md`](localization-pt-br.md), [`localization-es.md`](localization-es.md), [`localization-de.md`](localization-de.md), [`localization-ru.md`](localization-ru.md), -[`localization-cs.md`](localization-cs.md), [`localization-fi.md`](localization-fi.md), [`localization-ka.md`](localization-ka.md), [`localization-id.md`](localization-id.md) and [`localization-vi.md`](localization-vi.md). +[`localization-cs.md`](localization-cs.md), [`localization-fi.md`](localization-fi.md), [`localization-ka.md`](localization-ka.md), [`localization-id.md`](localization-id.md), [`localization-vi.md`](localization-vi.md) and [`localization-pl.md`](localization-pl.md). ## Adding a language 1. **Translate the two catalogs.** Copy `locales/ja.json` and `locales/ja-formats.json` to `locales/<code>.json` and `locales/<code>-formats.json`, then translate the values. Keys are the - English source strings and must stay byte-for-byte identical. The plain catalog may grow at its - own pace: a message it lacks shows in English, and `cargo test -p lightcraft-ui-egui i18n::tests - -- --nocapture` lists the gaps (it fails on an empty entry or mismatched placeholders). The - formats catalog must carry every message (the build fails otherwise; a message copied in English, - value equal to its key, is an untranslated placeholder until someone translates it), including the date + English source strings and must stay byte-for-byte identical. Both catalogs may grow at their + own pace: a message a catalog lacks, or translates as an empty string, shows in English, and + nothing fails. The translation gaps report lists what each language lacks (see + [Testing and looking at it](#testing-and-looking-at-it)). The formats catalog also holds the date patterns (`{year}`, `{month} {year}`, `{weekday}, {day} {month} {year}`…) that date headings and capture times use in every language but English; weekday names go in the plain catalog. 2. **Add the table entry** in `crates/ui-egui/src/i18n.rs`: @@ -81,18 +80,23 @@ tr_format!("Added {n} photo{} to “{}”", if n == 1 { "" } else { "s" }, album `"已将 {n} 张照片添加到“{1}”{0:.0}"`. Keep the source's spec (`{:.1}`, `{d:+}`, `{:.0}%`). - `format!` rejects an unused argument, so a value a language does not need — the English plural suffix (`"s"` / `""`) — is consumed as `{:.0}` (a string at precision 0 prints nothing). -- Every formats catalog carries the same messages (`build.rs` fails the build otherwise), and a - `tr_format!` call whose message is in no catalog does not compile: add it to every - `*-formats.json` file. +- A language whose formats catalog lacks a message shows the English source there, and a + `tr_format!` call whose message is in no catalog formats the English source (the macro's last + arm). A new message builds with no catalog entry. ## Testing and looking at it ```sh -cargo test -p lightcraft-ui-egui i18n::tests # catalogs, keys, placeholders, commands +cargo test -p lightcraft-ui-egui i18n::tests # catalogs load, placeholders, switching CRAFT_FONTS_DIR=../craft-fonts cargo test -p lightcraft-ui-egui i18n::tests # + glyph coverage +cargo test -p lightcraft-ui-egui --lib -- --exact i18n::tests::translation_gaps_report --nocapture ``` -The glyph tests are skipped without `CRAFT_FONTS_DIR` (there are no CJK faces to check then). +The tests fail on a broken catalog (malformed JSON, a repeated key, placeholders that differ from +the source), never on a missing translation. The last command is the translation gaps report: per +language, the count and list of plain and format messages it lacks and the number of untranslated +What's New lines. It always passes, and `cargo xtask ci` prints it after its test step. The glyph +tests are skipped without `CRAFT_FONTS_DIR` (there are no CJK faces to check then). To look at a language, render it headless: ```sh @@ -114,5 +118,5 @@ when a region has no dedicated entry. Help ▸ What's New shows `docs/whats-new.md`, and each of its lines (a heading, or one wrapped line of a bullet, without the `- ` or `### `) is looked up like any message, so a catalog can translate the notes line by line (German does). A line that is re-wrapped or edited no longer matches its translation and -shows in English until the catalog is updated; untranslated lines are reported by -`display_label_gaps_are_reported`, never failed. +shows in English until the catalog is updated; the translation gaps report counts the untranslated +lines. diff --git a/docs/mcp.md b/docs/mcp.md index af4c53ca92..4800c37d81 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -170,7 +170,7 @@ per-request `_meta` receive `resultType: complete` and list/read cache hints; re |---|---| | `list_commands {filter?}` | Every command: id, label, menu, shortcut, parameter doc, enabled now | | `run_command {command, params?}` | Run any command by id | -| `import {paths, album?, mode?, destination?, organize?, rename?}` | Import files/folders (folders are scanned recursively); the first new photo becomes active. `mode: "copy"` copies into `destination` (default: the library's Originals/), `mode: "move"` moves there (each original and its XMP sidecars are removed from the source only after the copy is verified and catalogued; duplicates and failures keep their sources; the result's `moved` / `kept` list what moved and what stayed, and why; undo leaves the moved files at the destination), filed by `organize`: `date` (YYYY/YYYY-MM-DD), `month`, `flat` or a folder template such as `{date:%Y}/{date:%Y%m%d}` (→ `2026/20260114`; capture date, else the import date; always inside the destination), and named by the `rename` template (`run_command photo.renameTokens` lists the tags) | +| `import {paths, album?, mode?, destination?, organize?, rename?}` | Import files/folders (folders are scanned recursively); the first new photo becomes active. `mode: "copy"` copies into `destination` (default: the library's Originals/), `mode: "move"` moves there (each original and its XMP sidecars are removed from the source only after the copy is verified and catalogued; duplicates and failures keep their sources; the result's `moved` / `kept` list what moved and what stayed, and why; undo leaves the moved files at the destination), filed by `organize`: `date` (YYYY/YYYY-MM-DD), `month`, `flat` or a folder template such as `{date:%Y}/{date:%Y%m%d}` (→ `2026/20260114`) or `{date:%Y}/{date:%B}` (→ `2026/January`; capture date, else the import date; always inside the destination), and named by the `rename` template (`run_command photo.renameTokens` lists the tags) | | `query_photos {filter?, sort?, offset?, limit?}` | Photos in the current view (or matching a catalog `Filter`) | | `select_photos {ids, active?, mode?}` | Set the selection / active photo. Every id (and `active`) must be in the library: an unknown id is a tool error (`no such photo 9999`) and the selection and active photo are left as they were | | `list_controls {section?}` | Every develop slider: id (`light.exposure`…), range, default, current value | @@ -316,10 +316,10 @@ lightcraft-cli calibrate --max 300 ~/Pictures/2026 # camera colour profiles (d ## Tests -- `crates/mcp/tests/e2e.rs` — M0.9 acceptance: over the stdio framing, set exposure and render; +- `crates/mcp/tests/it/e2e.rs` — M0.9 acceptance: over the stdio framing, set exposure and render; checks the decoded PNG gets brighter/darker. Runs headless and through the TCP transport (`Remote`) against a stand-in control server; also import → render → JPEG export of a real file. -- `apps/lightcraft-cli/tests/cli.rs` — spawns `lightcraft-cli mcp` with real pipes; `render`; +- `apps/lightcraft-cli/tests/it/cli.rs` — spawns `lightcraft-cli mcp` with real pipes; `render`; `commands`. ## Add to Apple Photos (macOS) diff --git a/docs/merge.md b/docs/merge.md index ce9c71bebf..e2183583a5 100644 --- a/docs/merge.md +++ b/docs/merge.md @@ -8,7 +8,8 @@ All algorithms are our own implementations from published papers (cited in the m - **App:** select the photos, then *Photo Merge ▸ HDR…* (`Ctrl+H`), *Panorama…* (`Ctrl+M`) or *HDR Panorama…* from the photo context menu (or the `dialog.merge*` commands). The dialog previews - the merge at ≤ 1024 px and re-runs the preview when an option changes; *Merge* runs the full merge + the merge at ≤ 1024 px and re-runs the preview when an option changes; as in Lightroom, a click on the preview + zooms in on that point (drag to pan, click again to fit), and it stays there while options change; *Merge* runs the full merge in the background (a row in the activity stack shows its progress, with ✕ to stop it). The result is written next to the first photo as `<name>-HDR.dng`, `-Pano.dng` or `-HDR-Pano.dng`, imported and selected. *Photo Merge ▸ HDR for Each Bracket Set* merges many brackets in one go with the last HDR options: one HDR per stack among the selected photos, then per diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 99f17561e3..080680b9ff 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -33,7 +33,7 @@ cited here still exists. Formerly docs/parity.md. | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | | F. Edit panel — global adjustments (EDIT) | 44 | 2 | 3 | 1 | 28/28 (100%) | 13/14 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | -| H. Crop & rotate (CROP) | 11 | 0 | 0 | 1 | 8/8 (100%) | 3/3 (100%) | +| H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | | J. Red eye (EYE) | 2 | 0 | 0 | 0 | — | 1/1 (100%) | | K. Masking (MASK) | 15 | 5 | 5 | 0 | 7/8 (88%) | 7/7 (100%) | @@ -44,7 +44,7 @@ cited here still exists. Formerly docs/parity.md. | P. Enhance (ENH) | 0 | 0 | 2 | 0 | — | — | | Q. HDR (HDR) | 2 | 3 | 0 | 0 | — | — | | R. Video (VID) | 0 | 0 | 5 | 1 | — | 0/2 (0%) | -| S. Export (EXP) | 15 | 4 | 0 | 0 | 7/7 (100%) | 7/7 (100%) | +| S. Export (EXP) | 14 | 5 | 0 | 0 | 7/7 (100%) | 6/7 (86%) | | T. Share (SHARE) | 0 | 0 | 0 | 4 | — | — | | U. Map & location (MAP) | 0 | 1 | 1 | 0 | — | 0/1 (0%) | | V. Preferences (PREF) | 6 | 2 | 2 | 2 | 1/1 (100%) | 4/5 (80%) | @@ -52,10 +52,10 @@ cited here still exists. Formerly docs/parity.md. | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | -| Lightroom Classic extras | 40 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 422 | 63 | 57 | 35 | 196/203 (97%) | 148/161 (92%) | +| Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | +| **Total** | 421 | 65 | 57 | 35 | 196/203 (97%) | 146/161 (91%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.7%** of 542 in-scope rows — P0 98.3% of 203 · P1 95.0% of 161 · P2 56.5% of 177. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.5%** of 543 in-scope rows — P0 98.3% of 203 · P1 94.4% of 161 · P2 56.7% of 178. <!-- /parity:summary --> ## Top gaps and shortcut notes @@ -70,7 +70,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/album_picker.rs`, `crates/ui-egui/src/tests_album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests_import.rs`) | -| LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → `cmd:library.import`) | dropping onto a specific album not supported | +| LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests_drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported | | LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests_import.rs` | | | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/import.rs`) | | LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/panels/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s | @@ -80,8 +80,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant | -| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `crates/raw/tests/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | +| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | | LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), and mid-sized NEF / RW2 JPEGs; a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests_import_move.rs`, `crates/ui-egui/src/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | @@ -96,11 +96,11 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters | | LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests_albums_local.rs`, `crates/ui-egui/src/tests_panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:<id>`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder) | | LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests_panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:<id>`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | -| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; sidebar counts are cached per catalog revision (and per minute while an “in the last…” rule is used), counted without building id lists; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort | +| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | | LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service | | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | -| LR-LIB-RATING | Star ratings | P0 | ✅ | `cmd:photo.rate` (`advance`), `cmd:photo.decreaseRating`, `cmd:photo.increaseRating`, `crates/ui-egui/src/shortcuts.rs` | 0 clears; 1–5 set; Shift+0–5 applies and advances once, including with Auto Advance. Default grid brackets adjust each photo by one, clamped to 0–5; one batch undo and AutoWrite. Batch grid and undo/redo regressions; macOS native ownership corrected (PR #261) | +| LR-LIB-RATING | Star ratings | P0 | ✅ | `cmd:photo.rate` (`advance`), `cmd:photo.decreaseRating`, `cmd:photo.increaseRating`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/rating.rs` | one shared star row in the bottom bar, Info panel and filter bar (hover previews, ←/→ on a focused star) and one painter for badges (grid cells, filmstrip, Compare caption); menu rows with star text (Photo ▸ Set Rating, Select By Rating, the grid context menu) are separate menu items, unchanged; 0 clears; 1–5 set; Shift+0–5 applies and advances once, including with Auto Advance. A rating, flag or label that takes the active photo out of the view (filter bar, Picks, smart album) makes the photo after it active (the one before at the end), and Shift / Auto Advance doesn't step past it (#2312). Default grid brackets adjust each photo by one, clamped to 0–5; one batch undo and AutoWrite. Batch grid and undo/redo regressions; macOS native ownership corrected (PR #261) | | LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag` | P pick, X reject, U clear; Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | | LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, label dot plus translucent colour on square-grid/filmstrip surrounds and photo-grid footers (photo pixels unchanged); colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), no custom extra labels | | LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; keywords reorganize by drag and drop in the Keyword List (LRC-LIB-KEYWORDS) | @@ -111,10 +111,10 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-REMOVE-ALBUM | Remove from album | P0 | ✅ | `cmd:album.removePhotos`, `crates/engine/src/tests_album_remove.rs`, `crates/ui-egui/src/tests_album_remove.rs` | changes the album only: the photos stay in the library, their library folder and their folder on disk (issue #1805); `id` defaults to the album on screen; returns `{removed, album}`. In a normal album ⌫ removes from the album (as in Lightroom; no confirmation, one undo step), in a smart album it changes nothing and says to edit its rules | | LR-LIB-DUPLICATE | Duplicate a photo | P2 | ✅ | `cmd:photo.duplicate` | Photo ▸ Duplicate: a real `-copy` file with the same settings, metadata and albums (virtual copies share the file) | | LR-LIB-RENAME | Batch rename | P1 | ✅ | `cmd:photo.rename`, `cmd:photo.renamePreview`, `cmd:photo.renameTokens`, `cmd:dialog.rename`, `crates/engine/src/rename.rs` (`TOKENS`) | template tokens {name} {num} {seq:N} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext} (shared with export naming and import rename); a Tags picker beside every template field (Rename Photos, import Rename, export File name) lists each tag with meaning + live example, the date directives and the rules, and inserts the clicked tag at the text cursor; unknown tags are flagged; preview; renames files on disk with their XMP sidecars (a stem sidecar another file still shares, e.g. raw + JPEG, is copied rather than taken), never overwriting (-1, -2… suffixes; a change of letter case only is checked by file identity, so on case-sensitive volumes `img_1.jpg` next to `IMG_1.JPG` is a collision), rolls back on failure (a file that can't be moved back is reported old → new and the library follows it as an undoable partial rename; the same for undo/redo); undo/redo move the files; virtual copies follow | -| LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. | +| LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. A capture time that doesn't fully read (cut short, or text after it) is left as it is and counted (`unreadable`); it can't anchor a set that moves other photos, and set alone repairs it. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s) with the sharpest marked; reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked; reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs` | “Copy N” badge, stacked with the original, same albums, no XMP writes; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -129,17 +129,17 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-VIEW-EDIT | Edit view | P0 | ✅ | `cmd:panel.edit` | | | LR-VIEW-FULLSCREEN | Full-screen preview | P1 | ✅ | `cmd:view.fullScreenPreview`, `cmd:view.enterFullScreen` | photo on black, arrows step, Esc exits; ⇧⌘F window full screen | | LR-VIEW-FILMSTRIP | Filmstrip | P0 | ✅ | `cmd:view.filmstrip`, `crates/ui-egui/src/panels/detail.rs` | the photo context menu on right-click; the mouse wheel scrolls it sideways, a third of its width per notch as in Lightroom Classic (trackpads scroll the points they report); it follows the active photo only when that changes (centred if off screen), so a scrolled strip stays put; every selected photo is highlighted, the active one framed in white, as in the grid | -| LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with soft proofing or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. Handing GPU renders to egui without a CPU readback is #1228. A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays that need whole-frame context (Visualize Spots, Point Color range, HDR range) and photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look or showing a diagnostic overlay, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the browser): the window grows to hold the spot and its source patch, or the dabs near it, and if that would take more (a clone from far away at 8:1) the loupe keeps the whole-frame render instead, and spots with an automatic source pick it from a fixed-size render of the whole frame (so a window's choice can differ from a whole-frame render's, which picks at its own resolution). The wide stages (dehaze, clarity, highlights/shadows base) and Refine Edges on masks read a window margin capped at 768 px; measured on hard-edged blocks that costs at most a few levels at 8:1. the histogram and Navigator come from the whole-frame render. Compare and Reference get the same windows, one per pane (`Slot::CompareRegion`, `panels/compare.rs`), over each pane's whole-frame render (at most 2560 px); while either view is open two originals stay decoded (`MediaCache::set_full_capacity`), so one pane's window does not evict the other's source; a pinch, or a slider drag on the active photo in Reference, keeps the windows there are until it ends. Mask overlays and soft proofing get the same windows (the window carries the overlay or the proof; the proof renders on the CPU, so a tick at 100 % on a 1400 × 900 canvas takes about 36 ms instead of a full-size 24 MP proof). Verified: a 1:1 window of a 24 MP photo with tone and colour edits is the full-size export to within one level (`one_to_one_window_pixels_are_export_pixels`). Measured on Linux (Ryzen AI Max+ 395, Radeon 8060S, GPU, `profile_slider_drag`): median tick→shown 7 ms at fit, 33 ms at 100 % and 6 ms at 400 % on 1400 × 900; 21 ms at 100 % and 9 ms at 400 % on 2800 × 1700; 36 ms at 100 % with soft proof. Not windowed: the diagnostic overlays named above | -| LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus_read.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests_focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests_focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Show Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only | +| LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with an output-device profile proof or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. Handing GPU renders to egui without a CPU readback is #1228. A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays (Visualize Spots, Point Color range, HDR range) get windows too, tested equal to the whole-frame render's pixels. Photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the browser): the window grows to hold the spot and its source patch, or the dabs near it, and if that would take more (a clone from far away at 8:1) the loupe keeps the whole-frame render instead, and spots with an automatic source pick it from a fixed-size render of the whole frame (so a window's choice can differ from a whole-frame render's, which picks at its own resolution). The wide stages (dehaze, clarity, highlights/shadows base) and Refine Edges on masks read a window margin capped at 768 px; measured on hard-edged blocks that costs at most a few levels at 8:1. the histogram and Navigator come from the whole-frame render. Compare and Reference get the same windows, one per pane (`Slot::CompareRegion`, `panels/compare.rs`), over each pane's whole-frame render (at most 2560 px); while either view is open two originals stay decoded (`MediaCache::set_full_capacity`), so one pane's window does not evict the other's source; a pinch, or a slider drag on the active photo in Reference, keeps the windows there are until it ends. Mask overlays and soft proofing get the same windows (the window carries the overlay or the proof; only an output-device-profile proof renders on the CPU, where a tick at 100 % on a 1400 × 900 canvas takes about 36 ms instead of a full-size 24 MP proof). Verified: a 1:1 window of a 24 MP photo with tone and colour edits is the full-size export to within one level (`one_to_one_window_pixels_are_export_pixels`). Measured on Linux (Ryzen AI Max+ 395, Radeon 8060S, GPU, `profile_slider_drag`): median tick→shown 7 ms at fit, 33 ms at 100 % and 6 ms at 400 % on 1400 × 900; 21 ms at 100 % and 9 ms at 400 % on 2800 × 1700; 36 ms at 100 % with an output-device-profile soft proof (the CPU path) | +| LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus_read.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests_focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests_focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only | | LR-VIEW-NAVIGATOR | Navigator mini map | P1 | ✅ | `cmd:view.navigator`, `crates/ui-egui/src/panels/detail.rs` | shown while zoomed (bottom right); click/drag pans | | LR-VIEW-BEFOREAFTER | Before / after | P0 | ✅ | `cmd:view.showOriginal`, `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom`, `cmd:beforeAfter.setBefore`, `cmd:beforeAfter.copyAfterToBefore`, `cmd:beforeAfter.copyBeforeToAfter`, `cmd:beforeAfter.swap`, `cmd:beforeAfter.resetBefore` | all four layouts; before = the import state (defaults + import preset) or a chosen history step / version / the current settings; copy and swap (View → Before/After Settings, History row menu). The chosen before lasts for the session; in side by side and top / bottom, clicks with the white-balance selector, colour samplers and targeted adjustment work in the Before view too (`crates/ui-egui/src/tests_before_after.rs`). Zoomed in, the side by side and stacked views each stay in their pane, with their labels under it. Click zoom animates both panes together, including cached window tiles; input follows the displayed image and render requests use the final size (#1821) | | LR-VIEW-COMPARE | Compare two photos | P1 | ✅ | `cmd:view.compare`, `cmd:compare.swap`, `cmd:compare.makeSelect`, `cmd:compare.set`, `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests_compare.rs` | select / candidate, synced zoom + pan, arrows move the candidate; a filmstrip click puts the photo into the active side (a photo on the other side swaps), so the active photo is always one of the two shown; a ⌘/Ctrl- or Shift-click on the filmstrip changes the selection as in the grid while the two photos shown stay selected and the active photo is unchanged (#187); 1:1 to 8:1 sharp on both sides (zoom windows, see LR-VIEW-ZOOM); no zoom-link toggle; each pane says “Rendering…” (widget `compare:rendering:<pane>`) or “This photo can't be opened” (`compare:renderFailed:<pane>`) as the loupe does | | LR-VIEW-SURVEY | Survey view [Classic] | P2 | ✅ | `cmd:view.survey`, `crates/ui-egui/src/panels/compare.rs` | selection tiled (≤ 48), keys, the bottom bar and the Info panel's stars and colour labels act on the active photo, each tile's caption shows its colour label, hover × removes | -| LR-VIEW-INFOOVERLAY | Info overlay on the photo | P1 | ✅ | `cmd:view.infoOverlay`, `cmd:view.viewOptions` | off / Info 1 (by default file name, capture date, size) / Info 2 (file name, exposure, camera + lens), each three lines chosen in View Options; ⌘I cycles (I in full screen; elsewhere I stays the Info panel) | +| LR-VIEW-INFOOVERLAY | Info overlay on the photo | P1 | ✅ | `cmd:view.infoOverlay`, `cmd:view.viewOptions`, `crates/ui-egui/src/panels/detail.rs` (`info_overlay`) | off / Info 1 (by default file name, capture date, size) / Info 2 (file name, exposure, camera + lens), each three lines chosen in View Options; ⌘I cycles (I in full screen; elsewhere I stays the Info panel); the star rating and flag show under the lines when the photo has them, and in the full-screen preview on macOS the overlay starts below the window controls (issue #2460) | | LR-VIEW-SLIDESHOW | Slideshow | P2 | ✅ | `cmd:view.slideshow` | View ▸ Slideshow (⌥⌘↩): the photos in view full screen from the selected one, played with the library's playback settings (see LRC-SS-PLAYBACK: fades, random order, repeat, previews prepared ahead; `interval` / any setting overrides one run); Space pauses, ←/→ step (a cut), Esc ends; playback controls on pointer movement | | LR-VIEW-SECONDWINDOW | Second display window [Classic] | P2 | ✅ | `cmd:view.secondWindow`, `crates/ui-egui/src/panels/second.rs` | Window ▸ Second Window (⌘F11): the active photo fitted in its own native window with its own render (a floating panel where there are no native windows); loupe view only (no grid / compare / survey there) | | LR-VIEW-CLIPPING | Clipping indicators | P0 | ✅ | `cmd:view.clipping` | | -| LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; no drag-to-adjust on the histogram; it follows slider drags live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag | +| LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; the plot's five tonal zones also drag to adjust their Basic control (LRC-DEV-HISTOGRAM-DRAG); it follows slider drags live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag | | LR-VIEW-HDR-DISPLAY | HDR display output | P2 | ⬜ | |, `apps/lightcraft/src/hdr_display.rs` (`choose`, `preferred_hdr_format`) | SDR/HDR decision (platform, surface format, OS headroom, `LIGHTCRAFT_HDR_DISPLAY=0`) is unit-tested and logged at start; always SDR today because eframe configures an 8-bit surface; no OS headroom query yet; | ## D. Search & filter (FILT) @@ -164,12 +164,12 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-META-INFO | Info panel | P0 | ✅ | `cmd:panel.info`, `cmd:photo.setMeta`, `crates/ui-egui/src/panels/right.rs` (`info`, `camera_card`) | camera card (camera, lens, size, format, focal length / shutter / aperture / ISO); title, caption, alt text, extended description, copyright, copyright status, rights usage terms, copyright info URL, creator; file name (rename), file path (reveal), capture time (edit); location, city, state, country; GPS. No flash, map snippet or people; a raw with no lens name (Nikon DSLRs) shows its range from Exif LensSpecification or the Nikon maker note's Lens tag, written like Lightroom's `24.0-70.0 mm f/2.8` | +| LR-META-INFO | Info panel | P0 | ✅ | `cmd:panel.info`, `cmd:photo.setMeta`, `cmd:view.infoSelectedPhotos`, `crates/ui-egui/src/panels/right.rs` (`info`, `camera_card`, `mixed_meta`) | camera card (camera, lens, size, format, focal length / shutter / aperture / ISO); title, caption, alt text, extended description, copyright, copyright status, rights usage terms, copyright info URL, creator; file name (rename), file path (reveal), capture time (edit); location, city, state, country; GPS. With several photos selected, Show Metadata For picks Selected Photos (the default: the values they share; a text field or GPS where they differ is empty and says Mixed, Copyright Status shows Mixed, and only what is typed or picked there is saved, to every selected photo) or Target Photo (the active photo's values; an edit goes to that photo alone). No flash, map snippet or people; a raw with no lens name (Nikon DSLRs) shows its range from Exif LensSpecification or the Nikon maker note's Lens tag, written like Lightroom's `24.0-70.0 mm f/2.8` | | LR-META-COPYRIGHT-DEFAULT | Default copyright on import | P1 | ✅ | `cmd:library.preferences` (`import.copyright`, `import.creator`), `crates/ui-egui/src/panels/settings.rs` | Settings → Import → Metadata; fills only photos without their own | | LR-META-LOCATION | Location editing | P2 | 🟡 | `cmd:photo.setMeta` (`location`, `city`, `state`, `country`, `gps`), `cmd:metadata.reverseGeocode` | place fields and GPS (decimal or degrees / minutes / seconds) edited in Info, read/written as IPTC Core / Photoshop / EXIF XMP; Show on Map opens OpenStreetMap; Fill Location fills empty City / State / Country from GPS offline (GeoNames, downloaded on request: `cmd:metadata.downloadPlaceNames`); no embedded map | | LR-META-COPYPASTE | Copy / paste metadata | P2 | ✅ | `cmd:photo.copyMetadata`, `cmd:photo.pasteMetadata` | title, caption, alt text, extended description, copyright (notice, status, usage terms, info URL), creator, place fields, keywords; `fields` picks a subset | -| LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | manual rereading also reads sidecar-free JPEG embedded XMP (first complete standard APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; no extended assembly or between-scan packets, not strict whole-JPEG validation; reader cases in `crates/engine/src/sidecar.rs`); a discovered unreadable sidecar fails without embedded fallback; procedural refresh/undo, non-UTF-8 sidecar and two explicit malformed fixtures in `crates/engine/src/tests_xmp.rs` (file-write checks use auto-write off); sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; saving merges into an existing sidecar (`crates/meta/src/xmp_merge.rs`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte, an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`<file>.xmp` for all but the raw; an import ranks the files it is adding the same way, so a TIFF or JPEG arriving beside its raw reads its own `<file>.xmp` and never the raw's `IMG_0001.xmp`, issue #1905); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); radial masks (`Mask/CircularGradient`) keep Lightroom's inside / outside: `crs:Flipped="true"` is the effect-inside flag of current masks and of the legacy Radial Filter, `crs:MaskInverted` the inversion, checked against Lightroom Classic's renders (issue #1815); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934); settings Lightroom writes only for itself (`CompatibleVersion`, the profile digests, the lens profile's name / file / setup, `CropConstrainToUnitSquare`, the lens profile's strength at 100 %) are not reported as unimported (`crates/engine/src/crs.rs`) | -| LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | `photo.allMetadata` reuses loaded original bytes for embedded XMP and keeps sidecar precedence (`crates/engine/src/tests_xmp.rs`); read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; metadata presets | +| LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | manual rereading also reads sidecar-free JPEG embedded XMP (first complete standard APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; no extended assembly or between-scan packets, not strict whole-JPEG validation; reader cases in `crates/engine/src/sidecar.rs`); a discovered unreadable sidecar fails without embedded fallback; procedural refresh/undo, non-UTF-8 sidecar and two explicit malformed fixtures in `crates/engine/src/tests_xmp.rs` (file-write checks use auto-write off); sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; saving merges into an existing sidecar (`crates/meta/src/xmp_merge.rs`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte (ownership follows namespace URI: foreign namespaces using `lc:` or `xmp:` cannot supply native settings or ratings and survive saving), an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`<file>.xmp` for all but the raw; an import ranks the files it is adding the same way, so a TIFF or JPEG arriving beside its raw reads its own `<file>.xmp` and never the raw's `IMG_0001.xmp`, issue #1905); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); radial masks (`Mask/CircularGradient`) keep Lightroom's inside / outside: `crs:Flipped="true"` is the effect-inside flag of current masks and of the legacy Radial Filter, `crs:MaskInverted` the inversion, checked against Lightroom Classic's renders (issue #1815); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934); settings Lightroom writes only for itself (`CompatibleVersion`, the profile digests, the lens profile's name / file / setup, `CropConstrainToUnitSquare`, the lens profile's strength at 100 %) are not reported as unimported (`crates/engine/src/crs.rs`) | +| LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | `photo.allMetadata` reuses loaded original bytes for embedded XMP and keeps sidecar precedence (`crates/engine/src/tests_xmp.rs`); read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; PSD/PSB EXIF resource 1058 and XMP resource 1060 feed the same metadata rows and preserve sidecar precedence; metadata presets | ## F. Edit panel — global adjustments (EDIT) @@ -184,7 +184,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632) | | LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites` | | | LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks` | | -| LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*` | | +| LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*`, `crates/pipeline/src/curve.rs` | the graph draws the renderer's own curve model; dragging the line moves the region under the pointer (one undo step) | | LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag; ⌥-drag moves it a tenth as far for fine adjustment, issue #1363); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON | | LR-EDIT-LIGHT-CURVE-RGB | Per-channel curves | P0 | ✅ | `cmd:develop.curve` (`channel`) | | | LR-EDIT-LIGHT-CURVE-REFINESAT | Curve saturation compensation | P1 | ✅ | `ctl:curve.refineSaturation` | | @@ -198,7 +198,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-COLOR-MIXER-HSL | 8-band colour mixer | P0 | ✅ | `ctl:mixer.*` | no targeted (drag-on-image) mode | | LR-EDIT-COLOR-MIXER-BW | B&W mix | P1 | ✅ | `ctl:bw.*`, `cmd:develop.autoBwMix` | eight bands; Auto pushes each hue band's colourful pixels away from the mean lightness (own rule) | | LR-EDIT-COLOR-POINTCOLOR | Point colour | P1 | ✅ | `cmd:pointColor.pick`, `cmd:pointColor.delete` | | -| LR-EDIT-COLOR-GRADING | Colour grading wheels | P0 | ✅ | `ctl:grading.*`, `crates/ui-egui/src/panels/edit.rs` (`grading`) | 3-Way / Shadows / Midtones / Highlights tabs; a range tab shows one large wheel with Hue, Saturation and Luminance sliders; Blending and Balance in every tab; 3-Way shows the hovered wheel's hue and saturation; every wheel marks its neutral centre; wheel modifiers as in Lightroom: Shift-drag keeps the puck's hue and changes saturation only (the spoke is the guide; a puck at the centre has no hue, so it takes the angle where the pointer pressed), Cmd/Ctrl-drag keeps the saturation and changes hue only (the circle is the guide), Alt/Option-drag fine-adjusts at 0.1x and combines with either lock, and a hover tooltip lists them (issues #559, #1160; tests `shift_dragging_across_the_tangent_keeps_the_hue_and_moves_saturation`, `shift_drag_keeps_the_pucks_hue_wherever_the_pointer_grabs`, `cmd_drag_keeps_the_saturation_and_changes_only_the_hue`, `alt_drag_fine_adjusts_to_a_tenth_of_the_pointers_travel`, `alt_works_with_shift_and_cmd_constraints` in `crates/ui-egui/src/tests_grading.rs`); the large wheel adds 25/50/75 % saturation rings (issue #559); each wheel's eye hides its effect for viewing only (`RenderJob::with_hidden_grading`, not saved, export unaffected) (issue #737). No Global wheel tab yet | +| LR-EDIT-COLOR-GRADING | Colour grading wheels | P0 | ✅ | `ctl:grading.*`, `crates/ui-egui/src/panels/edit.rs` (`grading`) | 3-Way / Shadows / Midtones / Highlights tabs; a range tab shows one large wheel with Hue, Saturation and Luminance sliders; Blending and Balance in every tab; 3-Way shows the hovered wheel's hue and saturation; every wheel marks its neutral centre; wheel modifiers as in Lightroom: Shift-drag keeps the puck's hue and changes saturation only (the spoke is the guide; a puck at the centre has no hue, so it takes the angle where the pointer pressed), Cmd/Ctrl-drag keeps the saturation and changes hue only (the circle is the guide), Alt/Option-drag fine-adjusts at 0.1x and combines with either lock, and a hover tooltip lists them (issues #559, #1160; tests `shift_dragging_across_the_tangent_keeps_the_hue_and_moves_saturation`, `shift_drag_keeps_the_pucks_hue_wherever_the_pointer_grabs`, `cmd_drag_keeps_the_saturation_and_changes_only_the_hue`, `alt_drag_fine_adjusts_to_a_tenth_of_the_pointers_travel`, `alt_works_with_shift_and_cmd_constraints` in `crates/ui-egui/src/tests_grading.rs`); a wheel drag holds the pointer as in Lightroom: hidden while dragging (the puck follows the mouse's travel; on macOS the pointer is locked in place), back where the button went down on release, and given back at once on Esc, a lost window focus or a wheel that goes away mid-drag; the browser can't move the pointer, so there it only shows again where the drag ended (issue #1899; tests `a_held_wheel_follows_the_mouses_motion_not_where_the_pointer_sits`, `a_wheel_drag_hides_the_pointer_and_releasing_puts_it_back_where_it_was_pressed`, `escape_or_losing_focus_gives_the_pointer_back_mid_drag`, `a_wheel_that_goes_away_mid_drag_gives_the_pointer_back`); the large wheel adds 25/50/75 % saturation rings (issue #559); each wheel's eye hides its effect for viewing only (`RenderJob::with_hidden_grading`, not saved, export unaffected) (issue #737). No Global wheel tab yet | | LR-EDIT-EFFECTS-TEXTURE | Texture | P0 | ✅ | `ctl:effects.texture` | | | LR-EDIT-EFFECTS-CLARITY | Clarity | P0 | ✅ | `ctl:effects.clarity` | | | LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | ✅ | `ctl:effects.dehaze` | | @@ -248,9 +248,9 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-CROP-RECT | Crop rectangle | P0 | ✅ | `cmd:crop.set`, `cmd:crop.drag`, `crates/geom/src/crop_drag.rs`, `crates/ui-egui/src/panels/detail.rs` | double-click inside the box applies the crop (like Return); on a straightened photo a moved box slides along the tilted edges to where the pointer asks, so a box that fills the photo's height still reaches its sides (issue #2299) | -| LR-CROP-ASPECT | Aspect ratios | P0 | ✅ | `cmd:crop.aspect`, `cmd:crop.rotateAspect`, `crates/ui-egui/src/panels/right.rs` | menu with presets + custom W × H (a preset takes the crop's orientation, portrait after X; a custom ratio is used as entered, issue #2253), visible Lock toggle (also A), button names the active ratio; every handle honours the lock, holding Shift while dragging a handle keeps the frame's proportions for that drag (issue #614), and the drag stops at the image edge instead of shifting the frame (issue #295); "Original" is the photo's own shape (no separate As Shot); the last chosen aspect is saved as a crop tool default, resolving Original per photo and preserving existing crops; opening Crop or browsing never edits a photo: the default applies only when a crop gesture starts, within its single undo step; a crop starts locked to the photo's own shape until the Lock is switched off once, then as last set (#991) | +| LR-CROP-ASPECT | Aspect ratios | P0 | ✅ | `cmd:crop.aspect`, `cmd:crop.rotateAspect`, `crates/ui-egui/src/panels/right.rs` | menu with presets + custom W × H (a preset takes the crop's orientation, portrait after X; a custom ratio is used as entered, issue #2253), visible Lock toggle (also A, its own row in Keyboard Shortcuts: `crop.lockAspect` toggles it, sharing A with Visualize Spots by context), button names the active ratio; every handle honours the lock, holding Shift while dragging a handle keeps the frame's proportions for that drag (issue #614), and the drag stops at the image edge instead of shifting the frame (issue #295); "Original" is the photo's own shape (no separate As Shot); the last chosen aspect is saved as a crop tool default, resolving Original per photo and preserving existing crops; opening Crop or browsing never edits a photo: the default applies only when a crop gesture starts, within its single undo step; a crop starts locked to the photo's own shape until the Lock is switched off once, then as last set (#991) | | LR-CROP-STRAIGHTEN | Straighten tool | P0 | ✅ | `cmd:crop.straighten`, `cmd:crop.autoStraighten`, `crates/ui-egui/src/panels/detail.rs` (`rotate_cursor`, `angle_readout`), `crates/ui-egui/src/panels/right.rs` (Angle field), `crates/ui-egui/src/tests_crop_rotate.rs` | Straighten Tool button: drag along a horizon/vertical; double-click or Auto levels automatically. Dragging outside the crop box rotates it: there the pointer is a curved double arrow that bulges away from the side of the box it is on, diagonally off a corner and following a rotated box (`rotate_cursor_turn`, tested by `rotate_cursor_faces_away_from_the_crop_box`) (with ⌘ held, the straighten crosshair), and while rotating the angle shows next to it, kept on the canvas (issue #534); an exact angle goes in the Angle field under Straighten (`cropAngleField`: applies on Return or leaving it, Esc keeps the old angle, takes a decimal comma; a drag on it is one undo step) or by clicking the Straighten value (its hover says so). Every way of setting the angle (rotate handle, Straighten slider, Angle field, `crop.straighten`, `crop.set {angle}`, and the generic `develop.set` / `develop.adjust` / `develop.quickAdjust` / `develop.resetControl` on `crop.angle`, as MCP, the control channel and `lightcraft-cli render --set` use them) keeps the crop if it still fits, else shrinks it about its own centre, keeping its aspect, until it fits; the full photo (or a crop an earlier turn shrank to the largest of its aspect) stays the largest, so it grows back towards 0° (issue #1388), and no other crop ever grows (issue #1794: a crop dragged in from a corner turned into nearly the whole photo) (`CropGeometry::with_angle`, `crates/engine/src/tests_crop_angle.rs`; before issue #742 the generic path left the box, and the export, past the photo with smeared edge pixels in the corners). The dimming outside the box is the photo minus the (rotated) box, drawn as one mesh (`outside_crop_mesh`), so rotating never dims wedges inside the box or doubles them outside (issue #731) | -| LR-CROP-AUTO | Auto straighten | P1 | ✅ | `cmd:crop.autoStraighten` | crop-angle leveling from detected horizon/plumb lines (consensus required) | +| LR-CROP-AUTO | Auto straighten | P1 | 🟡 | `cmd:crop.autoStraighten` | crop-angle leveling from detected horizon/plumb lines (consensus required); turns by at most 10° (`STRAIGHTEN_MAX_DEGREES`) and only on at least 3 agreeing lines (`STRAIGHTEN_MIN_LINES`), and says so when it finds nothing (`auto_straighten_says_when_it_finds_nothing`). Measured on 68 photos straightened by hand in Lightroom Classic and 300 left as shot: it levels 14 of the 68 within 0.5° (1 more than 1° off) and turns 19 of the 300 by more than 1° (before the limits: 79, some by 20° or more). 🟡 because it still leaves most tilted photos alone: a soft sea horizon among wave crests, and verticals that converge in perspective, aren't used yet | | LR-CROP-ANGLE | Angle slider | P0 | ✅ | `ctl:crop.angle`, `crates/ui-egui/src/panels/right.rs` | the Straighten slider; an exact angle can also be typed in the Angle field under it (see LR-CROP-STRAIGHTEN); setting `crop.angle` through `develop.set` fits the crop inside the photo as Straighten does (issue #742) | | LR-GUIDED-SELECT | Guide selection in Guided Upright mode | P0 | ✅ | `cmd:tool.guidedUpright`, `cmd:geometry.guides`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/state.rs` (`selected_guide`), `crates/ui-egui/src/tests_guided_guides.rs` | a press near a guide's line selects it (`selected_guide = Some((photo id, index))`; another press on it deselects), a press on an empty spot starts a new guide at that point, and an endpoint drags to reshape the guide (`Gesture::GuideEndpoint`, one undo step; clicking an endpoint only selects); tested in `tests_guided_guides` 8/8 | | LR-GUIDED-DELETE | Delete removes the selected guide alone | P0 | ✅ | `cmd:photo.delete`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/tests_guided_guides.rs` | with the Guided Upright tool open (`RightPanel::Crop && tool == "guidedUpright"`), Delete / Backspace removes only the selected guide and clears the selection; with nothing selected it removes nothing (the photo itself is never deleted while the tool is open); tested in `tests_guided_guides` | @@ -321,7 +321,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-PRE-PANEL | Presets panel | P0 | ✅ | `cmd:panel.presets`, `cmd:preset.apply`, `crates/ui-egui/src/panels/presets.rs` | grouped list with amount; the preset applied to a photo stays marked on returning to it until the photo is edited further (issue #2392); resting on a preset previews it in the loupe (no history entry); optional live thumbnails (⋯ → Show Thumbnails) | | LR-PRE-CREATE | Create preset | P0 | ✅ | `cmd:dialog.createPreset`, `cmd:preset.create` (`groups`) | name, group and a checklist of settings groups (crop, masks, remove, red eye off by default; All / None) | -| LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move` | rename, update with current settings, move to a group (existing or new); no hiding of groups | +| LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move` | rename, update with current settings, move to a group (existing or new); starred presets are listed in a Favorites section on top, as in the Profile browser (issue #1999, `crates/ui-egui/src/tests_preset_favorites.rs`); no hiding of groups | | LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | | | LR-PRE-ADAPTIVE | Adaptive presets | P2 | ⬜ | | | | LR-PRE-PREMIUM | Built-in presets (own) | P2 | ✅ | `crates/engine/src/presets.rs` | 41 own-authored presets in 10 groups (Color, Film, B&W incl. toners, Portrait, Landscape, Urban, Food, Seasons, Vintage, Style) | @@ -352,7 +352,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-MERGE-HDR | HDR merge | P2 | 🟡 | `cmd:merge.hdr`, `cmd:dialog.mergeHdr`, `crates/merge/src/frame.rs` (`Frame::lens`), `crates/merge/src/hdr.rs` | auto align (Lanczos-3 warp), deghost None–High + overlay, auto settings, float DNG, Create Stack; the DNG keeps the reference frame's embedded lens corrections (tested by `hdr_merge_keeps_the_reference_frames_lens_corrections`); raws without colour matrices of their own (CR2, NEF, ARW…) keep the colour they open with, written as DNG tags (`starting_colour_tags`; the look's chroma curve has no tag; panoramas too), issue #965; the DNG's `AsShotNeutral` is the median of the inputs' vendor white-balance multipliers, issue #1144. Tested on real Sony A7R VI brackets (67 MP, 2026-10-14): frames agree with the merged radiance within ~1 % in all channels, exposure steps match EXIF within 0.03 EV. A clipped highlight of the reference that moved in other frames (a star at 200 mm) stays instead of becoming a black hole, and deghost (≤ 2048 px maps) catches a brighter frame's ghost in a dark sky (`a_clipped_star_of_the_reference_is_not_erased_by_frames_where_it_moved`, `deghost_removes_a_bright_frames_ghost_in_a_dark_sky`). 🟡 because: AI Denoise doesn't run on merged DNGs (Bayer only; Lightroom's does), JPEG brackets are treated as linear (no camera response curve), and every frame is held as 32-bit float (~0.86 GB per 67 MP frame, so 7 frames need ~7 GB); gap 29 | +| LR-MERGE-HDR | HDR merge | P2 | 🟡 | `cmd:merge.hdr`, `cmd:dialog.mergeHdr`, `crates/merge/src/frame.rs` (`Frame::lens`), `crates/merge/src/hdr.rs` | auto align (Lanczos-3 warp), deghost None–High + overlay, click-to-zoom preview (drag pans; the zoom stays while options change), auto settings, float DNG, Create Stack; the DNG keeps the reference frame's embedded lens corrections (tested by `hdr_merge_keeps_the_reference_frames_lens_corrections`); raws without colour matrices of their own (CR2, NEF, ARW…) keep the colour they open with, written as DNG tags (`starting_colour_tags`; the look's chroma curve has no tag; panoramas too), issue #965; the DNG's `AsShotNeutral` is the median of the inputs' vendor white-balance multipliers, issue #1144. Tested on real Sony A7R VI brackets (67 MP, 2026-10-14): frames agree with the merged radiance within ~1 % in all channels, exposure steps match EXIF within 0.03 EV. A clipped highlight of the reference that moved in other frames (a star at 200 mm) stays instead of becoming a black hole, and deghost (≤ 2048 px maps) catches a brighter frame's ghost in a dark sky (`a_clipped_star_of_the_reference_is_not_erased_by_frames_where_it_moved`, `deghost_removes_a_bright_frames_ghost_in_a_dark_sky`). 🟡 because: AI Denoise doesn't run on merged DNGs (Bayer only; Lightroom's does), JPEG brackets are treated as linear (no camera response curve), and every frame is held as 32-bit float (~0.86 GB per 67 MP frame, so 7 frames need ~7 GB); gap 29 | | LR-MERGE-PANO | Panorama | P2 | ✅ | `cmd:merge.panorama`, `cmd:dialog.mergePanorama` | spherical/cylindrical/perspective + auto (projected with Lanczos-3), boundary warp, auto crop, fill edges (diffusion), DNG whose `AsShotNeutral` is the median of its frames' as-shot white balance (vendor multipliers for CR2, NEF, ARW…), issue #1144; no lens model / 360° wrap | | LR-MERGE-HDRPANO | HDR panorama | P2 | ✅ | `cmd:merge.hdrPanorama`, `cmd:dialog.mergeHdrPanorama` | brackets grouped by EXIF | | LR-MERGE-HEADLESS | Merge with last settings | P2 | ✅ | `cmd:merge.hdrLast`, `cmd:merge.panoramaLast`, `cmd:merge.hdrPanoramaLast`, `cmd:merge.hdrBatch`, `crates/catalog/src/stacks.rs` (`bracket_sets`) | no dialog; the options of the last merge of that kind (defaults the first time), kept in the library's prefs.json so they survive a restart; the HDR / Panorama / HDR Panorama dialogs open with them too (`merge_dialog_remembers_the_last_settings_per_kind`). HDR for Each Bracket Set merges a batch like Lightroom's merge of stacks: one HDR per stack among the photos, then per bracket (photos taken less than a second apart, after the shutter time, at exposures ≥ ½ EV apart; bursts at one exposure are skipped), one after the other in the activity stack (cancelling one stops the rest; a failed set doesn't); CLI `merge hdr-batch FILES…` | @@ -392,22 +392,22 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EXP-DIALOG | Export dialog | P0 | ✅ | `cmd:dialog.export`, `cmd:app.export` (`preset`), `cmd:export.presets`, `cmd:export.savePreset`, `cmd:export.deletePreset`, `crates/ui-egui/src/panels/dialogs.rs`, `crates/engine/src/export.rs` | batch export; built-in presets (JPEG Small 2048 px / Large full size, Original + Settings, DNG) and saved user presets (library prefs) load into the dialog; deleting a user preset is command-only; on a short window the options scroll and Cancel / OK stay visible (LR-BEHAV-DIALOGS, issue #781) | | LR-EXP-TYPE | File types | P0 | ✅ | `cmd:app.export` (`format`), `crates/engine/src/export.rs` (`ExportFormat`), `crates/engine/src/tests_export.rs` | JPEG, PNG, TIFF, PSD (flat, 8/16-bit, no layers: `crates/codecs/src/psd.rs`), WebP, AVIF, JPEG XL (issue #247: `jixel`, native only; lossy with quality or lossless, 8/16-bit, effort fast/normal (jixel's slowest search left out: jxl-oxide misdecodes its files), progressive, EXIF/XMP boxes; lossy files in Adobe RGB / ProPhoto are written as Rec. 2020, lossless keep any space via ICC; `crates/codecs/src/jxl_encode.rs`), DNG (raw photos: lossless re-encode with the edits in the embedded XMP; a raw without colour matrices of its own, as a NEF, gets the colour it opens with as `ColorMatrix1` / `ForwardMatrix1` / `AsShotNeutral`, also in Convert / Copy as DNG, so other raw converters open it, issue #1745), Original (+ XMP sidecar). Non-raw → DNG not supported; no JPEG XL export in the web build. Opaque 8-bit PNG/TIFF/WebP exports omit the redundant alpha channel; real transparency is retained (#1670). | | LR-EXP-DIM | Output size | P0 | ✅ | `cmd:app.export` (`longEdge`, `shortEdge`, `width`, `height`, `fit`, `megapixels`, `percent`, `dontEnlarge`, `ppi`), `crates/engine/src/export.rs` (`Resize`), `crates/ui-egui/src/panels/dialogs.rs` | full size = the cropped native size (no longer upscaled); both of Lightroom's boxes: Dimensions (W × H fits either orientation) and Width & Height (`fit: widthHeight`, each edge bound to its own number, #1620); ppi written to JFIF / pHYs / TIFF tags; at most 65,535 px an edge, and an export enlarged past the photo's size stops at 512 megapixels (Lightroom's ceiling too) and is refused, with the size it would need, when it needs more memory than the computer has (it aborted the process before) | -| LR-EXP-QUALITY | JPEG quality | P0 | ✅ | `cmd:app.export` (`quality`, `limitKb`), `crates/codecs/src/jpeg_par.rs` | 4:4:4 chroma (4:2:0 when a file-size limit is set); Huffman tables made for each image from its own symbol counts (T.81 Annex K.2) instead of the example tables: the same pixels, 12–14 % smaller files at quality 80–100 on a 24 MP photo-like image, still interleaved baseline (issue #1373) | +| LR-EXP-QUALITY | JPEG quality | P0 | ✅ | `cmd:app.export` (`quality`, `limitKb`), `crates/codecs/src/jpeg_par.rs` | 4:4:4 chroma (4:2:0 when a file-size limit is set); Huffman tables made for each image from its own symbol counts (T.81 Annex K.2) instead of the example tables: the same pixels, 12–14 % smaller files at quality 80–100 on a 24 MP photo-like image, still interleaved baseline (issue #1373); ordinary and HDR gain map JPEGs search quality up to the requested maximum to fit `limitKb`, including gain map and metadata, or return an error. Tested by `size_limit_respected` and `hdr_jpeg_size_limit_respected`. | | LR-EXP-BITDEPTH | Bit depth | P1 | ✅ | `cmd:app.export` (`bitDepth`), `crates/pipeline/src/output.rs` (`OutputDepth`), `crates/engine/src/export.rs` | 16-bit PNG/TIFF/JPEG XL rendered at 16 bits (TIFF defaults to 16), 32-bit float linear TIFF with a linear profile, 10-bit AVIF; high-bit-depth renders run on the CPU | | LR-EXP-COMPRESSION | TIFF compression | P1 | ✅ | `cmd:app.export` (`tiffCompression`: none / lzw / zip) | | | LR-EXP-COLORSPACE | Output colour space | P0 | ✅ | `cmd:app.export` (`colorSpace`), `crates/pipeline/src/output.rs`, `crates/engine/src/export.rs` | sRGB, Display P3, Adobe RGB (1998) compatible, ProPhoto RGB, Rec. 2020: rendered from the working space with gamut mapping into the target gamut (CPU + GPU), own ICC profile embedded; AVIF stays sRGB (muxer has no ICC); lossy JPEG XL declares sRGB / P3 / Rec. 2020 (Adobe RGB and ProPhoto written as Rec. 2020), lossless JPEG XL embeds the profile | | LR-EXP-HDR | HDR output | P2 | 🟡 | `cmd:app.export`, `crates/ui-egui/src/panels/dialogs.rs` | HDR output checkbox in the export dialog: gain map JPEG, PQ or HLG AVIF, PQ PNG, PQ JPEG XL, float TIFF; no HDR presets yet | | LR-EXP-SHARPEN | Output sharpening | P1 | ✅ | `cmd:app.export` (`sharpen`, `sharpenAmount`) | | | LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | | -| LR-EXP-WATERMARK | Watermark | P1 | ✅ | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (`image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | +| LR-EXP-WATERMARK | Watermark | P1 | 🟡 | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text uses Inter SemiBold, the existing Mincho-first CJK chain, then Thai faces from `CRAFT_FONTS_DIR`, shared with contact-sheet captions and slideshow overlays (#2052, partial). Horizontal Thai mark positioning remains incomplete. Arabic export fallback is deferred until joining and bidi reordering exist; UI font fallback is unchanged. Text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (EXIF orientation applied before sizing; oversized graphics fit the rotated image bounds without stretching, tested by `graphic_watermark_honours_exif_orientation` and `graphic_watermark_keeps_aspect_when_fitted_and_rotated`; `image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | | LR-EXP-NAMING | File naming | P1 | ✅ | `cmd:app.export` (`naming`, `startNumber`), `crates/engine/src/rename.rs` (`expand_tokens`) | one template language for export, Rename Photos and import renaming: `{name}`, `{num}` (number at the end of the name), `{seq}` / `{seq:N}`, `{date}` / `{date:%Y-%m-%d}`, `{folder}`, `{camera}`, `{lens}`, `{iso}`, `{rating}`, `{title}`, `{creator}`, `{ext}`; free-form template rather than a list of named schemes | | LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `destinationMode`: specificFolder / sameAsOriginal, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/panels/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; Export to: Specific folder or Same folder as original photo (each photo into its original's folder + the subfolder; a demo/browser photo or a missing folder is that photo's error, issue #956); existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) | | LR-EXP-PREVIOUS | Export with previous settings | P0 | ✅ | `cmd:app.exportPrevious`, `cmd:dialog.export` | last options persist in prefs.json; dialog prefilled; no named export presets yet | -| LR-EXP-DNGOPT | DNG options | P2 | 🟡 | `cmd:app.export` (`dngCompression`), `crates/engine/src/export.rs` | compression: lossless JPEG (default), ZIP, none, or lossy (demosaiced linear camera RGB as 8-bit JPEG tiles at the export quality, a `LinearizationTable` restoring linear values, scaled to the resize long edge when set; `crates/raw/tests/lossy_dng.rs`); no embedded JPEG preview size | +| LR-EXP-DNGOPT | DNG options | P2 | 🟡 | `cmd:app.export` (`dngCompression`), `crates/engine/src/export.rs` | compression: lossless JPEG (default), ZIP, none, or lossy (demosaiced linear camera RGB as 8-bit JPEG tiles at the export quality, a `LinearizationTable` restoring linear values, scaled to the resize long edge when set; `crates/raw/tests/it/lossy_dng.rs`); no embedded JPEG preview size | | LR-EXP-ORIGINAL | Original + XMP | P1 | ✅ | `cmd:app.export` (`format: original`), `crates/engine/src/tests_export.rs` | file copied byte for byte, sidecar named after the output and subject to the conflict policy | -| LR-EXP-RENDERDNG | Render to DNG (Classic 15.5) | P2 | 🟡 | `cmd:app.export` (`format: rendereddng`), `crates/raw/src/dngwrite.rs` (`write_rendered_dng`), `crates/raw/tests/rendered_dng.rs` | export format `rendereddng` (dialog: Format DNG, "DNG of: Rendered photo"): the rendered photo (edit, crop, size, sharpening, watermark baked in) as a LinearRaw DNG of 16-bit float Deflate tiles in the export colour space, with `ColorMatrix1` / `ForwardMatrix1` for that space, a neutral `AsShotNeutral` and an identity `ProfileToneCurve` so raw converters show it as rendered; HDR edits keep highlights above white. Not a menu command on selected photos (Lightroom adds the DNG to the catalog next to the original); export only | +| LR-EXP-RENDERDNG | Render to DNG (Classic 15.5) | P2 | 🟡 | `cmd:app.export` (`format: rendereddng`), `crates/raw/src/dngwrite.rs` (`write_rendered_dng`), `crates/raw/tests/it/rendered_dng.rs` | export format `rendereddng` (dialog: Format DNG, "DNG of: Rendered photo"): the rendered photo (edit, crop, size, sharpening, watermark baked in) as a LinearRaw DNG of 16-bit float Deflate tiles in the export colour space, with `ColorMatrix1` / `ForwardMatrix1` for that space, a neutral `AsShotNeutral` and an identity `ProfileToneCurve` so raw converters show it as rendered; HDR edits keep highlights above white. Not a menu command on selected photos (Lightroom adds the DNG to the catalog next to the original); export only | | LR-EXP-PHOTOS | Export to the system photo library | P2 | 🟡 | `cmd:app.export` (`addToPhotos`, `photosAlbum`), `cmd:export.addToPhotos`, `cmd:export.photosImports`, `crates/engine/src/apple_photos.rs`, `crates/ui-egui/src/panels/dialogs.rs`, `packaging/macos/entitlements.plist`, `docs/apple-photos.md` | macOS: the exported files go to Apple Photos through Apple Events to its import command (a constant AppleScript run by `/usr/bin/osascript`; album names and paths are separate arguments), into a top-level album of exactly that name, made when missing (several of that name: refused); the Export dialog's Add to Apple Photos, Export with Previous, presets, MCP and `lightcraft-cli` all reach it; imports are jobs, off the UI thread in the desktop app and awaited in one-shot headless runs, one at a time, reserved by an export before it writes; permission, missing Photos, timeouts and partial imports are reported; the packaged app carries the Apple Events entitlement and usage text. Tested end to end with the packaged app on macOS 26.6.2 / Photos 11.0 (manual steps in `docs/apple-photos.md`). Other platforms' photo libraries are not covered | -| LR-EXP-PSD | Round trip to an external editor | P2 | ✅ | `cmd:photo.editExternal`, `cmd:photo.editInPhotoCraft`, `cmd:photo.editInExternal`, `cmd:photo.openOriginalInExternal`, `crates/engine/src/cmd/convert.rs`, `apps/lightcraft/src/editors.rs` | an `-Edit` copy of each selected photo (up to 50 at once, issue #920) with the edits (PSD or TIFF, 16- or 8-bit, Adobe RGB / ProPhoto / P3 / sRGB, chosen per editor in Settings ▸ General ▸ External Editing) next to the original, added stacked on top of it and opened in PhotoCraft (found where its installers put it; a PSD by default, which PhotoCraft saves back to in place) or the other editor set there (or the system default); also on the photo's right-click menu (Edit In). Re-read when LightCraft is focused again. Open Original in Other Editor (RAW, no copy) hands that editor each selected photo's original file itself instead (a raw stays a raw, e.g. for DxO PhotoLab: no render, no copy, nothing added; several photos go to one start of the editor, which DxO PhotoLab 8 needs to get them all; demo photos, missing files and originals that are not a file type LightCraft reads are skipped with the reason, so a path an imported catalog named cannot hand a program to the system opener, issue #2135). No "Edit a copy / Edit original" choice for non-raw files yet | +| LR-EXP-PSD | Round trip to an external editor | P2 | ✅ | `cmd:photo.editExternal`, `cmd:photo.editInPhotoCraft`, `cmd:photo.editInExternal`, `cmd:photo.openOriginalInExternal`, `crates/engine/src/cmd/convert.rs`, `apps/lightcraft/src/editors.rs` | an `-Edit` copy of each selected photo (up to 50 at once, issue #920) with the edits (PSD or TIFF, 16- or 8-bit, Adobe RGB / ProPhoto / P3 / sRGB, chosen per editor in Settings ▸ General ▸ External Editing) next to the original, added stacked on top of it and opened in PhotoCraft (found where its installers put it; a PSD by default, which PhotoCraft saves back to in place) or the other editor set there (or the system default); also on the photo's right-click menu (Edit In). Re-read when LightCraft is focused again. Open Original in Other Editor (RAW, no copy) hands that editor each selected photo's original file itself instead (a raw stays a raw, e.g. for DxO PhotoLab: no render, no copy, nothing added; several photos go to one start of the editor, which DxO PhotoLab 8 needs to get them all; demo photos, missing files and originals that are not a file type LightCraft reads are skipped with the reason, so a path an imported catalog named cannot hand a program to the system opener, issue #2135). Imported PSD/PSB photos retain embedded capture dates; PSD edit copies retain EXIF/XMP fields in the catalog and All Metadata. Original with Remove Location Info is refused when embedded PSD/PSB GPS is detected. No "Edit a copy / Edit original" choice for non-raw files yet | ## T. Share (SHARE) @@ -429,7 +429,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-PREF-GENERAL | General settings | P0 | ✅ | `cmd:app.settings`, `cmd:app.openLibrary`, `crates/ui-egui/src/panels/settings.rs`, `crates/ui-egui/src/panels/notices.rs` | General / Import / Performance / Display / Interface tabs; app settings in ui.json (written atomically, saved when the library changes and every few seconds), library settings in prefs.json; a damaged settings file is kept as `.corrupt-<time>` and reported, an unreadable one is not overwritten that session (`library.info` → `settingsWarnings`); quitting with unsaved changes retries, then asks | +| LR-PREF-GENERAL | General settings | P0 | ✅ | `cmd:app.settings`, `cmd:app.openLibrary`, `crates/ui-egui/src/panels/settings.rs`, `crates/ui-egui/src/panels/notices.rs` | General / Import / Performance / Display / Interface tabs; app settings in ui.json (written atomically, saved when the library changes and every few seconds), library settings in prefs.json; At launch: open the last library or ask (see LRC-LIB-CATALOG-SWITCH); a damaged settings file is kept as `.corrupt-<time>` and reported, an unreadable one is not overwritten that session (`library.info` → `settingsWarnings`); quitting with unsaved changes retries, then asks | | LR-PREF-LOCALSTORAGE | Storage & cache | P1 | ✅ | `cmd:library.preferences`, `cmd:library.clearPreviews`, `cmd:library.compact` | thumbnail cache size + clear in Settings → Performance; library location + Open Library… in General | | LR-PREF-ACCOUNT | Account | OOS | 🚫 | | | | LR-PREF-INTERFACE | Interface options | P1 | ✅ | `cmd:app.settings`, `cmd:view.appearance`, `cmd:view.theme` | Appearance Mode (Sync with System / Dark / Light; the top bar button cycles Auto, Light, Dark) with separate dark (Charcoal, Midnight) and light (Silver, Paper) themes previewed in cards; hover stars persist favorite themes, the appearance button context menu opens Interface settings and lists light favorites before dark favorites; filmstrip names/badges, grid badges (auto/always/never), square-grid names, navigator, info overlay | @@ -437,7 +437,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PREF-PERFORMANCE | GPU / performance | P1 | ✅ | `cmd:app.gpu`, `cmd:app.memoryBudget`, `cmd:app.settings` | GPU on/off (a crash while the GPU device or its kernels are built, issue #250, turns it off for the next launch), preview size (Automatic = the whole-frame loupe render at canvas size, up to 2560 px; or a 1600–5120 px size for it; zoomed views add a window at up to 100 %, issue #323), memory budget (a quarter of it is the idle per-view stage caches' share; the open photo's views are counted and reported, and cut only past four times that, the before side's and the zoom window's first — a Before/After at 1:1 on a 2800 px canvas holds about 1 GB of GPU stages, plus the one 288 MB copy of the original, which `ui.inspect` reports as `sharedSourceBytes`), thumbnail cache size in Settings | | LR-PREF-PEOPLE | Face recognition | P2 | 🟡 | `cmd:faces.enable`, `cmd:faces.models.list`, `cmd:faces.models.inspect`, `cmd:faces.models.install`, `cmd:faces.models.download`, `cmd:faces.models.downloads`, `cmd:faces.models.downloadCancel`, `cmd:faces.models.remove`, `cmd:faces.models.select`, `cmd:dialog.faceModel`, `crates/faces/src/lib.rs`, `crates/ui-egui/src/panels/faces.rs` | Settings ▸ Faces: an off-by-default toggle and the face model list. Models are opt-in and never bundled, the 232 KB YuNet detector included. Press Download (terms first; then a pinned address, size and SHA-256 checked, fetched over pure-Rust https with `lightcraft-fetch`), or add any `.onnx` by picking or dropping it: it is recognised by hash or described from its shape, shows its licence terms and training-data note, runs a self-test, and installs only after an "I accept" box; an installed model is chosen and recognition switched on at once (the newest wins, each model keeps its own embedding cache). Non-commercial models are add-by-file only, never offered for download. Suggestions of names run on the shared pure-Rust CPU interpreter (`crates/faces/src/net.rs`, `crates/faces/src/runtime.rs`; bounded im2col/GEMM, checked ONNX shapes/operators; no external inference runtime; 40 public crops agree within 2.1e-6, one-thread SFace 34–36 ms / AuraFace 233–252 ms, see docs/faces.md) in a background worker and are never applied automatically. Thresholds are starting points calibrated on busts, not yet on live faces; the Recognise faces switch is off until a recognition model is chosen and installed (`faces.enable {enabled: true}` refuses otherwise; removing the last recogniser switches it off), issue #678 | | LR-PREF-WATERMARK | Watermark settings | P1 | ✅ | `cmd:export.savePreset`, `crates/ui-egui/src/panels/dialogs.rs` | set in the Export dialog; kept with Export with Previous and in saved export presets | -| LR-PREF-SHORTCUTS | Shortcut customisation | — | ✅ | `cmd:app.setShortcut`, `cmd:app.resetShortcuts`, `crates/ui-egui/src/panels/keymap.rs` | an extra (the reference app has no keymap editor): Help ▸ Keyboard Shortcuts (⌘/) lists every command; click a shortcut and press the new keys (Esc cancels), × removes, ↺ restores, Reset All; a key another command had moves over; saved in `ui.json`; native menu accelerators follow. Rating/label digits and secondary keys are listed read-only and yield to a key given to a command | +| LR-PREF-SHORTCUTS | Shortcut customisation | — | ✅ | `cmd:app.setShortcut`, `cmd:app.resetShortcuts`, `crates/ui-egui/src/panels/keymap.rs` | an extra (the reference app has no keymap editor): Help ▸ Keyboard Shortcuts (⌘/) lists every command; click a shortcut and press the new keys (Esc cancels), × removes, ↺ restores, Reset All; a key another command had moves over; a declared key that `ui.json` already gives another command stays with that command until ↺ takes it back; saved in `ui.json`; native menu accelerators follow. Rating/label digits and secondary keys are listed read-only and yield to a key given to a command | | LR-PREF-TECHPREVIEW | Early-access toggles | P2 | ⬜ | | | | LR-PREF-NOTIFICATIONS | Notifications | OOS | 🚫 | | | | LR-PREF-DEVICE | Device settings | P2 | ⬜ | | | @@ -461,27 +461,27 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | -| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | +| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | | LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | every slider exists and works, but the character of the result (tone curve shape, highlight recovery, texture / clarity / dehaze, noise reduction, sharpening, default look) is tuned by eye; there is no systematic side-by-side comparison against Lightroom on the same CC0 raws. Needs a fidelity suite: Lightroom reference renders kept only in the local `plan/` (never committed), compared per slider and preset with a perceptual metric. Tuning that changes how existing settings render ships as a new process version (LRC-DEV-PROCESS, `docs/process-versions.md`) | -| LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`) | files → app (import); grid photos → an album row (adds the selection, with a count badge while dragging); sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar) | +| LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`) | files → app (a drop-target card while they hover, then the import review); grid photos → an album row (adds the selection, with a count badge while dragging); sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar) | | LR-BEHAV-TOAST | Toast notifications | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` | | -| LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/panels/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests_dialog_fit.rs` | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / OK row stay on screen; lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window | +| LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/panels/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests_dialog_fit.rs`, `crates/ui-egui/src/tests_dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / OK row stay on screen; lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`) | | LR-BEHAV-SIDEBAR-COLLAPSE | Collapsible left-sidebar sections | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`section`, `section_header`), `crates/ui-egui/src/sidebar.rs` (`SidebarLayout`), `crates/ui-egui/src/tests_panels.rs` | click the Albums, Local, By Date, Folders or Keywords header (or drive `ui.clickWidget` `sidebarSection:<albums\|local\|byDate\|folders\|keywords>`) to fold or unfold the section; a chevron before the title shows the state; the choice is kept across restarts (`sidebar` in the UI state; the `collapsedSidebar` list of older settings files is still read). the click itself is UI-only, like the By Date / Keywords disclosure triangles, and `cmd:view.sidebarSection` `{section, collapsed}` folds and unfolds for agents; photos dropped on a folded Albums section have no target | | LR-BEHAV-SIDEBAR-SECTIONS | Left-sidebar sections share one frame and one arrangement | P2 | ✅ | `crates/ui-egui/src/sidebar.rs` (`SidebarSection`, `SidebarLayout`), `crates/ui-egui/src/panels/left.rs` (`section`, `section_header`, `tree_toggle`), `crates/ui-egui/src/tests_panels.rs` | Albums, Local, By Date, Folders and Keywords are drawn by one `section` frame (the same gap above, header, fold and accessibility name) from one arrangement, `sidebar` in the UI state: a list of `{id, hidden, collapsed}` top to bottom, also settable with `ui.set`. Whatever is read, every section is in it exactly once (unknown and repeated entries are dropped, the rest follow in the usual order), so a damaged or newer settings file never loses the other settings. Rows that open (album folders, Local folders, dates, library folders, keywords) share `tree_toggle`: the same triangle, the same remembered open state, announced as Expand / Collapse. A section with nothing to list (Folders before anything is imported, Keywords before any is added) stays, open, with a one-line note in place of rows (`sidebarEmpty:<id>`) instead of disappearing. `ui.set` reads `sidebar` strictly (`SidebarLayout::parse`): an unknown or repeated section, or a flag that is not true / false, is refused and changes nothing; sections left out follow in the usual order, shown and open; the older `collapsedSidebar` list still folds and unfolds. A section may have one button at the end of its header, declared in one place (`header_button`: an icon, a tooltip, and either an action or a menu): the frame draws it at the visible edge in the header and its pinned copy, keeps its click from folding the section and leaves it room beside a folded section's count. Albums has + (`icon:albumNew`: Create Album / Smart Album / Folder…), Keywords has + (`icon:keywordNew`: Create Keyword Tag, for a keyword inside the default parent, not inside what the Keyword List has picked; once made, Keywords is shown and opened down to it). My Photos (All Photos, Recently Added, Picks, Missing Photos, Recently Deleted) is not a section: it stays on top | | LR-BEHAV-SIDEBAR-HIDE | Show and hide left-sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset`, `crates/ui-egui/src/sidebar.rs`, `crates/ui-egui/src/panels/left.rs` (`sections_menu`), `crates/ui-egui/src/menubar.rs`, `crates/ui-egui/src/tests_panels.rs` | View ▸ Sidebar Sections lists Albums, Local, By Date, Folders and Keywords in the sidebar's order, each checked while shown; unchecking one takes its header and rows off the sidebar, checking it puts it back where and how it was (still folded if it was). The same list opens with a right-click on any section header (with Hide This Section first; widgets `sidebarMenu:hide`, `sidebarMenu:section:<id>`, `sidebarMenu:reset`) and on the My Photos title (`sidebarTitle`), which is always there, so hidden sections can always come back. Reset Sidebar Sections (enabled once something changed) shows and opens every section in the usual order. `view.sidebarSection` `{section, show?, collapsed?}` flips shown / hidden when neither flag is given and refuses an unknown section or a flag that is not true / false. Hiding the section of what the grid shows (an album, a keyword filter) leaves the grid as it is; an album made while Albums is hidden or folded brings Albums back, open. Kept with the UI state (`sidebar`). My Photos itself can't be hidden | | LR-BEHAV-SIDEBAR-REORDER | Reorder left-sidebar sections | P2 | ✅ | `cmd:view.sidebarMoveSection`, `crates/ui-egui/src/sidebar.rs` (`move_before`, `move_by`), `crates/ui-egui/src/panels/left.rs` (`section_drag`, `section_drop_before`, `section_drag_feedback`), `crates/ui-egui/src/tests_panels.rs` | drag a section by its header: its name follows the pointer, a line (`sidebarSectionDrop`) shows the gap it would go to (above the section whose upper half the pointer is over, or below the last), releasing over the sidebar moves it there, Esc or releasing elsewhere leaves it; the sidebar scrolls when the drag nears its top or bottom edge, also over a pinned header (a section picked up by the pinned header scrolls once the pointer has left it). A press on a header's button is never a section drag. A click on the header still folds the section, and an album dragged onto the Albums header is still an album drag. The header's menu has Move Up / Move Down (`sidebarMenu:moveUp` / `moveDown`), one shown section at a time, stepping over hidden ones, disabled at the ends. `view.sidebarMoveSection` `{section, direction: up\|down}` or `{section, before: <section>\|null}` (null: last) answers `{moved, order}`. The order is kept with the UI state (`sidebar`). Recently Deleted is listed with My Photos (below Picks / Missing Photos), not after the sections. Not here: dragging My Photos, or rows from one section into another | -| LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests_panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:<id>`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:<id>`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:<id>`, with Show Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button | +| LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests_panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:<id>`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:<id>`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:<id>`, with View ▸ Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button | | LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests_panels.rs` | drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed | -| LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `crates/ui-egui/src/tests_empty_library.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. The top bar has an Import button beside Export in every library. No drop-target highlight while files are dragged over the window yet, and a drop imports without the review the menu opens | +| LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `crates/ui-egui/src/tests_empty_library.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. The top bar has an Import button beside Export in every library. Files dragged over the window dim it and a card says what dropping will do; a drop of photos or folders opens the same import review as File ▸ Import | | LR-BEHAV-TOOLTIPS | Tooltips with shortcuts | P0 | ✅ | `crates/ui-egui/src/panels/bottombar.rs` | | | LR-BEHAV-TEXTFIELD | Text fields behave alike | P1 | 🟡 | `crates/ui-egui/src/text_field.rs`, `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/panels/right.rs` (`meta_field`), `crates/ui-egui/src/panels/dialogs.rs`, `crates/ui-egui/src/panels/unnamed.rs` | one shared field: right-click Cut / Copy / Paste / Select All (no Paste in the browser), Esc gives back the text from before the edit, Return / leaving / Esc reported to the caller, optional select-on-focus; agents use `ui.clipboard` (MCP `clipboard`) and `ui.inspect` → `copied`. Used by Search Photos, slider values, the Info panel's metadata fields (multi-line captions), the one-field dialogs (New / Rename Album, New Smart Album, Rename / Merge Keywords, text prompts) and the unnamed faces' name field so far; the other text fields (most dialogs, import, settings, masking, keywords …) still use egui's own and have no menu | | LR-BEHAV-HEADLESS | Headless UI snapshots | P2 | ✅ | `apps/lightcraft-cli/src/main.rs`, `crates/ui-egui/src/headless.rs`, `docs/control-protocol.md` | `snapshot` rasterizes the UI and defaults photo development to the CPU before the first frame, without adapter discovery; scaled dimensions are validated before allocation, and UI zoom preserves the requested physical viewport; JSON-lines control scripts are supported | -| LR-BEHAV-ACCESS | Accessibility | P2 | 🟡 | `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/text_field.rs`, `crates/ui-egui/src/panels/grid.rs`, `crates/ui-egui/tests/accessibility.rs` | AccessKit (VoiceOver / Narrator / AT-SPI): sliders announce control, value, range and step and take Increment / Decrement, buttons / icon buttons / dropdowns / section headers / sources their labels and state, text fields their caption, grid thumbnails file name, rating, flag and label. `tests/accessibility.rs` fails on an unnamed control, a slider without range or an untitled dialog in every view, Develop tool and 13 dialogs, and checks that Crop and Remove sliders are reached with Tab and that Tab walks the right panels top to bottom. Canvas tools by keyboard (`crates/ui-egui/src/canvas_keys.rs`, `crates/ui-egui/src/tests_canvas_keys.rs`): crop corners, edges and box, spot targets and sources, a New spot point (Return adds), radial / linear gradient handles and mask pins take the focus, are announced with their position and move with the arrows (Shift: further). Brush strokes and red-eye ellipses are pointer-only; not tried with a real screen reader ([audit](ui-parity.md#accessibility-audit)) | -| LR-BEHAV-LOCALE | Language options | P2 | ✅ | `cmd:app.language.english`, `cmd:app.language.simplifiedChinese`, `cmd:app.language.traditionalChinese`, `cmd:app.language.japanese`, `cmd:app.language.portuguese`, `cmd:app.language.french`, `cmd:app.language.spanish`, `cmd:app.language.german`, `cmd:app.language.russian`, `cmd:app.language.ukrainian`, `cmd:app.language.georgian` | Edit > Language lists every language in the table and the active one is checked; shared with Settings > General (docs/localization.md) | -| LR-BEHAV-LOCALIZE | Localisation | P2 | 🟡 | `crates/ui-egui/src/i18n.rs`, `crates/ui-egui/locales/`, `docs/localization.md`, `docs/localization-zh-hans.md`, `docs/localization-zh-hant.md`, `docs/localization-ja.md`, `docs/localization-pt-br.md`, `docs/localization-es.md`, `docs/localization-de.md`, `docs/localization-ru.md`, `docs/localization-ka.md` | One table entry per language (code, endonym, ISO 15924 script, catalog): English, Simplified Chinese, Traditional Chinese (Taiwan), Japanese, Brazilian Portuguese, Spanish, German, Russian, Ukrainian and Georgian UI with a persisted language preference and craft-fonts regular/bold faces per script (a variable face, as for Arabic, is drawn heavier for bold from its one file); menus, edit, crop/masks, settings, import/export and primary progress messages. Adding a language registers the locale and its language command, plus two catalogs. Stock presets/profiles, history steps, library headings, date headings and capture times are localised (user-named items stay verbatim); the Ukrainian catalog covers every existing catalog key, command/control label and rule-editor label; the German catalog reports newly added gaps; the other catalogs fall back to English for messages they lack. Technical errors remain English; release notes are translated in German and Ukrainian; craft-fonts faces for other scripts (Thai, Arabic, …) are UI fallbacks in every language, for file, folder and album names (#736); Traditional Chinese borrows the Simplified Chinese face (no TC face in craft-fonts yet), and the web build embeds the Japanese, Thai and Georgian faces in WASM while loading the Simplified Chinese face from a separate font file. | +| LR-BEHAV-ACCESS | Accessibility | P2 | 🟡 | `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/text_field.rs`, `crates/ui-egui/src/panels/grid.rs`, `crates/ui-egui/tests/it/accessibility.rs` | AccessKit (VoiceOver / Narrator / AT-SPI): sliders announce control, value, range and step and take Increment / Decrement, buttons / icon buttons / dropdowns / section headers / sources their labels and state, text fields their caption, grid thumbnails file name, rating, flag and label. `tests/it/accessibility.rs` fails on an unnamed control, a slider without range or an untitled dialog in every view, Develop tool and 13 dialogs, and checks that Crop and Remove sliders are reached with Tab and that Tab walks the right panels top to bottom. Canvas tools by keyboard (`crates/ui-egui/src/canvas_keys.rs`, `crates/ui-egui/src/tests_canvas_keys.rs`): crop corners, edges and box, spot targets and sources, a New spot point (Return adds), radial / linear gradient handles and mask pins take the focus, are announced with their position and move with the arrows (Shift: further). Dialogs with one name field (New Album, New Smart Album, Save Metadata Preset, the renames) take the focus once when they open, so Tab and Shift+Tab reach their check box, Cancel and OK, and Return and Esc still confirm and cancel (`crates/ui-egui/src/tests_dialog_tab.rs`). Brush strokes and red-eye ellipses are pointer-only; not tried with a real screen reader ([audit](ui-parity.md#accessibility-audit)) | +| LR-BEHAV-LOCALE | Language options | P2 | ✅ | `cmd:app.language.english`, `cmd:app.language.simplifiedChinese`, `cmd:app.language.traditionalChinese`, `cmd:app.language.japanese`, `cmd:app.language.portuguese`, `cmd:app.language.french`, `cmd:app.language.spanish`, `cmd:app.language.german`, `cmd:app.language.russian`, `cmd:app.language.ukrainian`, `cmd:app.language.georgian`, `cmd:app.language.polish`, `cmd:app.language.czech`, `cmd:app.language.italian`, `cmd:app.language.swedish`, `cmd:app.language.finnish`, `cmd:app.language.indonesian`, `cmd:app.language.vietnamese` | Edit > Language lists every language in the table and the active one is checked; shared with Settings > General (docs/localization.md) | +| LR-BEHAV-LOCALIZE | Localisation | P2 | 🟡 | `crates/ui-egui/src/i18n.rs`, `crates/ui-egui/locales/`, `docs/localization.md`, `docs/localization-zh-hans.md`, `docs/localization-zh-hant.md`, `docs/localization-ja.md`, `docs/localization-pt-br.md`, `docs/localization-es.md`, `docs/localization-de.md`, `docs/localization-ru.md`, `docs/localization-ka.md`, `docs/localization-pl.md` | One table entry per language (code, endonym, ISO 15924 script, catalog): English, Simplified Chinese, Traditional Chinese (Taiwan), Japanese, Brazilian Portuguese, Spanish, German, Russian, French, Ukrainian, Polish, Czech, Italian, Georgian, Swedish, Finnish, Indonesian and Vietnamese UI with a persisted language preference and craft-fonts regular/bold faces per script (a variable face, as for Arabic, is drawn heavier for bold from its one file); menus, edit, crop/masks, settings, import/export and primary progress messages. Adding a language registers the locale and its language command, plus two catalogs. Stock presets/profiles, history steps, library headings, date headings and capture times are localised (user-named items stay verbatim); the Ukrainian catalog covers every existing catalog key, command/control label and rule-editor label; the German catalog reports newly added gaps; the other catalogs fall back to English for messages they lack. Technical errors remain English; release notes are translated in German and Ukrainian; craft-fonts faces for other scripts (Thai, Arabic, …) are UI fallbacks in every language, for file, folder and album names (#736); Traditional Chinese borrows the Simplified Chinese face (no TC face in craft-fonts yet), and the web build embeds the Japanese, Thai and Georgian faces in WASM while loading the Simplified Chinese face from a separate font file. | | LR-BEHAV-LEARN | Tutorials | OOS | 🚫 | | | | LR-BEHAV-WHATSNEW | What's new | P2 | ✅ | `cmd:app.whatsNew`, `docs/whats-new.md` | Help ▸ What's New: release highlights | | LR-BEHAV-AI-EA | Early-access badges | P2 | ⬜ | | | @@ -529,8 +529,8 @@ visible menu bar yet: the menu model is only exposed through the control channel | MENU-EDIT-FIND | Find… | P0 | ✅ | `cmd:view.focusSearch`, `crates/ui-egui/src/panels/topbar.rs` | ⌘F focuses the search field | | MENU-VIEW-PHOTOGRID | Photo Grid | P0 | ✅ | `cmd:view.photoGrid` | | | MENU-VIEW-SQUAREGRID | Square Grid | P0 | ✅ | `cmd:view.squareGrid` | | -| MENU-VIEW-DETAIL | Detail | P0 | ✅ | `cmd:view.detail` | | -| MENU-VIEW-EDIT | Edit | P0 | ✅ | `cmd:panel.edit` | | +| MENU-VIEW-DETAIL | Detail View | P0 | ✅ | `cmd:view.detail` | | +| MENU-VIEW-EDIT | Edit Panel | P0 | ✅ | `cmd:panel.edit` | | | MENU-VIEW-FULLSCREENPREVIEW | Full Screen Preview | P1 | ✅ | `cmd:view.fullScreenPreview` | | | MENU-VIEW-LIGHTSOUT | Lights Out | P2 | ✅ | `cmd:view.lightsOut` | everything but the photo veiled; panels stay put | | MENU-VIEW-ENTERFULLSCREEN | Enter Full Screen | P1 | ✅ | `cmd:view.enterFullScreen` | | @@ -545,12 +545,12 @@ visible menu bar yet: the menu model is only exposed through the control channel | MENU-VIEW-SHOWORIGINAL | Show Original | P0 | ✅ | `cmd:view.showOriginal` | | | MENU-VIEW-BEFOREAFTER | Before/After submenu | P0 | ✅ | `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom` | | | MENU-VIEW-ZOOM | Zoom in / out / toggle / fit / 1:1 | P0 | ✅ | `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.zoomFit`, `cmd:view.zoom100` | | -| MENU-VIEW-CLIPPING | Show Clipping | P0 | ✅ | `cmd:view.clipping` | | +| MENU-VIEW-CLIPPING | Clipping | P0 | ✅ | `cmd:view.clipping` | | | MENU-VIEW-MASKOVERLAY | Mask overlay / cycle colour | P0 | ✅ | `cmd:view.maskOverlay`, `cmd:view.maskOverlayMode`, `cmd:view.maskOverlayColor` | colour cycles through the panel's swatches (no params) or takes `color` / `opacity` | | MENU-VIEW-INCLUDESUBFOLDERS | Include subfolders | P1 | ✅ | `cmd:library.browse` (`subfolders`) | toggle in the folder header; imports of folders are recursive | | MENU-VIEW-SORT | Sort submenu | P0 | ✅ | `cmd:library.sort`, `cmd:library.shuffle` | Random + Reshuffle; no colour-label key | | MENU-VIEW-STACKS | Expand/collapse stacks | P1 | ✅ | `cmd:stack.expandAll`, `cmd:stack.collapseAll` | | -| MENU-VIEW-PHOTOCOUNT | Show photo counts | P2 | ✅ | `cmd:view.photoCounts` | View ▸ Show Photo Counts toggles the left panel's counts | +| MENU-VIEW-PHOTOCOUNT | Show photo counts | P2 | ✅ | `cmd:view.photoCounts` | View ▸ Photo Counts toggles the left panel's counts | | MENU-VIEW-SIDEBARSECTIONS | Sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset` | View ▸ Sidebar Sections ▸ a checkable item per left-sidebar section, then Reset Sidebar Sections (see LR-BEHAV-SIDEBAR-HIDE) | | MENU-VIEW-HDR | HDR display options | P2 | ⬜ | | | | MENU-PHOTO-ADDTOALBUM | Add to album | P0 | ✅ | `cmd:album.addPhotos` | off for a Local-only selection, with an Add to My Photos First hint item (issue #684) | @@ -604,7 +604,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained | KEY-EDIT | Edit — E | P0 | ✅ | `cmd:panel.edit` | | | KEY-FULLSCREEN | Full-screen preview — F | P1 | ✅ | `cmd:view.fullScreenPreview` | | | KEY-LIGHTSOUT | Lights Out — Shift+L (Classic's L is Linear Gradient here) | P2 | ✅ | `cmd:view.lightsOut` | On → Dim (80 %) → Off; Esc turns the lights on | -| KEY-GRID | Grid — G | P0 | ✅ | `cmd:view.gridToggle`, `cmd:view.photoGrid` | G toggles Photo Grid ↔ Square Grid | +| KEY-GRID | Grid — G | P0 | ✅ | `cmd:view.gridToggle`, `cmd:view.photoGrid` | G toggles Photo Grid ↔ Square Grid; both View menu rows show its live shortcut (including remapping/unbinding), with direct grid bindings taking priority; menu clicks still choose the named grid (#2500) | | KEY-INFO | Info — I | P0 | ✅ | `cmd:panel.info` | | | KEY-KEYWORDS | Keywords — K | P0 | ✅ | `cmd:panel.keywords` | | | KEY-CLIPBOARD | Copy / paste edit settings — ⌘C / ⌘V | P0 | ✅ | `cmd:develop.copy`, `cmd:develop.paste`, `crates/ui-egui/src/shortcuts.rs` (`matches`) | ⌘X has nothing to cut outside text fields; on Windows and Linux, where the windowing layer sends Ctrl+C / Ctrl+V as clipboard events rather than key presses, those run the shortcuts too (⇧Insert pastes plainly); there Ctrl+V only arrives while the system clipboard holds text (egui-winit drops it otherwise), so with an empty clipboard Paste Settings needs the menu | @@ -691,7 +691,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LRC-LIB-IMPORT | Full import dialog | P1 | ✅ | `cmd:library.import` (`mode`, `destination`, `organize`, `rename`, `metadataPreset`, `preset`, `keywords`, `album`), `crates/ui-egui/src/import.rs` | review grid with duplicates skipped; add in place or copy (library Originals or any folder; by day / by month / one folder / custom folder template such as `{date:%Y}/{date:%Y%m%d}` → 2026/20260114, kept inside the destination; example destination shown; rename template with live example, Tags picker (insert at cursor) and unknown-tag warning, numbered across the import); develop preset, metadata preset, keywords, album on import | +| LRC-LIB-IMPORT | Full import dialog | P1 | ✅ | `cmd:library.import` (`mode`, `destination`, `organize`, `rename`, `metadataPreset`, `preset`, `keywords`, `album`), `crates/ui-egui/src/import.rs` | review grid with duplicates skipped; add in place or copy (library Originals or any folder; by day / by month / one folder / custom folder template such as `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 or `{date:%Y}/{date:%B}` → 2026/January, kept inside the destination; example destination shown; rename template with live example, Tags picker (insert at cursor) and unknown-tag warning, numbered across the import); develop preset, metadata preset, keywords, album on import | | LRC-LIB-AUTOIMPORT | Watched-folder import | P2 | ✅ | `cmd:library.autoImport` | see LR-IMP-AUTO | | LRC-LIB-TETHER | Tethered capture | P2 | ⬜ | | | | LRC-LIB-VIEWS | Grid / loupe / compare / survey / people | P1 | 🟡 | `cmd:view.photoGrid`, `cmd:view.squareGrid`, `cmd:view.detail`, `cmd:view.compare`, `cmd:view.survey`, `cmd:view.gridInfo` | grid, square grid, loupe, compare, survey, second window; square-grid captions: file name, exposure or capture date (View ▸ Grid Info; no people view; picking one in Photo Grid switches to Square Grid) | @@ -699,19 +699,19 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:<pane>`) or “This photo can't be opened” (`compare:renderFailed:<pane>`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `docs/lightroom-catalog-import.md` | read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/lightroom_destination.rs`, `crates/ui-egui/src/tests_lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | -| LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/panels/settings.rs`, `crates/ui-egui/src/panels/left.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests_keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key | +| LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/panels/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests_launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests_keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290) | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | | LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests_panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/<host>`), NFS (`/Network/Servers/<host>`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | | LRC-LIB-COLLECTIONS | Collections & sets | P1 | ✅ | `cmd:album.create`, `cmd:album.createSmart`, `cmd:album.toggleTarget`, `cmd:album.setTarget`, `cmd:album.clearQuick` | albums + folders (sets), smart albums (rule editor; rules incl. File Path — the whole string, either separator, case-insensitive), Quick Collection and target album (B in the grids adds / removes the selection; album menu ▸ Set as Target Album; the target is marked +) | | LRC-LIB-SMARTCOLL | Smart-collection rules | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:album.ruleFields`, `cmd:dialog.smartAlbum`, `crates/catalog/src/rules.rs`, `crates/ui-egui/src/panels/rules_editor.rs` | rule editor: match all / any / none, nested groups (⌥+ or + Group), 47 fields. The field menu shows Rating, Pick Flag, Color Label and Any Searchable Text, then one submenu per group (`FIELD_GROUPS`; `album.ruleFields` reports each field's `group`): Source (album — a plain or a smart album, so one smart album can include or exclude another; a rule that would make an album include itself, directly or through others, is refused, and a loop saved anyway can't recurse: inside it, the album being evaluated counts as holding no photos, so an "isn't" rule on it matches every photo, and the sidebar marks it ⚠ —, virtual copy, copy name, in a stack), File (filename, extension, file path, type, format, video duration), Date (capture / import / edit), Keywords & People (keywords, keyword count, people on named faces, people count), Description (title, caption, alt text, creator, copyright, copyright status), Camera Info (camera, lens, focal length, aperture, shutter speed as 1/250, ISO), Location (any, city, state / province, country, GPS), Size (long / short edge, aspect ratio and megapixels, all of the photo as shown: oriented and cropped), Develop (has edits, cropped, treatment), Assisted Culling (focus, best of similar shots); text / number / date / in-the-last operators; live match count; also usable as a library filter (`ruleSet`). Missing vs Classic: develop preset, flash, exposure bias, camera serial, colour profile / bit depth, IPTC Job, smart-preview status. Choice values read as words in every language (Public Domain, Black & White; `album.ruleFields` gives `choiceLabels`), while rules store the ids; yes/no fields read Yes / No and take `true`/`false`, `"yes"`/`"no"`, `"true"`/`"false"` or 1/0. Every value is checked against its field (`RuleSet::check`): numbers (rating 0–5), shutter speeds, dates (`2026`, `2026-08`, `2026-08-14`, then `T10`, `T10:00` or `T10:00:00`, a space working as the `T`, and after whole seconds a fraction and a time zone as imported capture times carry them (`.250+02:00`); no 30 February; `rules::rule_date` is the one reading for the check and the matcher; each date field has a calendar picker, `crates/ui-egui/src/date_picker.rs`, that picks a year, a month or a day and keeps a "between" in order), between = two bounds in order, in the last = more than 0 of a known unit, choices (ids, the flag's picked / rejected, a colour label's custom name), text with something to look for, an existing album (plain or smart, not a folder), no empty groups; each problem names its rule (`rule 2.1: no rating 0–5 is 9`), and album.createSmart / setRules / library.filter refuse them. The editor marks each bad rule under its row (inside groups too), keeps OK disabled until they are fixed (and its confirm refuses them before renaming anything), picks an Album rule's album with an album picker (`crates/ui-egui/src/album_picker.rs`: the sidebar's tree with folders, or type part of a name or folder; ↑ / ↓ / Enter; albums that can't be picked shown greyed with the reason) (is / isn't; a folder can't be tested), and drawing it never changes a rule: a rating of 9, "in the last 0 days" or 20,000 days, a "between" that isn't a pair all stay as stored (and are marked where they can't match) until edited. Album rules saved with an old operator (≥, between) are read as the "isn't" they always meant (`RuleSet::upgrade`). Saved smart albums whose rules no longer check are marked ⚠ in the sidebar (tooltip: what to fix; `albums.list` `problems`, `Catalog::smart_album_problems`); the name and rules of an album are saved as one undo step (`album.setRules` `name`). Problems read as the field's name and the issue in the editor's language (“Titel: braucht einen Suchbegriff”; `Problem::issue` / `field`, `Issue::text`, translated in every locale), while commands keep the English `rule 2.1: …` message for agents | | LRC-LIB-PUBLISH | Publish services | P2 | ⬜ | | | -| LRC-LIB-FILTERBAR | Library filter bar | P1 | ✅ | `cmd:view.filterBar`, `cmd:filter.applyPreset`, `cmd:library.filter` (`labels`, `ruleSet`), `crates/ui-egui/src/panels/filterbar.rs` | rating/flag/label (several labels at once = any of them)/kind/edited/camera/lens/keyword, clear, save as smart album, filter presets; the filter stays as you change albums (always locked, as in the desktop app); arbitrary conditions via the smart-album rule editor | +| LRC-LIB-FILTERBAR | Library filter bar | P1 | ✅ | `cmd:view.filterBar`, `cmd:filter.applyPreset`, `cmd:library.filter` (`labels`, `ruleSet`), `crates/ui-egui/src/panels/filterbar.rs` | rating/flag/label (several labels at once = any of them)/kind/edited/camera/lens/keyword, clear, save as smart album, filter presets; the filter stays as you change albums (an album the filter held is replaced by the album you show; always locked, as in the desktop app); arbitrary conditions via the smart-album rule editor | | LRC-LIB-STACKS | Stacks (full) | P1 | ✅ | `crates/catalog/src/stacks.rs`, `cmd:stack.group`, `cmd:stack.split`, `cmd:stack.moveUp`, `cmd:stack.moveDown` | group / ungroup / toggle / set top / remove / auto by time / split / move up and down | | LRC-LIB-VC | Virtual copies | P1 | ✅ | `cmd:photo.virtualCopy` | ⌘' | | LRC-LIB-LABELS | Colour-label sets | P1 | ✅ | `cmd:label.sets`, `cmd:label.applySet`, `cmd:label.saveSet`, `cmd:label.deleteSet`, `cmd:label.setNames`, `crates/engine/src/cmd/manage.rs` | built-in Colors / Review sets + user sets (Photo ▸ Set Color Label, Edit Label Names… dialog); names written to and read from `xmp:Label` | -| LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:tool.keywordPainter` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), a Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords to edit, them with their parents, what exported files carry), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:<parent>`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:<keyword>`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:<keyword>`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). Not yet: synonyms in search, person keywords tied to faces, Keyword Shortcut, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields | +| LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `cmd:tool.keywordPainter` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9; ⌥0 / ⌥⇧0 go to the next / previous set and wrap around at either end); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), a Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords to edit, them with their parents, what exported files carry), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:<parent>`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:<keyword>`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:<keyword>`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). Not yet: synonyms in search, person keywords tied to faces, Keyword Shortcut, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields. In the Keyword List a keyword's empty box carries a dot when the selected photos have a keyword inside it (its tooltip names them), so a folded keyword shows that something in it is applied | | LRC-LIB-METADATA | Metadata panel & presets | P1 | ✅ | `cmd:photo.setMeta`, `cmd:metadata.savePreset`, `cmd:metadata.applyPreset`, `cmd:metadata.presets`, `cmd:metadata.deletePreset`, `cmd:dialog.captureTime` | IPTC core, accessibility, place, capture-time edit; copyright status (unknown / copyrighted / public domain), rights usage terms and copyright info URL (`photo.setMeta` `copyrightStatus`, `usageTerms`, `copyrightUrl`; XMP Rights Management fields, kept by "copyright only" exports, a smart-album rule); metadata presets (Photo → Metadata Preset, Save Metadata Preset… from the active photo; applied on import from Settings) | | LRC-LIB-QUICKDEV | Quick develop | P2 | ✅ | `cmd:develop.quickAdjust`, `crates/ui-egui/src/panels/edit.rs` (`quick_develop`) | grid with several photos selected: Edit panel ▸ Quick Develop steps (exposure ⅓ / 1 stop, contrast, highlights, shadows, whites, blacks, clarity, vibrance, temperature) added to each photo's own value, one undo step | | LRC-LIB-PEOPLE | People view | P2 | 🟡 | `cmd:view.people`, `cmd:view.person`, `cmd:faces.person`, `cmd:faces.unnamed`, `cmd:faces.nameFaces`, `crates/ui-egui/src/panels/people.rs`, `crates/ui-egui/src/panels/person.rs`, `crates/ui-egui/src/panels/unnamed.rs`, `crates/engine/src/face_tiles.rs` | Named People cards (face close-up, the photo count on the picture, name) for the photos the active filters let through, with the filter chips shown above them, sized by the thumbnail slider. Below them the **Unnamed faces**: every face nobody has named as a cropped picture, look-alikes next to each other once recognition has looked at them, a suggested name on a face the named ones recognise; click or Shift-click to select, type a name, Enter names the whole group in one undo step. A click on a person opens their page: only cropped faces, then **More** (unnamed faces that look like them, best first; click to confirm one, × to hide for the session, or ↑ / hovered-or-focused A key to confirm all currently shown non-hidden suggestions at or above that face's score, including ties, in one undo step). Every face is shown by the detector's box where the scan has one, so faces are equally close. Until recognition is set up a line at the top offers the next step (Settings ▸ Faces, or Turn on), as does the loupe's name box. Face pictures of unedited raws are cut from the largest embedded preview (planned read: header and JPEG only, never the sensor data) when it holds at least ¾ of the tile's pixels across the face, else developed as before; all are kept in the thumbnail disk cache at 16 px size steps, so a later launch shows them without reading the originals (#1440, `docs/faces.md`). No clusters with separators between groups, no persistent reject, no merge of two people @@ -723,16 +723,17 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SLIDESHOW-IMPROMPTU | Impromptu slideshow | P2 | ✅ | `cmd:view.slideshow` | see LR-VIEW-SLIDESHOW | | LRC-DEV-SNAPSHOTS | Named snapshots | P1 | ✅ | `cmd:version.create`, `cmd:version.restore` | = versions | | LRC-DEV-HISTORY | Full history panel | P1 | ✅ | `cmd:history.list`, `cmd:history.restore`, `cmd:history.previous`, `cmd:history.next`, `cmd:history.clear` | row menu: copy step to before, create version from step, clear history; clicking a step loads it without adding one (current step highlighted, later steps greyed and returnable until a new edit truncates them; one undo step; cursor saved in the catalog, old catalogs open at the latest step) | -| LRC-DEV-SOFTPROOF | Soft proofing | P2 | 🟡 | `cmd:view.softProof`, `crates/pipeline/src/output.rs` (`Proof`), `crates/ui-egui/src/panels/edit.rs` (`soft_proofing`) | S in the loupe (in grids S stays Expand/Collapse Stack): paper-white surround and "Proof Preview", proof profile (sRGB / Display P3 / Adobe RGB / ProPhoto / Rec. 2020), destination (red) and display (blue) gamut warnings (the display's gamut is the monitor profile's, `cmd:app.displayProfile`, else sRGB), Create Proof Copy (a named virtual copy). printer / paper ICC profiles can be loaded as the proof profile (size-capped, the last few kept), with rendering intent (Perceptual / Relative Colorimetric), Simulate Paper & Ink and a device-gamut warning (`crates/codecs/src/proof.rs`, `crates/engine/src/proof.rs`) | +| LRC-DEV-SOFTPROOF | Soft proofing | P2 | 🟡 | `cmd:view.softProof`, `crates/pipeline/src/output.rs` (`Proof`), `crates/ui-egui/src/panels/edit.rs` (`soft_proofing`) | S in the loupe (in grids S stays Expand/Collapse Stack): paper-white surround and "Proof Preview", proof profile (sRGB / Display P3 / Adobe RGB / ProPhoto / Rec. 2020), destination (red) and display (blue) gamut warnings (the display's gamut is the monitor profile's, `cmd:app.displayProfile`, else sRGB), Create Proof Copy (a named virtual copy). printer / paper ICC profiles can be loaded as the proof profile (size-capped, the last few kept), with rendering intent (Perceptual / Relative Colorimetric), Simulate Paper & Ink and a device-gamut warning (`crates/codecs/src/proof.rs`, `crates/engine/src/proof.rs`); on the GPU for output-space proofs (destination and display gamut warnings included; equivalence-tested), an output-device profile's 3D table on the CPU | | LRC-DEV-AUTOSYNC | Sync / auto sync / paste previous | P1 | ✅ | `cmd:develop.sync`, `cmd:develop.autoSync`, `cmd:develop.pastePrevious` | Edit ▸ Sync Settings / Auto Sync (⌥⇧⌘A): only the changed settings carry over, one undo step, slider drags sync on release, spots / red eye stay per photo; Edit panel banner | | LRC-DEV-MATCHEXP | Match total exposures | P2 | ✅ | `cmd:develop.matchExposure` | Photo ▸ Match Total Exposures: the selected photos' Exposure set so shutter × ISO ÷ aperture² plus the slider matches the active photo's | | LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | | | LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | | | LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/panels/settings.rs` | Settings → Import: raw default and per-camera presets | | LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | each photo records the rendering process its settings are interpreted by: settings saved before this existed load as V1, new photos and Reset get the latest, virtual copies inherit, copy / paste / sync / presets keep each photo's own; Photo ▸ Update to Current Process (one undo step, enabled while a selected photo is on an older process); a number from a newer LightCraft is kept and renders with the newest known process. Only V1 exists so far: this is what lets a retuned default tone (#146) or stronger Light sliders (#196) ship without changing existing edits | -| LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/panels/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; applied as they change, saved with the app settings; `view.viewOptions {info1, info2}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), "show briefly when the photo changes", the loading-message and video-frame options | +| LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/panels/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option | | LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders | | LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | | +| LRC-DEV-HISTOGRAM-DRAG | Drag on the histogram to adjust tone regions | P2 | ✅ | `crates/ui-egui/src/panels/histogram.rs`, `crates/ui-egui/src/panels/edit.rs`, `crates/develop/src/controls.rs`, `crates/ui-egui/src/tests_histogram_drag.rs`, `cmd:develop.set`, `cmd:develop.beginInteraction`, `cmd:develop.endInteraction`, `ctl:light.blacks`, `ctl:light.shadows`, `ctl:light.exposure`, `ctl:light.highlights`, `ctl:light.whites` | five zones across the plot's width, each moving the Basic control it names: Blacks 0.00–0.15, Shadows 0.15–0.35, Exposure 0.35–0.65, Highlights 0.65–0.85, Whites 0.85–1.00; every step is a `develop.set` between `develop.beginInteraction` and `develop.endInteraction` (the sliders' own path), so the draft render follows the drag live and the whole drag lands as one undo step; the zone the press landed in stays locked for the drag, so dragging across the others changes nothing; sideways travel of the plot's width sweeps that control's whole range (Shift a tenth, as on the sliders), clamped to its spec; hovering a zone tints it and shows its value in the strip under the plot ("Exposure: +0.45 EV"), with the sideways-resize cursor; a double-click resets that zone's control to its default in one undo step; the strip under the plot (readout / EXIF) and the clipping buttons in the plot's top corners are not zones | | LRC-MAP-VIEW | Map view | P2 | ⬜ | | | | LRC-MAP-GEOTAG | Drag photos onto the map | P2 | ⬜ | | | | LRC-MAP-LOCATIONS | Saved locations | P2 | ⬜ | | | @@ -752,20 +753,20 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-SS-TEMPLATES | Slideshow templates | P2 | 🟡 | `cmd:slideshow.templates.list`, `cmd:slideshow.templates.apply`, `cmd:slideshow.templates.save`, `cmd:slideshow.templates.update`, `cmd:slideshow.templates.rename`, `cmd:slideshow.templates.delete`, `cmd:slideshow.templates.import`, `cmd:slideshow.templates.export`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_template.rs`, `path:crates/ui-egui/src/panels/slide_templates.rs` | Template Browser at the top of Settings ▸ Slideshow: a template is the Playback (not "prepare previews"), Layout / Options / Backdrop, Overlays and Titles settings as one versioned JSON document. Five built-ins of our own (Plain Black, Gallery Wall, Edge to Edge, Cinema Wide, Shooting Data; no Lightroom names or designs, no image or font files) and the user's own, saved as files in `<settings>/slideshow-templates` (machine-wide, like Classic's): save current settings, Update with Current Settings, rename, delete (confirmed), import / export `.json`. Click applies (one step, saved with the library); pointing at one previews it on the selected photo (or the intro / ending) in the live preview without changing anything (`slideshow.preview {template}`). No undo for library preferences: the settings a template replaced stay as "Previous settings" for the session (applying it again goes forward). Every section is read through its settings' own validation (out-of-range values clamped, wrong types or unknown keys refused), files are capped (256 KB, 1000 listed), a newer format version is refused with a message, a bad file is listed as skipped, names are sanitised into file names that can't leave the folder, a missing plate / watermark image or background photo applies with a warning. Missing: the Slideshow module's left-panel browser (it lives in Settings until the module view exists), template folders (New Folder, moving templates between folders), saving a slideshow with a collection, a preview thumbnail inside the browser itself | | LRC-SS-OPTIONS | Slideshow options | P2 | ✅ | `cmd:slideshow.layout`, `cmd:slideshow.preview`, `path:crates/slideshow/src/compose.rs` | Zoom to Fill Frame (the photo covers its image cell, cropped to it; off: fits inside), Stroke Border (colour, width as a share of the slide's shorter side, drawn around the photo), Cast Shadow (opacity, offset, radius, angle; a blurred offset rectangle under the photo and its stroke). Composed by `lightcraft-slideshow` (CPU, no UI) for playback, the Settings ▸ Slideshow preview and `slideshow.preview`; edited in Settings ▸ Slideshow until the Slideshow module view exists | | LRC-SS-LAYOUT | Slideshow layout | P2 | 🟡 | `cmd:slideshow.layout`, `cmd:slideshow.preview`, `path:crates/ui-egui/src/panels/slide_layout.rs` | Margins left / right / top / bottom (linked or each on its own; shares of the slide's shorter side, so any screen or output size looks the same), Show Guides, Aspect Preview (Screen, 16:9, 4:3). Missing: the Slideshow module's slide editor — guides are drawn only in the Settings ▸ Slideshow preview and can't be dragged to set the margins; the aspect preview applies to that preview and `slideshow.preview` (playback always fills the screen, as in Classic) | -| LRC-SS-OVERLAYS | Slideshow overlays | P2 | 🟡 | `cmd:slideshow.overlays`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_overlay.rs`, `path:crates/ui-egui/src/panels/slide_overlays.rs` | Identity plate (text with size / colour / opacity, or a PNG / JPEG file with its transparency; render behind image), rating stars (our own vector stars, colour, size), text overlays (up to 16) with tokens (`{file}`, `{caption}`, `{title}`, `{date}`, `{exposure}`, `{shutter}`, `{aperture}`, `{focal}`, `{iso}`, `{camera}`, `{lens}`, `{rating}`, `{copyright}` and the other rename tokens; unknown tags show as typed and are reported), size / colour / opacity and a drop shadow (opacity, offset, radius, angle); each at one of nine anchors of the slide or the photo plus an offset, kept on the slide; the export watermark on the photo. Sizes relative to the slide; drawn by the engine over the composed slide (Inter + craft-fonts CJK, the export watermark's text renderer) for playback, the Settings ▸ Slideshow preview and `slideshow.preview`. Missing: dragging overlays on the slide in a Slideshow module editor, font family / style choice (Inter SemiBold only), the Identity Plate Editor's styled multi-run text, right-to-left reordering (Arabic / Hebrew draw in logical order, and without glyphs in Inter) | +| LRC-SS-OVERLAYS | Slideshow overlays | P2 | 🟡 | `cmd:slideshow.overlays`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_overlay.rs`, `path:crates/ui-egui/src/panels/slide_overlays.rs` | Identity plate (text with size / colour / opacity, or a PNG / JPEG file with its transparency; render behind image), rating stars (our own vector stars, colour, size), text overlays (up to 16) with tokens (`{file}`, `{caption}`, `{title}`, `{date}`, `{exposure}`, `{shutter}`, `{aperture}`, `{focal}`, `{iso}`, `{camera}`, `{lens}`, `{rating}`, `{copyright}` and the other rename tokens; unknown tags show as typed and are reported), size / colour / opacity and a drop shadow (opacity, offset, radius, angle); each at one of nine anchors of the slide or the photo plus an offset, kept on the slide; the export watermark on the photo. Sizes relative to the slide; drawn by the engine over the composed slide (Inter + craft-fonts CJK and Thai, the export watermark's text renderer) for playback, the Settings ▸ Slideshow preview and `slideshow.preview`. Missing: dragging overlays on the slide in a Slideshow module editor, font family / style choice (Inter SemiBold only), the Identity Plate Editor's styled multi-run text, horizontal Thai mark positioning, Arabic joining and right-to-left reordering (no Arabic export fallback; Arabic / Hebrew remain missing-glyph boxes with the bundled faces) | | LRC-SS-BACKDROP | Slideshow backdrop | P2 | ✅ | `cmd:slideshow.layout`, `path:crates/slideshow/src/compose.rs` | Background colour, Color Wash (a gradient from a second colour, full at the side its angle points to, at an opacity), Background Image (a library photo filling the slide at an opacity: "Use selected photo" in Settings ▸ Slideshow, `backgroundImage` in `slideshow.layout`; rendered once and shared by the slides). In the web build the composition runs on the main thread when a worker's render comes back | | LRC-SS-TITLES | Slideshow titles | P2 | 🟡 | `cmd:slideshow.titles`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_title.rs`, `path:crates/ui-egui/src/panels/slide_titles.rs` | Intro screen and ending screen, each on or off (library preference, `slideshow.titles`; Settings ▸ Slideshow ▸ Titles): a background colour and, centred on it, the identity plate of the Overlays section (its text or image; Add Identity Plate) or the screen's own line of text, in the plate's colour or an override colour, at a scale (height as a share of the slide's shorter side; text wider than the slide shrinks to fit), for its own duration (default: the slide duration). Titles are items of the playback timeline: composed off the UI thread by the same composer at the screen's size, prepared ahead, waited for and faded like slides; the intro plays once before the first photo, the ending after the last photo when repeat is off; random order never moves them; ←/→ step across them; they never change the selection and the control bar shows Intro / End instead of n / N. `slideshow.preview {title}` renders a screen; the Settings preview shows Photo / Intro / Ending. An empty view still refuses to play ("no photos to show"). Missing: Classic's exact behaviour with Repeat on is not verified (we never show the ending, and show the intro only at the start, while repeating), the Identity Plate Editor's styled text (Inter SemiBold only), override colour leaves an image plate's colours alone, the Slideshow module's Titles panel (settings live in Settings ▸ Slideshow). Slideshow export (LRC-SS-EXPORT) includes them: a PDF page / JPEG each, and in video they hold and fade like slides | | LRC-SS-MUSIC | Slideshow music | P2 | ⬜ | | | -| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan & zoom, manual-advance mode, choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) | +| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held), manual slideshow (`manual`: a slide, the intro or the ending stays up until ←/→ or the control bar changes it; exports keep the slide duration). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan & zoom, choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) | | LRC-SS-EXPORT | Slideshow export | P2 | 🟡 | `cmd:slideshow.export`, `cmd:slideshow.exportStatus`, `cmd:dialog.slideshowExport`, `cmd:app.slideshowExport`, `path:crates/engine/src/slideshow_export.rs`, `path:crates/codecs/src/video.rs`, `path:crates/ui-egui/src/slideshow_export.rs` | View ▸ Export Slideshow… (and Export PDF / JPEG / Video in Settings ▸ Slideshow): the photos in view as their composed slides (layout, overlays) between the intro and ending screens that are on, in view order. **PDF**: one page per slide at 1024 / 1920 / 3840 px (any 64–8192 by command; page = slide pixels in points, aspect from the aspect preview, "screen" = 16:9), JPEG quality, each page carrying the slide duration and a fade transition for presentation mode, "Automatically show full screen" (`/PageMode /FullScreen`). **JPEG**: `<name>-001.jpg`… in a new folder. **Video**: AV1 (rav1e, fast preset) in MP4 or WebM written by our own muxers, 720p / 1080p (64–2160 by command), 24 / 30 fps (25 / 60 by command); each slide held for its duration (one long sample: variable frame rate) and fades rendered as blended frames (crossfade or through the fade colour); at most 2 hours. Runs in the background with a row in the activity stack (frames or slides done, ✕ cancels); files are written as `.part` and renamed when complete, so a cancelled or failed export leaves nothing; a photo that can't be rendered is skipped with a warning. Missing: H.264 (Classic's codec; patents, no pure-Rust encoder), audio / music in the video (LRC-SS-MUSIC), random order and pan & zoom in exports, the PDF's per-page fades follow the viewer (Acrobat), export presets, Classic's export dialog sizes beyond these, the web build (no export) | | LRC-PRINT-LAYOUTSTYLE | Print layout styles | P2 | ✅ | `cmd:dialog.print`, `cmd:print.set`, `cmd:print.get`, `cmd:print.exportPdf`, `cmd:export.contactSheet`, `crates/ui-egui/src/print_view.rs` | File → Print… (⌘P): Single Image, Contact Sheet, Picture Package and Custom Package, one page preview each; also `print.*` commands for the CLI, control channel and MCP; the older File → Contact Sheet PDF stays | | LRC-PRINT-IMAGESETTINGS | Print image settings | P2 | ✅ | `cmd:print.set`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/print_view.rs` | Zoom to Fill Frame, Rotate to Fit, Photo Border (width, colour; package styles) and Inner Stroke (width in points, colour) in the dialog, drawn in the preview and in the PDF; pixel-tested | -| LRC-PRINT-LAYOUT | Print layout | P2 | 🟡 | `cmd:print.set`, `cmd:print.layout.autoLayout`, `cmd:print.layout.newPage`, `cmd:print.layout.clear`, `cmd:app.print`, `cmd:export.contactSheet`, `crates/engine/src/print/layout.rs` | A3/A4/A5/Letter/Legal/Tabloid/4x6/5x7/8x10/13x19 and custom paper, portrait/landscape, per-side margins, grid with column/row spacing and square cells, 72–720 ppi, in a Print dialog with a scaled page preview; no printer-driver Page Setup, no cell size / alignment presets | +| LRC-PRINT-LAYOUT | Print layout | P2 | 🟡 | `cmd:print.set`, `cmd:print.layout.autoLayout`, `cmd:print.layout.newPage`, `cmd:print.layout.clear`, `cmd:app.print`, `cmd:export.contactSheet`, `crates/engine/src/print/layout.rs` | A3/A4/A5/Letter/Legal/Tabloid/4x6/5x7/8x10/13x19, the Japanese photo and postcard sizes (L判 89×127, 2L判 127×178, KG判 102×152, はがき 100×148, 往復はがき 148×200, 六切 203×254, 四切 254×305, 名刺 55×91 mm, by their customary names) and custom paper, portrait/landscape, per-side margins, grid with column/row spacing and square cells, 72–720 ppi, in a Print dialog with a scaled page preview; no printer-driver Page Setup, no cell size / alignment presets | | LRC-PRINT-GUIDES | Print guides | P2 | ✅ | `cmd:print.set`, `cmd:print.cell.move`, `crates/ui-egui/src/print_view.rs` | rulers in in/cm/mm/pt, snap off/cells/grid with a grid size, and Page Margins / Page Bleed (a fixed 0.125 in outline) / Page Grid / Image Cells / Dimensions guides drawn on the preview | | LRC-PRINT-CELLS | Picture-package cells | P2 | ✅ | `cmd:print.cell.add`, `cmd:print.cell.move`, `cmd:print.cell.resize`, `cmd:print.cell.delete`, `cmd:print.cell.stack`, `cmd:print.cell.photo`, `cmd:print.cell.page`, `cmd:print.layout.autoLayout`, `crates/ui-egui/src/print_view.rs` | add cells at standard or custom sizes, drag and resize them on the page preview (snap to cells, grid or off), Send to Back / Backward / Forward / Bring to Front, a photo per cell (Custom Package), Auto Layout packing, New Page, Clear Layout; no Auto Layout for Custom Package | | LRC-PRINT-PAGE | Print page options | P2 | 🟡 | `cmd:print.set`, `cmd:export.contactSheet`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/print_view.rs` | page background colour and margins in the Print dialog; Page Options for Single Image and Contact Sheet (`print.set {page: {pageNumbers, pageInfo, cropMarks}}`, checkboxes in the Page section, kept in templates): the page number at the bottom right, the print settings line (sharpening, profile, resolution) at the bottom left, crop marks at each photo's corners, drawn in the preview and in the PDF (`print::compose::tests::crop_marks_sit_outside_each_photo_corner`); filename captions in the contact-sheet PDF; no identity plate, watermark, photo info or package Cut Guides | | LRC-PRINT-JOB | Print job & colour management | P2 | 🟡 | `cmd:print.set`, `cmd:print.exportPdf`, `crates/ui-egui/src/print_view.rs`, `crates/engine/src/print_color.rs`, `crates/codecs/src/print.rs`, `crates/engine/src/pdf.rs`, `cmd:export.contactSheet` | the Print dialog's Print Job panel and `print.set {job}`: print resolution 72–720 ppi; colour management: Managed by Printer (sRGB / Adobe RGB, profile embedded) or a printer / paper ICC profile (RGB, CMYK or grey) converted here and named as the PDF's output intent; perceptual / relative colorimetric with black point compensation; Print Adjustment brightness / contrast; print sharpening Low / Standard / High for Matte / Glossy; 16-bit (or 8-bit) ICC-tagged lossless page images; a bad profile fails before rendering (`tests_print::export_pdf_with_a_printer_profile`). The contact sheet keeps its fixed 150 dpi sRGB JPEG PDF. Missing: printing to a printer (OS print dialog), JPEG file output, Draft Mode | -| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `crates/ui-egui/src/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; no built-in templates, no folders, no import / export of template files | +| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `cmd:print.template.export`, `cmd:print.template.import`, `crates/ui-egui/src/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; Export… writes a template to a `.lcprint` file and Import… adds one from such a file (checked like a saved template; a name already in use gets " (2)"); no built-in templates, no folders | | LRC-WEB-LAYOUT | Web gallery layouts | OOS | 🚫 | | | | LRC-WEB-SITEINFO | Web gallery site info | OOS | 🚫 | | | | LRC-WEB-COLOR | Web gallery colours | OOS | 🚫 | | | @@ -779,9 +780,9 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | KEYC-SECONDWINDOW | Classic secondary-window keys | P2 | ⬜ | | | | KEYC-CATALOG | Classic photo/catalog keys (⇧⌘I, ⌘', ⌘R, F2, ⌫, ⇧⌘E…) | P2 | ✅ | `cmd:library.import`, `cmd:photo.delete`, `cmd:photo.virtualCopy`, `cmd:app.showInFinder`, `cmd:dialog.rename`, `cmd:photo.editInExternal` | ⇧⌘I add, ⌘' virtual copy, ⌘R show in Finder, F2 rename, ⌫ delete, ⇧⌘E external editor | | KEYC-COMPARE | Classic grid/compare keys (Z, Home/End, =/−, ⌘⇧D, S…) | P2 | 🟡 | `cmd:view.zoomToggle`, `cmd:view.thumbSizeUp`, `cmd:view.thumbSizeDown`, `crates/ui-egui/src/tests_zoom_keys.rs`, `cmd:library.select`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/tests_keymap.rs` (`home_and_end_select_the_ends_of_the_grid`, `shift_arrows_extend_the_grid_selection`) | Z toggles zoom; `=` / `-` (and `+`) step the grid thumbnail size by 30 pt within the bottom-bar slider's 90–480 range in Photo Grid, Square Grid and People (nothing in Detail, Compare, Survey or Reference; a text field keeps the keys; ⌘= / ⌘− still zoom); Home / End make the first / last photo of the view the active, selected one and ⇧← / ⇧→ add the previous / next photo to the selection (the added photo becomes active; nothing is ever removed; at either end nothing happens), in Photo Grid and Square Grid only: they wait in the other views, in the full-screen preview, while a text field or a dialog has the keyboard, and when the user gave the key to a command; no compare, stacks keys | -| KEYC-RATING | Classic rating/flag keys (1–5, ⇧1–5, 6–9, P, X, U, ⇧X, ⇧U, `[` `]`, \`, ⌘↑ ⌘↓) | P2 | 🟡 | `cmd:photo.rate`, `cmd:photo.pick`, `cmd:photo.flag`, `cmd:photo.cycleFlag`, `cmd:photo.increaseFlag`, `cmd:photo.decreaseFlag` | 0–5 / Shift+0–5 and 6–9 / Shift+6–9; P/X/U, Shift+X/U and grid Shift+P work; ` (backtick) cycles each selected photo's flag unflagged → pick → reject → unflagged and ⌘↑ / ⌘↓ (Ctrl on Windows/Linux) raise / lower it (reject < unflagged < pick, clamped); one undo step, Compare/Survey act on the active photo, Auto Advance follows; tests cover batch/undo, active Compare candidate and text focus; `\` shows / hides the Filter Bar in the grids (Show Original in Detail). Missing: Shift+P outside grids (Presets), ⌘L Enable Filters | +| KEYC-RATING | Classic rating/flag keys (1–5, ⇧1–5, 6–9, P, X, U, ⇧X, ⇧U, `[` `]`, \`, ⌘↑ ⌘↓) | P2 | 🟡 | `cmd:photo.rate`, `cmd:photo.pick`, `cmd:photo.flag`, `cmd:photo.cycleFlag`, `cmd:photo.increaseFlag`, `cmd:photo.decreaseFlag`, `cmd:library.toggleFilters` | 0–5 / Shift+0–5 and 6–9 / Shift+6–9; P/X/U, Shift+X/U and grid Shift+P work; ` (backtick) cycles each selected photo's flag unflagged → pick → reject → unflagged and ⌘↑ / ⌘↓ (Ctrl on Windows/Linux) raise / lower it (reject < unflagged < pick, clamped); one undo step, Compare/Survey act on the active photo, Auto Advance follows; tests cover batch/undo, active Compare candidate and text focus; `\` shows / hides the Filter Bar in the grids (Show Original in Detail); ⌘L (Ctrl+L) Enable Filters puts the filter aside and brings it back as it was. Missing: Shift+P outside grids (Presets) | | KEYC-COLLECTIONS | Classic collection keys (⌘N, B…) | P2 | 🟡 | `cmd:dialog.newAlbum` | ⌘N new album; no quick collection | -| KEYC-METADATA | Classic keyword/metadata keys (⌘K, ⌘S, ⌘⌥⇧C/V…) | P2 | 🟡 | `cmd:photo.saveMetadataToFile` | ⌘S saves metadata; no keyword sets, metadata copy/paste | +| KEYC-METADATA | Classic keyword/metadata keys (⌘K, ⌘S, ⌘⌥⇧C/V…) | P2 | 🟡 | `cmd:photo.saveMetadataToFile`, `cmd:photo.copyMetadata`, `cmd:photo.pasteMetadata`, `cmd:panel.addKeywords`, `cmd:keyword.toggleFromSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `crates/ui-egui/src/tests_keymap.rs` (`cmd_alt_shift_c_and_v_copy_and_paste_metadata`) | ⌘S saves metadata; ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V on Windows/Linux) copy the active photo's metadata and paste it on the selection; ⌘K (Ctrl+K) Add Keywords shows the Keywords panel with the cursor in its Add keyword box; ⌥1–⌥9 toggle the current keyword set's keywords, ⌥0 / ⌥⇧0 go to the next / previous set. Missing: ⌘⇧K, ⌘⌥⇧K, ⇧K, ⌘⌥K painting, ⌘⌥⇧F Visual Search, ⇧O Edit Face name (⇧O cycles the crop overlay here, and the mask overlay color while masking), and the macOS-only ⌘: / ⌘; spelling and ⌘⌥T Character palette | | KEYC-DEVELOP | Classic develop keys (V, ⌘U, ⇧⌘U, R, Q, K, M, ⇧M, ⇧W, ⇧J, ⇧Q…) | P2 | 🟡 | `cmd:develop.treatment`, `cmd:develop.reset`, `cmd:crop.reset` | V, ⇧⌘R, ⌥⌘R, W, J, Y, ⇧Y, \ match; R/K/M/⇧M differ; no Classic keymap layer | | KEYC-MODULE-OUTPUT | Book / slideshow / print / map / web keys | P2 | ⬜ | | modules not implemented | | KEYC-HELP | Classic help keys (⌘/, F1) | P2 | 🟡 | `cmd:app.shortcuts` | ⌘/ only | @@ -798,24 +799,50 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | +| 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | +| 2026-10-24 | patch | LR-LIB-RATING, LR-LIB-DELETE: a slider drag still open when a rating, flag or label takes the photo out of the view, or when the photo is deleted, ends as its own undo step before the selection moves on, as moving to the next photo does; LR-BEHAV-LOCALIZE lists all 18 languages; status unchanged | +| 2026-10-24 | patch | Integration batch 43: Integrated main 98702b5c, preserving the new fail-closed GPS metadata check for Original export. Watermark geometry/orientation and HDR JPEG size-limit fixes remain in their shared helpers; no feature-count changes. | +| 2026-10-23 | patch | Export integration: Integrated main 5ca49b3e, retaining Width & Height resizing, export format/bit-depth validation and batch panic cancellation alongside the existing watermark and HDR JPEG size-limit fixes. No feature-count changes. | +| 2026-10-23 | minor | LRC-LIB-CATALOG-SWITCH, LR-PREF-GENERAL: Settings ▸ General ▸ At launch (Open the last library / Ask me) with a launch window listing the recent libraries, Alt/Option at launch asks once, File ▸ Open Recent Library ▸ Remove from List and `app.recentLibraries {remove}` (issue #1290); photos dropped while no library is open wait for the one opened (presets are refused then); status and counts unchanged (✅) | +| 2026-10-23 | minor | LRC-LIB-CATALOG-IMPORT: Import Lightroom Catalog… (and Open Library's offer for a Lightroom catalog) asks whether the catalog merges into the open library or goes into a new library made next to it; Settings ▸ General or "Don't ask again" switches the question off; `file.importLightroom` takes `into` / `name` / `location` (#2672); status unchanged (🟡) | +| 2026-10-22 | minor | LR-VIEW-INFOOVERLAY: the info overlay shows the star rating and flag, and in the full-screen preview on macOS it starts below the window controls (issue #2460); status unchanged | +| 2026-10-22 | patch | KEY-GRID: both grid rows in View show the cycle shortcut and follow keymap changes; direct bindings and native accelerator ownership are preserved (#2500); status and counts unchanged | +| 2026-10-22 | minor | LRC-PRINT-LAYOUT: the Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) are selectable in the page setup and Print dialog and print to PDF at their metric sizes | +| 2026-10-22 | minor | #2052 (partial): shared export text adds only Thai faces after Inter and the existing CJK chain. Thai horizontal mark positioning remains incomplete; Arabic fallback is deferred until joining and bidi reordering exist. LR-EXP-WATERMARK reassessed as partial for these layout and font limits; UI fallback unchanged | +| 2026-10-24 | patch | LR-LIB-SMARTALBUM: relative-date view and source-count caches expire on the session-clock minute, including nested smart albums; held views retain expired photos until refresh and admit new matches; status and feature counts unchanged | +| 2026-10-22 | patch | LR-META-XMP: namespace URI determines ownership; foreign namespaces using recognized prefixes survive saves and cannot supply native settings or ratings; status and counts unchanged | +| 2026-10-22 | patch | LR-EXP-PSD, LR-META-EXIF-FULL: PSD/PSB imports and image resources 1058/1060 now supply EXIF and XMP to metadata readers and All Metadata; Original with Remove Location Info refuses detected PSD/PSB GPS; statuses and feature counts unchanged | +| 2026-10-21 | patch | LR-LIB-CAPTURETIME: a capture time that doesn't fully read is left as it is and counted (`unreadable`) instead of shifted into a wrong one; it can't anchor a set that moves other photos; status unchanged | | 2026-10-21 | patch | LR-IMP-ADD-DIALOG: reconcile #2362 with current main; deleted-album guard and hierarchical picker retained; counts unchanged | -| 2026-10-20 | minor | LR-IMP-ADD-DIALOG: #2362 gives the import review the shared hierarchy/search album picker while retaining None/New album and existing destination IDs; status and feature counts unchanged | | 2026-10-21 | patch | KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the slider's row; leaving it (even between two frames) or Tab focus alone does not arm them (issue #1355); status unchanged | | 2026-10-21 | minor | KEYC-PANELS: F8 shows / hides the right panel (`view.rightPanel`), with F6 / F7 already bound; ⬜ → 🟡 | +| 2026-10-20 | patch | Graphic watermark inset regression: Oversized graphics fit the space remaining after the applicable anchor insets, with one aspect-preserving scale before quarter-turn rotation. Centered axes continue to ignore insets. Pixel-bound regressions cover edge/corner anchors, centered placement and all four rotations. Main d999e382 is integrated; HDR size-limit and EXIF-orientation fixes are unchanged. | +| 2026-10-20 | minor | LR-IMP-ADD-DIALOG: #2362 gives the import review the shared hierarchy/search album picker while retaining None/New album and existing destination IDs; status and feature counts unchanged | | 2026-10-20 | minor | LR-PRE-PANEL: the preset applied to a photo is marked again (with its Amount slider) on returning to the photo, until the photo is edited further (#2392); status unchanged (✅) | | 2026-10-20 | minor | LR-MASK-OVERLAY: creating, picking, duplicating or adding to a mask shows the overlay a mask slider hid (#1800); status unchanged (✅) | | 2026-10-20 | patch | LRC-LIB-COMPARE, LR-VIEW-SURVEY: in Compare and Survey the Info panel's stars and colour labels and the Set Color Label menu act on the active photo only (they labelled the whole selection), and the panes show the colour label (#2398); statuses unchanged | | 2026-10-20 | patch | LR-VIEW-ZOOM: the 20 ms rule clears a slow-drag verdict only on a drag timed at full size; a drag that drafts small leaves it unchanged, as the code does; status unchanged | +| 2026-10-19 | minor | LR-CROP-ASPECT: Lock Aspect Ratio is its own row in Help ▸ Keyboard Shortcuts (`crop.lockAspect`, default A, sharing A with Visualize Spots as a contextual pair); statuses unchanged (✅) (`tests_keymap` `lock_aspect_ratio_is_a_listed_row_on_a`, `a_is_the_aspect_lock_under_crop_and_visualize_spots_elsewhere`) | +| 2026-10-19 | patch | LR-LIB-RATING: a rating, flag or label that takes the active photo out of the view makes the photo after it active instead of leaving an unseen photo active (→ then went to the view's first photo), and Shift / Auto Advance doesn't step past it (#2312); status unchanged (✅) | +| 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling's burst gap and similarity are adjustable (dialog, `photo.analyze` `burstGap` / `similarity`; #2275). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-CROP-RECT: on a straightened photo a moved crop slides along the tilted edges, so a box that fills the photo's height reaches its sides (#2299); status unchanged | | 2026-10-19 | patch | LR-VIEW-ZOOM: the slow slider-drag verdict is described as per photo and control, as the code keys it; status unchanged | +| 2026-10-18 | patch | Export regression integration (maintenance): Graphic watermarks honour EXIF rotation/mirroring through the shared `read_graphic` path and keep their aspect ratio when fitted to the output. HDR JPEG `limitKb` includes the gain map and metadata. Refreshed onto main fb7ac08b, retaining upstream export bounds, colour metadata, JPEG encoding and opaque RGB/real-alpha handling (#1691); no feature-count or readiness estimate changes. | | 2026-10-18 | patch | LR-META-XMP: Lightroom's profile and version bookkeeping (`CompatibleVersion`, profile digests, lens profile identity, `CropConstrainToUnitSquare`, default-strength lens profile scales) is no longer reported as unimported XMP; status unchanged (✅) | +| 2026-10-17 | minor | MENU-VIEW-DETAIL, MENU-VIEW-EDIT, MENU-VIEW-CLIPPING, MENU-VIEW-MASKOVERLAY, MENU-VIEW-PHOTOCOUNT, MENU-VIEW-BEFOREAFTER, LR-VIEW-FOCUSPOINT: menu labels renamed: switches are named for what they show (Photo Counts, Focus Point, Clipping, Mask Overlay, All Mask Overlays, Mask Pins, Layout Image), View ▸ Detail is Detail View, Window ▸ Edit is Edit Panel, Compare Before and After is Before/After Side by Side, Clear Preview Cache is Discard Preview Cache; shortcuts and commands unchanged; statuses unchanged | +| 2026-10-17 | minor | LR-IMP-DRAGDROP: files dragged over the window show what dropping will do, and dropped photos and folders open the import review (Settings ▸ Import can import them at once); a drop while a dialog is open or an import is running is refused; a finished scan no longer replaces an open dialog; the web build tells the person when a dropped file can't be read or imported. LR-BEHAV-EMPTY-STATES, LR-BEHAV-DRAGDROP: text updated; status unchanged (✅) | +| 2026-10-16 | patch | LR-BEHAV-BG-TASKS: progress bars and spinners come from one component (`progress.rs`): the activity stack, model downloads, denoise and the face scan share it; busy buttons and a themed thumbnail placeholder added; status unchanged | +| 2026-10-15 | patch | LR-BEHAV-LOCALIZE: cites `docs/localization-pl.md` (Polish format messages finished, counts right for every number); status unchanged (🟡) | | 2026-10-15 | minor | LR-VIEW-ZOOM: a slow slider-drag verdict needs two drags over 20 ms and expires after 30 s (doubling to 240 s); hidden-window frame times are ignored; the slow set forgets its oldest entry, not all (issue #330); status unchanged | | 2026-10-15 | minor | LR-BEHAV-BG-TASKS: Reload from Disk reads its files on a worker thread with a cancellable activity row instead of freezing the window on a selection of raws; its result is committed through the command wrapper (XMP sidecars auto-written as before) and an older reload finishing late no longer overwrites a newer one; status unchanged (✅) | | 2026-10-19 | patch | LR-LIB-STACK: the filmstrip's stack badge expands / collapses the stack like the grid's, and a badge click works on a stack that isn't selected (it is selected first). Statuses and feature counts unchanged. | +| 2026-10-14 | minor | LR-VIEW-ZOOM: Visualize Spots, Point Color range and Visualize HDR render zoom windows; LRC-DEV-SOFTPROOF: output-space proofs on the GPU | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | +| 2026-10-13 | minor | LRC-LIB-KEYWORDS: the Keyword List marks a keyword that has an applied keyword inside it (a dot in its box); status unchanged | | 2026-10-12 | minor | LR-IMP-FORMATS: folder discovery includes SR2/SRF; MCP and CLI reuse the engine extension list. DSC-F828 remains preview-only; decoder support and row status unchanged | | 2026-10-15 | patch | KEYC-RATING: `\` shows / hides the Filter Bar in Photo Grid and Square Grid (Show Original in Detail); status unchanged (🟡) | | 2026-10-12 | minor | LR-EDIT-OPTICS-PROFILE: Sony ARW shading, CA and distortion tables decoded with settings and provenance (raw IFD, `SR2SubIFD` fallback); applied corrections unchanged (ILCE-7RM4A and ILCE-7RM6 distortion); status unchanged (🟡) | @@ -927,3 +954,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-16 | minor | LR-VIEW-PHOTOGRID: when the photos shown change by those an edit touched (an import's batch, a capture time, a crop), the grid reads only those photos' dates and shapes again instead of every photo of the list (a 16-photo batch at 181,749 photos: grid frame 101 ms → 7 ms); status unchanged | | 2026-10-19 | minor | LRC-LIB-LIBFOLDERS: the sidebar trees indent by a narrower step (14 / 12 / 10 / 8 pt) when the deepest open row would not fit the panel, instead of cutting its name or scrolling sideways at once (issue #2298); status unchanged (✅) | | 2026-10-15 | patch | LR-EXP-DIM: Width & Height (`fit: widthHeight`) limits the width and the height as the photo stands, beside Dimensions (W × H, either orientation), as in Lightroom (#1620); status unchanged (✅) | +| 2026-10-22 | minor | MENU-BAR: on macOS the native menu gives a key back to the window while a text field has focus or a shortcut is being recorded (muda's `set_accelerator(None)` does nothing there, so the menu item is now swapped for one without a key, and the key is put back on that item afterwards); status unchanged (✅) | +| 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | +| 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | +| 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index 2923ea8803..bd17a3d32b 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -46,11 +46,11 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange version. The year a model was added is approximated from that Camera Raw major version. - **What we decode**: the decoders and their refusals in `crates/raw/src` (`lib.rs` routing, `vendor/*.rs` coding variants, `crx.rs` CRX limits, `orf.rs` / `srw.rs` compressed refusals), the import list - `lightcraft_engine::import::EXTENSIONS`, and `KNOWN_UNSUPPORTED` in `crates/raw/tests/corpus.rs`. Doc + `lightcraft_engine::import::EXTENSIONS`, and `KNOWN_UNSUPPORTED` in `crates/raw/tests/it/corpus.rs`. Doc claims were not used. - **Verified** means a real file from that body decoded from sensor data in: the corpus test over the `RAW_SAMPLES` manifest (`xtask/src/main.rs`, 105 CC0 files; bodies whose sample is in - `KNOWN_UNSUPPORTED` excluded), `crates/raw/tests/cr3_corpus.rs` (3 bodies exact against an external decoder; + `KNOWN_UNSUPPORTED` excluded), `crates/raw/tests/it/cr3_corpus.rs` (3 bodies exact against an external decoder; the EOS R5 Mark II pinned, with a QP-map check of 33,665 private files; 22 more bodies pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each)), the RAF reference check ([raf-compression.md](raf-compression.md)), and the raw.pixls.us bulk checks recorded in issue @@ -64,7 +64,7 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange decoded on main `25ef65c8`; [raw/coverage-sweep.tsv](raw/coverage-sweep.tsv) records the URLs, SHA-256, dimensions, FNV-1a sensor hashes and render/reference luminance correlations (0.6801 to 0.9998). The hashes pin LightCraft's own output. The regression test is - `crates/raw/tests/coverage_sweep_corpus.rs`; downloads are in `RAW_SAMPLES`. Ten references are + `crates/raw/tests/it/coverage_sweep_corpus.rs`; downloads are in `RAW_SAMPLES`. Ten references are embedded TIFF images; the rest are JPEGs. FFF TIFF previews are not display-ready and check image structure only. Eleven candidate models were excluded for identity, provenance or missing/mismatched reference images. D6 / Z 6 / Z 7 verification covers compressed NEF only; diff --git a/docs/raw-preview-reads.md b/docs/raw-preview-reads.md index a16b9a3332..5d2467da72 100644 --- a/docs/raw-preview-reads.md +++ b/docs/raw-preview-reads.md @@ -144,15 +144,15 @@ use the largest JPEG, so their geometry and colour do not depend on the size lev sRGB stays on the fast path. A synthetic DNG with a full-size and a half-size JPEG gets, on the plan path, the half-size one for a box it covers and the full-size one otherwise, with the same pixels as the whole-file path (`preview_loading_plans_the_smallest_covering_jpeg`). -- `crates/raw/tests/sparse_corpus.rs`: `preview_plan` is asked for **every** corpus file, not only +- `crates/raw/tests/it/sparse_corpus.rs`: `preview_plan` is asked for **every** corpus file, not only the ones whose header plan is `Ready`, and the preview it yields must equal the whole file's with the skipped bytes `0` and `0xFF`. The test prints what each format reads. -- `crates/engine/tests/preview_read.rs` (opt-in, `#[ignore]`): the same measurement on a **real** +- `crates/engine/tests/it/preview_read.rs` (opt-in, `#[ignore]`): the same measurement on a **real** file, typically on a share: ```sh LC_PREVIEW_RAW="/mnt/nas/…/DSCF0001.RAF" \ - cargo test --release -p lightcraft-engine --test preview_read -- --ignored --nocapture + cargo test --release -p lightcraft-engine --test it preview_read:: -- --ignored --nocapture ``` No raw fixture is committed (media never is, see `AGENTS.md`). diff --git a/docs/raw/coverage.py b/docs/raw/coverage.py index a9a5f521fe..3db93ce812 100644 --- a/docs/raw/coverage.py +++ b/docs/raw/coverage.py @@ -29,7 +29,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) # Olympus ORF bodies that write uncompressed / packed data (crates/raw/src/vendor/orf.rs). Everything else # writes compressed ORF, which is preview-only (the E-M5 II / PEN-F high-res mode alone is decoded). -ORF_DECODED = re.compile(r"^(E-1|E-10|E-20|EVOLT E-300|EVOLT E-330|EVOLT E-400|EVOLT E-500|E-300|E-330|E-500|Camedia C-\S+.*|Stylus XZ-2 iHS)$") +ORF_DECODED = re.compile(r"^(E-1|E-10|E-20|EVOLT E-300|EVOLT E-330|EVOLT E-400|EVOLT E-500|E-300|E-330|E-500|Camedia C-\S.*|Stylus XZ-2 iHS)$") # Samsung SRW bodies with compressed raw data (crates/raw/src/vendor/srw.rs refuses 32770 / 32772 / 32773). SRW_COMPRESSED = re.compile(r"(^|\W)(NX1|NX30|NX300|NX300M|NX500|NX2000|NX3000|NX3300|NX mini|EK-GN\d+|EK-KN\d+)(\W|$)") # Fujifilm bodies before the X series whose RAF has no raw IFD (crates/raw/src/vendor/raf.rs). @@ -123,7 +123,7 @@ def main(): classes = ["verified", "unverified", "preview", "unsupported"] by_maker = {} for r in rows: - by_maker.setdefault(r["maker"], {c: 0 for c in classes})[r["class"]] += 1 + by_maker.setdefault(r["maker"], dict.fromkeys(classes, 0))[r["class"]] += 1 print("| Maker | Adobe models | verified | unverified | preview | unsupported |") print("|---|---:|---:|---:|---:|---:|") for m, c in sorted(by_maker.items(), key=lambda kv: -sum(kv[1].values())): diff --git a/docs/raw/coverage.tsv b/docs/raw/coverage.tsv index cc58084718..c062ea95e2 100644 --- a/docs/raw/coverage.tsv +++ b/docs/raw/coverage.tsv @@ -73,7 +73,7 @@ Apple iPhone 12 Mini Rear Wide Camera DNG 2020 unverified DNG decoder (uncompres Apple iPhone 12 Ultrawide camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone 12 Mini Ultrawide camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone 12 Pro Front Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Apple iPhone 12 Pro Rear Wide Camera DNG 2020 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Apple iPhone 12 Pro Rear Wide Camera DNG 2020 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Apple iPhone 12 Pro Rear Telephoto Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone 12 Pro Rear Ultra Wide Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone 12 Pro Max Front Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -97,16 +97,16 @@ Apple iPad Pro 12.9-inch (2018 model) DNG 2018 unverified DNG decoder (uncompres Apple iPad Pro 13-inch M4 (2024 version) Wide Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPad mini (6th Generation) Rear Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone 6s DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Apple iPhone 6s Plus DNG 2015 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Apple iPhone 6s Plus DNG 2015 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Apple iPhone 7 DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Apple iPhone 7 Plus DNG 2015 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Apple iPhone 7 Plus DNG 2015 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Apple iPhone 8 DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone 8 Plus DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone SE (2020 version) DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone SE DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone X DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone XR DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Apple iPhone XS DNG 2018 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Apple iPhone XS DNG 2018 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Apple iPhone XS Max DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPad Air (5th generation) Rear Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Apple iPhone SE (3rd generation) Front Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -116,117 +116,117 @@ Apple iPad mini (A17 Pro) Rear Camera DNG 2024 unverified DNG decoder (uncompres Canon EOS-1D TIF 2003 unsupported TIF is not imported Canon EOS-1D C CR2 2012 unverified CR2 lossless JPEG decoder Canon EOS-1D Mark II CR2 2003 unverified CR2 lossless JPEG decoder -Canon EOS-1D Mark II N CR2 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-1D Mark III CR2 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-1D Mark IV CR2 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D Mark II N CR2 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D Mark III CR2 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D Mark IV CR2 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS-1Ds TIF 2003 unsupported TIF is not imported Canon EOS-1Ds Mark II CR2 2005 unverified CR2 lossless JPEG decoder Canon EOS-1Ds Mark III CR2 2007 unverified CR2 lossless JPEG decoder Canon EOS-1D X CR2 2012 unverified CR2 lossless JPEG decoder -Canon EOS-1D X Mark II CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-1D X Mark III CR3 2019 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS 5D CR2 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 5D Mark II CR2 2008 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS-5D Mark III CR2 2012 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS-5D Mark IV (** see note) CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 5DS CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 5DS R CR2 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 6D CR2 2012 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 6D Mark II CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 7D CR2 2008 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 7D Mark II CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D X Mark II CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D X Mark III CR3 2019 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS 5D CR2 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 5D Mark II CR2 2008 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS-5D Mark III CR2 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS-5D Mark IV (** see note) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 5DS CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 5DS R CR2 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 6D CR2 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 6D Mark II CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 7D CR2 2008 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 7D Mark II CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 10D CRW 2003 preview CRW is opened from its embedded JPEG only -Canon EOS 20D CR2 2003 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 20D CR2 2003 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 20Da CR2 2005 unverified CR2 lossless JPEG decoder -Canon EOS 30D CR2 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 40D CR2 2007 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 50D CR2 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 60D CR2 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 30D CR2 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 40D CR2 2007 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 50D CR2 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 60D CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS 60Da CR2 2012 unverified CR2 lossless JPEG decoder -Canon EOS 70D CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 77D (EOS 9000D) CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 80D CR2 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 90D CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS 200D (EOS Kiss X9, EOS Rebel SL2) CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 250D (EOS Rebel SL3, EOS 200D II, EOS Kiss X10) CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS 70D CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 77D (EOS 9000D) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 80D CR2 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 90D CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS 200D (EOS Kiss X9, EOS Rebel SL2) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 250D (EOS Rebel SL3, EOS 200D II, EOS Kiss X10) CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS D30 CRW 2003 preview CRW is opened from its embedded JPEG only Canon EOS D60 CRW 2003 preview CRW is opened from its embedded JPEG only Canon EOS 300D (EOS Digital Rebel, EOS Kiss Digital) CRW 2003 preview CRW is opened from its embedded JPEG only -Canon EOS 100D (EOS Digital Rebel SL1, EOS Kiss X7) CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 500D (EOS Digital Rebel T1i, EOS Kiss X3 Digital) CR2 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 550D (EOS Digital Rebel T2i, EOS Kiss X4 Digital) CR2 2010 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 1100D (EOS Digital Rebel T3, EOS Kiss X50 Digital) CR2 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 600D (EOS Digital Rebel T3i, EOS Kiss X5 Digital) CR2 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 650D (EOS Digital Rebel T4i, EOS Kiss X4i) CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 700D (EOS Digital Rebel T5i, EOS Kiss X7i) CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1200D (EOS Digital Rebel T5, EOS Kiss X70) CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1300D (EOS Digital Rebel T6, EOS Kiss X80) CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1500D (EOS Rebel T7, EOS Kiss X90, EOS 2000D) CR2 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 3000D (EOS Rebel T100, EOS 4000D) CR2 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 750D (EOS Digital Rebel T6i, EOS Kiss X8i) CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 760D (EOS Digital Rebel T6s, EOS Kiss 8000D) CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 800D (EOS Digital Rebel T7i, EOS Kiss X9i) CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 850D (EOS Kiss X10i, EOS Rebel T8i) CR3 2019 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS 1000D (EOS Digital Rebel XS, EOS Kiss F) CR2 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 450D (EOS Digital Rebel XSi, EOS Kiss Digital X2) CR2 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 350D (EOS Digital Rebel XT, EOS Kiss Digital N) CR2 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 400D (EOS Digital Rebel XTi, EOS Kiss Digital X) CR2 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 100D (EOS Digital Rebel SL1, EOS Kiss X7) CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 500D (EOS Digital Rebel T1i, EOS Kiss X3 Digital) CR2 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 550D (EOS Digital Rebel T2i, EOS Kiss X4 Digital) CR2 2010 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 1100D (EOS Digital Rebel T3, EOS Kiss X50 Digital) CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 600D (EOS Digital Rebel T3i, EOS Kiss X5 Digital) CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 650D (EOS Digital Rebel T4i, EOS Kiss X4i) CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 700D (EOS Digital Rebel T5i, EOS Kiss X7i) CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1200D (EOS Digital Rebel T5, EOS Kiss X70) CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1300D (EOS Digital Rebel T6, EOS Kiss X80) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1500D (EOS Rebel T7, EOS Kiss X90, EOS 2000D) CR2 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 3000D (EOS Rebel T100, EOS 4000D) CR2 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 750D (EOS Digital Rebel T6i, EOS Kiss X8i) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 760D (EOS Digital Rebel T6s, EOS Kiss 8000D) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 800D (EOS Digital Rebel T7i, EOS Kiss X9i) CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 850D (EOS Kiss X10i, EOS Rebel T8i) CR3 2019 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS 1000D (EOS Digital Rebel XS, EOS Kiss F) CR2 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 450D (EOS Digital Rebel XSi, EOS Kiss Digital X2) CR2 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 350D (EOS Digital Rebel XT, EOS Kiss Digital N) CR2 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 400D (EOS Digital Rebel XTi, EOS Kiss Digital X) CR2 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon EOS C50 CR3 2025 unverified CRX decoder: lossless and C-RAW 0x100 / 0x200 single-tile; other variants fall back to the preview -Canon EOS M CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M2 CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M200 CR3 2019 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS M3 CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M5 CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M50 Mark II CR3 2020 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS M6 CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M6 Mark II CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS M10 CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M50 (EOS Kiss M) CR3 2017 verified corpus: crates/raw/tests/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) -Canon EOS M100 CR2 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS R (** see note) CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS M CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M2 CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M200 CR3 2019 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS M3 CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M5 CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M50 Mark II CR3 2020 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS M6 CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M6 Mark II CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS M10 CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M50 (EOS Kiss M) CR3 2017 verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) +Canon EOS M100 CR2 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS R (** see note) CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS R1 CR3 2023 unverified CRX decoder: lossless and C-RAW 0x100 / 0x200 single-tile; other variants fall back to the preview -Canon EOS R3 CR3 2021 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R5 CR3 2019 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R3 CR3 2021 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R5 CR3 2019 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS R5 C CR3 2021 unverified CRX decoder: lossless and C-RAW 0x100 / 0x200 single-tile; other variants fall back to the preview -Canon EOS R5 Mark II CR3 2023 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hashes, docs/cr3.md); bulk: QP maps of 33,665 C-RAW files -Canon EOS R6 CR3 2019 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R5 Mark II CR3 2023 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hashes, docs/cr3.md); bulk: QP maps of 33,665 C-RAW files +Canon EOS R6 CR3 2019 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS R6 V CR3 2025 unverified CRX decoder: lossless and C-RAW 0x100 / 0x200 single-tile; other variants fall back to the preview -Canon EOS R6 Mark II CR3 2022 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; C-RAW with adaptive QP above 168 still opens as the preview) -Canon EOS R6 Mark III CR3 2025 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R7 CR3 2021 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; lossless only, C-RAW unverified) +Canon EOS R6 Mark II CR3 2022 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; C-RAW with adaptive QP above 168 still opens as the preview) +Canon EOS R6 Mark III CR3 2025 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R7 CR3 2021 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; lossless only, C-RAW unverified) Canon EOS R8 Mark II CR3 2025 unverified CRX decoder: lossless and C-RAW 0x100 / 0x200 single-tile; other variants fall back to the preview -Canon EOS R10 CR3 2021 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R10 CR3 2021 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon EOS Ra CR3 2019 unverified CRX decoder: lossless and C-RAW 0x100 / 0x200 single-tile; other variants fall back to the preview -Canon EOS RP CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R8 CR3 2022 verified corpus: crates/raw/tests/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) -Canon EOS R50 CR3 2022 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R50 V CR3 2024 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R100 CR3 2022 verified corpus: crates/raw/tests/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) +Canon EOS RP CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R8 CR3 2022 verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) +Canon EOS R50 CR3 2022 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R50 V CR3 2024 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R100 CR3 2022 verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) Canon PowerShot 600 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot A5 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot A50 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot G1 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot G1 X CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G1 X Mark II CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G1 X Mark III CR2 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G1 X CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G1 X Mark II CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G1 X Mark III CR2 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G2 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot G3 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot G3 X CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G3 X CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G5 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot G5 X CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G5 X Mark II CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot G5 X CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G5 X Mark II CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Canon PowerShot G6 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot G7 X CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G7 X Mark II CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G7 X Mark III CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon PowerShot G9 CR2 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G9X CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G9 X Mark II CR2 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G7 X CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G7 X Mark II CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G7 X Mark III CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot G9 CR2 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G9X CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G9 X Mark II CR2 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot G10 CR2 2008 unverified CR2 lossless JPEG decoder -Canon PowerShot G11 CR2 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G12 CR2 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G15 CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G16 CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G11 CR2 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G12 CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G15 CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G16 CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot Pro 1 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot Pro70 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot Pro90 IS CRW 2003 preview CRW is opened from its embedded JPEG only @@ -236,17 +236,17 @@ Canon PowerShot S45 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot S50 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot S60 CRW 2003 preview CRW is opened from its embedded JPEG only Canon PowerShot S90 CR2 2008 unverified CR2 lossless JPEG decoder -Canon PowerShot S95 CR2 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S95 CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot S70 CRW 2003 preview CRW is opened from its embedded JPEG only -Canon PowerShot S100 CR2 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S100V CR2 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S110 CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S120 CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S100 CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S100V CR2 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S110 CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S120 CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Canon PowerShot SX1 IS CR2 2008 unverified CR2 lossless JPEG decoder -Canon PowerShot SX50 CR2 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot SX60 HS CR2 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot SX70 HS CR3 2018 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon PowerShot V1 CR3 2024 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot SX50 CR2 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot SX60 HS CR2 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot SX70 HS CR3 2018 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot V1 CR3 2024 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) Casio EXILIM EX-10 DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Casio EXILIM EX-100 DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Casio EXILIM EX-100F DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -274,9 +274,9 @@ Casio EXILIM EX-ZR4100 DNG 2017 unverified DNG decoder (uncompressed, LJ92, loss Casio EXILIM EX-ZR5000 DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Casio EXILIM EX-ZR5100 DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Contax N Digital RAW 2003 preview RAW is opened from its embedded JPEG only -DJI DJI Mavic 2 Pro (Hasselblad L1D-20c) DNG 2020 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mavic 2 Pro (Hasselblad L1D-20c) DNG 2020 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) DJI DJI AIR 2S DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -DJI DJI Mini 2 DNG 2020 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mini 2 DNG 2020 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) DJI DJI Air 3 Wide Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Air 3 Telephoto Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Mini 3 Pro DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -287,48 +287,48 @@ DJI DJI Mavic 3 Cine (Hasselblad L2D-20c) DNG 2023 unverified DNG decoder (uncom DJI DJI Mavic 3 Pro Super Telephoto Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Mavic 3 Pro Telephoto Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Mavic 3 Pro (Hasselblad L2D-20c) DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -DJI DJI Mavic 3 (Hasselblad L2D-20c) DNG 2023 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mavic 3 (Hasselblad L2D-20c) DNG 2023 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) DJI DJI Osmo Pocket 3 D DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Air 3S Telephoto Camera DNG 2024 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Air 3S Wide Camera DNG 2024 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Osmo Action 5 Pro DNG 2024 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DJI DJI Mavic 4 Pro (DJI FC9284) DNG 2025 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -DJI DJI Mavic 4 Pro (DJI FC9287) DNG 2025 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mavic 4 Pro (DJI FC9287) DNG 2025 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) DJI DJI Mavic 4 Pro (Hasselblad L3D-100c) DNG 2025 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) DxO DxO ONE DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Epson R-D1 ERF 2003 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Epson R-D1s ERF 2005 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Epson R-D1x ERF 2008 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm GFX 50R RAF 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 50S RAF 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm GFX 50S II RAF 2020 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 100 RAF 2018 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm GFX 100 II RAF 2022 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Epson R-D1 ERF 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Epson R-D1s ERF 2005 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Epson R-D1x ERF 2008 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 50R RAF 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 50S RAF 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 50S II RAF 2020 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 100 RAF 2018 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 100 II RAF 2022 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm GFX 100 II IR RAF 2024 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) Fujifilm GFX 100 IR RAF 2020 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) -Fujifilm GFX 100S RAF 2020 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm GFX 100S II RAF 2023 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 100RF (Final Support) RAF 2024 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 100S RAF 2020 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 100S II RAF 2023 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 100RF (Final Support) RAF 2024 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Fujifilm FinePix E900 RAF 2005 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix F505 EXR RAF 2012 preview pre-X FinePix RAF without a raw IFD -Fujifilm FinePix F550 EXR RAF 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix F550 EXR RAF 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm FinePix F600 EXR RAF 2010 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix F605 EXR RAF 2012 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix F700 RAF 2003 preview pre-X FinePix RAF without a raw IFD -Fujifilm FinePix F770 EXR RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix F770 EXR RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm FinePix F775 EXR RAF 2012 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix F800 EXR RAF 2012 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix F900 EXR RAF 2012 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix HS10 RAF 2010 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) Fujifilm FinePix HS20 EXR RAF 2010 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) Fujifilm FinePix HS22 EXR RAF 2013 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) -Fujifilm FinePix HS30 EXR RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix HS33 EXR RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix HS30 EXR RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix HS33 EXR RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm FinePix HS35 EXR RAF 2013 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) -Fujifilm FinePix HS50 EXR RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix HS50 EXR RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm FinePix IS-1 RAF 2007 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix IS Pro RAF 2008 preview pre-X FinePix RAF without a raw IFD -Fujifilm FinePix S1 RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix S1 RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm FinePix S100fs RAF 2007 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix S2 Pro RAF 2003 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix S20 Pro RAF 2003 preview pre-X FinePix RAF without a raw IFD @@ -342,64 +342,64 @@ Fujifilm FinePix S6000fd (FinePix S6500fd) RAF 2005 preview pre-X FinePix RAF wi Fujifilm FinePix S7000 Z RAF 2003 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix S9000 (FinePix S9500) RAF 2005 preview pre-X FinePix RAF without a raw IFD Fujifilm FinePix S9100 (FinePix S9600) RAF 2005 preview pre-X FinePix RAF without a raw IFD -Fujifilm FinePix SL1000 RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X10 RAF 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X100 RAF 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X-M1 RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X-S1 RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100F RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100S RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100T RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100V** RAF 2019 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100VI RAF 2023 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X20 RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X30 RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X70 RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A1 RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A2 RAF 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-A3 RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A5 RAF 2017 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-A7 RAF 2018 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A10 RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix SL1000 RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X10 RAF 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X100 RAF 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X-M1 RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X-S1 RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100F RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100S RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100T RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100V** RAF 2019 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100VI RAF 2023 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X20 RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X30 RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X70 RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A1 RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A2 RAF 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-A3 RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A5 RAF 2017 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-A7 RAF 2018 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A10 RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm X-A20 RAF 2017 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) -Fujifilm X-E1 RAF 2012 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-E2 RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E2S RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E3 RAF 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E4 RAF 2020 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E5 RAF 2024 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-H1 RAF 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E1 RAF 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-E2 RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E2S RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E3 RAF 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E4 RAF 2020 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E5 RAF 2024 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-H1 RAF 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm X-H2 IR RAF 2024 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) Fujifilm X-H2S RAF 2021 verified docs/raf-compression.md (supplied files, exact sensor arrays) -Fujifilm X-M5 RAF 2024 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-Pro1 RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-Pro2 RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-Pro3** RAF 2019 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-S10 RAF 2020 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-S20 RAF 2022 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T1 RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-M5 RAF 2024 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-Pro1 RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-Pro2 RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-Pro3** RAF 2019 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-S10 RAF 2020 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-S20 RAF 2022 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T1 RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Fujifilm X-T1 IR RAF 2015 unverified RAF decoder (uncompressed, lossless / lossy compressed, Bayer and X-Trans) -Fujifilm X-T2 RAF 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T3 RAF 2018 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T4** RAF 2019 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T5 RAF 2022 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T10 RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T20 RAF 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T30 RAF 2018 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T30 II RAF 2021 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T30 III RAF 2022 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T50 RAF 2023 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T100 RAF 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T200 RAF 2019 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XF1 RAF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XF10 RAF 2017 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XQ1 RAF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XQ2 RAF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-H2 RAF 2021 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T2 RAF 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T3 RAF 2018 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T4** RAF 2019 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T5 RAF 2022 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T10 RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T20 RAF 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T30 RAF 2018 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T30 II RAF 2021 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T30 III RAF 2022 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T50 RAF 2023 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T100 RAF 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T200 RAF 2019 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XF1 RAF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XF10 RAF 2017 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XQ1 RAF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XQ2 RAF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-H2 RAF 2021 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Google Pixel DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel XL DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 2 DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Google Pixel 2 XL DNG 2017 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Google Pixel 2 XL DNG 2017 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Google Pixel 3 DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 3 Front Standard Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 3 Front Wide Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -407,7 +407,7 @@ Google Pixel 3 XL DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, De Google Pixel 3 XL Front Standard Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 3 XL Front Wide Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 4 DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Google Pixel 4 XL DNG 2019 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 4 XL DNG 2019 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Google Pixel 5 Front Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 5 Rear Main Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 5 Rear Ultra Wide Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -415,7 +415,7 @@ Google Pixel 6 Front Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, Google Pixel 6 Rear Main Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 6 Rear Ultrawide Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 6 Pro Front Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Google Pixel 6 Pro Rear Main Camera DNG 2021 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 6 Pro Rear Main Camera DNG 2021 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Google Pixel 6 Pro Rear Telephoto Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 6 Pro Rear Ultrawide Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 7 Front Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -426,7 +426,7 @@ Google Pixel 7 Pro Telephoto Camera DNG 2022 unverified DNG decoder (uncompresse Google Pixel 7 Pro Ultrawide Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 7 Pro Wide Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 4a Front Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Google Pixel 4a Rear Wide Camera DNG 2022 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 4a Rear Wide Camera DNG 2022 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Google Pixel 5a Front Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 5a Rear Main Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 5a Rear Ultra Wide Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -442,7 +442,7 @@ Google Pixel 8 Wide Camera* DNG 2023 unverified DNG decoder (uncompressed, LJ92, Google Pixel 8 Pro Front Camera* DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 8 Pro Telephoto Camera* DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 8 Pro Ultrawide Camera* DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Google Pixel 8 Pro Wide Camera* DNG 2023 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 8 Pro Wide Camera* DNG 2023 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Google Pixel 8a Front Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 8a Ultrawide Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Google Pixel 8a Wide Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -502,7 +502,7 @@ Hasselblad CF-39MS 3FR 2008 preview 3FR is opened from its embedded JPEG only Hasselblad CFH-22 3FR 2008 preview 3FR is opened from its embedded JPEG only Hasselblad CFH-39 3FR 2008 preview 3FR is opened from its embedded JPEG only Hasselblad CFV 3FR 2008 preview 3FR is opened from its embedded JPEG only -Hasselblad CFV-50c 3FR 2008 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad CFV-50c 3FR 2008 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration Hasselblad H2D DNG 2003 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Hasselblad H2D-22 3FR 2008 preview 3FR is opened from its embedded JPEG only Hasselblad H2D-39 3FR 2008 preview 3FR is opened from its embedded JPEG only @@ -515,18 +515,18 @@ Hasselblad H3DII-39MS 3FR 2008 preview 3FR is opened from its embedded JPEG only Hasselblad H3DII-50 3FR 2008 preview 3FR is opened from its embedded JPEG only Hasselblad H4D-40 3FR 2010 preview 3FR is opened from its embedded JPEG only Hasselblad H4D-60 3FR 2010 preview 3FR is opened from its embedded JPEG only -Hasselblad H5D-40 3FR 2012 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad H5D-40 3FR 2012 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration Hasselblad H5D-50 3FR 2012 preview 3FR is opened from its embedded JPEG only -Hasselblad H5D-50c 3FR 2013 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad H5D-50c 3FR 2013 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration Hasselblad H5D-60 3FR 2013 preview 3FR is opened from its embedded JPEG only Hasselblad H6D-100c 3FR 2015 preview 3FR is opened from its embedded JPEG only Hasselblad HV ARW 2013 unverified ARW decoder (uncompressed, cRAW, packed 12-bit, lossless, downsized YCbCr) Hasselblad Lunar 3FR 2012 verified issue #1275: raw.pixls.us 4051 (a Sony NEX-7 ARW under Make HASSELBLAD) decodes from sensor data; black 512 and SR2SubIFD WB as on a NEX-7 Hasselblad Stellar II 3FR 2015 preview 3FR is opened from its embedded JPEG only -Hasselblad X1D 3FR 2015 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad X1D 3FR 2015 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration Hasselblad X2D II 100C (**) 3FR 2024 preview 3FR is opened from its embedded JPEG only -Hasselblad X1D II 50C 3FR 2018 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration -Hasselblad X2D 100C 3FR 2021 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad X1D II 50C 3FR 2018 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad X2D 100C 3FR 2021 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration Huawei Honor 20 Pro Rear Main Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Huawei Honor 20 Pro Rear Telephoto Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Huawei Honor 20 Pro Rear Wide Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -557,12 +557,12 @@ Konica Minolta Alpha Sweet Digital (Japan) MRW 2005 unverified MRW decoder (12-b Konica Minolta DiMAGE 5 MRW 2003 unverified MRW decoder (12-bit packed, 16-bit words) Konica Minolta DiMAGE 7 MRW 2003 verified raw.pixls.us check: CC0 sample decoded and its WB / CFA matched to the embedded preview (vendor/mrw.rs) Konica Minolta DiMAGE 7i MRW 2003 unverified MRW decoder (12-bit packed, 16-bit words) -Konica Minolta DiMAGE 7Hi MRW 2003 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Konica Minolta DiMAGE A1 MRW 2003 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Konica Minolta DiMAGE 7Hi MRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Konica Minolta DiMAGE A1 MRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Konica Minolta DiMAGE A2 MRW 2003 verified raw.pixls.us check: CC0 sample decoded and its WB / CFA matched to the embedded preview (vendor/mrw.rs) -Konica Minolta DiMAGE A200 MRW 2003 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Konica Minolta DiMAGE A200 MRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Konica Minolta Maxxum 5D Dynax 5D MRW 2005 unverified MRW decoder (12-bit packed, 16-bit words) -Konica Minolta Maxxum 7D Dynax 7D MRW 2003 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Konica Minolta Maxxum 7D Dynax 7D MRW 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Leaf AFi II 6 MOS 2008 preview MOS is opened from its embedded JPEG only Leaf AFi II 7 MOS 2008 preview MOS is opened from its embedded JPEG only Leaf Aptus 17 MOS 2007 preview MOS is opened from its embedded JPEG only @@ -586,8 +586,8 @@ Leaf Credo 50 IIQ 2013 preview IIQ is opened from its embedded JPEG only Leaf Credo 60 IIQ 2012 preview IIQ is opened from its embedded JPEG only Leaf Credo 80 IIQ 2012 preview IIQ is opened from its embedded JPEG only Leica C (Typ 112) RWL 2013 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format -Leica CL DNG 2017 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica C-Lux DNG 2017 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica CL DNG 2017 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica C-Lux DNG 2017 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Leica D-Lux 2 RAW 2005 unverified Panasonic decoder, every raw format Leica D-Lux 3 RAW 2005 verified PR #215: raw.pixls.us bulk check of every RW2 / RWL / RAW body Leica D-Lux 4 RWL 2008 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format @@ -601,26 +601,26 @@ Leica Digilux 2 RAW 2003 verified PR #215: raw.pixls.us bulk check of every RW2 Leica Digilux 3 RAW 2005 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Leica Digital-Modul-R DNG 2003 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica Leitz Phone 3 DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Leica M8 DNG 2003 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) -Leica M9 DNG 2008 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) -Leica M10 DNG 2015 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica M8 DNG 2003 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) +Leica M9 DNG 2008 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) +Leica M10 DNG 2015 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Leica M10-D DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M10-P DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Leica M10-R DNG 2019 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica M10-R DNG 2019 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Leica M11-D DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M (Typ 262) DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M-D (Typ 262) DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M-E DNG 2012 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M-EV1 DNG 2024 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M-P DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Leica M Monochrom DNG 2012 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) -Leica M Monochrom (Typ 246) DNG 2015 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) +Leica M Monochrom DNG 2012 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) +Leica M Monochrom (Typ 246) DNG 2015 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) Leica M10 Monochrom DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M11 DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M11 MONOCHROM DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica M11-P DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Leica Q (Typ 116) DNG 2015 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica Q2 DNG 2018 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica Q (Typ 116) DNG 2015 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica Q2 DNG 2018 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Leica Q2 Monochrom DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica Q3 DNG 2022 verified recorded check 2026-10-11: 38 private Q3 DNGs (landscape and portrait) decoded from sensor data and developed at full size without error, mean CIE76 dE to the camera JPEG 6.3-13.9 at 400 px (not committed; docs/raw-parity.md) Leica Q3 43 DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -628,8 +628,8 @@ Leica Q3 Monochrom DNG 2025 unverified DNG decoder (uncompressed, LJ92, lossy, D Leica S2 DNG 2010 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica S (Typ 007) DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica S3 DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Leica SL (Typ 601) DNG 2015 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica SL2 DNG 2019 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica SL (Typ 601) DNG 2015 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica SL2 DNG 2019 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Leica SL2-S DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica SL3 DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica SL3-P DNG 2025 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -643,7 +643,7 @@ Leica V-LUX 3 RAW 2010 unverified Panasonic decoder, every raw format Leica V-LUX 4 RWL 2012 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Leica V-LUX 5 RWL 2018 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Leica V-LUX (Typ 114) RWL 2013 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format -Leica X2 RWL 2012 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica X2 RWL 2012 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Leica X (Typ 113) DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Leica X-U (Typ 113) DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) LG G7 ThinQ DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -673,108 +673,108 @@ Mamiya Mamiya M18 TIF 2008 unsupported TIF is not imported Mamiya Mamiya M22 TIF 2008 unsupported TIF is not imported Mamiya Mamiya M31 TIF 2008 unsupported TIF is not imported Mamiya Mamiya DM40 MOS 2010 preview MOS is opened from its embedded JPEG only -Mamiya ZD MEF 2005 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Mamiya ZD MEF 2005 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Motorola Moto G Power (2021) Front Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Motorola Moto G Power (2021) Rear Macro Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Motorola Moto G Power (2021) Rear Wide Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Nikon 1 J1 NEF 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J2 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J3 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J4 NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J5 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 S1 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J1 NEF 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J2 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J3 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J4 NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J5 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 S1 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon 1 S2 NEF 2013 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon 1 V1 NEF 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 V2 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 V3 NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 V1 NEF 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 V2 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 V3 NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon COOLPIX 5000 NEF 2003 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX 5400 NEF 2003 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX 5700 NEF 2003 unsupported bulk: raw.pixls.us CC0 file decodes wrongly (two stacked half-height fields, CMYG mosaic read as RGB; green vs camera JPEG r 0.12-0.36) Nikon COOLPIX 8400 NEF 2005 unsupported bulk: raw.pixls.us CC0 file decodes wrongly (two stacked half-height fields, CMYG mosaic read as RGB; green vs camera JPEG r 0.12-0.36) Nikon COOLPIX 8700 NEF 2003 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX 8800 NEF 2005 unsupported bulk: raw.pixls.us CC0 file decodes wrongly (two stacked half-height fields, CMYG mosaic read as RGB; green vs camera JPEG r 0.12-0.36) -Nikon COOLPIX A NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX A1000 NRW 2018 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX B700 NRW 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Nikon COOLPIX A NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX A1000 NRW 2018 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX B700 NRW 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Nikon COOLPIX P330 NRW 2012 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX P340 NRW 2013 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon COOLPIX P1000 NRW 2018 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX P1100 NRW 2024 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX P1000 NRW 2018 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX P1100 NRW 2024 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon COOLPIX P6000 NRW 2008 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX P7000 NRW 2010 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX P7100 NRW 2010 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX P7700 NRW 2012 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon COOLPIX P7800 NRW 2013 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon COOLPIX P950 NEF 2019 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX P950 NEF 2019 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon D1 NEF 2003 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon D1H NEF 2003 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D1H NEF 2003 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon D1X NEF 2003 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon D2H NEF 2003 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D2Hs NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D2X NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D2Xs NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3 NEF 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3s NEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3X NEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D4 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D4S NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D40 NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D40x NEF 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D50 NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D60 NEF 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D6 NEF 2019 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) -Nikon D70 NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D70S NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D80 NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D90 NEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2H NEF 2003 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2Hs NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2X NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2Xs NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3 NEF 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3s NEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3X NEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D4 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D4S NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D40 NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D40x NEF 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D50 NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D60 NEF 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D6 NEF 2019 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) +Nikon D70 NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D70S NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D80 NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D90 NEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon D100 NEF 2003 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon D200 NEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D300 NEF 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D300s NEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D500 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D600 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D610 NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D700 NEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D750 NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D780 NEF 2019 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D800 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D800E NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D810 NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D200 NEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D300 NEF 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D300s NEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D500 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D600 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D610 NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D700 NEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D750 NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D780 NEF 2019 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D800 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D800E NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D810 NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon D810A NEF 2015 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon D850 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3000 NEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3100 NEF 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3200 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3300 NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3400 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3500 NEF 2018 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5000 NEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5100 NEF 2010 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon D5200 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5300 NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5500 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5600 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D7000 NEF 2010 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon D7100 NEF 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D7200 NEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D7500 NEF 2015 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon Df NEF 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 30 NEF 2021 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 50 NEF 2019 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 50 II NEF 2024 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 5 NEF 2019 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D850 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3000 NEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3100 NEF 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3200 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3300 NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3400 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3500 NEF 2018 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5000 NEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5100 NEF 2010 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon D5200 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5300 NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5500 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5600 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D7000 NEF 2010 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon D7100 NEF 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D7200 NEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D7500 NEF 2015 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon Df NEF 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 30 NEF 2021 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 50 NEF 2019 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 50 II NEF 2024 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 5 NEF 2019 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon Z 5 2 NEF 2024 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nikon Z 5 2C NEF 2025 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon Z 6 NEF 2018 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) -Nikon Z 6 II NEF 2020 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 6 NEF 2018 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) +Nikon Z 6 II NEF 2020 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon Z 6 III NEF 2023 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only -Nikon Z 7 NEF 2018 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) -Nikon Z 7 II NEF 2020 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 8 NEF 2022 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); HE / HE* remain preview-only -Nikon Z 9 (*See note) NEF 2021 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z fc NEF 2020 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z f NEF 2022 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Nikon Z 7 NEF 2018 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) +Nikon Z 7 II NEF 2020 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 8 NEF 2022 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); HE / HE* remain preview-only +Nikon Z 9 (*See note) NEF 2021 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z fc NEF 2020 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z f NEF 2022 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Nikon ZR NEF 2024 unverified NEF decoder (uncompressed, lossless, lossy, lossy after split); HE / HE* setting preview-only Nokia Lumia 1020 DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Nokia HMD Global Nokia 9 PureView Front Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -788,13 +788,13 @@ OM Digital Solutions OM-5 Mark II ORF 2024 preview compressed ORF is not decoded OM Digital Solutions OM-3 Astro ORF 2025 preview compressed ORF is not decoded Olympus AIR A01 ORF 2015 preview compressed ORF is not decoded Olympus Camedia C-5050 Zoom ORF 2003 unverified uncompressed / packed ORF -Olympus Camedia C-5060 Zoom ORF 2003 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Camedia C-7070 Wide Zoom ORF 2005 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus Camedia C-5060 Zoom ORF 2003 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus Camedia C-7070 Wide Zoom ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus Camedia C-8080 Wide Zoom ORF 2003 unverified uncompressed / packed ORF -Olympus E-1 ORF 2003 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Olympus E-1 ORF 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Olympus E-3 ORF 2007 preview compressed ORF is not decoded Olympus E-5 ORF 2010 preview compressed ORF is not decoded -Olympus E-10 ORF 2003 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash) +Olympus E-10 ORF 2003 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash) Olympus E-20 ORF 2003 unverified uncompressed / packed ORF Olympus E-30 ORF 2008 preview compressed ORF is not decoded Olympus E-420 ORF 2008 preview compressed ORF is not decoded @@ -802,18 +802,18 @@ Olympus E-450 ORF 2008 preview compressed ORF is not decoded Olympus E-520 ORF 2008 preview compressed ORF is not decoded Olympus E-600 ORF 2010 preview compressed ORF is not decoded Olympus E-620 ORF 2008 preview compressed ORF is not decoded -Olympus EVOLT E-300 ORF 2005 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus EVOLT E-330 ORF 2005 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus EVOLT E-400 ORF 2005 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Olympus EVOLT E-300 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus EVOLT E-330 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus EVOLT E-400 ORF 2005 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Olympus EVOLT E-410 ORF 2007 preview compressed ORF is not decoded -Olympus EVOLT E-500 ORF 2005 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus EVOLT E-500 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus EVOLT E-510 ORF 2007 preview compressed ORF is not decoded Olympus OM-D E-M1 ORF 2013 preview compressed ORF is not decoded Olympus OM-D E-M1X ORF 2018 preview compressed ORF is not decoded Olympus OM-D E-M1 Mark II ORF 2015 preview compressed ORF is not decoded Olympus OM-D E-M1 Mark III ORF 2019 preview compressed ORF is not decoded Olympus OM-D E-M5 ORF 2012 preview compressed ORF is not decoded -Olympus OM-D E-M5 Mark II ORF 2015 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus OM-D E-M5 Mark II ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus OM-D E-M5 Mark III ORF 2019 preview compressed ORF is not decoded Olympus OM-D E-M10 ORF 2013 preview compressed ORF is not decoded Olympus OM-D E-M10 Mark II ORF 2015 preview compressed ORF is not decoded @@ -837,25 +837,25 @@ Olympus PEN E-PL8 ORF 2015 preview compressed ORF is not decoded Olympus PEN E-PL9 ORF 2017 preview compressed ORF is not decoded Olympus PEN E-PM1 ORF 2010 preview compressed ORF is not decoded Olympus PEN E-PM2 ORF 2012 preview compressed ORF is not decoded -Olympus PEN-F ORF 2015 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus PEN-F ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus SP-310 ORF 2005 preview compressed ORF is not decoded Olympus SP-320 ORF 2005 preview compressed ORF is not decoded Olympus SP-350 ORF 2005 preview compressed ORF is not decoded Olympus SP-500 UZ ORF 2005 preview compressed ORF is not decoded -Olympus SP-510 UZ ORF 2005 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-550 UZ ORF 2007 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-510 UZ ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-550 UZ ORF 2007 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus SP-560 UZ ORF 2007 preview compressed ORF is not decoded -Olympus SP-565 UZ ORF 2008 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-570 UZ ORF 2007 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-565 UZ ORF 2008 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-570 UZ ORF 2007 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus Stylus 1 ORF 2013 preview compressed ORF is not decoded Olympus Stylus 1s ORF 2013 preview compressed ORF is not decoded -Olympus Stylus SH-2 ORF 2015 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus Stylus SH-2 ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus Stylus SH-3 ORF 2015 preview compressed ORF is not decoded Olympus Stylus Tough TG-4 ORF 2015 preview compressed ORF is not decoded Olympus Stylus Tough TG-5 ORF 2015 preview compressed ORF is not decoded Olympus Stylus Tough TG-6 ORF 2018 preview compressed ORF is not decoded -Olympus Stylus XZ-2 iHS ORF 2012 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Olympus Stylus XZ-10 ORF 2012 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus Stylus XZ-2 iHS ORF 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Olympus Stylus XZ-10 ORF 2012 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus XZ-1 ORF 2010 preview compressed ORF is not decoded OnePlus 7T Front Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) OnePlus 7T Rear Main Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -1007,46 +1007,46 @@ Panasonic LUMIX DC-S1M2ES (Final Support) RW2 2024 verified PR #215: 178 raw.pix Panasonic LUMIX DC-S1M2 RW2 2024 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Panasonic LUMIX DC-ZS300 (DC-TZ300, DC-TX3) RW2 2025 unverified Panasonic decoder, every raw format Panasonic LUMIX DC-L10 RW2 2025 unverified Panasonic decoder, every raw format -Parrot Anafi DNG 2017 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Parrot Anafi DNG 2017 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Parrot ANAFI Ai DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Pentax 645D DNG 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax 645Z DNG 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax *ist D PEF 2003 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax *ist DL PEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax 645D DNG 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax 645Z DNG 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax *ist D PEF 2003 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax *ist DL PEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Pentax *ist DL2 PEF 2005 unverified PEF decoder (uncompressed, Huffman, packed 12-bit) -Pentax *ist DS PEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax *ist DS PEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Pentax *ist DS2 PEF 2005 unverified PEF decoder (uncompressed, Huffman, packed 12-bit) -Pentax K-01 DNG 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-1 DNG 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-01 DNG 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-1 DNG 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Pentax K-1 II (* see note) DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Pentax K-3 DNG 2013 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Pentax K-3 II († see note) DNG 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-5 DNG 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-5 II DNG 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-5 IIs DNG 2012 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Pentax K-7 PEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-3 Mark III DNG 2020 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-3 Mark III Monochrome DNG 2022 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash) -Pentax K-30 DNG 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-50 DNG 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-70 PEF 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-500 DNG 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax KP DNG 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-r PEF 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-S1 DNG 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-S2 DNG 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-x PEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K10D DNG 2005 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Pentax K20D DNG 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K100D PEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K100D Super PEF 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K110D PEF 2005 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K200D DNG 2007 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K2000 K-m PEF 2008 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax KF PEF 2022 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax MX-1 DNG 2012 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax Q DNG 2010 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax Q7 DNG 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-3 DNG 2013 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Pentax K-3 II († see note) DNG 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-5 DNG 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-5 II DNG 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-5 IIs DNG 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Pentax K-7 PEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-3 Mark III DNG 2020 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-3 Mark III Monochrome DNG 2022 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash) +Pentax K-30 DNG 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-50 DNG 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-70 PEF 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-500 DNG 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax KP DNG 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-r PEF 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-S1 DNG 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-S2 DNG 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-x PEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K10D DNG 2005 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Pentax K20D DNG 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K100D PEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K100D Super PEF 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K110D PEF 2005 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K200D DNG 2007 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K2000 K-m PEF 2008 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax KF PEF 2022 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax MX-1 DNG 2012 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax Q DNG 2010 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax Q7 DNG 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Pentax Q10 DNG 2012 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Pentax QS-1 DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Pixii PIXII Camera (A1571) DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -1078,10 +1078,10 @@ Phase One P 40+ IIQ 2010 preview IIQ is opened from its embedded JPEG only Phase One P 45 TIF 2007 unsupported TIF is not imported Phase One P 45+ TIF 2007 unsupported TIF is not imported Phase One P 65+ IIQ 2010 preview IIQ is opened from its embedded JPEG only -Ricoh GR DNG 2013 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Ricoh GR II DNG 2015 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Ricoh GR III DNG 2018 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Ricoh GR IIIx DNG 2021 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Ricoh GR DNG 2013 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Ricoh GR II DNG 2015 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Ricoh GR III DNG 2018 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Ricoh GR IIIx DNG 2021 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Ricoh GR III HDF DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Ricoh GR IIIx HDF DNG 2023 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Ricoh GR IV DNG 2024 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -1091,7 +1091,7 @@ Ricoh GR Digital II DNG 2003 unverified DNG decoder (uncompressed, LJ92, lossy, Ricoh GR Digital III DNG 2008 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Ricoh GR Digital IV DNG 2010 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Ricoh GX100 DNG 2003 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Ricoh GX200 DNG 2003 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash) +Ricoh GX200 DNG 2003 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash) Ricoh GXR with GR LENS A12 28mm F2.5 DNG 2010 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Ricoh GXR with GR LENS A12 50mm F2.5 MACRO DNG 2008 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Ricoh GXR with GR LENS A16 24-85 F3.5-5.5 DNG 2010 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -1105,15 +1105,15 @@ Samsung EK-KN120 SRW 2012 preview compressed SRW is not decoded Samsung EX2F SRW 2012 unverified uncompressed / packed SRW Samsung NX300 SRW 2012 preview compressed SRW is not decoded Samsung NX500 SRW 2015 preview compressed SRW is not decoded -Samsung NX1000 SRW 2012 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Samsung NX1100 SRW 2012 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Samsung NX1000 SRW 2012 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Samsung NX1100 SRW 2012 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Samsung NX2000 SRW 2012 preview compressed SRW is not decoded Samsung NX3000 SRW 2013 preview compressed SRW is not decoded Samsung NX3300 SRW 2015 preview compressed SRW is not decoded Samsung NX U SRW 2012 unverified uncompressed / packed SRW Samsung Pro 815 DNG 2003 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Samsung TL350 (WB2000) SRW 2010 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Samsung TL500 (EX1) SRW 2010 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Samsung TL350 (WB2000) SRW 2010 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Samsung TL500 (EX1) SRW 2010 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Samsung Galaxy Note 9 DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy Note 20 Rear Main Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy Note 20 Ultra Rear Main Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -1127,16 +1127,16 @@ Samsung Galaxy S21 Rear Main Camera DNG 2020 unverified DNG decoder (uncompresse Samsung Galaxy S21 Rear Wide Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S21+ Rear Main Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S21+ Rear Wide Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Samsung Galaxy S21 Ultra Rear Main Camera DNG 2020 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S21 Ultra Rear Main Camera DNG 2020 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Samsung Galaxy S21 Ultra Rear Wide Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S21 Ultra Super Telephoto Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S21 Ultra Telephoto Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S6 DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S6 Edge DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S7 DNG 2015 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Samsung Galaxy S7 Edge DNG 2015 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S8 DNG 2017 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S8+ DNG 2017 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S7 Edge DNG 2015 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S8 DNG 2017 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S8+ DNG 2017 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Samsung Galaxy S9 DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S9+ DNG 2017 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy Z Fold3 Rear Main Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -1154,11 +1154,11 @@ Samsung Galaxy S22 Ultra Front Camera DNG 2021 unverified DNG decoder (uncompres Samsung Galaxy S22 Ultra Rear Super Telephoto Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S22 Ultra Rear Telephoto Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S22 Ultra Rear Ultrawide Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Samsung Galaxy S22 Ultra Rear Wide Camera DNG 2021 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S22 Ultra Rear Wide Camera DNG 2021 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Samsung Galaxy S23 Front Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S23 Rear Telephoto Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S23 Rear Ultrawide Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Samsung Galaxy S23 Rear Wide Camera DNG 2022 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S23 Rear Wide Camera DNG 2022 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Samsung Galaxy S23+ Front Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S23+ Rear Telephoto Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Samsung Galaxy S23+ Rear Ultrawide Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) @@ -1230,8 +1230,8 @@ Sigma BF DNG 2024 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JP Sigma DP1 X3F 2007 preview X3F is opened from its embedded JPEG only Sigma DP1s X3F 2008 preview X3F is opened from its embedded JPEG only Sigma DP2 X3F 2008 preview X3F is opened from its embedded JPEG only -Sigma fp DNG 2019 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Sigma fp L DNG 2020 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Sigma fp DNG 2019 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Sigma fp L DNG 2020 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) Sigma SD9 X3F 2003 preview X3F is opened from its embedded JPEG only Sigma SD10 X3F 2003 preview X3F is opened from its embedded JPEG only Sigma SD14 X3F 2007 preview X3F is opened from its embedded JPEG only @@ -1243,12 +1243,12 @@ Sony Xperia 1 V Front Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92 Sony Xperia 1 V Ultrawide Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Sony Xperia 1 V Wide Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Sony Xperia 1 V Zoom Camera DNG 2022 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -Sony A1 II (ILCE-1M2) (** see note) ARW 2024 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony A1 II (ILCE-1M2) (** see note) ARW 2024 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Sony A7 (ILCE-7) ARW 2013 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony A7 II (ILCE-A7M2) ARW 2013 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies Sony A7 III (ILCE-7M3) ARW 2017 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony A7 IV (ILCE-7M4) ARW 2021 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) -Sony A7 V (ILCE-7M5) (** see note) ARW 2025 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony A7 V (ILCE-7M5) (** see note) ARW 2025 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Sony A7C (ILCE-7C) ARW 2020 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony A7C II (ILCE-7CM2) ARW 2023 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony A7CR (ILCE-7CR) ARW 2023 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) @@ -1310,7 +1310,7 @@ Sony DSC-F828 SRF 2003 preview 2026-10-12 release CLI: raw.pixls.us DSC06227.SRF Sony DSC-HX95 ARW 2018 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony DSC-HX99 ARW 2018 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony DSC-V3 SRF 2005 unsupported SRF is discovered; sensor decoding unsupported, usable preview not verified on a real file -Sony DSC-RX100M7A ARW 2024 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony DSC-RX100M7A ARW 2024 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Sony FX3 (ILME-FX3) ARW 2020 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony FX30 (ILME-FX30) ARW 2022 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony NEX-3 ARW 2010 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) @@ -1375,16 +1375,16 @@ Sony Xperia 5 V Wide Camera DNG 2023 unverified DNG decoder (uncompressed, LJ92, Sony Xperia Pro-I Rear Wide Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Sony ZV-E10 ARW 2021 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony ZV-E1 ARW 2022 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) -Sony ZV-E10M2 ARW verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony ZV-1M2 ARW 2022 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony ZV-E10M2 ARW verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony ZV-1M2 ARW 2022 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Sony ZV-1A ARW 2024 unverified ARW decoder (uncompressed, cRAW, packed 12-bit, lossless, downsized YCbCr) Sony ILX-LR1 ARW 2023 unverified ARW decoder (uncompressed, cRAW, packed 12-bit, lossless, downsized YCbCr) Sony ILCE - 1M2 (Final Support) ARW 2024 unverified ARW decoder (uncompressed, cRAW, packed 12-bit, lossless, downsized YCbCr) Sony ILCE - 6100A ARW 2024 unverified ARW decoder (uncompressed, cRAW, packed 12-bit, lossless, downsized YCbCr) -Sony ILCE - 6400A ARW 2024 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony FX2 (ILMEFX2) (** see note) ARW 2024 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony ILCE - 6400A ARW 2024 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony FX2 (ILMEFX2) (** see note) ARW 2024 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Sony FX3A (ILMEFX3A) ARW 2024 unverified ARW decoder (uncompressed, cRAW, packed 12-bit, lossless, downsized YCbCr) -Sony RX1R III (DSC-RX1RM3) ARW 2024 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony RX1R III (DSC-RX1RM3) ARW 2024 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) Xiaomi Mi 11 Lite Front Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Xiaomi Mi 11 Lite Rear Ultrawide Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Xiaomi Mi 11 Lite Rear Wide Camera DNG 2021 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) diff --git a/docs/raw/evidence.tsv b/docs/raw/evidence.tsv index a09978c8d6..6212558585 100644 --- a/docs/raw/evidence.tsv +++ b/docs/raw/evidence.tsv @@ -1,119 +1,119 @@ # Per-model evidence that overrides the format rules in coverage.py. status: verified | preview | unsupported. # "verified" means a real file from this body decoded from sensor data in a corpus test or a recorded bulk check (source column). maker camera status source -Apple iPhone 12 Pro Rear Wide Camera verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 40D verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 550D (EOS Digital Rebel T2i, EOS Kiss X4 Digital) verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 5D Mark II verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 5DS R verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 6D verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 7D verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 80D verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS M50 (EOS Kiss M) verified corpus: crates/raw/tests/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) -Canon EOS R100 verified corpus: crates/raw/tests/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) -Canon EOS R5 Mark II verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hashes, docs/cr3.md); bulk: QP maps of 33,665 C-RAW files -Canon EOS R8 verified corpus: crates/raw/tests/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) -Canon EOS-1D X Mark III verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS 90D verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS 250D (EOS Rebel SL3, EOS 200D II, EOS Kiss X10) verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS 850D (EOS Kiss X10i, EOS Rebel T8i) verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS M200 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS M50 Mark II verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS M6 Mark II verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R (** see note) verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R3 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R5 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R6 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R6 Mark II verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; C-RAW with adaptive QP above 168 still opens as the preview) -Canon EOS R6 Mark III verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R7 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; lossless only, C-RAW unverified) -Canon EOS R10 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS RP verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R50 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS R50 V verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon PowerShot G5 X Mark II verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon PowerShot G7 X Mark III verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon PowerShot SX70 HS verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon PowerShot V1 verified corpus: crates/raw/tests/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) -Canon EOS-5D Mark III verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Canon EOS 70D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 800D (EOS Digital Rebel T7i, EOS Kiss X9i) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G9X verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 3000D (EOS Rebel T100, EOS 4000D) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1000D (EOS Digital Rebel XS, EOS Kiss F) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G1 X Mark II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 500D (EOS Digital Rebel T1i, EOS Kiss X3 Digital) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 400D (EOS Digital Rebel XTi, EOS Kiss Digital X) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S110 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1300D (EOS Digital Rebel T6, EOS Kiss X80) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 600D (EOS Digital Rebel T3i, EOS Kiss X5 Digital) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G1 X verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G16 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G3 X verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-1D X Mark II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 750D (EOS Digital Rebel T6i, EOS Kiss X8i) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 5DS verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S100V verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 350D (EOS Digital Rebel XT, EOS Kiss Digital N) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1200D (EOS Digital Rebel T5, EOS Kiss X70) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G11 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 100D (EOS Digital Rebel SL1, EOS Kiss X7) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G15 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-1D Mark IV verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M5 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S100 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 650D (EOS Digital Rebel T4i, EOS Kiss X4i) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot SX50 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M2 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M3 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G12 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 6D Mark II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M10 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 700D (EOS Digital Rebel T5i, EOS Kiss X7i) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1100D (EOS Digital Rebel T3, EOS Kiss X50 Digital) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 77D (EOS 9000D) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 1500D (EOS Rebel T7, EOS Kiss X90, EOS 2000D) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-5D Mark IV (** see note) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-1D Mark III verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 60D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS-1D Mark II N verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M100 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G5 X verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G9 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 5D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS M6 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G7 X Mark II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 7D Mark II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S120 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot S95 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G1 X Mark III verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 50D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 20D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G7 X verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 450D (EOS Digital Rebel XSi, EOS Kiss Digital X2) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot SX60 HS verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 200D (EOS Kiss X9, EOS Rebel SL2) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon PowerShot G9 X Mark II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 760D (EOS Digital Rebel T6s, EOS Kiss 8000D) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Canon EOS 30D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 100 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm GFX 100RF (Final Support) verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm GFX 100S verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm GFX 50S verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-A2 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-A5 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-E1 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-E5 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-H2 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Apple iPhone 12 Pro Rear Wide Camera verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 40D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 550D (EOS Digital Rebel T2i, EOS Kiss X4 Digital) verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 5D Mark II verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 5DS R verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 6D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 7D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 80D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS M50 (EOS Kiss M) verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) +Canon EOS R100 verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) +Canon EOS R5 Mark II verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hashes, docs/cr3.md); bulk: QP maps of 33,665 C-RAW files +Canon EOS R8 verified corpus: crates/raw/tests/it/cr3_corpus.rs (exact sensor hashes, docs/cr3.md) +Canon EOS-1D X Mark III verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS 90D verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS 250D (EOS Rebel SL3, EOS 200D II, EOS Kiss X10) verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS 850D (EOS Kiss X10i, EOS Rebel T8i) verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS M200 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS M50 Mark II verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS M6 Mark II verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R (** see note) verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R3 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R5 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R6 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R6 Mark II verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; C-RAW with adaptive QP above 168 still opens as the preview) +Canon EOS R6 Mark III verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R7 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md; lossless only, C-RAW unverified) +Canon EOS R10 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS RP verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R50 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS R50 V verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot G5 X Mark II verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot G7 X Mark III verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot SX70 HS verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon PowerShot V1 verified corpus: crates/raw/tests/it/cr3_corpus.rs (pinned sensor hash, camera-JPEG check, docs/cr3.md) +Canon EOS-5D Mark III verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Canon EOS 70D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 800D (EOS Digital Rebel T7i, EOS Kiss X9i) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G9X verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 3000D (EOS Rebel T100, EOS 4000D) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1000D (EOS Digital Rebel XS, EOS Kiss F) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G1 X Mark II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 500D (EOS Digital Rebel T1i, EOS Kiss X3 Digital) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 400D (EOS Digital Rebel XTi, EOS Kiss Digital X) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S110 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1300D (EOS Digital Rebel T6, EOS Kiss X80) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 600D (EOS Digital Rebel T3i, EOS Kiss X5 Digital) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G1 X verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G16 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G3 X verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D X Mark II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 750D (EOS Digital Rebel T6i, EOS Kiss X8i) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 5DS verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S100V verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 350D (EOS Digital Rebel XT, EOS Kiss Digital N) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1200D (EOS Digital Rebel T5, EOS Kiss X70) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G11 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 100D (EOS Digital Rebel SL1, EOS Kiss X7) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G15 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D Mark IV verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M5 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S100 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 650D (EOS Digital Rebel T4i, EOS Kiss X4i) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot SX50 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M2 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M3 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G12 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 6D Mark II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M10 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 700D (EOS Digital Rebel T5i, EOS Kiss X7i) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1100D (EOS Digital Rebel T3, EOS Kiss X50 Digital) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 77D (EOS 9000D) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 1500D (EOS Rebel T7, EOS Kiss X90, EOS 2000D) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-5D Mark IV (** see note) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D Mark III verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 60D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS-1D Mark II N verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M100 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G5 X verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G9 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 5D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS M6 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G7 X Mark II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 7D Mark II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S120 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot S95 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G1 X Mark III verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 50D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 20D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G7 X verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 450D (EOS Digital Rebel XSi, EOS Kiss Digital X2) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot SX60 HS verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 200D (EOS Kiss X9, EOS Rebel SL2) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon PowerShot G9 X Mark II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 760D (EOS Digital Rebel T6s, EOS Kiss 8000D) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Canon EOS 30D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 100 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 100RF (Final Support) verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 100S verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm GFX 50S verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-A2 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-A5 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-E1 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-E5 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-H2 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Fujifilm X-H2S verified docs/raf-compression.md (supplied files, exact sensor arrays) -Fujifilm X-M5 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T2 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T20 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T4** verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T5 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Fujifilm X-T50 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Google Pixel 2 XL verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-M5 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T2 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T20 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T4** verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T5 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Fujifilm X-T50 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Google Pixel 2 XL verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Hasselblad Lunar verified issue #1275: raw.pixls.us 4051 (a Sony NEX-7 ARW under Make HASSELBLAD) decodes from sensor data; black 512 and SR2SubIFD WB as on a NEX-7 Leica C (Typ 112) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Leica D-Lux (Typ 109) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format @@ -129,147 +129,147 @@ Leica V-LUX (Typ 114) verified PR #215: 178 raw.pixls.us files from 118 Panasoni Leica V-LUX 1 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Leica V-LUX 4 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Leica V-LUX 5 verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format -Leica M Monochrom verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) -Leica CL verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica M10 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica C-Lux verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica M Monochrom (Typ 246) verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) -Leica M8 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) -Leica X2 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica Q2 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica SL (Typ 601) verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica M10-R verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica SL2 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Leica M9 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash) -Leica Q (Typ 116) verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX B700 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon D5100 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon D7000 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon D7500 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon Z f verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Nikon D700 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XF10 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A10 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5300 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T100 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-Pro1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 V1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J4 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 100S II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D610 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D2H verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 6 II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX P1000 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X100 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X30 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X10 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D2Xs verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D4 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D800 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D780 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D850 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E2S verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D500 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 50R verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Df verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-S10 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 V2 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 V3 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3s verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z fc verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D810 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A3 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D40 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D800E verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3X verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100V** verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D4S verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T30 III verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XQ2 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T10 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D2X verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X70 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D80 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-H1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J5 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D7200 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T30 II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 50 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5000 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XQ1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix HS30 EXR verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D70S verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5200 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX P1100 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-S20 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 30 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E2 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D60 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J2 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5600 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D300 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix SL1000 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-Pro3** verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-Pro2 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 S1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100VI verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T200 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3200 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T3 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix F550 EXR verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D5500 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A7 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3300 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 5 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon 1 J3 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 9 (*See note) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX A1000 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100S verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D2Hs verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D90 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D50 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3000 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100T verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 50 II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D600 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm XF1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D7100 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E3 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-A1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3500 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix HS50 EXR verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 100 II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X100F verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D40x verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX A verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X20 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-E4 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm GFX 50S II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D1H verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D200 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix HS33 EXR verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix S1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon Z 7 II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D70 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D300s verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X-S1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D750 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3100 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon D3400 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix X-M1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm X-T30 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Nikon COOLPIX P950 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Fujifilm FinePix F770 EXR verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica M Monochrom verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) +Leica CL verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica M10 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica C-Lux verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica M Monochrom (Typ 246) verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) +Leica M8 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) +Leica X2 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica Q2 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica SL (Typ 601) verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica M10-R verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica SL2 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Leica M9 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash) +Leica Q (Typ 116) verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX B700 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon D5100 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon D7000 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon D7500 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon Z f verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Nikon D700 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XF10 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A10 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5300 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T100 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-Pro1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 V1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J4 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 100S II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D610 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2H verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 6 II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX P1000 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X100 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X30 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X10 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2Xs verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D4 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D800 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D780 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D850 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E2S verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D500 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 50R verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Df verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-S10 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 V2 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 V3 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3s verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z fc verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D810 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A3 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D40 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D800E verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3X verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100V** verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D4S verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T30 III verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XQ2 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T10 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2X verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X70 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D80 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-H1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J5 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D7200 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T30 II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 50 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5000 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XQ1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix HS30 EXR verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D70S verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5200 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX P1100 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-S20 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 30 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E2 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D60 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J2 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5600 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D300 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix SL1000 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-Pro3** verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-Pro2 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 S1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100VI verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T200 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3200 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T3 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix F550 EXR verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D5500 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A7 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3300 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 5 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon 1 J3 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 9 (*See note) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX A1000 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100S verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D2Hs verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D90 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D50 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3000 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100T verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 50 II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D600 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm XF1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D7100 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E3 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-A1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3500 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix HS50 EXR verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 100 II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X100F verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D40x verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX A verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X20 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-E4 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm GFX 50S II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D1H verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D200 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix HS33 EXR verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix S1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon Z 7 II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D70 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D300s verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X-S1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D750 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3100 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon D3400 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix X-M1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm X-T30 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Nikon COOLPIX P950 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Fujifilm FinePix F770 EXR verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) Nikon COOLPIX 5700 unsupported bulk: raw.pixls.us CC0 file decodes wrongly (two stacked half-height fields, CMYG mosaic read as RGB; green vs camera JPEG r 0.12-0.36) Nikon COOLPIX 8400 unsupported bulk: raw.pixls.us CC0 file decodes wrongly (two stacked half-height fields, CMYG mosaic read as RGB; green vs camera JPEG r 0.12-0.36) Nikon COOLPIX 8800 unsupported bulk: raw.pixls.us CC0 file decodes wrongly (two stacked half-height fields, CMYG mosaic read as RGB; green vs camera JPEG r 0.12-0.36) -Olympus E-1 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Olympus EVOLT E-400 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Olympus Stylus XZ-2 iHS verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Olympus E-1 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Olympus EVOLT E-400 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Olympus Stylus XZ-2 iHS verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Panasonic LUMIX DC - G97 (DC-G99M2) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Panasonic LUMIX DC-FZ1000M2 (DC-FZ10002) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Panasonic LUMIX DC-FZ80 (DC-FZ82, DC-FZ85) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format @@ -363,47 +363,47 @@ Panasonic LUMIX DMC-ZS40 (DMC-TZ60, DMC-TZ61) verified PR #215: 178 raw.pixls.us Panasonic LUMIX DMC-ZS50 (DMC-TZ70, DMC-TZ71) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Panasonic LUMIX DMC-ZS60 (DMC-TZ80, DMC-TZ81, DMC-TZ85) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format Panasonic LUMIX ZS200 (DC-TX2, DC-TZ200, DC-TZ202, DC-TZ220, DC-ZS220) verified PR #215: 178 raw.pixls.us files from 118 Panasonic / Leica bodies, every RW2 format -Pentax K-3 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Pentax K-5 IIs verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Pentax K10D verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Ricoh GR III verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Pentax K-1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax *ist DL verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Ricoh GX200 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash) -Pentax KP verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-3 Mark III Monochrome verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash) -Pentax K-70 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Ricoh GR IIIx verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K20D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax *ist DS verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-3 Mark III verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-01 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K110D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax Q7 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-S1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax *ist D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-30 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K200D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-5 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-x verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Ricoh GR verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax 645D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K100D verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-500 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K2000 K-m verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-50 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax 645Z verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-5 II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax Q verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax MX-1 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K100D Super verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Ricoh GR II verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-S2 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-r verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax KF verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-3 II († see note) verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Pentax K-7 verified corpus: crates/raw/tests/body_corpus.rs (pinned sensor hash, camera-JPEG check) -Samsung TL500 (EX1) verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Pentax K-3 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Pentax K-5 IIs verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Pentax K10D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Ricoh GR III verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Pentax K-1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax *ist DL verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Ricoh GX200 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash) +Pentax KP verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-3 Mark III Monochrome verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash) +Pentax K-70 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Ricoh GR IIIx verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K20D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax *ist DS verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-3 Mark III verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-01 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K110D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax Q7 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-S1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax *ist D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-30 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K200D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-5 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-x verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Ricoh GR verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax 645D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K100D verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-500 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K2000 K-m verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-50 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax 645Z verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-5 II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax Q verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax MX-1 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K100D Super verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Ricoh GR II verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-S2 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-r verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax KF verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-3 II († see note) verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Pentax K-7 verified corpus: crates/raw/tests/it/body_corpus.rs (pinned sensor hash, camera-JPEG check) +Samsung TL500 (EX1) verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Sony A100 (DSLR-A100) preview issue #702 fixed (#774): opens from its embedded JPEG; its raw (no CFA image IFD) is not decoded Sony A200 (DSLR-A200) preview issue #535: preview-only on the raw.pixls.us sample Sony A230 (DSLR-A230) preview issue #535: preview-only on the raw.pixls.us sample @@ -502,70 +502,70 @@ Sony RX1R II (DSC-RX1RM2) verified issue #535: raw.pixls.us bulk check of all 10 Sony ZV-1 (DCZV1/B) verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony ZV-E1 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) Sony ZV-E10 verified issue #535: raw.pixls.us bulk check of all 100 Sony bodies (decodes; BL/WL/crop/WB vs ExifTool) -Sony ZV-1M2 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony ZV-E10M2 verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony RX1R III (DSC-RX1RM3) verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony A1 II (ILCE-1M2) (** see note) verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony DSC-RX100M7A verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony A7 V (ILCE-7M5) (** see note) verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony FX2 (ILMEFX2) (** see note) verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Sony ILCE - 6400A verified corpus: crates/raw/tests/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-550 UZ verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus E-10 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash) -Olympus Camedia C-5060 Zoom verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-565 UZ verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus OM-D E-M5 Mark II verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus EVOLT E-300 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Stylus SH-2 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Camedia C-7070 Wide Zoom verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Stylus XZ-10 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus EVOLT E-330 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-570 UZ verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-510 UZ verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus PEN-F verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus EVOLT E-500 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Samsung TL350 (WB2000) verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Samsung NX1000 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Samsung NX1100 verified corpus: crates/raw/tests/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony ZV-1M2 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony ZV-E10M2 verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony RX1R III (DSC-RX1RM3) verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony A1 II (ILCE-1M2) (** see note) verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony DSC-RX100M7A verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony A7 V (ILCE-7M5) (** see note) verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony FX2 (ILMEFX2) (** see note) verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Sony ILCE - 6400A verified corpus: crates/raw/tests/it/sony_leica_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-550 UZ verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus E-10 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash) +Olympus Camedia C-5060 Zoom verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-565 UZ verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus OM-D E-M5 Mark II verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus EVOLT E-300 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus Stylus SH-2 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus Camedia C-7070 Wide Zoom verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus Stylus XZ-10 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus EVOLT E-330 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-570 UZ verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus SP-510 UZ verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus PEN-F verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus EVOLT E-500 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Samsung TL350 (WB2000) verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Samsung NX1000 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Samsung NX1100 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Sony A100 (DSLR-A100) unsupported issue #702: regression, refused as not a readable photo Sony DSC-F828 preview 2026-10-12 release CLI: raw.pixls.us DSC06227.SRF imports as preview-only through recursive and direct import (docs/raw-parity.md) -Epson R-D1 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Epson R-D1s verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Epson R-D1x verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Mamiya ZD verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Apple iPhone 6s Plus verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Apple iPhone 7 Plus verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Apple iPhone XS verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -DJI DJI Mavic 2 Pro (Hasselblad L1D-20c) verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -DJI DJI Mavic 3 (Hasselblad L2D-20c) verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -DJI DJI Mavic 4 Pro (DJI FC9287) verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -DJI DJI Mini 2 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Google Pixel 4 XL verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Google Pixel 4a Rear Wide Camera verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Google Pixel 6 Pro Rear Main Camera verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Google Pixel 8 Pro Wide Camera* verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Hasselblad CFV-50c verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration -Hasselblad H5D-40 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration -Hasselblad H5D-50c verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration -Hasselblad X1D verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration -Hasselblad X1D II 50C verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration -Hasselblad X2D 100C verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration -Nikon D6 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) -Nikon Z 6 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) -Nikon Z 7 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) -Nikon Z 8 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); HE / HE* remain preview-only -Parrot Anafi verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S21 Ultra Rear Main Camera verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S22 Ultra Rear Wide Camera verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S23 Rear Wide Camera verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S7 Edge verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S8 verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Samsung Galaxy S8+ verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Sigma fp verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Sigma fp L verified corpus: crates/raw/tests/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) -Konica Minolta DiMAGE 7Hi verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Konica Minolta DiMAGE A1 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Konica Minolta DiMAGE A200 verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) -Konica Minolta Maxxum 7D Dynax 7D verified corpus: crates/raw/tests/corpus.rs (xtask RAW_SAMPLES) +Epson R-D1 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Epson R-D1s verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Epson R-D1x verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Mamiya ZD verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Apple iPhone 6s Plus verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Apple iPhone 7 Plus verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Apple iPhone XS verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mavic 2 Pro (Hasselblad L1D-20c) verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mavic 3 (Hasselblad L2D-20c) verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mavic 4 Pro (DJI FC9287) verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +DJI DJI Mini 2 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 4 XL verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 4a Rear Wide Camera verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 6 Pro Rear Main Camera verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Google Pixel 8 Pro Wide Camera* verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Hasselblad CFV-50c verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad H5D-40 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad H5D-50c verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad X1D verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad X1D II 50C verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Hasselblad X2D 100C verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); decode verified, not colour calibration +Nikon D6 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) +Nikon Z 6 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) +Nikon Z 7 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); checked compressed NEF only; uncompressed remains preview-only (#671) +Nikon Z 8 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check); HE / HE* remain preview-only +Parrot Anafi verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S21 Ultra Rear Main Camera verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S22 Ultra Rear Wide Camera verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S23 Rear Wide Camera verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S7 Edge verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S8 verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Samsung Galaxy S8+ verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Sigma fp verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Sigma fp L verified corpus: crates/raw/tests/it/coverage_sweep_corpus.rs (pinned sensor hashes); bulk: docs/raw/coverage-sweep.tsv (CC0, SHA-256, camera-image check) +Konica Minolta DiMAGE 7Hi verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Konica Minolta DiMAGE A1 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Konica Minolta DiMAGE A200 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) +Konica Minolta Maxxum 7D Dynax 7D verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Konica Minolta DiMAGE 7 verified raw.pixls.us check: CC0 sample decoded and its WB / CFA matched to the embedded preview (vendor/mrw.rs) Konica Minolta DiMAGE A2 verified raw.pixls.us check: CC0 sample decoded and its WB / CFA matched to the embedded preview (vendor/mrw.rs) diff --git a/docs/releasing.md b/docs/releasing.md index 914a7ad840..1704492d1f 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -66,7 +66,7 @@ the web build requires BIZ UDPGothic Regular and packages Noto Sans CJK SC as a Local macOS, Linux and Windows packaging scripts automatically use the sibling `../craft-fonts` checkout. If it is absent, they clone it at revision -`3d9ab3a132ed0eff457e424226a435a901da30d3` (keep the pins in `packaging/fonts.sh` and +`b076417b5880bd4154bd22f00695b1d28c6bea83` (keep the pins in `packaging/fonts.sh` and `packaging/windows/fonts.ps1` in sync with the release workflow). Existing checkouts are left untouched. Set `CRAFT_FONTS_DIR` to use another checkout; relative paths resolve from the workspace root. The script requires the Chinese and Japanese diff --git a/docs/showcase/__pycache__/run.cpython-314.pyc b/docs/showcase/__pycache__/run.cpython-314.pyc new file mode 100644 index 0000000000..de0f9a97e5 Binary files /dev/null and b/docs/showcase/__pycache__/run.cpython-314.pyc differ diff --git a/docs/showcase/run.py b/docs/showcase/run.py index 8ea6c9fc9b..05de581af5 100644 --- a/docs/showcase/run.py +++ b/docs/showcase/run.py @@ -1,16 +1,38 @@ #!/usr/bin/env python3 """lcb.py FILE.jsonl — run control requests from a JSON-lines file ({"method":..., "params":...} or {"sleep": s}).""" import json, socket, sys, time +from pathlib import Path + + +# Largest control reply we accept (a screenshot response can carry a base64 image), after twice +# that the connection is closed instead of buffering further. +MAX_RESPONSE = 128 << 20 + +def _jsonl_path(arg): + """Resolve the CLI file argument; require an existing readable regular file.""" + path = Path(arg).resolve() + if not path.is_file(): + sys.exit(f"not a readable file: {arg}") + try: + path.open("rb").close() + except OSError: + sys.exit(f"not a readable file: {arg}") + return path + def call(method, params): s = socket.create_connection(("127.0.0.1", 7980), timeout=180) s.sendall((json.dumps({"id": 1, "method": method, "params": params}) + "\n").encode()) - buf = b"" - while not buf.endswith(b"\n"): + buf = bytearray() + while not (len(buf) and buf[-1:] == b"\n"): c = s.recv(1 << 20) if not c: break - buf += c + # a hostile server must not make a client buffer or pay quadratic copies forever (CWE-407) + if len(buf) + len(c) > MAX_RESPONSE: + s.close() + return {"ok": False, "error": f"response exceeds {MAX_RESPONSE} bytes"} + buf.extend(c) return json.loads(buf) -for line in open(sys.argv[1]): +for line in open(_jsonl_path(sys.argv[1])): line = line.strip() if not line or line.startswith("#"): continue r = json.loads(line) diff --git a/docs/slideshow.md b/docs/slideshow.md index 79cf5f04e7..e0c89b0311 100644 --- a/docs/slideshow.md +++ b/docs/slideshow.md @@ -7,7 +7,7 @@ next to a live preview of the selected photo's slide, and View ▸ Slideshow ( | Part | Commands | Code | |---|---|---| -| Playback: slide and fade durations, fade colour, random order, repeat, preparing slides ahead | `slideshow.playback`, `view.slideshow` | `crates/engine/src/slideshow.rs` (the timeline), `crates/ui-egui/src/panels/slideshow.rs` | +| Playback: slide and fade durations, fade colour, random order, repeat, preparing slides ahead, manual slideshow | `slideshow.playback`, `view.slideshow` | `crates/engine/src/slideshow.rs` (the timeline), `crates/ui-egui/src/panels/slideshow.rs` | | Layout, options, backdrop: margins, aspect preview, zoom to fill, stroke, shadow, colour, colour wash, background photo | `slideshow.layout` | `crates/slideshow` (the composer, no UI), `crates/engine/src/slide.rs` | | Overlays: identity plate, rating stars, text with tokens, watermark | `slideshow.overlays` | `crates/engine/src/slide_overlay.rs` | | Intro and ending screens | `slideshow.titles` | `crates/engine/src/slide_title.rs` | @@ -23,7 +23,7 @@ the same pixels through the same composer. View ▸ Export Slideshow… (or Export PDF / JPEG / Video at the end of Settings ▸ Slideshow) chooses a format and size, then asks where to write. The slides are the photos in view, in view order, between the intro and ending screens that -are on; random order and repeat are playback choices and don't apply. The slide aspect is the Layout's aspect preview +are on; random order, repeat and manual slideshow are playback choices and don't apply. The slide aspect is the Layout's aspect preview (Screen exports 16:9). - **PDF** — one page per slide, its picture a JPEG at the chosen quality, the page as many points as the slide has diff --git a/docs/sony-lens-corrections.md b/docs/sony-lens-corrections.md index dff886b13f..0252151cde 100644 --- a/docs/sony-lens-corrections.md +++ b/docs/sony-lens-corrections.md @@ -181,7 +181,7 @@ profile correction control when an existing edit has it disabled. ## Local inventory check -`crates/raw/tests/sony_lens_inventory.rs` is opt-in and does nothing in CI. With `LIGHTCRAFT_SONY_LENS_DIR` naming a +`crates/raw/tests/it/sony_lens_inventory.rs` is opt-in and does nothing in CI. With `LIGHTCRAFT_SONY_LENS_DIR` naming a directory of ARWs it decodes each from its headers and prints its record (settings, sources, copies' agreement, sample ranges, statuses); `LIGHTCRAFT_SONY_LENS_FULL=1` also compares header and full decode. With `LIGHTCRAFT_SONY_LENS_INVENTORY` naming a CSV inventory it checks every file's table counts, sizes, sample counts, @@ -300,7 +300,7 @@ The current `cargo xtask corpus --download` manifest contains 25 Sony CC0 sample including samples 4822 (A7R IVA / 24–105 mm) and 3989 (A9 II / 200–600 mm), each with a pinned SHA-256 that the download checks. `sony_embedded_distortion_is_limited_to_validated_models` checks 23 of them (the two ILCE-7CM2 codings have their own test), and `sony_lens_records_of_the_public_samples` verifies all 25 against their pins -(`SONY_SAMPLES` in `crates/raw/tests/corpus.rs`, itself anchored by a pinned digest and compared with the manifest) +(`SONY_SAMPLES` in `crates/raw/tests/it/corpus.rs`, itself anchored by a pinned digest and compared with the manifest) before decoding. **No CI job fetches the corpus**: these fixture tests run only where it has been downloaded, and otherwise skip each absent file. `LIGHTCRAFT_CORPUS_REQUIRED=1` makes `sony_lens_records_of_the_public_samples` fail on any absent pinned file instead. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a7091a05a..d72c165c41 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -158,7 +158,7 @@ essentials replaces its guessed 45% raw look with 84% × 0.75 (+1 point). | Discount | Mainstream | Essentials | Evidence | |---|---:|---:|---| | Interaction fidelity / UI clarity | ×0.95 | ×0.95 | brush live preview gaps and feathering (#517, #518); crop artefacts and limits (#731, #742, #770, #771); Compare white-balance selector (#743–#745); low-res slider previews (#330); dialogs taller than the window (#781); mouse-wheel scroll (#714) | -| Stability on real machines | ×0.92 | ×0.92 | launch and quit crashes or silent startup failures (#250 macOS 12 Intel, #315 Windows Intel GPU, #431 Intel Mac, #260, #462, #783 Linux / Nouveau, #790 Windows installer, fixed in 0.9.1); tests run in CI on FreeBSD only (gap 9) | +| Stability on real machines | ×0.92 | ×0.92 | launch and quit crashes or silent startup failures (#250 macOS 12 Intel, #315 Windows Intel GPU, #431 Intel Mac, #260, #462, #783 Linux / Nouveau, #790 Windows installer, fixed in 0.9.1); tests run in CI on Linux x64 and FreeBSD only (gap 9) | | File exchange with Lightroom users (mainstream) / opening files people send (essentials) | ×0.92 | ×0.95 | Adobe XMP sidecars change colours (#290), XMP CameraProfile and Upright ignored (#204, #205), catalog import fails (#599), same Light values render differently (#523, #209), no write-back to `.lrcat`; for casual users: CR3 beyond verified bodies, compressed ORF, HE NEF open as previews (#473, #485, #556), HEIC trouble (#693) | | **Product** | **×0.804** | **×0.830** | | @@ -300,6 +300,7 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. | Date | Change | Summary | |---|---|---| +| 2026-10-19 | patch | Stability note: tests run in CI on Linux x64 (every PR) as well as FreeBSD; macOS and Windows remain (gap 9) | | 2026-10-19 | minor | Localization ~55% → ~64% (mean of the 12 key languages): Indonesian (`id`) catalog, every message but What's New; full target 61.2% → 61.5% (still ~61%) | | 2026-10-19 | patch | Platforms: the Windows installer is no longer listed as unverified (the 0.9.1 x64 MSI is tested on Windows 11; a confirmation after uninstalling from Settings → Apps, #892, remains); #790 noted as fixed in 0.9.1; percentages and hours unchanged | | 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled | diff --git a/docs/tint-direction.md b/docs/tint-direction.md index 4f9097a784..40249e4597 100644 --- a/docs/tint-direction.md +++ b/docs/tint-direction.md @@ -12,7 +12,7 @@ Run the evidence without private samples: ```sh cargo test -p lightcraft-pipeline tint_ -- --nocapture -cargo test -p lightcraft-gpu --test equivalence tint_directions -- --nocapture +cargo test -p lightcraft-gpu --test it equivalence::tint_directions -- --nocapture cargo test -p lightcraft-color cct ``` diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f267092ebd..b6bee0dfac 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (context menus: a right-click elsewhere on the same widget moves its open menu instead of flashing it, issue #1877; Reference Escape, catalog-local pins and deleted-photo handling verified on Windows; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; earlier: zoom row soft proofing sharp at 1:1, canvas tools by keyboard, focus-order test, ~50 unnamed hand-drawn widgets named) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (KEYC-METADATA: ⌘⌥⇧C / ⌘⌥⇧V Copy / Paste Metadata; KEYC-RATING: ⌘L Enable Filters; context menus: a right-click elsewhere on the same widget moves its open menu instead of flashing it, issue #1877; Reference Escape, catalog-local pins and deleted-photo handling verified on Windows; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; earlier: zoom row soft proofing sharp at 1:1, canvas tools by keyboard, focus-order test, ~50 unnamed hand-drawn widgets named; KEYC-METADATA: ⌥0 / ⌥⇧0 next / previous keyword set; KEYC-RATING: ⌘L Enable Filters; context menus: a right-click elsewhere on the same widget moves its open menu instead of flashing it, issue #1877; Reference Escape, catalog-local pins and deleted-photo handling verified on Windows; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; earlier: zoom row soft proofing sharp at 1:1, canvas tools by keyboard, focus-order test, ~50 unnamed hand-drawn widgets named; KEYC-METADATA: ⌘K Add Keywords; KEYC-RATING: ⌘L Enable Filters; context menus: a right-click elsewhere on the same widget moves its open menu instead of flashing it, issue #1877; Reference Escape, catalog-local pins and deleted-photo handling verified on Windows; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; earlier: zoom row soft proofing sharp at 1:1, canvas tools by keyboard, focus-order test, ~50 unnamed hand-drawn widgets named) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 How LightCraft's interaction compares with Lightroom's: views, panels, tools and handles, modifier keys, shortcuts, zoom, context menus and feel. Rows for individual menu items and shortcuts live in @@ -27,7 +27,7 @@ assessment and the notes that don't fit a row. Visual reference for agents: `pla | Crop, Upright, transform handles | handles, aspect lock, angle, overlays (O / ⇧O), guided Upright | ✅ all of them; overlay cycle on ⇧O | 85% | crop opacity of cut-out area (15.5) | | Masking tools | brush (A / B, flow, density, auto mask, pressure), linear / radial, range masks, AI masks, pins | brush, linear, radial, colour / luminance range, add / subtract / intersect / invert, masks panel, pins | 60% | brush live preview (#517 / #518), no pen pressure, no depth range, AI masks, Feather / Edge controls (15.5) | | Remove / heal | content-aware remove, heal, clone, visualize spots | heal, clone, auto source, visualize spots, red / pet eye | 65% | content-aware (patch synthesis) remove, generative remove, detect distractions | -| Zoom and navigation | Fit / Fill / 1:1 / 2:1 … 11:1, Navigator, spacebar pan | Fit to 800%, pinch zoom, pan, Navigator-like | 60% | diagnostic overlays (Visualize Spots, Point Color range, HDR range) render the whole frame instead of a zoom window; everything else, mask overlays and soft proofing included, is sharp at 1:1–8:1 | +| Zoom and navigation | Fit / Fill / 1:1 / 2:1 … 11:1, Navigator, spacebar pan | Fit to 800%, pinch zoom, pan, Navigator-like; every view, mask and diagnostic overlays (Visualize Spots, Point Color range, HDR range) and soft proofing included, is sharp at 1:1–8:1 | 60% | zoom stops at 800 % (Adobe's reference goes to 11:1) | | Library culling and metadata | ratings, flags, labels with keys, painter, keywording, metadata panel, filter bar | ratings / flags / labels and advance, keyword list and sets, keywording box, metadata fields, smart albums, filter bar | 85% | painter tool, quick collection, some Classic keys | | Shortcuts | Lightroom desktop and Classic keymaps | Lightroom-desktop keymap with Classic additions, editable | 85% | deliberate differences below; no Classic keymap layer | | Context menus | everywhere | 31 sites (grid, filmstrip, albums, folders, keywords, masks, presets, text fields…), all through `widgets::context_menu` (`crates/ui-egui/src/widgets.rs`): a right-click elsewhere while a menu is open closes it and opens the menu there, also on the same widget (issue #1877: that one flashed at the new spot and closed, as egui counts the opening click as a click while open) | 70% | unaudited against Lightroom's menus item by item | @@ -66,12 +66,16 @@ under the UI command that wraps it (a no-op error); the UI command now wins. | Create Version | ⌘⇧S (+ ⇧M) | ⇧M (Windows: Ctrl+⇧S) | — | | Select None | ⌘⇧A (+ ⌘D) | ⌘D | — | -**Library culling (KEYC-RATING):** `0–5`, `6–9` and `P/X/U` reach egui on macOS even when displayed in the native menu (adapted from PR #261; issue #283). `Shift+0–9` applies and advances once; `Shift+P` picks and advances in Photo Grid / Square Grid and retains Presets elsewhere. See [library shortcuts](library-shortcuts.md) for the verified Classic mapping and regression coverage. F6, F7 and F8 show / hide the filmstrip, the left panel and the right panel (F8 brings back the panel it hid; `view.rightPanel`). `` ` `` cycles the flag (unflagged → pick → reject → unflagged) and ⌘↑ / ⌘↓ raise / lower it; the native menu leaves ⌘↑ / ⌘↓ to egui so Compare/Survey act on the active photo. `\` shows / hides the Filter Bar in Photo Grid / Square Grid and keeps Show Original in Detail. Remaining Classic gaps: ⌘L (Enable Filters). +**Library culling (KEYC-RATING):** `0–5`, `6–9` and `P/X/U` reach egui on macOS even when displayed in the native menu (adapted from PR #261; issue #283). `Shift+0–9` applies and advances once; `Shift+P` picks and advances in Photo Grid / Square Grid and retains Presets elsewhere. See [library shortcuts](library-shortcuts.md) for the verified Classic mapping and regression coverage. F6, F7 and F8 show / hide the filmstrip, the left panel and the right panel (F8 brings back the panel it hid; `view.rightPanel`). `` ` `` cycles the flag (unflagged → pick → reject → unflagged) and ⌘↑ / ⌘↓ raise / lower it; the native menu leaves ⌘↑ / ⌘↓ to egui so Compare/Survey act on the active photo. `\` shows / hides the Filter Bar in Photo Grid / Square Grid and keeps Show Original in Detail. ⌘L / Ctrl+L (Enable Filters) puts the filter aside and shows every photo, and the next press brings back the same filter, stars, flag and text together; setting or clearing a filter while it is off drops the one put aside (not documented by Adobe, our choice). ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V on Windows and Linux, KEYC-METADATA) copy the active photo's metadata and paste it on the selected photos. **Grid thumbnail size (KEYC-COMPARE):** Classic's `=` and `-` increase and decrease the Grid thumbnail size (same keys on macOS and Windows; `+` also works for the larger size here, as Shift+`=` or the keypad). They step the bottom-bar slider by 30 pt inside its 90–480 pt range, in Photo Grid, Square Grid and People only; Detail, Compare, Survey and Reference ignore them, and ⌘= / ⌘− stay Zoom In / Out. See [library shortcuts](library-shortcuts.md). +**Add Keywords key (KEYC-METADATA):** `⌘K` (`Ctrl+K` on Windows and Linux) is Add Keywords (`panel.addKeywords`): it shows the Keywords panel, opens its Keywording section when that is folded shut, and puts the cursor in the Add keyword box; pressed again it leaves the panel open. With no photo selected the panel says "Select photos to give them keywords." and the key does not move the cursor. The shortcut list names the key only; what the key opens is LightCraft's choice. Covered by `crates/ui-egui/src/tests_keywording.rs`. + **Library navigation keys (KEYC-COMPARE):** in Photo Grid and Square Grid, `Home` / `End` make the first / last photo of the view the active, selected one, and `Shift+Left` / `Shift+Right` add the previous / next photo of the view to the selection (the added photo becomes active; the keys never remove a photo from the selection, and do nothing at either end of the view). They wait in the other views, in the full-screen preview, while a text field or a dialog has the keyboard, and when you gave the key to a command; they are listed under Fixed keys in Help → Keyboard Shortcuts. `Cmd+O` (`Ctrl+O` on Windows and Linux) runs File → Open Library… ; View → Visualize HDR has no default key (`Shift+H` cycles the Tool Overlay, issue #224; `Cmd+Shift+H` stays the Histogram). Covered by `crates/ui-egui/src/tests_keymap.rs`; the macOS native menu path for `Cmd+O` is not exercised by the headless tests. +**Keyword sets (KEYC-METADATA):** `⌥0` / `⌥⇧0` (`Alt+0` / `Alt+Shift+0` on Windows and Linux) make the next / previous keyword set current (`keyword.nextSet`, `keyword.previousSet`), in the Keyword Set menu's order: Recent Keywords, then the saved sets. After the last set comes Recent Keywords, and before Recent Keywords comes the last set (not documented by Adobe, our choice). `⌥1`–`⌥9` then apply the new set's keywords. Both keys can be reassigned in Help → Keyboard Shortcuts. + **Still missing / broken:** - Tab / ⇧Tab (hide the side panels / all panels): Tab moves the keyboard focus here (accessibility), so it is not bound; F5 (hide the top panel) is not bound either. @@ -80,7 +84,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins. ## Accessibility audit -`crates/ui-egui/tests/accessibility.rs` walks the AccessKit tree egui hands to VoiceOver, Narrator and +`crates/ui-egui/tests/it/accessibility.rs` walks the AccessKit tree egui hands to VoiceOver, Narrator and AT-SPI, headless, in Photo Grid, Square Grid, Detail, Compare, Survey and Reference, in each right panel (Edit, Profiles, Crop, Remove, Masking, Red Eye, Versions, Activity, Keywords, Info) and in 13 dialogs (Export, Copy / Paste Settings, Create Preset, Rename, New Album, New Smart Album, Capture @@ -148,8 +152,13 @@ establish OS keyboard delivery or cross-platform acceptance. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | patch | KEYC-METADATA: ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V on Windows and Linux) copy and paste metadata | +| 2026-10-24 | minor | KEYC-METADATA: ⌥0 / ⌥⇧0 (Alt+0 / Alt+Shift+0) go to the next / previous keyword set, Recent Keywords first, wrapping around at either end | +| 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (Add Keywords) shows the Keywords panel with the cursor in its Add keyword box | | 2026-10-15 | patch | Context menus: a right-click elsewhere on the same widget while its menu is open moves the menu to the pointer; before it flashed at the new spot and closed (issue #1877); every site uses `widgets::context_menu`; 70% unchanged | +| 2026-10-23 | patch | KEYC-RATING: ⌘L / Ctrl+L (Library ▸ Enable Filters) switches the filter off and on, restoring it as it was | | 2026-10-15 | patch | KEYC-RATING: `\` shows / hides the Filter Bar in Photo Grid and Square Grid (Show Original in Detail); ⌘L is the filter-bar key left | +| 2026-10-14 | minor | Zoom row: diagnostic overlays render zoom windows too | | 2026-10-14 | patch | Shortcuts: Visualize HDR loses its default ⇧H, which cycles the Tool Overlay (issue #224); both PRs had claimed it | | 2026-10-12 | minor | Accessibility: crop handles, spots, gradient handles and mask pins operable by keyboard with AccessKit names and values; Tab order test for the right panels; hand-drawn icons and rows named; 55% → 75%; UI remaining 34–58 h → 32–54 h | | 2026-10-13 | minor | Shortcuts: Tool Overlay modes for spot and mask pins on ⇧H (H stays Remove; issue #224), listed with the deliberate differences; dropped from the missing list | diff --git a/docs/user/guides/edit-a-photo.md b/docs/user/guides/edit-a-photo.md index 366bf52125..af268731a0 100644 --- a/docs/user/guides/edit-a-photo.md +++ b/docs/user/guides/edit-a-photo.md @@ -9,12 +9,12 @@ Double-click a photo in the grid, then press `E` to open the **Edit** panel. Dra ## Steps -1. In **Photo Grid** or **Square Grid**, double-click the photo. It opens in the **Detail** view. -2. Press `E`, or choose **Window** > **Edit**, to open the **Edit** panel. +1. In **Photo Grid** or **Square Grid**, double-click the photo. It opens in the **Detail View**. +2. Press `E`, or choose **Window** > **Edit Panel**, to open the **Edit** panel. 3. Click **Auto** for a first pass, or skip this step and start with the sliders. 4. Open the **Light** section and set **Exposure**, **Contrast**, **Highlights**, **Shadows**, **Whites** and **Blacks**. 5. Open the **Color** section to change **Vibrance** and **Saturation**. Open **Effects** for **Texture**, **Clarity** and **Dehaze**. The panel also has **Detail** and **Optics** sections. -6. Check your work against the original. Hold `\` to peek at the original. Press `Y` (**View** > **Compare Before and After**) to see before and after side by side. +6. Check your work against the original. Hold `\` to peek at the original. Press `Y` (**View** > **Before/After Side by Side**) to see before and after side by side. 7. To go back a step, choose **Edit** > **Undo**. To drop all edits on the photo, click **Reset** at the top of the **Edit** panel. ## Black and white diff --git a/docs/web.md b/docs/web.md index 1d696266b8..5e5402d307 100644 --- a/docs/web.md +++ b/docs/web.md @@ -158,7 +158,10 @@ are the same in every version, so serve them with `Cache-Control: no-cache` (not `write` service hands each file to the browser as a download instead of writing it to disk. - **Automation.** `await lightcraft.command("library.info", "{}")` runs any engine or UI command by id on the next frame and resolves to the JSON result (`web.stats` reports storage, workers - and the render queue). This is how the headless-Chrome checks drive the page. + and the render queue). The params are a JSON object; empty text and JSON `null` mean `{}` + (no params: a command that takes photo ids then acts on the selection). Any other text that + isn't an object rejects the promise and runs nothing, as the control channel and MCP do, so a + typo can't run a command on the selection. This is how the headless-Chrome checks drive the page. - **Embedding (`?host=parent`).** A same-origin page framing LightCraft in an `<iframe>` speaks to it over `postMessage`, the protocol PdfCraft, GridCraft and DeckCraft share (`apps/lightcraft-web/src/host.rs`, issue #2270). LightCraft posts `lightcraft:ready` @@ -174,6 +177,10 @@ are the same in every version, so serve them with `Cache-Control: no-cache` (not before closing a window with edits. Only the parent window on the page's own origin is heard or answered; a page with an opaque origin (`"null"`: a sandboxed iframe, a `data:` page) gets no bridge. The library still lives in the iframe's browser storage. +- **The page title names the open photo**: `<file name> — LightCraft`, with ` •` after the name while + changes are not yet written to browser storage (`LightcraftApp::page_title`). eframe's web runner + ignores the window title the desktop app sets, and a host that embeds the page reads this title to + tell which photo a drop opened and whether it is saved (issue #2397). ## Not yet diff --git a/docs/whats-new.md b/docs/whats-new.md index aef899852a..1ba7a13149 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,14 +1,169 @@ # What's new in LightCraft -## 2026-10-22 +## 2026-10-26 ### The web build can be embedded - A page framing LightCraft in an iframe can open it with `?host=parent` and speak to it over `postMessage`, the protocol PdfCraft, GridCraft and DeckCraft share: it hands photos in, receives exports and backups instead of downloads, runs commands and hears whether closing would lose unsaved changes (issue #2270; `docs/web.md`). +## 2026-10-24 + +### Relative-date filters and smart albums follow the clock +- A current view or source count using “in the last” rules now refreshes when the session clock moves into a new + minute, even when no catalog edit occurred. This fixes stale photos remaining in the grid and stale counts for + direct or nested smart albums. Held views keep photos that expired until Refresh View while admitting photos that + newly match; expiry itself does not create an undo step. + +### The histogram's tonal zones adjust the Basic tones +- The histogram is a control surface again, as in Lightroom Classic: hovering one of its five zones (Blacks, Shadows, + Exposure, Highlights, Whites) tints it and shows its name and value under the plot ("Exposure: +0.45 EV"). Dragging one + sideways moves that control — the zone you pressed stays locked while the pointer crosses the others, Shift drags a + tenth as far, and the whole drag is one undo step. Double-clicking a zone puts its control back to its default. + +### Drag the parametric Tone Curve +- In the Tone Curve's parametric mode the graph is now drawn from the renderer's own curve, so it always matches the + photo, and the line can be dragged: pressing it picks the region under the pointer (Highlights, Lights, Darks or + Shadows) and moving up or down changes that slider, as one undo step. Hovering the line names the region first. + +## 2026-10-23 + +### Tab leaves the name field in New Album, New Smart Album and the name prompts +- In New Album, New Smart Album, Save Metadata Preset and the other dialogs with one name field, the field has the + keyboard focus when the dialog opens, and Tab now moves on to the check box, Cancel and OK (Shift+Tab goes back). + Before, the field took the focus back every frame, so only Return and Esc got you out of it. Return still + confirms and Esc still cancels. + +### Foreign XMP metadata survives namespace-prefix collisions +- Saving a sidecar keeps another application's properties even when its namespace uses prefixes such as `lc` + or `xmp`. Those foreign properties no longer become LightCraft settings or ratings when imported. + +### Find Missing Photos finds the files of a library made on Windows +- A library made on Windows records its originals with Windows paths. Opened on macOS or Linux, its photos are + missing until relinked, and Find Missing Photos found them only by their content, so it missed every photo it had + no fingerprint for (such as photos brought in from a Lightroom catalog) or that had been edited since, even in a + folder holding every file under the same name. It now matches them by name as it does any other photo: the name + after the last `/` or `\`, in any letter case, checked against the size when the library has one. Several files + of that name are still reported rather than guessed, and undo puts back the paths as they were. + +### Auto straighten leaves straight photos alone +- Auto straighten (Auto in the crop panel, or a double-click with the Straighten tool) no longer turns a photo by + more than 10°, and acts only when at least three lines agree. Before, it often turned photos that were straight: + the edges of wooden planks, a branch or a bird's wing were taken for the horizon, sometimes for a 25° turn. +- When it finds no horizon or vertical lines, it says so instead of doing nothing without a word. + +### PSD and PSB metadata stays available +- LightCraft now imports PSD and PSB files with EXIF and XMP image resources. Capture dates, GPS and descriptive fields + stay available in All Metadata; PSD edit copies keep their capture date. Original exports with Remove Location Info enabled + are refused when a PSD or PSB embeds GPS, since LightCraft cannot strip metadata from a byte-for-byte original copy. + +### Choose where a Lightroom catalog goes +- File ▸ Import Lightroom Catalog… now asks first: merge the catalog's photos, collections and edits into the + library open now, or create a new library for them, named after the catalog and placed next to the open library + (both can be changed). LightCraft opens the new library, then imports the catalog into it. Cancel does nothing. + Open Library… on a Lightroom catalog goes through the same choice. +- To import as before without the question, choose Settings ▸ General ▸ When importing a Lightroom catalog ▸ + Always merge into the open library, or tick Don't ask again in the window. Ask where to import it brings the + question back. + + +### Choose which library opens at launch +- Settings ▸ General ▸ **At launch**: *Open the last library* (as before) or *Ask me*. With *Ask me*, LightCraft + starts with a window listing your recent libraries: each one's name, the folder it is in and when you last opened + it. One that is gone (moved, renamed, on a disconnected drive), can't be read or no longer holds a library is + greyed out with the reason. Each one is checked in the background, showing *Checking…* until it answers (and that + the drive isn't answering after 5 s), so the list never waits on a network share that is offline or a disk that + has to wake up; File ▸ Open Recent Library uses the same answers (it greys out only libraries that are gone). Making the list only looks: it never locks or writes anything in your libraries, so one + that another program has open is reported, with who has it, when you press **Open**, and the window stays. The + last library is selected; **Open** (or Return, or a double-click) opens it, + **Open Another…** asks for a folder, **New Library…** makes one, **Quit** (or Esc) quits. ↑ and ↓ move through + the list. +- Holding Alt (Option on a Mac) as the window appears shows the same list once, over the library that opened: open + another one from it, or press Esc to keep working where you were. On a Mac, an Option key held from before + LightCraft starts is only noticed once it changes, so press it as the window appears. +- `--library` and `LIGHTCRAFT_LIBRARY` still decide the library when given, and `lightcraft-cli` never asks. +- File ▸ Open Recent Library ▸ **Remove from List** forgets one library, and the launch window's **Remove from + List** does the same. Only the entry goes: the library and its photos stay where they are. Agents use + `app.recentLibraries {remove: path}`; its list now also says when each library was last opened (`lastOpened`). +- Photos dropped on the window while the list (or the window of a library that couldn't open) is up wait for the + library you open and are imported into it, as files given on the command line are; presets dropped then are + refused with a note, since they belong to a library. + +## 2026-10-22 + +### Reliability +- Opening a library no longer writes through a link left at the lock's owner note (`catalog.lock.owner`): the link + is removed and a new note made in its place, so the file it pointed to is never changed (as for the catalog's + temporary files, issue #1502). + +### Keys reach text fields and the shortcut editor on macOS +- While a text field has focus, the native menu now lets go of the keys the field needs (`G`, the digits `0`–`9`, + `P`, `U` and the like), and while Keyboard Shortcuts is recording a key it lets go of all of them (⌘, and ⌘Q in + the LightCraft menu too), except the system's own items (Hide LightCraft ⌘H, Hide Others ⌥⌘H, Close Window ⌘W + and Minimize ⌘M) and the two keys of the Help menu (⌘/ and F1). Before, the menu item kept its key on macOS, so the + key could still run the menu command instead of reaching the field or the editor. The keys come back on the menu + items when the field loses focus or recording ends; the menu's order, checkmarks and enabled state are unchanged. + +### Find the grid shortcut in View +- Photo Grid and Square Grid now show the grid-cycle shortcut (G by default) in the View menu. The hints follow + shortcut changes; clicking a menu row still selects that grid (issue #2500). + + ## 2026-10-21 +### Settings window +- Settings is one size on every tab and stays where it is as you go through them; before, each tab made its own + size and the tabs moved under the pointer. The tabs stay in place while a long page scrolls (in a very short + LightCraft window, where the page has too little room to scroll by itself, the tabs and the page scroll together), a + page that goes on below shows a scroll handle without the pointer on it, and each page remembers where it was + scrolled to, also when Settings is closed and opened again. +- Nothing in Settings runs off the side any more. A row with more choices than fit (the languages on General) wraps + onto further lines and a long label wraps in its column, where both used to widen the window: in a small + LightCraft window the labels and the Close button of General ended up off screen. +- The Slideshow tab is one column like the other tabs, with the slide preview first, instead of a column beside the + preview that made Settings much wider on that tab. The preview stays above the page while it scrolls, so pointing + at a template further down still shows it there (in a very short window it scrolls with the page instead). Pointing + at a template no longer pushes its rows out from under the pointer, and the Export buttons wrap. +- A long folder (General ▸ Library ▸ Location, the folder Auto Import watches, the smart previews folder, a monitor + profile's file) is shortened to its last folders ("…/Pictures/Library") on one line; rest the pointer on it for + the whole path. +### One star rating control +- The stars in the bottom bar, the Info panel and the filter bar are now one shared control, and the badges on grid + cells, filmstrip thumbnails and the Compare caption use the same drawing. Hovering a star in the filter bar now + previews the rating like the others do, and with a star focused (Tab), ← and → lower and raise the rating. +### Progress looks the same everywhere +- Download, scan, denoise and activity progress now use one bar that fills the width it is given, with its text on + it, and a gentle sweep while the amount of work isn't known yet. Waits that only said "Selecting…", "Waiting to + start…" or "Installing…" now show a small turning arc beside the text, and a thumbnail still being made shows a + quiet placeholder that fits the theme in the grid, the filmstrip and Compare. Screen readers hear a progress + indicator with its percentage. +### Menu names that say what they are +- Switches in the menus are named for what they show, with the check mark saying whether it is on: Filmstrip ✓, + Focus Point ✓, Clipping ✓, Photo Counts ✓, Mask Overlay ✓ instead of Show Focus Point ✓. No two commands share a + name any more: View ▸ Detail is now Detail View (the Edit section Detail keeps its name), Window ▸ Edit is Edit + Panel, and Compare Before and After is Before/After Side by Side, next to Split and Top/Bottom. +- The preview cache command has one name, Discard Preview Cache, in File ▸ Previews and in the toast that confirms + it. Keyboard shortcuts are unchanged. +### Dropping files shows what will happen +- While files are dragged over the window, it dims and a card says what dropping will do: review the photos and + folders for import, import the presets, or open the face model. If a dialog is open, the card asks you to close it + first, and a drop is refused with a message instead of replacing the dialog. The same goes while an import is + running, and in the web version. +- The import review of a finished scan (a drop, or File ▸ Import) no longer replaces a dialog you opened in the + meantime; it opens as soon as that dialog is closed. +- Photos and folders dropped on the window now open the same import review as File ▸ Import, so you pick add, copy or + move, the destination and a preset before anything is imported. Settings ▸ Import ▸ "Import dropped files without + review" brings back the old behaviour of importing at once. +- In the web version, a dropped file the browser can't read, or that can't be imported, now shows a message instead of + failing silently. +- For scripts: `ui.dropFiles` hovers files over the window or drops them, as the operating system does. +### Counting many smart albums is faster +- Counting every smart album at once (the numbers in the Albums list, and the `albums.list` command) now works out an + album that other smart albums test (“album is …”) once for the whole library, instead of again for every album + that tests it. On a synthetic library of 312,000 photos with 77 smart albums, 51 of them testing one shared album, + the full count took about 14 s instead of about 23 s on a heavily loaded machine; the rest is the text rules of + the albums themselves. The counts are the same as before, including for albums that loop through each other. + ### Sharper resampling in HDR and panorama merges - Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around @@ -46,6 +201,20 @@ - `photo.setReference` refuses an `id` that is not a photo id (a string, a negative or fractional number) instead of pinning the active photo; only an absent or null `id` means the active photo. +### Edit Capture Time leaves a capture time it can't read as it was +- A capture time that is cut short, has seconds that aren't digits or has text after it (a Lightroom catalog's capture + time is copied as it is) is no longer shifted into a clean-looking wrong time: Edit Capture Time leaves the photo as + it was and says so, and its preview says the photo's time can't be read instead of previewing a wrong one. + `photo.setCaptureTime` counts those photos as `unreadable`. Set date & time still repairs such a photo selected on + its own; with other photos selected it says why it can't move them by the same amount. When the dialog can't make a + change (a time that isn't a date, a shift past year 9999), it now says why and stays open, instead of closing. + +### Month names in folder and file name templates +- Date templates take the month by name: `%B` gives January, `%b` gives Jan. Import ▸ Folders ▸ Custom template… + `{date:%Y}/{date:%B}` files photos into 2026/January, 2026/February…, the layout many existing libraries already + use. The names are English in every interface language, so folders don't change when the language does. Rename + Photos and export file names take them too. + ## 2026-10-20 ### Smart albums check File Path rules faster @@ -54,7 +223,6 @@ or "doesn't contain" rule took about 17 ms per pass instead of about 62 ms, around 3.5 times faster, with the same photos matched; about 6 ms of that is only reading the paths. Paths and rule text with letters beyond A–Z are compared as before. - ## 2026-10-19 ### AI Denoise on DirectX 12 with NVIDIA GTX 10-series cards @@ -77,6 +245,13 @@ - With several locations removed from Local, "Show N hidden locations" now lists them, so each comes back on its own (Restore All is there too). The row used to bring every hidden location back at once (issue #2114). +### Rating in a filtered view keeps your place +- When a filter shows only one-star photos and you take the star off a photo, it leaves the view and the photo after + it is now selected, so you carry on from where you were (issue #2312). The same goes for flags and colour labels, + in Picks and in smart albums. Before, the photo stayed selected although the grid no longer showed it, and → or + Auto Advance jumped back to the first photo of the view. With Auto Advance on, or with Shift+0–5, you land on the + photo after it: no photo is skipped. + ## 2026-10-18 ### Thumbnails of Lightroom HDR and panorama merges in a second @@ -148,7 +323,6 @@ one (issue #1507). LightCraft used to open the library without it, showing an incomplete catalog that the next save would write over the stored copy. It now leaves the library unopened, saves nothing and says which file couldn't be read; reload the page to try again. - ## 2026-10-14 ### Model downloads time out on a name that doesn't resolve @@ -394,6 +568,15 @@ screen and nearly as tall counts as zoomed. - For scripts: a size set with `ui.resize` is remembered like any other, so a script that needs a size sets it. +### Keyword List: a keyword shows that one inside it is applied +- In the Keyword List (right panel ▸ Keywords), a keyword whose box is empty now carries a dot in it when the + selected photos have a keyword inside it, at any depth: with `Places › Italy › Rome` on a photo, `Places` and + `Italy` show the dot and `Rome` the tick. A folded keyword no longer hides that something in it is applied. + Resting on the box names what is inside. +- The tick and the dash are as they were, and are about the keyword itself: all of the selected photos have it, or + some do. A keyword the photos have themselves shows that, not the dot. A click on the box still gives the + keyword itself to the selected photos. + ### HDR merges keep the lens correction - An HDR made with Photo ▸ Photo Merge ▸ HDR now keeps the lens correction the photos carry (Sony's, Panasonic's and Leica's, and the one some DNGs carry, e.g. from drones): Optics ▸ Enable Lens Corrections straightens it as it diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index b90e76c40e..7fd11a1728 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -81,6 +81,9 @@ the only copy of those edits outside that application's catalog. Saving never dr ones), `xmp:CreatorTool`, comments, the packet wrapper and padding. LightCraft's properties go into one `rdf:Description` of their own; owned properties written by another application (in attribute or element form) are removed from its description, which otherwise stays as it was. +- Ownership follows the namespace URI, not the prefix spelling. A foreign namespace bound to `lc:` or `xmp:` + stays foreign: its properties are preserved and do not become LightCraft settings or ratings. Genuine namespace + aliases remain interchangeable, including namespace declarations containing XML character references. - A sidecar that can't be read as XMP (not well-formed, not UTF-8, no `rdf:RDF`) is first copied to `<name>.xmp.bak-<date><time>` (`-1`, `-2`… if taken — a backup is never overwritten), then replaced. A sidecar that can't be read at all (permissions) is left alone and the save fails. diff --git a/flake.lock b/flake.lock index a9953fd126..29faf1a7cd 100644 --- a/flake.lock +++ b/flake.lock @@ -3,17 +3,17 @@ "craft-fonts": { "flake": false, "locked": { - "lastModified": 1791722036, - "narHash": "sha256-mNnDzBcOp1X10dzmiW0iBAkb74QjuzMO4slWudxXCTE=", + "lastModified": 1792808533, + "narHash": "sha256-jZ3VBAJDofB6RvsS7GGV5lLT4xiShIjpz5XHBCD2oUc=", "owner": "storytold", "repo": "craft-fonts", - "rev": "3d9ab3a132ed0eff457e424226a435a901da30d3", + "rev": "b076417b5880bd4154bd22f00695b1d28c6bea83", "type": "github" }, "original": { "owner": "storytold", "repo": "craft-fonts", - "rev": "3d9ab3a132ed0eff457e424226a435a901da30d3", + "rev": "b076417b5880bd4154bd22f00695b1d28c6bea83", "type": "github" } }, diff --git a/flake.nix b/flake.nix index 51dd933f9a..faa7e1d2ee 100644 --- a/flake.nix +++ b/flake.nix @@ -2,17 +2,21 @@ description = "LightCraft — photo library and non-destructive raw developer, in pure Rust"; inputs = { - # LightCraft needs edition 2024 and rustc ≥ 1.90, so the flake tracks unstable. Consumers on a + # LightCraft needs edition 2024 and rustc ≥ 1.95, so the flake tracks unstable. Consumers on a # release channel can retarget it: `inputs.lightcraft.inputs.nixpkgs.follows = "nixpkgs";` nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; - # Optional build input of the repository: the CJK fonts (BIZ UDPGothic, BIZ UDMincho, Noto Sans CJK SC, - # Shippori Mincho) that `crates/engine/build.rs` embeds when `CRAFT_FONTS_DIR` is set. Official - # releases always build with them; without them everything works but Japanese text has no - # glyphs. Pinned to the revision the release workflow uses — bump deliberately - # (`nix flake update craft-fonts`); craftrules standards/fonts.md. + # Optional build input of the repository: the default fonts (BIZ UDPGothic Regular/Bold, BIZ UDMincho, + # Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans Thai, Noto Sans Georgian, + # NanumGothic, Noto Sans Symbols, Noto Sans Symbols 2, Noto Sans Hebrew and Noto Sans Devanagari) + # listed in craft-fonts' `fonts/manifest.txt`, which `crates/engine/build.rs` embeds when + # `CRAFT_FONTS_DIR` is set. The opt-in LXGW WenKai Lite face in `fonts/simplified-chinese-manifest.txt` + # is not part of that default set and is not embedded. Official releases always build with the + # default fonts; without them everything works but non-Latin text lacks glyphs. Pinned to the same + # revision CI, the release workflow and the standalone packaging helpers use — bump all of them + # together (`nix flake update craft-fonts`); craftrules standards/fonts.md. craft-fonts = { - url = "github:storytold/craft-fonts/3d9ab3a132ed0eff457e424226a435a901da30d3"; + url = "github:storytold/craft-fonts/b076417b5880bd4154bd22f00695b1d28c6bea83"; flake = false; }; }; diff --git a/packaging/check-app-specific.sh b/packaging/check-app-specific.sh index 3b84227f2d..5600c071cb 100644 --- a/packaging/check-app-specific.sh +++ b/packaging/check-app-specific.sh @@ -5,10 +5,10 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.." for want in '<UIRef Id="LightcraftUI" />' 'Value="InstallDirDlg"' '<Property Id="WIXUI_INSTALLDIR" Value="INSTALLFOLDER" />' \ 'Key="Software\LightCraft" Name="InstallFolder"' 'Value="LaunchLightcraft"'; do - grep -qF "$want" packaging/windows/lightcraft.wxs || { echo "::error::lightcraft.wxs lost: $want"; exit 1; } + grep -qF "$want" packaging/windows/lightcraft.wxs || { echo "::error::lightcraft.wxs lost: $want" >&2; exit 1; } done grep -qF '<DialogRef Id="ExitDialog" />' packaging/windows/lightcraft.wxs \ - || { echo "::error::ExitDialog is not referenced; installs and removes end without a completion dialog"; exit 1; } + || { echo "::error::ExitDialog is not referenced; installs and removes end without a completion dialog" >&2; exit 1; } python3 - <<'PYEOF' import yaml diff --git a/packaging/env.sh b/packaging/env.sh index 11221a5eed..591cdfb862 100644 --- a/packaging/env.sh +++ b/packaging/env.sh @@ -19,10 +19,11 @@ workspace_version() { /^\[/ { in_pkg = ($0 == "[workspace.package]") ; next } in_pkg && $1 == "version" { gsub(/[" ]/, "", $3); print $3; exit } ' "$ROOT/Cargo.toml" + return $? } VERSION="${LIGHTCRAFT_VERSION:-$(workspace_version)}" -if [ -z "$VERSION" ]; then +if [[ -z "$VERSION" ]]; then echo "error: could not read [workspace.package] version from $ROOT/Cargo.toml" >&2 exit 1 fi @@ -32,7 +33,7 @@ DIST="${DIST:-$ROOT/dist/release}" mkdir -p "$DIST" export DIST -if [ -z "${LIGHTCRAFT_BUILD_SHA:-}" ]; then +if [[ -z "${LIGHTCRAFT_BUILD_SHA:-}" ]]; then LIGHTCRAFT_BUILD_SHA="$(git -C "$ROOT" rev-parse HEAD 2>/dev/null || true)" fi export LIGHTCRAFT_BUILD_SHA @@ -41,26 +42,31 @@ export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" # Emit a GitHub Actions warning (plain stderr outside Actions). warn() { - if [ -n "${GITHUB_ACTIONS:-}" ]; then echo "::warning::$*"; else echo "warning: $*" >&2; fi + if [[ -n "${GITHUB_ACTIONS:-}" ]]; then echo "::warning::$*"; else echo "warning: $*" >&2; fi + return 0 } -# Copy licence and readme files that exist into a package directory (plus the craft-fonts licences -# when building with CRAFT_FONTS_DIR). +# Copy licence and readme files that exist into a package directory, plus the font licence texts +# (Inter's OFL always; the craft-fonts OFLs when building with CRAFT_FONTS_DIR). copy_docs() { local dest="$1" f for f in README.md LICENSE LICENSE-MIT LICENSE-APACHE COPYRIGHT NOTICE; do - if [ -f "$ROOT/$f" ]; then cp "$ROOT/$f" "$dest/"; fi + if [[ -f "$ROOT/$f" ]]; then cp "$ROOT/$f" "$dest/"; fi done copy_font_licences "$dest" + return $? } -# Builds made with CRAFT_FONTS_DIR (storytold/craft-fonts, an optional build input) embed its fonts; -# their OFL licences go with the package as OFL-<family-dir>.txt. Nothing to do without it. +# Inter is embedded in every build (crates/ui-egui/src/theme.rs), so its OFL always ships with the +# package as OFL-Inter.txt. Builds made with CRAFT_FONTS_DIR (storytold/craft-fonts, an optional +# build input) also embed its fonts; their OFL licences go with the package as OFL-<family-dir>.txt. copy_font_licences() { local dest="$1" lic family - [ -n "${CRAFT_FONTS_DIR:-}" ] || return 0 + local inter="$ROOT/assets/fonts/OFL-Inter.txt" + cp "$inter" "$dest/OFL-Inter.txt" || return $? + [[ -n "${CRAFT_FONTS_DIR:-}" ]] || return 0 for lic in "$CRAFT_FONTS_DIR"/fonts/*/OFL.txt; do - [ -f "$lic" ] || continue + [[ -f "$lic" ]] || continue family="$(basename "$(dirname "$lic")")" cp "$lic" "$dest/OFL-$family.txt" done @@ -68,5 +74,7 @@ copy_font_licences() { # Portable SHA-256 of a file (prints just the hash). sha256() { - if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi + local file="$1" + if command -v sha256sum >/dev/null; then sha256sum "$file" | cut -d' ' -f1; else shasum -a 256 "$file" | cut -d' ' -f1; fi + return $? } diff --git a/packaging/fonts.sh b/packaging/fonts.sh index 70d9fe14ea..cab0e43508 100644 --- a/packaging/fonts.sh +++ b/packaging/fonts.sh @@ -8,9 +8,9 @@ prepare_fonts() { *) font_dir="$ROOT/$font_dir" ;; esac - if [ -z "${CRAFT_FONTS_DIR:-}" ] && [ ! -e "$font_dir" ]; then + if [[ -z "${CRAFT_FONTS_DIR:-}" ]] && [[ ! -e "$font_dir" ]]; then # Same revision as release.yml. Never update or reset an existing checkout. - local revision=3d9ab3a132ed0eff457e424226a435a901da30d3 + local revision=b076417b5880bd4154bd22f00695b1d28c6bea83 echo "==> downloading craft-fonts ($revision) to $font_dir" if ! git clone --no-checkout https://github.com/storytold/craft-fonts "$font_dir" || ! git -C "$font_dir" checkout --detach "$revision"; then @@ -19,7 +19,7 @@ prepare_fonts() { fi fi - if [ ! -f "$font_dir/fonts/manifest.txt" ]; then + if [[ ! -f "$font_dir/fonts/manifest.txt" ]]; then echo "error: missing $font_dir/fonts/manifest.txt; set CRAFT_FONTS_DIR to a complete craft-fonts checkout" >&2 return 1 fi diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 665444f803..1e4c5ed41d 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -20,7 +20,7 @@ APP_ID=ai.storyteller.lightcraft SKIP_BUILD=0 DRY_RUN=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --dry-run) DRY_RUN=1; SKIP_BUILD=1; shift ;; @@ -36,7 +36,7 @@ case "$MACHINE" in arm64 | aarch64) ARCH=aarch64 ;; *) echo "unsupported architecture $MACHINE" >&2; exit 2 ;; esac -if [ "$DRY_RUN" = 0 ] && [ "$(uname -s)" != FreeBSD ]; then +if [[ "$DRY_RUN" = 0 ]] && [[ "$(uname -s)" != FreeBSD ]]; then echo "error: build on FreeBSD (or pass --dry-run to check the tree layout)" >&2 exit 2 fi @@ -46,7 +46,7 @@ echo "==> LightCraft $VERSION for FreeBSD $ARCH" # The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p lightcraft -p lightcraft-cli --features lightcraft/heif,lightcraft-cli/heif) fi WORK="$CARGO_TARGET_DIR/freebsd-package" @@ -56,7 +56,7 @@ mkdir -p "$WORK" BIN="$CARGO_TARGET_DIR/release" OUT_DIR="$DIST" -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then # Stub binaries, and the tarball stays in the work dir so dist/ only ever holds real builds. BIN="$WORK/stub-bin" OUT_DIR="$WORK" @@ -84,7 +84,7 @@ copy_docs "$STAGE/share/doc/lightcraft" for f in bin/lightcraft bin/lightcraft-cli "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ share/doc/lightcraft/LICENSE-MIT share/doc/lightcraft/LICENSE-APACHE; do - if [ ! -e "$STAGE/$f" ]; then echo "error: $f is missing from the package" >&2; exit 1; fi + if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done # ---- .tar.gz ------------------------------------------------------------------------------------ @@ -93,7 +93,7 @@ tar -C "$WORK" -czf "$OUT_DIR/$BASENAME.tar.gz" "$BASENAME" echo "wrote $OUT_DIR/$BASENAME.tar.gz" "$STAGE/bin/lightcraft-cli" --version -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then echo "==> dry run: tarball contents" tar -tzvf "$OUT_DIR/$BASENAME.tar.gz" fi diff --git a/packaging/icons.sh b/packaging/icons.sh index cf7895ecbd..b0a2f17d99 100755 --- a/packaging/icons.sh +++ b/packaging/icons.sh @@ -22,7 +22,10 @@ MAC="$TMP/macos.svg" sed 's/viewBox="0 0 512 512"/viewBox="-62 -62 636 636"/' "$SVG" >"$MAC" grep -q 'viewBox="-62 -62 636 636"' "$MAC" || { echo "error: unexpected viewBox in $SVG" >&2; exit 1; } -render() { resvg -w "$2" -h "$2" "$1" "$3" </dev/null; } +render() { + local src="$1" size="$2" out="$3" + resvg -w "$size" -h "$size" "$src" "$out" </dev/null +} render "$SVG" 1024 "$DIR/lightcraft-1024.png" # Runtime window/Dock icon on macOS (embedded by apps/lightcraft/src/main.rs). diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 6ad39ebec7..4638fdcc37 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -21,7 +21,7 @@ FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 TARBALL="" -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --no-test) TEST=0; shift ;; -h | --help) sed -n '2,14p' "$0"; exit 0 ;; @@ -38,7 +38,7 @@ case "$ARCH" in esac BASENAME="lightcraft-$VERSION-linux-$ARCH" TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}" -[ -f "$TARBALL" ] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } +[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } for tool in flatpak flatpak-builder; do command -v "$tool" >/dev/null || { echo "error: $tool not found (apt install flatpak flatpak-builder librsvg2-common)" >&2; exit 1; } done @@ -49,7 +49,7 @@ WORK="$CARGO_TARGET_DIR/flatpak-bundle" rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 -[ -x "$WORK/stage/bin/lightcraft" ] || { echo "error: $TARBALL has no bin/lightcraft" >&2; exit 1; } +[[ -x "$WORK/stage/bin/lightcraft" ]] || { echo "error: $TARBALL has no bin/lightcraft" >&2; exit 1; } cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" flatpak remote-add --user --if-not-exists flathub "$FLATHUB" @@ -62,7 +62,7 @@ OUT="$DIST/$BASENAME.flatpak" flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" -if [ "$TEST" = 1 ]; then +if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" flatpak info --user "$APP_ID" flatpak run --command=lightcraft-cli "$APP_ID" --version diff --git a/packaging/linux/flatpak/ai.storyteller.lightcraft.yml b/packaging/linux/flatpak/ai.storyteller.lightcraft.yml index e9dbd244b5..4e03df0055 100644 --- a/packaging/linux/flatpak/ai.storyteller.lightcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.lightcraft.yml @@ -52,6 +52,9 @@ modules: - install -Dm644 packaging/linux/ai.storyteller.lightcraft.desktop /app/share/applications/ai.storyteller.lightcraft.desktop - install -Dm644 packaging/linux/ai.storyteller.lightcraft.mime.xml /app/share/mime/packages/ai.storyteller.lightcraft.xml - mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/ + - install -Dm644 NOTICE /app/share/doc/lightcraft/NOTICE + - install -Dm644 assets/ATTRIBUTION.md /app/share/doc/lightcraft/ATTRIBUTION.md + - install -Dm644 assets/fonts/OFL-Inter.txt /app/share/doc/lightcraft/OFL-Inter.txt - >- version=$(awk '/^\[/{p=($0=="[workspace.package]");next} p&&$1=="version"{gsub(/[" ]/,"",$3);print $3;exit}' Cargo.toml); install -d /app/share/metainfo; diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 084972f72b..d42fc5fd3e 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -24,7 +24,7 @@ APP_ID=ai.storyteller.lightcraft SKIP_BUILD=0 FORMATS="appimage deb rpm tar" -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; @@ -45,7 +45,7 @@ BASENAME="lightcraft-$VERSION-linux-$ARCH" echo "==> LightCraft $VERSION for Linux $ARCH ($FORMATS)" -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then # shellcheck source=../fonts.sh . "$ROOT/packaging/fonts.sh" prepare_fonts @@ -78,7 +78,10 @@ if command -v appstreamcli >/dev/null; then appstreamcli validate --no-net --explain "$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" fi -has() { case " $FORMATS " in *" $1 "*) return 0 ;; *) return 1 ;; esac; } +has() { + local format="$1" + case " $FORMATS " in *" $format "*) return 0 ;; *) return 1 ;; esac +} # ---- .tar.gz ------------------------------------------------------------------------------------ if has tar; then @@ -102,27 +105,63 @@ fi # ---- AppImage ----------------------------------------------------------------------------------- if has appimage; then + APPIMAGETOOL_VERSION=1.9.1 + case "$ARCH" in + x86_64) APPIMAGETOOL_SHA256=ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0 ;; + aarch64) APPIMAGETOOL_SHA256=f0837e7448a0c1e4e650a93bb3e85802546e60654ef287576f46c71c126a9158 ;; + *) APPIMAGETOOL_SHA256='' ;; + esac + # The runtime appimagetool embeds in every AppImage; unpinned, it would fetch type2-runtime's + # moving `continuous` build and embed it unchecked. + RUNTIME_VERSION=20251108 + case "$ARCH" in + x86_64) RUNTIME_SHA256=2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d ;; + aarch64) RUNTIME_SHA256=00cbdfcf917cc6c0ff6d3347d59e0ca1f7f45a6df1a428a0d6d8a78664d87444 ;; + *) RUNTIME_SHA256='' ;; + esac APPDIR="$WORK/LightCraft.AppDir" cp -R "$STAGE" "$APPDIR" - mv "$APPDIR/usr/share/doc" "$WORK/doc-unused" ln -s usr/bin/lightcraft "$APPDIR/AppRun" cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" ln -s "$APP_ID.png" "$APPDIR/.DirIcon" TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" - if [ -z "$TOOL" ]; then - TOOL="$CARGO_TARGET_DIR/appimagetool-$ARCH.AppImage" - if [ ! -x "$TOOL" ]; then - curl --proto '=https' -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" - chmod +x "$TOOL" + if [[ -z "$TOOL" ]]; then + if [[ -z "$APPIMAGETOOL_SHA256" ]]; then + echo "no pinned appimagetool for $ARCH; set APPIMAGETOOL or put appimagetool on PATH" >&2 + exit 2 fi + TOOL="$CARGO_TARGET_DIR/appimagetool-$APPIMAGETOOL_VERSION-$ARCH.AppImage" + if [[ ! -x "$TOOL" ]]; then + download="$TOOL.download" + curl --proto '=https' -fsSL -o "$download" \ + "https://github.com/AppImage/appimagetool/releases/download/$APPIMAGETOOL_VERSION/appimagetool-$ARCH.AppImage" + printf '%s %s\n' "$APPIMAGETOOL_SHA256" "$download" | sha256sum -c - + chmod 755 "$download" + mv "$download" "$TOOL" + fi + printf '%s %s\n' "$APPIMAGETOOL_SHA256" "$TOOL" | sha256sum -c - fi + if [[ -z "$RUNTIME_SHA256" ]]; then + echo "no pinned AppImage runtime for $ARCH" >&2 + exit 2 + fi + RUNTIME="$CARGO_TARGET_DIR/appimage-runtime-$RUNTIME_VERSION-$ARCH" + if [[ ! -f "$RUNTIME" ]]; then + download="$RUNTIME.download" + curl --proto '=https' -fsSL -o "$download" \ + "https://github.com/AppImage/type2-runtime/releases/download/$RUNTIME_VERSION/runtime-$ARCH" + printf '%s %s\n' "$RUNTIME_SHA256" "$download" | sha256sum -c - + mv "$download" "$RUNTIME" + fi + printf '%s %s\n' "$RUNTIME_SHA256" "$RUNTIME" | sha256sum -c - # Absolute, because appimagetool runs in $DIST below (CARGO_TARGET_DIR or APPIMAGETOOL may be # relative). OUT="$(cd "$DIST" && pwd)/$BASENAME.AppImage" APPDIR="$(cd "$APPDIR" && pwd)" TOOL="$(cd "$(dirname "$TOOL")" && pwd)/$(basename "$TOOL")" + RUNTIME="$(cd "$(dirname "$RUNTIME")" && pwd)/$(basename "$RUNTIME")" # A .zsync left by an earlier run would hide a missing zsyncmake and describe another file. rm -f "$OUT.zsync" # Update information: AppImageUpdate, AppImageLauncher and the like read it from the file and @@ -134,18 +173,18 @@ if has appimage; then # Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime, # so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync # package) appimagetool also writes the .zsync, into its working directory, hence the cd. - (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT") echo "wrote $OUT" - if [ -s "$OUT.zsync" ]; then + if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" else warn "zsyncmake not found, so $OUT.zsync was not written; AppImage delta updates need it" fi fi -if [ -z "${CROSS_TARGET:-}" ]; then +if [[ -z "${CROSS_TARGET:-}" ]]; then "$STAGE/usr/bin/lightcraft-cli" --version -elif [ -n "${EMULATOR:-}" ]; then +elif [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$STAGE/usr/bin/lightcraft-cli" --version fi echo "==> done" diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh index ef966034e4..959f80fcef 100755 --- a/packaging/macos/import-cert.sh +++ b/packaging/macos/import-cert.sh @@ -12,14 +12,18 @@ umask 077 # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" -if [ -z "${APPLE_CERTIFICATE:-}" ]; then +if [[ -z "${APPLE_CERTIFICATE:-}" ]]; then warn "APPLE_CERTIFICATE is not set: macOS builds will be ad-hoc signed and not notarized" exit 0 fi TMP="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" -KEYCHAIN="$TMP/lightcraft-signing.keychain-db" -CERT="$TMP/lightcraft-signing.p12" +# A private directory (mktemp -d): a predictable name in a shared TMPDIR can be precreated by another +# local account, and a plain redirect would then receive the private key archive (CWE-377). Encoded +# signing material is written only inside the 0700 directory. +CERTDIR="$(mktemp -d "$TMP/lightcraft-signing.XXXXXX")" +KEYCHAIN="$CERTDIR/lightcraft-signing.keychain-db" +CERT="$CERTDIR/lightcraft-signing.p12" KC_PASS="${KEYCHAIN_PASSWORD:-$(openssl rand -hex 24)}" trap 'rm -f "$CERT"' EXIT @@ -36,13 +40,13 @@ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KC_PASS" security list-keychains -d user -s "$KEYCHAIN" $(security list-keychains -d user | tr -d '"') IDENTITY="$(security find-identity -v -p codesigning "$KEYCHAIN" | awk '/Developer ID Application/ { print $2; exit }')" -if [ -z "$IDENTITY" ]; then +if [[ -z "$IDENTITY" ]]; then security find-identity -v -p codesigning "$KEYCHAIN" >&2 echo "error: no 'Developer ID Application' identity in APPLE_CERTIFICATE" >&2 exit 1 fi echo "Imported signing identity $IDENTITY" -if [ -n "${GITHUB_ENV:-}" ]; then +if [[ -n "${GITHUB_ENV:-}" ]]; then { echo "MACOS_SIGN_IDENTITY=$IDENTITY"; echo "MACOS_KEYCHAIN=$KEYCHAIN"; } >>"$GITHUB_ENV" else echo "MACOS_SIGN_IDENTITY=$IDENTITY" diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index f26237a4cd..eab3cde225 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -20,7 +20,7 @@ HERE="$ROOT/packaging/macos" ARCH=universal SKIP_BUILD=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --arch) ARCH="$2"; shift 2 ;; --skip-build) SKIP_BUILD=1; shift ;; @@ -45,9 +45,9 @@ DMG="$DIST/lightcraft-$VERSION-macos-$ARCH.dmg" CLI_ZIP="$DIST/lightcraft-cli-$VERSION-macos-$ARCH.zip" NOTARIZE=0 -if [ "$IDENTITY" = "-" ]; then +if [[ "$IDENTITY" = "-" ]]; then warn "macOS: ad-hoc signing (no MACOS_SIGN_IDENTITY); artifacts are not notarized" -elif [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then +elif [[ -n "${APPLE_ID:-}" ]] && [[ -n "${APPLE_PASSWORD:-}" ]] && [[ -n "${APPLE_TEAM_ID:-}" ]]; then NOTARIZE=1 else warn "macOS: APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID incomplete; signed but not notarized" @@ -56,7 +56,7 @@ fi echo "==> LightCraft $VERSION for macOS ($ARCH), identity: $IDENTITY, notarize: $NOTARIZE" # ---- build ------------------------------------------------------------------------------------- -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then # shellcheck source=../fonts.sh . "$ROOT/packaging/fonts.sh" prepare_fonts @@ -78,9 +78,9 @@ done sign() { # Hardened runtime + secure timestamp for a real identity; ad-hoc can't be timestamped. local ts=(--timestamp) - [ "$IDENTITY" = "-" ] && ts=(--timestamp=none) + [[ "$IDENTITY" = "-" ]] && ts=(--timestamp=none) local kc=() - [ -n "${MACOS_KEYCHAIN:-}" ] && kc=(--keychain "$MACOS_KEYCHAIN") + [[ -n "${MACOS_KEYCHAIN:-}" ]] && kc=(--keychain "$MACOS_KEYCHAIN") codesign --force --sign "$IDENTITY" ${kc[@]+"${kc[@]}"} "${ts[@]}" "$@" } @@ -92,8 +92,8 @@ notarize() { echo "$out" id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" - if [ "$status" != "Accepted" ]; then - if [ -n "$id" ]; then + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" || true fi echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 @@ -126,7 +126,7 @@ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" codesign --verify --strict --deep --verbose=2 "$APP" -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then ditto -c -k --keepParent "$APP" "$WORK/LightCraft-notarize.zip" notarize "$WORK/LightCraft-notarize.zip" xcrun stapler staple "$APP" @@ -149,16 +149,16 @@ rm -f "$DMG" # create -srcfolder preserves the signed app and the existing .DS_Store layout. # hdiutil may transiently return "Resource busy" on CI; retry boundedly. hdiutil_retry() { - local attempt + local verb="$1" attempt for attempt in 1 2 3 4 5; do if hdiutil "$@"; then return 0 fi - if [ "$attempt" = 5 ]; then - echo "error: hdiutil $1 failed after five attempts" >&2 + if [[ "$attempt" = 5 ]]; then + echo "error: hdiutil $verb failed after five attempts" >&2 return 1 fi - warn "hdiutil $1 attempt $attempt failed; retrying" + warn "hdiutil $verb attempt $attempt failed; retrying" sleep $((attempt * 10)) done } @@ -179,17 +179,17 @@ verify_dmg_app() { fi echo "==> strict codesign of LightCraft.app in finished DMG" codesign --verify --deep --strict --verbose=2 "$mount/LightCraft.app" || rc=1 - if [ "$rc" = 0 ]; then + if [[ "$rc" = 0 ]]; then ditto "$mount/LightCraft.app" "$copy/LightCraft.app" || rc=1 fi - if [ "$rc" = 0 ]; then + if [[ "$rc" = 0 ]]; then echo "==> strict codesign of LightCraft.app after ditto install-copy" codesign --verify --deep --strict --verbose=2 "$copy/LightCraft.app" || rc=1 fi - if [ "$rc" = 0 ] && [ "$NOTARIZE" = 1 ]; then + if [[ "$rc" = 0 ]] && [[ "$NOTARIZE" = 1 ]]; then spctl --assess --type execute -vvv "$copy/LightCraft.app" || rc=1 fi - if [ "$rc" != 0 ]; then + if [[ "$rc" != 0 ]]; then echo "error: published-image app verification failed; reject $DMG" >&2 xattr -lr "$mount/LightCraft.app" >&2 || true fi @@ -201,7 +201,7 @@ verify_dmg_app() { return "$rc" } verify_dmg_app -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then notarize "$DMG" xcrun stapler staple "$DMG" xcrun stapler validate "$DMG" @@ -222,7 +222,7 @@ codesign --verify --strict --verbose=2 "$CLI_DIR/lightcraft-cli" rm -f "$CLI_ZIP" ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP" # A bare Mach-O can't carry a stapled ticket; Gatekeeper looks the notarization up online. -if [ "$NOTARIZE" = 1 ]; then notarize "$CLI_ZIP"; fi +if [[ "$NOTARIZE" = 1 ]]; then notarize "$CLI_ZIP"; fi "$WORK/bin/lightcraft-cli" --version echo "==> done" diff --git a/packaging/web/package.sh b/packaging/web/package.sh index 16691a6ba8..3465f5004b 100755 --- a/packaging/web/package.sh +++ b/packaging/web/package.sh @@ -11,12 +11,12 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/web" -if [ "${1:-}" != "--skip-build" ]; then +if [[ "${1:-}" != "--skip-build" ]]; then # CI (the shared release workflow installs only trunk): install the wasm-bindgen CLI at the # version in Cargo.lock. Locally, `cargo xtask web` says which version to install. - if [ -n "${CI:-}" ]; then + if [[ -n "${CI:-}" ]]; then WASM_BINDGEN_VERSION="$(awk '$0 == "name = \"wasm-bindgen\"" { getline; gsub(/version = |"/, ""); print; exit }' "$ROOT/Cargo.lock")" - [ -n "$WASM_BINDGEN_VERSION" ] || { echo "error: wasm-bindgen not found in Cargo.lock" >&2; exit 1; } + [[ -n "$WASM_BINDGEN_VERSION" ]] || { echo "error: wasm-bindgen not found in Cargo.lock" >&2; exit 1; } if ! { command -v wasm-bindgen >/dev/null && wasm-bindgen --version | grep -qF " $WASM_BINDGEN_VERSION"; }; then cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked fi @@ -25,13 +25,13 @@ if [ "${1:-}" != "--skip-build" ]; then fi SITE="$CARGO_TARGET_DIR/web-site" -[ -f "$SITE/index.html" ] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } +[[ -f "$SITE/index.html" ]] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } # Guard against Cargo build artifacts leaking into the release (issue #793): cross-compiling writes # the selected profile's *host* artifacts (build scripts, proc-macros, deps/, build/, .fingerprint/) # to <target>/<profile>/, so if SITE ever points at a profile directory again the zip would carry # ~113 MB of build output. Fail loudly instead. for d in deps build .fingerprint; do - if [ -e "$SITE/$d" ]; then + if [[ -e "$SITE/$d" ]]; then echo "error: $SITE/$d exists — $SITE holds Cargo build artifacts, not just the site (issue #793)" >&2 exit 1 fi diff --git a/packaging/windows/fonts.ps1 b/packaging/windows/fonts.ps1 index 74f383fd8b..6d22053fe3 100644 --- a/packaging/windows/fonts.ps1 +++ b/packaging/windows/fonts.ps1 @@ -6,7 +6,7 @@ function Initialize-CraftFonts([string] $WorkspaceRoot) { if (-not $env:CRAFT_FONTS_DIR -and -not (Test-Path -LiteralPath $fontDir)) { # Same revision as release.yml and packaging/fonts.sh. Existing checkouts stay untouched. - $revision = '3d9ab3a132ed0eff457e424226a435a901da30d3' + $revision = 'b076417b5880bd4154bd22f00695b1d28c6bea83' Write-Output "==> downloading craft-fonts ($revision) to $fontDir" & git clone --no-checkout https://github.com/storytold/craft-fonts $fontDir if ($LASTEXITCODE -ne 0) { throw 'Could not download craft-fonts; provide a complete checkout with CRAFT_FONTS_DIR' } diff --git a/packaging/windows/lightcraft.wxs b/packaging/windows/lightcraft.wxs index 533c24d202..9e23e54309 100644 --- a/packaging/windows/lightcraft.wxs +++ b/packaging/windows/lightcraft.wxs @@ -206,6 +206,9 @@ <Component Id="LightcraftCli"> <File Id="LightcraftCliExe" Source="$(var.BinDir)\lightcraft-cli.exe" KeyPath="yes" /> </Component> + <Component Id="LightcraftNotice"> + <File Id="LightcraftNoticeFile" Source="$(var.BinDir)\NOTICE" KeyPath="yes" /> + </Component> <Component Id="LightcraftFontLicences"> <File Id="LightcraftFontLicencesFile" Source="$(var.BinDir)\FONT-LICENCES.txt" KeyPath="yes" /> </Component> diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 50aa77ea8f..110d8b60c7 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -116,6 +116,8 @@ $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'lightcraft.exe'), (Join-Path $Bin 'lightcraft-cli.exe') $Stage +# The bundled egui font MIT notice is required even without optional craft-fonts. +Copy-Item -LiteralPath (Join-Path $Root 'NOTICE') -Destination $Stage # Include the embedded fonts' unmodified OFL texts in both installer and portable releases. . (Join-Path $PSScriptRoot 'font-licences.ps1') Write-FontLicences (Join-Path $Stage 'FONT-LICENCES.txt') (Join-Path $Root 'assets\fonts\OFL-Inter.txt') $env:CRAFT_FONTS_DIR diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 3139b70b23..0a226f9b2c 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -56,8 +56,8 @@ if (-not $haveCert -and -not $haveAzure) { $script:SignTool = Find-SignTool $common = @('sign', '/v', '/fd', 'SHA256', '/td', 'SHA256', '/d', 'LightCraft', '/du', 'https://github.com/storytold/lightcraft') -$tmp = Join-Path ([IO.Path]::GetTempPath()) "lightcraft-sign-$PID" -New-Item -ItemType Directory -Force -Path $tmp | Out-Null +$tmp = Join-Path ([IO.Path]::GetTempPath()) "lightcraft-sign-$([IO.Path]::GetRandomFileName())" +New-Item -ItemType Directory -Path $tmp | Out-Null try { if ($haveCert) { @@ -73,8 +73,15 @@ try { Write-Output "Signing with Azure Trusted Signing ($env:AZURE_SIGNING_ACCOUNT / $env:AZURE_CERT_PROFILE): $($Files -join ', ')" # The dlib authenticates with DefaultAzureCredential, which reads AZURE_TENANT_ID, # AZURE_CLIENT_ID and AZURE_CLIENT_SECRET from the environment. + $trustedSigningVersion = '1.0.95' + $trustedSigningSha256 = '3bfcf1e0a3cb42af1692f0a8ed45c15de070c2de86f28a59b2795d904d8a920f' $pkg = Join-Path $tmp 'trusted-signing.zip' - Invoke-WebRequest -Uri 'https://www.nuget.org/api/v2/package/Microsoft.Trusted.Signing.Client' -OutFile $pkg + $uri = "https://api.nuget.org/v3-flatcontainer/microsoft.trusted.signing.client/$trustedSigningVersion/microsoft.trusted.signing.client.$trustedSigningVersion.nupkg" + Invoke-WebRequest -Uri $uri -OutFile $pkg + $actualHash = (Get-FileHash -Path $pkg -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actualHash -ne $trustedSigningSha256) { + throw "Microsoft.Trusted.Signing.Client $trustedSigningVersion checksum mismatch" + } Expand-Archive -Path $pkg -DestinationPath (Join-Path $tmp 'client') -Force $dlib = Get-ChildItem -Path (Join-Path $tmp 'client') -Recurse -Filter Azure.CodeSigning.Dlib.dll | Where-Object { $_.FullName -match '\\x64\\' } | Select-Object -First 1 diff --git a/sonar-project.properties b/sonar-project.properties index d0480c0ed3..336e755db7 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,2 +1,3 @@ sonar.projectKey=storytold_lightcraft sonar.organization=storytold +sonar.coverage.exclusions=**/tools/**,**/docs/**,**/examples/** diff --git a/tools/install-sam3.sh b/tools/install-sam3.sh index b9d95cf7fe..625c2dab0f 100755 --- a/tools/install-sam3.sh +++ b/tools/install-sam3.sh @@ -42,8 +42,9 @@ while [ $# -gt 0 ]; do done sha256() { - if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1 - else sha256sum "$1" | cut -d' ' -f1; fi + sha_file=$1 + if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$sha_file" | cut -d' ' -f1 + else sha256sum "$sha_file" | cut -d' ' -f1; fi } verify() { @@ -78,22 +79,37 @@ fi mkdir -p "$DIR" BASE="https://huggingface.co/$REPO/resolve/main" +# The bearer header goes through a private temporary file, never argv: on systems that expose other +# users' process arguments another local account could read the token from `ps` (CWE-214), but not a +# 0600 file. curl's config format: `header = "..."`. +if [ -n "$TOKEN" ]; then + AUTH_FILE=$(mktemp "${TMPDIR:-/tmp}/lightcraft-sam3-auth.XXXXXX") + trap 'rm -f "$AUTH_FILE"' EXIT + printf 'header = "Authorization: Bearer %s"\n' "$TOKEN" > "$AUTH_FILE" +fi + # fetch FILE DEST [resume]: HTTP errors never reach DEST (--fail writes no error page), and a # resume the server refuses (416) starts over instead of counting as done. fetch() { - set -- "$1" "$2" "${3:-}" - if [ -n "$TOKEN" ]; then auth="Authorization: Bearer $TOKEN"; else auth="X-No-Auth: 1"; fi - code=$(curl --proto '=https' -fsSL ${3:+-C -} -H "$auth" -w '%{http_code}' -o "$2" "$BASE/$1") || true + file=$1 dest=$2 resume=${3:-} + # POSIX sh has no arrays: the auth option and its value travel as two plain words. + if [ -n "$TOKEN" ]; then + auth_opt=--config auth_val=$AUTH_FILE + else + # not secret (no token is sent); kept in argv only to mirror the authenticated call shape + auth_opt=-H auth_val="X-No-Auth: 1" + fi + code=$(curl --proto '=https' -fsSL ${resume:+-C -} "$auth_opt" "$auth_val" -w '%{http_code}' -o "$dest" "$BASE/$file") || true case "$code" in 200|206) return 0 ;; 416) - echo "the partial download of $1 doesn't match the server's; starting over" >&2 - rm -f "$2" - code=$(curl --proto '=https' -fsSL -H "$auth" -w '%{http_code}' -o "$2" "$BASE/$1") || true + echo "the partial download of $file doesn't match the server's; starting over" >&2 + rm -f "$dest" + code=$(curl --proto '=https' -fsSL "$auth_opt" "$auth_val" -w '%{http_code}' -o "$dest" "$BASE/$file") || true [ "$code" = 200 ] && return 0 - echo "download of $REPO/$1 failed ($code)" >&2; return 1 ;; - 401|403) echo "access denied to $REPO/$1 (has your request for facebook/sam3 been approved?)" >&2; return 1 ;; - *) echo "download of $REPO/$1 failed (${code:-no response})" >&2; return 1 ;; + echo "download of $REPO/$file failed ($code)" >&2; return 1 ;; + 401|403) echo "access denied to $REPO/$file (has your request for facebook/sam3 been approved?)" >&2; return 1 ;; + *) echo "download of $REPO/$file failed (${code:-no response})" >&2; return 1 ;; esac } diff --git a/tools/requirements-sam3-reference.txt b/tools/requirements-sam3-reference.txt index cf8f263aa2..baba772498 100644 --- a/tools/requirements-sam3-reference.txt +++ b/tools/requirements-sam3-reference.txt @@ -1,4 +1,4 @@ -# Python packages for tools/sam3_reference.py (reference tensors for crates/segment/tests/reference.rs). +# Python packages for tools/sam3_reference.py (reference tensors for crates/segment/tests/it/reference.rs). # python3 -m venv .venv-sam3 && .venv-sam3/bin/pip install -r tools/requirements-sam3-reference.txt torch>=2.6 torchvision>=0.21 diff --git a/tools/sam3_reference.py b/tools/sam3_reference.py index 99a06f3ee9..417be5a9f8 100644 --- a/tools/sam3_reference.py +++ b/tools/sam3_reference.py @@ -1,4 +1,4 @@ -"""Reference tensors for the Rust SAM 3 port (crates/segment/tests/reference.rs). +"""Reference tensors for the Rust SAM 3 port (crates/segment/tests/it/reference.rs). Runs the Hugging Face transformers implementation (fp32, CPU) on one photo and writes the shared pixel input plus intermediate and final outputs of the click (tracker) and text diff --git a/tools/spectral_camera_table.py b/tools/spectral_camera_table.py index b05ac28028..d936983b47 100644 --- a/tools/spectral_camera_table.py +++ b/tools/spectral_camera_table.py @@ -19,6 +19,25 @@ import sys import colour import numpy as np from scipy.optimize import minimize +from pathlib import Path + + +def _existing_dir(arg): + """Resolve a directory CLI argument; require it to exist.""" + path = Path(arg).resolve() + if not path.is_dir(): + sys.exit(f"not a directory: {arg}") + return str(path) + + +def _out_path(arg): + """Resolve an output path CLI argument; require its parent to exist.""" + path = Path(arg).resolve() + if not path.parent.is_dir(): + sys.exit(f"output directory does not exist: {arg}") + if path.exists() and not path.is_file(): + sys.exit(f"output path is not a regular file: {arg}") + return str(path) WL = np.arange(380, 781, 5) D50 = colour.xy_to_XYZ(colour.CCS_ILLUMINANTS["CIE 1931 2 Degree Standard Observer"]["D50"]) @@ -72,6 +91,23 @@ def dng_tags(cmf, refl, ssf): return out +def rust_lit(s): + """The body of a Rust string literal: text from a checkout becomes data, never code.""" + out = [] + for ch in s: + if ch == "\\": out.append("\\\\") + elif ch == '"': out.append('\\"') + elif ch == "\t": out.append("\\t") + elif ord(ch) < 0x20 or ord(ch) == 0x7F: out.append(f"\\u{{{ord(ch):x}}}") + else: out.append(ch) + return "".join(out) + + +def rust_comment(s): + """One line of printable text: a raw newline in an external comment would introduce Rust code.""" + return rust_lit(" ".join(str(s).split())) + + def mat(m): return "Mat3([" + ", ".join("[" + ", ".join(f"{v:.6}" for v in row) + "]" for row in m) + "])" @@ -92,12 +128,12 @@ def main(root, out): (cm1, fm1, e1), (cm2, fm2, e2) = dng_tags(cmf, refl, spectral(path, 3)) print(f"{f}: training dE76 A {e1:.3f}, D65 {e2:.3f}", file=sys.stderr) rows.append( - f' Camera {{\n make: "{header["manufacturer"]}",\n model: "{header["model"]}",\n' + f' Camera {{\n make: "{rust_lit(header["manufacturer"])}",\n model: "{rust_lit(header["model"])}",\n' f" color_matrix: [{mat(cm1)}, {mat(cm2)}],\n forward_matrix: [{mat(fm1)}, {mat(fm2)}],\n }}," ) aliases = json.load(open(os.path.join(root, "data/aliases.json")))["data"]["camera"]["model"] alias_rows = [ - f' ("{make}", "{alias}", "{target["model"]}"), // {target.get("comments", "")}' + f' ("{rust_lit(make)}", "{rust_lit(alias)}", "{rust_lit(target["model"])}"), // {rust_comment(target.get("comments", ""))}' for make, models in aliases.items() for alias, target in models.items() ] @@ -119,4 +155,4 @@ def main(root, out): if __name__ == "__main__": if len(sys.argv) != 3: sys.exit("usage: spectral_camera_table.py <rawtoaces-data checkout> <output .rs>") - main(sys.argv[1], sys.argv[2]) + main(_existing_dir(sys.argv[1]), _out_path(sys.argv[2])) diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 0f1b1f77de..c68c7dca25 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -14,4 +14,4 @@ serde_json = { workspace = true } sha2 = { workspace = true } # precompressed web bundle (`cargo xtask web`); pure Rust flate2 = "1" -brotli = { version = "8", default-features = false, features = ["std"] } +brotli = { version = "9", default-features = false, features = ["std"] } diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs new file mode 100644 index 0000000000..9504beb20f --- /dev/null +++ b/xtask/src/ci_lock.rs @@ -0,0 +1,152 @@ +//! One `cargo xtask ci` at a time per machine. +//! +//! Every CI run builds the workspace several times with one job per CPU. Several worktrees running +//! it at once (parallel agents) slow each other down far more than waiting in turn would, and make +//! the machine unusable meanwhile. So `ci` first takes one of `LIGHTCRAFT_CI_SLOTS` (default 1) +//! lock files in a per-user cache directory, shared by every checkout and worktree, and holds it +//! until it exits. The OS drops the lock when the process ends, crashed or not. +//! +//! - `LIGHTCRAFT_CI_SLOTS=N`: N runs at once (1–64). +//! - `LIGHTCRAFT_CI_LOCK=off`: no lock (e.g. a CI runner that only ever runs one job). +//! - `LIGHTCRAFT_CI_LOCK=<dir>`: keep the lock files there instead. + +use std::fs::{File, OpenOptions, TryLockError}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +const POLL: Duration = Duration::from_secs(2); + +/// A held CI slot; dropping it releases the slot. +pub struct Held { + _file: File, + owner: PathBuf, +} + +impl Drop for Held { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.owner); + } +} + +/// Where the lock files live, or `None` when the lock is switched off. +fn lock_dir() -> Option<PathBuf> { + match std::env::var_os("LIGHTCRAFT_CI_LOCK") { + Some(v) if matches!(v.to_str(), Some("off" | "0" | "false" | "no")) => return None, + Some(v) if !v.is_empty() => return Some(PathBuf::from(v)), + _ => {} + } + let cache = std::env::var_os("XDG_CACHE_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from)) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) + .unwrap_or_else(std::env::temp_dir); + Some(cache.join("lightcraft")) +} + +fn slots() -> usize { + std::env::var("LIGHTCRAFT_CI_SLOTS").ok().and_then(|s| s.trim().parse().ok()).unwrap_or(1).clamp(1, 64) +} + +fn slot_path(dir: &Path, slot: usize) -> PathBuf { + if slot == 0 { dir.join("ci.lock") } else { dir.join(format!("ci-{}.lock", slot + 1)) } +} + +fn owner_path(lock: &Path) -> PathBuf { + lock.with_extension("lock.owner") +} + +/// What to do when the lock itself can't be set up (read-only home, sandbox, network mount). +const LOCK_HINT: &str = "set LIGHTCRAFT_CI_LOCK=off to run without the lock, or LIGHTCRAFT_CI_LOCK=<dir> to keep it elsewhere"; + +/// Take the first free slot of `slots` in `dir`, or `None` when all are held. +pub fn try_acquire(dir: &Path, slots: usize, owner: &str) -> Result<Option<Held>, String> { + std::fs::create_dir_all(dir).map_err(|e| format!("ci lock: {}: {e} ({LOCK_HINT})", dir.display()))?; + for slot in 0..slots.max(1) { + let path = slot_path(dir, slot); + let file = OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .map_err(|e| format!("ci lock: {}: {e} ({LOCK_HINT})", path.display()))?; + match file.try_lock() { + Ok(()) => { + // a sidecar file, not the lock file: Windows locks are mandatory, so others couldn't read it + let owner_file = owner_path(&path); + let _ = std::fs::File::create(&owner_file).and_then(|mut f| f.write_all(owner.as_bytes())); + return Ok(Some(Held { _file: file, owner: owner_file })); + } + Err(TryLockError::WouldBlock) => continue, + Err(TryLockError::Error(e)) => return Err(format!("ci lock: {}: {e} ({LOCK_HINT})", path.display())), + } + } + Ok(None) +} + +/// Who holds each slot, as they wrote it. +fn holders(dir: &Path, slots: usize) -> Vec<String> { + (0..slots.max(1)) + .filter_map(|slot| std::fs::read_to_string(owner_path(&slot_path(dir, slot))).ok()) + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) + .collect() +} + +/// Wait for a CI slot (see the module docs). `None` when the lock is off. +pub fn acquire(root: &Path, command: &str) -> Result<Option<Held>, String> { + let Some(dir) = lock_dir() else { + return Ok(None); + }; + let slots = slots(); + let owner = format!("pid {} in {}: {command}", std::process::id(), root.display()); + if let Some(held) = try_acquire(&dir, slots, &owner)? { + return Ok(Some(held)); + } + let waiting = Instant::now(); + eprintln!("=== ci: waiting for another CI run to finish ({slots} at a time; LIGHTCRAFT_CI_SLOTS changes it) ==="); + for h in holders(&dir, slots) { + eprintln!(" running: {h}"); + } + loop { + std::thread::sleep(POLL); + if let Some(held) = try_acquire(&dir, slots, &owner)? { + eprintln!("=== ci: waited {:.0} s for a CI slot ===", waiting.elapsed().as_secs_f64()); + return Ok(Some(held)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("xtask-ci-lock-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + #[test] + fn one_slot_is_exclusive_until_dropped() { + let dir = scratch("one"); + let first = try_acquire(&dir, 1, "first").unwrap().expect("free slot"); + assert!(try_acquire(&dir, 1, "second").unwrap().is_none()); + assert_eq!(holders(&dir, 1), ["first"]); + drop(first); + assert!(holders(&dir, 1).is_empty()); + assert!(try_acquire(&dir, 1, "third").unwrap().is_some()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn more_slots_admit_more_runs() { + let dir = scratch("two"); + let a = try_acquire(&dir, 2, "a").unwrap(); + let b = try_acquire(&dir, 2, "b").unwrap(); + assert!(a.is_some() && b.is_some()); + assert!(try_acquire(&dir, 2, "c").unwrap().is_none()); + assert_eq!(holders(&dir, 2), ["a", "b"]); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs new file mode 100644 index 0000000000..3242c95afa --- /dev/null +++ b/xtask/src/ci_quick.rs @@ -0,0 +1,349 @@ +//! `cargo xtask ci --quick`: the checks a branch's own changes can break, for a pre-push check. +//! +//! The full `ci` builds the workspace four ways (clippy, heif, tests, wasm) plus the CLI for the +//! parity check, ~23 minutes cold. `--quick` looks at what changed since the merge base with +//! `origin/main` (or `--base REF`), committed or not, and runs: +//! +//! - fmt, layers, assets: always (seconds); +//! - clippy on the whole workspace (check builds only; catches callers broken by an API change); +//! - the tests of the changed packages only (not their dependents); +//! - heif when `lightcraft-codecs` / `lightcraft-heif` changed; +//! - parity when the tracker docs, a command/control crate, or a file's path changed (renames and +//! deletions: the tracker cites paths); +//! - the wasm check of the changed packages that must build for wasm32. +//! +//! A file outside any package that a crate compiles in (`include_str!` of `docs/whats-new.md`, +//! fonts and camera profiles under `assets/`, ...) counts as a change to that crate (`EMBEDDED`). +//! A change to a workspace-wide file (root `Cargo.toml`, `Cargo.lock`, lint or toolchain config) +//! tests everything. The full `ci` (GitHub's CI on every PR) stays the merge gate. + +use std::collections::BTreeSet; +use std::path::Path; +use std::process::Command; + +/// Root-level files whose change can affect every package. +const WORKSPACE_WIDE: &[&str] = + &["Cargo.toml", "Cargo.lock", "clippy.toml", "rustfmt.toml", ".rustfmt.toml", "rust-toolchain", "rust-toolchain.toml"]; +const WORKSPACE_WIDE_DIRS: &[&str] = &[".cargo/"]; +/// Packages whose ids or paths the parity tracker cites (commands, develop controls, UI menus). +const PARITY_PACKAGES: &[&str] = &["lightcraft-engine", "lightcraft-develop", "lightcraft-ui-egui", "lightcraft-cli"]; +const PARITY_DOCS: &[&str] = &["docs/parity-checklist.md", "docs/gaps.md"]; +const HEIF_PACKAGES: &[&str] = &["lightcraft-codecs", "lightcraft-heif"]; +/// Files outside a package's directory that it compiles in (`include_str!` / `include_bytes!`, +/// a build script's `rerun-if-changed`): a change to one counts as a change to those packages. +/// An entry ending in `/` covers the directory. `embedded_files_are_mapped` keeps this complete. +const EMBEDDED: &[(&str, &[&str])] = &[ + ("assets/app-icon/", &["lightcraft"]), + ("assets/camera-profiles/", &["lightcraft-engine"]), + ("assets/camera-tone/", &["lightcraft-engine"]), + ("assets/fonts/", &["lightcraft-engine", "lightcraft-ui-egui"]), + ("contributors/", &["lightcraft-ui-egui"]), + ("docs/whats-new.md", &["lightcraft-ui-egui"]), + ("docs/raw/coverage-sweep.tsv", &["lightcraft-raw"]), + ("docs/raf-corpus.sha256", &["lightcraft-raw"]), + ("xtask/src/main.rs", &["lightcraft-raw"]), + ("crates/ui-egui/src/menus.rs", &["xtask"]), +]; + +/// The packages that compile in `path` from outside their own directory. +fn embedders(path: &str) -> impl Iterator<Item = &'static str> + '_ { + EMBEDDED.iter().filter(move |(p, _)| if p.ends_with('/') { path.starts_with(p) } else { path == *p }).flat_map(|(_, pkgs)| pkgs.iter().copied()) +} + +/// A changed path, relative to the workspace root; `gone` when deleted or renamed away. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Changed { + pub path: String, + pub gone: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Plan { + /// Workspace packages with a changed file. + pub packages: BTreeSet<String>, + /// A workspace-wide file changed: test everything. + pub workspace_wide: bool, + pub heif: bool, + pub parity: bool, + /// What the changes were measured against, for the log and the report. + pub base: String, + pub files: usize, +} + +impl Plan { + /// Whether anything compiled changed (otherwise clippy and the tests are skipped). + pub fn rust(&self) -> bool { + self.workspace_wide || !self.packages.is_empty() + } +} + +/// Decide what to run. `packages` are (name, directory relative to the root, `/`-separated). +pub fn plan(changed: &[Changed], packages: &[(String, String)], base: String) -> Plan { + let mut p = Plan { base, files: changed.len(), ..Plan::default() }; + for c in changed { + let path = c.path.as_str(); + if WORKSPACE_WIDE.contains(&path) || WORKSPACE_WIDE_DIRS.iter().any(|d| path.starts_with(d)) { + p.workspace_wide = true; + } + if PARITY_DOCS.contains(&path) || c.gone { + p.parity = true; + } + // the innermost package directory containing the file + let owner = packages + .iter() + .filter(|(_, dir)| !dir.is_empty() && path.strip_prefix(dir.as_str()).is_some_and(|rest| rest.starts_with('/'))) + .max_by_key(|(_, dir)| dir.len()); + if let Some((name, _)) = owner { + p.packages.insert(name.clone()); + } + for name in embedders(path) { + if packages.iter().any(|(n, _)| n == name) { + p.packages.insert(name.to_owned()); + } + } + } + p.heif = p.workspace_wide || HEIF_PACKAGES.iter().any(|h| p.packages.contains(*h)); + p.parity |= p.workspace_wide || PARITY_PACKAGES.iter().any(|h| p.packages.contains(*h)); + p +} + +fn git(root: &Path, args: &[&str]) -> Result<String, String> { + let out = Command::new("git").args(args).current_dir(root).output().map_err(|e| format!("git {}: {e}", args.join(" ")))?; + if !out.status.success() { + return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +/// Parse `git diff --name-status -z` output: NUL-separated fields, a status then its path, or +/// two paths (old, new) for a rename or copy. `-z` leaves non-ASCII paths unquoted. +fn parse_name_status(out: &str) -> Vec<Changed> { + let mut v = Vec::new(); + let mut fields = out.split('\0'); + while let Some(status) = fields.next() { + let Some(kind) = status.trim().chars().next() else { continue }; + let Some(first) = fields.next() else { break }; + match kind { + // renamed / copied: old path, new path + 'R' | 'C' => { + v.push(Changed { path: first.to_owned(), gone: kind == 'R' }); + if let Some(second) = fields.next() { + v.push(Changed { path: second.to_owned(), gone: false }); + } + } + 'D' => v.push(Changed { path: first.to_owned(), gone: true }), + _ => v.push(Changed { path: first.to_owned(), gone: false }), + } + } + v +} + +/// Parse NUL-separated `git ls-files -z` output. +fn parse_paths_z(out: &str) -> impl Iterator<Item = Changed> + '_ { + out.split('\0').filter(|p| !p.is_empty()).map(|p| Changed { path: p.to_owned(), gone: false }) +} + +/// The files changed since the merge base with `base` (default `origin/main`, else `main`): +/// committed, staged, unstaged and untracked. Returns the base description and the files. +pub fn changed_files(root: &Path, base: Option<&str>) -> Result<(String, Vec<Changed>), String> { + let base = match base { + Some(b) => b.to_owned(), + None => ["origin/main", "main"] + .into_iter() + .find(|b| git(root, &["rev-parse", "--verify", "--quiet", &format!("{b}^{{commit}}")]).is_ok()) + .ok_or("no origin/main or main to compare with; pass --base REF")? + .to_owned(), + }; + let merge_base = git(root, &["merge-base", "HEAD", &base])?.trim().to_owned(); + let mut files = parse_name_status(&git(root, &["diff", "--name-status", "-z", "-M", &merge_base])?); + files.extend(parse_paths_z(&git(root, &["ls-files", "-z", "--others", "--exclude-standard"])?)); + let short: String = merge_base.chars().take(10).collect(); + Ok((format!("{base} (merge base {short})"), files)) +} + +/// (name, root-relative directory) of each workspace package, from `cargo metadata`. +pub fn packages(root: &Path, metadata: &serde_json::Value) -> Vec<(String, String)> { + let roots: Vec<std::path::PathBuf> = [Some(root.to_path_buf()), root.canonicalize().ok()].into_iter().flatten().collect(); + metadata["packages"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| { + let name = p["name"].as_str()?; + let dir = Path::new(p["manifest_path"].as_str()?).parent()?; + let rel = roots.iter().find_map(|r| dir.strip_prefix(r).ok())?; + let rel = rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"); + Some((name.to_owned(), rel)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ch(path: &str) -> Changed { + Changed { path: path.into(), gone: false } + } + + fn pkgs() -> Vec<(String, String)> { + [ + ("lightcraft-raw", "crates/raw"), + ("lightcraft-codecs", "crates/codecs"), + ("lightcraft-engine", "crates/engine"), + ("lightcraft-cli", "apps/lightcraft-cli"), + ("xtask", "xtask"), + ("lightcraft-raw-nested", "crates/raw/nested"), + ] + .into_iter() + .map(|(a, b)| (a.to_owned(), b.to_owned())) + .collect() + } + + #[test] + fn changed_files_pick_their_innermost_package() { + let p = plan(&[ch("crates/raw/src/lib.rs"), ch("crates/raw/nested/src/x.rs"), ch("crates/rawx/y.rs")], &pkgs(), "b".into()); + assert_eq!(p.packages.iter().map(String::as_str).collect::<Vec<_>>(), ["lightcraft-raw", "lightcraft-raw-nested"]); + assert!(p.rust() && !p.workspace_wide && !p.heif && !p.parity); + } + + #[test] + fn docs_only_skip_the_builds_but_tracker_docs_run_parity() { + let p = plan(&[ch("README.md"), ch("docs/raw-parity.md")], &pkgs(), "b".into()); + assert!(!p.rust() && !p.parity); + let p = plan(&[ch("docs/gaps.md")], &pkgs(), "b".into()); + assert!(!p.rust() && p.parity); + } + + #[test] + fn workspace_files_heif_and_parity_triggers() { + let p = plan(&[ch("Cargo.lock")], &pkgs(), "b".into()); + assert!(p.workspace_wide && p.rust() && p.heif && p.parity); + let p = plan(&[ch("crates/codecs/src/heif.rs")], &pkgs(), "b".into()); + assert!(p.heif && !p.parity); + let p = plan(&[ch("crates/engine/src/commands.rs")], &pkgs(), "b".into()); + assert!(p.parity && !p.heif); + let p = plan(&[Changed { path: "crates/raw/src/old.rs".into(), gone: true }], &pkgs(), "b".into()); + assert!(p.parity, "a removed path may be cited by the tracker"); + } + + #[test] + fn name_status_parses_renames_and_deletions() { + let v = parse_name_status("M\0a.rs\0R087\0old.rs\0new.rs\0D\0gone.rs\0C100\0src.rs\0copy.rs\0A\0added.rs\0"); + assert_eq!( + v, + [ + ch("a.rs"), + Changed { path: "old.rs".into(), gone: true }, + ch("new.rs"), + Changed { path: "gone.rs".into(), gone: true }, + ch("src.rs"), + ch("copy.rs"), + ch("added.rs"), + ] + ); + // truncated output: no panic, keeps what it could read + assert_eq!(parse_name_status("M\0a.rs\0R100\0x.rs"), [ch("a.rs"), Changed { path: "x.rs".into(), gone: true }]); + } + + #[test] + fn non_ascii_paths_still_map_to_their_package() { + // without -z, git prints these quoted and octal-escaped ("crates/raw/src/\303\251t\303\251.rs") + let v = parse_name_status("M\0crates/raw/src/été.rs\0R100\0crates/engine/a.rs\0crates/engine/日本.rs\0"); + assert_eq!(v[0], ch("crates/raw/src/été.rs")); + assert_eq!(v[2], ch("crates/engine/日本.rs")); + let untracked: Vec<_> = parse_paths_z("crates/codecs/ünï code.rs\0").collect(); + assert_eq!(untracked, [ch("crates/codecs/ünï code.rs")]); + let p = plan(&[v, untracked].concat(), &pkgs(), "b".into()); + assert_eq!(p.packages.iter().map(String::as_str).collect::<Vec<_>>(), ["lightcraft-codecs", "lightcraft-engine", "lightcraft-raw"]); + } + + #[test] + fn embedded_files_outside_a_crate_test_the_crates_that_embed_them() { + let p = plan(&[ch("docs/raw/coverage-sweep.tsv")], &pkgs(), "b".into()); + assert!(p.rust()); + assert_eq!(p.packages.iter().map(String::as_str).collect::<Vec<_>>(), ["lightcraft-raw"]); + let p = plan(&[ch("assets/fonts/Inter-Regular.ttf")], &pkgs(), "b".into()); + assert!(p.rust() && p.packages.contains("lightcraft-engine")); + // a consumer missing from the workspace's package list is not invented + assert!(!p.packages.contains("lightcraft-ui-egui")); + let p = plan(&[ch("assets/ATTRIBUTION.md"), ch("docs/raw-parity.md")], &pkgs(), "b".into()); + assert!(!p.rust(), "only files something compiles in"); + } + + /// Every `include_str!` / `include_bytes!` of a file outside its package, and every `"../…"` + /// path in a build script, is listed in `EMBEDDED` for that package. + #[test] + fn embedded_files_are_mapped() { + use std::path::{Component, PathBuf}; + fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) { + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let p = e.path(); + if p.is_dir() && p.file_name().is_some_and(|n| n != "target") { + rs_files(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().expect("xtask is in the workspace").to_path_buf(); + // `a/b/../c` -> `a/c`, relative to the root; None outside it + let normalize = |p: &Path| -> Option<String> { + let mut parts: Vec<String> = Vec::new(); + for c in p.strip_prefix(&root).ok()?.components() { + match c { + Component::ParentDir => { + parts.pop()?; + } + Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()), + _ => {} + } + } + Some(parts.join("/")) + }; + let mut files = Vec::new(); + for d in ["crates", "apps", "xtask"] { + rs_files(&root.join(d), &mut files); + } + let (mut checked, mut missing) = (0, Vec::new()); + for file in files { + let Ok(src) = std::fs::read_to_string(&file) else { continue }; + // the package: the nearest directory with a Cargo.toml + let Some(pkg_dir) = file.ancestors().skip(1).find(|d| d.join("Cargo.toml").is_file()) else { continue }; + let manifest = std::fs::read_to_string(pkg_dir.join("Cargo.toml")).unwrap_or_default(); + let Some(name) = manifest.lines().find_map(|l| l.strip_prefix("name = \"")?.strip_suffix('"')) else { continue }; + let Some(pkg_rel) = normalize(pkg_dir) else { continue }; + let mut targets = Vec::new(); + for mac in ["include_str!(", "include_bytes!("] { + for (i, _) in src.match_indices(mac) { + let rest = src[i + mac.len()..].trim_start(); + if let Some(lit) = rest.strip_prefix('"').and_then(|r| r.split('"').next()) { + targets.push(file.parent().expect("a file has a directory").join(lit)); + } + } + } + if file.file_name().is_some_and(|n| n == "build.rs") { + for (i, _) in src.match_indices("\"../") { + if let Some(lit) = src[i + 1..].split('"').next() { + targets.push(pkg_dir.join(lit)); + } + } + } + for t in targets { + // outside the workspace (`../craft-fonts`), not a real file, or inside the package + let Some(rel) = normalize(&t) else { continue }; + if !root.join(&rel).exists() || rel.starts_with(&format!("{pkg_rel}/")) { + continue; + } + checked += 1; + // a directory (`rerun-if-changed=../../contributors`) needs a `dir/` entry + let rel = if root.join(&rel).is_dir() { format!("{rel}/") } else { rel }; + if !embedders(&rel).any(|p| p == name) { + missing.push(format!("{rel} (compiled into {name} by {})", file.display())); + } + } + } + assert!(checked > 0, "found no embedded files: the scan is broken"); + assert!(missing.is_empty(), "add these to ci_quick::EMBEDDED:\n{}", missing.join("\n")); + } +} diff --git a/xtask/src/ci_report.rs b/xtask/src/ci_report.rs index dfbd9f5f90..8be686ef11 100644 --- a/xtask/src/ci_report.rs +++ b/xtask/src/ci_report.rs @@ -307,8 +307,16 @@ pub fn seconds(s: f64) -> String { if s < 60.0 { format!("{s:.1} s") } else { format!("{}m {:02}s", (s / 60.0).floor() as u64, (s % 60.0).floor() as u64) } } +/// `binary::test`, or the binary and the location when the test's name is unknown (thread +/// `main`). A crate's integration tests share one binary, `it`, named here after the crate's +/// directory: `gpu/it::equivalence::camera_tone`. fn test_name(s: &Skip) -> String { - if s.test.is_empty() || s.test == "main" { format!("{} ({})", s.binary, s.location) } else { format!("{}::{}", s.binary, s.test) } + let mut dirs = s.location.split('/'); + let binary = match (s.binary.as_str(), dirs.next(), dirs.next()) { + ("it", Some("crates" | "apps"), Some(dir)) => format!("{dir}/it"), + _ => s.binary.clone(), + }; + if s.test.is_empty() || s.test == "main" { format!("{binary} ({})", s.location) } else { format!("{binary}::{}", s.test) } } fn adapter_line(a: &Value) -> String { @@ -505,9 +513,8 @@ mod tests { fn skips_are_read_per_step_deduplicated_and_cut_free_of_the_root() { let root = Path::new("/work/lightcraft"); let dir = tmp("skips"); - let gpu = - r#"{"need":"gpu","reason":"no GPU adapter","test":"camera_tone","binary":"equivalence","location":"crates/gpu/tests/equivalence.rs:22"}"#; - let corpus = r#"{"need":"corpus","reason":"skip /work/lightcraft/crates/raw/../../corpus/raw absent","test":"decodes","binary":"corpus","location":"crates/raw/tests/corpus.rs:28"}"#; + let gpu = r#"{"need":"gpu","reason":"no GPU adapter","test":"equivalence::camera_tone","binary":"it","location":"crates/gpu/tests/it/equivalence.rs:22"}"#; + let corpus = r#"{"need":"corpus","reason":"skip /work/lightcraft/crates/raw/../../corpus/raw absent","test":"corpus::decodes","binary":"it","location":"crates/raw/tests/it/corpus.rs:28"}"#; std::fs::write(dir.join("skips-heif.jsonl"), format!("{corpus}\n")).unwrap(); std::fs::write(dir.join("skips-test.jsonl"), format!("{gpu}\n{corpus}\nnot json\n")).unwrap(); std::fs::write(dir.join("other.jsonl"), format!("{gpu}\n")).unwrap(); @@ -521,6 +528,25 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn integration_test_skips_are_named_after_their_crate() { + let skip = |test: &str, binary: &str, location: &str| Skip { + need: "gpu".into(), + reason: String::new(), + test: test.into(), + binary: binary.into(), + location: location.into(), + steps: Vec::new(), + }; + assert_eq!(test_name(&skip("equivalence::camera_tone", "it", "crates/gpu/tests/it/equivalence.rs:22")), "gpu/it::equivalence::camera_tone"); + assert_eq!( + test_name(&skip("main", "it", "apps/lightcraft-cli/tests/it/cli.rs:9")), + "lightcraft-cli/it (apps/lightcraft-cli/tests/it/cli.rs:9)" + ); + assert_eq!(test_name(&skip("memory", "memory", "crates/gpu/tests/memory.rs:12")), "memory::memory"); + assert_eq!(test_name(&skip("tests::a", "lightcraft_engine", "crates/engine/src/tests.rs:3")), "lightcraft_engine::tests::a"); + } + #[test] fn prepare_clears_the_last_runs_files_only() { let root = tmp("prepare"); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7af8c82ace..088103f780 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -5,6 +5,8 @@ mod assets; mod bench; +mod ci_lock; +mod ci_quick; mod ci_report; mod ico; mod layers; @@ -30,15 +32,22 @@ commands: parity [--write] check docs/parity-checklist.md (every cmd:/ctl: id and path it cites exists) and print the Lightroom parity summary; --write refreshes the summary table in the document - wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (+ the web app) + wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (+ the web app), in one call web [--serve [port]] [--dev] build the browser app (apps/lightcraft-web) into <target>/web-site/; --serve serves it on http://127.0.0.1:<port> (default 8080) - ci [--hardware] [--summary-md] + ci [--hardware] [--summary-md] [--quick [--base REF]] fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, assets, wasm - (stops at first failure); writes target/ci/report.json (machine, GPU adapters, data, + (stops at first failure). Tests run under cargo test (cargo nextest with + LIGHTCRAFT_NEXTEST=1), without examples, then doctests with cargo test --doc; after + them it prints the translation gaps report (never a failure). Writes + target/ci/report.json (machine, GPU adapters, data, steps, skipped tests) and target/ci/summary.md; --hardware also runs the GPU tests on - every backend with a hardware adapter; --summary-md prints the Markdown summary + every backend with a hardware adapter; --summary-md prints the Markdown summary. + --quick: only what the changes since the merge base with origin/main (or REF) can + break: clippy, the changed packages' tests, and heif / parity / wasm when they apply. + One ci runs at a time per machine; others wait (LIGHTCRAFT_CI_SLOTS=N for N at once, + LIGHTCRAFT_CI_LOCK=off to skip the lock) corpus [--download] show where test corpora live; --download fetches PngSuite and CC0 raw samples (raw.pixls.us) into corpus/ and checks their sha256 stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) @@ -118,9 +127,12 @@ pub fn cargo() -> Command { // wall-clock frame-budget tests flaky on a loaded machine. (jobs.to_string(), jobs.min(4).to_string()) }); - for (key, value) in - [("CARGO_PROFILE_DEV_DEBUG", "line-tables-only"), ("CARGO_BUILD_JOBS", build.as_str()), ("RUST_TEST_THREADS", threads.as_str())] - { + for (key, value) in [ + ("CARGO_PROFILE_DEV_DEBUG", "line-tables-only"), + ("CARGO_BUILD_JOBS", build.as_str()), + ("RUST_TEST_THREADS", threads.as_str()), + ("NEXTEST_TEST_THREADS", threads.as_str()), + ] { if std::env::var_os(key).is_none() { c.env(key, value); } @@ -184,6 +196,142 @@ fn total_ram_gb() -> Option<u64> { Some(bytes.saturating_add(1 << 29) >> 30) } +/// The targets the test runs build: no examples (clippy `--all-targets` still checks them). +/// Doctests run on their own, [`doctests`]: nextest can't run them. +const TEST_TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; + +/// `args` followed by [`TEST_TARGETS`]. +fn with_test_targets<'a>(args: &[&'a str]) -> Vec<&'a str> { + args.iter().copied().chain(TEST_TARGETS).collect() +} + +/// Whether the tests run under `cargo nextest`: only when `LIGHTCRAFT_NEXTEST=1` asks for it and +/// nextest is installed. `cargo test` is the default because the demo library's generated scenes +/// are cached per process: libtest runs a binary's tests in one process and generates each scene +/// once, while nextest's process per test regenerates them (measured: the ui-egui tests take about +/// 30 min under nextest, under 5 min under cargo test). +fn nextest() -> bool { + static FOUND: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *FOUND.get_or_init(|| { + if std::env::var_os("LIGHTCRAFT_NEXTEST").is_none_or(|v| v != "1") { + return false; + } + let found = cargo() + .args(["nextest", "--version"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()); + if !found { + eprintln!("note: LIGHTCRAFT_NEXTEST=1 but cargo-nextest is not installed, so the tests run under cargo test (cargo install cargo-nextest --locked)"); + } + found + }) +} + +/// A test run of `args` (packages, features, targets, filters): `cargo nextest run`, or `cargo +/// test`. The command and how to print it. +fn tests(args: &[&str]) -> (Command, String) { + let mut c = cargo(); + let tool = if nextest() { "nextest run" } else { "test" }; + c.args(tool.split(' ')).args(args); + (c, format!("cargo {tool} {}", args.join(" "))) +} + +/// The workspace's doctests. +fn doctests() -> (Command, String) { + let mut c = cargo(); + c.args(["test", "--workspace", "--doc"]); + (c, "cargo test --workspace --doc".to_owned()) +} + +/// `ci --quick`'s tests: build every workspace test target, then run only the test binaries of +/// `packages`. Building with `-p` instead would resolve features per selection: different +/// artifacts from `ci`'s workspace build, so it would recompile ~130 crates. Doc tests are left to +/// the full `ci`. +fn test_selected(root: &Path, packages: &std::collections::BTreeSet<String>, skip_log: &Path) -> Result<(), String> { + let manifests: std::collections::BTreeMap<String, String> = metadata()?["packages"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| Some((p["manifest_path"].as_str()?.to_owned(), p["name"].as_str()?.to_owned()))) + .filter(|(_, name)| packages.contains(name)) + .collect(); + let what = "cargo test --workspace --no-run --lib --bins --tests"; + eprintln!("$ {what} (then the test binaries of {})", packages.iter().map(String::as_str).collect::<Vec<_>>().join(", ")); + let out = cargo() + .args(with_test_targets(&["test", "--workspace", "--no-run", "--message-format=json-render-diagnostics"])) + .stderr(std::process::Stdio::inherit()) + .output() + .map_err(|e| format!("{what}: failed to spawn: {e}"))?; + if !out.status.success() { + return Err(format!("{what}: exited with {}", out.status)); + } + let mut binaries = Vec::new(); + for line in String::from_utf8_lossy(&out.stdout).lines() { + let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) else { continue }; + if msg["reason"] != "compiler-artifact" || msg["profile"]["test"] != true { + continue; + } + let (Some(exe), Some(manifest)) = (msg["executable"].as_str(), msg["manifest_path"].as_str()) else { continue }; + if let Some(name) = manifests.get(manifest) { + binaries.push((name.clone(), manifest.to_owned(), exe.to_owned())); + } + } + if binaries.is_empty() { + println!("no test binaries in {}", packages.iter().map(String::as_str).collect::<Vec<_>>().join(", ")); + return Ok(()); + } + let mut failed = Vec::new(); + for (name, manifest, exe) in &binaries { + let dir = Path::new(manifest).parent().unwrap_or(root); + let mut c = Command::new(exe); + c.current_dir(dir).env("CARGO_MANIFEST_DIR", dir).env("CARGO_PKG_NAME", name).env(ci_report::SKIP_LOG_ENV, skip_log); + if std::env::var_os("RUST_TEST_THREADS").is_none() { + // as the cargo runs of ci (`cargo()`): more threads make the frame-budget tests flaky + c.env("RUST_TEST_THREADS", std::thread::available_parallelism().map_or(4, |n| n.get()).min(4).to_string()); + } + let file = Path::new(exe).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); + if run(c, &format!("{name}: {file}")).is_err() { + failed.push(format!("{name} ({file})")); + } + } + if failed.is_empty() { Ok(()) } else { Err(format!("tests failed in {}", failed.join(", "))) } +} + +/// The test that prints the messages each language lacks (shown in English); it always passes. +const TRANSLATION_GAPS_TEST: &str = "i18n::tests::translation_gaps_report"; + +/// Print the translation gaps report into the log: [`TRANSLATION_GAPS_TEST`] of lightcraft-ui-egui, +/// run from the test binary the test step built (found with `--no-run` and the step's own +/// arguments, so nothing rebuilds). A report that can't run is a note, never a failed step. +fn translation_gaps() { + eprintln!("\n=== ci: translation gaps ==="); + let mut c = cargo(); + c.args(["test", "--no-run", "--message-format=json"]).args(with_test_targets(&["--workspace"])); + let binary = c.output().map_err(|e| format!("cargo test --no-run: {e}")).and_then(|out| { + String::from_utf8_lossy(&out.stdout) + .lines() + .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok()) + .find(|m| { + m["reason"] == "compiler-artifact" + && m["target"]["name"] == "lightcraft_ui_egui" + && m["profile"]["test"] == true + && m["target"]["kind"].as_array().is_some_and(|kinds| kinds.iter().any(|kind| kind == "lib")) + }) + .and_then(|m| m["executable"].as_str().map(PathBuf::from)) + .ok_or_else(|| format!("no lightcraft-ui-egui test binary in the build (cargo exited with {})", out.status)) + }); + let ran = binary.and_then(|binary| { + let mut c = Command::new(&binary); + c.args(["--exact", TRANSLATION_GAPS_TEST, "--nocapture", "--quiet"]); + run(c, &format!("{} --exact {TRANSLATION_GAPS_TEST} --nocapture --quiet", binary.display())) + }); + if let Err(e) = ran { + eprintln!("note: the translation gaps report did not run: {e}"); + } +} + pub fn run(mut cmd: Command, what: &str) -> Result<(), String> { eprintln!("$ {what}"); let status = cmd.status().map_err(|e| format!("{what}: failed to spawn: {e}"))?; @@ -248,38 +396,67 @@ fn wasm_set() -> Result<Vec<String>, String> { .collect()) } +/// One `cargo check` over the whole set; `--keep-going` reports every crate that fails. fn cmd_wasm() -> Result<(), String> { - let set = wasm_set()?; - let mut results = Vec::new(); + cmd_wasm_for(None) +} + +/// The wasm check of the wasm-safe crates, or only those of them in `only` (`ci --quick`). +fn cmd_wasm_for(only: Option<&std::collections::BTreeSet<String>>) -> Result<(), String> { + let set: Vec<String> = wasm_set()?.into_iter().filter(|p| only.is_none_or(|o| o.contains(p))).collect(); + if set.is_empty() { + println!("wasm32-unknown-unknown check: no changed crate builds for wasm32"); + return Ok(()); + } + let mut c = cargo(); + c.args(["check", "--target", "wasm32-unknown-unknown", "--keep-going"]); for pkg in &set { - let mut c = cargo(); - c.args(["check", "--target", "wasm32-unknown-unknown", "-p", pkg]); - let ok = run(c, &format!("cargo check --target wasm32-unknown-unknown -p {pkg}")).is_ok(); - results.push((pkg.clone(), ok)); + c.args(["-p", pkg]); } - println!("\nwasm32-unknown-unknown check:"); - for (p, ok) in &results { - println!(" {:<6} {p}", if *ok { "ok" } else { "FAIL" }); - } - let failed = results.iter().filter(|r| !r.1).count(); - if failed == 0 { Ok(()) } else { Err(format!("{failed} crate(s) failed the wasm check")) } + run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going -p {}", set.join(" -p "))) } fn cmd_ci(args: &[&str]) -> Result<(), String> { let hardware = args.contains(&"--hardware"); let print_md = args.contains(&"--summary-md"); - if let Some(other) = args.iter().find(|a| !matches!(**a, "--hardware" | "--summary-md")) { + let quick = args.contains(&"--quick"); + let base_at = args.iter().position(|a| *a == "--base"); + let base = base_at.map(|i| args.get(i + 1).copied().ok_or("ci: --base needs a ref")).transpose()?; + let unknown = args + .iter() + .enumerate() + .find(|(i, a)| !matches!(**a, "--hardware" | "--summary-md" | "--quick" | "--base") && base_at.is_none_or(|b| *i != b + 1)); + if let Some((_, other)) = unknown { return Err(format!("ci: unknown option `{other}`\n\n{USAGE}")); } + if base.is_some() && !quick { + return Err("ci: --base only applies to --quick".into()); + } let root = root(); + let command = std::iter::once("cargo xtask ci").chain(args.iter().copied()).collect::<Vec<_>>().join(" "); + // held until ci returns: one run at a time per machine (ci_lock.rs) + let _slot = ci_lock::acquire(&root, &command)?; + let plan = if quick { + let (base, files) = ci_quick::changed_files(&root, base)?; + let plan = ci_quick::plan(&files, &ci_quick::packages(&root, &metadata()?), base); + let packages: Vec<&str> = plan.packages.iter().map(String::as_str).collect(); + eprintln!("=== ci --quick: {} changed file(s) since {} ===", plan.files, plan.base); + eprintln!(" packages: {}", if packages.is_empty() { "none".to_owned() } else { packages.join(", ") }); + if plan.workspace_wide { + eprintln!(" a workspace-wide file changed: testing every package"); + } + Some(plan) + } else { + None + }; let report_dir = ci_report::prepare(&root)?; let started = std::time::Instant::now(); let started_unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); - // test runs append the skips their tests record (`lightcraft_testkit::skip!`) to target/ci/skips-<step>.jsonl - let test = |cargo_args: &[&str], step: &str| { - let mut c = cargo(); - c.args(cargo_args).env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, step)); - run(c, &format!("cargo {}", cargo_args.join(" "))) + // test runs append the skips their tests record (`lightcraft_testkit::skip!`) to + // target/ci/skips-<step>.jsonl: a file, so it works the same under nextest and cargo test + let test = |(mut c, what): (Command, String), step: &str| { + c.env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, step)); + run(c, &what) }; let gpu = std::cell::RefCell::new(serde_json::Value::Null); let hardware_runs = std::cell::RefCell::new(Vec::new()); @@ -296,6 +473,16 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { }; type Step<'a> = (&'static str, Box<dyn Fn() -> Result<(), String> + 'a>); + // `--quick`: which steps apply (all of them in a full run) and the packages to test + let wants = |step: &str| match &plan { + None => true, + Some(p) => match step { + "clippy" | "test" | "wasm" => p.rust(), + "heif" => p.heif, + "parity" => p.parity, + _ => true, + }, + }; let mut steps: Vec<Step> = vec![ ( "fmt", @@ -309,8 +496,8 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { "clippy", Box::new(|| { let mut c = cargo(); - c.args(["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]); - run(c, "cargo clippy --workspace --all-targets -- -D warnings") + c.args(["clippy", "--workspace", "--all-targets", "--keep-going", "--", "-D", "warnings"]); + run(c, "cargo clippy --workspace --all-targets --keep-going -- -D warnings") }), ), ( @@ -320,13 +507,23 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { let mut c = cargo(); c.args(["clippy", "-p", "lightcraft-codecs", "--features", "heif", "--all-targets", "--", "-D", "warnings"]); run(c, "cargo clippy -p lightcraft-codecs --features heif --all-targets -- -D warnings")?; - test(&["test", "-p", "lightcraft-codecs", "-p", "lightcraft-heif", "--features", "lightcraft-codecs/heif"], "heif")?; + test( + tests(&with_test_targets(&["-p", "lightcraft-codecs", "-p", "lightcraft-heif", "--features", "lightcraft-codecs/heif"])), + "heif", + )?; // the engine's HEIC import test, with the decoder (the workspace run checks the error) - test(&["test", "-p", "lightcraft-engine", "--lib", "--features", "lightcraft-codecs/heif", "heic"], "heif") + test(tests(&["-p", "lightcraft-engine", "--lib", "--features", "lightcraft-codecs/heif", "heic"]), "heif") + }), + ), + ( + "test", + Box::new(|| match &plan { + Some(p) if !p.workspace_wide => test_selected(&root, &p.packages, &ci_report::skip_log(&root, "test")), + _ => test(tests(&with_test_targets(&["--workspace"])), "test").and_then(|()| test(doctests(), "test")), }), ), - ("test", Box::new(|| test(&["test", "--workspace"], "test"))), ]; + steps.retain(|(name, _)| wants(name)); if hardware { steps.push(( "gpu-backends", @@ -340,12 +537,10 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { let mut failed = Vec::new(); for (backend, adapter) in backends { let step = format!("gpu-{backend}"); - let mut c = cargo(); - c.args(["test", "-p", "lightcraft-gpu", "--features", "denoise"]) - .env("LIGHTCRAFT_GPU_BACKEND", &backend) - .env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, &step)); + let (mut c, what) = tests(&with_test_targets(&["-p", "lightcraft-gpu", "--features", "denoise"])); + c.env("LIGHTCRAFT_GPU_BACKEND", &backend).env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, &step)); let t = std::time::Instant::now(); - let ok = run(c, &format!("LIGHTCRAFT_GPU_BACKEND={backend} cargo test -p lightcraft-gpu --features denoise")).is_ok(); + let ok = run(c, &format!("LIGHTCRAFT_GPU_BACKEND={backend} {what}")).is_ok(); hardware_runs.borrow_mut().push(serde_json::json!({ "backend": backend, "adapter": adapter, @@ -360,10 +555,17 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { }), )); } - steps.push(("parity", Box::new(|| parity::run(&root, false)))); + if wants("parity") { + steps.push(("parity", Box::new(|| parity::run(&root, false)))); + } steps.push(("layers", Box::new(cmd_layers))); steps.push(("assets", Box::new(|| assets::run(&root)))); - steps.push(("wasm", Box::new(cmd_wasm))); + if wants("wasm") { + match plan.as_ref().filter(|p| !p.workspace_wide) { + Some(p) => steps.push(("wasm", Box::new(|| cmd_wasm_for(Some(&p.packages))))), + None => steps.push(("wasm", Box::new(cmd_wasm))), + } + } let mut results = Vec::new(); let mut failure = None; @@ -373,9 +575,10 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { let r = f(); let status = if r.is_ok() { "ok" } else { "fail" }; results.push(serde_json::json!({"name": name, "status": status, "seconds": t.elapsed().as_secs_f64()})); - if *name == "test" { + if *name == "test" && plan.is_none() { // right after the workspace tests, before parity and wasm build other feature sets probe(); + translation_gaps(); } if let Err(e) = r { failure = Some((*name, e)); @@ -383,7 +586,8 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { } } if gpu.borrow().is_null() { - *gpu.borrow_mut() = serde_json::json!({"error": "not probed: the test step did not run"}); + let why = if plan.is_some() { "not probed: --quick" } else { "not probed: the test step did not run" }; + *gpu.borrow_mut() = serde_json::json!({"error": why}); } let done: Vec<&str> = steps.iter().take(results.len()).map(|(n, _)| *n).collect(); match &failure { @@ -407,7 +611,8 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { let ram_mb = available_ram_mb(); let report = serde_json::json!({ "schema": ci_report::SCHEMA, - "command": std::iter::once("cargo xtask ci").chain(args.iter().copied()).collect::<Vec<_>>().join(" "), + "command": command, + "quick": plan.as_ref().map(|p| serde_json::json!({"base": p.base, "files": p.files, "packages": p.packages, "workspace_wide": p.workspace_wide})), "result": if failure.is_some() { "fail" } else { "pass" }, "failed_step": failure.as_ref().map(|(n, _)| *n), "started_unix": started_unix, @@ -440,11 +645,12 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { } /// Run the ignored `gpu_probe` test of lightcraft-gpu: the pipeline's device (`None`) or one -/// backend's adapters. `--workspace`, like the test step, so its build is reused. Its stdout, or why +/// backend's adapters. `--workspace`, like the test step, so its build is reused (every crate's `it` +/// binary starts; only lightcraft-gpu's has the test). Its stdout, or why /// it failed (a driver that crashes while it is enumerated, issue #136, ends up here, not in xtask). fn probe_gpu(backend: Option<&str>) -> Result<String, String> { let mut c = cargo(); - c.args(["test", "-q", "--workspace", "--test", "gpu_probe", "--", "--ignored", "--exact", "gpu_probe", "--nocapture"]); + c.args(["test", "-q", "--workspace", "--test", "it", "--", "--ignored", "--exact", "gpu_probe::gpu_probe", "--nocapture"]); c.env("LIGHTCRAFT_GPU_PROBE", backend.unwrap_or("")); let out = c.output().map_err(|e| format!("gpu_probe: {e}"))?; if !out.status.success() {