Merge raw-negative-channels (with main) into camera-colour-pushed-shadows

main took LOOK_VERSION 13, so this branch's 13-16 become 14-17.
This commit is contained in:
robmdunn committed 2026-10-31 09:28:00 -04:00
commit f381a79067
380 files changed
+26829 -1855

No files matched your search

+6 -12
View File
@@ -14,8 +14,7 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi
4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut).
When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` /
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history, per
craftrules `standards/progress-docs.md`); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
path the tracker cites still exists, and `cargo xtask parity --write` refreshes its summary.
5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
@@ -32,8 +31,7 @@ and often so a crash loses minutes, not hours.
People trust LightCraft with their photo libraries and edits; a crash loses their work. A malformed raw/JPEG/XMP, a bad
command, control or MCP argument, a corrupt catalog or settings file, or a full disk must produce an error the user (or
agent) can act on, never a panic. Don't ship a feature by adding a panic path, and fix a crash before building on top
of it. Full standard: `../craftrules/standards/never-crash.md`
([storytold/craftrules](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md)).
of it.
- **Non-test code never panics:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`, and
no `unsafe`. Return the crate's error type through `Result` and `?`; use `ok_or(..)?`, `let … else`, `if let`, or a
fallback (`unwrap_or…`) only where it can't silently corrupt a document. An unfinished feature returns an
@@ -86,8 +84,7 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter. Unset,
`CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build
with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip
without it; the FreeBSD CI job runs them with it. Rules: craftrules
[`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md).
without it; the FreeBSD CI job runs them with it.
- Icons drawn in code (e.g. `crates/ui-egui/src/icons.rs`) are original work and are recorded in `assets/ATTRIBUTION.md` as such; do not trace them from Adobe icons.
- Demo/test images: generated procedurally by `lightcraft-scenes`, or CC0 downloads kept in the gitignored `corpus/` with their source recorded. Screenshots of Adobe apps live only in the gitignored `plan/` and are never committed or published.
- **Enforced:** `cargo xtask assets` (in `ci`) fails when an image/icon/font/sound/video/raw/ICC/XMP file is not matched
@@ -113,7 +110,7 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-<name>`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`<scratch>/<agent-name>/`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone).
- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media.
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
## Testing & performance (do this often)
- Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`,
@@ -142,20 +139,17 @@ evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the work
## Contributor credits (About window)
- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json`
(commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for
(commit stats; never hand-edit) and `contributors/people.toml` (names people chose for
themselves). See `docs/contributors.md`.
- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
whether they want to be credited by more than their username: a real name, a display name, and/or
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
(copy the template at the top of the file, or run
`python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`)
(copy the template at the top of the file)
and include it in their PR, committed as them. If no, change nothing: they are credited as
`@username` anyway.
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
GitHub profiles). Never hand-edit `contributors.json`.
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
+4 -7
View File
@@ -14,8 +14,7 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi
4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut).
When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` /
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history, per
craftrules `standards/progress-docs.md`); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
path the tracker cites still exists and that `docs/gaps.md` lists each gap once, and `cargo xtask parity --write`
refreshes its summary.
5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
@@ -33,8 +32,7 @@ and often so a crash loses minutes, not hours.
People trust LightCraft with their photo libraries and edits; a crash loses their work. A malformed raw/JPEG/XMP, a bad
command, control or MCP argument, a corrupt catalog or settings file, or a full disk must produce an error the user (or
agent) can act on, never a panic. Don't ship a feature by adding a panic path, and fix a crash before building on top
of it. Full standard: `../craftrules/standards/never-crash.md`
([storytold/craftrules](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md)).
of it.
- **Non-test code never panics:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`, and
no `unsafe`. Return the crate's error type through `Result` and `?`; use `ok_or(..)?`, `let … else`, `if let`, or a
fallback (`unwrap_or…`) only where it can't silently corrupt a document. An unfinished feature returns an
@@ -97,8 +95,7 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter; the UI also falls back on the faces of other scripts (Thai, Arabic, …). Unset,
`CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build
with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip
without it; the FreeBSD CI job runs them with it. Rules: craftrules
[`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md).
without it; the FreeBSD CI job runs them with it.
- Icons drawn in code (e.g. `crates/ui-egui/src/icons.rs`) are original work and are recorded in `assets/ATTRIBUTION.md` as such; do not trace them from Adobe icons.
- Demo/test images: generated procedurally by `lightcraft-scenes`, or CC0 downloads kept in the gitignored `corpus/` with their source recorded. Screenshots of Adobe apps live only in the gitignored `plan/` and are never committed or published.
- **Enforced:** `cargo xtask assets` (in `ci`) fails when an image/icon/font/sound/video/raw/ICC/XMP file is not matched
@@ -127,7 +124,7 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-<name>`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`<scratch>/<agent-name>/`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone).
- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media.
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
## Testing & performance (do this often)
- Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`,
Generated
+49 -46
View File
@@ -1184,17 +1184,17 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1217,7 +1217,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1238,7 +1238,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"chrono",
"dunce",
@@ -1264,7 +1264,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1871,7 +1871,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3536,7 +3536,7 @@ dependencies = [
[[package]]
name = "lightcraft"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"chrono",
"craft-update",
@@ -3563,10 +3563,11 @@ dependencies = [
[[package]]
name = "lightcraft-catalog"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"chrono",
"crc32fast",
"dhat",
"lightcraft-develop",
"lightcraft-geom",
"lightcraft-meta",
@@ -3583,7 +3584,7 @@ dependencies = [
[[package]]
name = "lightcraft-cli"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"dhat",
"lightcraft-codecs",
@@ -3593,13 +3594,14 @@ dependencies = [
"lightcraft-merge",
"lightcraft-raster",
"lightcraft-sysmem",
"lightcraft-testkit",
"lightcraft-ui-egui",
"serde_json",
]
[[package]]
name = "lightcraft-codecs"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"avif-serialize",
"bytemuck",
@@ -3630,7 +3632,7 @@ dependencies = [
[[package]]
name = "lightcraft-color"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lightcraft-geom",
"proptest",
@@ -3639,7 +3641,7 @@ dependencies = [
[[package]]
name = "lightcraft-denoise"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"faer-core",
"lightcraft-denoise-core",
@@ -3656,7 +3658,7 @@ dependencies = [
[[package]]
name = "lightcraft-denoise-core"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"dhat",
"lightcraft-raster",
@@ -3672,7 +3674,7 @@ dependencies = [
[[package]]
name = "lightcraft-develop"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lightcraft-color",
"lightcraft-geom",
@@ -3684,7 +3686,7 @@ dependencies = [
[[package]]
name = "lightcraft-engine"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"ab_glyph",
"chrono",
@@ -3728,7 +3730,7 @@ dependencies = [
[[package]]
name = "lightcraft-faces"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lightcraft-testkit",
"matrixmultiply",
@@ -3743,7 +3745,7 @@ dependencies = [
[[package]]
name = "lightcraft-fetch"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"log",
"rustls",
@@ -3754,7 +3756,7 @@ dependencies = [
[[package]]
name = "lightcraft-geocode"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"miniz_oxide 0.9.1",
"serde",
@@ -3762,7 +3764,7 @@ dependencies = [
[[package]]
name = "lightcraft-geom"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"proptest",
"serde",
@@ -3770,7 +3772,7 @@ dependencies = [
[[package]]
name = "lightcraft-gpu"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"bytemuck",
"lightcraft-color",
@@ -3790,7 +3792,7 @@ dependencies = [
[[package]]
name = "lightcraft-heif"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"heic-rs",
"rayon",
@@ -3798,14 +3800,14 @@ dependencies = [
[[package]]
name = "lightcraft-inpaint"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"rayon",
]
[[package]]
name = "lightcraft-lensdb"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lightcraft-develop",
"lightcraft-geom",
@@ -3814,7 +3816,7 @@ dependencies = [
[[package]]
name = "lightcraft-mcp"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lightcraft-codecs",
"lightcraft-engine",
@@ -3825,7 +3827,7 @@ dependencies = [
[[package]]
name = "lightcraft-merge"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lightcraft-codecs",
"lightcraft-color",
@@ -3841,10 +3843,11 @@ dependencies = [
[[package]]
name = "lightcraft-meta"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"chrono",
"lightcraft-geom",
"lightcraft-heif",
"lightcraft-tiff",
"proptest",
"quick-xml 0.41.0",
@@ -3854,7 +3857,7 @@ dependencies = [
[[package]]
name = "lightcraft-pipeline"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"dhat",
"image",
@@ -3873,7 +3876,7 @@ dependencies = [
[[package]]
name = "lightcraft-preview"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"jpeg-encoder",
"lightcraft-raster",
@@ -3885,7 +3888,7 @@ dependencies = [
[[package]]
name = "lightcraft-raster"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"libc",
"lightcraft-color",
@@ -3897,7 +3900,7 @@ dependencies = [
[[package]]
name = "lightcraft-raw"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"dhat",
"jpeg-encoder",
@@ -3921,7 +3924,7 @@ dependencies = [
[[package]]
name = "lightcraft-scenes"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"image",
"lightcraft-color",
@@ -3932,7 +3935,7 @@ dependencies = [
[[package]]
name = "lightcraft-segment"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"candle-core",
"candle-nn",
@@ -3946,7 +3949,7 @@ dependencies = [
[[package]]
name = "lightcraft-slideshow"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lightcraft-raster",
"serde",
@@ -3955,15 +3958,15 @@ dependencies = [
[[package]]
name = "lightcraft-sysmem"
version = "0.15.0"
version = "0.16.0"
[[package]]
name = "lightcraft-testkit"
version = "0.15.0"
version = "0.16.0"
[[package]]
name = "lightcraft-tiff"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"proptest",
"serde",
@@ -3972,7 +3975,7 @@ dependencies = [
[[package]]
name = "lightcraft-ui-egui"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"craft-ui",
"craft-update",
@@ -4003,7 +4006,7 @@ dependencies = [
[[package]]
name = "lightcraft-web"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"crc32fast",
"eframe",
@@ -4884,7 +4887,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5843,7 +5846,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5900,7 +5903,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6479,10 +6482,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -7405,7 +7408,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -7820,7 +7823,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"brotli",
"flate2",
+5 -5
View File
@@ -3,18 +3,18 @@ resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.15.0"
version = "0.16.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/lightcraft"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
# internal
lightcraft-denoise-core = { path = "crates/denoise-core" }
lightcraft-denoise = { path = "crates/denoise", default-features = false }
+33 -2
View File
@@ -259,7 +259,8 @@ lightcraft --control 7980 ~/Pictures/trip
- **Command registry.** `engine.commands` lists the available commands; `develop.controls` lists every slider's
range, default and current value.
- **MCP server.** `lightcraft-cli mcp` exposes the command registry to Claude (or any MCP client), alongside
helpers for import, query, develop, mask, render (returned as an image) and export. It runs headless, or attached
helpers for import, query, develop, render (returned as an image) and export. Masks have no helper of their own:
create and edit them through `run_command` (e.g. `mask.add`). It runs headless, or attached
to the running app with screenshots, clicks and gestures. See [docs/mcp.md](docs/mcp.md).
```sh
@@ -451,6 +452,36 @@ information combined with LTO and one codegen unit on low-memory builders. A PKG
its own profile settings can override inherited variables; adjust the packaging recipe locally or
contact its maintainer rather than assuming an environment prefix on `makepkg` will take precedence.
**Linux/Arch build troubleshooting: rustc SIGILL with ThinLTO.**
In [#2811](https://github.com/storytold/lightcraft/issues/2811), an Arch Linux x86_64 build on an
AMD Ryzen 9 7900X3D with 64 GB RAM failed with rustc 1.99.0 / LLVM 23.1.1, AUR `lightcraft`
`0.7.1-1` and `0.13.0-1`, `RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`, and release settings
`opt-level=3`, `lto=thin`, `codegen-units=1`. `cargo build --frozen --release` reached the executable
crates before rustc crashed with signal 4 (`SIGILL` / `ILL_ILLOPN`). The core dumps point into LLVM's
SelectionDAG / vector-combine optimization path; the exact compiler root cause has not been isolated.
This does not mean every machine with that hardware or toolchain will fail. It is a different observed
failure from the 16 GB OOM kills in [#1196](https://github.com/storytold/lightcraft/issues/1196) above;
there is no evidence establishing a shared root cause.
For a direct Cargo source build, the equivalent command-local LTO override is:
```sh
CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release
```
Reporter @rwarmstr verified the workaround by exporting `CARGO_PROFILE_RELEASE_LTO=off` **inside the
AUR PKGBUILD's `_srcenv()` function** and rebuilding both package versions, without changing
`RUSTFLAGS`. The reporter tested the AUR recipe, not the direct Cargo invocation above.
A variable prefixed to `makepkg` alone may be overwritten by the PKGBUILD's own exports; the recipe
must honor or set the override. The AUR `!lto` opt-out behavior is tracked separately in
[#2813](https://github.com/storytold/lightcraft/issues/2813).
[Cargo's LTO documentation](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) distinguishes
`false` from `off`: `false` can still perform thin local LTO across codegen units (unless
`codegen-units=1` or `opt-level=0`); `off` disables LTO explicitly. The low-memory recipe above is
unchanged. This workaround is for affected builds, not a new default; disabling LTO may change
performance, binary size and build behavior.
Tests that need a GPU, the corpus, the craft-fonts faces or a model pass without checking anything when
those are missing (libtest has no "skipped" status), so `cargo xtask ci` lists them: tests record a skip
with `lightcraft_testkit::skip!`, and the run ends with what the machine offered (OS, CPUs, RAM, GPU
@@ -466,7 +497,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft
```
Without it LightCraft builds and runs the same, but Chinese and Japanese text have no glyphs. Fonts are never committed to this
repo — the standard for what goes there lives with it: see the [craft-fonts README](https://github.com/storytold/craft-fonts#readme).
repo — what goes there is described in the [craft-fonts README](https://github.com/storytold/craft-fonts#readme).
**Interface language:** **Edit → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Polski, Čeština, Italiano, ქართული, Svenska, Suomi, Bahasa Indonesia, Tiếng Việt) or **Settings → General →
Language**; the choice applies immediately and persists. See [docs/localization.md](docs/localization.md).
+30 -2
View File
@@ -241,7 +241,7 @@ lightcraft --control 7980 ~/Pictures/trip
- **命令注册表。** `engine.commands` 列出可用命令;`develop.controls` 列出每个滑块的范围、
默认值和当前值。
- **MCP 服务器。** `lightcraft-cli mcp` 把命令注册表开放给 Claude(或任何 MCP 客户端),
同时提供导入、查询、显影、蒙版、渲染(以图像返回)和导出的辅助工具。它既能无界面运行,也能附着
同时提供导入、查询、显影、渲染(以图像返回)和导出的辅助工具。蒙版没有专门的辅助工具,请通过 `run_command` 使用(例如 `mask.add`)。它既能无界面运行,也能附着
到正在运行的应用上,支持截图、点击和手势。见 [docs/mcp.md](docs/mcp.md)。
```sh
@@ -384,6 +384,34 @@ CARGO_BUILD_JOBS=1 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_LTO=false
设置可以覆盖继承的环境变量;应在本地调整打包配方或联系维护者,而不要假定给
`makepkg` 添加环境变量前缀就能优先生效。
**Linux/Arch 构建故障:rustc 在 ThinLTO 阶段发生 SIGILL。**
在 [#2811](https://github.com/storytold/lightcraft/issues/2811) 中,报告者的 Arch Linux x86_64
机器配备 AMD Ryzen 9 7900X3D 和 64 GB RAM,使用 rustc 1.99.0 / LLVM 23.1.1、AUR
`lightcraft` `0.7.1-1` 和 `0.13.0-1`、`RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`,
以及 release 设置 `opt-level=3`、`lto=thin`、`codegen-units=1`。
`cargo build --frozen --release` 在编译到可执行 crate 时,rustc 因 signal 4
(`SIGILL` / `ILL_ILLOPN`)崩溃。core dump 指向 LLVM 的 SelectionDAG / vector-combine
优化路径;编译器的具体根因尚未确定。这不表示所有使用这些硬件或工具链的机器都会失败。
此故障与上文 [#1196](https://github.com/storytold/lightcraft/issues/1196) 中 16 GB 机器上的
OOM 终止表现不同,没有证据表明两者根因相同。
直接使用 Cargo 从源码构建时,等价的单条命令 LTO 覆盖方式是:
```sh
CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release
```
报告者 @rwarmstr 验证成功的是:在 **AUR PKGBUILD 的 `_srcenv()` 函数内部**导出
`CARGO_PROFILE_RELEASE_LTO=off` 后重新构建上述两个版本,无需更改 `RUSTFLAGS`。
报告者测试的是 AUR 配方,并未单独验证上面的直接 Cargo 命令。仅在 `makepkg` 前添加变量,
可能会被 PKGBUILD 自己的 export 覆盖;打包配方必须保留或设置该覆盖值。
AUR 的 `!lto` 选项行为由 [#2813](https://github.com/storytold/lightcraft/issues/2813) 单独跟踪。
[Cargo 的 LTO 文档](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) 区分了 `false`
和 `off`:`false` 仍可能在代码生成单元之间执行 thin local LTO(除非 `codegen-units=1`
或 `opt-level=0`);`off` 则明确禁用 LTO。上文的低内存配方保持不变。
此绕过方法仅针对受影响的构建,不是新的默认建议;禁用 LTO 可能改变性能、二进制大小和构建行为。
**中文和日文文字**需要共享字体仓库,这是一个可选的构建输入(所有正式发布版都会包含它):
```sh
@@ -392,7 +420,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft
```
不指定它时,LightCraft 构建和运行的方式完全相同,只是中文和日文文字没有字形。字体从不提交到
本仓库;见 [craftrules `standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)。
本仓库。
**界面语言:** **编辑 → 语言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français)或 **设置 → 一般 →
语言**;选择立即生效并会保留。见 [docs/localization.md](docs/localization.md)。
+29 -1
View File
@@ -240,7 +240,7 @@ lightcraft --control 7980 ~/Pictures/trip
- **指令註冊表。** `engine.commands` 列出可用的指令;`develop.controls` 列出每個滑桿的範圍、
預設值與目前值。
- **MCP 伺服器。** `lightcraft-cli mcp` 把指令註冊表開放給 Claude(或任何 MCP 用戶端),
同時提供匯入、查詢、顯影、遮色片、算繪(以影像回傳)與匯出的輔助工具。它可以無介面執行,也可以附掛
同時提供匯入、查詢、顯影、算繪(以影像回傳)與匯出的輔助工具。遮色片沒有專屬的輔助工具,請透過 `run_command` 使用(例如 `mask.add`)。它可以無介面執行,也可以附掛
到正在執行的應用程式上,支援截圖、點擊與手勢。詳見 [docs/mcp.md](docs/mcp.md)。
```sh
@@ -402,6 +402,34 @@ CARGO_BUILD_JOBS=1 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_LTO=false
PKGBUILD 可能會覆寫繼承的環境變數;請在本機調整打包腳本或聯絡維護者,而不要假設替
`makepkg` 加上環境變數前綴就能優先生效。
**Linux/Arch 建置故障:rustc 在 ThinLTO 階段發生 SIGILL。**
在 [#2811](https://github.com/storytold/lightcraft/issues/2811) 中,回報者的 Arch Linux x86_64
機器配備 AMD Ryzen 9 7900X3D 與 64 GB RAM,使用 rustc 1.99.0 / LLVM 23.1.1、AUR
`lightcraft` `0.7.1-1` 與 `0.13.0-1`、`RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`,
以及 release 設定 `opt-level=3`、`lto=thin`、`codegen-units=1`。
`cargo build --frozen --release` 在編譯到可執行 crate 時,rustc 因 signal 4
(`SIGILL` / `ILL_ILLOPN`)當機。core dump 指向 LLVM 的 SelectionDAG / vector-combine
最佳化路徑;編譯器的具體根因尚未確定。這不表示所有使用這些硬體或工具鏈的機器都會失敗。
此故障與上文 [#1196](https://github.com/storytold/lightcraft/issues/1196) 中 16 GB 機器上的
OOM 終止表現不同,沒有證據顯示兩者根因相同。
直接使用 Cargo 從原始碼建置時,等價的單條指令 LTO 覆寫方式是:
```sh
CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release
```
回報者 @rwarmstr 驗證成功的是:在 **AUR PKGBUILD 的 `_srcenv()` 函式內部**匯出
`CARGO_PROFILE_RELEASE_LTO=off` 後重新建置上述兩個版本,無須變更 `RUSTFLAGS`。
回報者測試的是 AUR 腳本,並未單獨驗證上面的直接 Cargo 指令。僅在 `makepkg` 前加上變數,
可能會被 PKGBUILD 自己的 export 覆寫;打包腳本必須保留或設定該覆寫值。
AUR 的 `!lto` 選項行為由 [#2813](https://github.com/storytold/lightcraft/issues/2813) 另行追蹤。
[Cargo 的 LTO 文件](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) 區分了 `false`
與 `off`:`false` 仍可能在程式碼產生單元之間執行 thin local LTO(除非 `codegen-units=1`
或 `opt-level=0`);`off` 則明確停用 LTO。上文的低記憶體建置配方維持不變。
此繞過方法僅適用於受影響的建置,不是新的預設建議;停用 LTO 可能改變效能、二進位檔大小與建置行為。
測試在缺少 GPU、語料庫、craft-fonts 字型或模型時會直接通過而不檢查任何內容(libtest 沒有「已跳過」
這個狀態),所以 `cargo xtask ci` 會把它們列出來:測試會用 `lightcraft_testkit::skip!` 記錄跳過原因,
執行結束時會列出機器提供的環境(作業系統、CPU、記憶體、每個後端的 GPU 配接器、語料庫、字型)以及每一項
+8 -8
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~14 points and ~340–600 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (the lens profile database priority links its tracking issue #329; 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
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; 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
@@ -31,7 +31,7 @@ Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%):
The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), compressed ORF and HE NEF
open as previews, rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
tests run in CI on FreeBSD only. **Why alpha:** core workflows run end to end, but readiness is below
tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below
the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have blocking gaps (compressed ORF and HE NEF open as previews; Canon,
~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows
(import, cull, develop, save and reopen, batch looks, export) work end to end on macOS
@@ -109,7 +109,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
5. AI masks: Subject / Sky / People (40–70 h + model decision)
6. Compressed ORF and HE NEF (28–55 h)
7. Lens profile database of our own (40–80 h, #329)
8. Tests in CI on macOS, Windows and Linux (6–12 h)
8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h)
9. Per-model raw verification (20–35 h)
## Progress log
@@ -150,10 +150,9 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
- 2026-10-10 (RAW): RAW measured model by model against Adobe's 1,446-model list (234 verified, 943
unverified, 233 preview-only, 36 unsupported; ~84% of photographers' cameras decode, ~40% on a
verified body). Full ~61%, mainstream ~49%, essentials ~64%; beta ~14 points away.
- 2026-10-10 (final): full ready is a weighted sum over the dimensions (~59%; method aligned with
the standard); mainstream practitioner ~51% (450–840 h), essentials user ~63% (160–300 h);
- 2026-10-10 (final): full ready is a weighted sum over the dimensions (~59%; no new evidence); mainstream practitioner ~51% (450–840 h), essentials user ~63% (160–300 h);
alpha gate passes.
- 2026-10-10: full re-measure for the progress-docs standard: stage alpha, ready ~55%, checklist
- 2026-10-10: full re-measure, progress docs restructured: stage alpha, ready ~55%, checklist
81.1%; new docs (target-app-parity, gaps, roadmap, architecture, raw / file-format / hardware / UI
/ localization parity); `docs/parity.md` renamed `docs/parity-checklist.md`. Landed today: Nikon
lossy-after-split NEF (#633), ORF 12.8 bpp (#651), HDR gain map JPEG / PQ AVIF / float TIFF export
@@ -192,6 +191,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| Date | Change | Summary |
|---|---|---|
| 2026-10-24 | minor | Priority 7 (lens profile database) links its tracking issue #329; headline numbers unchanged |
| 2026-10-24 | patch | Alpha rationale: tests run in CI on Linux x64 (#2667) and FreeBSD nightly, not on macOS or Windows; ranked item 8 now reads "Tests in CI on macOS and Windows, and the GPU tests in CI"; percentages and hours unchanged |
| 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 |
@@ -213,10 +213,10 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| 2026-10-12 | minor | 117 Nikon and Fujifilm bodies verified (354 models, 24%); headline numbers unchanged |
| 2026-10-11 | minor | EOS R5 Mark II CR3 verified: CR3 on four verified bodies, RAW decoding 76% → 77%; headline numbers unchanged |
| 2026-10-10 | minor | RAW measured model by model; RAW decode and colour as explicit rows: full 59% → 61%, mainstream 51% → 49%, essentials 63% → 64%; beta ~14 points |
| 2026-10-10 | minor | Full ready restored to the additive weighted sum (~59%; method aligned with the standard, no new evidence); hours per audience; beta ~16 points away |
| 2026-10-10 | minor | Full ready restored to the additive weighted sum (~59%; no new evidence); hours per audience; beta ~16 points away |
| 2026-10-10 | minor | Mainstream practitioner and essentials user numbers; full ready 55% → 46% (method written down); beta 340–600 h |
| 2026-10-10 | minor | Alpha gate added (core-workflow check): passes, stays alpha |
| 2026-10-10 | major | Restructured to the progress-docs standard; re-measured; *Where we stand*, *Parity estimate* and *Totals* moved to docs/target-app-parity.md, milestones and risks to docs/roadmap.md, raw coverage to docs/raw-parity.md, catalog migration to docs/file-format-parity.md, CJK notes to docs/localization-parity.md |
| 2026-10-10 | major | Progress docs restructured; re-measured; *Where we stand*, *Parity estimate* and *Totals* moved to docs/target-app-parity.md, milestones and risks to docs/roadmap.md, raw coverage to docs/raw-parity.md, catalog migration to docs/file-format-parity.md, CJK notes to docs/localization-parity.md |
| 2026-10-08 | minor | *Where we stand* by dimension and by kind of user |
| 2026-10-02 | major | Parity estimate and effort table |
| 2026-09-30 | major | Created |
+3
View File
@@ -25,6 +25,9 @@ lightcraft-merge = { workspace = true }
serde_json = { workspace = true }
dhat = { workspace = true, optional = true }
[dev-dependencies]
lightcraft-testkit = { workspace = true }
[features]
default = ["denoise"]
denoise = ["lightcraft-engine/denoise"]
+102 -11
View File
@@ -155,7 +155,16 @@ fn main() -> ExitCode {
// Warnings (a GPU render redone on the CPU, an unknown backend name) on stderr; LIGHTCRAFT_LOG
// or RUST_LOG picks another level (#168).
lightcraft_engine::logging::install("lightcraft-cli");
let args: Vec<String> = std::env::args().skip(1).collect();
let mut args: Vec<String> = Vec::new();
for (index, arg) in std::env::args_os().skip(1).enumerate() {
match arg.into_string() {
Ok(arg) => args.push(arg),
Err(_) => {
eprintln!("lightcraft-cli: argument {} is not valid Unicode", index + 1);
return ExitCode::FAILURE;
}
}
}
let r = match args.first().map(String::as_str) {
Some("run") => run(&args[1..]),
Some("mcp") => mcp(&args[1..]),
@@ -561,6 +570,8 @@ fn run(args: &[String]) -> Result<(), String> {
} else {
std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?
};
// Windows PowerShell 5.1 writes a UTF-8 BOM; it is not part of the first JSON line.
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
for (n, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty() && !l.trim_start().starts_with('#')) {
let v: Value = serde_json::from_str(line).map_err(|e| format!("{path}:{}: {e}", n + 1))?;
// `{"command": id, "params": …}` or a control request `{"method": m, "params": …}`
@@ -569,7 +580,11 @@ fn run(args: &[String]) -> Result<(), String> {
.or(v.get("method"))
.and_then(Value::as_str)
.ok_or_else(|| format!("{path}:{}: needs `command` or `method`", n + 1))?;
let params = v.get("params").cloned().filter(|p| p.is_object()).unwrap_or_else(|| json!({}));
let params = match v.get("params") {
None | Some(Value::Null) => json!({}),
Some(Value::Object(params)) => Value::Object(params.clone()),
Some(_) => return Err(format!("{path}:{}: `params` must be a JSON object", n + 1)),
};
steps.push(Step { id: id.to_string(), params });
}
}
@@ -598,14 +613,7 @@ fn run(args: &[String]) -> Result<(), String> {
None => Headless::default(),
};
if !imports.is_empty() {
let paths = expand_paths(&imports);
let r = h.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?;
// what follows acts on the imported photos (already-known files are reported as duplicates)
let mut ids: Vec<Value> = r["imported"].as_array().cloned().unwrap_or_default();
ids.extend(r["duplicates"].as_array().into_iter().flatten().filter_map(|d| d.get("existing").filter(|v| v.is_u64()).cloned()));
if let Some(first) = ids.first().cloned() {
h.session.execute("library.select", &json!({"ids": ids, "active": first})).map_err(|e| e.to_string())?;
}
import_and_select(&mut h.session, &imports)?;
}
Box::new(h)
}
@@ -630,6 +638,34 @@ fn run(args: &[String]) -> Result<(), String> {
if failed > 0 { Err(format!("{failed} command(s) failed")) } else { Ok(()) }
}
fn import_and_select(session: &mut Session, imports: &[String]) -> Result<(), String> {
let selection = session.selection.clone();
let paths = expand_paths(imports);
let result = (|| {
let r = session.execute("library.import", &json!({"paths": paths})).map_err(|e| format!("import failed: {e}; no commands were run"))?;
let ids = import_targets(&r)?;
let first = ids.first().cloned().ok_or("import found no photos to select; no commands were run")?;
session.execute("library.select", &json!({"ids": ids, "active": first})).map_err(|e| e.to_string())?;
Ok::<(), String>(())
})();
if result.is_err() {
session.selection = selection;
}
result
}
fn import_targets(report: &Value) -> Result<Vec<Value>, String> {
if let Some(failed) = report["failed"].as_array().filter(|failed| !failed.is_empty()) {
return Err(format!("import failed for {} item(s): {}; no commands were run", failed.len(), json!(failed)));
}
let mut ids: Vec<Value> = report["imported"].as_array().cloned().unwrap_or_default();
ids.extend(report["duplicates"].as_array().into_iter().flatten().filter_map(|d| d.get("existing").filter(|v| v.is_u64()).cloned()));
ids.extend(report["restored"].as_array().into_iter().flatten().filter(|id| id.is_u64()).cloned());
let mut seen = std::collections::HashSet::new();
ids.retain(|id| id.as_u64().is_none_or(|id| seen.insert(id)));
if ids.is_empty() { Err("import found no photos to select; no commands were run".into()) } else { Ok(ids) }
}
fn take_value<'a>(args: &'a [String], i: &mut usize, flag: &str) -> Result<&'a str, String> {
*i += 1;
args.get(*i).map(String::as_str).ok_or_else(|| format!("{flag} needs a value"))
@@ -687,7 +723,9 @@ fn render(args: &[String]) -> Result<(), String> {
"--set" => {
let kv = take_value(args, &mut i, "--set")?;
let (k, v) = kv.split_once('=').ok_or_else(|| format!("--set expects control=value, got `{kv}`"))?;
let v: f64 = v.trim().parse().map_err(|_| format!("--set {k}: `{v}` is not a number"))?;
// `inf` / `NaN` parse as f64 but become JSON null, which the control would silently ignore.
let v: f64 =
v.trim().parse().ok().filter(|n: &f64| n.is_finite()).ok_or_else(|| format!("--set {k}: `{v}` is not a finite number"))?;
values.insert(k.trim().to_string(), json!(v));
}
"--settings" => settings = Some(read_settings(take_value(args, &mut i, "--settings")?)?),
@@ -856,6 +894,8 @@ fn snapshot(args: &[String]) -> Result<(), String> {
let mut failed = 0usize;
if let Some(script) = &script {
let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?;
// Windows PowerShell 5.1 writes a UTF-8 BOM; it is not part of the first JSON line.
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let mut out = std::io::stdout().lock();
for (n, line) in text.lines().enumerate() {
let line = line.trim();
@@ -1032,3 +1072,54 @@ fn denoise_serve(args: &[String]) -> Result<(), String> {
fn denoise_serve(_: &[String]) -> Result<(), String> {
Err("denoise-serve: this build has no denoise support (build with the `denoise` feature)".into())
}
#[cfg(test)]
mod import_target_tests {
use super::{import_and_select, import_targets, json};
#[test]
fn empty_reports_and_duplicates_without_ids_have_no_target() {
assert!(import_targets(&json!({})).is_err());
assert!(import_targets(&json!({"imported": [], "duplicates": [{"existing": null}]})).is_err());
}
#[test]
fn restored_only_and_mixed_reports_keep_target_order() {
assert_eq!(import_targets(&json!({"restored": [9]})).unwrap(), vec![json!(9)]);
assert_eq!(
import_targets(&json!({"imported": [1], "duplicates": [{"existing": null}, {"existing": 2}], "restored": [3]})).unwrap(),
vec![json!(1), json!(2), json!(3)]
);
}
#[test]
fn repeated_targets_are_selected_once_in_first_occurrence_order() {
let report = json!({"imported": [5, 7], "duplicates": [{"existing": 5}, {"existing": 8}, {"existing": 8}, {"existing": 7}, {"existing": null}], "restored": [8, 9, 5]});
assert_eq!(import_targets(&report).unwrap(), vec![json!(5), json!(7), json!(8), json!(9)]);
}
#[test]
fn failed_items_reject_even_when_targets_exist() {
let error = import_targets(&json!({"imported": [1], "failed": [["broken.png", "invalid"]]})).unwrap_err();
assert!(error.contains("1") && error.contains("broken.png") && error.contains("no commands were run"), "{error}");
}
#[test]
fn failed_partial_import_restores_empty_selection() {
let dir = std::env::temp_dir().join(format!("lightcraft-import-selection-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("valid.png");
let broken = dir.join("broken.png");
let img = lightcraft_raster::Rgba8::from_fn(2, 2, |_, _| [20, 40, 60, 255]);
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
std::fs::write(&input, png).unwrap();
std::fs::write(&broken, b"not a PNG").unwrap();
let mut headless = lightcraft_mcp::Headless::default();
let session = &mut headless.session;
let selection = session.selection.clone();
assert!(selection.ids.is_empty() && selection.active.is_none());
assert!(import_and_select(session, &[input.to_string_lossy().into_owned(), broken.to_string_lossy().into_owned()]).is_err());
assert_eq!(session.selection, selection);
let _ = std::fs::remove_dir_all(dir);
}
}
+353 -15
View File
@@ -162,6 +162,43 @@ fn mcp_over_stdio_sets_exposure_and_renders() {
assert!(b > a + 10.0, "{a} → {b}");
}
#[cfg(unix)]
#[test]
fn non_utf8_argument_fails_without_a_panic() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let out = tmp("non-utf8-output.png");
let _ = std::fs::remove_file(&out);
let output = Command::new(binary()).arg("render").arg(OsString::from_vec(b"bad-\xff.png".to_vec())).arg("-o").arg(&out).output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{stderr}");
assert!(stderr.contains("argument 2"), "{stderr}");
assert!(stderr.contains("is not valid Unicode"), "{stderr}");
assert!(!stderr.contains("panicked"), "{stderr}");
assert!(!out.exists());
assert!(Command::new(binary()).arg("--version").status().unwrap().success());
}
#[cfg(windows)]
#[test]
fn non_unicode_argument_fails_without_a_panic_on_windows() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let out = tmp("non-unicode-output.png");
let _ = std::fs::remove_file(&out);
let name: Vec<u16> = "bad-".encode_utf16().chain([0xD800]).chain(".png".encode_utf16()).collect();
let output = Command::new(binary()).arg("render").arg(OsString::from_wide(&name)).arg("-o").arg(&out).output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{stderr}");
assert!(stderr.contains("argument 2"), "{stderr}");
assert!(stderr.contains("is not valid Unicode"), "{stderr}");
assert!(!stderr.contains("panicked"), "{stderr}");
assert!(!out.exists());
assert!(Command::new(binary()).arg("--version").status().unwrap().success());
}
#[test]
fn render_subcommand() {
let input = tmp("r-in.png");
@@ -184,6 +221,12 @@ fn render_subcommand() {
let o = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "nope=1"]).output().unwrap();
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown control"));
// Values that parse as f64 but are not finite fail cleanly too.
for bad in ["light.exposure=inf", "light.exposure=-inf", "light.exposure=NaN", "light.exposure=1e999"] {
let o = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", bad]).output().unwrap();
assert!(!o.status.success(), "{bad} must be refused");
assert!(String::from_utf8_lossy(&o.stderr).contains("not a finite number"), "{bad}");
}
}
/// Issue #1730: `render --settings` took a `.lcpreset` from `preset.export`, ignored its wrapper
@@ -443,7 +486,12 @@ fn snapshot_defaults_to_cpu_without_gpu_environment_overrides() {
let script = tmp("default-cpu.jsonl");
std::fs::write(
&script,
format!("{}\n{}\n", json!({"method": "engine.execute", "params": {"command": "app.gpu"}}), json!({"method": "ui.screenshot"})),
format!(
"{}\n{}\n{}\n",
json!({"method": "engine.execute", "params": {"command": "app.gpu", "params": {"wait": false}}}),
json!({"method": "engine.execute", "params": {"command": "app.gpu"}}),
json!({"method": "ui.screenshot"})
),
)
.unwrap();
let image = tmp("default-cpu.png");
@@ -457,15 +505,52 @@ fn snapshot_defaults_to_cpu_without_gpu_environment_overrides() {
assert!(output.status.success(), "status {}: {}", output.status, String::from_utf8_lossy(&output.stderr));
let replies: Vec<Value> = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert!(replies.iter().all(|reply| reply["ok"] == true), "{replies:?}");
let gpu = &replies[0]["result"];
assert_eq!(gpu["enabled"], false, "{gpu}");
assert_eq!(gpu["available"], false, "{gpu}");
assert_eq!(gpu["adapter"], Value::Null, "no device is created: {gpu}");
assert!(gpu["reason"].as_str().is_some_and(|reason| reason.contains("preference")), "{gpu}");
// `wait: false` (what the UI sends) still says why the GPU is off: no device is being created
for gpu in [&replies[0]["result"], &replies[1]["result"]] {
assert_eq!(gpu["enabled"], false, "{gpu}");
assert_eq!(gpu["available"], false, "{gpu}");
assert_eq!(gpu["adapter"], Value::Null, "no device is created: {gpu}");
assert!(gpu["reason"].as_str().is_some_and(|reason| reason.contains("preference")), "{gpu}");
}
let decoded = lightcraft_codecs::decode(&std::fs::read(image).unwrap(), Default::default()).unwrap();
assert_eq!((decoded.width, decoded.height), (480, 320));
}
/// Issue #136: `app.gpu {enabled: true, wait: false}` (what the UI sends on its first frame) answers
/// at once while the device is still being created: enabled, and nothing known yet (`null`), instead
/// of waiting for the driver. It starts creating the device (off the calling thread), so this test
/// touches the GPU driver and skips when the environment turns the GPU off.
#[test]
fn enabling_the_gpu_without_waiting_answers_before_the_device_exists() {
if std::env::var("LIGHTCRAFT_GPU").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")) {
lightcraft_testkit::skip!(Gpu, "LIGHTCRAFT_GPU=0: enabling the GPU starts creating a device");
return;
}
let script = tmp("gpu-starting.jsonl");
std::fs::write(
&script,
format!("{}\n", json!({"method": "engine.execute", "params": {"command": "app.gpu", "params": {"enabled": true, "wait": false}}})),
)
.unwrap();
let image = tmp("gpu-starting.png");
let output = Command::new(binary())
.env_remove("LIGHTCRAFT_GPU")
.env_remove("LIGHTCRAFT_GPU_BACKEND")
.env_remove("WGPU_BACKEND")
.args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", image.to_str().unwrap(), "--size", "480x320"])
.output()
.unwrap();
assert!(output.status.success(), "status {}: {}", output.status, String::from_utf8_lossy(&output.stderr));
let replies: Vec<Value> = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], true, "{replies:?}");
let gpu = &replies[0]["result"];
assert_eq!(gpu["enabled"], true, "{gpu}");
for field in ["available", "adapter", "reason"] {
assert_eq!(gpu[field], Value::Null, "{field} is not known while the device is created: {gpu}");
}
}
/// Issue #136: with the GPU switched off from the environment the UI starts and renders on the CPU,
/// without creating a GPU device (no driver is loaded), and says why.
#[test]
@@ -502,6 +587,29 @@ fn snapshot_starts_without_a_gpu() {
}
}
/// A loopback port nothing listens on, for tests that need `--connect` to be refused (#3070).
/// A fixed port is not safe: agents give their apps' control servers ports in 18000–19999 (and
/// 7980 is the default), so a test could reach someone's running app and drive it. The OS hands
/// out a free port for `:0`; the listener is dropped so connecting to it is refused. Another
/// process could bind the port between the drop and the connect. That window is a few
/// milliseconds, and `:0` draws from the OS's ephemeral range (from 32768 on Linux, 49152 on
/// macOS and Windows), where nobody puts a control server (7980, 18000–19999): the standard
/// trade-off for a test that needs a refused connection.
///
/// Within this binary the window is closed: the tests that take an ephemeral port and let it go
/// hold [`ephemeral_ports`], so `denoise-serve` can't start on a port a refused-connection test
/// picked while it runs.
fn unused_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
/// Held by each test that picks an ephemeral port and releases it before use, for the whole test.
fn ephemeral_ports() -> std::sync::MutexGuard<'static, ()> {
static PORTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
// a test that failed while holding it doesn't fail the others
PORTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn run_cli(args: &[&str], stdin: Option<&str>) -> (bool, Vec<Value>, String) {
let mut child = Command::new(binary()).arg("run").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
if let Some(text) = stdin {
@@ -513,6 +621,230 @@ fn run_cli(args: &[&str], stdin: Option<&str>) -> (bool, Vec<Value>, String) {
(o.status.success(), lines, String::from_utf8_lossy(&o.stderr).to_string())
}
/// Windows PowerShell 5.1 writes a UTF-8 BOM; `--script` (file and stdin) must accept it.
#[test]
fn run_script_accepts_a_utf8_bom() {
let text = "\u{feff}{\"command\": \"library.info\", \"params\": {}}\n";
let script = tmp("bom-steps.jsonl");
std::fs::write(&script, text).unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--script", script.to_str().unwrap()], None);
assert!(ok, "file: {err}");
assert_eq!(lines.len(), 1, "{lines:?}");
let (ok, lines, err) = run_cli(&["--demo", "--script", "-"], Some(text));
assert!(ok, "stdin: {err}");
assert_eq!(lines.len(), 1, "{lines:?}");
}
#[test]
fn run_script_params_validate_before_any_commands() {
let path = tmp("run-invalid-params.jsonl");
let path_str = path.to_str().unwrap();
for params in [json!([]), json!("invalid"), json!(42), json!(true)] {
let script = format!("{}\n{}\n", json!({"command": "library.info"}), json!({"command": "develop.reset", "params": params}));
std::fs::write(&path, &script).unwrap();
for (source, stdin) in [("-", Some(script.as_str())), (path_str, None)] {
let (ok, lines, err) = run_cli(&["--script", source], stdin);
assert!(!ok, "{source}: {params}: {lines:?}");
assert!(lines.is_empty(), "{source}: {params}: {lines:?}");
assert!(err.contains(&format!("{source}:2")), "{err}");
assert!(err.contains("`params` must be a JSON object"), "{err}");
}
}
for script in
["{\"command\":\"library.info\"}\n", "{\"command\":\"library.info\",\"params\":null}\n", "{\"command\":\"library.info\",\"params\":{}}\n"]
{
let (ok, lines, err) = run_cli(&["--script", "-"], Some(script));
assert!(ok, "{script}: {err}");
assert_eq!(lines.len(), 1, "{script}: {lines:?}");
assert_eq!(lines[0]["ok"], true, "{script}: {lines:?}");
}
std::fs::remove_file(path).unwrap();
}
#[test]
fn run_failed_import_never_edits_existing_selection() {
let dir = tmp("failed-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let lib = dir.join("library");
let missing = dir.join("missing.png");
let empty = dir.join("empty");
std::fs::create_dir(&empty).unwrap();
assert!(!missing.exists());
let lib = lib.to_str().unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--library", lib, "library.state"], None);
assert!(ok, "{err}");
let id = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, _, err) = run_cli(&["--library", lib, "photo.rate", &format!("ids=[{id}]"), "rating=0"], None);
assert!(ok, "{err}");
for path in [&missing, &empty] {
let (ok, lines, err) = run_cli(&["--library", lib, "--import", path.to_str().unwrap(), "photo.rate", "rating=5"], None);
assert!(!ok, "import unexpectedly succeeded for {}: {lines:?}", path.display());
assert!(lines.is_empty(), "commands ran: {lines:?}");
assert!(err.contains("import") && err.contains("no commands were run"), "{err}");
if path == &missing {
assert!(err.contains("failed") && err.contains("missing.png"), "{err}");
}
let (ok, lines, err) = run_cli(&["--library", lib, "photo.inspect", &format!("id={id}")], None);
assert!(ok, "{err}");
assert_eq!(lines[0]["result"]["rating"], 0);
}
}
#[test]
fn run_partial_import_stops_commands_and_import_targets_remain_usable() {
let dir = tmp("partial-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("valid.png");
let broken = dir.join("broken.png");
gradient_png(&input);
std::fs::write(&broken, b"not a PNG").unwrap();
let mixed_lib = dir.join("mixed");
let mixed_lib = mixed_lib.to_str().unwrap();
let input = input.to_str().unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--library", mixed_lib, "catalog.query"], None);
assert!(ok, "{err}");
let photos = lines[0]["result"]["photos"].as_array().unwrap();
let a = photos[0]["id"].as_u64().unwrap();
let b = photos[1]["id"].as_u64().unwrap();
let (ok, lines, err) = run_cli(
&[
"--library",
mixed_lib,
"library.select",
&format!("ids=[{a},{b}]"),
&format!("active={a}"),
"photo.rate",
&format!("ids=[{a}]"),
"rating=0",
"library.state",
],
None,
);
assert!(ok, "{err}");
let selection = lines[2]["result"]["selection"].clone();
assert_eq!(selection["ids"], json!([a, b]));
assert_eq!(selection["active"], a);
let (ok, lines, err) =
run_cli(&["--library", mixed_lib, "--import", input, "--import", broken.to_str().unwrap(), "photo.rate", "rating=5"], None);
let (query_ok, after, query_err) =
run_cli(&["--library", mixed_lib, "library.state", "photo.inspect", &format!("id={a}"), "catalog.query"], None);
assert!(query_ok, "{query_err}");
assert_eq!(after[0]["result"]["selection"], selection, "selection changed after partial import");
assert!(!ok, "partial import unexpectedly succeeded: {lines:?}");
assert!(lines.is_empty() && err.contains("failed") && err.contains("no commands were run"), "{err}: {lines:?}");
assert_eq!(after[1]["result"]["rating"], 0);
assert!(after[2]["result"]["photos"].as_array().unwrap().iter().any(|p| p["fileName"] == "valid.png"));
let lib = dir.join("duplicates");
let lib = lib.to_str().unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--library", lib, "library.state"], None);
assert!(ok, "{err}");
let previous = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, lines, err) = run_cli(&["--library", lib, "--import", input, "photo.rate", "rating=4", "library.state"], None);
assert!(ok, "{err}");
let id = lines[1]["result"]["selection"]["active"].as_u64().unwrap();
assert_ne!(id, previous);
let (ok, _, err) = run_cli(&["--library", lib, "library.select", &format!("ids=[{previous}]"), "photo.rate", "rating=0"], None);
assert!(ok, "{err}");
let (ok, _, err) = run_cli(&["--library", lib, "--import", input, "photo.rate", "rating=3"], None);
assert!(ok, "{err}");
let (ok, lines, err) = run_cli(&["--library", lib, "photo.inspect", &format!("id={id}"), "photo.inspect", &format!("id={previous}")], None);
assert!(ok, "{err}");
assert_eq!(lines[0]["result"]["rating"], 3);
assert_eq!(lines[1]["result"]["rating"], 0);
}
#[test]
fn run_restored_import_is_selected() {
let dir = tmp("restored-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("valid.png");
gradient_png(&input);
let lib = dir.join("library");
let (lib, input) = (lib.to_str().unwrap(), input.to_str().unwrap());
let (ok, lines, err) = run_cli(&["--library", lib, "--import", input, "library.state"], None);
assert!(ok, "{err}");
let id = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, _, err) = run_cli(&["--library", lib, "photo.delete"], None);
assert!(ok, "{err}");
let (ok, _, err) = run_cli(&["--library", lib, "--import", input, "photo.rate", "rating=4"], None);
assert!(ok, "{err}");
let (ok, lines, err) = run_cli(&["--library", lib, "catalog.query"], None);
assert!(ok, "{err}");
assert_eq!(lines[0]["result"]["photos"].as_array().unwrap().len(), 1);
assert_eq!(lines[0]["result"]["photos"][0]["id"], id);
assert_eq!(lines[0]["result"]["photos"][0]["rating"], 4);
}
#[test]
fn run_same_batch_duplicates_selects_photo_once() {
let dir = tmp("same-batch-duplicates");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let first = dir.join("first.png");
let second = dir.join("second.png");
gradient_png(&first);
std::fs::copy(&first, &second).unwrap();
let library = dir.join("library");
let (ok, lines, err) = run_cli(
&[
"--library",
library.to_str().unwrap(),
"--import",
first.to_str().unwrap(),
"--import",
second.to_str().unwrap(),
"photo.rate",
"rating=4",
"library.state",
"catalog.query",
],
None,
);
assert!(ok, "{err}");
let selection = &lines[1]["result"]["selection"];
let ids = selection["ids"].as_array().unwrap();
assert_eq!(ids.len(), 1, "same photo selected more than once: {selection}");
assert_eq!(selection["active"], ids[0]);
let photos = lines[2]["result"]["photos"].as_array().unwrap();
assert_eq!(photos.len(), 1);
assert_eq!(photos[0]["id"], ids[0]);
assert_eq!(photos[0]["rating"], 4);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn run_mixed_new_and_restored_import_selects_both() {
let dir = tmp("mixed-restored-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let restored = dir.join("restored.png");
let new = dir.join("new.png");
gradient_png(&restored);
let image = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, 200, 255]);
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&image), &Default::default()).unwrap();
std::fs::write(&new, png).unwrap();
let lib = dir.join("library");
let (lib, restored, new) = (lib.to_str().unwrap(), restored.to_str().unwrap(), new.to_str().unwrap());
let (ok, lines, err) = run_cli(&["--library", lib, "--import", restored, "library.state"], None);
assert!(ok, "{err}");
let restored_id = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, _, err) = run_cli(&["--library", lib, "photo.delete"], None);
assert!(ok, "{err}");
let (ok, lines, err) = run_cli(&["--library", lib, "--import", new, "--import", restored, "photo.rate", "rating=4", "library.state"], None);
assert!(ok, "{err}");
assert_eq!(lines[1]["result"]["selection"]["ids"].as_array().unwrap().len(), 2);
let (ok, lines, err) = run_cli(&["--library", lib, "catalog.query"], None);
assert!(ok, "{err}");
let photos = lines[0]["result"]["photos"].as_array().unwrap();
assert_eq!(photos.len(), 2);
assert!(photos.iter().any(|p| p["id"] == restored_id && p["rating"] == 4));
assert!(photos.iter().any(|p| p["fileName"] == "new.png" && p["id"] != restored_id && p["rating"] == 4));
}
#[test]
fn run_subcommand_chains_commands_and_persists_a_library() {
let input = tmp("run-in.png");
@@ -614,9 +946,11 @@ fn a_library_open_in_another_process_is_refused() {
/// ADDR actually names — following the old fixed "7980" left the retry connecting elsewhere.
#[test]
fn connect_failure_hint_names_the_attempted_port() {
let (ok, _lines, err) = run_cli(&["--connect", "127.0.0.1:18437", "ui.inspect"], None);
let _ports = ephemeral_ports();
let port = unused_port();
let (ok, _lines, err) = run_cli(&["--connect", &format!("127.0.0.1:{port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "the hint must name the port it tried: {err}");
assert!(err.contains(&format!("--control {port}")), "the hint must name the port it tried: {err}");
assert!(!err.contains("--control 7980"), "{err}");
}
@@ -626,20 +960,23 @@ fn connect_failure_hint_names_the_attempted_port() {
/// works; non-numeric, non-`ADDR`-shaped tokens (e.g. a real command id) keep falling through.
#[test]
fn connect_bare_port_is_treated_as_loopback_port() {
let _ports = ephemeral_ports();
let port = unused_port();
let hint = format!("--control {port}");
// Bare port: the failure hint names that port.
let (ok, _lines, err) = run_cli(&["--connect", "18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&["--connect", &port.to_string(), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "bare port must reach the hint: {err}");
assert!(err.contains(&hint), "bare port must reach the hint: {err}");
assert!(!err.contains("--control 7980"), "{err}");
// `<host>:<port>` still works (issue #167 case).
let (ok, _lines, err) = run_cli(&["--connect", "127.0.0.1:18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&["--connect", &format!("127.0.0.1:{port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "{err}");
assert!(err.contains(&hint), "{err}");
// `--connect=<bare-port>` already worked (the `a.starts_with("--connect=")` arm); spot-check
// the hint matches its port too.
let (ok, _lines, err) = run_cli(&["--connect=18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&[&format!("--connect={port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "{err}");
assert!(err.contains(&hint), "{err}");
}
/// The CLI logs warnings on stderr (#168): with `RUST_LOG=warn` an unknown GPU backend name is
@@ -785,7 +1122,8 @@ fn denoise_serve_runs_tiles_for_another_computer() {
Command::new(binary()).args(["denoise-serve", "--models", models.to_str().unwrap(), "--token-env", "LC_TEST_NO_SUCH_VAR"]).output().unwrap();
assert!(!o.status.success() && String::from_utf8_lossy(&o.stderr).contains("LC_TEST_NO_SUCH_VAR"));
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let _ports = ephemeral_ports();
let port = unused_port();
let addr = format!("127.0.0.1:{port}");
let token = "cli-test-token-0123456789";
let mut child = Command::new(binary())
+115 -19
View File
@@ -87,7 +87,7 @@ fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context, id
log::warn!("control connection closed: could not set idle read timeout: {e}");
return;
}
serve_lines(&stream, &stream, |method, params| {
serve_stream(stream, |method, params| {
let (req, rrx) = ControlRequest::new(method, params);
let state = Arc::clone(&req.state);
tx.send(req).ok()?;
@@ -96,6 +96,40 @@ fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context, id
});
}
/// The longest a closing connection is drained, however slowly its peer keeps sending.
const DRAIN_TIME: Duration = Duration::from_secs(1);
/// [`serve_lines`] on a socket, then close it so the peer reads every reply.
fn serve_stream(stream: TcpStream, handle: impl FnMut(String, Value) -> Option<Value>) {
serve_lines(&stream, &stream, handle);
close_gracefully(&stream);
}
/// Close a connection the server is done with without destroying its last reply. A socket closed
/// while the peer's later lines are unread, or arrive after it, answers them with a reset, and a
/// reset can discard the replies the peer has not read yet (on Windows it does): the client sees
/// "connection reset" instead of why. Send FIN, then read and drop what is left (at most
/// [`MAX_LINE`] bytes, 500 ms per read and [`DRAIN_TIME`] in all) before closing. From #1970
/// (LochLogic).
fn close_gracefully(stream: &TcpStream) {
let _ = stream.shutdown(std::net::Shutdown::Write);
let start = std::time::Instant::now();
let mut sink = [0u8; 8192];
let mut left = MAX_LINE;
let mut reader = stream;
while left > 0 {
// a peer that keeps trickling bytes must not hold the connection slot past DRAIN_TIME
let wait = DRAIN_TIME.saturating_sub(start.elapsed()).min(Duration::from_millis(500));
if wait.is_zero() || stream.set_read_timeout(Some(wait)).is_err() {
break;
}
match reader.read(&mut sink) {
Ok(0) | Err(_) => break,
Ok(n) => left = left.saturating_sub(n),
}
}
}
/// Wait for a request's reply. While the app has not picked the request up and `frames` (its
/// frame counter) stands still for `no_frames`, the request is abandoned (it will not run late)
/// and the reply says why; a request the app is running gets the whole `timeout`.
@@ -170,15 +204,40 @@ fn parse_line(bytes: &[u8]) -> Line {
}
}
/// The error of the notice sent when an idle connection is closed. Clients match the reply's
/// `"closed": "idle"` marker; `crates/mcp/src/backend.rs` also matches this text, for apps from
/// before the marker, so keep the two in step.
const IDLE_CLOSE_ERROR: &str = "control connection idle read timed out; closing the connection";
/// Why the server closes a connection; its error reply says so.
#[derive(Debug, PartialEq)]
enum Closing {
/// Nothing complete arrived within the idle timeout. Nothing more is read, so a request that
/// crosses the notice is never run: the reply carries `"closed": "idle"` to tell clients it is
/// safe to send that request again on a new connection.
Idle,
/// Junk, an overlong line or a failed read.
Error(String),
}
impl Closing {
fn reply(&self) -> Value {
match self {
Self::Idle => json!({"ok": false, "error": IDLE_CLOSE_ERROR, "closed": "idle"}),
Self::Error(e) => json!({"ok": false, "error": e}),
}
}
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, Closing> {
buf.clear();
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() {
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => "control connection idle read timed out; closing the connection".to_string(),
_ => e.to_string(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => Closing::Idle,
_ => Closing::Error(e.to_string()),
})?;
if n == 0 {
return Ok(false);
@@ -191,7 +250,7 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -
return Ok(true);
}
if buf.len() > max {
return Err(format!("request line longer than {max} bytes; closing the connection"));
return Err(Closing::Error(format!("request line longer than {max} bytes; closing the connection")));
}
// Last line without a newline, then end of stream.
Ok(true)
@@ -204,12 +263,12 @@ fn serve_lines<R: Read, W: Write>(read: R, mut out: W, mut handle: impl FnMut(St
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
let closing = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
Ok(false) => return,
Err(e) => e,
Err(closing) => closing,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
Line::Reject(e) => Closing::Error(e),
Line::Request { id, method, params } => {
let Some(mut r) = handle(method, params) else { return };
if let Some(o) = r.as_object_mut() {
@@ -222,7 +281,7 @@ fn serve_lines<R: Read, W: Write>(read: R, mut out: W, mut handle: impl FnMut(St
}
},
};
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush());
let _ = writeln!(out, "{}", closing.reply()).and_then(|()| out.flush());
return;
}
}
@@ -287,7 +346,9 @@ mod tests {
assert!(connection.requests.try_recv().is_err(), "incomplete input never runs");
let reply: Value = serde_json::from_str(&reply).unwrap();
assert_eq!(reply["ok"], false);
assert!(reply["error"].as_str().unwrap().contains("idle read timed out"));
assert_eq!(reply["error"], IDLE_CLOSE_ERROR);
assert_eq!(reply["closed"], "idle", "clients may resend a request that crossed this notice");
assert!(reply.get("id").is_none());
// A subsequent connection is admitted through the same accounting path.
let mut next = Connection::new(&open, Duration::from_secs(1), |c| c.shutdown(std::net::Shutdown::Write).unwrap());
@@ -413,6 +474,7 @@ mod tests {
assert_eq!(r.len(), 1);
assert_eq!(r[0]["ok"], false);
assert!(r[0]["error"].as_str().unwrap().contains("closing the connection"));
assert!(r[0].get("closed").is_none(), "only an idle close invites a resend: {}", r[0]);
}
#[test]
@@ -502,18 +564,52 @@ mod tests {
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
let read = s.try_clone().unwrap();
serve_lines(read, s, |_, _| Some(json!({"ok": true})));
serve_stream(s, |_, _| Some(json!({"ok": true})));
});
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
let mut text = String::new();
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap();
let mut replies = BufReader::new(c.try_clone().unwrap());
let (mut first, mut second) = (String::new(), String::new());
replies.read_line(&mut first).unwrap();
replies.read_line(&mut second).unwrap();
assert!(first.contains("\"id\":7"), "{first}");
assert!(second.contains("closing the connection"), "{second}");
// A client that keeps sending after the junk: its next line reaches the server after the
// rejection. A socket closed by then answers that line with a reset, which the client reads
// as "connection reset" (os error 10053 / 10054 on Windows) instead of the end of the
// replies. The pause lets a reset arrive before the read.
c.write_all(b"{\"method\":\"y\"}\n").unwrap();
std::thread::sleep(Duration::from_millis(100));
let mut rest = String::new();
let read = replies.read_to_string(&mut rest);
server.join().unwrap();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 2, "{text}");
assert!(lines[0].contains("\"id\":7"));
assert!(lines[1].contains("closing the connection"));
assert!(read.is_ok(), "the close must be clean, not a reset: {read:?}");
assert_eq!(rest, "", "nothing follows the rejection");
}
#[test]
fn a_closing_connection_is_not_held_open_by_a_trickling_peer() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let server_done = Arc::clone(&done);
let server = std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
let t0 = std::time::Instant::now();
close_gracefully(&s);
server_done.store(true, Ordering::SeqCst);
t0.elapsed()
});
let mut c = TcpStream::connect(addr).unwrap();
// one byte every 100 ms: each read returns well within its 500 ms timeout
for _ in 0..100 {
if done.load(Ordering::SeqCst) || c.write_all(b"x").is_err() {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
let drained = server.join().unwrap();
assert!(drained < DRAIN_TIME + Duration::from_secs(1), "drained for {drained:?}");
}
}
+39 -7
View File
@@ -3,7 +3,8 @@ use super::prefs::config_dir;
pub(crate) const HELP: &str = "\
lightcraft — photo library + raw developer
USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported)
USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported; a library's catalog.snap or
folder opens that library)
OPTIONS:
--library DIR open (or create) this library (env LIGHTCRAFT_LIBRARY; default: the last library opened, or
@@ -30,17 +31,48 @@ ENVIRONMENT:
/// The launch arguments' files and folders to import (absolute), and a notice for each one that
/// is not imported (see [`lightcraft_engine::import::launch_path`]; issue #374).
pub(crate) fn launch_imports(args: &[String]) -> (Vec<String>, Vec<String>) {
pub(crate) fn launch_imports(args: &[String]) -> LaunchArgs {
let cwd = std::env::current_dir().ok();
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
launch_imports_in(args, cwd.as_deref(), home.as_deref())
}
pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> (Vec<String>, Vec<String>) {
use lightcraft_engine::import::{LaunchPath, launch_path};
let (mut files, mut notices) = (Vec::new(), Vec::new());
/// The library a launch argument names, after `--library` (`flag`) and `LIGHTCRAFT_LIBRARY` (`env`):
/// the library to pass on as the flag, and whether the argument chose it (it is then remembered).
pub(crate) fn launch_library_choice(
flag: Option<std::path::PathBuf>,
env: Option<&std::path::PathBuf>,
argument: Option<std::path::PathBuf>,
) -> (Option<std::path::PathBuf>, bool) {
match (flag, env, argument) {
(Some(flag), _, _) => (Some(flag), false),
(None, None, Some(argument)) => (Some(argument), true),
_ => (None, false),
}
}
/// What the launch arguments ask for: files and folders to import, a library to open (a library's `catalog.snap`
/// or folder, double-clicked in the file manager), and a notice for each argument
/// left alone.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct LaunchArgs {
pub(crate) files: Vec<String>,
pub(crate) library: Option<std::path::PathBuf>,
pub(crate) notices: Vec<String>,
}
pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> LaunchArgs {
use lightcraft_engine::import::{LaunchPath, launch_deadline, launch_path_until};
let (mut files, mut notices, mut library) = (Vec::new(), Vec::new(), None);
// one deadline for every argument's library check: they all run before the window opens
let deadline = launch_deadline();
for a in args {
match launch_path(a, cwd, home, lightcraft_engine::devices::dcim_in) {
match launch_path_until(a, cwd, home, lightcraft_engine::devices::dcim_in, deadline) {
Some(LaunchPath::Library(dir)) if library.is_none() => library = Some(std::path::PathBuf::from(dir)),
Some(LaunchPath::Library(dir)) => {
log::warn!("one library at a time: not opening {dir} given at launch");
notices.push(format!("{dir} was not opened: LightCraft opens one library at a time. Open it with File ▸ Open Library…"));
}
Some(LaunchPath::Import(p)) => files.push(p),
Some(LaunchPath::Refused { path, why }) => {
log::warn!("not importing {path} given at launch: {why}");
@@ -50,7 +82,7 @@ pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>,
None => {}
}
}
(files, notices)
LaunchArgs { files, library, notices }
}
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
+40 -4
View File
@@ -55,7 +55,10 @@ use gpu_crash::{gpu_crash_check, gpu_lost_check_at, gpu_lost_marker_path, gpu_lo
use gpu_crash::{gpu_crash_check_at, gpu_crash_notice, window_wgpu_options};
#[cfg(test)]
use launch::launch_imports_in;
use launch::{HELP, control_port_from, launch_imports, log_dir, panic_log_path_with, startup_failed, stopped_text, stopped_while_running};
use launch::{
HELP, LaunchArgs, control_port_from, launch_imports, launch_library_choice, log_dir, panic_log_path_with, startup_failed, stopped_text,
stopped_while_running,
};
#[cfg(test)]
use platform::{explorer_select_arg, explorer_select_command, windows_open_url_command};
use prefs::{PrefsWriter, as_remembered, load_prefs, prefs_path};
@@ -79,6 +82,11 @@ fn app_icon() -> egui::IconData {
struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
// The transparency-capable DirectComposition window is a presentation workaround;
// translucent UI layers (disabled panels, modal dimming) must not reveal the desktop.
egui::Color32::from_rgb(12, 12, 12).to_normalized_gamma_f32()
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if let Some(m) = self.2.as_mut()
@@ -116,6 +124,12 @@ impl eframe::App for App {
if !self.0.shutdown(EXIT_WAIT) {
log::warn!("quit: background work was still running after {EXIT_WAIT:?}");
}
// macOS only: the process ends below without running destructors, and only the lock's
// `Drop` removes `catalog.lock.owner` (the OS frees the lock, not the note), so let go of
// the library's lock here, saved or not (we leave either way). Elsewhere eframe drops the
// app after this and the session's last writes (face data) still go out under the lock.
#[cfg(target_os = "macos")]
self.0.session.release_library_lock();
// macOS (#1331): end the process here, before eframe tears the window down, as Quit from
// the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's
// content view and restores its class on teardown; AppKit's Touch Bar support observes
@@ -192,7 +206,11 @@ fn main() -> eframe::Result {
}
// what the arguments name, resolved now: an empty or relative argument never becomes a drive
// root, and a whole drive or home folder is not walked (issue #374)
let (files, launch_notices) = launch_imports(&files);
let LaunchArgs { files, library: launch_library, notices: launch_notices } = launch_imports(&files);
// a library double-clicked (its catalog.snap or folder) is the one that opens, not the last one
// used; --library and LIGHTCRAFT_LIBRARY still win
let env_library: Option<std::path::PathBuf> = std::env::var_os("LIGHTCRAFT_LIBRARY").filter(|p| !p.is_empty()).map(Into::into);
let (library_dir, opened_by_argument) = launch_library_choice(library_dir, env_library.as_ref(), launch_library);
let (prefs, prefs_warning, keep_prefs_file) = load_prefs(in_memory);
// the saved language from the start, so a failed start is reported in it too
if let Some(ui) = &prefs {
@@ -203,7 +221,7 @@ fn main() -> eframe::Result {
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),
env_library,
prefs.as_ref().map(|u| &u.settings),
lightcraft_engine::library::default_dir(),
);
@@ -214,8 +232,11 @@ fn main() -> eframe::Result {
lightcraft_engine::gpu::set_enabled(gpu_on);
// the window's renderer: probed (Windows) and with a fallback chain, so a driver that can't
// build egui's pipeline never kills the start-up
let compose_window =
prefs.as_ref().map_or_else(|| lightcraft_ui_egui::state::AppSettings::default().compose_window, |ui| ui.settings.compose_window)
&& std::env::var_os("WGPU_BACKEND").is_none();
let win_files = std::sync::Arc::new(window_files(in_memory));
let window_gpu::Chosen { renderer, wgpu_options, which: window_renderer, notice: window_notice } = window_gpu::choose(&win_files);
let window_gpu::Chosen { renderer, wgpu_options, which: window_renderer, notice: window_notice } = window_gpu::choose(&win_files, compose_window);
win_files.arm(window_renderer);
let win_files_app = win_files.clone();
// the window came up: a failure after this is LightCraft stopping, not a start that failed
@@ -228,6 +249,7 @@ fn main() -> eframe::Result {
viewport: as_remembered(egui::ViewportBuilder::default().with_title("LightCraft"), opens_as)
.with_min_inner_size(lightcraft_ui_egui::window_place::MIN_SIZE)
.with_drag_and_drop(true)
.with_transparent(window_gpu::composes_window(compose_window, window_renderer))
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
@@ -295,6 +317,20 @@ fn main() -> eframe::Result {
keep_file: keep_prefs_file,
..Default::default()
};
// a library opened from its catalog file is the one in use from now on, as Open Library makes it
// (after the snapshot above, so the writer saves it)
if opened_by_argument
&& problem.is_none()
&& let Some(dir) = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.to_string_lossy().into_owned())
{
let settings = &mut app.ui.settings;
if settings.library_path != dir && !settings.library_path.is_empty() {
let previous = settings.library_path.clone();
lightcraft_ui_egui::panels::settings::remember_library(&mut settings.recent_libraries, &previous);
}
lightcraft_ui_egui::panels::settings::remember_library(&mut settings.recent_libraries, &dir);
settings.library_path = dir;
}
// after the snapshot above, so the writer saves the switched-off preference
if let Some(notice) = gpu_crash {
app.ui.settings.gpu = false;
+259 -54
View File
@@ -118,6 +118,74 @@ impl Item {
}
}
impl SyncRow for Item {
fn label(&self) -> &str {
&self.label
}
fn show_label(&mut self, label: String) {
match &self.handle {
Handle::Plain(h) => h.set_text(label.replace('&', "&&")),
Handle::Check(h) => h.set_text(label.replace('&', "&&")),
}
self.label = label;
}
fn enabled(&self) -> bool {
self.enabled
}
fn show_enabled(&mut self, enabled: bool) {
match &self.handle {
Handle::Plain(h) => h.set_enabled(enabled),
Handle::Check(h) => h.set_enabled(enabled),
}
self.enabled = enabled;
}
fn show_checked(&mut self, checked: bool) {
if let Handle::Check(h) = &self.handle {
// also resyncs after AppKit toggled it on click
if h.is_checked() != checked {
h.set_checked(checked);
}
self.checked = Some(checked);
}
}
}
/// What the per-frame sync needs of a native row, so it can be run on stand-ins without a
/// main-thread `muda::Menu` (as [`SwapTarget`] does for the swap).
trait SyncRow {
fn label(&self) -> &str;
fn show_label(&mut self, label: String);
fn enabled(&self) -> bool;
fn show_enabled(&mut self, enabled: bool);
/// Only a row that is a check item takes it.
fn show_checked(&mut self, checked: bool);
}
/// Puts each model row's live label, enabled and checked state on its own native row, found by
/// the row's native id (two rows may run the same command and params).
fn sync_rows<R: SyncRow>(nodes: &[MenuNode], items: &mut HashMap<String, R>, keymap: &lightcraft_ui_egui::shortcuts::Keymap) {
let mut rows = Vec::new();
native_rows(nodes, &mut RowIds::default(), &mut rows);
for (native_id, node) in rows {
let MenuNode::Item { id, params, label, shortcut, enabled, checked } = node else { continue };
let Some(it) = items.get_mut(&native_id) else { continue };
let (native_label, _) = native_item_presentation(keymap, id, params, label, shortcut.as_deref());
if it.label() != native_label {
it.show_label(native_label);
}
if it.enabled() != *enabled {
it.show_enabled(*enabled);
}
if let Some(c) = checked {
it.show_checked(*c);
}
}
}
/// 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<Accelerator>, want: Option<Accelerator>, native_call_worked: bool) -> Option<Accelerator> {
@@ -311,6 +379,50 @@ fn tidy_separators(nodes: Vec<MenuNode>) -> Vec<MenuNode> {
out
}
/// The model's rows of one menu as the native menu installs them: About, Settings and Quit live in
/// the app menu on macOS.
fn install_nodes(nodes: &[MenuNode]) -> Vec<MenuNode> {
let kept = nodes.iter().filter(|n| !matches!(n, MenuNode::Item { id, .. } if id == "app.about" || id == SETTINGS || id == QUIT));
tidy_separators(kept.cloned().collect())
}
/// Native (muda) ids, one per menu row. muda ids must be unique, but the model may hold the same
/// command and params twice (`dialog.export` is File ▸ Export… and Export with Preset ▸ Custom…;
/// `dialog.newAlbum` is in File and in Photo ▸ Add to Album), so a repeated key gets an occurrence
/// suffix. The first row keeps the plain [`MenuNode::key`]. Rows are numbered in model order, so
/// the install and the per-frame sync, which both walk the model in that order, agree.
#[derive(Default)]
struct RowIds {
seen: HashMap<String, usize>,
}
impl RowIds {
/// The row's native id, and whether an earlier row already has the same command and params.
fn next(&mut self, id: &str, params: &Value) -> (String, bool) {
let key = MenuNode::key(id, params);
let n = self.seen.entry(key.clone()).or_insert(0);
*n += 1;
if *n == 1 { (key, false) } else { (format!("{key}#{n}"), true) }
}
}
/// The key a row is installed with. A repeated row has none: AppKit would list one key twice, and
/// the first row of the command keeps it (a click on either row runs the command).
fn row_accelerator(native_key: Option<&str>, repeated: bool) -> Option<Accelerator> {
native_key.filter(|s| !repeated && !CONTEXTUAL.contains(s)).and_then(accelerator)
}
/// Every item of the model with its native id, in model order.
fn native_rows<'a>(nodes: &'a [MenuNode], ids: &mut RowIds, out: &mut Vec<(String, &'a MenuNode)>) {
for n in nodes {
match n {
MenuNode::Item { id, params, .. } => out.push((ids.next(id, params).0, n)),
MenuNode::Submenu { children, .. } => native_rows(children, ids, out),
MenuNode::Separator => {}
}
}
}
impl NativeMenu {
/// Build the menu bar and install it as the application menu (main thread, after launch).
pub fn install(app: &mut LightcraftApp, ctx: &egui::Context) -> NativeMenu {
@@ -379,6 +491,8 @@ impl NativeMenu {
}
let _ = self.menu.append(&app_menu);
let mut ids = RowIds::default();
let mut help_menu = None;
for (title, nodes) in &bar {
let sub = Submenu::new(label_text(title), true);
if title == "Window" {
@@ -388,16 +502,10 @@ impl NativeMenu {
&PredefinedMenuItem::separator(),
]);
}
// About and Settings live in the app menu on macOS
let nodes: Vec<MenuNode> = nodes
.iter()
.filter(|n| !matches!(n, MenuNode::Item { id, .. } if id == "app.about" || id == SETTINGS || id == QUIT))
.cloned()
.collect();
let nodes = tidy_separators(nodes);
let nodes = install_nodes(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");
self.append_nodes(&sub, &nodes, &app.ui.settings.keymap, title != "Help", &mut ids);
if title == "File" {
// ⌘W, the system's own item
let _ = sub.append_items(&[
@@ -413,11 +521,16 @@ impl NativeMenu {
sub.set_as_windows_menu_for_nsapp();
}
if title == "Help" {
sub.set_as_help_menu_for_nsapp();
help_menu = Some(sub.clone());
}
let _ = self.menu.append(&sub);
}
self.menu.init_for_nsapp();
// muda finds the submenu through the main menu installed just above; asked earlier it does
// nothing, and AppKit never learns which menu is the Help menu
if let Some(help) = help_menu {
help.set_as_help_menu_for_nsapp();
}
self.text_focus = false;
self.capturing = false;
self.accelerators_pending = false;
@@ -426,7 +539,7 @@ impl NativeMenu {
/// 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) {
fn append_nodes(&mut self, sub: &Submenu, nodes: &[MenuNode], keymap: &lightcraft_ui_egui::shortcuts::Keymap, swappable: bool, ids: &mut RowIds) {
for n in nodes {
match n {
MenuNode::Separator => {
@@ -434,16 +547,13 @@ impl NativeMenu {
}
MenuNode::Submenu { label, children } => {
let s = Submenu::new(label_text(label), true);
self.append_nodes(&s, children, keymap, swappable);
self.append_nodes(&s, children, keymap, swappable, ids);
let _ = sub.append(&s);
}
MenuNode::Item { id, params, label, shortcut, enabled, checked } => {
let key = MenuNode::key(id, params);
if self.items.contains_key(&key) {
continue; // muda ids must be unique
}
let (key, repeated) = ids.next(id, params);
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 accel = row_accelerator(native_key, repeated);
let handle = match checked {
Some(c) => {
let it = CheckMenuItem::with_id(key.clone(), native_label.replace('&', "&&"), *enabled, *c, accel);
@@ -497,9 +607,7 @@ impl NativeMenu {
// 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 {
let (cmd, params) = if key == QUIT || key == "app.about" || key == SETTINGS {
(key, serde_json::json!({}))
} else if let Some(it) = self.items.get(&key) {
(it.cmd.clone(), it.params.clone())
@@ -516,41 +624,10 @@ impl NativeMenu {
// to, so the sync below runs in this same frame and no key reaches the menu in between)
self.rebuild(app);
}
/// Synchronize live labels and states; accelerator ownership changes already triggered a rebuild.
fn walk(nodes: &[MenuNode], items: &mut HashMap<String, Item>, keymap: &lightcraft_ui_egui::shortcuts::Keymap) {
for n in nodes {
match n {
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 };
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(native_label.replace('&', "&&")),
Handle::Check(h) => h.set_text(native_label.replace('&', "&&")),
}
it.label = native_label;
}
if it.enabled != *enabled {
match &it.handle {
Handle::Plain(h) => h.set_enabled(*enabled),
Handle::Check(h) => h.set_enabled(*enabled),
}
it.enabled = *enabled;
}
if let (Handle::Check(h), Some(c)) = (&it.handle, checked) {
// also resyncs after AppKit toggled it on click
if h.is_checked() != *c {
h.set_checked(*c);
}
it.checked = Some(*c);
}
}
MenuNode::Separator => {}
}
}
}
walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::<Vec<_>>(), &mut self.items, &app.ui.settings.keymap);
// Synchronize live labels and states row by row (accelerator ownership changes already
// triggered a rebuild).
let all: Vec<MenuNode> = bar.into_iter().flat_map(|(_, v)| v).collect();
sync_rows(&all, &mut self.items, &app.ui.settings.keymap);
let focus = ctx.egui_wants_keyboard_input();
let capturing = app.recording_shortcut.is_some();
@@ -613,6 +690,134 @@ mod tests {
set_language(Locale::En);
}
/// Every row of the model gets its own native row and keeps its own label, and a click on a
/// native id runs that row's command (two rows may share a command and params).
#[test]
fn rows_sharing_a_command_get_their_own_native_ids_and_labels() {
let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default());
let bar = menu_bar(&app);
let all: Vec<MenuNode> = bar.iter().flat_map(|(_, v)| v.clone()).collect();
let mut rows = Vec::new();
native_rows(&all, &mut RowIds::default(), &mut rows);
fn count(n: &[MenuNode]) -> usize {
n.iter()
.map(|x| match x {
MenuNode::Item { .. } => 1,
MenuNode::Submenu { children, .. } => count(children),
MenuNode::Separator => 0,
})
.sum()
}
assert_eq!(rows.len(), count(&all));
let ids: HashSet<&str> = rows.iter().map(|(id, _)| id.as_str()).collect();
assert_eq!(ids.len(), rows.len(), "a native id per row");
// The install walks each menu as `install_nodes` leaves it, the per-frame sync walks the whole
// bar: a row the menu has must get the same id, so the same node (label, command, params),
// from both, and a click on its id runs that row's command.
let mut installed = Vec::new();
let mut install_ids = RowIds::default();
let menus: Vec<Vec<MenuNode>> = bar.iter().map(|(_, nodes)| install_nodes(nodes)).collect();
for nodes in &menus {
native_rows(nodes, &mut install_ids, &mut installed);
}
let synced: HashMap<&str, &MenuNode> = rows.iter().map(|(id, n)| (id.as_str(), *n)).collect();
for (nid, n) in &installed {
assert_eq!(synced.get(nid.as_str()), Some(n), "{nid}");
}
for (cmd, labels) in [("dialog.export", ["Export…", "Custom…"]), ("dialog.newAlbum", ["New Album…", "New Album…"])] {
let own: Vec<(&str, &str)> = installed
.iter()
.filter_map(|(nid, n)| match n {
MenuNode::Item { id, label, params, .. } if id == cmd && params.is_null() => Some((nid.as_str(), label.as_str())),
_ => None,
})
.collect();
assert_eq!(own.len(), 2, "{cmd} is in two menus");
assert_ne!(own[0].0, own[1].0, "{cmd}: one native id per row");
assert_eq!([own[0].1, own[1].1], labels, "{cmd}: each row keeps its label");
}
// A repeated row is installed without its key (AppKit would list one key twice).
assert_eq!(row_accelerator(Some("G"), false), accelerator("G"));
assert_eq!(row_accelerator(Some("G"), true), None);
let mut ids = RowIds::default();
assert_eq!(ids.next("view.layoutImage", &Value::Null), ("view.layoutImage".to_string(), false));
assert_eq!(ids.next("view.layoutImage", &Value::Null), ("view.layoutImage#2".to_string(), true));
}
/// A native row's shown state, to run the per-frame sync without a main-thread `muda::Menu`.
#[derive(Debug, PartialEq)]
struct FakeRow {
label: String,
enabled: bool,
checked: Option<bool>,
}
impl SyncRow for FakeRow {
fn label(&self) -> &str {
&self.label
}
fn show_label(&mut self, label: String) {
self.label = label;
}
fn enabled(&self) -> bool {
self.enabled
}
fn show_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
}
fn show_checked(&mut self, checked: bool) {
self.checked = Some(checked);
}
}
/// Two rows with the same command and params keep their own label, enabled and checked state
/// when the model changes (the sync once wrote the last row's state onto the first).
#[test]
fn the_sync_updates_rows_sharing_a_command_independently() {
use lightcraft_ui_egui::i18n::{Locale, set_language};
set_language(Locale::En);
let keymap = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()).ui.settings.keymap.clone();
let item = |cmd: &str, label: &str, enabled: bool, checked: Option<bool>| MenuNode::Item {
id: cmd.into(),
params: Value::Null,
label: label.into(),
shortcut: None,
enabled,
checked,
};
let model = |a: (&str, bool, Option<bool>), b: (&str, bool, Option<bool>), c: (&str, bool, Option<bool>), d: (&str, bool, Option<bool>)| {
vec![
item("dialog.export", a.0, a.1, a.2),
MenuNode::Separator,
MenuNode::Submenu { label: "Export with Preset".into(), children: vec![item("dialog.export", b.0, b.1, b.2)] },
item("view.toggle", c.0, c.1, c.2),
MenuNode::Submenu { label: "More".into(), children: vec![item("view.toggle", d.0, d.1, d.2)] },
]
};
// what the native rows show after the install
let installed = model(("Export…", true, None), ("Custom…", true, None), ("Show", true, Some(false)), ("Show", true, Some(false)));
let mut rows = Vec::new();
native_rows(&installed, &mut RowIds::default(), &mut rows);
let mut items: HashMap<String, FakeRow> = rows
.iter()
.filter_map(|(nid, n)| match n {
MenuNode::Item { label, enabled, checked, .. } => {
Some((nid.clone(), FakeRow { label: label.clone(), enabled: *enabled, checked: *checked }))
}
_ => None,
})
.collect();
assert_eq!(items.len(), 4, "a native row for each of the four rows");
// the model changes: each row of a pair gets a different state
let live = model(("Export…", false, None), ("Custom…", true, None), ("Show", true, Some(true)), ("Hide", false, Some(false)));
sync_rows(&live, &mut items, &keymap);
let shown: Vec<&FakeRow> = rows.iter().map(|(nid, _)| &items[nid]).collect();
let row = |label: &str, enabled: bool, checked: Option<bool>| FakeRow { label: label.into(), enabled, checked };
assert_eq!(shown[0], &row("Export…", false, None), "File ▸ Export… keeps its label and is disabled alone");
assert_eq!(shown[1], &row("Custom…", true, None), "Custom… stays enabled and keeps its label");
assert_eq!(shown[2], &row("Show", true, Some(true)), "the first toggle is checked alone");
assert_eq!(shown[3], &row("Hide", false, Some(false)), "the second toggle has its own label and state");
}
#[test]
fn accelerators_yield_to_text_focus_and_shortcut_recording() {
let g = accelerator("G");
+10 -3
View File
@@ -253,7 +253,7 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
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),
Launch::Open { dir, remembered, .. } => open_library_session(in_memory, dir.clone(), *remembered, 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));
@@ -267,7 +267,9 @@ pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) ->
/// If the library can't be opened the session is empty and in memory — never seeded with the
/// demo photos, never written anywhere — and the problem is returned: the window then says so
/// and offers Try Again / Choose Another Library… / Continue Without Saving / Quit (issue #100).
fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
/// So is a `remembered` library (the one last opened) that isn't there any more: opening would
/// make a new, empty one in its place, e.g. on an unmounted drive's path (issue #3239).
fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, remembered: bool, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
if in_memory {
return (if seed_demo { Session::with_demo() } else { Session::new() }.with_fs().with_default_denoise_models().with_system_clock(), None);
}
@@ -276,9 +278,14 @@ fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_d
log::warn!("no library location (set --library or LIGHTCRAFT_LIBRARY)");
return (unopened(), Some(LibraryProblem::new("", "There is no home folder to keep the library in. Choose a folder for it.")));
};
if remembered && let Some(why) = lightcraft_ui_egui::panels::library_problem::missing_library_reason(&dir) {
log::error!("library {} can't be opened: {why}", dir.display());
// Try Again must not make one there either (an empty mount point, issue #3239)
return (unopened(), Some(LibraryProblem { existing_only: true, ..LibraryProblem::new(dir.to_string_lossy(), why) }));
}
let t0 = std::time::Instant::now();
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
match s.open_library(&dir, seed_demo) {
match s.open_library(&dir, seed_demo && !remembered) {
Ok(r) => {
let (replayed, torn) = (r.replayed, r.torn_bytes);
log::info!(
+161 -3
View File
@@ -1,5 +1,20 @@
use super::*;
#[test]
fn desktop_clear_color_stays_opaque_with_a_modal_open() {
let mut app = App(
LightcraftApp::new(Session::new(), Services::default()),
PrefsWriter::default(),
#[cfg(target_os = "macos")]
None,
);
app.0.run("app.settings", serde_json::json!({})).unwrap();
assert!(app.0.ui.dialog.is_some());
for visuals in [egui::Visuals::dark(), egui::Visuals::light()] {
assert_eq!(eframe::App::clear_color(&app, &visuals)[3], 1.0);
}
}
fn dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-app-prefs-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
@@ -14,22 +29,62 @@ fn launch_arguments_never_walk_a_drive_or_the_home_folder() {
let home = dir("launch");
std::fs::create_dir_all(home.join("Trip")).unwrap();
let args: Vec<String> = ["", " ", ".", "Trip", &home.to_string_lossy()].iter().map(|s| s.to_string()).collect();
let (files, notices) = launch_imports_in(&args, Some(&home), Some(&home));
let LaunchArgs { files, notices, library } = launch_imports_in(&args, Some(&home), Some(&home));
assert_eq!(library, None);
assert_eq!(files, [home.join("Trip").to_string_lossy().to_string()]);
assert_eq!(notices.len(), 2, "{notices:?}");
assert!(notices.iter().all(|n| n.contains("was not imported")), "{notices:?}");
// the working folder is a drive root (a launcher's choice): `.` is never the whole drive
let root = home.ancestors().last().unwrap().to_path_buf();
let (files, notices) = launch_imports_in(&[".".to_string()], Some(&root), None);
let LaunchArgs { files, notices, .. } = launch_imports_in(&[".".to_string()], Some(&root), None);
assert!(files.iter().all(|f| f.ends_with("DCIM")) && files.len() + notices.len() == 1, "{files:?} {notices:?}");
let _ = std::fs::remove_dir_all(&home);
}
/// `--library` and `LIGHTCRAFT_LIBRARY` win over a library given as an argument, which is
/// then not remembered either.
#[test]
fn the_library_flag_and_variable_win_over_a_library_argument() {
use std::path::PathBuf;
let (flag, env, arg) = (PathBuf::from("flag"), PathBuf::from("env"), PathBuf::from("arg"));
assert_eq!(launch_library_choice(Some(flag.clone()), Some(&env), Some(arg.clone())), (Some(flag.clone()), false));
assert_eq!(launch_library_choice(None, Some(&env), Some(arg.clone())), (None, false), "the variable is passed on as itself");
assert_eq!(launch_library_choice(None, None, Some(arg.clone())), (Some(arg), true));
assert_eq!(launch_library_choice(None, None, None), (None, false));
assert_eq!(launch_library_choice(Some(flag.clone()), None, None), (Some(flag), false));
}
/// A library's catalog.snap (double-clicked in Explorer) or its folder given at
/// launch opens that library and is never imported as photos; a second library is left with a notice.
#[test]
fn a_librarys_catalog_given_at_launch_opens_that_library() {
let home = dir("launch-library");
let lib = home.join("Wedding LC");
let mut s = lightcraft_engine::Session::new().with_fs();
s.open_library(&lib, false).unwrap();
s.close_library().unwrap();
let snap = lib.join("catalog.snap");
assert!(snap.is_file(), "a library keeps its catalog.snap");
let other = home.join("Other LC");
let mut s = lightcraft_engine::Session::new().with_fs();
s.open_library(&other, false).unwrap();
s.close_library().unwrap();
for arg in [snap.to_string_lossy().to_string(), lib.to_string_lossy().to_string(), "Wedding LC/catalog.snap".to_string()] {
let got = launch_imports_in(std::slice::from_ref(&arg), Some(&home), Some(&home.join("elsewhere")));
assert_eq!(got.library.as_deref(), Some(lib.as_path()), "{arg}");
assert!(got.files.is_empty() && got.notices.is_empty(), "{arg}: never imported: {got:?}");
}
let got = launch_imports_in(&[snap.to_string_lossy().to_string(), other.to_string_lossy().to_string()], Some(&home), None);
assert_eq!(got.library.as_deref(), Some(lib.as_path()), "the first one");
assert_eq!(got.notices.len(), 1, "{got:?}");
let _ = std::fs::remove_dir_all(&home);
}
/// Issue #236: the window answers control requests on its UI thread, so the desktop session
/// 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, &Launch::Open { dir: None, alt_asks: false }, false);
let (s, problem) = open_session(true, &Launch::Open { dir: None, alt_asks: false, remembered: false }, false);
assert!(problem.is_none());
assert!(s.apple_photos_background);
assert!(!lightcraft_engine::Session::new().apple_photos_background);
@@ -63,6 +118,74 @@ fn asking_at_launch_opens_nothing_and_still_saves_the_settings() {
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #3239: the library remembered in Settings whose folder is missing at launch (a disk or
/// network share not connected) is reported in the library problem window. Nothing is created
/// there (not the folder, not its parents) and no demo photos are added.
#[test]
fn a_remembered_library_missing_at_launch_is_reported_not_made_anew() {
let d = dir("missing-library");
let gone = d.join("gone");
let lib = gone.join("Lib");
let launch = Launch::Open { dir: Some(lib.clone()), alt_asks: true, remembered: true };
let (s, problem) = open_session(false, &launch, true);
let problem = problem.expect("the missing library is reported");
assert_eq!(problem.path, lib.to_string_lossy());
assert!(problem.can_retry, "Try Again once the drive is back");
assert!(problem.existing_only, "Try Again makes no library there either");
assert!(!gone.exists(), "nothing is created where the library was");
assert!(s.library.is_none() && s.catalog.is_empty(), "no library, no demo photos");
// a remembered folder that is there but holds no library is reported too
std::fs::create_dir_all(&lib).unwrap();
let (s, problem) = open_session(false, &launch, true);
assert!(problem.as_ref().is_some_and(|p| p.existing_only) && s.library.is_none() && s.catalog.is_empty(), "{problem:?}");
assert!(!lightcraft_engine::library::is_library(&lib), "nothing written in it");
// the default location (or --library) is still made when it's missing, with the demo photos
let fresh = d.join("fresh").join("Lib");
let (s, problem) = open_session(false, &Launch::Open { dir: Some(fresh.clone()), alt_asks: true, remembered: false }, true);
assert!(problem.is_none() && s.library.is_some() && !s.catalog.is_empty(), "{problem:?}");
assert!(lightcraft_engine::library::is_library(&fresh));
drop(s);
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #3239: a remembered library whose folder can't be looked into (no permission) is
/// reported as unreadable at launch, not as gone, and nothing is opened or written there.
#[cfg(unix)]
#[test]
fn a_remembered_library_it_may_not_read_at_launch_says_so() {
use std::os::unix::fs::PermissionsExt;
let d = dir("denied-library");
let lib = d.join("Lib");
let mut s = lightcraft_engine::Session::new().with_fs();
s.open_library(&lib, false).unwrap();
s.close_library().unwrap();
drop(s);
let names = |dir: &std::path::Path| {
let mut names: Vec<_> = std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name()).collect();
names.sort();
names
};
let before = names(&lib);
std::fs::set_permissions(&lib, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::read_dir(&lib).is_ok() {
std::fs::set_permissions(&lib, std::fs::Permissions::from_mode(0o755)).unwrap();
let _ = std::fs::remove_dir_all(&d);
lightcraft_testkit::skip!(System, "running as root: a folder with mode 000 is still readable");
return;
}
let launch = Launch::Open { dir: Some(lib.clone()), alt_asks: true, remembered: true };
let (s, problem) = open_session(false, &launch, true);
std::fs::set_permissions(&lib, std::fs::Permissions::from_mode(0o755)).unwrap();
let problem = problem.expect("the unreadable library is reported");
assert!(problem.error.starts_with("This folder can't be read:"), "{}", problem.error);
assert!(problem.error.to_lowercase().contains("permission denied"), "{}", problem.error);
assert!(problem.existing_only, "Try Again makes no library there either");
assert!(s.library.is_none() && s.catalog.is_empty(), "no library, no demo photos");
assert_eq!(names(&lib), before, "nothing written there");
drop(s);
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]
@@ -462,3 +585,38 @@ fn on_exit_ends_the_process_on_macos() {
assert!(stdout.contains("calling on_exit"), "the child didn't run the test: {stdout}");
assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}");
}
/// Quitting leaves no `catalog.lock.owner` behind, though the process ends without running
/// destructors (macOS): `on_exit` releases the library's lock itself. The child opens a library
/// and calls `on_exit` (on macOS that ends it); the parent looks at the folder afterwards. Other
/// systems drop the app after `on_exit`, which removes the note anyway.
#[test]
fn on_exit_removes_the_lock_owner_note() {
if let Some(dir) = std::env::var_os("LIGHTCRAFT_TEST_LOCK_DIR") {
let mut session = lightcraft_engine::Session::new();
session.open_library(&dir, false).unwrap();
let mut app = App(
LightcraftApp::new(session, Services::default()),
PrefsWriter::default(),
#[cfg(target_os = "macos")]
None,
);
eframe::App::on_exit(&mut app, None);
return;
}
let dir = std::env::temp_dir().join(format!("lc-app-lock-owner-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::on_exit_removes_the_lock_owner_note", "--nocapture"])
.env("LIGHTCRAFT_TEST_LOCK_DIR", &dir)
.env("LIGHTCRAFT_NO_PREFS", "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{stdout}");
assert!(dir.join("catalog.snap").exists(), "the child didn't open and save the library: {stdout}");
assert!(!dir.join("catalog.lock.owner").exists(), "the owner note was left behind");
assert!(lightcraft_engine::Session::new().open_library(&dir, false).is_ok(), "the library is still locked");
let _ = std::fs::remove_dir_all(&dir);
}
+63 -7
View File
@@ -85,7 +85,7 @@ impl Files {
}
/// The renderer for this start: see the module docs.
pub fn choose(files: &Files) -> Chosen {
pub fn choose(files: &Files, compose_window: bool) -> Chosen {
let forced =
backend::forced_window_renderer(std::env::var("LIGHTCRAFT_GPU_BACKEND").ok().as_deref(), std::env::var("WGPU_BACKEND").ok().as_deref());
let failed = files.take_failed();
@@ -95,7 +95,7 @@ pub fn choose(files: &Files) -> Chosen {
let order = backend::window_renderer_order(forced, remembered, failed, os, compiled, true);
let mut problems = Vec::new();
let chosen = if cfg!(windows) {
pick_probed(&order, &mut problems)
pick_probed(&order, &mut problems, compose_window)
} else if forced == Some(WindowRenderer::Glow) || (forced.is_none() && failed.is_some_and(|f| f != WindowRenderer::Glow)) {
// elsewhere eframe's own wgpu set-up stays the default; glow after a failed start
Some((WindowRenderer::Glow, None))
@@ -142,8 +142,13 @@ fn user_notice(failed: Option<WindowRenderer>, forced: Option<WindowRenderer>, p
}
/// eframe's defaults with the app's backends and DX12 shader compiler (issues #136, #471).
///
/// Taken from `NativeOptions::default()`, whose surface is egui-wgpu's `LOW_LATENCY` (one frame in
/// flight; two drawables on Metal). `WgpuConfiguration::default()` is `HIGH_THROUGHPUT` instead (two
/// frames queued, three drawables): every drag, slider and crop handle reached the screen a frame
/// later than eframe's default. Live window resizing still gets three drawables from egui-wgpu.
pub fn base_options() -> WgpuConfiguration {
let mut c = WgpuConfiguration::default();
let mut c = eframe::NativeOptions::default().wgpu_options;
if let WgpuSetup::CreateNew(n) = &mut c.wgpu_setup {
n.instance_descriptor.backends = backend::window_backends();
n.instance_descriptor.backend_options = backend::backend_options();
@@ -154,12 +159,12 @@ pub fn base_options() -> WgpuConfiguration {
}
/// The first renderer of `order` that probes cleanly (glow is taken without a probe).
fn pick_probed(order: &[WindowRenderer], problems: &mut Vec<String>) -> Option<(WindowRenderer, Option<WgpuSetupExisting>)> {
fn pick_probed(order: &[WindowRenderer], problems: &mut Vec<String>, compose_window: bool) -> Option<(WindowRenderer, Option<WgpuSetupExisting>)> {
for &r in order {
match r {
WindowRenderer::Glow => return Some((r, None)),
WindowRenderer::Wgpu(b) => {
let probed = std::panic::catch_unwind(|| probe(b)).unwrap_or_else(|_| Err("panicked".into()));
let probed = std::panic::catch_unwind(|| probe(b, compose_window)).unwrap_or_else(|_| Err("panicked".into()));
match probed {
Ok(e) => return Some((r, Some(e))),
Err(e) => {
@@ -174,11 +179,11 @@ fn pick_probed(order: &[WindowRenderer], problems: &mut Vec<String>) -> Option<(
}
/// Create a device on `backends` and build egui's pipeline on it; any wgpu error is returned.
fn probe(backends: Backends) -> Result<WgpuSetupExisting, String> {
fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting, String> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends,
flags: backend::instance_flags_from_env(wgpu::InstanceFlags::from_build_config().with_env()),
backend_options: backend::backend_options(),
backend_options: presentation_options(backends, compose_window),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: None,
});
@@ -242,6 +247,22 @@ pub fn relaunch_after_failure(files: &Files) -> bool {
.is_ok()
}
/// Only DX12 windows use the compositor; fallback renderers retain their normal presentation.
/// Adapted from kmnkv1's PhotoCraft PR: https://github.com/storytold/photocraft/pull/7035.
pub fn composes_window(enabled: bool, renderer: WindowRenderer) -> bool {
cfg!(target_os = "windows") && enabled && renderer == WindowRenderer::Wgpu(Backends::DX12)
}
/// Select DirectComposition for opted-in Windows DX12 windows, preserving
/// the default presentation options for other renderers.
fn presentation_options(backends: Backends, enabled: bool) -> wgpu::BackendOptions {
let mut options = backend::backend_options();
if composes_window(enabled, WindowRenderer::Wgpu(backends)) {
options.dx12.presentation_system = wgpu::Dx12SwapchainKind::DxgiFromVisual;
}
options
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
@@ -290,6 +311,23 @@ mod tests {
assert!(died.contains("last time") && !died.contains("Validation Error"), "{died}");
}
/// The window keeps eframe's low-latency surface: one frame queued (two Metal drawables), not
/// the high-throughput `WgpuConfiguration::default()`, which held input a frame longer. The
/// probed (Windows) and forced-backend configurations are built on the same options.
#[test]
fn window_surface_keeps_one_frame_in_flight() {
let surface = base_options().surface;
assert_eq!(surface, eframe::NativeOptions::default().wgpu_options.surface);
assert_eq!(surface, eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
assert_eq!(surface.desired_maximum_frame_latency, Some(1));
assert_eq!(surface.present_mode, wgpu::PresentMode::AutoVsync);
assert_ne!(surface, WgpuConfiguration::default().surface, "egui-wgpu's own default is the high-throughput one");
// what `main` hands eframe (on Windows `choose` probes the adapters first; not here)
if !cfg!(windows) {
assert_eq!(choose(&Files::new(None), false).wgpu_options.surface, surface);
}
}
/// 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]
@@ -334,4 +372,22 @@ mod tests {
// outside a scope: logged by our handler, not a panic
let _ = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl("not wgsl".into()) });
}
/// The workaround is opt-in and changes presentation only for Windows DX12.
#[test]
fn composition_only_changes_windows_dx12_presentation() {
let legacy: lightcraft_ui_egui::state::AppSettings = serde_json::from_str("{}").unwrap();
assert!(!legacy.compose_window, "existing settings keep the workaround off until opted in");
assert!(!lightcraft_ui_egui::state::AppSettings::default().compose_window);
let enabled: lightcraft_ui_egui::state::AppSettings = serde_json::from_str(r#"{"composeWindow":true}"#).unwrap();
let saved = serde_json::to_value(&enabled).unwrap();
assert_eq!(saved["composeWindow"], true);
for backend in [Backends::DX12, Backends::VULKAN, Backends::GL] {
let wanted = cfg!(target_os = "windows") && backend == Backends::DX12;
assert_eq!(composes_window(true, WindowRenderer::Wgpu(backend)), wanted);
assert_eq!(presentation_options(backend, true).dx12.presentation_system == wgpu::Dx12SwapchainKind::DxgiFromVisual, wanted);
assert!(!composes_window(false, WindowRenderer::Wgpu(backend)));
}
assert!(!composes_window(true, WindowRenderer::Glow));
}
}
+1 -1
View File
@@ -53,4 +53,4 @@ Notes
- CJK fonts (BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC) are not in this repository. They live in
[storytold/craft-fonts](https://github.com/storytold/craft-fonts), with their licences and attribution in its
`ATTRIBUTION.md`, and are embedded only in builds made with the optional `CRAFT_FONTS_DIR` build input (all official
releases). Never commit font files here; add new fonts to craft-fonts (craftrules `standards/fonts.md`).
releases). Never commit font files here; add new fonts to craft-fonts.
+2 -3
View File
@@ -20,9 +20,8 @@ Windows and Linux files use the full-bleed tile so the lynx reads at 16-48 px.
## Provenance
The owner's original drawing, made in ArtCraft (2880 px, keyed to the three colours), vectorised with
craftrules `assets/logo-options/_tools/vectorize_tile.py`. The source drawing stays in craftrules at
`assets/app-icons/lightcraft/source.png`; `lightcraft.svg` here is the canonical artwork. Licence:
The owner's original drawing, made in ArtCraft (2880 px, keyed to the three colours) and
vectorised. `lightcraft.svg` here is the canonical artwork. Licence:
`LICENSE.txt` (MIT OR Apache-2.0, like the repo).
## Files
+10 -5
View File
@@ -1,13 +1,10 @@
# Contributor names for the About window (craftrules standards/contributors.md).
# Contributor names for the About window.
#
# Everyone who contributes is credited by GitHub username automatically. Anything more is up to
# you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a
# maintainer may add a person only when that person asked, recording where in consent_source.
#
# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \
# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name]
#
# Or copy this block, replacing your-github-username (every field is optional):
# Copy this block, replacing your-github-username (every field is optional):
#
# [people.your-github-username]
# real_name = "Your Name" # shown when the viewer picks "Real name"
@@ -75,5 +72,13 @@ sync_github_name = true
real_name = "Robert Lee"
sync_github_name = true
[people.samuelili]
real_name = "Samuel Li"
sync_github_name = true
[people.dylanmtaylor]
sync_github_name = true
[people.Peaperfish]
real_name = "Yule Wang"
display_name = "Brian Wang"
+1
View File
@@ -24,6 +24,7 @@ web-time = { workspace = true }
winapi-util = { workspace = true }
[dev-dependencies]
dhat = { workspace = true }
lightcraft-geom = { workspace = true }
lightcraft-testkit = { workspace = true }
proptest = { workspace = true }
+14 -1
View File
@@ -49,7 +49,12 @@ pub fn weekday(iso: &str) -> Option<&'static str> {
pub fn shift_iso(iso: &str, secs: i64) -> Option<String> {
let iso = iso.trim();
let tail = iso.get(tail_start(iso)?..)?;
let t = iso_seconds(iso)?.checked_add(secs)?;
let base = iso_seconds(iso)?;
// reject impossible dates that the arithmetic silently rolls over (2026-02-30)
if civil(base).get(..10) != iso.get(..10) {
return None;
}
let t = base.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;
@@ -295,6 +300,14 @@ mod tests {
assert_eq!(normalize_iso("2026-02-30"), None);
}
#[test]
fn shift_refuses_impossible_dates() {
assert_eq!(shift_iso("2026-02-30T10:00:00", 60), None);
assert_eq!(shift_iso("2026-02-29T10:00:00", 0), None);
assert_eq!(shift_iso("2026-04-31T10:00:00", 0), None);
assert_eq!(shift_iso("2024-02-29T10:00:00", 0).as_deref(), Some("2024-02-29T10:00:00"));
}
#[test]
fn shift_keeps_the_zone_of_a_time_without_seconds() {
assert_eq!(shift_iso("2026-01-01T10:00+02:00", 3600).as_deref(), Some("2026-01-01T11:00:00+02:00"));
+63 -1
View File
@@ -43,6 +43,33 @@ pub fn reparent(k: &str, from: &str, to: &str) -> String {
std::iter::once(to).filter(|t| !t.is_empty()).chain(rest).collect::<Vec<_>>().join("|")
}
/// A photo's keywords as a sidecar writes them: the two lists [`to_file`] fills.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FileKeywords {
/// For `dc:subject`: every level of every keyword, each once.
pub flat: Vec<String>,
/// For `lr:hierarchicalSubject`: every keyword as its path, when any keyword has levels;
/// empty otherwise, so a library without hierarchy doesn't gain the property.
pub hierarchical: Vec<String>,
}
/// A photo's keywords as a sidecar writes them, the inverse of [`from_file`]. `dc:subject` is the
/// flat list other applications search, so it gets names (`travel`, `Italy`, `Rome`), never paths,
/// as Lightroom Classic and darktable write it; the paths go to `lr:hierarchicalSubject`. Unlike
/// [`Catalog::export_keywords`] it applies no export options (a sidecar is the photo's own record,
/// not an export): no keyword is left out and no synonym added, so [`from_file`] reads the pair
/// back as the same keywords. When any keyword has levels, every keyword is listed in
/// `hierarchical`, the flat ones too: a flat `Rome` beside `travel|Italy|Rome` would otherwise be
/// taken for a level of the path on the way back.
pub fn to_file(keywords: &[String]) -> FileKeywords {
let mut paths: Vec<String> = keywords.iter().map(|k| clean(k)).collect();
dedupe(&mut paths);
let mut flat: Vec<String> = paths.iter().flat_map(|p| p.split(SEP).map(str::to_string)).collect();
dedupe(&mut flat);
let hierarchical = if paths.iter().any(|p| p.contains(SEP)) { paths } else { Vec::new() };
FileKeywords { flat, hierarchical }
}
/// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, then the
/// names of `dc:subject` that aren't levels of those paths (Lightroom Classic writes each keyword's
/// name, its parents' and synonyms flat besides its path). Each once, cleaned.
@@ -192,6 +219,10 @@ pub struct KeywordInfo {
/// most, see [`Catalog::default_keyword_parent`].
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub new_keywords_inside: bool,
/// Part of the keyword shortcut (Set Keyword Shortcut), which ⇧K adds to or removes from the
/// selected photos: see [`Catalog::keyword_shortcut`].
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub keyword_shortcut: bool,
}
fn yes() -> bool {
@@ -207,6 +238,7 @@ impl Default for KeywordInfo {
export_synonyms: true,
person: false,
new_keywords_inside: false,
keyword_shortcut: false,
}
}
}
@@ -369,6 +401,7 @@ impl Catalog {
match list.get_mut(&path.to_lowercase()) {
Some(there) => {
there.info.new_keywords_inside |= l.info.new_keywords_inside;
there.info.keyword_shortcut |= l.info.keyword_shortcut;
for s in l.info.synonyms {
if !there.info.synonyms.iter().any(|x| same(x, &s)) {
there.info.synonyms.push(s);
@@ -580,7 +613,13 @@ impl Catalog {
continue;
}
if !known.contains_key(&key) {
list.insert(key.clone(), ListedKeyword { path: path.clone(), info: KeywordInfo { new_keywords_inside: false, ..info.clone() } });
list.insert(
key.clone(),
ListedKeyword {
path: path.clone(),
info: KeywordInfo { new_keywords_inside: false, keyword_shortcut: false, ..info.clone() },
},
);
// it and its parents are the library's now: what follows spells them so
let levels: Vec<&str> = path.split(SEP).collect();
for i in 0..levels.len() {
@@ -666,6 +705,29 @@ impl Catalog {
})
}
/// The keyword shortcut's keywords (Set Keyword Shortcut), in the keyword list's order.
pub fn keyword_shortcut(&self) -> Vec<String> {
self.keyword_list.values().filter(|l| l.info.keyword_shortcut).map(|l| l.path.clone()).collect()
}
/// Make `keywords` the keyword shortcut, in one batch. A keyword the library doesn't have yet is
/// listed, and the others keep the attributes they have.
pub fn set_keyword_shortcut_ops(&self, keywords: &[String]) -> Op {
let paths: Vec<String> =
keywords.iter().map(|k| self.keyword_path(k).unwrap_or_else(|| self.spelled(&clean(k)))).filter(|k| !k.is_empty()).collect();
Op::Batch {
ops: self.list_ops(|list| {
for l in list.values_mut() {
l.info.keyword_shortcut = false;
}
for path in paths {
let l = list.entry(path.to_lowercase()).or_insert_with(|| ListedKeyword { path, info: KeywordInfo::default() });
l.info.keyword_shortcut = true;
}
}),
}
}
/// The keyword as written in the library (whatever the case of `path`): its listing, or the
/// levels a photo's keyword spells it with. `None` when there is no such keyword.
pub fn keyword_path(&self, path: &str) -> Option<String> {
+62 -1
View File
@@ -424,6 +424,36 @@ fn one_keyword_is_where_new_keywords_go() {
assert_eq!(c.default_keyword_parent(), None, "undo of the first: none was");
}
/// The keyword shortcut is a mark on its keywords: setting it is one undo step (a new name is
/// listed), and the mark moves with its keyword (also into a merge), goes with it, and comes
/// back with undo.
#[test]
fn the_keyword_shortcut_moves_with_its_keywords() {
let (mut c, _) = lib(&[&["Events|Weddings"], &["Travel"]]);
let op = c.set_keyword_shortcut_ops(&["travel".into(), "Lisbon".into()]);
let undo = c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Lisbon", "Travel"], "spelled as the library spells it; a new name listed");
let op = c.set_keyword_shortcut_ops(&["events|weddings".into(), "Travel".into()]);
c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings", "Travel"], "the old marks are cleared");
let op = c.rename_keyword_ops("travel", "Trips").unwrap();
let undo_rename = c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings", "Trips"]);
c.apply(undo_rename).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings", "Travel"], "undo moves it back");
let op = c.set_keyword_shortcut_ops(&["Travel".into()]);
c.apply(op).unwrap();
let op = c.merge_keywords_ops(&["travel".into()], "Events|Weddings").unwrap();
c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings"], "into the merge");
let op = c.delete_keyword_ops("events").unwrap();
c.apply(op).unwrap();
assert!(c.keyword_shortcut().is_empty());
assert_eq!(c.set_keyword_shortcut_ops(&[]), Op::Batch { ops: vec![] }, "none to clear");
c.apply(undo).unwrap();
assert!(c.keyword_shortcut().is_empty(), "undo of the first: there was none");
}
/// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, and the
/// names of `dc:subject` that aren't levels of those paths (an exported `travel|Italy` comes
/// back as one keyword, not three). Without paths, the names as they are.
@@ -433,7 +463,38 @@ fn a_files_keywords_keep_their_hierarchy() {
assert_eq!(from_file(&v(&["Rome", "Italy", "travel", "beach"]), &v(&["travel|Italy|Rome"])), ["travel|Italy|Rome", "beach"]);
assert_eq!(from_file(&v(&["ROME"]), &v(&["travel|Rome", " travel | rome "])), ["travel|Rome"], "each once, cleaned");
assert_eq!(from_file(&v(&["beach", " sea "]), &[]), ["beach", "sea"]);
assert_eq!(from_file(&v(&["a|b"]), &[]), ["a|b"], "LightCraft's own sidecars write paths flat");
assert_eq!(from_file(&v(&["a|b"]), &[]), ["a|b"], "sidecars from LightCraft 0.13 and older wrote paths flat");
}
/// A sidecar's keywords: names in `dc:subject`, never paths, and the paths in
/// `lr:hierarchicalSubject`; read back, the same keywords, however they were spelt or nested.
#[test]
fn a_sidecar_writes_names_flat_and_paths_hierarchical() {
let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let f = to_file(&v(&["Places|Italy|Rome", "sunset"]));
assert_eq!(f.flat, ["Places", "Italy", "Rome", "sunset"]);
assert_eq!(f.hierarchical, ["Places|Italy|Rome", "sunset"]);
assert!(f.flat.iter().all(|k| !k.contains(SEP)), "no path in dc:subject");
let f = to_file(&v(&["beach", " sea ", "Beach"]));
assert_eq!((f.flat, f.hierarchical), (v(&["beach", "sea"]), v(&[])), "no hierarchy: no lr:hierarchicalSubject");
assert_eq!(to_file(&[]), FileKeywords::default());
for keywords in [
v(&["Places|Italy|Rome", "sunset"]),
v(&["travel|Italy|Rome", "Rome"]),
v(&["travel|Italy", "travel|France", "Italy"]),
v(&["beach", "sea"]),
v(&[" a | b ", "A|B|c"]),
] {
let f = to_file(&keywords);
let mut back = from_file(&f.flat, &f.hierarchical);
let mut want: Vec<String> = keywords.iter().map(|k| clean(k)).collect();
dedupe(&mut want);
back.sort_by_key(|k| k.to_lowercase());
want.sort_by_key(|k| k.to_lowercase());
assert_eq!(back, want, "round trip of {keywords:?}");
}
}
/// A new keyword inside one the library has takes the library's spelling of it: creating
+293 -7
View File
@@ -294,6 +294,10 @@ pub struct Catalog {
/// Lookups derived from the above (never saved), see [`index`].
#[serde(skip)]
index: index::Indexes,
/// Each smart album's rules ready to run (cheapest rule first), worked out when first asked and
/// forgotten when an op adds or removes an album or changes rules.
#[serde(skip)]
plans: PlansMemo,
}
/// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a
@@ -332,6 +336,32 @@ impl Aspects {
/// The most photos remembered as touched; older changes are then answered with "anything may have changed".
const MAX_TOUCHED: usize = 8192;
/// [`Catalog::plans`] as last worked out: derived from the albums, like [`index::Indexes`], so no
/// part of what a catalog is; a copy starts without it.
#[derive(Default)]
struct PlansMemo {
plans: std::sync::OnceLock<std::collections::HashMap<AlbumId, query::Prepared>>,
guard: std::sync::OnceLock<bool>,
}
impl Clone for PlansMemo {
fn clone(&self) -> Self {
Self::default()
}
}
impl PartialEq for PlansMemo {
fn eq(&self, _: &PlansMemo) -> bool {
true
}
}
impl std::fmt::Debug for PlansMemo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PlansMemo")
}
}
/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
/// follow a small edit without being worked out again from every photo.
#[derive(Clone, Debug, Default)]
@@ -442,12 +472,61 @@ impl Catalog {
/// no smart album).
pub fn album_contains(&self, id: AlbumId, p: &Photo) -> bool {
match self.albums.get(&id) {
Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_one(), p),
Some(Album { smart: Some(rules), .. }) => match self.plans().get(&id) {
Some(plan) => self.smart_album_has(id, rules, plan, p),
None => self.smart_album_has(id, rules, &rules.prepare_one(self), p),
},
Some(a) => self.album_lists(a.id, p.id),
None => false,
}
}
/// Every smart album's [`Filter::prepare_one`], worked out once for the albums as they are
/// (so a photo asked about does not prepare the album's rules again).
fn plans(&self) -> &std::collections::HashMap<AlbumId, query::Prepared> {
self.plans.plans.get_or_init(|| self.albums.values().filter_map(|a| a.smart.as_ref().map(|rules| (a.id, rules.prepare_one(self)))).collect())
}
/// Whether rules must be tested as written, not cheapest first ([`Filter::prepare`]): some smart
/// album tests itself (a saved or damaged catalog; the app refuses to make one), or a chain of
/// smart albums testing smart albums is as long as [`rules::MAX_ALBUM_DEPTH`], where the
/// innermost hold nothing. There an answer can depend on which album was asked first (the
/// answers memo keeps what was worked out under the cut), so reordering could change who
/// matches. Worked out once for the albums as they are.
pub(crate) fn keeps_written_order(&self) -> bool {
*self.plans.guard.get_or_init(|| {
self.albums.values().any(|a| a.smart.is_some() && self.album_reaches(a.id, a.id)) || self.longest_chain() >= rules::MAX_ALBUM_DEPTH
})
}
/// The most smart albums one smart album leads through, itself included, by the smart albums
/// its rules and album filter test. Only asked of albums that lead back to none.
fn longest_chain(&self) -> usize {
let tests = |id: &AlbumId| -> Vec<AlbumId> {
let tested = self.albums.get(id).and_then(|a| a.smart.as_deref()).map(Filter::albums_tested).unwrap_or_default();
tested.into_iter().filter(|t| self.albums.get(t).is_some_and(|a| a.smart.is_some())).collect()
};
let mut chain: std::collections::HashMap<AlbumId, usize> = std::collections::HashMap::new();
for root in self.albums.values().filter(|a| a.smart.is_some()).map(|a| a.id) {
let mut stack = vec![root];
while let Some(a) = stack.last().copied() {
if chain.contains_key(&a) {
stack.pop();
continue;
}
let kids = tests(&a);
let pending: Vec<AlbumId> = kids.iter().copied().filter(|k| !chain.contains_key(k)).collect();
if pending.is_empty() {
chain.insert(a, 1 + kids.iter().filter_map(|k| chain.get(k)).copied().max().unwrap_or(0));
stack.pop();
} else {
stack.extend(pending);
}
}
}
chain.values().copied().max().unwrap_or(0)
}
/// Whether smart album `id` with `rules` (as [`Filter::prepare`]d) holds `p`.
fn smart_album_has(&self, id: AlbumId, rules: &Filter, prepared: &query::Prepared, p: &Photo) -> bool {
// guarded: a smart album testing smart albums can't loop or recurse without end
@@ -502,7 +581,7 @@ impl Catalog {
pub fn album_photos(&self, id: AlbumId) -> Vec<PhotoId> {
match self.albums.get(&id) {
Some(Album { smart: Some(rules), .. }) => {
let prepared = rules.prepare();
let prepared = rules.prepare(self);
self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect()
}
Some(a) => a.photos.clone(),
@@ -515,7 +594,7 @@ impl Catalog {
match self.albums.get(&id) {
// counted in place: no id list is built just for its length
Some(Album { smart: Some(rules), .. }) => {
let prepared = rules.prepare();
let prepared = rules.prepare(self);
self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).count()
}
Some(a) => a.photos.iter().filter(|p| self.photos.get(p).is_some_and(|p| !p.deleted)).count(),
@@ -652,6 +731,44 @@ impl Catalog {
Ok(inv)
}
/// [`Self::apply`] for a new edit (not an undo, a redo or the replay of a saved log, which bring
/// back what was): refused when it would put a smart album on a loop, one that includes itself
/// through the albums it tests. THE place that rule is kept, whichever command, importer or
/// task makes the edit, alone or in a batch. A library that already holds a loop still opens,
/// and an edit that puts no album on one it was not on goes through, also to an album on a loop.
///
/// The check is made on what the edit would do to the albums, before it is done: a refused
/// edit never touched the library, so there is nothing to take back.
pub fn apply_new(&mut self, op: Op) -> Result<Op> {
if let Some((id, name)) = self.would_put_on_a_loop(&op) {
return Err(CatalogError::Invalid(format!(
"smart album “{name}” (album {}) would include itself: its rules lead back to it through the albums they test",
id.0
)));
}
self.apply(op)
}
/// The album `op` would newly put on a loop, as its id and name: the album the op is about
/// when that is one of them. `None` when it makes none (or changes no album's rules).
fn would_put_on_a_loop(&self, op: &Op) -> Option<(AlbumId, String)> {
if !changes_what_albums_test(op) {
return None;
}
let mut graph = AlbumGraph::of(self.albums.values());
let now = graph.on_a_loop();
let mut edited = Vec::new();
foresee(&mut graph, op, &mut edited);
let then = graph.on_a_loop();
let name_of = |id: AlbumId| self.albums.get(&id).map(|a| a.name.clone()).unwrap_or_default();
let new_edited = edited.iter().find(|(id, _)| then.contains(id) && !now.contains(id));
match new_edited {
Some((id, name)) => Some((*id, name.map_or_else(|| name_of(*id), str::to_string))),
// an album the edit is not about (it tests one that now leads back to it)
None => then.difference(&now).next().map(|id| (*id, name_of(*id))),
}
}
fn apply_inner(&mut self, op: Op) -> Result<Op> {
// An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind
// can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's
@@ -699,10 +816,11 @@ impl Catalog {
| Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1),
}
Ok(match op {
Op::AddPhoto { photo } => {
Op::AddPhoto { mut photo } => {
if self.photos.contains_key(&photo.id) {
return Err(CatalogError::Invalid(format!("photo {:?} exists", photo.id)));
}
photo.trim_history();
let id = photo.id;
self.next_photo = self.next_photo.max(id.0.saturating_add(1));
self.photos.insert(id, Arc::new(*photo));
@@ -753,7 +871,14 @@ impl Catalog {
}
Op::SetHistory { id, history } => {
let p = self.photo_mut(id)?;
Op::SetHistory { id, history: std::mem::replace(&mut p.history, history) }
let old = std::mem::replace(&mut p.history, history);
let old_cursor = p.history_cursor;
p.trim_history();
if p.history_cursor == old_cursor {
Op::SetHistory { id, history: old }
} else {
Op::Batch { ops: vec![Op::SetHistory { id, history: old }, Op::SetHistoryCursor { id, cursor: old_cursor }] }
}
}
Op::PushHistory { id, step } => {
let p = self.photo_mut(id)?;
@@ -779,6 +904,7 @@ impl Catalog {
Op::SetHistoryCursor { id, cursor: std::mem::replace(&mut p.history_cursor, cursor) }
}
Op::AddAlbum { album } => {
self.plans = PlansMemo::default();
if self.albums.contains_key(&album.id) {
return Err(CatalogError::Invalid(format!("album {:?} exists", album.id)));
}
@@ -800,6 +926,7 @@ impl Catalog {
Op::RemoveAlbum { id }
}
Op::RemoveAlbum { id } => {
self.plans = PlansMemo::default();
if self.albums.values().any(|a| a.parent == Some(id)) {
return Err(CatalogError::Invalid("folder is not empty".into()));
}
@@ -860,6 +987,7 @@ impl Catalog {
Op::SetAlbumCover { id, cover: std::mem::replace(&mut a.cover, cover) }
}
Op::SetAlbumRules { id, rules } => {
self.plans = PlansMemo::default();
self.validate_rules(&rules)?;
let a = self.album_mut(id)?;
let Some(old) = a.smart.as_mut() else {
@@ -1054,8 +1182,9 @@ impl Catalog {
/// finds in them, and walks folders up to the top): every photo, album and stack carries the
/// id it is filed under; the id counters lie past every id in use; a stack keeps only photos
/// in the catalog, once each, and goes when fewer than two are left; an album whose parent is
/// missing, not a folder or inside itself moves to the top level. Returns what was changed
/// (nothing, for a catalog this build wrote).
/// missing, not a folder or inside itself moves to the top level; a photo keeps its newest
/// [`HISTORY_LIMIT`] History steps. Returns what was changed (nothing, for a catalog this build
/// wrote).
pub fn repair(&mut self) -> Vec<String> {
let mut changed = Vec::new();
for (id, p) in self.photos.iter_mut() {
@@ -1063,6 +1192,10 @@ impl Catalog {
changed.push(format!("photo {} was filed as {}", p.id.0, id.0));
Arc::make_mut(p).id = *id;
}
if p.history.len() > HISTORY_LIMIT {
let n = Arc::make_mut(p).trim_history();
changed.push(format!("photo {}: {n} History step(s) beyond the newest {HISTORY_LIMIT} dropped", id.0));
}
}
for (id, a) in self.albums.iter_mut() {
if a.id != *id {
@@ -1149,6 +1282,8 @@ impl Catalog {
if !changed.is_empty() {
// stacks and albums changed outside `apply`: the lookups are built again when asked
self.index = index::Indexes::default();
// (and what was worked out from the albums, the guard of [`Self::keeps_written_order`] too)
self.plans = PlansMemo::default();
}
changed
}
@@ -1180,6 +1315,153 @@ impl Catalog {
}
}
/// Whether `op` changes which albums a smart album tests: it adds or removes an album, or changes
/// rules (alone or in a batch).
fn changes_what_albums_test(op: &Op) -> bool {
// listed kind by kind (as in `apply_inner`), so a new kind has to be put on one side
match op {
Op::AddAlbum { .. } | Op::RemoveAlbum { .. } | Op::SetAlbumRules { .. } => true,
Op::Batch { ops } => ops.iter().any(changes_what_albums_test),
Op::AddPhoto { .. }
| Op::RemovePhoto { .. }
| Op::SetDeleted { .. }
| Op::SetLocal { .. }
| Op::SetContent { .. }
| Op::SetEmbeddedLens { .. }
| Op::SetAsShotWb { .. }
| Op::SetRating { .. }
| Op::SetFlag { .. }
| Op::SetLabel { .. }
| Op::SetMeta { .. }
| Op::SetCaptured { .. }
| Op::SetFile { .. }
| Op::Relink { .. }
| Op::SetAnalysis { .. }
| Op::SetDevelop { .. }
| Op::SetVersions { .. }
| Op::SetHistory { .. }
| Op::PushHistory { .. }
| Op::SetHistoryCursor { .. }
| Op::RenameAlbum { .. }
| Op::MoveAlbum { .. }
| Op::SetAlbumOrder { .. }
| Op::SetAlbumPhotos { .. }
| Op::SetAlbumCover { .. }
| Op::AddStack { .. }
| Op::RemoveStack { .. }
| Op::SetStack { .. }
| Op::SetLabelName { .. }
| Op::SetBrowsed { .. }
| Op::SetKeyword { .. }
| Op::SetFolderRecord { .. } => false,
}
}
/// What `op` would do to `graph`, as far as loops go (which album tests which), without the
/// checks `apply` makes: an op it would refuse is refused there. `edited` gets the albums the op
/// is about, with their name when the op brings it.
fn foresee<'a>(graph: &mut AlbumGraph, op: &'a Op, edited: &mut Vec<(AlbumId, Option<&'a str>)>) {
match op {
Op::AddAlbum { album } => {
// an id that is taken stays as it is: `apply` refuses the add
if let std::collections::hash_map::Entry::Vacant(slot) = graph.leads_to.entry(album.id) {
slot.insert(album.smart.as_deref().map(Filter::albums_tested));
edited.push((album.id, Some(album.name.as_str())));
}
}
Op::RemoveAlbum { id } => {
graph.leads_to.remove(id);
}
Op::SetAlbumRules { id, rules } => {
// only a smart album has rules: `apply` refuses them for another
if let Some(tested) = graph.leads_to.get_mut(id).filter(|t| t.is_some()) {
*tested = Some(rules.albums_tested());
edited.push((*id, None));
}
}
Op::Batch { ops } => ops.iter().for_each(|op| foresee(graph, op, edited)),
_ => {}
}
}
/// Which album tests which: what a smart album's photos depend on beyond its own rules. Made in
/// one look at the albums, for questions about all of them.
struct AlbumGraph {
/// Every album; `Some(albums its rules test)` for a smart album, `None` for any other.
leads_to: std::collections::HashMap<AlbumId, Option<Vec<AlbumId>>>,
}
impl AlbumGraph {
fn of<'a>(albums: impl Iterator<Item = &'a Album>) -> AlbumGraph {
AlbumGraph { leads_to: albums.map(|a| (a.id, a.smart.as_deref().map(Filter::albums_tested))).collect() }
}
/// The smart albums that lead back to themselves: those in a ring of albums leading to one
/// another (a strongly connected part of more than one album), or testing themselves. One
/// walk over the albums (Tarjan's, with its own stack rather than recursion: a chain of
/// thousands of albums must not overflow the call stack).
fn on_a_loop(&self) -> std::collections::BTreeSet<AlbumId> {
// only what tests an album can be on a ring: number those
let testing: Vec<(AlbumId, &[AlbumId])> =
self.leads_to.iter().filter_map(|(id, tested)| tested.as_deref().filter(|t| !t.is_empty()).map(|t| (*id, t))).collect();
let number: std::collections::HashMap<AlbumId, usize> = testing.iter().enumerate().map(|(i, (id, _))| (*id, i)).collect();
let leads: Vec<Vec<usize>> = testing.iter().map(|(_, t)| t.iter().filter_map(|to| number.get(to).copied()).collect()).collect();
const UNSEEN: usize = usize::MAX;
let n = testing.len();
// when each was first reached, the earliest still-open album it leads back to, the open
// ones in the order reached, and whether each ended up on a ring
let (mut reached, mut back) = (vec![UNSEEN; n], vec![0usize; n]);
let (mut open, mut is_open, mut ringed) = (Vec::new(), vec![false; n], vec![false; n]);
let mut clock = 0usize;
for root in 0..n {
if reached[root] != UNSEEN {
continue;
}
// (album, how many of its leads were followed)
let mut walk: Vec<(usize, usize)> = vec![(root, 0)];
while let Some(&(v, followed)) = walk.last() {
if followed == 0 && reached[v] == UNSEEN {
reached[v] = clock;
back[v] = clock;
clock += 1;
open.push(v);
is_open[v] = true;
}
if let Some(&w) = leads[v].get(followed) {
if let Some(top) = walk.last_mut() {
top.1 += 1;
}
if reached[w] == UNSEEN {
walk.push((w, 0));
} else if is_open[w] {
back[v] = back[v].min(reached[w]);
}
continue;
}
// every lead of `v` followed: it closes, and with it the ring it is the first of
walk.pop();
if let Some(&(parent, _)) = walk.last() {
back[parent] = back[parent].min(back[v]);
}
if back[v] == reached[v] {
let mut ring = Vec::new();
while let Some(w) = open.pop() {
is_open[w] = false;
ring.push(w);
if w == v {
break;
}
}
if ring.len() > 1 || leads[v].contains(&v) {
ring.into_iter().for_each(|w| ringed[w] = true);
}
}
}
}
testing.iter().zip(&ringed).filter(|(_, ringed)| **ringed).map(|((id, _), _)| *id).collect()
}
}
/// How siblings are listed: folders first, then the ones with a place of their own by it, then by
/// name; the id settles any tie.
fn album_order_key(a: &Album) -> (bool, bool, u32, String, AlbumId) {
@@ -1189,6 +1471,8 @@ fn album_order_key(a: &Album) -> (bool, bool, u32, String, AlbumId) {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_album_loops;
#[cfg(test)]
mod tests_album_order;
#[cfg(test)]
mod tests_background;
@@ -1209,6 +1493,8 @@ mod tests_lock;
#[cfg(test)]
mod tests_repair;
#[cfg(test)]
mod tests_rule_order;
#[cfg(test)]
mod tests_scale;
#[cfg(test)]
mod tests_tally;
+4 -2
View File
@@ -17,8 +17,10 @@
//! open" for a moment and a re-open would be refused (issue #680). `LOCK_UN` through our
//! descriptor frees the lock whatever copies a child still holds.
//! - Who holds it (process id, computer, program, version) is written to `catalog.lock.owner`, for
//! the error message. It's a separate file because a Windows lock also blocks reading the
//! locked file. It's only a hint: it may be missing or left over from a crash.
//! the error message. Only dropping the [`LibraryLock`] removes it, so a program that ends with
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). It's a separate
//! file because a Windows lock also blocks reading the locked file. It's only a hint: it may be
//! missing or left over from a crash.
//! - File systems without lock support (some network shares): the library opens unlocked, with a
//! warning — refusing it would lock the user out of their own library. Locks over SMB/NFS are
//! advisory and depend on the server; the owner file is then the only hint.
+36
View File
@@ -354,6 +354,17 @@ pub fn preview_stamp(preview_only: &Option<String>) -> String {
}
impl Photo {
/// Keep the newest [`HISTORY_LIMIT`](crate::HISTORY_LIMIT) History steps; the cursor moves with
/// its step, or to the oldest step kept when its own is dropped. Returns how many were dropped.
pub fn trim_history(&mut self) -> usize {
let n = self.history.len().saturating_sub(crate::HISTORY_LIMIT);
if n > 0 {
self.history.drain(..n);
self.history_cursor = self.history_cursor.map(|c| c.saturating_sub(n));
}
n
}
/// The History step the settings are at (the cursor, clamped to the list; `None` = no history).
pub fn history_index(&self) -> Option<usize> {
let last = self.history.len().checked_sub(1)?;
@@ -458,6 +469,15 @@ impl Photo {
pub fn extension(&self) -> &str {
self.file_name.rsplit_once('.').filter(|(stem, _)| !stem.is_empty()).map_or("", |(_, ext)| ext)
}
/// A video clip (an MP4, a MOV, …), which the image decoders can't read. Besides the kind, the
/// format and the extension count: a Lightroom catalog lists its videos with the format `VIDEO`,
/// and libraries made before they were imported as videos hold them as images.
pub fn is_video(&self) -> bool {
const EXTENSIONS: [&str; 12] = ["mp4", "mov", "m4v", "avi", "mts", "m2ts", "3gp", "mkv", "webm", "wmv", "mpg", "mpeg"];
self.kind == MediaKind::Video
|| self.format.eq_ignore_ascii_case("VIDEO")
|| EXTENSIONS.iter().any(|e| self.extension().eq_ignore_ascii_case(e))
}
/// Width and height in pixels as the photo is shown: turned by its orientation and cut by its
/// crop. Straightening and Constrain Crop shrink the crop without changing its shape, so the
/// aspect is exact and the edges can read a little larger than an export.
@@ -554,6 +574,22 @@ mod edited_tests {
use super::*;
use lightcraft_develop::WbScale;
#[test]
fn a_video_is_known_by_its_kind_format_or_extension() {
let file = |name: &str, format: &str| Photo::new(PhotoId(1), Source::Demo { scene: 0 }, name, format, 10, 10, "2026-10-01T00:00:00");
let mut clip = file("a.jpg", "JPEG");
clip.kind = MediaKind::Video;
assert!(clip.is_video(), "by its kind");
assert!(file("clip", "video").is_video(), "by the format a Lightroom catalog gives videos");
for name in ["VID_1.mp4", "a.MOV", "b.m4v", "c.mts", "d.webm"] {
assert!(file(name, "").is_video(), "{name}");
}
// (a name without an extension, or a dot file, has none)
for (name, format) in [("a.jpg", "JPEG"), ("a.arw", "ARW"), ("a.heic", "HEIC"), ("mp4", ""), (".mov", "")] {
assert!(!file(name, format).is_video(), "{name}");
}
}
#[test]
fn raw_with_import_settings_is_not_edited() {
let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, "a.arw", "ARW", 10, 10, "2026-10-01T00:00:00");
+59 -13
View File
@@ -36,6 +36,10 @@ pub struct Filter {
/// Any of these labels (the filter bar's multi-select); empty = no constraint.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<ColorLabel>,
/// Any of these flags (the filter bar's multi-select: Picked and Unflagged hide only the
/// rejects); empty = no constraint.
#[serde(skip_serializing_if = "Vec::is_empty", deserialize_with = "null_as_empty")]
pub flags: Vec<Flag>,
pub kind: Option<MediaKind>,
pub edited: Option<bool>,
pub album: Option<AlbumId>,
@@ -72,6 +76,11 @@ pub struct Filter {
pub rule_set: Option<crate::RuleSet>,
}
/// A list that may be given as `null`, read as empty: agents clear `flags` the way they clear `flag`.
fn null_as_empty<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
Ok(Option::<Vec<T>>::deserialize(d)?.unwrap_or_default())
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SortKey {
@@ -143,6 +152,9 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 {
pub(crate) struct Prepared {
root: Option<String>,
only: Option<std::collections::HashSet<PhotoId>>,
/// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]);
/// `None` tests them as written.
rules: Option<crate::RuleSet>,
}
/// The tokens of a search text: split at whitespace, except inside double quotes, so
@@ -263,6 +275,17 @@ impl Filter {
self.describe_in(Some(cat))
}
/// The flags that `flag` and `flags` let through together (they AND), in the filter bar's
/// 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 flags_shown(&self) -> Option<Vec<Flag>> {
if self.flag.is_none() && self.flags.is_empty() {
return None;
}
let passes = |f: &Flag| self.flag.is_none_or(|x| x == *f) && (self.flags.is_empty() || self.flags.contains(f));
Some([Flag::Pick, Flag::Reject, Flag::None].into_iter().filter(passes).collect())
}
fn describe_in(&self, cat: Option<&crate::Catalog>) -> String {
let mut v: Vec<String> = Vec::new();
if self.rating > 0 {
@@ -276,6 +299,9 @@ impl Filter {
if let Some(f) = self.flag {
v.push(format!("flag {}", format!("{f:?}").to_lowercase()));
}
if !self.flags.is_empty() {
v.push(format!("flag {}", self.flags.iter().map(|f| format!("{f:?}").to_lowercase()).collect::<Vec<_>>().join(" or ")));
}
if let Some(l) = self.label {
v.push(format!("label {}", format!("{l:?}").to_lowercase()));
}
@@ -329,18 +355,35 @@ impl Filter {
}
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
self.matches_in(p, cat, &self.prepare_one())
// one photo: its rules are tested as written (ordering them would cost more than it saves)
self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, rules: None })
}
/// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed).
pub(crate) fn prepare_one(&self) -> Prepared {
Prepared { root: self.library_root(), only: None }
/// [`Filter::prepare`] for testing one photo at a time, with what each needs worked out once
/// (the `only` ids are looked through, not hashed).
pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared {
Prepared { root: self.library_root(), only: None, rules: self.ordered_rules(cat) }
}
/// The rule set to test, cheapest rule first: once per prepared filter, not per photo. `None`
/// (as written) while any smart album tests itself or a chain is too deep ([`Catalog::keeps_written_order`]), where the
/// order could change which photos match.
fn ordered_rules(&self, cat: &Catalog) -> Option<crate::RuleSet> {
if cat.keeps_written_order() {
return None;
}
self.rule_set.as_ref().map(|rs| rs.by_cost(cat))
}
/// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than
/// once per photo: the library folder's identity and the `only` ids as a set.
pub(crate) fn prepare(&self) -> Prepared {
Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()) }
/// once per photo: the library folder's identity, the `only` ids as a set and the rules in the
/// order to test them.
pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared {
Prepared {
root: self.library_root(),
only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()),
rules: self.ordered_rules(cat),
}
}
/// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice.
@@ -384,13 +427,16 @@ impl Filter {
return false;
}
if let Some(rs) = &self.rule_set
&& !rs.matches(p, cat)
&& !prepared.rules.as_ref().unwrap_or(rs).matches(p, cat)
{
return false;
}
if !self.labels.is_empty() && !p.label.is_some_and(|l| self.labels.contains(&l)) {
return false;
}
if !self.flags.is_empty() && !self.flags.contains(&p.flag) {
return false;
}
if self.only_none {
return false;
}
@@ -484,9 +530,9 @@ impl Catalog {
/// album's rules, the filter bar), as long as they are still where the view looks (`within`: in the library,
/// the album, the folder; not deleted).
pub fn query_keeping(&self, filter: &Filter, sort: &Sort, keep: &std::collections::HashSet<PhotoId>, within: &Filter) -> Vec<PhotoId> {
let prepared = filter.prepare();
let prepared = filter.prepare(self);
// `within` only decides for the few kept photos: worked out per photo, not hashed
let within_prepared = within.prepare_one();
let within_prepared = within.prepare_one(self);
let mut v: Vec<&Photo> = self
.photos()
.map(|p| p.as_ref())
@@ -504,7 +550,7 @@ impl Catalog {
pub fn follow(&self, was: &[PhotoId], touched: &[PhotoId], filter: &Filter, sort: &Sort, within: Option<&Filter>) -> Vec<PhotoId> {
let listed: std::collections::HashSet<PhotoId> = was.iter().copied().filter(|id| touched.binary_search(id).is_ok()).collect();
let mut ids: Vec<PhotoId> = was.iter().copied().filter(|id| !listed.contains(id)).collect();
let (prepared, within_prepared) = (filter.prepare_one(), within.map(Filter::prepare_one));
let (prepared, within_prepared) = (filter.prepare_one(self), within.map(|w| w.prepare_one(self)));
for id in touched {
let Some(p) = self.photo(*id) else { continue };
let kept = within.zip(within_prepared.as_ref()).is_some_and(|(w, wp)| listed.contains(id) && w.matches_in(p, self, wp));
@@ -519,7 +565,7 @@ impl Catalog {
/// How many photos match `filter`: [`Catalog::query`]'s length without its sorting.
pub fn count(&self, filter: &Filter) -> usize {
let prepared = filter.prepare();
let prepared = filter.prepare(self);
self.photos().filter(|p| filter.matches_in(p, self, &prepared)).count()
}
@@ -576,7 +622,7 @@ impl Catalog {
pub fn people_in(&self, filter: &Filter) -> Vec<Person> {
let filter = Filter { person: None, ..filter.clone() };
let mut m: std::collections::HashMap<String, (Person, f64)> = Default::default();
let prepared = filter.prepare();
let prepared = filter.prepare(self);
for p in self.photos().filter(|p| filter.matches_in(p, self, &prepared)) {
let mut seen: Vec<String> = Vec::new();
for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) {
+140 -6
View File
@@ -488,6 +488,12 @@ fn pass_answer(id: crate::AlbumId, photo: crate::PhotoId) -> Option<bool> {
})
}
#[cfg(test)]
thread_local! {
/// Tests: test rules in the order they were written, as before [`RuleSet::by_cost`].
pub(crate) static WRITTEN_ORDER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(test)]
thread_local! {
/// How many times a smart album's rules were worked out on this thread (tests count them).
@@ -514,9 +520,11 @@ pub(crate) fn smart_album_holds(id: crate::AlbumId, photo: crate::PhotoId, match
}
}
}
let _forget = Forget(EVALUATING.with_borrow(Vec::is_empty));
let outermost = EVALUATING.with_borrow(Vec::is_empty);
let _forget = Forget(outermost);
let answer = evaluating(id, matches);
if let Some(a) = answer {
// (the outermost answer would be forgotten as this returns: only what a nested question worked out is kept)
if let (Some(a), false) = (answer, outermost) {
ANSWERS.with_borrow_mut(|known| known.insert((id, photo), a));
}
answer.unwrap_or(false)
@@ -901,9 +909,11 @@ fn path_bytes_contains(hay: &[u8], needle: &[u8]) -> bool {
tail.iter().enumerate().any(|(j, &c)| at(tail_from + j, c))
}
/// A `filePath` rule. The common case (an ASCII path and an ASCII text) is compared in place, folding
/// case and `\` as it goes, with nothing allocated per photo; any other text takes
/// [`file_path_matches_slow`], so Unicode lower-casing (ß, İ, final sigma…) behaves as it always did.
/// A `filePath` rule. An ASCII path and an ASCII text are compared as bytes, a path or text with other
/// characters folded into stack buffers ([`file_path_matches_folded`]); both fold case and `\` as they
/// go, with nothing allocated per photo. Only what that can't reproduce (a text that is not a string, a
/// path or text longer than the buffers, or a capital sigma, whose lower case depends on its neighbors)
/// takes [`file_path_matches_slow`], so Unicode lower-casing (ß, İ, final sigma…) behaves as it always did.
fn file_path_matches(op: &str, source: &Source, value: &Value) -> bool {
let path = match source {
Source::File { path } => path.as_str(),
@@ -911,7 +921,7 @@ fn file_path_matches(op: &str, source: &Source, value: &Value) -> bool {
};
let Value::String(want) = value else { return file_path_matches_slow(op, path, value) };
if !path.is_ascii() || !want.is_ascii() {
return file_path_matches_slow(op, path, value);
return file_path_matches_folded(op, path, want).unwrap_or_else(|| file_path_matches_slow(op, path, value));
}
let (path, want) = (path.trim().as_bytes(), want.trim().as_bytes());
match op {
@@ -928,6 +938,70 @@ fn file_path_matches(op: &str, source: &Source, value: &Value) -> bool {
}
}
/// Room for a folded path (a path of 1 KiB; the fold of a character is at most 1.5 times its bytes) and a folded text.
const FOLDED_PATH_BYTES: usize = 1536;
const FOLDED_TEXT_BYTES: usize = 384;
/// The pair tried first.
const SMALL_PATH_BYTES: usize = 256;
const SMALL_TEXT_BYTES: usize = 96;
/// `s` as the `filePath` rules compare it, written into `buf`: `\` as `/`, every character lower-cased
/// the way [`str::to_lowercase`] does (`İ` becomes `i` and U+0307). `None` when it doesn't fit, or for a
/// capital sigma, which `to_lowercase` writes as `ς` at the end of a word and `σ` elsewhere, by Unicode
/// tables this module can't reach; the caller takes the allocating comparison.
fn fold_path<'b>(s: &str, buf: &'b mut [u8]) -> Option<&'b str> {
let (mut n, mut at) = (0, 0);
while at < s.len() {
// an ASCII run is copied and folded as one block
let run = s.as_bytes()[at..].iter().position(|b| !b.is_ascii()).unwrap_or(s.len() - at);
if run > 0 {
let out = buf.get_mut(n..n + run)?;
out.copy_from_slice(&s.as_bytes()[at..at + run]);
out.iter_mut().for_each(|b| *b = fold_path_byte(*b));
(n, at) = (n + run, at + run);
continue;
}
let c = s[at..].chars().next()?;
if c == '\u{3a3}' {
return None;
}
for l in c.to_lowercase() {
n += l.encode_utf8(buf.get_mut(n..)?.get_mut(..l.len_utf8())?).len();
}
at += c.len_utf8();
}
std::str::from_utf8(&buf[..n]).ok()
}
/// [`file_path_matches`] for a path or text with non-ASCII characters: both folded into stack buffers, then
/// compared as the allocating comparison does, so the answers are the same by construction (a match may
/// begin inside one character's several lower-case characters, `İ` then U+0307, as it does there).
/// Photo paths are short, so a small pair of buffers goes first (clearing a big one costs more than a
/// short path's fold); `None` where [`fold_path`] can't fold them in the large pair either.
fn file_path_matches_folded(op: &str, path: &str, want: &str) -> Option<bool> {
file_path_matches_folded_in::<{ SMALL_PATH_BYTES }, { SMALL_TEXT_BYTES }>(op, path, want)
.or_else(|| file_path_matches_folded_in::<{ FOLDED_PATH_BYTES }, { FOLDED_TEXT_BYTES }>(op, path, want))
}
fn file_path_matches_folded_in<const PATH: usize, const TEXT: usize>(op: &str, path: &str, want: &str) -> Option<bool> {
if matches!(op, "isEmpty" | "isNotEmpty") {
return Some((op == "isEmpty") == path.trim().is_empty());
}
let mut want_buf = [0u8; TEXT];
let mut path_buf = [0u8; PATH];
let want = fold_path(want.trim(), &mut want_buf)?;
Some(match op {
// the whole string, spaces included (not word by word like the other text fields)
"contains" => !want.is_empty() && fold_path(path, &mut path_buf)?.contains(want),
"notContains" => want.is_empty() || !fold_path(path, &mut path_buf)?.contains(want),
"is" => fold_path(path.trim(), &mut path_buf)? == want,
"isNot" => fold_path(path.trim(), &mut path_buf)? != want,
"startsWith" => fold_path(path.trim(), &mut path_buf)?.starts_with(want),
"endsWith" => fold_path(path.trim(), &mut path_buf)?.ends_with(want),
_ => false,
})
}
/// [`file_path_matches`] for any text: the path and the text are normalised into new strings.
fn file_path_matches_slow(op: &str, path: &str, value: &Value) -> bool {
// `/` and `\` both separate, whatever platform the catalog came from; demo photos have no path
@@ -1048,6 +1122,48 @@ impl Rule {
}
}
/// How much work one rule is, in tiers: [`RuleSet::by_cost`] tests the cheaper first.
const COST_SCALAR: u8 = 0;
const COST_SMALL: u8 = 1;
const COST_TEXT: u8 = 2;
const COST_ALBUM: u8 = 3;
impl Rule {
/// A rule's tier: 0 numbers, choices and yes/no questions about one photo's own record (and
/// anything that is settled at once: an unknown field or a missing album); 1 dates, keyword and
/// people lists, short single fields, an index lookup and a plain album's list (a folder holds no photos here: an empty lookup); 2 text built
/// from several fields and file paths (long strings, matched for each photo); 3 a smart album,
/// which runs a whole rule set for the photo. A group costs as much as its dearest rule.
fn cost(&self, cat: &Catalog) -> u8 {
match self {
Rule::Group { group } => group.rules.iter().map(|r| r.cost(cat)).max().unwrap_or(COST_SCALAR),
Rule::Field { field, value, .. } => match field.as_str() {
"album" => album_rule_id(value).map_or(COST_SCALAR, |id| match cat.albums.get(&id) {
None => COST_SCALAR,
Some(a) if a.smart.is_some() => COST_ALBUM,
Some(_) => COST_SMALL,
}),
"text" | "filePath" | "location" => COST_TEXT,
"keywords" | "person" | "personCount" | "stacked" | "copyName" | "fileName" | "extension" | "format" | "title" | "caption"
| "altText" | "city" | "state" | "country" | "camera" | "lens" | "creator" | "copyright" | "captureDate" | "importDate"
| "editDate" | "shutterSpeed" | "aspect" => COST_SMALL,
_ => COST_SCALAR,
},
}
}
/// This rule with its nested groups ordered by cost, and its tier.
fn by_cost(&self, cat: &Catalog) -> (u8, Rule) {
match self {
Rule::Group { group } => {
let group = group.by_cost(cat);
(group.rules.iter().map(|r| r.cost(cat)).max().unwrap_or(COST_SCALAR), Rule::Group { group })
}
field => (field.cost(cat), field.clone()),
}
}
}
impl RuleSet {
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
if self.rules.is_empty() {
@@ -1060,6 +1176,22 @@ impl RuleSet {
}
}
/// This rule set with its rules (and those of nested groups) in the order to test them: the
/// cheapest first ([`Rule::cost`]), the user's order among equals. Rules are pure (they read
/// the photo and the catalog; a smart album's answer is the same however it is reached as long
/// as no smart album tests itself and no chain is cut by the depth limit, which callers check first: [`Catalog::keeps_written_order`]),
/// so for all, any and none the photos that match are the same in any order; only the work
/// differs. Worked out once for a pass, never per photo. The saved rules are untouched.
pub(crate) fn by_cost(&self, cat: &Catalog) -> RuleSet {
#[cfg(test)]
if WRITTEN_ORDER.get() {
return self.clone();
}
let mut rules: Vec<(u8, Rule)> = self.rules.iter().map(|r| r.by_cost(cat)).collect();
rules.sort_by_key(|(cost, _)| *cost);
RuleSet { mode: self.mode, rules: rules.into_iter().map(|(_, r)| r).collect() }
}
/// Whether matches depend on the clock ("in the last…" rules, nested groups included): the
/// same photos can enter or leave the set without any catalog change.
pub fn depends_on_now(&self) -> bool {
@@ -1180,3 +1312,5 @@ impl RuleSet {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_path_fold;
+135
View File
@@ -0,0 +1,135 @@
//! A `filePath` rule over a non-ASCII path or text compares in place, with the answers the
//! allocating comparison ([`file_path_matches_slow`]) always gave. That nothing is allocated per
//! photo is checked in `tests/path_fold_heap.rs` (dhat's profiler is global, so it has its own binary).
use proptest::prelude::*;
use serde_json::{Value, json};
use super::*;
use crate::Source;
const OPS: [&str; 9] = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty", "bogus"];
fn file(path: &str) -> Source {
Source::File { path: path.to_string() }
}
fn fast(op: &str, path: &str, want: &str) -> bool {
file_path_matches(op, &file(path), &Value::String(want.to_string()))
}
fn old(op: &str, path: &str, want: &str) -> bool {
file_path_matches_slow(op, path, &Value::String(want.to_string()))
}
#[test]
fn pinned_unicode_cases_keep_their_old_answers() {
// (path, text) pairs where lower-casing changes the length, folds across scripts or looks at its neighbors
let pairs = [
("İstanbul/Photo", "i̇stanbul"), // İ lower-cases to i + U+0307
("a/İ", "\u{307}"), // a match that starts inside an expansion
("STRASSE", "straße"), // ß never equals ss, either way
("Straße", "STRASSE"),
("ẞ/x", "ß"), // capital sharp s lower-cases to ß
("ΟΔΟΣ", "οδος"), // final sigma: Σ → ς at the end of a word
("ΟΔΟΣ", "οδοσ"),
("ΣΑΣ/ΟΔΟΣ", "σας"),
("\u{212A}elvin", "kelvin"), // Kelvin sign → k
("Dž/x", "dž"), // a title-case digraph
("D:\\Фото\\Ё", "d:/фото/ё"),
(" Ünï ", "ünï"), // whitespace around the path is trimmed for is / startsWith / endsWith
("Ünï", " ünï\t"),
("\u{85}Ü\u{2003}", "ü"),
("", "é"),
("é", ""),
];
for (path, want) in pairs {
for op in OPS {
assert_eq!(fast(op, path, want), old(op, path, want), "{op} {path:?} {want:?}");
}
}
}
#[test]
fn a_path_or_text_longer_than_the_buffers_still_answers_as_before() {
// İ grows by half when lower-cased, so these cross FOLDED_PATH_BYTES and FOLDED_TEXT_BYTES on either side of the limit
for len in [FOLDED_PATH_BYTES / 3, FOLDED_PATH_BYTES / 2 - 1, FOLDED_PATH_BYTES / 2, FOLDED_PATH_BYTES, FOLDED_PATH_BYTES * 2] {
let path = format!("/Фото/{}/IMG.JPG", "İ".repeat(len / 2));
for want_len in [3, FOLDED_TEXT_BYTES / 3, FOLDED_TEXT_BYTES / 2, FOLDED_TEXT_BYTES, FOLDED_TEXT_BYTES * 2] {
let tail = "i̇".repeat(want_len / 3);
for want in [tail.clone(), format!("{tail}/img.jpg"), format!("/фото/{tail}")] {
for op in OPS {
assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{op} {len} {want_len}");
}
}
}
}
}
#[test]
fn a_text_that_is_not_a_string_still_answers_as_before() {
for value in [json!(7), json!(null), json!(true), json!(["é"])] {
for op in OPS {
let src = file("/Фото/7.jpg");
assert_eq!(file_path_matches(op, &src, &value), file_path_matches_slow(op, "/Фото/7.jpg", &value), "{op} {value}");
}
}
}
/// Letters whose lower-casing is odd, plus plain ones, separators and whitespace.
fn glyph() -> impl Strategy<Value = char> {
prop::sample::select(vec![
'a', 'A', 's', 'S', 'ß', 'ẞ', 'İ', 'i', 'I', '\u{307}', 'é', 'É', 'ü', 'Ü', 'Σ', 'σ', 'ς', 'Dž', 'dž', 'DŽ', '\u{212A}', 'k', 'Ω', 'ω', 'Ё',
'ё', 'Ф', 'ф', '日', '本', '/', '\\', ' ', '\t', '\u{85}', '\u{2003}', '.', '1',
])
}
fn text() -> impl Strategy<Value = String> {
prop::collection::vec(glyph(), 0..14).prop_map(|v| v.into_iter().collect())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4000))]
#[test]
fn the_in_place_comparison_equals_the_allocating_one(path in text(), want in text(), op in prop::sample::select(OPS.to_vec())) {
prop_assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{} {:?} {:?}", op, path, want);
}
#[test]
fn a_slice_of_the_path_is_found_whatever_its_case(path in text(), from in 0usize..14, len in 0usize..14, upper in any::<bool>(), op in prop::sample::select(OPS.to_vec())) {
let chars: Vec<char> = path.chars().collect();
let from = from.min(chars.len());
let to = (from + len).min(chars.len());
let slice: String = chars[from..to].iter().collect();
let want = if upper { slice.to_uppercase() } else { slice.to_lowercase() };
prop_assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{} {:?} {:?}", op, path, want);
}
#[test]
fn any_unicode_text_agrees(path in "\\PC{0,12}", want in "\\PC{0,6}", op in prop::sample::select(OPS.to_vec())) {
prop_assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{} {:?} {:?}", op, path, want);
}
}
/// A timed loop over a library's worth of non-ASCII paths: run it with
/// `just test catalog path_fold_timing -- --ignored --nocapture` (release numbers: `--release`).
#[test]
#[ignore = "a measurement, not a check"]
fn path_fold_timing() {
const N: usize = 844_425;
let folders = ["Фото", "Ünïcode", "日本語", "Straße", "Éclair", "İstanbul"];
let paths: Vec<Source> = (0..N).map(|i| file(&format!("/Volumes/share/{}/{}/IMG_{i:07}.JPG", folders[i % 6], folders[(i / 6) % 6]))).collect();
let wants = [("contains", "ÉCLAIR/img_000"), ("contains", "tokyo"), ("startsWith", "/volumes/share/фото"), ("endsWith", "99.jpg")];
for (op, want) in wants {
let value = Value::String(want.to_string());
let t = std::time::Instant::now();
let new_hits = paths.iter().filter(|p| file_path_matches(op, p, &value)).count();
let new_time = t.elapsed();
let t = std::time::Instant::now();
let old_hits = paths.iter().filter(|p| matches!(p, Source::File { path } if file_path_matches_slow(op, path, &value))).count();
let old_time = t.elapsed();
assert_eq!(new_hits, old_hits);
println!("{op:<11} {want:<22} hits {new_hits:>7} in place {new_time:>10.2?} allocating {old_time:>10.2?}");
}
}
+25
View File
@@ -125,6 +125,31 @@ fn filter_search_sort() {
/// A search word with a colon whose left part is not a known field ("10:30", "Re:") is plain
/// text, not a fielded token that matches nothing.
/// `flags` (#2588) matches any of its flags; a filter saved before it, with the single `flag`, reads
/// and filters as it did, and a filter without `flags` is written without the key.
#[test]
fn filter_flags_any_of_and_the_old_single_flag() {
let mut c = Catalog::new();
let a = photo(&mut c, "a.jpg", "2026-01-01T10:00:00");
let b = photo(&mut c, "b.jpg", "2026-01-02T10:00:00");
let d = photo(&mut c, "d.jpg", "2026-01-03T10:00:00");
c.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap();
c.apply(Op::SetFlag { id: d, flag: Flag::Reject }).unwrap();
let f = Filter { flags: vec![Flag::Pick, Flag::None], ..Default::default() };
assert_eq!(c.query(&f, &Sort::default()), vec![b, a]);
let f = Filter { flags: vec![Flag::Reject, Flag::None], ..Default::default() };
assert_eq!(c.query(&f, &Sort::default()), vec![d, b]);
let saved: Filter = serde_json::from_value(serde_json::json!({"text": "", "rating": 0, "flag": "reject", "label": null})).unwrap();
assert!(saved.flags.is_empty());
assert_eq!(c.query(&saved, &Sort::default()), vec![d]);
let written = serde_json::to_value(&saved).unwrap();
assert_eq!(written.get("flag"), Some(&serde_json::json!("reject")));
assert!(written.get("flags").is_none(), "{written}");
let round: Filter =
serde_json::from_value(serde_json::to_value(Filter { flags: vec![Flag::Pick, Flag::None], ..Default::default() }).unwrap()).unwrap();
assert_eq!(round.flags, vec![Flag::Pick, Flag::None]);
}
#[test]
fn free_text_with_a_colon_searches_the_text_fields() {
let mut c = Catalog::new();
+243
View File
@@ -0,0 +1,243 @@
//! Smart albums that would include themselves, through the albums they test.
//!
//! The rule is the catalog's: a new edit that would put a smart album on such a loop is refused
//! (`Catalog::apply_new`), whoever makes it and however it is packed (alone, in a batch, as a
//! new album). A library that already holds a loop opens and keeps working (`Catalog::apply`,
//! `replay` and snapshots take it).
//!
//! Scenarios:
//! - When a new edit (adding a smart album, changing rules, alone or in a batch) would put a
//! smart album on a loop, then it is refused, names the album, and nothing changed.
//! - When a new edit makes no loop, then it goes through, whatever else is in the library.
//! - Given a library that already holds a loop, then it opens, and edits that add no loop go
//! through (also to the albums on it), and the loop can be mended.
//! - Given a ring of thousands of smart albums, then the edit that closes it is refused without
//! running out of stack.
use crate::*;
fn smart(c: &mut Catalog, name: &str, rules: Filter) -> AlbumId {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(rules)), ..Album::new(id, name) } }).unwrap();
id
}
fn plain(c: &mut Catalog, name: &str) -> AlbumId {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album::new(id, name) }).unwrap();
id
}
/// Rules of Album rules: `(op, album)` joined by `all`.
fn tests(rules: &[(&str, AlbumId)]) -> Filter {
let rules: Vec<serde_json::Value> = rules.iter().map(|(op, a)| serde_json::json!({"field": "album", "op": op, "value": a.0})).collect();
serde_json::from_value(serde_json::json!({"ruleSet": {"match": "all", "rules": rules}})).unwrap()
}
/// The same, with the albums in a group of the rules.
fn tests_in_a_group(album: AlbumId) -> Filter {
serde_json::from_value(serde_json::json!({"ruleSet": {"match": "all", "rules": [
{"field": "rating", "op": "is", "value": 3},
{"group": {"match": "any", "rules": [{"field": "album", "op": "is", "value": album.0}]}}
]}}))
.unwrap()
}
fn set_rules(id: AlbumId, rules: Filter) -> Op {
Op::SetAlbumRules { id, rules: Box::new(rules) }
}
fn rated(rating: u8) -> Filter {
Filter { rating, ..Default::default() }
}
/// What the albums are: the whole library as saved.
fn saved(c: &Catalog) -> String {
c.to_snapshot()
}
#[test]
fn a_new_edit_that_would_make_a_loop_is_refused() {
let mut c = Catalog::new();
let a = smart(&mut c, "A", rated(1));
let b = smart(&mut c, "B", tests(&[("is", a)]));
let chain = smart(&mut c, "Chain", tests(&[("isNot", b)]));
let (x, y) = (smart(&mut c, "X", rated(2)), smart(&mut c, "Y", rated(3)));
// F tests E; E is removed, so F tests an album that is not there (a saved rule may)
let e = smart(&mut c, "E", rated(4));
let f = smart(&mut c, "F", tests(&[("is", e)]));
c.apply(Op::RemoveAlbum { id: e }).unwrap();
let (before, revision) = (saved(&c), c.revision);
let refused: Vec<(&str, Op, &str)> = vec![
("tests an album that tests it", set_rules(a, tests(&[("is", b)])), "A"),
("tests itself", set_rules(a, tests(&[("is", a)])), "A"),
("tests itself through a group", set_rules(a, tests_in_a_group(a)), "A"),
("tests the end of a chain that leads to it", set_rules(a, tests(&[("isNot", chain)])), "A"),
("limited to itself by its album field", set_rules(a, Filter { album: Some(a), ..Default::default() }), "A"),
("two edits, each alone without a loop", Op::Batch { ops: vec![set_rules(x, tests(&[("is", y)])), set_rules(y, tests(&[("is", x)]))] }, "X"),
("a rename and a loop", Op::Batch { ops: vec![Op::RenameAlbum { id: a, name: "Renamed".into() }, set_rules(a, tests(&[("is", b)]))] }, "A"),
(
"a batch in a batch",
Op::Batch {
ops: vec![Op::Batch { ops: vec![set_rules(x, tests(&[("is", y)]))] }, Op::Batch { ops: vec![set_rules(y, tests(&[("is", x)]))] }],
},
"X",
),
(
"a new album that takes the id an album was tested by",
Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", f)]))), ..Album::new(e, "Back") } },
"Back",
),
(
"a new album and its own rules in one batch",
Op::Batch {
ops: vec![
Op::AddAlbum { album: Album { smart: Some(Box::new(rated(1))), ..Album::new(AlbumId(90), "Fresh") } },
set_rules(AlbumId(90), tests(&[("is", AlbumId(90))])),
],
},
"Fresh",
),
];
for (what, op, name) in refused {
let e = c.apply_new(op).unwrap_err().to_string();
assert!(e.contains(&format!("“{name}”")) && e.contains("include itself"), "{what}: {e}");
assert_eq!(saved(&c), before, "{what}: nothing changed");
assert_eq!(c.revision, revision, "{what}: not even looked at as changed");
}
}
#[test]
fn a_new_edit_that_makes_no_loop_goes_through() {
let mut c = Catalog::new();
let a = smart(&mut c, "A", rated(1));
let b = smart(&mut c, "B", tests(&[("is", a)]));
let list = plain(&mut c, "List");
let c1 = smart(&mut c, "C", tests(&[("isNot", b)]));
let allowed = vec![
("a chain gets longer", set_rules(a, rated(2))),
("testing a plain album", set_rules(a, tests(&[("is", list)]))),
("a smart album testing another, the other way round", set_rules(c1, tests(&[("is", a), ("is", b)]))),
(
"a new smart album testing others",
Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", c1)]))), ..Album::new(AlbumId(50), "New") } },
),
("a new plain album", Op::AddAlbum { album: Album::new(AlbumId(51), "Plain") }),
("a rename", Op::RenameAlbum { id: b, name: "B2".into() }),
("a removal", Op::RemoveAlbum { id: c1 }),
("photos of a plain album", Op::SetAlbumPhotos { id: list, photos: vec![] }),
("the album field of the rules", set_rules(b, Filter { album: Some(list), ..Default::default() })),
(
"a batch of edits that don't meet",
Op::Batch { ops: vec![set_rules(a, rated(3)), Op::RenameAlbum { id: a, name: "A3".into() }, set_rules(b, tests(&[("is", a)]))] },
),
(
"a batch that passes through a loop and ends without one",
Op::Batch { ops: vec![set_rules(a, tests(&[("is", b)])), set_rules(b, rated(1))] },
),
];
for (what, op) in allowed {
let revision = c.revision;
let undo = c.apply_new(op).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(c.revision, revision + 1, "{what}");
assert!(c.albums().all(|al| !c.smart_album_problems(al.id).iter().any(|p| p.issue == rules::Issue::AlbumLoop)), "{what}: no loop");
// and it is undone by what it returned
c.apply(undo).unwrap();
}
}
/// The refusal is the only difference between the two ways in: an edit that makes no loop does
/// the same through either.
#[test]
fn apply_new_changes_what_apply_changes() {
let mut a = Catalog::new();
let first = smart(&mut a, "A", rated(1));
let second = smart(&mut a, "B", tests(&[("is", first)]));
let mut b = Catalog::from_snapshot(&saved(&a)).unwrap();
let ops = vec![set_rules(first, rated(4)), Op::RenameAlbum { id: second, name: "B2".into() }, set_rules(second, tests(&[("isNot", first)]))];
for op in ops {
let (ia, ib) = (a.apply(op.clone()).unwrap(), b.apply_new(op).unwrap());
assert_eq!(Catalog::op_to_log_line(&ia), Catalog::op_to_log_line(&ib));
}
assert_eq!(saved(&a), saved(&b));
}
/// A library saved by a version without the rule: it may hold a loop. It opens (a snapshot, a
/// replayed log), its albums still list and count, edits that make no loop go through, also
/// those to the albums on the loop, and an edit that closes another loop is still refused.
#[test]
fn a_library_that_already_holds_a_loop_opens_and_can_be_mended() {
let mut old = Catalog::new();
let mut log = String::new();
let mut record = |c: &mut Catalog, op: Op| {
log.push_str(&Catalog::op_to_log_line(&op));
c.apply(op).unwrap();
};
let (first, second, other, third) = (AlbumId(1), AlbumId(2), AlbumId(3), AlbumId(4));
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(first, "First") } });
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", first)]))), ..Album::new(second, "Second") } });
record(&mut old, set_rules(first, tests(&[("is", second)])));
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(other, "Other") } });
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", other)]))), ..Album::new(third, "Third") } });
let mut c = Catalog::new();
assert_eq!(c.replay(&log).unwrap(), 5, "the log replays, loop and all");
let mut from_snapshot = Catalog::from_snapshot(&c.to_snapshot()).unwrap();
for lib in [&mut c, &mut from_snapshot] {
// they still answer
for id in [first, second, other, third] {
let _ = (lib.album_photos(id), lib.album_count(id), lib.smart_album_problems(id));
}
// edits that make no loop go through: elsewhere, and to the albums on the loop
lib.apply_new(Op::RenameAlbum { id: first, name: "First, renamed".into() }).unwrap();
lib.apply_new(set_rules(other, rated(2))).unwrap();
lib.apply_new(set_rules(third, tests(&[("isNot", other)]))).unwrap();
lib.apply_new(Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", second)]))), ..Album::new(AlbumId(60), "Reads the loop") } })
.unwrap();
lib.apply_new(set_rules(first, Filter { rating: 3, rule_set: tests(&[("is", second)]).rule_set, ..Default::default() })).unwrap();
// not one that closes another
let e = lib.apply_new(set_rules(other, tests(&[("is", third)]))).unwrap_err().to_string();
assert!(e.contains("“Other”") && e.contains("include itself"), "{e}");
// mended by an edit that makes no loop
lib.apply_new(set_rules(second, rated(1))).unwrap();
assert!(!lib.smart_album_problems(first).iter().any(|p| p.issue == rules::Issue::AlbumLoop), "mended");
assert!(!lib.smart_album_problems(second).iter().any(|p| p.issue == rules::Issue::AlbumLoop), "mended");
}
}
/// What an album on a loop holds is whatever it held before the refusal existed: the rule keeps
/// new loops out and decides nothing about the photos of old ones.
#[test]
fn what_an_album_on_a_loop_holds_is_left_as_it_was() {
let mut c = Catalog::new();
let id = c.alloc_photo_id();
c.apply(Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 1 }, "p.jpg", "JPEG", 60, 40, "2026-02-01T10:00:00")) }).unwrap();
c.apply(Op::SetRating { id, rating: 3 }).unwrap();
let first = smart(&mut c, "First", Filter::default());
let second = smart(&mut c, "Second", tests(&[("is", first)]));
c.apply(set_rules(first, tests(&[("is", second)]))).unwrap();
let held = |c: &Catalog| [first, second].map(|a| (c.album_photos(a), c.album_count(a)));
let looped = held(&c);
// edits that go through the check, one of them to an album on the loop
c.apply_new(set_rules(first, Filter { rule_set: tests(&[("is", second)]).rule_set, ..Default::default() })).unwrap();
let id = c.alloc_album_id();
c.apply_new(Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", second)]))), ..Album::new(id, "Reads the loop") } }).unwrap();
assert_eq!(held(&c), looped);
}
/// The search for loops walks the albums with its own stack: a ring of thousands of smart albums
/// is found, not overflowed.
#[test]
fn a_very_long_ring_is_refused_without_running_out_of_stack() {
const N: usize = 20_000;
let mut c = Catalog::new();
let ids: Vec<AlbumId> = (0..N).map(|i| smart(&mut c, &format!("S{i}"), Filter::default())).collect();
// each tests the next; the last one is left open
for pair in ids.windows(2) {
c.apply(set_rules(pair[0], tests(&[("is", pair[1])]))).unwrap();
}
let (first, last) = (ids[0], ids[N - 1]);
let e = c.apply_new(set_rules(last, tests(&[("is", first)]))).unwrap_err().to_string();
assert!(e.contains("include itself"), "{e}");
// and what makes no ring goes through
c.apply_new(set_rules(last, rated(5))).unwrap();
}
+25
View File
@@ -262,6 +262,31 @@ fn push_history_is_bounded_and_invertible() {
assert_eq!(c.to_snapshot(), before);
}
/// A photo added with, or given, a whole History (op log replay, undo of a removal) kept every
/// step: only `PushHistory` applied the limit (#2579).
#[test]
fn add_photo_and_set_history_are_bounded_and_invertible() {
let mut c = Catalog::new();
let id = c.alloc_photo_id();
let step = |i: usize| HistoryStep { label: format!("s{i}"), settings: Arc::new(DevelopSettings::default()) };
let mut p = Photo::new(id, Source::Demo { scene: 1 }, "a", "JPEG", 1, 1, "t");
p.history = (0..HISTORY_LIMIT + 5).map(step).collect();
p.history_cursor = Some(10);
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let p = c.photo(id).unwrap();
assert_eq!((p.history.len(), p.history[0].label.as_str()), (HISTORY_LIMIT, "s5"));
assert_eq!(p.history_cursor, Some(5), "the cursor stays on step s10");
let before = c.to_snapshot();
let inv = c.apply(Op::SetHistory { id, history: (0..HISTORY_LIMIT * 2).map(step).collect() }).unwrap();
let p = c.photo(id).unwrap();
assert_eq!(p.history.len(), HISTORY_LIMIT);
assert_eq!(p.history[0].label, format!("s{HISTORY_LIMIT}"));
assert_eq!(p.history_cursor, Some(0), "its step was dropped: the oldest one kept");
c.apply(inv).unwrap();
assert_eq!(c.to_snapshot(), before);
}
#[test]
fn fs_store_roundtrip() {
let dir = std::env::temp_dir().join(format!("lc-journal-{}", std::process::id()));
+51
View File
@@ -195,6 +195,33 @@ fn id_counters_are_moved_past_the_ids_in_use() {
assert!(c.apply(Op::AddPhoto { photo: Box::new(p) }).is_err(), "the id is taken: refused, not overwritten");
}
/// History was bounded only where an edit adds a step, so a snapshot holding more steps kept
/// every one in memory on each load (#2579). The newest are kept and the cursor stays on its step.
#[test]
fn history_beyond_the_limit_is_trimmed_on_load() {
let (mut c, ids) = sound();
let extra = HISTORY_LIMIT * 5;
let step = HistoryStep { label: "s0".into(), settings: std::sync::Arc::new(lightcraft_develop::DevelopSettings::default()) };
c.apply(Op::PushHistory { id: ids[0], step }).unwrap();
c.apply(Op::SetHistoryCursor { id: ids[0], cursor: Some(extra - 3) }).unwrap();
let (loaded, report) = load_edited(&c, |v| {
let history = &mut v["photos"][ids[0].0.to_string()]["history"];
let one = history[0].clone();
*history = (0..extra)
.map(|i| {
let mut s = one.clone();
s["label"] = format!("s{i}").into();
s
})
.collect();
});
let p = loaded.photo(ids[0]).unwrap();
assert_eq!(p.history.len(), HISTORY_LIMIT);
assert_eq!(p.history[0].label, format!("s{}", extra - HISTORY_LIMIT));
assert_eq!(p.history_index().map(|i| p.history[i].label.clone()), Some(format!("s{}", extra - 3)));
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
}
/// A sound catalog loads unchanged.
#[test]
fn a_sound_snapshot_needs_no_repair() {
@@ -218,3 +245,27 @@ fn an_album_filed_under_another_id_gets_its_own() {
assert_eq!((a.id, a.parent), (inner, Some(folder)));
assert_eq!(c.album_children(Some(folder)).iter().map(|a| a.id).collect::<Vec<_>>(), vec![inner]);
}
/// What was worked out from the albums (whether rules may be tested cheapest first) is worked out
/// again when a repair changes the albums.
#[test]
fn a_repair_forgets_what_was_worked_out_from_the_albums() {
let (mut c, _) = sound();
let smart = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..album(smart.0, None, false, vec![]) } }).unwrap();
assert!(!c.keeps_written_order(), "worked out, and remembered");
// damaged outside `apply`: the smart album tests itself, and an album is filed under another id
let rules: Filter =
serde_json::from_value(serde_json::json!({"ruleSet": {"match": "all", "rules": [{"field": "album", "op": "is", "value": smart.0}]}}))
.unwrap();
if let Some(a) = c.albums.get_mut(&smart) {
a.smart = Some(Box::new(rules));
}
let inner = c.albums().find(|a| !a.folder && a.smart.is_none()).unwrap().id;
if let Some(mut a) = c.albums.remove(&inner) {
a.id = AlbumId(900);
c.albums.insert(inner, a);
}
assert!(!c.repair().is_empty());
assert!(c.keeps_written_order(), "the loop the repair left is seen");
}
+365
View File
@@ -0,0 +1,365 @@
//! A rule set is tested cheapest rule first ([`RuleSet::by_cost`]), once per pass; what matches
//! is what testing the rules in the order they were written gives.
//!
//! Scenarios:
//! - Given random libraries (Unicode and Windows paths, nested groups, album rules that test
//! smart albums and missing albums), then every album, query and count gives what the written
//! order gives, for all, any and none.
//! - Given a library where smart albums test themselves (the app refuses to make one; a saved or
//! damaged catalog can hold it, and there the answer can depend on which album is asked first),
//! then the rules are tested as written, so the answers are the written order's, as before.
//! - Given `all[album is <smart album>, <a rule no photo meets>]`, then the smart album is never
//! asked about a photo: the cheap rule ends it first (written first, it ran for every photo).
//! - Given rules in any order, then the saved rules and the order the editor shows are untouched.
use serde_json::json;
use crate::rules::{EVALUATED, WRITTEN_ORDER};
use crate::*;
/// A small generator: the same sequence every run.
struct Rng(u64);
impl Rng {
fn next(&mut self, n: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % n
}
fn pick<'a, T>(&mut self, of: &'a [T]) -> &'a T {
&of[self.next(of.len() as u64) as usize]
}
}
const PATHS: &[&str] = &[
"/Volumes/share/photos/Asie/Japon/Été/IMG_0001.jpg",
"/Volumes/share/photos/ASIE/japon/IMG_0002.JPG",
"C:\\Users\\me\\Pictures\\Ünïcode\\Tokyo\\IMG_0003.jpg",
"/Volumes/share/photos/Straße/İstanbul/IMG_0004.cr2",
"/Volumes/share/photos/東京/渋谷/IMG_0005.jpg",
"/Volumes/share/photos/Asie/Chine/clip.mp4",
"relative/dir/IMG_0007.jpg",
];
const WORDS: &[&str] =
&["asie", "Japon", "été", "ÜNÏCODE", "tokyo", "straße", "i̇stanbul", "東京", "photos\\asie", "photos/Asie/", " ", "", "img_000"];
fn library(rng: &mut Rng) -> (Catalog, Vec<PhotoId>) {
let mut c = Catalog::new();
let ids: Vec<PhotoId> = (0..24)
.map(|i| {
let id = c.alloc_photo_id();
let path = if i == 5 { None } else { Some(rng.pick(PATHS).to_string()) };
let source = path.map_or(Source::Demo { scene: 1 }, |path| Source::File { path });
let name = format!("IMG_{i:04}.{}", ["jpg", "cr2", "mp4"][rng.next(3) as usize]);
let mut p = Photo::new(id, source, &name, "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.rating = rng.next(6) as u8;
p.flag = [Flag::None, Flag::Pick, Flag::Reject][rng.next(3) as usize];
p.label = [None, Some(ColorLabel::Red), Some(ColorLabel::Blue)][rng.next(3) as usize];
p.meta.keywords = (0..rng.next(4)).map(|k| format!("kw{}", k + rng.next(2))).collect();
p.captured = Some(format!("20{}-0{}-1{}T10:00:00", 10 + rng.next(16), 1 + rng.next(9), rng.next(9)));
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
id
})
.collect();
(c, ids)
}
fn leaf(rng: &mut Rng, albums: &[AlbumId]) -> serde_json::Value {
let field = |f: &str, op: &str, v: serde_json::Value| json!({"field": f, "op": op, "value": v});
match rng.next(14) {
0 => field("rating", ["gte", "lte", "is", "gt", "lt"][rng.next(5) as usize], json!(rng.next(6))),
1 => field("flag", ["is", "isNot"][rng.next(2) as usize], json!(["pick", "reject", "none"][rng.next(3) as usize])),
2 => field("label", ["is", "isNot"][rng.next(2) as usize], json!(["red", "blue", "none"][rng.next(3) as usize])),
3 => field("kind", ["is", "isNot"][rng.next(2) as usize], json!(["image", "raw", "video"][rng.next(3) as usize])),
4 => field("keywordCount", ["lte", "gte"][rng.next(2) as usize], json!(rng.next(4))),
5 => field("keywords", ["contains", "notContains", "isEmpty"][rng.next(3) as usize], json!(format!("kw{}", rng.next(3)))),
6 => field("captureDate", ["before", "after"][rng.next(2) as usize], json!(format!("20{}", 10 + rng.next(16)))),
7 | 8 => field("filePath", ["contains", "notContains", "startsWith", "is", "isEmpty"][rng.next(5) as usize], json!(*rng.pick(WORDS))),
9 => field("fileName", "contains", json!(["img_000", ".cr2", "mp4"][rng.next(3) as usize])),
10 => field("text", ["contains", "notContains"][rng.next(2) as usize], json!(*rng.pick(WORDS))),
// an album that may not exist (99) or may be on a loop
_ => {
let album = if rng.next(8) == 0 { AlbumId(99) } else { *rng.pick(albums) };
field("album", ["is", "isNot"][rng.next(2) as usize], json!(album.0))
}
}
}
fn rule_set(rng: &mut Rng, albums: &[AlbumId], depth: u32) -> serde_json::Value {
let rules: Vec<serde_json::Value> = (0..rng.next(5))
.map(|_| if depth < 2 && rng.next(4) == 0 { json!({"group": rule_set(rng, albums, depth + 1)}) } else { leaf(rng, albums) })
.collect();
let mode = ["all", "any", "none"][rng.next(3) as usize];
json!({"match": mode, "rules": rules})
}
fn filter(rules: serde_json::Value) -> Filter {
Filter { rule_set: Some(serde_json::from_value(rules).unwrap()), ..Default::default() }
}
/// What a catalog answers for every album, photo and a few queries.
fn answers(c: &Catalog, albums: &[AlbumId], photos: &[PhotoId], queries: &[Filter]) -> String {
let mut out = String::new();
for a in albums {
let held: Vec<bool> = photos.iter().map(|p| c.album_contains(*a, c.photo(*p).unwrap())).collect();
out += &format!("{a:?} {held:?} {:?} {}\n", c.album_photos(*a), c.album_count(*a));
}
for p in photos {
out += &format!("{p:?} {:?}\n", c.albums_of(*p));
}
for q in queries {
out += &format!("{:?} {}\n", c.query(q, &Sort::default()), c.count(q));
}
out
}
#[test]
fn the_cheapest_first_order_matches_what_the_written_order_matches() {
let chained = same_answers_in_random_libraries(Rng(11), false);
assert!(chained > 20, "the generator makes smart albums that test smart albums: {chained}");
}
#[test]
fn a_library_with_loops_answers_as_written_and_does_not_hang() {
let looping = same_answers_in_random_libraries(Rng(5), true);
assert!(looping > 20, "the generator makes loops: {looping}");
}
/// Albums of random libraries and queries answer the same cheapest first and as written; returns
/// how many smart albums tested a smart album (`loops`: one that leads back to itself).
fn same_answers_in_random_libraries(mut rng: Rng, loops: bool) -> usize {
let mut chained = 0;
for round in 0..150 {
let (mut c, photos) = library(&mut rng);
let plain = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { photos: photos.iter().copied().step_by(3).collect(), ..Album::new(plain, "Plain") } }).unwrap();
let folder = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { folder: true, ..Album::new(folder, "F") } }).unwrap();
let smarts: Vec<AlbumId> = (0..6)
.map(|i| {
let id = c.alloc_album_id();
let parent = (i % 3 == 0).then_some(folder);
c.apply(Op::AddAlbum { album: Album { parent, smart: Some(Box::default()), ..Album::new(id, format!("S{i}")) } }).unwrap();
id
})
.collect();
let albums: Vec<AlbumId> = [plain, folder].into_iter().chain(smarts.iter().copied()).collect();
for (i, s) in smarts.iter().enumerate() {
// (without loops a smart album tests only the albums made before it)
let testable = if loops { &albums[..] } else { &albums[..2 + i] };
let _ = c.apply(Op::SetAlbumRules { id: *s, rules: Box::new(filter(rule_set(&mut rng, testable, 0))) });
}
let queries: Vec<Filter> = (0..4).map(|_| filter(rule_set(&mut rng, &albums, 0))).collect();
// (the copy starts without what the catalog worked out, so each is worked out under its own order)
let written = c.clone();
let ordered_answers = answers(&c, &albums, &photos, &queries);
WRITTEN_ORDER.set(true);
let written_answers = answers(&written, &albums, &photos, &queries);
WRITTEN_ORDER.set(false);
assert_eq!(ordered_answers, written_answers, "round {round}: {}", c.to_snapshot());
let reaching = |s: &AlbumId| {
smarts.iter().any(|t| if loops { c.album_reaches(*t, *s) && c.album_reaches(*s, *t) } else { t != s && c.album_reaches(*s, *t) })
};
chained += smarts.iter().filter(|s| reaching(s)).count();
assert_eq!(c.keeps_written_order(), smarts.iter().any(|s| c.album_reaches(*s, *s)));
assert!(loops || !c.keeps_written_order(), "round {round}: {}", c.to_snapshot());
}
chained
}
#[test]
fn a_cheap_rule_that_fails_ends_the_test_before_a_smart_album_runs() {
let mut c = Catalog::new();
let photos: Vec<PhotoId> = (0..20)
.map(|i| {
let id = c.alloc_photo_id();
let p = Photo::new(id, Source::File { path: format!("/a/b/{i}.jpg") }, &format!("{i}.jpg"), "JPEG", 6000, 4000, "2026-09-30T10:00:00");
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
id
})
.collect();
let inner = c.alloc_album_id();
c.apply(Op::AddAlbum {
album: Album {
smart: Some(Box::new(filter(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/a/"}]})))),
..Album::new(inner, "Inner")
},
})
.unwrap();
let rules = |first: serde_json::Value, second: serde_json::Value| json!({"match": "all", "rules": [first, second]});
let album = json!({"field": "album", "op": "is", "value": inner.0});
// no photo is rated 6 stars (a rating is at most 5)
let never = json!({"field": "rating", "op": "gte", "value": 6});
let outer = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(filter(rules(album.clone(), never.clone())))), ..Album::new(outer, "Outer") } })
.unwrap();
EVALUATED.set(0);
assert_eq!(c.album_count(outer), 0);
// (the outer album's own rules count as one run for each photo; its inner album must run for none)
assert_eq!(EVALUATED.get(), photos.len(), "only the outer album ran, once per photo");
// the same photos whichever way round the rules are written
let swapped = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(filter(rules(never, album)))), ..Album::new(swapped, "Swapped") } }).unwrap();
assert_eq!((c.album_count(swapped), c.album_photos(swapped)), (0, vec![]));
}
#[test]
fn rules_are_ordered_by_cost_without_touching_the_saved_ones() {
let mut c = Catalog::new();
let plain = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album::new(plain, "Plain") }).unwrap();
let smart = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(smart, "Smart") } }).unwrap();
let written: RuleSet = serde_json::from_value(json!({"match": "all", "rules": [
{"field": "album", "op": "is", "value": smart.0},
{"field": "filePath", "op": "contains", "value": "x"},
{"group": {"match": "any", "rules": [
{"field": "album", "op": "isNot", "value": smart.0},
{"field": "rating", "op": "gte", "value": 3}]}},
{"field": "keywords", "op": "contains", "value": "k"},
{"field": "album", "op": "is", "value": plain.0},
{"field": "rating", "op": "gte", "value": 3},
{"field": "album", "op": "is", "value": 99},
{"field": "flag", "op": "is", "value": "pick"}]}))
.unwrap();
let before = written.clone();
let ordered = written.by_cost(&c);
assert_eq!(written, before, "the saved rules stay as the user wrote them");
let names: Vec<String> = ordered
.rules
.iter()
.map(|r| match r {
Rule::Group { .. } => "group".to_string(),
Rule::Field { field, op, .. } => format!("{field} {op}"),
})
.collect();
// scalars (a missing album is false at once), then lists and a plain album, then text, then
// smart albums and the group that holds one; equals keep the written order
assert_eq!(names, ["rating gte", "album is", "flag is", "keywords contains", "album is", "filePath contains", "album is", "group"]);
let inner: Vec<&str> = match ordered.rules.get(7) {
Some(Rule::Group { group }) => group.rules.iter().map(|r| if let Rule::Field { field, .. } = r { field.as_str() } else { "group" }).collect(),
_ => Vec::new(),
};
assert_eq!(inner, ["rating", "album"], "nested groups are ordered too");
}
/// B = all[album is C], C = all[album isNot B], A = all[any[album is C, flag is pick], album is B]:
/// asked in the order the rules are written, a picked photo is not in A; asked cheapest first
/// (the flag, then the albums) it was. With a loop the order stays as written.
#[test]
fn smart_albums_that_test_each_other_keep_the_written_order() {
let mut c = Catalog::new();
let mut p = Photo::new(c.alloc_photo_id(), Source::File { path: "/a/1.jpg".into() }, "1.jpg", "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.flag = Flag::Pick;
let photo = p.id;
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let ids: Vec<AlbumId> = ["A", "B", "C"]
.iter()
.map(|name| {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(id, *name) } }).unwrap();
id
})
.collect();
let (a, b, cc) = (ids[0], ids[1], ids[2]);
let album = |op: &str, id: AlbumId| json!({"field": "album", "op": op, "value": id.0});
let set = |c: &mut Catalog, id: AlbumId, rules: serde_json::Value| c.apply(Op::SetAlbumRules { id, rules: Box::new(filter(rules)) }).unwrap();
set(&mut c, b, json!({"match": "all", "rules": [album("is", cc)]}));
set(&mut c, cc, json!({"match": "all", "rules": [album("isNot", b)]}));
set(
&mut c,
a,
json!({"match": "all", "rules": [
{"group": {"match": "any", "rules": [album("is", cc), {"field": "flag", "op": "is", "value": "pick"}]}},
album("is", b)]}),
);
let written = c.clone();
let ask = |c: &Catalog| {
ids.iter().map(|id| (c.album_contains(*id, c.photo(photo).unwrap()), c.album_photos(*id), c.album_count(*id))).collect::<Vec<_>>()
};
WRITTEN_ORDER.set(true);
let as_written = ask(&written);
WRITTEN_ORDER.set(false);
assert!(c.keeps_written_order());
assert_eq!(ask(&c), as_written);
}
/// A = all[any[album is D1, flag is pick], album is W], D1 tests D2 … D30, D30 tests W, W tests Z,
/// Z = rating ≥ 0: asked from A, the chain is cut by the depth limit, and asked cheapest first (the
/// flag, then the albums) the cut falls elsewhere. Chains that long keep the written order.
#[test]
fn a_chain_as_deep_as_the_limit_keeps_the_written_order() {
let mut c = Catalog::new();
let mut p = Photo::new(c.alloc_photo_id(), Source::File { path: "/a/1.jpg".into() }, "1.jpg", "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.flag = Flag::Pick;
p.rating = 0; // (Z, rating at least 0, holds for it)
let photo = p.id;
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let new_smart = |c: &mut Catalog, name: &str| {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(id, name) } }).unwrap();
id
};
let a = new_smart(&mut c, "A");
let chain: Vec<AlbumId> = (1..=30).map(|i| new_smart(&mut c, &format!("D{i}"))).collect();
let (w, z) = (new_smart(&mut c, "W"), new_smart(&mut c, "Z"));
let album = |id: AlbumId| json!({"field": "album", "op": "is", "value": id.0});
let set = |c: &mut Catalog, id: AlbumId, rules: serde_json::Value| c.apply(Op::SetAlbumRules { id, rules: Box::new(filter(rules)) }).unwrap();
set(
&mut c,
a,
json!({"match": "all", "rules": [{"group": {"match": "any", "rules": [album(chain[0]), {"field": "flag", "op": "is", "value": "pick"}]}}, album(w)]}),
);
for pair in chain.windows(2) {
set(&mut c, pair[0], json!({"match": "all", "rules": [album(pair[1])]}));
}
set(&mut c, chain[29], json!({"match": "all", "rules": [album(w)]}));
set(&mut c, w, json!({"match": "all", "rules": [album(z)]}));
set(&mut c, z, json!({"match": "all", "rules": [{"field": "rating", "op": "gte", "value": 0}]}));
let written = c.clone();
let ask = |c: &Catalog| [a, w, z, chain[0]].map(|id| (c.album_contains(id, c.photo(photo).unwrap()), c.album_photos(id), c.album_count(id)));
WRITTEN_ORDER.set(true);
let as_written = ask(&written);
// (the expected answers, written down: the same evaluator gives both sides below, so a
// regression that lets the 33rd album in would otherwise change both alike)
assert_eq!(as_written.each_ref().map(|answer| answer.0), [false, true, true, true], "the depth limit cuts the chain only while A is asked");
WRITTEN_ORDER.set(false);
assert!(c.keeps_written_order());
assert_eq!(ask(&c), as_written);
}
/// What was worked out from the albums (whether rules may be tested cheapest first) is worked out
/// again after an album is added or removed: 31 smart albums in a chain are fine, a 32nd on top of
/// it reaches the depth limit (the written order from then on), and taking it away lifts that.
#[test]
fn adding_or_removing_an_album_forgets_whether_the_rules_may_be_reordered() {
let mut c = Catalog::new();
let mut p = Photo::new(c.alloc_photo_id(), Source::File { path: "/a/1.jpg".into() }, "1.jpg", "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.flag = Flag::Pick;
let photo = p.id;
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let album = |id: AlbumId| json!({"field": "album", "op": "is", "value": id.0});
let smart = |c: &mut Catalog, name: &str, rules: serde_json::Value| {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(filter(rules))), ..Album::new(id, name) } }).unwrap();
id
};
// S1 tests S2 … S30 tests S31, which tests nothing: 31 albums
let mut chain = vec![smart(&mut c, "S31", json!({"match": "all", "rules": []}))];
for i in (1..=30).rev() {
let next = chain[chain.len() - 1];
chain.push(smart(&mut c, &format!("S{i}"), json!({"match": "all", "rules": [album(next)]})));
}
let bottom = chain[0];
let top = chain[30];
let ask = |c: &Catalog| [top, bottom].map(|id| (c.album_contains(id, c.photo(photo).unwrap()), c.album_photos(id), c.album_count(id)));
assert!(!c.keeps_written_order(), "31 albums in a chain are under the limit (worked out, and remembered)");
let before = ask(&c);
let head = smart(&mut c, "S0", json!({"match": "all", "rules": [album(top)]}));
assert!(c.keeps_written_order(), "a 32nd album on top of the chain reaches the depth limit");
assert_eq!(c.clone().keeps_written_order(), c.keeps_written_order(), "as a catalog that worked it out afresh");
assert_eq!(ask(&c), ask(&c.clone()));
c.apply(Op::RemoveAlbum { id: head }).unwrap();
assert!(!c.keeps_written_order(), "without it the chain is under the limit again");
assert_eq!(c.clone().keeps_written_order(), c.keeps_written_order());
assert_eq!(ask(&c), before);
}
+59
View File
@@ -0,0 +1,59 @@
//! Heap blocks a smart album's `filePath` rules allocate per photo, measured with dhat's testing mode. A rule over
//! a non-ASCII path or text (`crates/catalog/src/rules.rs`, `file_path_matches`) used to build two lower-cased
//! strings for every photo it was asked about; a large library asks it for every photo of every smart album, so
//! it compares in place. One test per binary (dhat's profiler is global).
use lightcraft_catalog::{Catalog, Photo, PhotoId, RuleSet, Source};
use serde_json::json;
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
fn photo(id: u64, path: &str) -> Photo {
Photo::new(PhotoId(id), Source::File { path: path.to_string() }, "IMG_0001.JPG", "JPG", 6000, 4000, "2026-09-20T10:00:00")
}
fn rule_set(op: &str, value: &str) -> RuleSet {
serde_json::from_value(json!({"rules": [{"field": "filePath", "op": op, "value": value}]})).unwrap()
}
#[test]
fn a_file_path_rule_allocates_nothing_per_photo() {
let cat = Catalog::new();
let photos: Vec<Photo> = ["/Volumes/tokyo/Фото/Éclair/Straße/ÜBER_2026.JPG", "D:\\日本語\\İstanbul\\IMG_0001.jpg", "/srv/plain/ascii/path.jpg"]
.iter()
.zip(1u64..)
.map(|(p, i)| photo(i, p))
.collect();
let rules: Vec<RuleSet> = [
("contains", "éCLAIR"),
("contains", "tokyo"),
("notContains", "ÜBER"),
("is", "/srv/plain/ascii/path.jpg"),
("isNot", "straße"),
("startsWith", "\\Volumes\\TOKYO\\ФОТО"),
("endsWith", ".JPG"),
("isEmpty", ""),
("isNotEmpty", ""),
]
.iter()
.map(|(op, v)| rule_set(op, v))
.collect();
// warm anything lazily built (the clock, thread locals) before counting
let expected: Vec<Vec<bool>> = rules.iter().map(|r| photos.iter().map(|p| r.matches(p, &cat)).collect()).collect();
let _profiler = dhat::Profiler::builder().testing().build();
let before = dhat::HeapStats::get().total_blocks;
let mut hits = 0usize;
for _ in 0..100 {
for (r, want) in rules.iter().zip(&expected) {
for (p, w) in photos.iter().zip(want) {
let got = r.matches(p, &cat);
assert_eq!(got, *w);
hits += usize::from(got);
}
}
}
let blocks = dhat::HeapStats::get().total_blocks - before;
assert!(hits > 0, "the rules matched nothing: the test measures nothing");
assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len());
}
+1 -1
View File
@@ -46,7 +46,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d
| Format | Decode | Encode | Notes |
|---|---|---|---|
| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2, multi-chunk), Adobe APP14, MPF previews |
| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews |
| PNG | yes, 1–16-bit, palette, tRNS, interlaced | 8/16-bit, gray/GA/RGB/RGBA | iCCP, eXIf, iTXt XMP; sRGB/cICP/cHRM/gAMA honoured when no ICC |
| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `lightcraft-tiff`) |
| WebP | lossy + lossless, alpha, first frame of animations | lossless only | ICCP/EXIF/XMP chunks |
+6 -4
View File
@@ -78,6 +78,8 @@ pub(crate) struct Raw {
#[derive(Default)]
pub(crate) struct Meta {
pub icc: Option<Vec<u8>>,
/// An ICC profile was declared by the container but its sequence was invalid.
pub icc_invalid: bool,
pub exif: Option<Vec<u8>>,
pub xmp: Option<String>,
/// Orientation from the container itself (e.g. TIFF tag); EXIF blob is consulted otherwise.
@@ -120,7 +122,7 @@ pub(crate) fn finish(format: Format, raw: Raw, meta: Meta, source_dims: (u32, u3
let (image, space) = if let Some(space) = meta.already_linear.clone() {
(to_rgb_passthrough(&raw, ch), space)
} else if raw.model == Model::Cmyk {
cmyk(&raw, ch, meta.icc.as_deref(), parsed_icc.as_ref())
cmyk(&raw, ch, meta.icc.as_deref(), parsed_icc.as_ref(), meta.icc_invalid)
} else {
rgb_or_gray(&raw, ch, &meta, parsed_icc.as_ref(), float)
};
@@ -299,7 +301,7 @@ fn rgb_or_gray(raw: &Raw, ch: usize, meta: &Meta, info: Option<&icc::IccInfo>, f
_ => {}
}
}
if meta.icc.is_some() {
if meta.icc.is_some() || meta.icc_invalid {
// Present but unusable (malformed, mismatched model, CMS failure): assume sRGB.
let s = SourceSpace::named(NamedSpace::Srgb, SpaceOrigin::IccUnsupported);
let t = NamedSpace::Srgb.trc();
@@ -323,7 +325,7 @@ fn rgb_or_gray(raw: &Raw, ch: usize, meta: &Meta, info: Option<&icc::IccInfo>, f
(linearize(raw, ch, &t), s)
}
fn cmyk(raw: &Raw, ch: usize, icc_bytes: Option<&[u8]>, info: Option<&icc::IccInfo>) -> (Rgb32f, SourceSpace) {
fn cmyk(raw: &Raw, ch: usize, icc_bytes: Option<&[u8]>, info: Option<&icc::IccInfo>, icc_invalid: bool) -> (Rgb32f, SourceSpace) {
let samples = device_samples(raw, ch, 4);
if let (Some(bytes), Some(info)) = (icc_bytes, info)
&& info.model == IccColorModel::Cmyk
@@ -343,6 +345,6 @@ fn cmyk(raw: &Raw, ch: usize, icc_bytes: Option<&[u8]>, info: Option<&icc::IccIn
[(1.0 - c[0]) * k, (1.0 - c[1]) * k, (1.0 - c[2]) * k].map(lightcraft_color::transfer::srgb_to_linear)
})
.collect();
let origin = if icc_bytes.is_some() { SpaceOrigin::IccUnsupported } else { SpaceOrigin::Naive };
let origin = if icc_bytes.is_some() || icc_invalid { SpaceOrigin::IccUnsupported } else { SpaceOrigin::Naive };
(from_vec(raw.width, raw.height, px), SourceSpace::named(NamedSpace::Srgb, origin))
}
+222 -12
View File
@@ -24,6 +24,8 @@ pub(crate) struct Markers {
pub exif_offset: usize,
pub xmp: Option<String>,
pub icc: Option<Vec<u8>>,
/// An ICC_PROFILE APP2 segment was present but its sequence was invalid.
pub icc_invalid: bool,
pub adobe_transform: Option<u8>,
/// Offset of the MPF TIFF header within the file and its bytes.
pub mpf: Option<(usize, Vec<u8>)>,
@@ -45,7 +47,8 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
return None;
}
let mut m = Markers::default();
let mut icc_chunks: Vec<(u8, &[u8])> = Vec::new();
let mut icc_chunks: [Option<&[u8]>; 255] = [None; 255];
let mut icc_total = None;
let mut p = 2;
while p + 4 <= b.len() {
if b[p] != 0xFF {
@@ -73,9 +76,11 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
if len < 2 {
return None;
}
let start = p + 4;
let end = (p + 2 + len).min(b.len());
let seg = &b[start..end];
let start = p.checked_add(4)?;
let declared_end = p.checked_add(2)?.checked_add(len)?;
let complete = declared_end <= b.len();
let end = declared_end.min(b.len());
let seg = b.get(start..end)?;
match marker {
0xC0..=0xCF if marker != 0xC4 && marker != 0xC8 && marker != 0xCC && seg.len() >= 6 && m.components == 0 => {
m.precision = seg[0];
@@ -96,8 +101,30 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
}
}
0xE2 => {
if seg.starts_with(b"ICC_PROFILE\0") && seg.len() >= 14 {
icc_chunks.push((seg[12], &seg[14..]));
if seg.starts_with(b"ICC_PROFILE\0") {
if !complete || seg.len() < 14 {
m.icc_invalid = true;
} else if let (Some(&sequence), Some(&total)) = (seg.get(12), seg.get(13)) {
if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) {
m.icc_invalid = true;
} else {
icc_total = Some(total);
let Some(slot) = icc_chunks.get_mut(usize::from(sequence - 1)) else {
m.icc_invalid = true;
p = declared_end;
continue;
};
if slot.is_some() {
m.icc_invalid = true;
} else if let Some(data) = seg.get(14..) {
*slot = Some(data);
} else {
m.icc_invalid = true;
}
}
} else {
m.icc_invalid = true;
}
} else if seg.starts_with(b"MPF\0") && m.mpf.is_none() {
m.mpf = Some((start + 4, seg[4..].to_vec()));
} else if let Some(p) = seg.strip_prefix(crate::gainmap::ISO_URN)
@@ -111,11 +138,32 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
}
_ => {}
}
p += 2 + len;
p = declared_end;
}
if !icc_chunks.is_empty() {
icc_chunks.sort_by_key(|c| c.0);
m.icc = Some(icc_chunks.iter().flat_map(|c| c.1.iter().copied()).collect());
if let Some(total) = icc_total {
let mut profile_len = 0usize;
for chunk in icc_chunks.iter().take(usize::from(total)) {
let Some(bytes) = chunk else {
m.icc_invalid = true;
break;
};
let Some(next_len) = profile_len.checked_add(bytes.len()) else {
m.icc_invalid = true;
break;
};
profile_len = next_len;
}
let maximum_len = usize::from(total).checked_mul(65_519);
if maximum_len.is_none_or(|maximum| profile_len > maximum) {
m.icc_invalid = true;
}
if !m.icc_invalid {
let mut profile = Vec::with_capacity(profile_len);
for bytes in icc_chunks.iter().take(usize::from(total)).flatten() {
profile.extend_from_slice(bytes);
}
m.icc = Some(profile);
}
}
Some(m)
}
@@ -131,6 +179,7 @@ const MAX_APP1: u32 = 128;
/// type or component count, or when its markers don't run to an end-of-image marker after the
/// image data (a truncated file). Damage *inside* the entropy-coded data can't be seen this way.
pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> {
let bytes = &*without_sef_trailer(bytes);
let m = parse_markers(bytes).ok_or_else(|| Error::Malformed(F, "missing SOI".into()))?;
if m.components == 0 {
return Err(Error::Malformed(F, "no frame header".into()));
@@ -177,7 +226,62 @@ fn reaches_eoi(b: &[u8]) -> bool {
}
}
/// A Samsung panorama whose scan runs straight into its SEF trailer, with no EOI marker (issue
/// #3350), as the file it stands for: the bytes before the trailer's earliest data block plus an
/// EOI. Every other file, a genuinely truncated one included, is borrowed unchanged.
fn without_sef_trailer(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
use std::borrow::Cow;
// The trailer is checked first: it reads only the file's last bytes, not the scan data.
let Some(image) = sef_image_end(bytes).and_then(|end| bytes.get(..end)) else { return Cow::Borrowed(bytes) };
// the image before the trailer: an FF D9 inside the SEF data doesn't end the scan
if reaches_eoi(image) {
return Cow::Borrowed(bytes);
}
let mut fixed = Vec::with_capacity(image.len().saturating_add(2));
fixed.extend_from_slice(image);
fixed.extend_from_slice(&[0xFF, 0xD9]);
// The cut must leave the scan data, not a segment or anything before the first scan, open.
let in_scan = parse_markers(&fixed).is_some_and(|m| m.first_scan_components > 0) && reaches_eoi(&fixed);
if in_scan { Cow::Owned(fixed) } else { Cow::Borrowed(bytes) }
}
/// Where the image ends in a file carrying a Samsung SEF trailer: the start of its earliest data
/// block. The trailer is the file's last bytes: `SEFH`, a u32 LE version and entry count, 12-byte
/// entries (u16 padding, u16 type, u32 LE offset of the block back from `SEFH`, u32 LE length),
/// then the u32 LE length of that directory and `SEFT`. Each block starts with the same padding
/// and type as its entry. `None` unless every entry's block is nonempty, starts with its entry's
/// type and lies inside the file, before `SEFH`.
fn sef_image_end(b: &[u8]) -> Option<usize> {
let le32 = |at: usize| b.get(at..at.checked_add(4)?)?.try_into().ok().map(|v| u32::from_le_bytes(v) as usize);
let tail = b.len().checked_sub(8)?;
if b.get(tail.checked_add(4)?..)? != b"SEFT" {
return None;
}
let dir = tail.checked_sub(le32(tail)?)?;
if b.get(dir..dir.checked_add(4)?)? != b"SEFH" {
return None;
}
let count = le32(dir.checked_add(8)?)?;
let entries = dir.checked_add(12)?;
if count == 0 || count > tail.checked_sub(entries)? / 12 {
return None;
}
let mut start = dir;
for i in 0..count {
let entry = entries.checked_add(i.checked_mul(12)?)?;
let block = dir.checked_sub(le32(entry.checked_add(4)?)?)?;
let len = le32(entry.checked_add(8)?)?;
let kind = |at: usize| b.get(at.checked_add(2)?..at.checked_add(4)?);
if len < 4 || block.checked_add(len)? > dir || kind(block)? != kind(entry)? {
return None;
}
start = start.min(block);
}
Some(start)
}
pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback: Option<crate::NamedSpace>) -> Result<Decoded> {
let bytes = &*without_sef_trailer(bytes);
let m = parse_markers(bytes).ok_or_else(|| Error::Malformed(F, "missing SOI".into()))?;
if m.components == 0 {
return Err(Error::Malformed(F, "no frame header".into()));
@@ -201,8 +305,10 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
};
// A raw container may carry the colour declaration of an otherwise untagged preview.
// Apply it before linearization/resizing; existing JPEG metadata always wins.
let hint = fallback.filter(|_| m.icc.is_none() && m.exif.is_none()).map(|space| crate::SourceSpace::named(space, crate::SpaceOrigin::Container));
let meta = Meta { icc: m.icc, exif: m.exif, xmp: m.xmp, hint, ..Default::default() };
let hint = fallback
.filter(|_| m.icc.is_none() && !m.icc_invalid && m.exif.is_none())
.map(|space| crate::SourceSpace::named(space, crate::SpaceOrigin::Container));
let meta = Meta { icc: m.icc, icc_invalid: m.icc_invalid, exif: m.exif, xmp: m.xmp, hint, ..Default::default() };
finish(F, raw, meta, (m.width, m.height), opts)
}
@@ -450,6 +556,110 @@ mod tests {
assert!(crate::decode_jpeg_with_fallback(b"bad JPEG", DecodeOptions::default(), NamedSpace::AdobeRgb).is_err());
}
fn app2_icc(sequence: u8, total: u8, data: &[u8]) -> Vec<u8> {
let mut payload = b"ICC_PROFILE\0".to_vec();
payload.extend_from_slice(&[sequence, total]);
payload.extend_from_slice(data);
let mut segment = vec![0xff, 0xe2];
segment.extend_from_slice(&u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
segment.extend_from_slice(&payload);
segment
}
fn jpeg_with_icc_chunks(chunks: &[Vec<u8>]) -> Vec<u8> {
use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let pixels = [180, 60, 40, 180, 60, 40, 180, 60, 40, 180, 60, 40];
let base = encode_jpeg(&EncodeImage::new(2, 2, 3, Samples::U8(&pixels)), 100, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
let mut jpeg = base.get(..2).unwrap_or_default().to_vec();
for chunk in chunks {
jpeg.extend_from_slice(chunk);
}
jpeg.extend_from_slice(base.get(2..).unwrap_or_default());
jpeg
}
#[test]
fn jpeg_icc_accepts_reordered_chunks_and_preserves_pixels() {
use crate::{NamedSpace, SpaceOrigin, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let (first, second) = profile.split_at(profile.len() / 2);
let single = jpeg_with_icc_chunks(&[app2_icc(1, 1, &profile)]);
let reordered = jpeg_with_icc_chunks(&[app2_icc(2, 2, second), app2_icc(1, 2, first)]);
let one = crate::decode(&single, DecodeOptions::default()).unwrap();
let two = crate::decode(&reordered, DecodeOptions::default()).unwrap();
assert_eq!(one.icc.as_deref(), Some(profile.as_slice()));
assert_eq!(two.icc.as_deref(), Some(profile.as_slice()));
assert!(!parse_markers(&reordered).unwrap().icc_invalid);
assert_eq!(one.space, two.space);
assert_eq!(two.space.origin, SpaceOrigin::IccMatrixTrc);
let (a, b) = (one.to_working(), two.to_working());
assert_eq!(a.data.len(), b.data.len());
for (left, right) in a.data.iter().zip(&b.data) {
assert!(left.iter().zip(right).all(|(x, y)| (x - y).abs() < 0.00001), "{left:?} != {right:?}");
}
}
#[test]
fn jpeg_icc_rejects_incoherent_chunks_and_uses_unsupported_fallback() {
use crate::{NamedSpace, SpaceOrigin, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let (first, second) = profile.split_at(profile.len() / 2);
let base = jpeg_with_icc_chunks(&[]);
let reference = crate::decode(&base, DecodeOptions::default()).unwrap();
let cases = [
("missing", vec![app2_icc(1, 2, &profile)]),
("duplicate", vec![app2_icc(1, 2, first), app2_icc(1, 2, second)]),
("zero sequence", vec![app2_icc(0, 1, &profile)]),
("zero total", vec![app2_icc(1, 0, &profile)]),
("out of range", vec![app2_icc(2, 1, &profile)]),
("gap", vec![app2_icc(1, 3, first), app2_icc(3, 3, second)]),
("inconsistent totals", vec![app2_icc(1, 2, first), app2_icc(2, 3, second)]),
("short header", {
let mut segment = vec![0xff, 0xe2];
segment.extend_from_slice(&15u16.to_be_bytes());
segment.extend_from_slice(b"ICC_PROFILE\0\x01");
vec![segment]
}),
];
for (name, chunks) in cases {
let jpeg = jpeg_with_icc_chunks(&chunks);
let markers = parse_markers(&jpeg).unwrap();
let decoded = crate::decode(&jpeg, DecodeOptions::default()).unwrap();
assert_eq!(decoded.space.origin, SpaceOrigin::IccUnsupported, "{name}: invalid profile must not be applied");
assert!(markers.icc.is_none(), "{name}: invalid ICC must not be assembled");
assert!(markers.icc_invalid, "{name}: invalid ICC presence must be retained");
assert_eq!(decoded.icc, None, "{name}: invalid ICC bytes must not escape decode");
assert_eq!(decoded.space.origin, SpaceOrigin::IccUnsupported, "{name}");
assert_eq!(decoded.space.named, Some(NamedSpace::Srgb), "{name}");
assert_eq!(decoded.to_working(), reference.to_working(), "{name}: fallback pixels");
}
}
#[test]
fn jpeg_icc_invalid_sequence_prevents_raw_colour_hint() {
use crate::{NamedSpace, SpaceOrigin, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let jpeg = jpeg_with_icc_chunks(&[app2_icc(1, 2, &profile)]);
let decoded = crate::decode_jpeg_with_fallback(&jpeg, DecodeOptions::default(), NamedSpace::AdobeRgb).unwrap();
assert_eq!(decoded.space.origin, SpaceOrigin::IccUnsupported);
assert_eq!(decoded.space.named, Some(NamedSpace::Srgb));
}
#[test]
fn jpeg_icc_rejects_truncated_app2_segment() {
use crate::{NamedSpace, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let mut segment = app2_icc(1, 1, &profile);
let declared = u16::from_be_bytes([segment[2], segment[3]]).saturating_add(1);
segment[2..4].copy_from_slice(&declared.to_be_bytes());
let mut jpeg = vec![0xff, 0xd8];
jpeg.extend_from_slice(&segment);
let markers = parse_markers(&jpeg).unwrap();
assert!(markers.icc.is_none());
assert!(markers.icc_invalid);
}
#[test]
fn scaled_request_covers() {
assert_eq!(scaled_request(6000, 4000, 256, 256), (256, 171));
+1
View File
@@ -207,6 +207,7 @@ pub fn read_header_unguarded(bytes: &[u8], format: Format) -> Result<Header> {
Format::WebP => webp::header(bytes)?,
Format::Psd => psd::header(bytes)?,
Format::Heif => heif::header(bytes)?,
Format::Gif | Format::Bmp => other::header(bytes, format)?,
// rare here (or, for JPEG XL, without a header reader yet): a small decode, as before
_ => {
let d = decode_unguarded(bytes, format, &DecodeOptions::fit(64, 64))?;
+333 -1
View File
@@ -4,6 +4,291 @@ use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::{DecodeOptions, Decoded, Error, Format, Result};
use image::{DynamicImage, ImageDecoder};
/// Canvases up to this many pixels are still decoded by [`header`] (at most 16 MB), so a truncated
/// small file is refused at import as before.
const HEADER_DECODE_MAX_PIXELS: u64 = 4_000_000;
/// Stored size for the import probe (issue #2553). The probe used to decode these in full, and a
/// few-dozen-byte file declaring a gigapixel canvas allocated gigabytes. The size now comes from the
/// header and must be one the file's bytes can fill; only a canvas small enough to be cheap is
/// decoded (to catch truncation). Orientation is always 1: neither format carries EXIF here.
pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> {
let err = |e: image::ImageError| Error::Malformed(format, e.to_string());
let cursor = std::io::Cursor::new(bytes);
let (w, h) = match format {
Format::Gif => image::codecs::gif::GifDecoder::new(cursor).map_err(err)?.dimensions(),
Format::Bmp => image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?.dimensions(),
_ => return Err(Error::Unsupported(format, "not handled by this decoder")),
};
if w == 0 || h == 0 {
return Err(Error::Malformed(format, "zero dimension".into()));
}
check_fillable(format, bytes, w, h)?;
if u64::from(w).saturating_mul(u64::from(h)) <= HEADER_DECODE_MAX_PIXELS {
let d = decode(bytes, format, &DecodeOptions::fit(64, 64))?;
return Ok((d.source_width, d.source_height, d.orientation));
}
Ok((w, h, 1))
}
/// The decoder's allocation limit: the RGBA buffer of the largest image `opts` allows. It bounds the
/// decoders' own frame buffers only: `DynamicImage::from_decoder` allocates the canvas without
/// consulting it, so the canvas is bounded by `check_size` and [`check_fillable`] beforehand (a
/// mostly blank one by [`SPARSE_MAX_PIXELS`]).
fn limits(opts: &DecodeOptions) -> image::Limits {
let mut l = image::Limits::default();
l.max_alloc = Some(opts.max_pixels.saturating_mul(4));
l
}
/// The largest canvas allowed that the file's pixel data leaves mostly blank: a GIF screen its
/// first frame's codes don't cover, or an RLE BMP whose runs don't. Its decode still allocates the
/// whole canvas (16 MB at this size), so it is held well below `max_pixels`.
const SPARSE_MAX_PIXELS: u64 = 4_000_000;
/// Refuses a canvas larger than the file's pixel data can describe, before the decoder allocates it
/// (issue #2553). Coverage is measured from the pixel data itself, never from the file's length, so
/// padding (comments, bytes after an end code, trailing bytes) covers nothing:
///
/// - Uncompressed BMP rows are read in full, padding included, from the offset the file header
/// gives, so the data must hold every row: anything shorter fails to decode once the canvas is
/// allocated, and is refused here instead.
/// - An RLE BMP covers the pixels its runs and absolute blocks draw, as the decoder paints them; an
/// end-of-row, end-of-bitmap or delta code leaves the rest blank.
/// - A GIF covers the pixels its first frame's LZW codes draw up to the end code. A code expands to
/// at most 4096 pixels and takes 12 bits once the table holds that many (fewer bits only while its
/// strings are shorter), so a frame larger than 2731 pixels per byte of LZW data is refused
/// outright. The screen around the frame may be larger, and is blank there.
///
/// Canvases the data leaves mostly blank are limited to [`SPARSE_MAX_PIXELS`].
fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> {
let area = |w: u32, h: u32| u64::from(w).saturating_mul(u64::from(h));
let canvas = area(w, h);
// the pixels the file's data can cover
let covered = match format {
Format::Gif => {
// without a frame there is nothing to decode, and nothing to bound the canvas by
let Some(frame) = gif_first_frame(bytes) else {
return Err(Error::Malformed(format, "no readable first frame".into()));
};
let (fw, fh, len) = (frame.width, frame.height, frame.data_len);
if area(fw, fh) > (len as u64).saturating_mul(2_731) {
return Err(Error::Malformed(format, format!("a {fw} × {fh} frame is far larger than its {len} bytes of pixel data can hold")));
}
gif_frame_pixels(bytes, frame.codes, area(fw, fh))
}
_ => match bmp_layout(bytes) {
BmpLayout::Rle { offset, rle4 } => bmp_rle_pixels(bytes, offset, rle4, w, h),
BmpLayout::Rows { offset, bits } => {
let row = u64::from(w).saturating_mul(u64::from(bits)).div_ceil(32).saturating_mul(4);
let needed = row.saturating_mul(u64::from(h));
let held = bytes.len().saturating_sub(offset) as u64;
if held < needed {
return Err(Error::Malformed(
format,
format!("a {w} × {h} canvas is larger than its {held} bytes of pixel data can hold ({needed} needed)"),
));
}
canvas
}
},
};
if canvas > covered && canvas > SPARSE_MAX_PIXELS {
return Err(Error::Malformed(
format,
format!(
"a {w} × {h} canvas is mostly blank (its pixel data covers at most {covered} pixels), and such pictures are limited to {SPARSE_MAX_PIXELS} pixels"
),
));
}
Ok(())
}
/// Where a BMP's pixels start (the offset in its file header, which the decoder seeks to) and how
/// they are stored.
enum BmpLayout {
/// RLE8 or RLE4 commands.
Rle { offset: usize, rle4: bool },
/// Rows of `bits` per pixel, each padded to 4 bytes.
Rows { offset: usize, bits: u16 },
}
/// The layout the decoder reads, from the file header and the bitmap header: a 12-byte core header
/// (bits per pixel at 24, never compressed) or a 40-byte or larger one (bits at 28, compression at
/// 30). Fields the decoder would have refused are read as 1 bit per pixel at offset 0, the most
/// lenient layout.
fn bmp_layout(bytes: &[u8]) -> BmpLayout {
let u16_at = |i: usize| bytes.get(i..i.checked_add(2)?).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let u32_at = |i: usize| bytes.get(i..i.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
let offset = u32_at(10).and_then(|o| usize::try_from(o).ok()).unwrap_or(0);
let (bits, compression) = match u32_at(14) {
Some(12) => (u16_at(24), Some(0)),
_ => (u16_at(28), u32_at(30)),
};
match compression {
Some(1) => BmpLayout::Rle { offset, rle4: false },
Some(2) => BmpLayout::Rle { offset, rle4: true },
_ => BmpLayout::Rows { offset, bits: bits.filter(|&b| b > 0).unwrap_or(1) },
}
}
/// The pixels an RLE8 or RLE4 BMP's commands draw on a `w` × `h` canvas, read the way the decoder
/// paints them: a run is clipped at the end of its row, an end-of-row code moves to the next row, a
/// delta skips pixels (left blank), and an end-of-bitmap code, a truncated command or the last row
/// ends the picture. Every command takes at least 2 bytes, so the walk is linear in the file.
fn bmp_rle_pixels(bytes: &[u8], offset: usize, rle4: bool, w: u32, h: u32) -> u64 {
let (w, h) = (u64::from(w), u64::from(h));
let (mut pos, mut x, mut y, mut covered) = (offset, 0u64, 0u64, 0u64);
while y < h {
let (Some(&count), Some(&value)) = (bytes.get(pos), bytes.get(pos.saturating_add(1))) else {
break;
};
pos = pos.saturating_add(2);
match (count, value) {
// end of row
(0, 0) => (x, y) = (0, y.saturating_add(1)),
// end of bitmap
(0, 1) => break,
// delta: right and down
(0, 2) => {
let (Some(&dx), Some(&dy)) = (bytes.get(pos), bytes.get(pos.saturating_add(1))) else {
break;
};
pos = pos.saturating_add(2);
(x, y) = (x.saturating_add(u64::from(dx)), y.saturating_add(u64::from(dy)));
}
// absolute: `value` pixels stored one per byte (RLE8) or nibble (RLE4), padded to 2 bytes
(0, n) => {
let len = if rle4 { usize::from(n).div_ceil(2) } else { usize::from(n) };
pos = pos.saturating_add(len + (len & 1));
if pos > bytes.len() {
break;
}
covered = covered.saturating_add(u64::from(n).min(w.saturating_sub(x)));
x = x.saturating_add(u64::from(n));
}
// a run of `count` pixels
(n, _) => {
covered = covered.saturating_add(u64::from(n).min(w.saturating_sub(x)));
x = x.saturating_add(u64::from(n));
}
}
}
covered
}
/// A GIF's first frame, from its image descriptor.
struct GifFrame {
width: u32,
height: u32,
/// Bytes of LZW data present (its palettes, comments and other extensions describe no pixels).
data_len: usize,
/// Position of its LZW minimum code size, which its data sub-blocks follow.
codes: usize,
}
/// A GIF's first frame. `None` when the blocks before the frame can't be walked.
fn gif_first_frame(bytes: &[u8]) -> Option<GifFrame> {
let u16_at = |i: usize| bytes.get(i..i.checked_add(2)?).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 };
let mut pos = 13 + table(*bytes.get(10)?);
loop {
match *bytes.get(pos)? {
// extension: introducer, label, sub-blocks
0x21 => pos = sub_blocks(bytes, pos.saturating_add(2)).1,
// image descriptor (separator, left, top, width, height, flags), local colour table,
// LZW minimum code size, data sub-blocks
0x2C => {
let (fw, fh) = (u16_at(pos.saturating_add(5))?, u16_at(pos.saturating_add(7))?);
let codes = pos.saturating_add(10).saturating_add(table(*bytes.get(pos.saturating_add(9))?));
let data_len = sub_blocks(bytes, codes.saturating_add(1)).0;
return Some(GifFrame { width: u32::from(fw), height: u32::from(fh), data_len, codes });
}
_ => return None,
}
}
}
/// The pixels a GIF frame's LZW codes draw, at most `max` (the frame's size): the codes are walked
/// up to the end code, an invalid code or the end of the data, keeping only the length of each
/// table string, never the pixels. Data after the end code draws nothing. Codes are packed
/// least-significant bit first across the data sub-blocks and start one bit wider than the minimum
/// code size; a code is one bit wider each time the table fills its width, up to 12 bits, and a
/// clear code starts the table again (GIF89a, appendix F).
fn gif_frame_pixels(bytes: &[u8], codes: usize, max: u64) -> u64 {
// the `gif` decoder accepts minimum code sizes of 1 to 11
let Some(min_size) = bytes.get(codes).copied().filter(|s| (1..=11).contains(s)) else {
return 0;
};
let clear = 1usize << min_size;
let end = clear + 1;
let mut lens = [1u16; 4096]; // string length of each code; literals (below `clear`) are 1
let (mut width, mut next, mut prev) = (u32::from(min_size) + 1, end + 1, None::<usize>);
let (mut bits, mut held, mut covered) = (0u32, 0u32, 0u64);
let mut pos = codes.saturating_add(1);
while let Some(&n) = bytes.get(pos) {
let start = pos.saturating_add(1);
pos = start.saturating_add(usize::from(n));
if n == 0 {
break;
}
for &byte in bytes.get(start..pos.min(bytes.len())).unwrap_or_default() {
bits |= u32::from(byte) << held;
held += 8;
while held >= width {
let code = (bits & ((1 << width) - 1)) as usize;
bits >>= width;
held -= width;
if code == clear {
(width, next, prev) = (u32::from(min_size) + 1, end + 1, None);
continue;
}
let len_of = |c: usize| lens.get(c).copied().unwrap_or(1);
let len = match prev {
_ if code == end => return covered,
None if code < clear => 1,
Some(_) if code < next => len_of(code),
// the string just being defined: the previous one and its first pixel
Some(p) if code == next => len_of(p).saturating_add(1),
_ => return covered,
};
// each code after the first defines the next string: the previous one and a pixel
let defined = prev.map(|p| len_of(p).saturating_add(1));
if let Some(defined) = defined
&& let Some(slot) = lens.get_mut(next)
{
*slot = defined;
next += 1;
if next == 1 << width && width < 12 {
width += 1;
}
}
prev = Some(code);
covered = covered.saturating_add(u64::from(len));
if covered >= max {
return max;
}
}
}
}
covered
}
/// The GIF sub-blocks starting at `pos`: the data bytes present, and the position after them.
fn sub_blocks(bytes: &[u8], mut pos: usize) -> (usize, usize) {
let mut data = 0usize;
while let Some(&n) = bytes.get(pos) {
let start = pos.saturating_add(1);
if n == 0 {
return (data, start);
}
let end = start.saturating_add(usize::from(n));
data = data.saturating_add(end.min(bytes.len()).saturating_sub(start));
pos = end;
}
(data, pos)
}
pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Result<Decoded> {
if format == Format::Gif {
gated_first_frame(bytes, opts)?;
@@ -15,6 +300,8 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu
let mut d = image::codecs::gif::GifDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
@@ -22,6 +309,8 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu
let mut d = image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
@@ -88,7 +377,7 @@ fn gated_first_frame(bytes: &[u8], opts: &DecodeOptions) -> Result<()> {
#[cfg(test)]
mod tests {
use crate::{DecodeOptions, Error};
use super::*;
fn gif(blocks: &[u8]) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
@@ -118,4 +407,47 @@ mod tests {
let r = crate::decode(&bytes, DecodeOptions::default());
assert!(matches!(r, Err(Error::Malformed(..)) | Err(Error::TooLarge(..))), "{r:?}");
}
/// A GIF whose blocks can't be walked to a first frame (here a comment that runs to the end of the
/// file) is refused, instead of the whole file being counted as pixel data for its 400 MP screen.
/// The `image` decoder also stops at such a file when it opens it, but the canvas bound doesn't
/// rely on the two walks agreeing.
#[test]
fn a_gif_with_no_readable_first_frame_is_refused() {
let mut b = b"GIF89a".to_vec();
b.extend(20_000u16.to_le_bytes());
b.extend(20_000u16.to_le_bytes());
b.extend([0, 0, 0, 0x21, 0xFE]);
for _ in 0..600 {
b.push(255);
b.extend([b'x'; 255]);
}
let r = check_fillable(Format::Gif, &b, 20_000, 20_000);
assert!(matches!(&r, Err(Error::Malformed(_, m)) if m.contains("no readable first frame")), "{r:?}");
}
/// The LZW walk counts exactly the pixels an encoder wrote up to its end code: a frame of one
/// colour (long strings, the smallest codes), a 256-colour gradient and noise (a table that fills
/// up and is cleared again).
#[test]
fn the_lzw_walk_counts_every_pixel_an_encoder_wrote() {
let (w, h) = (640u32, 480u32);
let mut seed = 2_553u32;
let mut noise = move || {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 24) as u8
};
let frames = [
("solid", image::RgbaImage::from_pixel(w, h, image::Rgba([90, 90, 90, 255]))),
("gradient", image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x / 40 * 16) as u8, (y / 30 * 16) as u8, 0, 255]))),
("noise", image::RgbaImage::from_fn(w, h, |_, _| image::Rgba([noise(), noise(), noise(), 255]))),
];
for (name, frame) in frames {
let mut gif = Vec::new();
image::codecs::gif::GifEncoder::new_with_speed(&mut gif, 30).encode_frame(image::Frame::new(frame)).unwrap();
let first = gif_first_frame(&gif).unwrap();
assert_eq!((first.width, first.height), (w, h), "{name}");
assert_eq!(gif_frame_pixels(&gif, first.codes, u64::MAX), u64::from(w * h), "{name}");
}
}
}
+206
View File
@@ -74,6 +74,212 @@ fn thumbnail_rejects_huge_gif_before_allocating_source_pixels() {
assert!(matches!(result, Err(Error::TooLarge(42_127, 16_304))), "{result:?}");
}
/// A GIF of a few dozen bytes: a `w` × `h` logical screen and one empty frame of that size.
fn tiny_gif(w: u16, h: u16) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend([0, 0, 0, b',', 0, 0, 0, 0]);
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend([0, 2, 0, b';']);
b
}
/// A 54-byte uncompressed 24-bit BMP header declaring `w` × `h` and no pixel data.
fn tiny_bmp(w: i32, h: i32) -> Vec<u8> {
let mut b = b"BM".to_vec();
b.extend(54u32.to_le_bytes());
b.extend(0u32.to_le_bytes());
b.extend(54u32.to_le_bytes());
b.extend(40u32.to_le_bytes());
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend(1u16.to_le_bytes());
b.extend(24u16.to_le_bytes());
b.extend([0u8; 24]);
b
}
/// Issue #2553: the import probe had no header reader for GIF or BMP and decoded them in full, so
/// a tiny file declaring a canvas just under the 1-gigapixel limit allocated ~4.3 GB (an abort, not
/// an error, when it failed). Both the probe and a decode now refuse a canvas the file's bytes
/// can't fill, before the decoder allocates it.
#[test]
fn tiny_gif_and_bmp_declaring_a_gigapixel_canvas_are_refused_before_allocating() {
for (name, bytes) in [("gif", tiny_gif(32_767, 32_767)), ("bmp", tiny_bmp(32_000, 32_000))] {
assert!(bytes.len() < 64, "{name}: {} bytes", bytes.len());
let header = read_header(&bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{name}: {header:?}");
let decoded = decode(&bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{name}: {:?}", decoded.err());
}
}
/// Above 4 MP the probe reads GIF and BMP sizes from the header without decoding; the size agrees
/// with a full decode.
#[test]
fn large_gif_and_bmp_sizes_come_from_the_header() {
let (w, h) = (2_100u32, 2_000u32);
let rgb = vec![90u8; (w * h * 3) as usize];
let mut bmp = Vec::new();
image::codecs::bmp::BmpEncoder::new(&mut bmp).encode(&rgb, w, h, image::ExtendedColorType::Rgb8).unwrap();
let mut gif = Vec::new();
let frame = image::RgbaImage::from_pixel(w, h, image::Rgba([90, 90, 90, 255]));
image::codecs::gif::GifEncoder::new(&mut gif).encode_frame(image::Frame::new(frame)).unwrap();
for (name, bytes) in [("bmp", bmp), ("gif", gif)] {
let header = read_header(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!((header.width, header.height, header.orientation), (w, h, 1), "{name}");
let d = decode(&bytes, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (w, h), "{name}");
}
}
/// A 64-byte RLE8 BMP declaring `w` × `h` whose pixels are one end-of-bitmap code: all blank.
fn rle_bmp_ending_at_once(w: i32, h: i32) -> Vec<u8> {
let mut b = b"BM".to_vec();
b.extend(64u32.to_le_bytes()); // file size
b.extend(0u32.to_le_bytes());
b.extend(62u32.to_le_bytes()); // pixel data offset: 14 + 40 + 2 palette entries
b.extend(40u32.to_le_bytes());
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend(1u16.to_le_bytes());
b.extend(8u16.to_le_bytes());
b.extend(1u32.to_le_bytes()); // BI_RLE8
b.extend(2u32.to_le_bytes()); // pixel data size
b.extend([0u8; 8]);
b.extend(2u32.to_le_bytes()); // colours used
b.extend(0u32.to_le_bytes());
b.extend([0, 0, 0, 0, 255, 255, 255, 0]);
b.extend([0, 1]); // end of bitmap
assert_eq!(b.len(), 64);
b
}
/// An RLE8 BMP may end its pixels with an end-of-bitmap code that leaves the rest blank, so a file
/// of a few dozen bytes is a valid picture: up to 4 MP it opens, at its declared size.
#[test]
fn an_rle_bmp_that_ends_early_still_opens() {
let (w, h) = (2_000i32, 2_000i32);
let b = rle_bmp_ending_at_once(w, h);
let header = read_header(&b).unwrap();
assert_eq!((header.width, header.height), (w as u32, h as u32));
let d = decode(&b, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (w as u32, h as u32));
}
/// A mostly blank canvas still costs its full size to decode, so a tiny RLE BMP can't claim a
/// gigapixel one: canvases the file's runs can't cover are limited to 4 MP, refused before the
/// decoder allocates them.
#[test]
fn a_tiny_rle_bmp_declaring_a_gigapixel_canvas_is_refused_before_allocating() {
for (w, h) in [(2_001, 2_000), (32_000, 32_000)] {
let b = rle_bmp_ending_at_once(w, h);
let header = read_header(&b);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{w} × {h}: {header:?}");
let decoded = decode(&b, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{w} × {h}: {:?}", decoded.err());
}
}
/// A `sw` × `sh` GIF screen whose first frame is one pixel (black, from a 2-colour palette).
fn gif_with_one_pixel_frame(sw: u16, sh: u16) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
b.extend(sw.to_le_bytes());
b.extend(sh.to_le_bytes());
b.extend([0x80, 0, 0]); // global colour table of 2 entries
b.extend([0, 0, 0, 255, 255, 255]);
b.extend([b',', 0, 0, 0, 0, 1, 0, 1, 0, 0]); // a 1 × 1 frame at the origin
b.extend([2, 2, 0x44, 0x01, 0]); // LZW: clear, index 0, end
b.push(b';');
b
}
/// Density is judged on the first frame's own size, not the screen's: a valid GIF with a small first
/// frame on a larger screen opens, at the screen's size (up to 4 MP, as for other mostly blank
/// canvases).
#[test]
fn a_gif_with_a_small_first_frame_on_a_larger_screen_opens() {
let b = gif_with_one_pixel_frame(2_000, 2_000);
let header = read_header(&b).unwrap();
assert_eq!((header.width, header.height), (2_000, 2_000));
let d = decode(&b, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (2_000, 2_000));
}
#[test]
fn a_gif_whose_one_pixel_frame_sits_on_a_gigapixel_screen_is_refused_before_allocating() {
let b = gif_with_one_pixel_frame(32_767, 32_767);
let header = read_header(&b);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{header:?}");
let decoded = decode(&b, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{:?}", decoded.err());
}
/// A GIF's comments and other extensions describe no pixels, so padding a tiny GIF with 100 KB of
/// comment doesn't let it claim a gigapixel canvas: only the frame's LZW data counts.
#[test]
fn a_gif_padded_with_comments_still_cannot_claim_a_gigapixel_canvas() {
let mut bytes = tiny_gif(32_767, 32_767);
let mut comment = vec![0x21, 0xFE];
for _ in 0..400 {
comment.push(255);
comment.extend([b'x'; 255]);
}
comment.push(0);
bytes.splice(13..13, comment);
assert!(bytes.len() > 100_000);
let header = read_header(&bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{header:?}");
let decoded = decode(&bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{:?}", decoded.err());
}
/// Padding is not pixel data: coverage comes from what the pixel data draws, not from the file's
/// length. Each file here is padded past what the old length-based bounds (8 pixels per byte for
/// uncompressed BMP, 128 for RLE, 2731 per LZW byte for a GIF frame) needed to accept its 9 MP
/// canvas, and each draws far less, so each is refused before the decoder allocates the canvas.
#[test]
fn files_padded_with_junk_cannot_claim_a_canvas_their_pixel_data_doesnt_draw() {
let refused = |name: &str, bytes: &[u8], why: &str| {
let header = read_header(bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains(why)), "{name}: {header:?}");
let decoded = decode(bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains(why)), "{name}: {:?}", decoded.err());
};
// a 24-bit BMP needs 3 bytes a pixel (27 MB here); 1.2 MB of zeros used to pass as 8 pixels a byte
let mut bmp = tiny_bmp(3_000, 3_000);
bmp.resize(bmp.len() + 1_200_000, 0);
refused("uncompressed bmp", &bmp, "can hold");
// an RLE BMP's picture ends at its end-of-bitmap code; 100 KB of runs after it draw nothing
let mut rle = rle_bmp_ending_at_once(3_000, 3_000);
rle.extend([255, 1].repeat(50_000));
refused("rle bmp padded after its end", &rle, "mostly blank");
// runs that never end their row are clipped to it: 100 KB of them draw one 3000-pixel row
let mut rle = rle_bmp_ending_at_once(3_000, 3_000);
rle.truncate(rle.len() - 2);
rle.extend([255, 1].repeat(50_000));
refused("rle bmp padded within one row", &rle, "mostly blank");
// a GIF frame's picture ends at its LZW end code; 4 KB of data sub-blocks after it draw nothing
let mut gif = b"GIF89a".to_vec();
gif.extend(3_000u16.to_le_bytes());
gif.extend(3_000u16.to_le_bytes());
gif.extend([0x80, 0, 0, 0, 0, 0, 255, 255, 255]); // 2-colour global table
gif.extend([b',', 0, 0, 0, 0]);
gif.extend(3_000u16.to_le_bytes());
gif.extend(3_000u16.to_le_bytes());
gif.extend([0, 2]); // no local table; LZW minimum code size 2
gif.extend([255, 0x2C]); // a full sub-block: 3-bit clear (4) then end (5), then padding
gif.extend([0xFF; 254]);
for _ in 0..15 {
gif.push(255);
gif.extend([0xFF; 255]);
}
gif.extend([0, b';']);
refused("gif padded after its end code", &gif, "mostly blank");
}
#[test]
fn thumbnail_respects_configured_source_pixel_limit() {
let image = Rgba8::from_fn(3, 2, |_, _| [40, 80, 120, 255]);
+66
View File
@@ -160,6 +160,72 @@ fn truncation_details() {
assert!(read_header(&png[..png.len() - 12]).is_err(), "nothing after the image data: truncated");
}
/// A Samsung SEF trailer as the end of `image`: one `Panorama_Shot_Info` data block, then the
/// `SEFH` directory with one entry (type 0x08E0) whose offset counts back from `SEFH` by `back`,
/// the directory's length and `SEFT`.
fn with_sef_trailer(image: &[u8], back: u32, magic: &[u8; 4]) -> Vec<u8> {
// marker-like bytes: both decoders refuse them as a second frame header after the scan
sef_file(image, back, magic, 0x08E0, &[0xFF, 0xC0, 0, 0x11, 0xFF, 0xDA, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], None)
}
/// [`with_sef_trailer`] with the entry's type, the block's data after its name, and the length
/// the entry gives (`None`: the block's own).
fn sef_file(image: &[u8], back: u32, magic: &[u8; 4], kind: u16, data: &[u8], len: Option<u32>) -> Vec<u8> {
let mut b = image.to_vec();
let mut block = vec![0, 0, 0xE0, 0x08];
block.extend_from_slice(&18u32.to_le_bytes());
block.extend_from_slice(b"Panorama_Shot_Info");
block.extend_from_slice(data);
b.extend_from_slice(&block);
let mut dir = magic.to_vec();
dir.extend_from_slice(&106u32.to_le_bytes());
dir.extend_from_slice(&1u32.to_le_bytes());
dir.extend_from_slice(&[0, 0]);
dir.extend_from_slice(&kind.to_le_bytes());
dir.extend_from_slice(&back.to_le_bytes());
dir.extend_from_slice(&len.unwrap_or(block.len() as u32).to_le_bytes());
let len = dir.len() as u32;
b.extend_from_slice(&dir);
b.extend_from_slice(&len.to_le_bytes());
b.extend_from_slice(b"SEFT");
b
}
/// Issue #3350: a Samsung panorama has no EOI; its scan data runs into the SEF trailer. It reads
/// and decodes (both decoders: zune-jpeg in full, jpeg-decoder DCT-scaled) as the image before the
/// trailer, and a file cut short with no trailer, or with a broken one, is still truncated.
#[test]
fn samsung_sef_trailer_without_eoi() {
let jpeg = fixtures(160, 96).into_iter().find(|x| x.0 == "jpeg 420 o6").map(|x| x.1).unwrap();
let scan = &jpeg[..jpeg.len() - 2];
let block = 4 + 4 + 18 + 18;
let pano = with_sef_trailer(scan, block, b"SEFH");
let header = read_header(&pano).unwrap();
assert_eq!((header.width, header.height, header.orientation), (160, 96, 6));
let full = decode(&pano, DecodeOptions::default()).unwrap();
assert_eq!((full.source_width, full.source_height), (160, 96));
let reference = decode(&jpeg, DecodeOptions::default()).unwrap();
assert_eq!(full.image.data, reference.image.data, "the same pixels as the file with its EOI");
let small = decode(&pano, DecodeOptions::fit(32, 32)).unwrap();
assert_eq!((small.source_width, small.source_height), (160, 96));
// an FF D9 inside the SEF data is not the image's end
let eoi_in_data = sef_file(scan, block, b"SEFH", 0x08E0, &[0xFF, 0xC0, 0, 0x11, 0xFF, 0xD9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], None);
assert_eq!(read_header(&eoi_in_data).unwrap().width, 160);
let small = decode(&eoi_in_data, DecodeOptions::fit(32, 32)).unwrap();
assert_eq!((small.source_width, small.source_height), (160, 96));
// still truncated: no trailer, offsets outside the file or past `SEFH`, no `SEFH`, an empty
// entry, an entry whose type isn't its block's, a cut before the first scan
assert!(read_header(scan).is_err());
assert!(read_header(&with_sef_trailer(scan, u32::MAX, b"SEFH")).is_err());
assert!(read_header(&with_sef_trailer(scan, block - 1, b"SEFH")).is_err());
assert!(read_header(&with_sef_trailer(scan, block, b"SEFX")).is_err());
assert!(read_header(&sef_file(scan, 0, b"SEFH", 0x08E0, &[], Some(0))).is_err());
assert!(read_header(&sef_file(scan, block, b"SEFH", 0x0A01, &[0; 18], None)).is_err());
let cut_in_headers = with_sef_trailer(&jpeg[..40], block, b"SEFH");
assert!(read_header(&cut_in_headers).is_err());
assert!(decode(&cut_in_headers, DecodeOptions::fit(32, 32)).is_err());
}
/// eXIf after the image data counts, as it does for a decode (which reads the whole file).
#[test]
fn png_exif_after_idat() {
+32 -3
View File
@@ -56,6 +56,10 @@ impl MonotoneCurve {
}
pub fn eval(&self, x: f64) -> f64 {
// NaN passes both bound checks below and would send the search past either end
if x.is_nan() {
return x;
}
let n = self.xs.len();
if x <= self.xs[0] {
return self.ys[0] + self.ms[0] * (x - self.xs[0]).min(0.0) * 0.0;
@@ -76,8 +80,9 @@ impl MonotoneCurve {
+ (t3 - t2) * h * self.ms[i + 1]
}
/// Sample into a LUT of `n` entries over `0..1`.
/// Sample into a LUT of `n` entries (at least 2) over `0..1`.
pub fn to_lut(&self, n: usize) -> Lut1 {
let n = n.max(2);
Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() }
}
@@ -93,16 +98,24 @@ pub struct Lut1 {
}
impl Lut1 {
/// At least 2 entries, like [`Lut1::from_fn`].
pub fn identity(n: usize) -> Lut1 {
Lut1 { v: (0..n).map(|i| i as f32 / (n - 1) as f32).collect() }
Lut1::from_fn(n, |x| x)
}
/// `f` sampled at `n` evenly spaced points over `0..1` (at least 2).
pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 {
let n = n.max(2);
Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() }
}
/// `v` is public, so a table shorter than 2 entries is read as constant (1) or the identity (0).
#[inline]
pub fn eval(&self, x: f32) -> f32 {
let x = x.clamp(0.0, 1.0);
let n = self.v.len();
let f = x.clamp(0.0, 1.0) * (n - 1) as f32;
if n < 2 {
return self.v.first().copied().unwrap_or(x);
}
let f = x * (n - 1) as f32;
let i = (f as usize).min(n - 2);
let t = f - i as f32;
self.v[i] + (self.v[i + 1] - self.v[i]) * t
@@ -163,6 +176,22 @@ mod tests {
assert!((c.eval(0.3) - 0.3).abs() < 2e-3);
}
#[test]
fn nan_input_and_short_luts_do_not_panic() {
let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]);
assert!(c.eval(f64::NAN).is_nan());
assert!(c.eval(-f64::NAN).is_nan());
for n in [0, 1] {
assert_eq!(c.to_lut(n).v.len(), 2, "{n}");
assert!(Lut1::identity(n).is_identity(), "{n}");
assert_eq!(Lut1::from_fn(n, |x| x).v.len(), 2, "{n}");
}
assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3);
assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0, "inputs outside 0..1 clamp, as for any table");
assert_eq!(Lut1 { v: vec![] }.eval(2.0), 1.0);
assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7);
}
proptest::proptest! {
#[test]
fn monotone_for_increasing_data(ys in proptest::collection::vec(0.0f64..1.0, 3..8)) {
+30
View File
@@ -97,6 +97,10 @@ impl ControlSpec {
}
pub fn format(&self, v: f64) -> String {
let s = format!("{:.*}", self.decimals as usize, v);
if v.is_finite() && !s.bytes().any(|b| matches!(b, b'1'..=b'9')) {
// Rounds to zero: no sign.
return s.trim_start_matches('-').to_string();
}
if v > 0.0 && self.min < 0.0 { format!("+{s}") } else { s }
}
/// Where `v` sits on the slider track, from 0 (left end) to 1 (right end). Linear, except for the Kelvin
@@ -410,6 +414,9 @@ pub static INDEXED: &[ControlSpec] = &[
fn split_indexed(id: &str) -> Option<(&str, usize, &str)> {
let mut it = id.splitn(3, '.');
let (fam, i, field) = (it.next()?, it.next()?, it.next()?);
if i.is_empty() || !i.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
Some((fam, i.parse().ok()?, field))
}
@@ -493,6 +500,17 @@ pub fn in_section(section: Section) -> impl Iterator<Item = &'static ControlSpec
mod tests {
use super::*;
#[test]
fn format_shows_no_sign_on_a_value_that_rounds_to_zero() {
let e = find("light.exposure").unwrap();
assert_eq!(e.format(0.004), "0.00");
assert_eq!(e.format(-0.004), "0.00");
assert_eq!(e.format(0.5), "+0.50");
assert_eq!(e.format(-0.5), "-0.50");
assert_eq!(e.format(f64::INFINITY), "+inf");
assert_eq!(e.format(f64::NEG_INFINITY), "-inf");
}
#[test]
fn every_control_reads_its_default() {
let s = DevelopSettings::default();
@@ -538,6 +556,18 @@ mod tests {
}
}
#[test]
fn signed_indexes_are_unknown_ids() {
let mut s = DevelopSettings::default();
s.point_colors.push(Default::default());
let before = s.point_colors[0].hue_shift;
assert!(!set(&mut s, "pointColor.+0.hueShift", 10.0), "signed index");
assert_eq!(s.point_colors[0].hue_shift, before);
assert_eq!(get(&s, "pointColor.+0.hueShift"), None);
assert!(find("pointColor.+0.hueShift").is_none());
assert!(find("redEye.+0.darken").is_none());
}
#[test]
fn formatting() {
let e = find("light.exposure").unwrap();
+112 -5
View File
@@ -38,6 +38,14 @@ impl DevelopSettings {
serde_json::from_value(v.clone())
}
/// [`Self::from_json`] for settings from outside the app, such as a sidecar's `lc:settings`
/// (issue #2555): kept in range as [`Self::merged`] keeps them.
pub fn from_untrusted_json(v: &Value) -> Result<DevelopSettings, serde_json::Error> {
let mut s = DevelopSettings::from_json(v)?;
s.keep_in_range(&DevelopSettings::default());
Ok(s)
}
/// Merge a partial JSON object into these settings (fields not mentioned are kept). A white balance that
/// names no [`WbScale`] keeps the meaning it always had (`Legacy`), whatever scale these settings were on: a
/// partial from before the scale existed, or one that never said, must not become Kelvin by landing on
@@ -58,8 +66,9 @@ impl DevelopSettings {
/// What crs XMP import does to the values it reads, for settings that arrive as JSON (presets, `develop.merge`,
/// `render --settings`; issue #1946): every slider clamped through its control spec, point curves in 0..1, and a
/// crop with no area left as it was in `before`. Unrotated, the crop is clipped to the photo first; a turned crop
/// may reach past 0..1 and is left to the crop tools, which know the photo's size.
/// crop with no area left as it was in `before`. The angle is kept within ±45° (not finite: 0). Unrotated, the crop
/// is clipped to the photo first; a turned crop may reach past 0..1 and is bounded where the photo's size is known
/// (`CropGeometry::bounded`, applied by the pipeline).
fn keep_in_range(&mut self, before: &DevelopSettings) {
for c in controls::CONTROLS {
if let Some(v) = controls::get(self, c.id) {
@@ -71,6 +80,7 @@ impl DevelopSettings {
*p = lightcraft_geom::Point::new(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0));
}
let g = &mut self.crop.geometry;
g.angle = if g.angle.is_finite() { g.angle.clamp(-45.0, 45.0) } else { 0.0 };
if g.angle == 0.0 {
g.rect = g.rect.intersect(&lightcraft_geom::Rect::UNIT);
}
@@ -145,7 +155,8 @@ impl DevelopSettings {
}
}
/// Reset every control in `section` to its default.
/// Reset every control in `section` to its default, and the settings of the section that are not
/// controls (the creative profile, the curve, the white balance mode).
pub fn reset_section(&mut self, section: Section) {
for c in controls::in_section(section) {
controls::set(self, c.id, c.default);
@@ -157,13 +168,29 @@ impl DevelopSettings {
}
Section::Color => self.wb.mode = WbMode::AsShot,
Section::Detail => self.enhance.denoise_on = None,
// the creative profile is not a control: the chosen look goes back to the default one,
// and so does the camera's own local tone mapping
Section::Profile => {
self.profile = Profile::default();
}
_ => {}
}
}
/// Next free mask id.
/// Next free mask id: one past the highest, or, when that is `u32::MAX` (ids come from files,
/// pastes and agents), the lowest one no mask uses.
pub fn next_mask_id(&self) -> u32 {
self.masks.iter().map(|m| m.id).max().map_or(1, |m| m + 1)
match self.masks.iter().map(|m| m.id).max() {
None => 1,
// fewer masks than ids: one of the first `masks.len() + 1` is free
Some(max) => max
.checked_add(1)
.or_else(|| {
let used: std::collections::HashSet<u32> = self.masks.iter().map(|m| m.id).collect();
(1..=u32::MAX).find(|id| !used.contains(id))
})
.unwrap_or(0),
}
}
}
@@ -271,6 +298,54 @@ mod tests {
assert_eq!(s.grading.blending, 50.0);
}
/// Settings with one colour-range mask of `n` distinct samples (built in code, so not capped).
fn color_range_settings(n: usize) -> DevelopSettings {
let samples = (0..n).map(|i| [i as f64 / 1000.0, 0.1, -0.1]).collect();
let mut s = DevelopSettings::default();
s.masks.push(Mask {
id: 1,
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::ColorRange { samples, refine: 50.0 } }],
..Default::default()
});
s
}
fn color_range_samples(s: &DevelopSettings) -> &[[f64; 3]] {
match s.masks.first().and_then(|m| m.components.first()).map(|c| &c.shape) {
Some(MaskShape::ColorRange { samples, .. }) => samples,
other => panic!("expected a colour range, got {other:?}"),
}
}
/// Issue #2556: `mask.add`/`mask.update` capped a colour range's samples, but a sidecar `lc:settings`, a
/// preset, `develop.merge`, `render --settings` or a catalog / history load took any number (render cost is
/// pixels x samples). Every load now keeps the first [`MAX_COLOR_RANGE_SAMPLES`], in order.
#[test]
fn color_range_samples_are_capped_however_settings_load() {
let big = color_range_settings(1000);
let want = &color_range_samples(&big)[..MAX_COLOR_RANGE_SAMPLES];
let v = big.to_json();
let loaded = DevelopSettings::from_json(&v).unwrap();
assert_eq!(color_range_samples(&loaded).len(), MAX_COLOR_RANGE_SAMPLES);
assert_eq!(color_range_samples(&loaded), want);
let from_str: DevelopSettings = serde_json::from_str(&v.to_string()).unwrap();
assert_eq!(color_range_samples(&from_str), want);
// `develop.merge`, `render --settings` and presets merge a partial
let merged = DevelopSettings::default().merged(&json!({"masks": v["masks"]})).unwrap();
assert_eq!(color_range_samples(&merged), want);
let preset =
Preset { id: "p".into(), name: "P".into(), group: "G".into(), settings: json!({"masks": v["masks"]}), favorite: false, builtin: false };
assert_eq!(color_range_samples(&preset.apply(&DevelopSettings::default(), 1.0)), want);
// a capped list round-trips, and a short one is unchanged
assert_eq!(DevelopSettings::from_json(&loaded.to_json()).unwrap(), loaded);
let few = color_range_settings(2);
assert_eq!(DevelopSettings::from_json(&few.to_json()).unwrap(), few);
// a list that isn't samples is still refused
let mut bad = v.clone();
bad["masks"][0]["components"][0]["shape"]["samples"] = json!([[0.1, 0.2]]);
assert!(DevelopSettings::from_json(&bad).is_err());
}
#[test]
fn merge_partial() {
let s = DevelopSettings::default();
@@ -316,6 +391,26 @@ mod tests {
assert!(s.is_unedited());
}
#[test]
fn resetting_the_profile_section_restores_the_default_profile() {
// the chosen creative profile is not a control, so resetting the section must restore it too
let mut s = DevelopSettings::default();
s.profile.id = "lc.muted.matte-soft".into();
s.profile.amount = 40.0;
s.reset_section(Section::Profile);
assert_eq!(s.profile.id, "lc.color", "the creative profile is reset to the default one");
assert_eq!(s.profile.amount, 100.0);
}
#[test]
fn resetting_the_profile_section_clears_the_camera_local_tone() {
// the camera's local tone mapping is not a control either: a Profile reset switches it off
let mut s = DevelopSettings::default();
s.profile.camera_local_tone = true;
s.reset_section(Section::Profile);
assert!(!s.profile.camera_local_tone);
}
#[test]
fn section_toggles() {
let mut s = DevelopSettings::default();
@@ -363,4 +458,16 @@ mod tests {
s.reset_section(Section::Detail);
assert_eq!(s.enhance.denoise_on, None);
}
#[test]
fn next_mask_id_after_the_highest_id_is_unused() {
// ids come from files, pastes and agents: one at the limit must not overflow (a panic in
// debug builds) or wrap to an id another mask has
let mut s = DevelopSettings::default();
assert_eq!(s.next_mask_id(), 1);
s.masks = vec![Mask { id: u32::MAX, ..Default::default() }, Mask { id: 1, ..Default::default() }];
let next = s.next_mask_id();
assert!(!s.masks.iter().any(|m| m.id == next), "{next}");
assert_eq!(next, 2);
}
}
+20 -3
View File
@@ -220,14 +220,12 @@ impl Preset {
o.remove("masks");
}
let mut out = apply_partial(s, &rest, amount);
let mut next = out.masks.iter().map(|m| m.id).max().unwrap_or(0);
for m in masks {
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
continue;
}
next += 1;
m.id = next;
m.id = out.next_mask_id();
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
out.masks.push(m);
}
@@ -293,4 +291,23 @@ mod tests {
deep_merge(&mut a, &json!({"x": {"b": 3}, "y": [2, 3]}));
assert_eq!(a, json!({"x": {"a": 1, "b": 3}, "y": [2, 3]}));
}
#[test]
fn preset_masks_get_unused_ids_after_a_mask_id_at_the_limit() {
let s = DevelopSettings { masks: vec![crate::Mask { id: u32::MAX, name: "Theirs".into(), ..Default::default() }], ..Default::default() };
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "User".into(),
settings: json!({"masks": [{"id": 7, "name": "A"}, {"id": 7, "name": "B"}]}),
favorite: false,
builtin: false,
};
let out = p.apply(&s, 1.0);
let mut ids: Vec<u32> = out.masks.iter().map(|m| m.id).collect();
assert_eq!(ids.len(), 3);
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), 3, "{:?}", out.masks);
}
}
+13 -1
View File
@@ -104,9 +104,14 @@ fn base64_encode(bytes: &[u8]) -> String {
fn base64_decode(s: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() / 4 * 3);
let (mut acc, mut bits) = (0u32, 0u32);
let mut padded = false;
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
if c == b'=' {
break;
padded = true;
continue;
}
if padded {
return None;
}
let v = B64.iter().position(|b| *b == c)? as u32;
acc = (acc << 6) | v;
@@ -117,6 +122,9 @@ fn base64_decode(s: &str) -> Option<Vec<u8>> {
acc &= (1 << bits) - 1;
}
}
if bits == 6 {
return None;
}
Some(out)
}
@@ -133,6 +141,10 @@ mod tests {
assert_eq!(base64_encode(b"Man"), "TWFu");
assert_eq!(base64_encode(b"Ma"), "TWE=");
assert!(base64_decode("TW!u").is_none());
assert!(base64_decode("Z").is_none());
assert!(base64_decode("Zm9vY").is_none());
assert!(base64_decode("Zg==!!!not-base64").is_none());
assert_eq!(base64_decode("Zg==\n").unwrap(), b"f");
}
#[test]
+36 -1
View File
@@ -134,6 +134,7 @@ pub struct DevelopSettings {
pub orientation: Orientation,
pub masks: Vec<Mask>,
pub spots: Vec<Spot>,
/// Red eye corrections; the first [`MAX_RED_EYES`] render.
pub red_eye: Vec<RedEye>,
pub lens_blur: LensBlur,
pub enhance: Enhance,
@@ -921,6 +922,35 @@ impl Default for BrushStroke {
}
}
/// Most samples a colour-range mask keeps. It compares every pixel against every sample, so render and export cost
/// is pixels x samples; the interactive sampler stops at 5, and a sidecar, preset or `mask.add` with thousands could
/// stall a render or lose the GPU device (issue #2556).
pub const MAX_COLOR_RANGE_SAMPLES: usize = 64;
/// Deserialize a colour range's samples, keeping the first [`MAX_COLOR_RANGE_SAMPLES`] (the rest are skipped without
/// being stored), however the settings arrive: sidecar, catalog, history, preset or merge.
fn de_color_range_samples<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<[f64; 3]>, D::Error> {
struct Capped;
impl<'de> serde::de::Visitor<'de> for Capped {
type Value = Vec<[f64; 3]>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of OkLab colours")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<[f64; 3]>, A::Error> {
let mut out = Vec::new();
while out.len() < MAX_COLOR_RANGE_SAMPLES {
match seq.next_element::<[f64; 3]>()? {
Some(s) => out.push(s),
None => return Ok(out),
}
}
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
Ok(out)
}
}
d.deserialize_seq(Capped)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum MaskShape {
@@ -941,8 +971,9 @@ pub enum MaskShape {
feather: f64,
invert: bool,
},
/// Colour range: sampled OkLab colours with a refine amount 0..100.
/// Colour range: sampled OkLab colours (at most [`MAX_COLOR_RANGE_SAMPLES`]) with a refine amount 0..100.
ColorRange {
#[serde(deserialize_with = "de_color_range_samples")]
samples: Vec<[f64; 3]>,
refine: f64,
},
@@ -1069,6 +1100,10 @@ impl Default for Spot {
}
}
/// Most red eye / pet eye corrections a photo renders. Every output pixel goes through every eye, so render cost is
/// pixels x eyes; a sidecar, preset or agent with thousands could stall a render for hours (issue #2556).
pub const MAX_RED_EYES: usize = 64;
/// A red eye / pet eye correction: the user's ellipse (centre normalized, radii as fractions of
/// the long edge); the pupil inside it is found automatically.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+10 -5
View File
@@ -80,11 +80,16 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// a tone-only fallback for near-black scenes with too few colour pairs (#1587); DNG tone fitting uses a
/// lens-corrected proxy when the file carries lens opcodes; validated A7CR distortion, including the lens data
/// stored with each smart preview.
/// 13: a photo no look fits keeps its camera profile's colour instead of the neutral fallback.
/// 14: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed.
/// 15: only a look with the profile's colour continues along its pooled tone curve.
/// 16: continuing a photo's curve keeps it as it was where its JPEG taught it (`thinned_knots`).
pub const LOOK_VERSION: u32 = 16;
/// 13: tone curves no steeper than a log-log slope of 4 between knots (#1904).
/// 13: the Canon CR3/CR2 camera JPEG read in the colour space of the Canon maker note (#2654).
/// 13: the sensor proxy of every per-file fit gets the embedded vignetting correction the render applies (Fujifilm
/// RAF; other makes with a lens database), so the render no longer applies it twice, at the position a lens warp samples;
/// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black.
/// 14: a photo no look fits keeps its camera profile's colour instead of the neutral fallback.
/// 15: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed.
/// 16: only a look with the profile's colour continues along its pooled tone curve.
/// 17: continuing a photo's curve keeps it as it was where its JPEG taught it (`thinned_knots`).
pub const LOOK_VERSION: u32 = 17;
#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
+7 -6
View File
@@ -1,6 +1,6 @@
use super::look_fit::{fit_dng_tone, fit_preview};
use super::look_fit::{fit_dng_tone, fit_preview, look_proxies};
use super::mono::{fit_dark_tone, monochrome_look};
use super::proxy::{LensGeometry, proxies};
use super::proxy::LensGeometry;
use super::{CameraLook, CameraTone, CameraTransform, ColorData, D50, D65, Mat3, ProfileLook, REC2020, RawFormat, RawImage, ToneCurve, Xy, bradford};
/// Long edge of the sensor/JPEG proxy a single photo's look is fitted on (the acceptance gates
@@ -42,7 +42,8 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool {
/// as-shot white, the camera transform at it and the fitted look.
/// `lens` is the file's own lens-correction warp ([`lens_geometry`], read before the caller removes it from
/// `OpcodeList3`): the camera applied it to its JPEG, so the sensor proxy is warped the same way before pairing.
/// `embedded` is the file's embedded lens vignetting, for the DNG tone fit.
/// `embedded` is the file's embedded lens correction: its vignetting is applied to the sensor proxy of every fit, as
/// the render applies it.
pub(crate) fn starting_colour(
raw: &mut RawImage,
bytes: &[u8],
@@ -51,13 +52,13 @@ pub(crate) fn starting_colour(
) -> (Xy, CameraTransform, Option<CameraLook>) {
let (xy, t, look) = starting_colour_with(
raw,
|raw, t| fit_preview(raw, bytes, t, lens),
|raw, t| monochrome_look(raw, bytes, t, lens),
|raw, t| fit_preview(raw, bytes, t, lens, embedded),
|raw, t| monochrome_look(raw, bytes, t, lens, embedded),
|raw, t| {
if !file_local_look(raw.format) {
return None;
}
let (sensor, reference, clipped) = proxies(raw, bytes, t, PROXY, 0.0, lens)?;
let (sensor, reference, clipped) = look_proxies(raw, bytes, t, lens, embedded)?;
fit_dark_tone(&sensor, &reference, &clipped)
},
);
+26 -3
View File
@@ -6,11 +6,18 @@ use super::tone::{HighlightCheck, highlights};
use super::{CameraLook, CameraTone, CameraTransform, HsvTable, Mat3, RawImage, Rgb32f, ToneMap, luminance_2020};
/// The look fitted to the file's camera JPEG, and whether that JPEG is black and white ([`monochrome`]).
pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> (Option<CameraLook>, bool) {
/// `embedded`: the file's embedded lens correction, whose vignetting the render applies ([`look_proxies`]).
pub(crate) fn fit_preview(
raw: &RawImage,
bytes: &[u8],
transform: &CameraTransform,
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> (Option<CameraLook>, bool) {
if !transform.matrix_is_fallback || !file_local_look(raw.format) {
return (None, false);
}
let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0, lens) else { return (None, false) };
let Some((sensor, reference, clipped)) = look_proxies(raw, bytes, transform, lens, embedded) else { return (None, false) };
let black_and_white = monochrome(&reference);
// A camera profile pooled from many photos knows colours this photo shows too little of;
// try its colour first and fit tone/chroma per photo (picture styles vary).
@@ -234,7 +241,9 @@ pub(super) fn fit_dng_tone(
}
None
};
let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None) else { return refuse("preview") };
let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None, None) else {
return refuse("preview");
};
// As the loader renders it: the profile's tables around the baseline exposure.
let xy = lightcraft_raw::color::as_shot_white_xy(raw);
if let Some(tables) = lightcraft_raw::profile::ProfileTables::new(&raw.color.profile, lightcraft_raw::color::illuminant_weight(&raw.color, xy)) {
@@ -284,6 +293,20 @@ pub(super) fn clips_more(sensor: &Rgb32f, reference: &Rgb32f, fitted: &ToneMap,
near_white(fitted) > near_white(plain).max(preview) + CLIP_TOLERANCE
}
/// The proxies a photo's look is fitted on ([`proxies`] at [`PROXY`]), the sensor's with the embedded vignetting
/// correction the render applies. Without it the tone curve learns the camera JPEG's corrected
/// brightness from the uncorrected sensor, and the render then corrects it again: 21 X-S10 RAFs rendered up to 0.3 EV
/// brighter in their midtones and 0.6 EV in their shadows than their camera JPEGs, about 0.05 EV once corrected.
pub(super) fn look_proxies(
raw: &RawImage,
bytes: &[u8],
transform: &CameraTransform,
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<(Rgb32f, Rgb32f, Vec<bool>)> {
proxies(raw, bytes, transform, PROXY, 0.0, lens, embedded)
}
/// Multiply the sensor proxy (sensor orientation, default crop) by the embedded vignetting correction, the gain the
/// pipeline applies to the render (`optics::embedded_vignette_gain`; `lens` is in the oriented, cropped frame): the
/// camera JPEG has it applied, so a tone fitted without it brightens the render's corners twice.
+12 -6
View File
@@ -1,11 +1,11 @@
use super::colour::{PROXY, file_local_look};
use super::colour::file_local_look;
use super::hue_sat::HueSat;
use super::look_fit::{with_dro_off_tone, without_clipped};
use super::look_fit::{look_proxies, with_dro_off_tone, without_clipped};
use super::pairs::{
EDGE_CONTRAST, MIN_IMPROVEMENT, PARTIAL_MIN_RANK_CORRELATION, Pairs, collect_pairs, displayed, fit_tone_with_shadows, local_contrast, luma,
rank_correlation_ties,
};
use super::proxy::{LensGeometry, proxies};
use super::proxy::LensGeometry;
use super::tone::{HighlightCheck, ToneFit, fit_tone, highlights, highlights_hold};
use super::{CameraLook, CameraTransform, D50, D65, HsvTable, Mat3, PROPHOTO, REC2020, RawImage, Rgb32f, ToneMap, bradford, luminance_2020};
@@ -33,12 +33,18 @@ pub(super) fn monochrome(reference: &Rgb32f) -> bool {
/// and flatter than the same body's photos shot in colour. But the JPEG still shows the camera's tone curve.
/// `transform` is the colour the photo gets otherwise (the spectral matrices or the fallback's); the look keeps it and
/// adds the tone curve alone ([`fit_tone_only_with`]), as [`fit_look_with`] tries the photo's own colour after a profile's. The
/// chroma curve stays neutral: the JPEG has no colourfulness to learn.
pub(super) fn monochrome_look(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> Option<CameraLook> {
/// chroma curve stays neutral: the JPEG has no colourfulness to learn. `embedded` as for [`fit_preview`].
pub(super) fn monochrome_look(
raw: &RawImage,
bytes: &[u8],
transform: &CameraTransform,
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<CameraLook> {
if !file_local_look(raw.format) {
return None;
}
let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0, lens)?;
let (sensor, reference, clipped) = look_proxies(raw, bytes, transform, lens, embedded)?;
if !monochrome(&reference) {
return None;
}
+10 -4
View File
@@ -1,6 +1,6 @@
use super::colour::{PROFILE_PROXY, PROXY, file_local_look};
use super::hue_sat::fit_hue_sat;
use super::look_fit::{FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, clip_mask, without_clipped};
use super::look_fit::{FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, clip_mask, correct_vignetting, without_clipped};
use super::mono::monochrome;
use super::pairs::{collect_pairs, fit_matrix, luma};
use super::tone::fit_tone;
@@ -84,7 +84,8 @@ pub(super) fn structure_agrees(sensor: &Rgb32f, reference: &Rgb32f) -> bool {
/// Same-size proxies of the sensor (white-balanced, baseline exposure, through `transform`'s
/// matrix: the generic camera ≈ sRGB model) and of the file's embedded camera JPEG (linear Rec.2020),
/// and per proxy pixel whether any sensor sample it covers is clipped.
/// and per proxy pixel whether any sensor sample it covers is clipped. `embedded`'s vignetting correction is applied to
/// the sensor ([`correct_vignetting`]) before any `lens` warp, at the source position, as the render applies it.
pub(super) fn proxies(
raw: &RawImage,
bytes: &[u8],
@@ -92,6 +93,7 @@ pub(super) fn proxies(
size: usize,
min_fraction: f64,
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<(Rgb32f, Rgb32f, Vec<bool>)> {
let edge = (2 * size).max(384) as u32;
let decoded = crate::files::decode_raw_preview(
@@ -127,6 +129,7 @@ pub(super) fn proxies(
let k = (crop.width.max(crop.height).div_ceil(edge as usize).max(2)).div_ceil(2) * 2;
let mut sensor = sensor_proxy(raw, k, edge as usize)?;
let mut clipped = clip_mask(&sensor);
correct_vignetting(&mut sensor, embedded, raw.orientation);
// The camera may have corrected its JPEG with the lens warp the file carries (Nikon Z lenses always, at up to 9 %
// zoom; other cameras when their correction setting is on): the sensor moved into that geometry is a candidate,
// kept below when it lines up with the JPEG better than the uncorrected one.
@@ -331,7 +334,7 @@ pub(crate) fn profile_samples(raw: &RawImage, bytes: &[u8], lens: Option<&LensGe
return None;
}
let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw));
let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens)?;
let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, None)?;
let to_camera = transform.matrix.inverse()?;
// clipped sensor pixels don't record the scene's colour (see `fit_look`)
let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor);
@@ -503,7 +506,10 @@ pub(super) fn alignment(a: &Rgb32f, b: &Rgb32f) -> f64 {
if (b.width, b.height) != (w, h) || w < 3 || h < 3 {
return -1.0;
}
let lum = |img: &Rgb32f| img.data.iter().map(|p| (luminance_2020(*p).max(1e-4) as f64).ln()).collect::<Vec<f64>>();
// NaN (outside a lens-warped proxy) stays NaN: `max` would turn it into a black border and a false edge
let lum = |img: &Rgb32f| {
img.data.iter().map(|p| luminance_2020(*p)).map(|y| if y.is_nan() { f64::NAN } else { (y.max(1e-4) as f64).ln() }).collect::<Vec<f64>>()
};
let high = |l: &[f64]| -> Vec<f64> {
(0..w * h)
.map(|i| {
+218 -39
View File
@@ -1,3 +1,4 @@
use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity};
use super::*;
fn steep_toe_scene() -> (Rgb32f, Rgb32f) {
@@ -26,6 +27,74 @@ fn camera_tone_follows_the_jpegs_deep_shadows() {
assert_eq!(look.matrix, Mat3::IDENTITY);
}
/// Issue #1904: two populations the camera renders at different brightness for the same scene luminance (saturated
/// blue at 1.7x, red at 2.64x) made quantile matching join them with a near-vertical step.
#[test]
fn tone_fit_does_not_step_between_two_pixel_populations() {
let mut pairs = Vec::new();
for i in 0..620 {
let x = 0.040 + 0.012 * f64::from(i) / 620.0;
pairs.push((x, 1.7 * x));
}
for i in 0..380 {
let x = 0.02 * (10.0f64).powf(f64::from(i) / 380.0);
pairs.push((x, 2.64 * x));
}
let elasticity = |k: &[[f32; 2]; 32]| {
k.windows(2)
.map(|w| {
((f64::from(w[1][1]) + ELASTICITY_BLACK) / (f64::from(w[0][1]) + ELASTICITY_BLACK)).ln()
/ (f64::from(w[1][0]) / f64::from(w[0][0])).ln()
})
.fold(0.0, f64::max)
};
let mut xs: Vec<f64> = pairs.iter().map(|p| p.0).collect();
let mut ys: Vec<f64> = pairs.iter().map(|p| p.1).collect();
xs.sort_by(f64::total_cmp);
ys.sort_by(f64::total_cmp);
let raw: [[f32; 2]; 32] = std::array::from_fn(|i| {
let mid = (i * xs.len() / 32 + (i + 1) * xs.len() / 32) / 2;
[xs[mid] as f32, ys[mid] as f32]
});
assert!(elasticity(&raw) > 10.0, "the synthetic scene must reproduce the step: {}", elasticity(&raw));
let tone = fit_tone(pairs).unwrap();
let knots = tone.knots();
assert!(elasticity(knots) <= MAX_TONE_ELASTICITY + 1e-3, "{}", elasticity(knots));
assert!(knots.iter().zip(&raw).all(|(a, b)| a[0] == b[0]), "only the outputs move");
for w in knots.windows(2) {
assert!(w[1][1] >= w[0][1]);
}
// A curve within the bound is left alone.
let smooth: [[f32; 2]; 32] = std::array::from_fn(|i| {
let x = 0.01 * 1.15f32.powi(i as i32);
[x, 0.9 * (x / (x + 0.18))]
});
assert_eq!(limit_elasticity(smooth, &[]), Some(smooth));
}
/// A step at the top of the curve reaches its end: the pinned window and the free end are both under the bound, and
/// the pixel pairs choose between them.
#[test]
fn a_step_at_the_curves_end_is_repaired_from_the_side_the_pixels_support() {
let x = |i: usize| 0.01 * 1.15f64.powi(i as i32);
let stepped: [[f32; 2]; 32] = std::array::from_fn(|i| [x(i) as f32, (0.3 * x(i) * if i >= 30 { 3.0 } else { 1.0 }) as f32]);
let pairs = |gain: f64| -> Vec<(f64, f64)> {
(0..4000).map(|j| x(0) * (x(31) / x(0)).powf(f64::from(j) / 3999.0)).map(|x| (x, 0.3 * x * if x >= 0.62 { gain } else { 1.0 })).collect()
};
// The pixels follow the curve below the step: the end is left free and the top knots drop to the repair slope.
let free = limit_elasticity(stepped, &pairs(1.0)).unwrap();
assert_eq!(free[..30], stepped[..30], "the curve up to the step is kept");
let (u29, v29) = (x(29).ln(), (f64::from(stepped[29][1]) + ELASTICITY_BLACK).ln());
for k in 30..32 {
let limit = (v29 + TONE_REPAIR_ELASTICITY * (x(k).ln() - u29)).exp() - ELASTICITY_BLACK;
assert!(f64::from(free[k][1]) <= limit + 1e-6, "knot {k}: {} over {limit}", free[k][1]);
}
// The pixels do sit above the step: the window stays pinned to the top knot.
let pinned = limit_elasticity(stepped, &pairs(3.0)).unwrap();
assert_eq!(pinned[31], stepped[31], "the end the pixels support is kept");
assert!(pinned[29][1] > stepped[29][1] && pinned[30][1] < stepped[30][1], "the step is spread over the window");
}
#[test]
fn colour_holdouts_stay_out_of_the_wider_tone_training() {
let (sensor, reference) = steep_toe_scene();
@@ -661,7 +730,7 @@ fn corpus_lens_corrected_jpegs_pair_with_the_warped_sensor() {
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
let (Some((plain, reference, _)), Some((chosen, chosen_reference, _))) =
(proxies(&raw, &bytes, &t, PROXY, 0.0, None), proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&lens)))
(proxies(&raw, &bytes, &t, PROXY, 0.0, None, None), proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&lens), None))
else {
continue;
};
@@ -928,7 +997,7 @@ fn corpus_cr3_gets_a_framing_aligned_camera_look() {
assert_eq!(raw.format, RawFormat::Cr3);
assert_eq!(raw.info().developed_size(), (6000, 4000));
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;
let look = fit_preview(&raw, &bytes, &transform, None, None).0;
eprintln!("R100 guarded colour fit accepted: {}", look.is_some());
assert!(look.is_some(), "this R100 corpus photo has enough matching colour after camera-framing alignment");
let (_, info) = crate::files::load_bytes(&bytes, 400).unwrap();
@@ -965,7 +1034,7 @@ fn corpus_uses_the_bundled_profile(file: &str, model: &str) {
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, lens.as_ref()).0.expect("fit accepted");
let look = fit_preview(&raw, &bytes, &transform, lens.as_ref(), None).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) {
@@ -1346,9 +1415,9 @@ fn corpus_arw_with_dro_is_lowered_to_the_dro_off_tone() {
let mut raw = lightcraft_raw::decode(&bytes).unwrap();
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("a camera look");
let look = fit_preview(&raw, &bytes, &transform, None, None).0.expect("a camera look");
// the look fitted to the JPEG, as before this change
let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0, None).unwrap();
let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap();
let profile = raw.metadata.model.as_deref().and_then(crate::camera_profiles::get);
let colour = profile.as_ref().and_then(|p| Some((p.matrix().mul(&transform.matrix.inverse()?), p.hue_sat.clone())));
let fitted = fit_look(&sensor, &reference, &clipped, colour).unwrap();
@@ -1978,20 +2047,22 @@ fn a_rejected_profile_leaves_the_tone_curve_on_the_photos_own_colour() {
assert!(look.is_some() && !t.matrix_is_fallback);
}
/// [`monochrome_look`] on a synthetic raw file: an ILCE-7M4 (it has a bundled camera profile) whose camera JPEG,
/// in a minimal TIFF, is black and white gets the tone curve, on the colour of the transform it is given; the
/// same file with a tinted JPEG gets nothing from this step.
#[test]
fn monochrome_look_reads_the_files_black_and_white_jpeg() {
/// A synthetic ILCE-7M4 raw (it has a bundled camera profile; demosaiced grey `sensor` levels) and its file bytes:
/// a minimal TIFF holding the camera JPEG, a bright camera curve on the `scene` luminance as an 8-bit sRGB JPEG in
/// `tint` (grey for `[1.0; 3]`).
fn grey_raw_with_jpeg(
(w, h): (usize, usize),
sensor: impl Fn(usize, usize) -> f32,
scene: impl Fn(usize, usize) -> f32,
tint: [f32; 3],
) -> (RawImage, Vec<u8>) {
use lightcraft_raw::{BlackLevel, ColorData, OpcodeLists, Orientation, RawData, Rect};
let (w, h) = (192usize, 128usize);
let level = |x: usize, y: usize| 0.01 + 0.5 * (x as f32 / w as f32) * (0.3 + 0.7 * y as f32 / h as f32);
let raw = RawImage {
format: RawFormat::Arw,
width: w,
height: h,
cpp: 3,
data: RawData::F32((0..w * h).flat_map(|i| [level(i % w, i / w); 3]).collect()),
data: RawData::F32((0..w * h).flat_map(|i| [sensor(i % w, i / w); 3]).collect()),
cfa: None,
bits: 16,
black: BlackLevel::uniform(0.0),
@@ -2007,38 +2078,146 @@ fn monochrome_look_reads_the_files_black_and_white_jpeg() {
metadata: lightcraft_meta::Metadata { make: Some("SONY".into()), model: Some("ILCE-7M4".into()), ..Default::default() },
lens_metadata: Default::default(),
};
let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
let pixels: Vec<u8> = (0..w * h)
.flat_map(|i| {
let v = 1.0 - (-3.0 * scene(i % w, i / w)).exp();
tint.map(|t| (srgb(v * t).clamp(0.0, 1.0) * 255.0).round() as u8)
})
.collect();
let image = lightcraft_codecs::EncodeImage::new(w as u32, h as u32, 3, lightcraft_codecs::Samples::U8(&pixels));
let jpeg = lightcraft_codecs::encode_jpeg(&image, 95, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap();
// II*, IFD0 at 8 with JPEGInterchangeFormat (0x201) and its length (0x202), the JPEG after it
let mut tiff = b"II*\0\x08\0\0\0\x02\0".to_vec();
for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] {
tiff.extend(tag.to_le_bytes());
tiff.extend(4u16.to_le_bytes());
tiff.extend(1u32.to_le_bytes());
tiff.extend(value.to_le_bytes());
}
tiff.extend(0u32.to_le_bytes());
assert_eq!(tiff.len(), 38);
tiff.extend(jpeg);
(raw, tiff)
}
/// [`monochrome_look`] on a synthetic raw file: an ILCE-7M4 whose camera JPEG is black and white gets the tone curve,
/// on the colour of the transform it is given; the same file with a tinted JPEG gets nothing from this step.
#[test]
fn monochrome_look_reads_the_files_black_and_white_jpeg() {
let (w, h) = (192usize, 128usize);
let level = |x: usize, y: usize| 0.01 + 0.5 * (x as f32 / w as f32) * (0.3 + 0.7 * y as f32 / h as f32);
let (raw, grey) = grey_raw_with_jpeg((w, h), level, level, [1.0; 3]);
assert!(crate::camera_profiles::get("ILCE-7M4").is_some());
// the camera's rendering: a bright curve on the scene's luminance, as a grey (or tinted) 8-bit sRGB JPEG
let file = |tint: [f32; 3]| {
let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
let pixels: Vec<u8> = (0..w * h)
.flat_map(|i| {
let v = 1.0 - (-3.0 * level(i % w, i / w)).exp();
tint.map(|t| (srgb(v * t).clamp(0.0, 1.0) * 255.0).round() as u8)
})
.collect();
let image = lightcraft_codecs::EncodeImage::new(w as u32, h as u32, 3, lightcraft_codecs::Samples::U8(&pixels));
let jpeg = lightcraft_codecs::encode_jpeg(&image, 95, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap();
// II*, IFD0 at 8 with JPEGInterchangeFormat (0x201) and its length (0x202), the JPEG after it
let mut tiff = b"II*\0\x08\0\0\0\x02\0".to_vec();
for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] {
tiff.extend(tag.to_le_bytes());
tiff.extend(4u16.to_le_bytes());
tiff.extend(1u32.to_le_bytes());
tiff.extend(value.to_le_bytes());
}
tiff.extend(0u32.to_le_bytes());
assert_eq!(tiff.len(), 38);
tiff.extend(jpeg);
tiff
};
let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
let look = monochrome_look(&raw, &file([1.0; 3]), &t, None).expect("a tone curve from the black-and-white JPEG");
let look = monochrome_look(&raw, &grey, &t, None, None).expect("a tone curve from the black-and-white JPEG");
assert!(look.matrix == Mat3::IDENTITY && look.hue_sat.is_none(), "on the transform's colour");
let curve = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0);
let mid = curve.apply(0.25);
assert!((mid - (1.0 - (-0.75f32).exp())).abs() < 0.05, "the camera's curve at 0.25: {mid}");
assert!(monochrome_look(&raw, &file([1.0, 0.9, 0.8]), &t, None).is_none(), "a tinted JPEG is not black and white");
let (_, tinted) = grey_raw_with_jpeg((w, h), level, level, [1.0, 0.9, 0.8]);
assert!(monochrome_look(&raw, &tinted, &t, None, None).is_none(), "a tinted JPEG is not black and white");
}
/// The look is fitted on the sensor as the render shows it, with the file's embedded vignetting correction: the
/// camera corrected its JPEG, so a curve fitted to the uncorrected sensor learns that brightening, and the render
/// then applies it twice (X-S10 RAFs up to 0.3 EV brighter than their camera JPEGs).
#[test]
fn the_look_is_fitted_on_the_vignetting_corrected_sensor() {
use lightcraft_develop::{EmbeddedLens, EmbeddedVignette};
let (w, h) = (192usize, 128usize);
let vignette = EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 };
let gain = |x: usize, y: usize| {
let point = lightcraft_geom::Point::new(x as f64 + 0.5, y as f64 + 0.5);
lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, point, w as f64, h as f64) as f32
};
let scene = |x: usize, y: usize| 0.01 + 0.5 * (x as f32 / w as f32) * (0.3 + 0.7 * y as f32 / h as f32);
let (raw, bytes) = grey_raw_with_jpeg((w, h), |x, y| scene(x, y) / gain(x, y), scene, [1.0; 3]);
let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
let lens = EmbeddedLens { vignette: Some(vignette), ..Default::default() };
let camera = 1.0 - (-0.75f32).exp();
let at_quarter = |embedded: Option<&EmbeddedLens>| {
let look = monochrome_look(&raw, &bytes, &t, None, embedded).expect("a tone curve");
ToneMap::camera(&look.tone, 0.0, 0.0, 0.0).apply(0.25)
};
let (corrected, uncorrected) = (at_quarter(Some(&lens)), at_quarter(None));
assert!((corrected - camera).abs() < 0.03, "the camera's curve at 0.25: {corrected} vs {camera}");
assert!(uncorrected > camera + 0.03, "without the correction the curve brightens: {uncorrected} vs {camera}");
}
/// The colour fit gets the embedded vignetting correction too ([`starting_colour`] forwards it to every fit): the
/// tinted camera JPEG of the vignetted sensor takes the colour path, not the black-and-white one.
#[test]
fn the_colour_look_is_fitted_on_the_vignetting_corrected_sensor() {
use lightcraft_develop::{EmbeddedLens, EmbeddedVignette};
let (w, h) = (192usize, 128usize);
let vignette = EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 };
let gain = |x: usize, y: usize| {
let point = lightcraft_geom::Point::new(x as f64 + 0.5, y as f64 + 0.5);
lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, point, w as f64, h as f64) as f32
};
let scene = |x: usize, y: usize| 0.01 + 0.5 * (x as f32 / w as f32) * (0.3 + 0.7 * y as f32 / h as f32);
let (raw, bytes) = grey_raw_with_jpeg((w, h), |x, y| scene(x, y) / gain(x, y), scene, [1.0, 0.9, 0.8]);
let lens = EmbeddedLens { vignette: Some(vignette), ..Default::default() };
let at_quarter = |embedded: Option<&EmbeddedLens>| {
let (_, _, look) = starting_colour(&mut raw.clone(), &bytes, None, embedded);
let look = look.expect("a colour look");
assert!(look.matrix != Mat3::IDENTITY || look.hue_sat.is_some(), "the colour fit, not the black-and-white one");
ToneMap::camera(&look.tone, 0.0, 0.0, 0.0).apply(0.25)
};
let (corrected, uncorrected) = (at_quarter(Some(&lens)), at_quarter(None));
assert!(uncorrected > corrected + 0.03, "without the correction the curve brightens: {uncorrected} vs {corrected}");
}
/// A lens-warped sensor proxy gets the vignetting gain of the position it samples, as the render applies it: the
/// vignetted sensor, corrected, gives the proxy of the same sensor without vignetting.
#[test]
fn the_vignetting_correction_is_applied_before_the_lens_warp() {
use lightcraft_develop::{EmbeddedLens, EmbeddedVignette};
// twice the 384 px proxy edge: the demosaiced proxy of this linear raw is then the size a warp needs (bins of 2)
let (w, h) = (768usize, 512usize);
let vignette = EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 };
let gain = |x: usize, y: usize| {
let point = lightcraft_geom::Point::new(x as f64 + 0.5, y as f64 + 0.5);
lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, point, w as f64, h as f64) as f32
};
// a texture for the warped candidate to line up with: the JPEG shows the sensor's centre zoomed by 1 / 0.8
let texture = |x: f64, y: f64| 0.2 * (1.0 + 0.3 * ((x / 48.0).floor() + (y / 48.0).floor()).rem_euclid(2.0)) as f32;
let warp = LensGeometry { k: [0.8, 0.0, 0.0, 0.0], center: [0.5, 0.5] };
let (cx, cy) = ((w - 1) as f64 / 2.0, (h - 1) as f64 / 2.0);
let jpeg = |x: usize, y: usize| texture(cx + (x as f64 - cx) * 0.8, cy + (y as f64 - cy) * 0.8);
let sensor_proxy = |vignetted: bool, embedded: Option<&EmbeddedLens>| {
let sensor = |x: usize, y: usize| texture(x as f64, y as f64) / if vignetted { gain(x, y) } else { 1.0 };
let (raw, bytes) = grey_raw_with_jpeg((w, h), sensor, jpeg, [1.0; 3]);
let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
let (plain, _, _) = proxies(&raw, &bytes, &t, PROXY, 0.0, None, embedded).unwrap();
let (sensor, _, _) = proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&warp), embedded).unwrap();
assert!(sensor.data.iter().zip(&plain.data).any(|(a, b)| a != b), "the warped candidate is chosen");
sensor
};
let lens = EmbeddedLens { vignette: Some(vignette), ..Default::default() };
let (corrected, expected) = (sensor_proxy(true, Some(&lens)), sensor_proxy(false, None));
let worst = corrected.data.iter().zip(&expected.data).map(|(a, b)| (a[1] / b[1] - 1.0).abs()).filter(|d| d.is_finite()).fold(0.0, f32::max);
assert!(worst < 0.02, "largest deviation {worst}");
}
/// [`alignment`] leaves out the pixels a proxy lacks (NaN outside a lens-warped one): read as black, they made a
/// false edge around the border, and the warped candidate lost against a worse unwarped one.
#[test]
fn alignment_leaves_out_missing_pixels() {
let (w, h) = (48usize, 32usize);
let mut a = Rgb32f::new(w, h);
for (i, p) in a.data.iter_mut().enumerate() {
*p = [0.1 + 0.05 * ((i * 7919) % 13) as f32; 3];
}
let mut b = a.clone();
for (i, p) in b.data.iter_mut().enumerate() {
let (x, y) = (i % w, i / w);
if x < 4 || y < 4 || x >= w - 4 || y >= h - 4 {
*p = [f32::NAN; 3];
}
}
assert!(alignment(&a, &b) > 0.999, "{}", alignment(&a, &b));
}
/// The black-and-white fit has the partial look's checks: a JPEG of another picture, or one the default curve
+101 -2
View File
@@ -133,7 +133,106 @@ pub(super) fn fit_tone(pairs: Vec<(f64, f64)>) -> Option<CameraTone> {
if knots[31][0] < knots[0][0] * MIN_TONE_RANGE {
return None;
}
CameraTone::new(knots)
CameraTone::new(limit_elasticity(knots, &pairs)?)
}
/// Largest log-log slope (elasticity, d ln y / d ln x with [`ELASTICITY_BLACK`] added to y) a fitted tone curve may
/// have between two knots. A much steeper segment is not a camera curve but two pixel populations the camera renders at
/// different brightness for the same scene luminance (by hue): quantile matching puts all of one population's scene
/// range below the other's JPEG range and joins them with a near-vertical step, which amplifies the luminance noise of
/// every pixel on it and renders as contours and blotches. On a dark ISO 1100 D3400 frame of saturated blue and red
/// (issue #1904; reds 1.55x brighter in the JPEG than blues of the same scene luminance) the step had elasticity 12-28,
/// and the render's fine luminance noise in the blue area was 1.46x that of Adobe's DNG of the same frame; with the
/// bound it is 0.99x. Of 514 fitted looks on the user samples the median curve's steepest segment is 2.1 and the 95th
/// percentile 3.6. The smoothed window ends where its end-to-end slope is first under the bound, so a looser bound
/// (5 or 6) only spreads the D3400 step over a few knots and leaves the noise as it was.
pub(super) const MAX_TONE_ELASTICITY: f64 = 4.0;
/// Log-log slope of a curve end left free by [`limit_elasticity`]: about the median steepest segment of fitted looks
/// (2.1), so the knots past the step follow an ordinary camera curve. At the bound itself (4) the D3400 frame's fine
/// luminance noise stays 1.2x Adobe's; at 2 it is 0.99x.
pub(super) const TONE_REPAIR_ELASTICITY: f64 = 2.0;
/// Display level added to both ends of a segment's elasticity, so a toe rising from black is not counted as infinitely
/// steep.
pub(super) const ELASTICITY_BLACK: f64 = 0.002;
/// `knots` with every segment steeper than [`MAX_TONE_ELASTICITY`] smoothed. The knots inside the smallest window
/// around the segment (widened a knot on each side at a time) whose end-to-end elasticity is under the bound move onto
/// the straight log-log line between the window's ends, so the step is spread over the scene range of the populations it
/// joined. A window that reaches an end of the curve is pinned there, which can drag most of the curve onto one line
/// (a step at the top of a Coolpix P340 curve pulled knots 3-29 up, held-out error +4 dE00), so it is weighed against
/// leaving that end free: the knots past the segment on that side move onto [`TONE_REPAIR_ELASTICITY`] from the
/// segment's other knot instead. Of the two the one closer to `pairs` (absolute error) is kept. The curve outside the
/// window and its monotonicity are kept. `None` when nothing brings the curve under the bound. Knots within the bound are returned as
/// they are.
pub(super) fn limit_elasticity(mut knots: [[f32; 2]; 32], pairs: &[(f64, f64)]) -> Option<[[f32; 2]; 32]> {
let (bound, repair) = (MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY);
let at = |k: &[[f32; 2]; 32], i: usize| (f64::from(k[i][0]).ln(), (f64::from(k[i][1]) + ELASTICITY_BLACK).ln());
let slope = |k: &[[f32; 2]; 32], a: usize, b: usize| {
let ((ua, va), (ub, vb)) = (at(k, a), at(k, b));
(vb - va) / (ub - ua)
};
let level = |v: f64| (v.exp() - ELASTICITY_BLACK).max(0.0) as f32;
let error = |k: &[[f32; 2]; 32]| {
let tone = CameraTone::new(*k)?;
Some(pairs.iter().map(|&(x, y)| (f64::from(tone.apply(x as f32)) - y).abs()).sum::<f64>())
};
for _ in 0..64 {
let Some(i) = (0..31).find(|&i| slope(&knots, i, i + 1) > bound) else { return Some(knots) };
let (mut lo, mut hi) = (i, i + 1);
while slope(&knots, lo, hi) > bound && !(lo == 0 && hi == 31) {
lo = lo.saturating_sub(1);
hi = (hi + 1).min(31);
}
let mut pinned = knots;
let pinned_ok = slope(&knots, lo, hi) <= bound;
if pinned_ok {
let ((ua, va), (ub, vb)) = (at(&knots, lo), at(&knots, hi));
for k in lo + 1..hi {
pinned[k][1] = level(va + (vb - va) * (f64::from(knots[k][0]).ln() - ua) / (ub - ua));
}
}
// A window that reaches an end of the curve can leave that end free instead: the knots below the segment rise
// onto the repair slope down from knot i + 1, or the knots above it drop onto it up from knot i.
let mut free = None;
if lo == 0 || hi == 31 {
let mut k2 = knots;
if lo == 0 {
let (ub, vb) = at(&knots, i + 1);
for k in 0..=i {
let (u, v) = at(&knots, k);
k2[k][1] = level(v.max(vb - repair * (ub - u)));
}
} else {
let (ua, va) = at(&knots, i);
for k in i + 1..32 {
let (u, v) = at(&knots, k);
k2[k][1] = level(v.min(va + repair * (u - ua)));
}
}
free = Some(k2);
}
let next = match (pinned_ok, free) {
(true, Some(free)) => {
if error(&free).unwrap_or(f64::INFINITY) < error(&pinned).unwrap_or(f64::INFINITY) {
free
} else {
pinned
}
}
(true, None) => pinned,
(false, Some(free)) => free,
(false, None) => return None,
};
if lightcraft_pipeline::profiling() {
let moved: Vec<usize> = (0..32).filter(|&k| next[k][1] != knots[k][1]).collect();
eprintln!("[profile] camera tone: elasticity {:.1} at scene {:.4}, knots {moved:?} moved", slope(&knots, i, i + 1), knots[i][0]);
}
if next == knots {
return None;
}
knots = next;
}
None
}
fn median(values: &mut [f64]) -> Option<f64> {
@@ -182,5 +281,5 @@ pub(super) fn fit_tone_conditional(mut pairs: Vec<(f64, f64)>) -> Option<CameraT
}
i += n;
}
CameraTone::new(knots)
CameraTone::new(limit_elasticity(knots, &pairs)?)
}
+14
View File
@@ -193,6 +193,20 @@ pub(crate) fn names_photos(p: &Value) -> bool {
["ids", "id"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null()))
}
/// The call names its target photos in `ids`, whatever else it carries in `id` (`album.addPhotos`'s `id` is the album).
pub(crate) fn names_photo_ids(p: &Value) -> bool {
p.get("ids").is_some_and(|v| !v.is_null())
}
/// For a command that opts into `explicit_targets` but whose `id` isn't a photo: [`Session::execute`] skipped the
/// selection check because the call carries an `id`, so the command makes it itself unless `ids` names the photos.
pub(crate) fn enabled_unless_ids(s: &Session, p: &Value, id: &str, enabled: Enabled) -> Result<()> {
if names_photo_ids(p) {
return Ok(());
}
enabled(s).map_err(|why| EngineError::Disabled(id.to_string(), why))
}
/// The photos `ids` names: `None` when it is missing or null (the command then falls back to the
/// selection, or its own default), else every entry as a photo id. An `ids` that isn't a list of
/// whole numbers is an error, never `None`: falling back would act on the selection instead of
+201 -4
View File
@@ -256,10 +256,11 @@ pub fn specs() -> Vec<CommandSpec> {
"Rename Folder",
[],
None,
"{path, name} — rename a folder on disk (its files and sidecars go along) and relink the photos in it; one undo step (undo renames it back, refused if the old name is taken) → {path, relinked}",
"{path, name} — rename a folder on disk (its files and sidecars go along) and relink the photos in it; one undo step (undo renames it back, refused if the old name is taken); refused for the home folder and its Pictures, Desktop and Downloads → {path, relinked}",
always,
|s, p| {
let from = str_param(p, "path").ok_or_else(|| bad("folder.rename", "missing path"))?.trim_end_matches(['/', '\\']).to_string();
refuse_protected_place("folder.rename", &from)?;
let name = str_param(p, "name")
.map(str::trim)
.filter(|n| !n.is_empty() && !n.contains(['/', '\\']) && *n != "." && *n != "..")
@@ -274,10 +275,11 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Folder",
[],
None,
"{path, into: destination folder} — move a folder on disk into another and relink the photos in it; one undo step (undo moves it back, refused if the old place is taken) → {path, relinked}",
"{path, into: destination folder} — move a folder on disk into another and relink the photos in it; one undo step (undo moves it back, refused if the old place is taken); refused for the home folder and its Pictures, Desktop and Downloads → {path, relinked}",
always,
|s, p| {
let from = str_param(p, "path").ok_or_else(|| bad("folder.move", "missing path"))?.trim_end_matches(['/', '\\']).to_string();
refuse_protected_place("folder.move", &from)?;
let into = str_param(p, "into").ok_or_else(|| bad("folder.move", "missing into"))?;
let name = Path::new(&from).file_name().ok_or_else(|| bad("folder.move", "bad path"))?;
let to = Path::new(into).join(name).to_string_lossy().to_string();
@@ -483,15 +485,20 @@ 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);
follow_library_folder(&mut s.filter.folder, from, to);
if let Some(f) = s.shelved_filter.as_mut() {
follow_library_folder(&mut f.library_folder, from, to);
follow_library_folder(&mut f.folder, from, to);
}
if let Some(b) = &mut s.browse
&& let Ok(rel) = Path::new(&b.path).strip_prefix(from)
{
b.path = Path::new(to).join(rel).to_string_lossy().to_string();
let f = b.path.clone();
s.filter.folder = Some(f);
// with filters off the filter stays empty: Cmd+L brings back the one put aside
if s.shelved_filter.is_none() {
let f = b.path.clone();
s.filter.folder = Some(f);
}
}
}
@@ -550,3 +557,193 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result:
follow_folder(s, from, to);
Ok(n)
}
/// Whether `path` is the user's home folder or one of its standard places (Pictures, Desktop,
/// Downloads): the computer's own folders, which renaming or moving would break for every other
/// program. `home` is passed in so the check can be tested; the commands read the real one.
pub(crate) fn is_protected_place(path: &Path, home: &Path) -> bool {
use lightcraft_catalog::query::folder_key;
let home = home.to_string_lossy();
if home.is_empty() {
return false;
}
// compared without case where the usual volumes ignore it (macOS, Windows): there `pictures` is `Pictures`
let fold = cfg!(any(target_os = "macos", windows));
let key = |p: &str| if fold { folder_key(p).to_lowercase() } else { folder_key(p) };
let path = key(&path.to_string_lossy());
std::iter::once(home.to_string())
.chain(["Pictures", "Desktop", "Downloads"].map(|sub| Path::new(&*home).join(sub).to_string_lossy().to_string()))
.any(|p| key(&p) == path)
}
/// Refuses `from` when renaming or moving it would take the home folder or a standard place of it.
fn refuse_protected_place(command: &str, from: &str) -> Result<()> {
refuse_protected_place_in(command, from, crate::library::home_folder().as_deref())
}
/// What `from` names once the file system has read it: made absolute against the working folder
/// (the commands act on it that way) and with its parent's links followed, so a spelling through a
/// linked folder is the same place. The last name stays as written (a link that merely points at
/// Pictures is its own folder: renaming it renames the link), except that a name which is not a
/// link is also read in full, which turns a Windows short name (`DOWNLO~1`) into the long one.
fn named_places(from: &str) -> Vec<std::path::PathBuf> {
let spelled = std::path::absolute(from).unwrap_or_else(|_| from.into());
let followed = spelled.parent().and_then(|p| p.canonicalize().ok()).zip(spelled.file_name()).map(|(p, name)| p.join(name));
let is_link = std::fs::symlink_metadata(&spelled).is_ok_and(|m| m.file_type().is_symlink());
let read = if is_link { None } else { spelled.canonicalize().ok() };
std::iter::once(spelled).chain(followed).chain(read).collect()
}
/// The home folder and its standard places.
fn standard_places(home: &Path) -> Vec<std::path::PathBuf> {
std::iter::once(home.to_path_buf()).chain(["Pictures", "Desktop", "Downloads"].map(|sub| home.join(sub))).collect()
}
/// Whether `from` is, on disk, one of `places`, however it is spelled (a firmlink or bind mount
/// reaches the same folder under another path). A link to a place is not the place, but a place
/// that is itself a link stands for the folder it points to (the places are read through their
/// links), since renaming that folder would break the place.
#[cfg(unix)]
fn is_one_of(from: &str, places: &[std::path::PathBuf]) -> bool {
use std::os::unix::fs::MetadataExt;
let Ok(mine) = std::fs::symlink_metadata(std::path::absolute(from).unwrap_or_else(|_| from.into())) else { return false };
mine.is_dir() && places.iter().filter_map(|p| std::fs::metadata(p).ok()).any(|m| (m.dev(), m.ino()) == (mine.dev(), mine.ino()))
}
#[cfg(not(unix))]
fn is_one_of(_from: &str, _places: &[std::path::PathBuf]) -> bool {
false
}
fn refuse_protected_place_in(command: &str, from: &str, home: Option<&Path>) -> Result<()> {
let Some(home) = home.filter(|h| !h.as_os_str().is_empty()) else { return Ok(()) };
let homes: Vec<std::path::PathBuf> = std::iter::once(home.to_path_buf()).chain(home.canonicalize().ok()).collect();
let spelled = named_places(from).iter().any(|place| homes.iter().any(|h| is_protected_place(place, h)));
if spelled || is_one_of(from, &homes.iter().flat_map(|h| standard_places(h)).collect::<Vec<_>>()) {
return Err(bad(
command,
format!(
"{from} is the home folder or one of its standard places (Pictures, Desktop, Downloads); rename or move it in the system's file manager instead"
),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{is_protected_place, refuse_protected_place_in};
use std::path::Path;
#[test]
fn the_home_folder_and_its_standard_places_are_protected() {
let home = Path::new("/home/example");
for path in [
"/home/example",
"/home/example/",
"/home/example/Pictures",
"/home/example/Pictures/",
"/home/example/Desktop",
"/home/example/Downloads",
] {
assert!(is_protected_place(Path::new(path), home), "{path}");
}
for path in ["/home/example/Pictures/Trip", "/home/example/Documents", "/home/other", "/home", "/home/example2", "Pictures", ""] {
assert!(!is_protected_place(Path::new(path), home), "{path}");
}
// no home known: nothing is protected, and no relative path is mistaken for a place
assert!(!is_protected_place(Path::new("Pictures"), Path::new("")));
assert!(!is_protected_place(Path::new(""), Path::new("")));
// case counts only where the volume ignores it
assert_eq!(is_protected_place(Path::new("/home/example/pictures"), home), cfg!(any(target_os = "macos", windows)));
}
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("lightcraft-protected-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("home/Pictures")).expect("scratch home");
dir
}
#[test]
fn a_protected_place_is_refused_by_name_with_the_reason() {
let dir = scratch("named");
let home = dir.join("home");
for from in [home.clone(), home.join("Pictures"), home.join("Pictures").join(".")] {
let e = refuse_protected_place_in("folder.rename", &from.to_string_lossy(), Some(&home)).expect_err("refused").to_string();
assert!(e.contains("home folder") && e.contains("file manager"), "{e}");
}
assert!(refuse_protected_place_in("folder.move", &home.join("Pictures").join("Trip").to_string_lossy(), Some(&home)).is_ok());
assert!(refuse_protected_place_in("folder.rename", &home.to_string_lossy(), None).is_ok(), "no home known");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_relative_path_to_a_protected_place_is_refused() {
let dir = scratch("relative");
// the home folder is spelled through a link, so only the spelling as given can match it
#[cfg(unix)]
let home = {
std::os::unix::fs::symlink(dir.join("home"), dir.join("alias")).expect("link");
dir.join("alias")
};
#[cfg(not(unix))]
let home = dir.join("home");
// the commands act on the process's working folder, so a relative path names the real place
let cwd = std::env::current_dir().expect("working folder");
let relative = pathdiff(&home.join("Pictures"), &cwd);
if !Path::new(&relative).is_absolute() {
// what the commands will see: the working folder's spelling of the same place
assert!(super::named_places(&relative).iter().any(|p| is_protected_place(p, &home)), "{relative}");
assert!(refuse_protected_place_in("folder.rename", &relative, Some(&home)).is_err(), "{relative}");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// `target` as a path relative to `from` (both absolute), with `..` steps.
fn pathdiff(target: &Path, from: &Path) -> String {
let (t, f): (Vec<_>, Vec<_>) = (target.components().collect(), from.components().collect());
let common = t.iter().zip(&f).take_while(|(a, b)| a == b).count();
let mut out = std::path::PathBuf::new();
f[common..].iter().for_each(|_| out.push(".."));
t[common..].iter().for_each(|c| out.push(c));
out.to_string_lossy().to_string()
}
#[cfg(target_os = "macos")]
#[test]
fn a_protected_place_spelled_through_a_firmlink_is_refused() {
let dir = scratch("firmlink");
let home = dir.join("home");
// the data volume is also reachable under /System/Volumes/Data: the same folders, spelled otherwise
let real = home.canonicalize().expect("home");
let spelled = Path::new("/System/Volumes/Data").join(real.strip_prefix("/").expect("absolute"));
if spelled.is_dir() {
for from in [spelled.clone(), spelled.join("Pictures")] {
assert!(refuse_protected_place_in("folder.rename", &from.to_string_lossy(), Some(&home)).is_err(), "{}", from.display());
}
}
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn a_protected_place_reached_through_a_linked_parent_is_refused() {
let dir = scratch("linked");
let home = dir.join("home");
let alias = dir.join("alias");
std::os::unix::fs::symlink(&home, &alias).expect("link");
// the home folder is spelled one way, the path another, both naming the same folder
let through_the_link = alias.join("Pictures");
assert!(refuse_protected_place_in("folder.rename", &through_the_link.to_string_lossy(), Some(&home)).is_err());
assert!(
refuse_protected_place_in("folder.rename", &alias.join("Pictures").to_string_lossy(), Some(&alias)).is_err(),
"home spelled through the link"
);
// a link that merely points at Pictures is its own folder: renaming it renames the link
let shortcut = dir.join("shortcut");
std::os::unix::fs::symlink(home.join("Pictures"), &shortcut).expect("link");
assert!(refuse_protected_place_in("folder.rename", &shortcut.to_string_lossy(), Some(&home)).is_ok());
let _ = std::fs::remove_dir_all(&dir);
}
}
+92 -3
View File
@@ -51,6 +51,80 @@ fn refit_crop_angle(touched: bool, before: CropGeometry, d: &mut DevelopSettings
const CROP_ANGLE: &str = "crop.angle";
/// Whether a white balance mode renders its own white instead of the numbers stored on the photo: `As Shot`
/// renders the source's as-shot white, and on a raw edited in Kelvin a named preset renders its own Kelvin / tint
/// ([`WbMode::preset`]). Either way a number written into `temp` / `tint` is stored but read by nothing, so the
/// panel shows the number while the render uses the mode's white. `Custom` reads its stored numbers, and so does
/// `Auto` on such a raw: its white is resolved and stored when the mode is set (`develop.wb`), not at render time.
fn wb_mode_ignores_its_numbers(mode: WbMode, info: &lightcraft_pipeline::SourceInfo) -> bool {
mode == WbMode::AsShot || (info.raw && !info.relative_wb && mode.preset().is_some())
}
/// Bring a photo's settings onto the scale and mode a white balance partial names, so a one-field partial means
/// what it says (issue #2910, and its review). `None` when the partial needs no such preparation: it names both
/// numbers, neither, or a mode of its own. [`merge_settings_for_photo`] and `preset.apply` both start here, and
/// both finish with `normalize_wb` so the photo ends on the scale it is edited on.
pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value, info: &lightcraft_pipeline::SourceInfo) -> Option<DevelopSettings> {
let mut d = (*d).clone();
let wb = partial.get("wb").and_then(Value::as_object);
// the partial names one of the two numbers, and not both or neither
let one_field = wb.is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint"));
if !one_field {
return None;
}
// a photo whose source is edited in Kelvin is the one with two scales to trip over
let kelvin_source = info.raw && !info.relative_wb;
// the scale the partial's numbers are written on: an unmentioned scale means the relative scale, as `merged` reads it
let partial_scale = match wb.as_ref().and_then(|wb| wb.get("scale")).and_then(Value::as_str) {
Some("kelvin") => lightcraft_develop::WbScale::Kelvin,
_ => lightcraft_develop::WbScale::Legacy,
};
// put the photo onto the scale it is edited on: its values marked Kelvin, or a look still on the relative
// scale converted to the Kelvin / tint that renders the same
lightcraft_pipeline::local::normalize_wb(&mut d, info);
// a mode that answers its own white would swallow the partial's number: write the white the photo really
// renders as Custom values, so the number means what it says and the other field carries that white's look
if !wb.is_some_and(|wb| wb.contains_key("mode")) && wb_mode_ignores_its_numbers(d.wb.mode, info) {
let (t, tint) = lightcraft_pipeline::local::effective_wb(info, &d);
(d.wb.mode, d.wb.temp, d.wb.tint) = (WbMode::Custom, t, tint);
}
if kelvin_source && partial_scale == lightcraft_develop::WbScale::Legacy {
// and onto the partial's scale, so the field the partial leaves out is the photo's own look read there
let as_shot = (info.as_shot_temp, info.as_shot_tint);
let (kt, ktint) = lightcraft_pipeline::local::effective_wb(info, &d);
if let Some((lt, ltint)) = lightcraft_pipeline::local::kelvin_to_legacy(kt, ktint, as_shot) {
(d.wb.mode, d.wb.temp, d.wb.tint, d.wb.scale) = (WbMode::Custom, lt, ltint, lightcraft_develop::WbScale::Legacy);
}
}
Some(d)
}
/// Merge a partial settings JSON into a photo's settings (issue #2910). `DevelopSettings::merged` keeps a white
/// balance that names no scale on the relative scale; on a photo edited in Kelvin the field the partial does not
/// name (a partial with only `temp`, or only `tint`) would then be read on the other scale, giving a white neither
/// the photo nor the partial asked for. A one-field white balance partial is therefore resolved against the photo
/// first: the photo's white balance is brought onto the partial's scale with the photo's as-shot white
/// (`kelvin_to_legacy` / `legacy_to_kelvin` via `normalize_wb`), the partial merges unchanged, and the result lands
/// back on the photo's editing scale (`normalize_wb`), where the kept field carries the look the photo had.
/// Partials naming both fields, or neither, mean the same as before. A photo whose white balance mode renders its
/// own white — `As Shot`, or a named preset on a raw edited in Kelvin — has that white written out as Custom values
/// first ([`wb_mode_ignores_its_numbers`]), because a mode that answers its own white would otherwise store the
/// partial's number without any render reading it; a partial that names a `mode` itself stays authoritative.
pub(crate) fn merge_settings_for_photo(
d: &DevelopSettings,
partial: &Value,
info: &lightcraft_pipeline::SourceInfo,
) -> std::result::Result<DevelopSettings, serde_json::Error> {
let prepared = prepare_photo_for_wb_partial(d, partial, info);
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
let mut out = prepared.as_ref().unwrap_or(d).merged(partial)?;
if on_kelvin_scale {
// and the result back onto the scale this photo is edited on
lightcraft_pipeline::local::normalize_wb(&mut out, info);
}
Ok(out)
}
/// `v` as a list of numbers; `None` unless it is an array of nothing but numbers.
fn numbers(v: Option<&Value>) -> Option<Vec<f64>> {
v?.as_array()?.iter().map(Value::as_f64).collect()
@@ -256,8 +330,10 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("develop.merge", "Apply Settings JSON", [], None, "{settings: partial DevelopSettings JSON, label?}", has_active, |s, p| {
let partial = p.get("settings").cloned().ok_or_else(|| bad("develop.merge", "missing settings"))?;
let label = str_param(p, "label").unwrap_or("Edit").to_string();
let id = active(s, "develop.merge")?;
let info = s.source_info(id);
edit(s, "develop.merge", &label, |d| {
*d = d.merged(&partial).map_err(|e| bad("develop.merge", e.to_string()))?;
*d = merge_settings_for_photo(d, &partial, &info).map_err(|e| bad("develop.merge", e.to_string()))?;
Ok(())
})
}),
@@ -333,7 +409,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Section",
[],
None,
"{section: light|curve|color|mixer|grading|effects|vignette|grain|detail|optics|geometry}",
"{section: profile|light|curve|color|mixer|grading|effects|vignette|grain|detail|optics|geometry}",
has_active,
|s, p| {
let sec = section_param(p, "develop.resetSection")?;
@@ -1016,7 +1092,20 @@ pub fn specs() -> Vec<CommandSpec> {
let ops = ids
.iter()
.filter_map(|id| s.develop_of(*id).map(|d| (*id, d)))
.filter_map(|(id, d)| s.develop_op(id, preset.apply(&d, amount), &format!("Preset: {}", preset.name)))
.filter_map(|(id, d)| {
// a hand-written preset may name one white balance number only, and then it means the same as
// a partial: bring the photo onto that scale first, with its own as-shot white, and put the
// result back on the scale the photo is edited on (issue #2910) — the merge `develop.merge` uses
let info = s.source_info(id);
let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info);
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d);
let mut next = preset.apply(base, amount);
if on_kelvin_scale {
lightcraft_pipeline::local::normalize_wb(&mut next, &info);
}
s.develop_op(id, next, &format!("Preset: {}", preset.name))
})
.collect::<Vec<_>>();
s.commit(&format!("Preset: {}", preset.name), Op::Batch { ops })?;
ok()
+26 -5
View File
@@ -280,6 +280,7 @@ mod imp {
use lightcraft_faces::runtime::Embedder;
use lightcraft_geom::Rect;
use lightcraft_meta::{Region, RegionKind};
use rayon::prelude::*;
use serde_json::{Value, json};
use super::super::bad;
@@ -345,10 +346,12 @@ mod imp {
current_with(s, cmd, true)
}
/// Whether the background scan should look for faces in this photo: it is in the library, has no face regions at all
/// (nothing from XMP, nothing drawn or named, no earlier detection) and has not been searched yet.
/// Whether the background scan should look for faces in this photo: it is in the library, is not a video (the image
/// decoders can't read one, [`Photo::is_video`]), has no face regions at all (nothing from XMP, nothing drawn or
/// named, no earlier detection) and has not been searched yet.
fn needs_search(s: &Session, photo: &Photo) -> bool {
photo.in_library()
&& !photo.is_video()
&& !photo.meta.regions.iter().any(|r| r.kind == RegionKind::Face)
&& !s.faces.scanned.contains(photo.id.0)
&& !s.faces.scan_failed.contains(&photo.id.0)
@@ -731,11 +734,13 @@ mod imp {
return ready;
}
let bar = embedder.manifest().thresholds.match_cosine.unwrap_or(DEFAULT_THRESHOLD) * 0.8;
let refs: Vec<(&str, &[f32])> = gallery.iter().map(|e| ("person", &e[..])).collect();
let refs: Vec<&[f32]> = gallery.iter().map(|e| &e[..]).collect();
// every unnamed face against every face of theirs: some 400 million comparisons for a person with 4 000 faces
// in a library of 90 000, so on every core (minutes on one)
let mut scored: Vec<(f32, u64, usize, Rect)> = candidates
.into_iter()
.into_par_iter()
.filter_map(|(photo, index, rect, e)| {
let score = matching::rank(&e, &refs).first()?.score;
let score = matching::person_score(&e, &refs, matching::TOP_FACES)?;
(score >= bar).then_some((score, photo, index, rect))
})
.collect();
@@ -971,6 +976,22 @@ mod imp {
let _ = std::fs::remove_dir_all(&d);
}
/// A video went to the image decoders to be searched for faces and failed, once each launch: it is skipped, as the
/// grid's thumbnails skip it (issue #2682 is about those).
#[test]
fn a_video_is_not_searched_for_faces() {
let (mut s, d) = loaded("video");
let (a, _) = two_photos(&s);
let id = s.catalog.alloc_photo_id();
let path = d.join("clip.mp4").to_string_lossy().into_owned();
let clip = Photo::new(id, lightcraft_catalog::Source::File { path }, "clip.mp4", "VIDEO", 1920, 1080, "2026-10-24T00:00:00");
s.catalog.apply(Op::AddPhoto { photo: Box::new(clip) }).unwrap();
assert!(needs_search(&s, s.catalog.photo(a).unwrap()), "a photo is searched");
assert!(!needs_search(&s, s.catalog.photo(id).unwrap()));
assert!(!pending(&s, &[], true).contains(&id));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn only_the_background_scan_looks_for_faces_and_only_in_photos_without_any() {
let (mut s, d) = loaded("search");
+80
View File
@@ -1,6 +1,7 @@
//! Library-wide keyword commands: list (tree with counts), suggestions, rename, delete, merge;
//! keyword sets (nine keywords a keystroke away: ⌥1–⌥9) and Recent Keywords.
use lightcraft_catalog::Filter;
use lightcraft_catalog::keywords::{KeywordInfo, clean, closest, is_under, reparent};
use serde_json::{Value, json};
@@ -33,10 +34,17 @@ fn commit_keywords(s: &mut Session, label: &str, op: lightcraft_catalog::Op, fol
s.filter.keyword = follow(&k);
}
// a filter put aside by Enable Filters follows the keyword too
let mut gone_from_put_aside = false;
if let Some(f) = s.shelved_filter.as_mut()
&& let Some(k) = f.keyword.clone()
{
f.keyword = follow(&k);
// the keyword was deleted: if that emptied the filter, nothing is left to bring back. The rating
// operator filters nothing without stars, so it alone does not count as something to bring back.
gone_from_put_aside = f.keyword.is_none() && (Filter { rating_op: Default::default(), ..f.clone() }) == Filter::default();
}
if gone_from_put_aside {
s.shelved_filter = None;
}
Ok(json!({"changed": photos, "listed": listed}))
}
@@ -54,6 +62,7 @@ fn info_from(p: &Value, base: KeywordInfo) -> KeywordInfo {
export_synonyms: bool_or(p, "exportSynonyms", base.export_synonyms),
person: bool_or(p, "person", base.person),
new_keywords_inside: base.new_keywords_inside,
keyword_shortcut: base.keyword_shortcut,
}
}
@@ -139,6 +148,35 @@ pub fn slots(typed: &[String]) -> Vec<String> {
out
}
/// The keyword shortcut's keywords: a list, or one text with commas between them. Each is
/// cleaned, a new name goes inside the default parent as the Keywording box puts it, and each is
/// kept once whatever its case; empty ones are dropped. The text Set Keyword Shortcut… shows (the
/// keyword shortcut's keywords joined with ", ") keeps them as they are, commas in a name included.
/// Any other value, or parameters that are not an object, is an error, and the keyword shortcut is
/// left as it was.
fn shortcut_keywords(s: &Session, p: &Value) -> Result<Vec<String>> {
if !p.is_object() {
return Err(bad("keyword.setShortcut", "parameters must be an object"));
}
let now = s.catalog.keyword_shortcut();
let invalid = || bad("keyword.setShortcut", "`keywords` must be a string or an array of strings");
let typed: Vec<String> = match p.get("keywords") {
Some(Value::String(text)) if !now.is_empty() && text.trim() == now.join(", ") => return Ok(now),
Some(Value::String(text)) => text.split(',').map(str::to_string).collect(),
Some(Value::Array(a)) => a.iter().map(|k| k.as_str().map(str::to_string).ok_or_else(invalid)).collect::<Result<_>>()?,
None | Some(Value::Null) => Vec::new(),
Some(_) => return Err(invalid()),
};
let mut out: Vec<String> = Vec::new();
for k in typed {
let k = s.catalog.typed_keyword(&k);
if !k.is_empty() && !out.iter().any(|x| lightcraft_catalog::keywords::same(x, &k)) {
out.push(k);
}
}
Ok(out)
}
/// The nine keywords ⌥1–⌥9 apply: the current set's, or the recent ones.
pub fn current_keywords(s: &Session) -> Vec<String> {
let set = s.keyword_set.as_deref().and_then(|n| s.keyword_sets.iter().find(|x| same_set(&x.name, n)));
@@ -310,6 +348,48 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(r)
}
),
cmd!(query "keyword.shortcut", "Keyword Shortcut", [], None, "{} → {keywords: the keyword shortcut's, which ⇧K adds or removes}", always, |s, _| {
Ok(json!({"keywords": s.catalog.keyword_shortcut()}))
}),
cmd!(
"keyword.setShortcut",
"Set Keyword Shortcut",
[],
None,
"{keywords: [..] or \"a, b\" (none clears it)}: sets the keyword shortcut, a mark on its keywords in the keyword list (a new name is listed; one undo step) → {keywords}",
always,
|s, p| {
let op = s.catalog.set_keyword_shortcut_ops(&shortcut_keywords(s, p)?);
commit_keywords(s, "Set Keyword Shortcut", op, |k| Some(k.to_string()))?;
Ok(json!({"keywords": s.catalog.keyword_shortcut()}))
}
),
cmd!(
"keyword.toggleShortcut",
"Add or Remove Keyword Shortcut",
[],
Some("Shift+K"),
"{ids?}: removes the keyword shortcut's keywords from the target photos when they all have every one, else adds them → {changed, keywords, added}",
super::has_selection,
|s, p| {
let keywords = s.catalog.keyword_shortcut();
let ids = s.targets(p)?;
// with no keyword shortcut set, ⇧K returns without changing any photo
if keywords.is_empty() {
return Ok(json!({"changed": 0, "keywords": keywords}));
}
let has = |ph: &lightcraft_catalog::Photo, k: &str| {
ph.meta.keywords.iter().any(|x| lightcraft_catalog::keywords::same(&clean(x), &clean(k)))
};
let all = !ids.is_empty() && ids.iter().all(|id| s.catalog.photo(*id).is_some_and(|ph| keywords.iter().all(|k| has(ph, k))));
let ids: Vec<u64> = ids.iter().map(|i| i.0).collect();
let key = if all { "removeKeywords" } else { "addKeywords" };
let mut r = s.execute("photo.setMeta", &json!({"ids": ids, key: keywords}))?;
r["keywords"] = json!(keywords);
r["added"] = json!(!all);
Ok(r)
}
),
cmd!(query "keyword.list", "Keywords", [], None, "{} → [{name, path, count, children}] keyword tree (`a|b|c` keywords are hierarchical)", always, |s, _| {
Ok(serde_json::to_value(s.catalog.keyword_tree()).unwrap_or_default())
}),
+4
View File
@@ -29,6 +29,10 @@ mod flag_cycle_tests;
#[path = "library/tests_rated_out.rs"]
mod rated_out_tests;
#[cfg(test)]
#[path = "library/tests_clear_label.rs"]
mod clear_label_tests;
#[cfg(test)]
#[path = "library/tests_enable_filters.rs"]
mod enable_filters_tests;
+270 -28
View File
@@ -2,47 +2,191 @@
/// "51°30'26\"N 0°7'39\"W" (degrees, minutes, seconds; N/S/E/W or signs).
pub(crate) fn parse_gps(t: &str) -> Option<(f64, f64)> {
// typographic minus signs and dashes mean a negative value, like ASCII '-'
let t = t.replace(['\u{2212}', '\u{2012}', '\u{2013}', '\u{FE63}', '\u{FF0D}'], "-");
let t = t.trim();
// split into the two coordinates: at a comma, else after the first N/S hemisphere letter
let (a, b) = match t.split_once(',') {
Some((a, b)) => (a.trim().to_string(), b.trim().to_string()),
None => {
let lead = t.starts_with(['N', 'S', 'n', 's']);
let i = if lead {
// hemisphere letter first: "N 51.5 W 0.1" splits at the E/W letter
t.char_indices().skip(1).find(|(_, c)| matches!(c, 'E' | 'W' | 'e' | 'w')).map(|(i, _)| i)
} else {
t.find(['N', 'S', 'n', 's']).map(|i| i + 1)
}
.or_else(|| t.find(char::is_whitespace))?;
(t[..i].trim().to_string(), t[i..].trim().to_string())
if t.is_empty() || t.chars().take(129).count() > 128 {
return None;
}
let normalized = t.replace(['\u{2212}', '\u{2012}', '\u{2013}', '\u{FE63}', '\u{FF0D}'], "-");
let t = normalized.as_str();
if let Some((a, b)) = t.split_once(',') {
if b.contains(',') {
return None;
}
return parse_gps_pair(a, b);
}
// A suffix N/S marks the end of latitude; a prefix N/S uses the next hemisphere prefix as
// the boundary. If only longitude has a hemisphere, the whitespace pass below handles it.
let mut parsed: Option<(f64, f64)> = None;
let mut latitude_markers = t.char_indices().filter(|(_, c)| matches!(c, 'N' | 'S' | 'n' | 's'));
if let Some((first, marker)) = latitude_markers.next() {
if first == 0 {
if let Some((second, _)) = t.char_indices().skip(1).find(|(_, c)| is_gps_hemisphere(*c))
&& let Some(pair) = parse_gps_pair(t.get(..second)?, t.get(second..)?)
{
parsed = Some(pair);
}
} else {
let end = first.checked_add(marker.len_utf8())?;
return parse_gps_pair(t.get(..end)?, t.get(end..)?);
}
}
// A comma-free pair can be separated by whitespace. Trying each boundary also permits spaces
// between DMS components without letting unconsumed text vanish. If multiple boundaries parse,
// they must agree so ambiguous text cannot be reinterpreted.
for (at, separator) in t.char_indices().filter(|(_, c)| c.is_whitespace()) {
let after = at.checked_add(separator.len_utf8())?;
if let Some(pair) = parse_gps_pair(t.get(..at)?, t.get(after..)?) {
match parsed {
Some(previous) if previous != pair => return None,
None => parsed = Some(pair),
Some(_) => {}
}
}
}
parsed
}
#[derive(Clone, Copy)]
enum GpsAxis {
Latitude,
Longitude,
}
fn is_gps_hemisphere(c: char) -> bool {
matches!(c, 'N' | 'S' | 'E' | 'W' | 'n' | 's' | 'e' | 'w')
}
fn parse_gps_pair(latitude: &str, longitude: &str) -> Option<(f64, f64)> {
Some((parse_gps_coordinate(latitude, GpsAxis::Latitude)?, parse_gps_coordinate(longitude, GpsAxis::Longitude)?))
}
fn parse_gps_coordinate(text: &str, axis: GpsAxis) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
let prefix = ['N', 'S', 'E', 'W']
.into_iter()
.find_map(|h| text.strip_prefix(h).or_else(|| text.strip_prefix(h.to_ascii_lowercase())).map(|rest| (h, rest)));
let suffix = ['N', 'S', 'E', 'W']
.into_iter()
.find_map(|h| text.strip_suffix(h).or_else(|| text.strip_suffix(h.to_ascii_lowercase())).map(|rest| (rest, h)));
let (body, hemisphere) = if let Some((h, body)) = prefix {
(body, Some(h))
} else if let Some((body, h)) = suffix {
(body, Some(h))
} else {
(text, None)
};
let one = |s: &str, pos: char, neg: char| -> Option<f64> {
let up = s.to_ascii_uppercase();
let sign = if up.contains(neg) || up.trim_start().starts_with('-') { -1.0 } else { 1.0 };
let nums: Vec<f64> =
up.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|x| !x.is_empty()).map(|x| x.parse::<f64>().ok()).collect::<Option<_>>()?;
let v = match nums.as_slice() {
[d] => *d,
[d, m] => d + m / 60.0,
[d, m, s] => d + m / 60.0 + s / 3600.0,
if body.chars().any(is_gps_hemisphere) {
return None;
}
let body = body.trim();
if body.is_empty() {
return None;
}
let hemisphere_negative = match (axis, hemisphere) {
(_, None) => None,
(GpsAxis::Latitude, Some('N')) | (GpsAxis::Longitude, Some('E')) => Some(false),
(GpsAxis::Latitude, Some('S')) | (GpsAxis::Longitude, Some('W')) => Some(true),
_ => return None,
};
let mut components = Vec::with_capacity(3);
let mut token = String::new();
let mut explicit_sign = None;
let mut degree_mark = false;
let mut minute_mark = false;
let mut second_mark = false;
for c in body.chars() {
match c {
'0'..='9' | '.' => token.push(c),
'+' | '-' if components.is_empty() && token.is_empty() => token.push(c),
c if c.is_whitespace() => flush_gps_number(&mut token, &mut components, &mut explicit_sign)?,
'°' => {
flush_gps_number(&mut token, &mut components, &mut explicit_sign)?;
if components.len() != 1 || degree_mark || minute_mark || second_mark {
return None;
}
degree_mark = true;
}
'\'' | '′' => {
flush_gps_number(&mut token, &mut components, &mut explicit_sign)?;
if components.len() != 2 || minute_mark || second_mark {
return None;
}
minute_mark = true;
}
'"' | '″' => {
flush_gps_number(&mut token, &mut components, &mut explicit_sign)?;
if components.len() != 3 || !minute_mark || second_mark {
return None;
}
second_mark = true;
}
_ => return None,
};
let _ = pos;
Some(sign * v)
}
}
flush_gps_number(&mut token, &mut components, &mut explicit_sign)?;
let [degrees, rest @ ..] = components.as_slice() else { return None };
if rest.iter().any(|v| *v < 0.0 || *v >= 60.0) {
return None;
}
let magnitude = degrees.abs() + rest.first().copied().unwrap_or(0.0) / 60.0 + rest.get(1).copied().unwrap_or(0.0) / 3600.0;
if !magnitude.is_finite() {
return None;
}
let negative = match (hemisphere_negative, explicit_sign) {
(Some(hemisphere_negative), Some(explicit_negative)) if hemisphere_negative != explicit_negative => return None,
(Some(hemisphere_negative), _) => hemisphere_negative,
(None, Some(explicit_negative)) => explicit_negative,
(None, None) => false,
};
let (la, lo) = (one(&a, 'N', 'S')?, one(&b, 'E', 'W')?);
(la.abs() <= 90.0 && lo.abs() <= 180.0).then_some((la, lo))
let value = if negative { -magnitude } else { magnitude };
let limit = match axis {
GpsAxis::Latitude => 90.0,
GpsAxis::Longitude => 180.0,
};
(value.is_finite() && value.abs() <= limit).then_some(value)
}
fn flush_gps_number(token: &mut String, components: &mut Vec<f64>, explicit_sign: &mut Option<bool>) -> Option<()> {
if token.is_empty() {
return Some(());
}
if components.len() == 3 {
return None;
}
let value = token.parse::<f64>().ok()?;
if !value.is_finite() {
return None;
}
if components.is_empty() && (token.starts_with('-') || token.starts_with('+')) {
*explicit_sign = Some(token.starts_with('-'));
}
components.push(value);
token.clear();
Some(())
}
#[cfg(test)]
mod gps_tests {
use serde_json::json;
#[test]
fn coordinates_people_type() {
let p = super::parse_gps;
assert_eq!(p("51.5072, -0.1276"), Some((51.5072, -0.1276)));
assert_eq!(p("10 20 30"), None);
assert_eq!(p("10 20"), Some((10.0, 20.0)));
let (la, lo) = p("51°30'26\"N 0°7'39\"W").unwrap();
assert!((la - 51.50722).abs() < 1e-4 && (lo + 0.1275).abs() < 1e-4, "{la} {lo}");
let (la, lo) = p("33.8688 S, 151.2093 E").unwrap();
@@ -51,7 +195,105 @@ mod gps_tests {
assert_eq!(p("N 51.5072 W 0.1276"), Some((51.5072, -0.1276)));
assert_eq!(p("S 33.8688 E 151.2093"), Some((-33.8688, 151.2093)));
assert_eq!(p("\u{2212}33.8688, 151.2093"), Some((-33.8688, 151.2093)));
assert_eq!(p("51.5072 -0.1276"), Some((51.5072, -0.1276)));
assert_eq!(p("51.5072 0.1276 W"), Some((51.5072, -0.1276)));
let (la, lo) = p("51° 30' 26\" 0° 7' 39\"").unwrap();
assert!((la - 51.50722).abs() < 1e-4 && (lo - 0.1275).abs() < 1e-4, "{la} {lo}");
assert_eq!(p("95, 10"), None);
assert_eq!(p("hello"), None);
assert_eq!(p("s 33.8688 e 151.2093"), Some((-33.8688, 151.2093)));
assert_eq!(p("0N, 0E"), Some((0.0, 0.0)));
assert_eq!(p("90N, 180E"), Some((90.0, 180.0)));
assert_eq!(p("90S, 180W"), Some((-90.0, -180.0)));
}
#[test]
fn gps_does_not_reinterpret_exponents() {
assert_eq!(super::parse_gps("1e-3, 2e-3"), None);
}
#[test]
fn gps_rejects_wrong_axis_or_conflicting_hemispheres() {
let p = super::parse_gps;
assert_eq!(p("45E, 7N"), None);
assert_eq!(p("45E 7N"), None);
assert_eq!(p("45NS, 7E"), None);
assert_eq!(p("-45N, 7E"), None);
assert_eq!(p("45N 7NE"), None);
}
#[test]
fn gps_tries_whitespace_split_when_prefix_marker_split_fails() {
assert_eq!(super::parse_gps("N51 0E"), Some((51.0, 0.0)));
}
#[test]
fn gps_rejects_unconsumed_coordinate_text() {
assert_eq!(super::parse_gps("garbage45, 7junk"), None);
}
#[test]
fn gps_rejects_oversized_coordinate_text() {
let input = format!("{}, 0", "0".repeat(129));
assert_eq!(super::parse_gps(&input), None);
}
#[test]
fn gps_rejects_invalid_dms_components() {
let p = super::parse_gps;
assert_eq!(p("45°60'0\"N, 7E"), None);
assert_eq!(p("45°0'60\"N, 7E"), None);
assert_eq!(p("45°-1'0\"N, 7E"), None);
assert_eq!(p("45°0'-1\"N, 7E"), None);
}
#[test]
fn gps_rejected_text_does_not_change_metadata() {
let mut s = crate::Session::with_demo();
let ids: Vec<_> = s.catalog.photos().take(2).map(|photo| photo.id).collect();
assert_eq!(ids.len(), 2, "demo has two records for the batch check");
let id_values: Vec<_> = ids.iter().map(|id| id.0).collect();
s.execute("library.select", &json!({"ids": id_values})).unwrap();
s.execute("photo.setMeta", &json!({"title": "Before"})).unwrap();
s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.25})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.redo.is_empty(), "rejection must preserve a populated redo history");
let snapshot = s.catalog.to_snapshot();
let revision = s.catalog.revision;
let selection = s.selection.clone();
let commits = s.commits();
let undo = format!("{:?}", s.undo);
let redo = format!("{:?}", s.redo);
let error = s.execute("photo.setMeta", &json!({"gps": "garbage45, 7junk", "title": "After"})).unwrap_err();
assert!(matches!(error, crate::EngineError::BadParams { ref cmd, .. } if cmd == "photo.setMeta"), "{error}");
assert_eq!(s.catalog.to_snapshot(), snapshot, "catalog data is unchanged");
assert_eq!(s.catalog.revision, revision, "catalog revision is unchanged");
assert_eq!(s.selection, selection, "selection is unchanged");
assert_eq!(s.commits(), commits, "commit count is unchanged");
assert_eq!(format!("{:?}", s.undo), undo, "undo history is unchanged");
assert_eq!(format!("{:?}", s.redo), redo, "redo history is unchanged");
for id in ids {
assert_eq!(s.catalog.photo(id).map(|photo| photo.meta.title.as_str()), Some("Before"));
}
}
#[test]
fn gps_valid_edit_is_one_undo_step() {
let mut s = crate::Session::with_demo();
let id = s.active().or_else(|| s.catalog.photos().next().map(|photo| photo.id)).unwrap();
let previous = s.catalog.photo(id).unwrap().meta.clone();
let commits = s.commits();
s.execute("photo.setMeta", &json!({"gps": "48°51'30\"N 2°17'40\"E", "title": "GPS edited"})).unwrap();
let photo = s.catalog.photo(id).unwrap();
assert_eq!(photo.meta.title, "GPS edited");
assert!(photo.meta.gps.is_some());
assert_eq!(s.commits(), commits + 1);
s.execute("edit.undo", &json!({})).unwrap();
let photo = s.catalog.photo(id).unwrap();
assert_eq!(photo.meta.title, previous.title);
assert_eq!(photo.meta.gps, previous.gps);
}
}
+5 -1
View File
@@ -66,6 +66,10 @@ pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
}
None => Default::default(),
};
let rename_start = match p.get("renameStart").and_then(Value::as_u64) {
Some(n) => usize::try_from(n).map_err(|_| bad("library.import", "renameStart is too large for this platform"))?,
None => 1,
};
let opts = crate::import::ImportOptions {
on_deleted,
mode,
@@ -74,7 +78,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
destination: str_param(p, "destination").map(str::to_string),
organize,
rename: str_param(p, "rename").map(str::to_string),
rename_start: p.get("renameStart").and_then(Value::as_u64).unwrap_or(1) as usize,
rename_start,
metadata_preset,
convert_dng: bool_or(p, "dng", false),
local: bool_or(p, "local", false),
+15 -3
View File
@@ -35,10 +35,22 @@ pub(super) fn strs(p: &Value, key: &str) -> Vec<String> {
/// The targets an album can hold and how many were browsed (Local) photos, which album views
/// never show (issue #684): those are skipped, and reported, instead of becoming invisible members.
/// An id the catalog doesn't have (named outright, or kept selected after an undo took its photo
/// away) is dropped before anything changes, and isn't counted: `skipped` stays the Local count
/// the toasts name.
pub(super) fn album_targets(s: &Session, targets: Vec<PhotoId>) -> (Vec<PhotoId>, usize) {
let before = targets.len();
let kept: Vec<PhotoId> = targets.into_iter().filter(|id| s.catalog.photo(*id).is_none_or(|p| !p.local)).collect();
let skipped = before - kept.len();
let mut skipped = 0;
let kept: Vec<PhotoId> = targets
.into_iter()
.filter(|id| match s.catalog.photo(*id) {
None => false,
Some(p) if p.local => {
skipped += 1;
false
}
Some(_) => true,
})
.collect();
(kept, skipped)
}
+122 -73
View File
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Filter",
[],
None,
"partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, label?, kind?, merged?: hdr|panorama|hdrPanorama|any, edited?, date?, libraryFolder?: a path from library.folders, keyword?, person?, camera?}",
"partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, flags?: [pick|reject|none] (any of them; [] = no constraint), label?, kind?, merged?: hdr|panorama|hdrPanorama|any, edited?, date?, libraryFolder?: a path from library.folders, keyword?, person?, camera?}",
always,
|s, p| {
let mut v = serde_json::to_value(&s.filter).unwrap_or_default();
@@ -347,7 +347,10 @@ pub fn specs() -> Vec<CommandSpec> {
s.end_interaction()?;
match mode {
"replace" => {
s.selection = Selection { ids: ids.clone(), active: active.or(ids.first().copied()) };
// a repeated id is one photo: keep the first of each, in the order given
let mut seen = std::collections::HashSet::with_capacity(ids.len());
let ids: Vec<PhotoId> = ids.into_iter().filter(|id| seen.insert(*id)).collect();
s.selection = Selection { active: active.or(ids.first().copied()), ids };
}
"add" => {
for id in ids {
@@ -575,6 +578,16 @@ pub fn specs() -> Vec<CommandSpec> {
cull(s, p, |s| for_targets(s, p, "Set Color Label", |id| Some(Op::SetLabel { id, label: l })))
}
),
// `photo.label` takes the colour as a parameter, so a key can't be given to "none" alone
cmd!(
"photo.clearLabel",
"Clear Color Label",
["Photo", "Set Color Label"],
None,
"{ids?, advance?: bool} — `photo.label` with `none`; 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, "Set Color Label", |id| Some(Op::SetLabel { id, label: None }))) }
),
// ---- orientation
cmd!("photo.rotateLeft", "Rotate Left", ["Photo"], Some("Cmd+["), "{ids?}", has_selection, |s, p| rotate(s, p, false)),
cmd!("photo.rotateRight", "Rotate Right", ["Photo"], Some("Cmd+]"), "{ids?}", has_selection, |s, p| rotate(s, p, true)),
@@ -806,7 +819,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Smart Album…",
[],
None,
"{name, rules?: partial Filter (rating, ratingOp, flag, label, kind, edited, keyword, camera, lens, dateFrom, dateTo, date, text, album, ruleSet: {match: all|any|none, rules: [{field, op, value} | {group: ruleSet}]} — see album.ruleFields), parent?: folderId} — without `rules`, saves the current view (source + filter)",
"{name, rules?: partial Filter (rating, ratingOp, flag, flags, label, labels, kind, edited, keyword, camera, lens, dateFrom, dateTo, date, text, album, ruleSet: {match: all|any|none, rules: [{field, op, value} | {group: ruleSet}]} — see album.ruleFields), parent?: folderId} — without `rules`, saves the current view (source + filter)",
always,
|s, p| {
let name = str_param(p, "name").unwrap_or("Smart Album").trim().to_string();
@@ -877,7 +890,7 @@ pub fn specs() -> Vec<CommandSpec> {
view
} else {
let replace = bool_or(p, "replace", false);
let folder = cur.library_folder.clone();
let (folder, album) = (cur.library_folder.clone(), cur.album);
let base = if replace { Default::default() } else { cur };
let mut r = merge_rules(&base, p.get("rules").unwrap_or(&Value::Null), "album.setRules", &s.catalog, Some(id))?;
// the rules dialog has no folder field: replacing its rules keeps the folder
@@ -885,6 +898,11 @@ pub fn specs() -> Vec<CommandSpec> {
if replace && p.get("rules").and_then(|r| r.get("libraryFolder")).is_none() {
r.library_folder = folder;
}
// nor one for the album or folder of albums a saved view is limited to
// (`album: null` drops it)
if replace && p.get("rules").and_then(|r| r.get("album")).is_none() {
r.album = album;
}
r
};
let set = Op::SetAlbumRules { id, rules: Box::new(rules) };
@@ -1022,76 +1040,107 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({"changed": changed}))
}
),
cmd!(
"album.addPhotos",
"Add to Album",
["Photo"],
None,
"{id: albumId, ids?: [photoIds]} (default: selection) → {added, skipped}; Local photos are skipped (albums hold library photos), only Local ones is an error",
has_library_selection,
|s, p| {
let id = album_param(p, "id", "album.addPhotos")?;
let targets = crate::cmd::photo_ids(p, "album.addPhotos")?.unwrap_or_else(|| s.selected());
let al = s.catalog.album(id).ok_or_else(|| bad("album.addPhotos", "no such album"))?;
if al.is_smart() || al.folder {
return Err(bad("album.addPhotos", "smart albums and folders can't hold photos"));
}
let (targets, skipped) = album_targets_or_err(s, "album.addPhotos", targets)?;
let mut photos = al.photos.clone();
let before = photos.len();
// looked up, not searched for: adding thousands to a big album stays linear
let mut held: std::collections::HashSet<PhotoId> = photos.iter().copied().collect();
for t in targets {
if held.insert(t) {
photos.push(t);
CommandSpec {
explicit_targets: true,
..cmd!(
"album.addPhotos",
"Add to Album",
["Photo"],
None,
"{id: albumId, ids?: [photoIds]} (default: selection) → {added, skipped}; Local photos are skipped (albums hold library photos), only Local ones is an error; ids the library doesn't have are dropped; nothing new to add changes nothing (no undo step)",
has_library_selection,
|s, p| {
crate::cmd::enabled_unless_ids(s, p, "album.addPhotos", has_library_selection)?;
let id = album_param(p, "id", "album.addPhotos")?;
let targets = crate::cmd::photo_ids(p, "album.addPhotos")?.unwrap_or_else(|| s.selected());
let al = s.catalog.album(id).ok_or_else(|| bad("album.addPhotos", "no such album"))?;
if al.is_smart() || al.folder {
return Err(bad("album.addPhotos", "smart albums and folders can't hold photos"));
}
}
let added = photos.len() - before;
let cover = al.cover.or(photos.first().copied());
s.commit("Add to Album", Op::Batch { ops: vec![Op::SetAlbumPhotos { id, photos }, Op::SetAlbumCover { id, cover }] })?;
Ok(json!({"added": added, "skipped": skipped}))
}
),
cmd!(
"album.toggleTarget",
"Add to Target Album",
[],
None,
"{ids?} — B: adds the photos to the target album (the Quick Collection unless one is set), or removes them when they're all in it → {album, added, skipped}; Local photos are skipped",
has_library_selection,
|s, p| {
let targets =
album_targets_or_err(s, "album.toggleTarget", crate::cmd::photo_ids(p, "album.toggleTarget")?.unwrap_or_else(|| s.selected()))?;
let (targets, skipped) = targets;
let target = s.target_album.filter(|a| s.catalog.album(*a).is_some_and(|al| !al.is_smart() && !al.folder));
let id = match target.or_else(|| s.catalog.quick_collection()) {
Some(id) => id,
None => {
let id = s.catalog.alloc_album_id();
let album = Album { quick: true, ..Album::new(id, "Quick Collection") };
s.commit("New Quick Collection", Op::AddAlbum { album })?;
id
let (targets, skipped) = album_targets_or_err(s, "album.addPhotos", targets)?;
let mut photos = al.photos.clone();
let before = photos.len();
// looked up, not searched for: adding thousands to a big album stays linear
let mut held: std::collections::HashSet<PhotoId> = photos.iter().copied().collect();
for t in targets {
if held.insert(t) {
photos.push(t);
}
}
};
let al = s.catalog.album(id).ok_or_else(|| bad("album.toggleTarget", "no target album"))?;
// looked up, not searched for: thousands toggled in a big album stay linear
let mut held: std::collections::HashSet<PhotoId> = al.photos.iter().copied().collect();
let all_in = !targets.is_empty() && targets.iter().all(|t| held.contains(t));
let photos: Vec<PhotoId> = if all_in {
let targets: std::collections::HashSet<PhotoId> = targets.iter().copied().collect();
al.photos.iter().copied().filter(|x| !targets.contains(x)).collect()
} else {
al.photos.iter().copied().chain(targets.iter().copied().filter(|t| held.insert(*t))).collect()
};
let name = al.name.clone();
let cover = al.cover.filter(|c| photos.contains(c)).or(photos.first().copied());
s.commit(
if all_in { "Remove from Target Album" } else { "Add to Target Album" },
Op::Batch { ops: vec![Op::SetAlbumPhotos { id, photos }, Op::SetAlbumCover { id, cover }] },
)?;
Ok(json!({"album": id.0, "name": name, "added": !all_in, "count": s.catalog.album_count(id), "skipped": skipped}))
}
),
let added = photos.len() - before;
// all of them were there already (or none was left to add): the album is unchanged,
// so no undo step, and redo stays
if added == 0 {
return Ok(json!({"added": 0, "skipped": skipped}));
}
let cover = al.cover.or(photos.first().copied());
s.commit("Add to Album", Op::Batch { ops: vec![Op::SetAlbumPhotos { id, photos }, Op::SetAlbumCover { id, cover }] })?;
Ok(json!({"added": added, "skipped": skipped}))
}
)
},
CommandSpec {
explicit_targets: true,
..cmd!(
"album.toggleTarget",
"Add to Target Album",
[],
None,
"{ids?} — B: adds the photos to the target album (the Quick Collection unless one is set), or removes them when they're all in it → {album, added, toggled, skipped}; Local photos are skipped, ids the library doesn't have are dropped (none left: nothing changes and `added` is null)",
has_library_selection,
|s, p| {
crate::cmd::enabled_unless_ids(s, p, "album.toggleTarget", has_library_selection)?;
let targets = album_targets_or_err(
s,
"album.toggleTarget",
crate::cmd::photo_ids(p, "album.toggleTarget")?.unwrap_or_else(|| s.selected()),
)?;
let (targets, skipped) = targets;
// nothing left to toggle (every id named is gone): no album is made or changed
if targets.is_empty() {
let existing = s
.target_album
.filter(|a| s.catalog.album(*a).is_some_and(|al| !al.is_smart() && !al.folder))
.or_else(|| s.catalog.quick_collection());
let al = existing.and_then(|a| s.catalog.album(a));
return Ok(
json!({"album": al.map(|a| a.id.0), "name": al.map(|a| a.name.clone()), "added": null, "toggled": 0, "count": al.map_or(0, |a| s.catalog.album_count(a.id)), "skipped": skipped}),
);
}
let target = s.target_album.filter(|a| s.catalog.album(*a).is_some_and(|al| !al.is_smart() && !al.folder));
let id = match target.or_else(|| s.catalog.quick_collection()) {
Some(id) => id,
None => {
let id = s.catalog.alloc_album_id();
let album = Album { quick: true, ..Album::new(id, "Quick Collection") };
s.commit("New Quick Collection", Op::AddAlbum { album })?;
id
}
};
let al = s.catalog.album(id).ok_or_else(|| bad("album.toggleTarget", "no target album"))?;
// looked up, not searched for: thousands toggled in a big album stay linear
let mut held: std::collections::HashSet<PhotoId> = al.photos.iter().copied().collect();
let all_in = targets.iter().all(|t| held.contains(t));
let photos: Vec<PhotoId> = if all_in {
let targets: std::collections::HashSet<PhotoId> = targets.iter().copied().collect();
al.photos.iter().copied().filter(|x| !targets.contains(x)).collect()
} else {
al.photos.iter().copied().chain(targets.iter().copied().filter(|t| held.insert(*t))).collect()
};
let name = al.name.clone();
// photos that went in or came out: what a toast can say (not the ones that were in already)
let toggled = al.photos.len().abs_diff(photos.len());
let cover = al.cover.filter(|c| photos.contains(c)).or(photos.first().copied());
s.commit(
if all_in { "Remove from Target Album" } else { "Add to Target Album" },
Op::Batch { ops: vec![Op::SetAlbumPhotos { id, photos }, Op::SetAlbumCover { id, cover }] },
)?;
Ok(
json!({"album": id.0, "name": name, "added": !all_in, "toggled": toggled, "count": s.catalog.album_count(id), "skipped": skipped}),
)
}
)
},
cmd!("album.setTarget", "Set as Target Album", [], None, "{id: albumId | null} (null = the Quick Collection)", always, |s, p| {
s.target_album = match p.get("id").and_then(Value::as_u64) {
Some(a) => {
@@ -1289,7 +1338,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Photos",
["File"],
Some("Cmd+Shift+I"),
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1, metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
always,
|s, p| {
let req = import_params(s, p)?;
@@ -0,0 +1,70 @@
//! `photo.clearLabel`: the colour label taken off, as a command that can have a key of its own (#2980).
use lightcraft_catalog::{ColorLabel, Op, Photo, PhotoId, Source};
use serde_json::json;
use crate::{Result, Session};
fn session() -> Result<Session> {
let mut s = Session::new();
for (id, label) in [(1, Some(ColorLabel::Red)), (2, Some(ColorLabel::Purple)), (3, Some(ColorLabel::Blue)), (4, None)] {
let mut photo = Photo::new(
PhotoId(id),
Source::File { path: format!("/lightcraft-clear-label/{id}.jpg") },
&format!("{id}.jpg"),
"JPEG",
40,
30,
"2026-10-25",
);
photo.label = label;
s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) })?;
}
s.execute("library.sort", &json!({"key": "fileName", "ascending": true}))?;
Ok(s)
}
fn labels(s: &Session) -> Vec<Option<ColorLabel>> {
(1..=4).map(|id| s.catalog.photo(PhotoId(id)).unwrap().label).collect()
}
#[test]
fn the_selected_photos_lose_their_label_in_one_undo_step() {
let mut s = session().unwrap();
s.execute("library.select", &json!({"ids": [1, 2], "active": 2})).unwrap();
s.execute("photo.clearLabel", &json!({})).unwrap();
assert_eq!(labels(&s), [None, None, Some(ColorLabel::Blue), None]);
assert_eq!(s.undo.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(labels(&s), [Some(ColorLabel::Red), Some(ColorLabel::Purple), Some(ColorLabel::Blue), None]);
}
#[test]
fn it_does_what_photo_label_none_does() {
let mut a = session().unwrap();
let mut b = session().unwrap();
for s in [&mut a, &mut b] {
s.execute("library.select", &json!({"ids": [3]})).unwrap();
}
a.execute("photo.clearLabel", &json!({})).unwrap();
b.execute("photo.label", &json!({"label": "none"})).unwrap();
assert_eq!(labels(&a), labels(&b));
assert_eq!(a.undo.len(), b.undo.len());
}
#[test]
fn ids_name_the_photos_and_an_unlabelled_or_unknown_photo_is_handled() {
let mut s = session().unwrap();
s.execute("library.select", &json!({"ids": [4]})).unwrap();
s.execute("photo.clearLabel", &json!({"ids": [1]})).unwrap();
assert_eq!(labels(&s), [None, Some(ColorLabel::Purple), Some(ColorLabel::Blue), None]);
// a photo without a label is left as it is, and a photo that does not exist is an error
s.execute("photo.clearLabel", &json!({"ids": [4]})).unwrap();
assert!(s.execute("photo.clearLabel", &json!({"ids": [999]})).is_err());
}
#[test]
fn it_has_no_key_of_its_own_and_is_listed_for_the_keyboard_shortcuts_editor() {
let spec = crate::command_specs().iter().find(|c| c.id == "photo.clearLabel").expect("registered");
assert_eq!(spec.shortcut, None, "the 6-9 keys are Lightroom's; none is given to clearing");
assert_eq!(spec.label, "Clear Color Label");
}
@@ -152,3 +152,72 @@ fn a_keyword_renamed_while_off_is_followed_by_the_filter_put_aside() {
assert_eq!(s.filter.keyword.as_deref(), Some("dog"), "the put-aside filter follows the rename");
assert_eq!(s.visible().len(), 1);
}
/// The session's photos plus one photo that carries the keyword "cat".
fn session_with_a_cat() -> Session {
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
}
#[test]
fn deleting_the_only_keyword_put_aside_leaves_filtering_on() {
let mut s = session_with_a_cat();
s.execute("library.filter", &json!({"keyword": "cat"})).unwrap();
assert_eq!(s.visible().len(), 1);
s.execute("library.toggleFilters", &json!({})).unwrap();
assert!(s.filters_off());
s.execute("keyword.delete", &json!({"keyword": "cat"})).unwrap();
assert!(!s.filters_off(), "an empty filter is not left put aside");
let r = s.execute("library.toggleFilters", &json!({})).unwrap();
assert_eq!((r["enabled"].clone(), r["count"].clone()), (json!(true), json!(5)), "nothing was put aside, so nothing is switched off");
assert_eq!(s.filter, Filter::default());
}
#[test]
fn deleting_a_keyword_put_aside_keeps_the_rest_of_the_filter() {
let mut s = session_with_a_cat();
s.execute("library.filter", &json!({"keyword": "cat", "rating": 4})).unwrap();
s.execute("library.toggleFilters", &json!({})).unwrap();
s.execute("keyword.delete", &json!({"keyword": "cat"})).unwrap();
assert!(s.filters_off(), "the stars are still put aside");
s.execute("library.toggleFilters", &json!({})).unwrap();
assert_eq!(s.filter, Filter { rating: 4, ..Default::default() });
}
#[test]
fn a_rating_operator_without_stars_does_not_keep_an_emptied_filter_put_aside() {
let mut s = session_with_a_cat();
// the filter bar's operator picker can be set with no stars chosen; it filters nothing
s.execute("library.filter", &json!({"keyword": "cat", "ratingOp": "exactly"})).unwrap();
s.execute("library.toggleFilters", &json!({})).unwrap();
assert!(s.filters_off());
s.execute("keyword.delete", &json!({"keyword": "cat"})).unwrap();
assert!(!s.filters_off(), "only an operator with no stars is left: nothing to bring back");
let r = s.execute("library.toggleFilters", &json!({})).unwrap();
assert_eq!(r["enabled"], json!(true));
}
#[test]
fn a_rating_operator_put_aside_survives_a_keyword_change_that_does_not_touch_it() {
let mut s = session_with_a_cat();
s.execute("library.filter", &json!({"ratingOp": "exactly"})).unwrap();
s.execute("library.toggleFilters", &json!({})).unwrap();
assert!(s.filters_off());
s.execute("keyword.rename", &json!({"from": "cat", "to": "dog"})).unwrap();
assert!(s.filters_off(), "the filter put aside held no keyword, so the rename leaves it alone");
s.execute("library.toggleFilters", &json!({})).unwrap();
assert_eq!(s.filter.rating_op, lightcraft_catalog::RatingOp::Exactly);
}
#[test]
fn a_rating_operator_with_stars_is_kept_when_the_keyword_goes() {
let mut s = session_with_a_cat();
s.execute("library.filter", &json!({"keyword": "cat", "rating": 4, "ratingOp": "exactly"})).unwrap();
s.execute("library.toggleFilters", &json!({})).unwrap();
s.execute("keyword.delete", &json!({"keyword": "cat"})).unwrap();
s.execute("library.toggleFilters", &json!({})).unwrap();
assert_eq!((s.filter.rating, s.filter.rating_op), (4, lightcraft_catalog::RatingOp::Exactly));
}
@@ -65,6 +65,7 @@ fn flags_and_labels_that_leave_the_view_go_on_to_the_next_photo_too() {
(json!({"flag": "pick"}), "photo.cycleFlag", json!({})),
(json!({"flag": "pick"}), "photo.decreaseFlag", json!({})),
(json!({"label": "red"}), "photo.label", json!({"label": "none"})),
(json!({"label": "red"}), "photo.clearLabel", json!({})),
(json!({}), "photo.increaseRating", json!({})),
] {
let mut s = one_star().unwrap();
+6 -6
View File
@@ -1,6 +1,8 @@
//! Masking and Remove (spot) commands on the active photo.
use lightcraft_develop::{BrushStroke, LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape, RedEye, Spot, SpotMode};
use lightcraft_develop::{
BrushStroke, LocalAdjustments, MAX_COLOR_RANGE_SAMPLES, MAX_RED_EYES, Mask, MaskComponent, MaskOp, MaskShape, RedEye, Spot, SpotMode,
};
use lightcraft_geom::Point;
use serde_json::{Value, json};
@@ -8,11 +10,6 @@ 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 {
@@ -1025,6 +1022,9 @@ pub fn specs() -> Vec<CommandSpec> {
catchlight: None,
};
let id = s.active().ok_or_else(|| bad(c, "no active photo"))?;
if s.develop_of(id).is_some_and(|d| d.red_eye.len() >= MAX_RED_EYES) {
return Err(bad(c, format!("at most {MAX_RED_EYES} red eye corrections")));
}
let mut dd = (*s.develop_of(id).unwrap_or_default()).clone();
dd.red_eye.push(eye);
let n = dd.red_eye.len();
+73 -3
View File
@@ -41,7 +41,77 @@ pub fn missing(s: &Session) -> Vec<(PhotoId, String)> {
if cfg!(target_arch = "wasm32") {
return Vec::new();
}
missing_with(&s.catalog, |f| Path::new(f).exists())
let exists = s.media.availability.probe();
missing_with(&s.catalog, |f| exists(f))
}
/// Every in-scope photo with its file ([`checked_path`]), without touching the disk: what a
/// sweep ([`sweep`]) goes through, so a caller can take the list on its own thread and check
/// the files on another.
pub fn checked(cat: &Catalog) -> Vec<(PhotoId, String)> {
cat.photos().filter_map(|p| checked_path(p).map(|f| (p.id, f.to_string()))).collect()
}
fn fingerprint_of<'a>(entries: impl Iterator<Item = (PhotoId, &'a str)>) -> u64 {
use std::hash::{DefaultHasher, Hash, Hasher};
entries.fold(0u64, |sum, entry| {
let mut h = DefaultHasher::new();
entry.hash(&mut h);
sum.wrapping_add(h.finish())
})
}
/// What [`checked`] lists, as one number (the photos in scope and the file each one points at,
/// whatever their order), without building the list. A caller that took `checked` and checked its
/// files on another thread compares it with [`fingerprint_of_checked`] to know whether the photos
/// changed meanwhile.
pub fn fingerprint(cat: &Catalog) -> u64 {
fingerprint_of(cat.photos().filter_map(|p| checked_path(p).map(|f| (p.id, f))))
}
/// [`fingerprint`] of the list [`checked`] gave.
pub fn fingerprint_of_checked(files: &[(PhotoId, String)]) -> u64 {
fingerprint_of(files.iter().map(|(id, f)| (*id, f.as_str())))
}
/// What of `gone` (a sweep's answer, of the catalog as it was) still holds in `cat` as it is now: the
/// photos still in scope that still point at the file that was not found. A photo removed, moved to
/// Recently Deleted or relinked since is not reported as missing; one added since was not checked.
pub fn still_missing(cat: &Catalog, gone: Vec<(PhotoId, String)>) -> Vec<(PhotoId, String)> {
gone.into_iter().filter(|(id, file)| cat.photo(*id).and_then(|p| checked_path(p)) == Some(file.as_str())).collect()
}
/// How many files [`sweep`] checks between two reports of its progress.
const PROGRESS_EVERY: usize = 64;
/// The files among `files` that `exists` doesn't find, in order: [`missing`] for a caller that
/// checks on a thread of its own. `stop` is asked before every check (`None`: it said yes, and
/// the rest was not looked at); `progress` is told how many files are done every few dozen.
pub fn sweep(
files: Vec<(PhotoId, String)>,
exists: impl Fn(&str) -> bool,
stop: impl Fn() -> bool,
progress: impl Fn(usize),
) -> Option<Vec<(PhotoId, String)>> {
let mut gone = Vec::new();
for (done, (id, file)) in files.into_iter().enumerate() {
if stop() {
return None;
}
if done % PROGRESS_EVERY == 0 {
progress(done);
}
if !exists(&file) {
gone.push((id, file));
}
}
// (a stop that came during the last check is honoured too)
(!stop()).then_some(gone)
}
/// `library.missing`'s answer: `[{id, path}]`.
pub fn missing_json(gone: Vec<(PhotoId, String)>) -> Value {
Value::Array(gone.into_iter().map(|(id, path)| json!({"id": id.0, "path": path})).collect())
}
/// Whether photo `id` is in scope and its file is gone (the Missing Photos view checks only
@@ -418,8 +488,8 @@ fn find_missing(s: &mut Session, p: &Value) -> Result<Value> {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "library.missing", "Missing Photos", [], None, "{} → [{id, path}] — photos whose original file isn't where the library expects it", always, |s, _| {
Ok(Value::Array(missing(s).into_iter().map(|(id, path)| json!({"id": id.0, "path": path})).collect()))
cmd!(query "library.missing", "Missing Photos", [], None, "{} → [{id, path}] — photos whose original file isn't where the library expects it (every file is looked at: on a network share that takes minutes, so the desktop app, asked over its control channel, checks on a worker thread, with a row in the activity stack that can stop it, and answers when it is done)", always, |s, _| {
Ok(missing_json(missing(s)))
}),
cmd!(
"photo.relink",
+45 -6
View File
@@ -3,6 +3,7 @@
use lightcraft_catalog::{HistoryStep, Op, PhotoId, Stack, StackId};
use serde_json::{Value, json};
use std::collections::HashMap;
use super::{CommandSpec, always, bad, bool_or, cmd, f64_or, has_selection, str_param};
use crate::{Result, Selection, Session};
@@ -63,18 +64,53 @@ fn copy_number(name: Option<&str>) -> u32 {
name.and_then(|n| n.strip_prefix("Copy ")).and_then(|n| n.trim().parse().ok()).unwrap_or(0)
}
/// Resolve every requested name before creating copies, so an exhausted counter cannot leave a
/// partially completed batch. Explicit names do not depend on the numeric sequence.
fn virtual_copy_names(s: &Session, targets: &[PhotoId], name: Option<&str>) -> Result<Vec<Option<String>>> {
if let Some(name) = name {
return Ok(targets.iter().map(|id| s.catalog.photo(*id).map(|_| name.to_string())).collect());
}
let mut last_by_master = HashMap::new();
for id in targets {
if let Some(photo) = s.catalog.photo(*id) {
last_by_master.entry(photo.copy_of.unwrap_or(*id)).or_insert(0_u32);
}
}
for photo in s.catalog.photos() {
if let Some(master) = photo.copy_of
&& let Some(last) = last_by_master.get_mut(&master)
{
*last = (*last).max(copy_number(photo.copy_name.as_deref()));
}
}
targets
.iter()
.map(|id| {
let Some(photo) = s.catalog.photo(*id) else { return Ok(None) };
let master = photo.copy_of.unwrap_or(*id);
let last = last_by_master.get_mut(&master).ok_or_else(|| bad("photo.virtualCopy", "could not resolve the virtual-copy master"))?;
let number = last.checked_add(1).ok_or_else(|| {
bad("photo.virtualCopy", format!("default virtual-copy numbering is exhausted for master {}; provide an explicit name", master.0))
})?;
*last = number;
Ok(Some(format!("Copy {number}")))
})
.collect()
}
/// Create one virtual copy of `src`: a new photo sharing its file, with the same settings and
/// metadata, added to the same albums and stacked right after it (the stack is expanded so the
/// copy is visible). `name` replaces the default "Copy N".
fn virtual_copy(s: &mut Session, src: PhotoId, name: Option<&str>) -> Result<Option<PhotoId>> {
/// copy is visible). `name` is resolved by the command before any copies are created.
fn virtual_copy(s: &mut Session, src: PhotoId, name: &str) -> Result<Option<PhotoId>> {
let Some(orig) = s.catalog.photo(src).cloned() else { return Ok(None) };
let master = orig.copy_of.unwrap_or(src);
let n = 1 + s.catalog.photos().filter(|p| p.copy_of == Some(master)).map(|p| copy_number(p.copy_name.as_deref())).max().unwrap_or(0);
let id = s.catalog.alloc_photo_id();
let mut c = (*orig).clone();
c.id = id;
c.copy_of = Some(master);
c.copy_name = Some(name.map_or_else(|| format!("Copy {n}"), str::to_string));
c.copy_name = Some(name.to_string());
c.versions.clear();
c.history = vec![HistoryStep { label: "Virtual Copy".into(), settings: c.develop.clone() }];
c.deleted = false;
@@ -113,9 +149,12 @@ pub fn specs() -> Vec<CommandSpec> {
|s, p| {
let targets = s.targets(p)?;
let name = str_param(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string);
let names = virtual_copy_names(s, &targets, name.as_deref())?;
let mut made = Vec::new();
for t in targets {
if let Some(id) = virtual_copy(s, t, name.as_deref())? {
for (t, name) in targets.into_iter().zip(names) {
if let Some(name) = name
&& let Some(id) = virtual_copy(s, t, &name)?
{
made.push(id);
}
}
+21 -1
View File
@@ -320,9 +320,13 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
type SmartJob = (lightcraft_catalog::PhotoId, std::path::PathBuf, Option<crate::media::SourceRef>, bool);
/// DNG tone fits also go stale, although DNGs keep their own matrix and Kelvin white-balance scale.
/// So do preview-only raws: their proxy is the embedded JPEG, read in the colour space the raw
/// declares, which a look version bump can change too (#2654).
#[cfg(not(target_arch = "wasm32"))]
fn preview_fitted_look(photo: &lightcraft_catalog::Photo) -> bool {
photo.fitted_look() || (photo.develops_raw() && photo.format.eq_ignore_ascii_case("DNG"))
photo.fitted_look()
|| (photo.develops_raw() && photo.format.eq_ignore_ascii_case("DNG"))
|| (photo.kind == lightcraft_catalog::MediaKind::Raw && photo.preview_only.is_some())
}
/// Held while one proxy is checked and (re)written, so Build Smart Previews and the opening look
@@ -691,6 +695,22 @@ mod tests {
use crate::Session;
use crate::media::SourceRef;
// Given a preview-only raw, its proxy goes stale with the look version: the embedded JPEG's colour
// space can change with it (#2654); a rendered photo's proxy does not
#[test]
fn preview_only_raws_follow_the_look_version() {
use lightcraft_catalog::{MediaKind, Photo, PhotoId, Source};
let mut ph = Photo::new(PhotoId(1), Source::File { path: "/x.cr3".into() }, "x.cr3", "CR3", 6000, 4000, "2026-10-23T00:00:00");
ph.kind = MediaKind::Raw;
assert!(super::preview_fitted_look(&ph), "a developed CR3");
ph.set_preview_only(Some("unsupported".into()));
assert!(super::preview_fitted_look(&ph), "a preview-only CR3");
ph.kind = MediaKind::Image;
ph.format = "JPG".into();
ph.set_preview_only(None);
assert!(!super::preview_fitted_look(&ph), "a JPEG");
}
// Given a photo's preview jobs, the grid thumbnail is made from the source the view decoded, not
// by reading the file again (here: a thumbnail job pointing at a file that is not there)
#[test]
+21 -2
View File
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
.map(|r| json!({"group": r.group, "tag": r.tag, "name": r.name, "value": r.value}))
.collect();
// Keep sidecar precedence; reuse the loaded bytes for embedded XMP.
let packet = match crate::sidecar::find_sidecar(path, s.sidecar_naming(ph.id)) {
let packet = match s.sidecar_lookup(ph.id).find(path) {
Some(sc) => std::fs::read_to_string(sc).ok(),
None => lightcraft_meta::embedded(&bytes).xmp,
};
@@ -230,10 +230,29 @@ pub fn specs() -> Vec<CommandSpec> {
"versions": ph.versions.iter().map(|v| json!({"name": v.name, "created": v.created})).collect::<Vec<_>>(),
}))
}),
cmd!(query "app.gpu", "GPU Rendering", [], None, "{enabled?: bool} — allow/forbid GPU rendering (CPU fallback; LIGHTCRAFT_GPU=0 forbids it for the process); returns {enabled, available, adapter, reason (why the GPU is off), lastFallback (latest render redone on the CPU, and why)}", always, |_, p| {
cmd!(query "app.gpu", "GPU Rendering", [], None, "{enabled?: bool, wait?: bool} — allow/forbid GPU rendering (CPU fallback; LIGHTCRAFT_GPU=0 forbids it for the process); returns {enabled, available, adapter, reason (why the GPU is off), lastFallback (latest render redone on the CPU, and why)}. wait: false never waits for a device still being created (available, adapter and reason are then null and the device is created in the background; with GPU rendering off they say so at once)", always, |_, p| {
if let Some(on) = p.get("enabled").and_then(Value::as_bool) {
lightcraft_gpu::set_enabled(on);
}
// the UI applies the setting on its first frame: it must not wait seconds for the
// device there (issue #136; `warm_up` creates it off the UI thread)
if p.get("wait").and_then(Value::as_bool) == Some(false) && !lightcraft_gpu::ready() {
// off (preference, environment): known at once, and asking the adapter would
// create the device; on: still being created, so nothing is known yet
let on = lightcraft_gpu::enabled();
if on {
// a caller that never waits still gets an answer later (off the UI thread;
// starts at most once)
lightcraft_gpu::warm_up();
}
return Ok(json!({
"enabled": on,
"available": if on { Value::Null } else { Value::Bool(false) },
"adapter": null,
"reason": if on { None } else { lightcraft_gpu::unavailable_reason() },
"lastFallback": lightcraft_gpu::last_fallback(),
}));
}
Ok(json!({
"enabled": lightcraft_gpu::enabled(),
"available": lightcraft_gpu::available(),
+19
View File
@@ -152,6 +152,25 @@ mod tests {
}
}
/// Alt-drag previews on a profiled display (issue #937): the histogram stays the photo's (not
/// the preview's), and the clipping view is tested and drawn in sRGB, so it stays black and white.
#[test]
fn diagnostic_views_keep_the_photos_histogram() {
use lightcraft_pipeline::Overlay;
let mut session = crate::Session::with_demo();
let id = session.visible_cloned()[0];
let d = std::sync::Arc::new(p3());
let mut run = |o| session.loupe_job(id, 320, 240, true).unwrap().with_display(Some(d.clone())).with_overlay(o).run().rendered.unwrap();
let plain = run(Overlay::None);
let clip = run(Overlay::ClipShadows);
let (a, b) = (plain.histogram.mean_luma(), clip.histogram.mean_luma());
assert!((a - b).abs() < 0.02, "the photo's histogram: {a} vs {b}");
let px = &clip.image.data;
// (the profile may round white to 254)
let binary = px.iter().filter(|p| p[..3].iter().all(|v| *v <= 2 || *v >= 253)).count();
assert!(binary as f64 > 0.99 * px.len() as f64, "{binary} of {}", px.len());
}
#[test]
fn load_reports_and_rejects() {
let dir = std::env::temp_dir().join(format!("lightcraft-display-{}", std::process::id()));
+1
View File
@@ -63,6 +63,7 @@ mod tests {
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));
#[cfg(not(windows))]
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")));
+15 -2
View File
@@ -227,9 +227,22 @@ impl PreparedExport {
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() {
if !bytes.starts_with(b"8BPS") {
let embedded = lightcraft_meta::embedded(&bytes);
if let Some(xmp) = embedded.xmp.as_deref() {
lightcraft_meta::parse_xmp(xmp).map_err(|e| {
format!("{label}: can't verify location metadata in this original file: malformed embedded XMP: {e}")
})?;
}
}
let embeds_place_name =
[metadata.sublocation.as_deref(), metadata.city.as_deref(), metadata.state.as_deref(), metadata.country.as_deref()]
.into_iter()
.flatten()
.any(|value| !value.trim().is_empty());
if metadata.gps.is_some() || embeds_place_name {
return Err(format!(
"{label}: can't remove the location from an original file that embeds GPS; export as JPEG, TIFF or DNG instead"
"{label}: can't remove the location from an original file that embeds GPS or place names; export as JPEG or TIFF, or as DNG for a raw photo"
));
}
}
+45
View File
@@ -916,6 +916,51 @@ fn distinct_levels(bytes: &[u8]) -> (usize, lightcraft_codecs::Decoded) {
(v.len(), d)
}
/// A 16-bit render of a photo-like scene: smooth colour gradients plus sensor-like noise of
/// `noise` (linear, about 0.002 to 0.03 for clean to high-ISO raws), the case where the low
/// byte of every 16-bit sample is mostly noise.
fn noisy_render(noise: f32) -> lightcraft_pipeline::Rendered {
let (w, h) = (512, 384);
// a hash of the position and channel: the same noise every run
let hash = |x: usize, y: usize, c: usize| {
let mut z = (x as u64) << 32 ^ (y as u64) << 2 ^ c as u64 ^ 0x2882;
z = (z ^ (z >> 33)).wrapping_mul(0xff51_afd7_ed55_8ccd);
z = (z ^ (z >> 33)).wrapping_mul(0xc4ce_b9fe_1a85_ec53);
(z ^ (z >> 33)) as f32 / u64::MAX as f32 - 0.5
};
let src = lightcraft_raster::Rgb32f::from_fn(w, h, |x, y| {
let (u, v) = (x as f32 / w as f32, y as f32 / h as f32);
let base = [0.05 + 0.4 * u, 0.1 + 0.3 * v, 0.2 + 0.2 * (u * v)];
[0, 1, 2].map(|c| (base[c] + noise * hash(x, y, c)).max(0.0))
});
let req = lightcraft_pipeline::RenderRequest { depth: OutputDepth::U16, ..lightcraft_pipeline::RenderRequest::fit(w, h) };
lightcraft_pipeline::render(&src, &Default::default(), &Default::default(), &req)
}
/// Issue #2882: a 16-bit TIFF with ZIP (the default) is never larger than the same render
/// uncompressed, from smooth to noisy. (LZW can be: it is printed, not checked, and the export
/// dialog says so when it is picked.)
#[test]
fn sixteen_bit_zip_tiff_is_never_larger_than_uncompressed() {
assert_eq!(ExportOptions::default().tiff_compression, TiffCompression::Deflate, "ZIP is the default");
for noise in [0.0, 0.002, 0.01, 0.03, 0.1] {
let r = noisy_render(noise);
assert!(matches!(r.deep.as_ref().unwrap().samples, DeepSamples::U16(_)));
let size = |tiff_compression| {
let o = ExportOptions { format: ExportFormat::Tiff, bit_depth: Some(16), tiff_compression, ..Default::default() };
assert_eq!(o.effective_depth(), OutputDepth::U16);
encode_rendered(&r, &o, None).unwrap().len()
};
let (none, zip, lzw) = (size(TiffCompression::None), size(TiffCompression::Deflate), size(TiffCompression::Lzw));
eprintln!(
"noise {noise}: none {none} B, ZIP {zip} B ({:+.1} %), LZW {lzw} B ({:+.1} %)",
100.0 * (zip as f64 / none as f64 - 1.0),
100.0 * (lzw as f64 / none as f64 - 1.0)
);
assert!(zip <= none, "noise {noise}: 16-bit ZIP {zip} B is larger than uncompressed {none} B");
}
}
#[test]
fn sixteen_bit_tiff_and_png_have_no_banding() {
let tiff = |bit_depth| ExportOptions { format: ExportFormat::Tiff, bit_depth, ..Default::default() };
+12 -6
View File
@@ -76,11 +76,17 @@ pub fn fs_pair_loader() -> PairLoader {
pub fn fs_hooks() -> (FileLoader, FileProbe) {
let loader: FileLoader = Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge)));
let probe: FileProbe = Arc::new(|path: &str| {
let len = std::fs::metadata(path).map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).unwrap_or(0);
use std::io::Read;
// one open, then everything from the open file: its size and modification time are not
// round trips of their own (on a network share each of them is one)
let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
let meta = file.metadata().ok();
let len = meta.as_ref().map_or(0, |m| usize::try_from(m.len()).unwrap_or(usize::MAX));
let _permit = crate::memory::work_gate().acquire(len);
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).map_err(|e| format!("{path}: {e}"))?;
let mut info = probe_bytes(path, &bytes)?;
info.file_modified = file_modified(path);
info.file_modified = meta.as_ref().and_then(modified_iso);
Ok(info)
});
(loader, probe)
@@ -104,10 +110,10 @@ fn fs_load<T>(path: &str, max_edge: usize, load: impl FnOnce(Vec<u8>) -> Result<
r
}
/// `path`'s modification time as ISO 8601 (see [`ProbeInfo::file_modified`]); `None` when the
/// The modification time in `meta` as ISO 8601 (see [`ProbeInfo::file_modified`]); `None` when the
/// filesystem doesn't say or the time is before 1970.
fn file_modified(path: &str) -> Option<String> {
let t = std::fs::metadata(path).ok()?.modified().ok()?;
fn modified_iso(meta: &std::fs::Metadata) -> Option<String> {
let t = meta.modified().ok()?;
let secs = i64::try_from(t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs()).ok()?;
Some(crate::import::civil(secs))
}
+35
View File
@@ -119,6 +119,26 @@ fn white_balance_scale_follows_the_files_matrices_then_the_cameras() {
assert!(!lightcraft_catalog::relative_wb_camera("DNG", "SONY ILCE-7M3"));
}
/// A Fujifilm X-Trans III body reads Kelvin through the neutral pair its RAF stores (issue #730); without the pair
/// in the file, or on a body with matrices (X-T3), nothing changes.
#[test]
fn a_fujifilm_x_trans_iii_raf_reads_kelvin_through_its_neutral_pair() {
use lightcraft_raw::{ColorData, RawFormat};
let meta = |make: &str, model: &str| lightcraft_meta::Metadata { make: Some(make.into()), model: Some(model.into()), ..Default::default() };
let a = [366.0f32 / 302.0, 1.0, 866.0 / 302.0];
let d65 = [646.0f32 / 302.0, 1.0, 498.0 / 302.0];
let pair = lightcraft_raw::kelvin_presets::KelvinPresets::from_neutral_pair(a, d65);
assert!(pair.is_some());
let with = ColorData { kelvin_presets: pair, ..Default::default() };
let xt20 = WbScaleOf::new(RawFormat::Raf, &with, Some(d65), &meta("FUJIFILM", "X-T20"));
assert!(!xt20.relative && xt20.scale_white.is_some());
let (t, tint) = xt20.as_shot(lightcraft_color::cct::temp_tint_to_xy(6500.0, 0.0));
assert!((6000.0..7000.0).contains(&t) && tint.abs() < 25.0, "{t} {tint}");
assert!(!lightcraft_catalog::relative_wb_camera("RAF", "FUJIFILM X-T20"));
let bare = WbScaleOf::new(RawFormat::Raf, &ColorData::default(), Some(d65), &meta("FUJIFILM", "X-T20"));
assert!(bare.scale_white.is_none());
}
/// A merged DNG (Photo Merge) of a raw without colour matrices shows the As Shot temperature and tint its source
/// shows, on every scale: through the measured matrices (ILCE-7M3), through the presets (ILCA-99M2), the relative
/// scale's 6500 K / 0 (ILCE-7M2) and a file's own white (an unfitted format). Merges of real ILCE-7M3 brackets
@@ -427,6 +447,21 @@ fn undated_files_take_the_file_date() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The probe opens the file once and says the same thing as before about one that can't be read:
/// its path, then the system's words (a missing file, a folder).
#[test]
fn a_probe_of_a_file_that_cannot_be_read_names_the_path_and_the_cause() {
let dir = std::env::temp_dir().join(format!("lightcraft-probe-errors-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (_, probe) = fs_hooks();
for path in [dir.join("no-such-file.jpg"), dir.clone()] {
let path = path.to_string_lossy().to_string();
let e = probe(&path).unwrap_err();
assert_eq!(e, format!("{path}: {}", std::fs::read(&path).unwrap_err()));
}
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #367: probes read headers, not pixels, and report what the decode-based probe did:
/// oriented dimensions (EXIF orientation 6 swaps them), metadata, the error for a truncated
/// file or one that isn't an image.
+1 -1
View File
@@ -3,7 +3,7 @@
//! Built with `CRAFT_FONTS_DIR=<craft-fonts checkout>`, [`CRAFT_FONTS`] holds every font in its
//! manifest (today: the Japanese and Simplified-Chinese UI and document fonts); otherwise it is
//! empty and LightCraft uses only its own bundled fonts (Inter). Both the egui UI and the export
//! watermark renderer read it from here. See craftrules `standards/fonts.md`.
//! watermark renderer read it from here.
/// A font from the optional craft-fonts build input (empty unless built with `CRAFT_FONTS_DIR`).
pub struct CraftFont {
+1 -1
View File
@@ -1,4 +1,4 @@
//! Last-resort panic guard (never-crash standard, `AGENTS.md`): a panic that escapes a command
//! Last-resort panic guard (see `AGENTS.md`): a panic that escapes a command
//! becomes that command's error and the session (catalog, library, undo history) stays usable.
//! It's a safety net, not a way to report errors: commands return `Err` themselves.
+8 -4
View File
@@ -18,6 +18,8 @@
//! 7. Optionally apply a preset and add keywords (the import dialog's options).
//! 8. Commit all new photos as one undoable op. (Undoing a move removes the catalog records;
//! the files stay at the destination — undo never moves files back over a card.)
//! 9. Copy and Move rename sequences use checked platform-sized numbers: the last number is usable once, and any
//! further renamed files are reported as failed without losing earlier completed transfers.
//!
//! The import dialog first calls [`scan`] (`library.importPreview`): the same expansion, probing
//! and duplicate detection without adding anything, so the user can review the candidates. The
@@ -43,18 +45,20 @@ mod types;
pub(crate) use commit::workers;
pub use commit::{batch_size, civil, commit_prepared, system_clock};
pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults};
pub use files::{EXTENSIONS, LaunchPath, accept_list, expand, expand_within, is_supported, launch_path};
pub use files::{
EXTENSIONS, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_within, is_supported, launch_deadline, launch_path, launch_path_until,
};
pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with};
#[cfg(test)]
use job::PreparedItem;
pub use job::{ImportJob, Prepared, import, import_with};
pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with};
pub(crate) use scan::scan_files;
pub use scan::{ScanInput, ScanOutput, ScanProgress, scan, scan_with};
#[cfg(test)]
use scan::{library_files, library_hashes};
pub use types::{
Duplicate, ImportCandidate, ImportMode, ImportOptions, ImportReport, ImportUprightMode, ImportWarning, ImportWarningCode, Kept, Moved, OnDeleted,
Organize,
Duplicate, FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, ImportUprightMode, ImportWarning, ImportWarningCode, Kept, Moved,
OnDeleted, Organize,
};
#[cfg(test)]
+4 -2
View File
@@ -213,7 +213,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
}
report.imported.push(id.0);
}
PreparedItem::Duplicate { path, existing, reason, hash } => {
PreparedItem::Duplicate { path, existing, reason, hash, file } => {
let existing = existing.or_else(|| {
let h = hash?;
new_hash.get(&h).copied().or_else(|| s.catalog.photos().find(|p| p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id))
@@ -232,7 +232,9 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
report.restored.push(id.0);
}
}
_ => report.duplicates.push(Duplicate { path, existing: existing.map(|i| i.0), reason, existing_deleted: trashed.is_some() }),
_ => {
report.duplicates.push(Duplicate { path, existing: existing.map(|i| i.0), reason, existing_deleted: trashed.is_some(), file })
}
}
}
PreparedItem::Failed(path, e) => report.failed.push((path, e)),
+377
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use super::commit::workers;
#[cfg(test)]
@@ -119,6 +121,53 @@ pub enum LaunchPath {
/// Not imported: `path` (absolute) is a whole drive or the whole home folder, which is never
/// walked without being chosen in the app (issue #374).
Refused { path: String, why: String },
/// Open this (absolute) library folder: the argument was a library's `catalog.snap` or its folder, as a
/// double-click on a catalog in the file manager gives. Never imported.
Library(String),
}
/// The library folder `path` names: a library's `catalog.snap` (its folder), or a folder holding one. `None` for
/// anything else (photos, folders of photos). The folder must pass the library opener's own test
/// ([`crate::library::is_library`]), so a `CATALOG.SNAP` the opener would not read (a case-sensitive file system)
/// never opens its folder as a new, empty library.
pub fn library_dir_of(path: &Path) -> Option<PathBuf> {
let snapshot = lightcraft_catalog::journal::SNAPSHOT;
let named = path.file_name().is_some_and(|n| n.to_string_lossy().eq_ignore_ascii_case(snapshot));
if named && path.is_file() {
return path.parent().filter(|dir| crate::library::is_library(dir)).map(Path::to_path_buf);
}
(path.is_dir() && crate::library::is_library(path)).then(|| path.to_path_buf())
}
/// How long the launch arguments' library checks may take, all of them together, before LightCraft gives up and
/// treats the arguments not yet checked as photos to import (in the background). A path on a dead network mount
/// can block a file-system query for minutes, and these checks run before the window opens.
pub const LAUNCH_PROBE_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);
/// When the launch arguments' library checks, starting now, must be done: [`LAUNCH_PROBE_LIMIT`] from now.
pub fn launch_deadline() -> std::time::Instant {
let now = std::time::Instant::now();
now.checked_add(LAUNCH_PROBE_LIMIT).unwrap_or(now)
}
/// `probe`'s answer, or `None` when it takes longer than `limit`: it runs on its own thread, which is left to
/// finish (or stay blocked) on its own. Also `None` when no thread can be started.
pub(crate) fn within<T: Send + 'static>(limit: std::time::Duration, probe: impl FnOnce() -> Option<T> + Send + 'static) -> Option<T> {
let (tx, rx) = std::sync::mpsc::channel();
let started = std::thread::Builder::new().name("launch-probe".into()).spawn(move || {
let _ = tx.send(probe());
});
if let Err(e) = started {
log::warn!("could not start the launch-path check: {e}");
return None;
}
match rx.recv_timeout(limit) {
Ok(found) => found,
Err(_) => {
log::warn!("the launch-path check took longer than {limit:?}; treating the argument as photos to import");
None
}
}
}
/// Resolve a launch argument for importing (issue #374). An empty argument is ignored (`None`);
@@ -128,6 +177,19 @@ pub enum LaunchPath {
/// or file-system root is replaced by its camera folder (`DCIM`, from `dcim`: a memory card) or
/// refused, and so is the home folder `home`: either would walk most of the disk.
pub fn launch_path(arg: &str, cwd: Option<&Path>, home: Option<&Path>, dcim: impl Fn(&Path) -> Option<PathBuf>) -> Option<LaunchPath> {
launch_path_until(arg, cwd, home, dcim, launch_deadline())
}
/// [`launch_path`], with its library check bounded by `deadline` (from [`launch_deadline`]), which every argument
/// of one launch shares: several paths on a dead mount wait [`LAUNCH_PROBE_LIMIT`] in all, not each. Once it has
/// passed, an argument is imported without the check.
pub fn launch_path_until(
arg: &str,
cwd: Option<&Path>,
home: Option<&Path>,
dcim: impl Fn(&Path) -> Option<PathBuf>,
deadline: std::time::Instant,
) -> Option<LaunchPath> {
if arg.trim().is_empty() {
return None;
}
@@ -162,6 +224,13 @@ pub fn launch_path(arg: &str, cwd: Option<&Path>, home: Option<&Path>, dcim: imp
if home.is_some_and(|h| key(&h.to_string_lossy()) == key(&shown)) {
return Some(LaunchPath::Refused { path: shown, why: "the whole home folder".into() });
}
let left = deadline.saturating_duration_since(std::time::Instant::now());
let probed = abs.clone();
if !left.is_zero()
&& let Some(dir) = within(left, move || library_dir_of(&probed))
{
return Some(LaunchPath::Library(dir.to_string_lossy().to_string()));
}
Some(LaunchPath::Import(shown))
}
@@ -238,6 +307,112 @@ pub(crate) fn probe_all(
.collect()
}
/// What the disk says about a file ([`stat_all`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Seen {
/// Not asked about: `cancel` was set first.
Unchecked,
/// Not there, or not readable.
Gone,
At {
is_file: bool,
len: u64,
},
}
/// [`Seen`] of `path` from the file system.
fn stat_file(path: &str) -> Seen {
match std::fs::metadata(path) {
Ok(m) => Seen::At { is_file: m.is_file(), len: m.len() },
Err(_) => Seen::Gone,
}
}
/// Files asked about at once: a question to a network share (a stat, a name looked up) is a round
/// trip (50 ms and more under load) that waits for nothing but the server, so a few more than the
/// readers' threads.
#[cfg(not(target_arch = "wasm32"))]
const AT_ONCE: usize = 16;
/// Run `ask` on each of `items`, several at once (one at a time, a folder of thousands of photos on
/// a network share waited minutes for its questions alone). The answers come in the order of
/// `items`; `None` for an item not reached once `cancel` is set (or whose asker died).
fn at_once<T: Sync, R: Send>(items: &[T], cancel: &std::sync::atomic::AtomicBool, ask: impl Fn(&T) -> R + Sync) -> Vec<Option<R>> {
use std::sync::atomic::Ordering::Relaxed;
let mut answers: Vec<Option<R>> = items.iter().map(|_| None).collect();
#[cfg(not(target_arch = "wasm32"))]
{
let n = AT_ONCE.min(items.len());
if n > 1 {
let next = std::sync::atomic::AtomicUsize::new(0);
let mine: Vec<Vec<(usize, R)>> = std::thread::scope(|sc| {
let askers: Vec<_> = (0..n)
.map(|_| {
sc.spawn(|| {
let mut mine = Vec::new();
loop {
let i = next.fetch_add(1, Relaxed);
let Some(item) = items.get(i) else { break };
if cancel.load(Relaxed) {
break;
}
mine.push((i, ask(item)));
}
mine
})
})
.collect();
askers.into_iter().map(|a| a.join().unwrap_or_default()).collect()
});
for (i, r) in mine.into_iter().flatten() {
if let Some(slot) = answers.get_mut(i) {
*slot = Some(r);
}
}
return answers;
}
}
for (slot, item) in answers.iter_mut().zip(items) {
if cancel.load(Relaxed) {
break;
}
*slot = Some(ask(item));
}
answers
}
/// Ask `stat` about each of `paths`, several at once ([`at_once`]); the ones not reached once
/// `cancel` is set are [`Seen::Unchecked`].
pub(crate) fn stat_all(paths: &[&str], cancel: &std::sync::atomic::AtomicBool, stat: impl Fn(&str) -> Seen + Sync) -> Vec<Seen> {
at_once(paths, cancel, |p| stat(p)).into_iter().map(|s| s.unwrap_or(Seen::Unchecked)).collect()
}
/// The sidecar of each of `files` (`find` says which: a few names looked up on the disk for each,
/// a round trip apiece on a network share), several files at once ([`at_once`]); `None` for a
/// file with no sidecar or not reached once `cancel` is set.
pub(super) fn sidecars_of(
files: &[&str],
cancel: &std::sync::atomic::AtomicBool,
find: impl Fn(&str) -> Option<PathBuf> + Sync,
) -> Vec<Option<PathBuf>> {
at_once(files, cancel, |f| find(f)).into_iter().map(Option::flatten).collect()
}
/// The probes in `cache` of `files` that are still true: the file is looked at ([`stat_all`]) and
/// `ok` says it is as it was probed. `None` for a file with no probe in `cache`, one that changed,
/// and one not looked at because `cancel` was set.
pub(super) fn reusable_probes(
files: &[String],
cache: &mut HashMap<String, ProbeInfo>,
cancel: &std::sync::atomic::AtomicBool,
ok: impl Fn(Seen, &ProbeInfo) -> bool,
) -> Vec<Option<ProbeInfo>> {
let held: Vec<Option<ProbeInfo>> = files.iter().map(|f| cache.remove(f)).collect();
let asked: Vec<&str> = files.iter().zip(&held).filter(|(_, h)| h.is_some()).map(|(f, _)| f.as_str()).collect();
let mut seen = stat_all(&asked, cancel, stat_file).into_iter();
held.into_iter().map(|h| h.filter(|info| seen.next().is_some_and(|s| s != Seen::Unchecked && ok(s, info)))).collect()
}
/// Copy `src` into `dir` as `name` (default: its own name), made unique with -1, -2…; returns the
/// new path. The copy is verified ([`crate::import_move::copy_new`]: a new file, synced and
/// checked against `probe_hash`, the content hash the probe computed — or compared byte for byte
@@ -255,6 +430,67 @@ mod prepared_tests {
use super::*;
use lightcraft_catalog::{Op, Photo, PhotoId, Source};
fn temp_dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("lc-launch-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// A launch argument names a library only when the library opener would read that folder: a `CATALOG.SNAP`
/// on a case-sensitive file system (no `catalog.snap` or `catalog.log` beside it) is not one.
#[test]
fn a_launch_argument_names_a_library_only_when_the_opener_can_read_it() {
let dir = temp_dir("upper");
let upper = dir.join("CATALOG.SNAP");
std::fs::write(&upper, b"x").unwrap();
let found = library_dir_of(&upper);
assert_eq!(found.is_some(), crate::library::is_library(&dir), "{found:?}");
if let Some(d) = &found {
assert!(crate::library::is_library(d), "{} opened as a library the opener can't read", d.display());
}
// a folder holding only the journal is a library to the opener, so it is one here too
let journal = temp_dir("journal");
std::fs::write(journal.join(lightcraft_catalog::journal::LOG), b"x").unwrap();
assert_eq!(library_dir_of(&journal), Some(journal.clone()));
// a folder of photos is not
let photos = temp_dir("photos");
std::fs::write(photos.join("a.jpg"), b"x").unwrap();
assert_eq!(library_dir_of(&photos), None);
for d in [dir, journal, photos] {
let _ = std::fs::remove_dir_all(d);
}
}
/// The library check runs before the window opens; one that blocks (a dead network mount) gives up after the
/// limit and the argument is imported instead, so LightCraft still starts.
#[test]
fn a_blocked_launch_probe_gives_up_after_its_limit() {
let start = std::time::Instant::now();
let found = within(std::time::Duration::from_millis(50), || {
std::thread::sleep(std::time::Duration::from_secs(5));
Some(PathBuf::from("late"))
});
assert_eq!(found, None);
assert!(start.elapsed() < std::time::Duration::from_secs(2), "waited {:?}", start.elapsed());
assert_eq!(within(LAUNCH_PROBE_LIMIT, || Some(1)), Some(1), "a quick answer is kept");
}
/// The launch arguments share one deadline (CodeRabbit on #2979): once it has passed, an argument is imported
/// without its library check, so several paths on a dead mount can't each wait the limit.
#[test]
fn launch_arguments_share_one_deadline() {
let dir = temp_dir("deadline");
std::fs::write(dir.join(lightcraft_catalog::journal::LOG), b"x").unwrap();
let arg = dir.to_string_lossy().to_string();
let none = |_: &Path| None;
assert_eq!(launch_path_until(&arg, None, None, none, launch_deadline()), Some(LaunchPath::Library(arg.clone())));
let start = std::time::Instant::now();
assert_eq!(launch_path_until(&arg, None, None, none, start), Some(LaunchPath::Import(arg.clone())), "deadline passed");
assert!(start.elapsed() < std::time::Duration::from_millis(500), "waited {:?}", start.elapsed());
let _ = std::fs::remove_dir_all(dir);
}
/// 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> {
@@ -370,4 +606,145 @@ mod prepared_tests {
assert!(seen.load(Relaxed) <= 8, "read {} files after cancel", seen.load(Relaxed));
assert!(prepared.items.is_empty());
}
/// Given files on a network share, when an import checks the probes a scan left, then it asks
/// the disk about several files at once: one at a time, 5,990 photos spent 300 s on stats alone
/// (99 % of the import's time), each a round trip to the server.
#[test]
fn stats_are_asked_for_several_files_at_once() {
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
let (active, together) = (AtomicUsize::new(0), AtomicUsize::new(0));
let names: Vec<String> = (0..6).map(|i| format!("file-{i}")).collect();
let paths: Vec<&str> = names.iter().map(String::as_str).collect();
let seen = stat_all(&paths, &std::sync::atomic::AtomicBool::new(false), |p| {
active.fetch_add(1, Relaxed);
// waits (at most a second) for another file to be asked about while this one is
let end = std::time::Instant::now() + std::time::Duration::from_secs(1);
while active.load(Relaxed) < 2 && std::time::Instant::now() < end {
std::thread::yield_now();
}
together.fetch_max(active.load(Relaxed), Relaxed);
active.fetch_sub(1, Relaxed);
Seen::At { is_file: true, len: p.trim_start_matches("file-").parse().unwrap_or(u64::MAX) }
});
assert!(together.load(Relaxed) >= 2, "the files were asked about one at a time");
let lens: Vec<Seen> = (0..6).map(|len| Seen::At { is_file: true, len }).collect();
assert_eq!(seen, lens, "the answers keep the order of the files");
}
/// ✕ while the stats run: the files not asked about yet stay unchecked, and no more are asked.
#[test]
fn stats_stop_when_cancelled() {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
let (cancel, asked) = (AtomicBool::new(false), AtomicUsize::new(0));
let names: Vec<String> = (0..400).map(|i| format!("file-{i}")).collect();
let paths: Vec<&str> = names.iter().map(String::as_str).collect();
let seen = stat_all(&paths, &cancel, |_| {
asked.fetch_add(1, Relaxed);
cancel.store(true, Relaxed);
Seen::Gone
});
assert_eq!(seen.len(), 400);
// at most the files the (up to 16) readers had already started
assert!(asked.load(Relaxed) <= 16, "asked about {} files after cancel", asked.load(Relaxed));
assert_eq!(seen.iter().filter(|s| **s == Seen::Gone).count(), asked.load(Relaxed));
assert!(seen.iter().all(|s| matches!(s, Seen::Gone | Seen::Unchecked)));
}
/// A probe a scan left is used again for a file that is as it was, and only for it: a file that
/// changed size, one that is gone and one with no probe are read.
#[test]
fn a_scans_probe_is_reused_only_for_a_file_as_it_was() {
use std::sync::atomic::Ordering::Relaxed;
let dir = std::env::temp_dir().join(format!("lightcraft-reuse-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut files = Vec::new();
for (name, bytes) in [("same.jpg", 10usize), ("grown.jpg", 10), ("fresh.jpg", 10)] {
let p = dir.join(name);
std::fs::write(&p, vec![0u8; bytes]).unwrap();
files.push(p.to_string_lossy().to_string());
}
let gone = dir.join("gone.jpg").to_string_lossy().to_string();
files.push(gone.clone());
let mut s = Session::new();
let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap();
let probed = |size: u64| ProbeInfo { format: "JPEG".into(), file_size: size, ..ProbeInfo::default() };
job.cache.insert(files[0].clone(), probed(10));
job.cache.insert(files[1].clone(), probed(5));
job.cache.insert(gone.clone(), probed(10));
let read = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let read_in_probe = read.clone();
job.probe = Some(std::sync::Arc::new(move |p: &str| {
read_in_probe.lock().unwrap().push(p.to_string());
Ok(probed(10))
}));
let prepared = job.prepare_files(files.clone(), &std::sync::atomic::AtomicBool::new(false));
let mut read = read.lock().unwrap().clone();
read.sort();
let mut expect = vec![files[1].clone(), files[2].clone(), gone];
expect.sort();
assert_eq!(read, expect, "only what was not as the scan saw it is read");
assert_eq!(job.read_total.load(Relaxed), 3);
assert_eq!(prepared.items.len(), 4);
let _ = std::fs::remove_dir_all(&dir);
}
/// Given photos on a network share, when an import looks for their sidecars, then it asks about
/// several photos at once: one photo after another, nine names each, they were 77 % of the
/// import's preparation (95 % where a folder listing could not vouch for the names).
#[test]
fn sidecars_are_looked_up_for_several_photos_at_once() {
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
let (active, together) = (AtomicUsize::new(0), AtomicUsize::new(0));
let names: Vec<String> = (0..6).map(|i| format!("photo-{i}.jpg")).collect();
let files: Vec<&str> = names.iter().map(String::as_str).collect();
let found = sidecars_of(&files, &std::sync::atomic::AtomicBool::new(false), |f| {
active.fetch_add(1, Relaxed);
let end = std::time::Instant::now() + std::time::Duration::from_secs(1);
while active.load(Relaxed) < 2 && std::time::Instant::now() < end {
std::thread::yield_now();
}
together.fetch_max(active.load(Relaxed), Relaxed);
active.fetch_sub(1, Relaxed);
f.ends_with("-3.jpg").then(|| PathBuf::from(f).with_extension("xmp"))
});
assert!(together.load(Relaxed) >= 2, "the photos were looked up one at a time");
let expect: Vec<Option<PathBuf>> = (0..6).map(|i| (i == 3).then(|| PathBuf::from("photo-3.xmp"))).collect();
assert_eq!(found, expect, "each sidecar stays with its photo");
}
/// The sidecars found for a batch go to the photos they belong to, whichever have one, and a
/// photo that failed to probe takes none of the others'.
#[test]
fn a_batchs_sidecars_go_to_their_own_photos() {
let dir = std::env::temp_dir().join(format!("lightcraft-sidecars-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><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="4"/></rdf:RDF></x:xmpmeta>"#;
let files: Vec<String> = ["a.jpg", "broken.jpg", "c.jpg", "d.jpg"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect();
for f in &files {
std::fs::write(f, b"x").unwrap();
}
std::fs::write(dir.join("c.xmp"), xmp).unwrap();
let mut s = Session::new();
let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap();
job.probe = Some(std::sync::Arc::new(|p: &str| {
if p.ends_with("broken.jpg") {
Err("unreadable".into())
} else {
Ok(ProbeInfo { format: "JPEG".into(), file_size: 1, ..ProbeInfo::default() })
}
}));
let prepared = job.prepare_files(files, &std::sync::atomic::AtomicBool::new(false));
let rating = |name: &str| {
prepared.items.iter().find_map(|i| match i {
PreparedItem::Ready(r) if r.path.ends_with(name) => Some(r.sidecar.as_ref().and_then(|sc| sc.rating)),
_ => None,
})
};
assert_eq!((rating("a.jpg"), rating("c.jpg"), rating("d.jpg")), (Some(None), Some(Some(4)), Some(None)));
assert!(prepared.items.iter().any(|i| matches!(i, PreparedItem::Failed(p, _) if p.ends_with("broken.jpg"))));
let _ = std::fs::remove_dir_all(&dir);
}
}
+89 -37
View File
@@ -1,6 +1,6 @@
use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock};
use super::files::{expand, probe_all};
use super::types::{ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted};
use super::files::{Seen, expand, probe_all, reusable_probes, sidecars_of};
use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted};
use super::{HashMap, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source};
/// Import files/folders. See the module docs.
@@ -44,10 +44,11 @@ pub struct ImportJob {
pub(super) probe: Option<crate::media::FileProbe>,
file_bytes: Option<crate::merge::ByteReader>,
/// Probes from a preceding scan (not read again).
cache: HashMap<String, ProbeInfo>,
pub(super) cache: HashMap<String, ProbeInfo>,
naming: crate::sidecar::SidecarNaming,
now: String,
seq: usize,
/// Next rename number; `None` once the final representable value has been reserved.
seq: Option<usize>,
/// Files found so far (folders expanded) and handled so far, for progress.
pub total: std::sync::Arc<std::sync::atomic::AtomicUsize>,
pub done: std::sync::Arc<std::sync::atomic::AtomicUsize>,
@@ -73,6 +74,8 @@ pub(super) enum PreparedItem {
existing: Option<PhotoId>,
reason: &'static str,
hash: Option<String>,
/// What the file itself says, when it was read ([`Duplicate::file`]).
file: Option<Box<FileFacts>>,
},
Failed(String, String),
Kept(Kept),
@@ -141,6 +144,7 @@ impl Prepared {
existing: Some(existing),
reason: if existing_path.is_some() { "path" } else { "content" },
hash: info.content_hash,
file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured })),
});
} else {
items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed })));
@@ -180,7 +184,7 @@ impl ImportJob {
}
let fresh = opts.on_deleted == OnDeleted::Fresh;
Ok(ImportJob {
seq: opts.rename_start.max(1),
seq: Some(opts.rename_start.max(1)),
opts,
mode,
lib_dir,
@@ -261,7 +265,7 @@ impl ImportJob {
self.done.fetch_add(1, Relaxed);
}
Some((id, _)) => {
out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None });
out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None });
self.done.fetch_add(1, Relaxed);
}
None => todo.push(f),
@@ -270,15 +274,10 @@ impl ImportJob {
// files a preceding scan already probed are not read again (a network share is slow to read),
// as long as they are still there, as they were: a file gone or changed since is probed again
let cached: Vec<Option<ProbeInfo>> = todo
.iter()
.map(|f| {
// (the web's files are not std::fs files: kept as probed)
self.cache
.remove(f)
.filter(|info| cfg!(target_arch = "wasm32") || std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.len() == info.file_size))
})
.collect();
let cached = reusable_probes(&todo, &mut self.cache, cancel, |seen, info| {
// (the web's files are not std::fs files: kept as probed)
cfg!(target_arch = "wasm32") || matches!(seen, Seen::At { is_file: true, len } if len == info.file_size)
});
let missing: Vec<String> = todo.iter().zip(&cached).filter(|(_, c)| c.is_none()).map(|(f, _)| f.clone()).collect();
// Reading the files is the slow part of adding them where they are: it is counted on its
// own, and `cancel` stops it too (a large library takes long enough to want both).
@@ -294,6 +293,20 @@ impl ImportJob {
library.as_ref(),
todo.iter().zip(&probed).filter_map(|(path, info)| info.as_ref().ok().map(|i| (path.as_str(), i.kind))),
);
// The sidecar of every file that was probed, looked up for the batch at once: each is a few
// names asked of the disk, which on a network share made a folder of thousands of photos wait
// a round trip per name, one name after another.
let asked: Vec<&str> = todo.iter().zip(&probed).filter(|(_, p)| p.is_ok()).map(|(f, _)| f.as_str()).collect();
// (a file whose content the library has is skipped below as a duplicate: it asks the disk nothing)
let known: std::collections::HashSet<&str> = todo
.iter()
.zip(&probed)
.filter(|(_, p)| !opts.local && p.as_ref().is_ok_and(|i| i.content_hash.as_ref().is_some_and(|h| self.by_hash.contains_key(h))))
.map(|(f, _)| f.as_str())
.collect();
let mut found =
sidecars_of(&asked, cancel, |f| if known.contains(f) { None } else { crate::sidecar::find_sidecar_for_import(&stems, self.naming, f) })
.into_iter();
// Files are planned one by one, in order (duplicates, sidecars, names, folders); their
// copies or moves — the slow part, reading and writing every byte and verifying it — are
// collected and run on several threads (issue #367), then their outcomes take their places.
@@ -311,6 +324,8 @@ impl ImportJob {
continue;
}
};
// (this file's place in the lookups above: files that failed to probe have none)
let found_sidecar = found.next().flatten();
// a copy of a file whose transfer is still pending: a duplicate only if that one succeeds
if !opts.local
&& let Some(h) = &info.content_hash
@@ -321,20 +336,17 @@ impl ImportJob {
break;
}
}
if let Some(h) = &info.content_hash
&& !opts.local
&& let Some(existing) = self.by_hash.get(h)
{
self.done.fetch_add(1, Relaxed);
plan.slots.push(Slot::Item(PreparedItem::Duplicate { path, existing: *existing, reason: "content", hash: Some(h.clone()) }));
continue;
}
// same bytes as a library photo: skipped below, once its capture time is known
let duplicate_of =
info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing)));
// the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files
// and names the copy when the file itself has none
// and names the copy when the file itself has none (a duplicate needs only that time)
let raw = info.kind == MediaKind::Raw;
let packet = crate::sidecar::find_sidecar_for_import(&stems, self.naming, &path)
.and_then(|f| std::fs::read_to_string(f).ok())
.or_else(|| info.xmp.clone().filter(|_| raw));
let packet = if duplicate_of.is_some() && info.captured.is_some() {
None
} else {
found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw))
};
let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera);
let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) {
Ok(sc) => Some(sc),
@@ -350,6 +362,17 @@ impl ImportJob {
if info.captured.is_none() {
info.captured = info.file_modified.clone();
}
if let Some((hash, existing)) = duplicate_of {
self.done.fetch_add(1, Relaxed);
plan.slots.push(Slot::Item(PreparedItem::Duplicate {
path,
existing,
reason: "content",
hash: Some(hash),
file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured })),
}));
continue;
}
let stored = match (mode, &self.copy_root) {
(ImportMode::Copy | ImportMode::Move, Some(root))
if !crate::import_move::inside(Path::new(&path), root)
@@ -360,11 +383,20 @@ impl ImportJob {
let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now);
q.captured = info.captured.clone();
q.meta = info.meta.clone();
let name = opts.rename.as_deref().filter(|t| !t.trim().is_empty()).map(|t| {
let n = crate::rename::expand(t, &q, self.seq);
self.seq += 1;
n
});
let name = if let Some(template) = opts.rename.as_deref().filter(|t| !t.trim().is_empty()) {
let Some(seq) = self.seq else {
self.done.fetch_add(1, Relaxed);
plan.slots.push(Slot::Item(PreparedItem::Failed(
path,
"rename sequence exhausted; choose a lower renameStart or leave rename blank".into(),
)));
continue;
};
self.seq = seq.checked_add(1);
Some(crate::rename::expand(template, &q, seq))
} else {
None
};
let folders = opts.organize.folders(&q);
let dir = folders.iter().fold(root.to_path_buf(), |d, f| d.join(f));
// the name this file gets depends on what a pending transfer of a like-named file
@@ -431,6 +463,11 @@ impl ImportJob {
}
}
/// Identity of a candidate preview at the bounded requested edge, without constructing a job.
pub fn candidate_thumb_key(c: &ImportCandidate, edge: usize) -> u64 {
lightcraft_preview::Hasher128::new().str(&c.path).u64(c.file_size).u64(edge.clamp(64, 1024) as u64).finish().0 as u64
}
impl Session {
/// A thumbnail for an import candidate (not in the catalog): a raw's embedded preview, else a
/// small render of the file. `slot` makes the job's photo id unique (`u64::MAX - slot`).
@@ -447,10 +484,13 @@ impl Session {
p.preview_only = info.preview_only.clone();
}
p.develop = std::sync::Arc::new(p.import_defaults());
let edge = edge.clamp(64, crate::media::SourceLevel::Thumb.max_edge());
let level = crate::media::SourceLevel::Thumb;
let edge = edge.clamp(64, 1024);
let level = crate::media::SourceLevel::for_size(edge);
let source = self.media.origin_ref(&p.source, level.max_edge());
let key = lightcraft_preview::Hasher128::new().str(&c.path).u64(c.file_size).u64(edge as u64).finish().0 as u64;
let key = candidate_thumb_key(c, edge);
// A small original already supplies all its detail; do not enlarge it to the bucket.
let native_edge = c.width.max(c.height) as usize;
let render_edge = if native_edge > 0 { edge.min(native_edge) } else { edge };
let small = crate::media::RenderJob {
request_id: 0,
cache_generation: self.media.rendered.generation(),
@@ -461,7 +501,7 @@ impl Session {
origin: p.source.clone(),
info: crate::media::source_info(&p),
settings: p.develop.clone(),
request: lightcraft_pipeline::RenderRequest::fit(edge, edge),
request: lightcraft_pipeline::RenderRequest::fit(render_edge, render_edge),
key,
cache: None,
stages: None,
@@ -475,7 +515,16 @@ impl Session {
(Some(l), MediaKind::Raw) => Some((c.path.clone(), l.clone(), edge)),
_ => None,
};
Some(crate::media::QuickJob { request_id: 0, photo: id, key, cached: Vec::new(), embedded, small: Some(Box::new(small)) })
let minimum_embedded_edge = (c.preview_only.is_none() && p.preview_only.is_none()).then_some(render_edge);
Some(crate::media::QuickJob {
request_id: 0,
photo: id,
key,
cached: Vec::new(),
embedded,
minimum_embedded_edge,
small: Some(Box::new(small)),
})
}
/// Use the system clock for import/edit times (native hosts).
@@ -484,3 +533,6 @@ impl Session {
self
}
}
#[cfg(test)]
mod tests;
+92
View File
@@ -0,0 +1,92 @@
//! Import previews must cover the tile when possible, retaining camera JPEGs as a safe fallback.
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use crate::Session;
use crate::import::ImportCandidate;
use crate::media::QuickSource;
/// Synthetic raw, bounded decoder and camera JPEG, with reads counted independently of pixels.
fn fixture(preview_edge: Option<usize>, renderable: bool, preview_only: bool) -> (Session, ImportCandidate, Arc<AtomicUsize>) {
let mut session = Session::new();
let reads = Arc::new(AtomicUsize::new(0));
let count = reads.clone();
session.media.file_loader = Some(Arc::new(move |_, edge| {
count.fetch_add(1, Ordering::SeqCst);
if !renderable {
return Err("synthetic raw cannot be rendered".into());
}
let width = edge.min(1024);
let height = width * 3 / 4;
Ok((lightcraft_raster::Rgb32f { width, height, data: vec![[0.1, 0.2, 0.3]; width * height] }, Default::default()))
}));
session.media.preview_loader = Some(Arc::new(move |_, requested| {
let width = preview_edge?.min(requested);
Some(lightcraft_raster::Rgba8 { width, height: width * 3 / 4, data: vec![[30, 60, 90, 255]; width * (width * 3 / 4)] })
}));
let candidate = ImportCandidate {
path: "synthetic-import.nef".into(),
name: "synthetic-import.nef".into(),
format: "NEF".into(),
kind: lightcraft_catalog::MediaKind::Raw,
width: 1024,
height: 768,
preview_only: preview_only.then(|| "unsupported synthetic raw variant".into()),
..Default::default()
};
(session, candidate, reads)
}
#[test]
/// A renderable raw fills the requested tile when its embedded JPEG is too small.
fn import_preview_renders_when_the_camera_jpeg_cannot_cover_the_tile() {
let (mut session, candidate, reads) = fixture(Some(64), true, false);
let mut job = session.candidate_thumb_job(&candidate, 768, 0).unwrap();
job.request_id = 42;
let key = job.key;
let result = job.run();
assert_eq!(result.quick, Some(QuickSource::Small));
let image = result.rendered.unwrap().image;
assert_eq!((image.width, image.height), (768, 576));
assert_eq!(reads.load(Ordering::SeqCst), 1);
assert_eq!((result.request_id, result.key), (42, key));
}
#[test]
/// A sufficient camera JPEG avoids decoding the raw, retaining the fast path.
fn import_preview_keeps_a_camera_jpeg_that_already_covers_the_tile() {
let (mut session, candidate, reads) = fixture(Some(1024), true, false);
let result = session.candidate_thumb_job(&candidate, 768, 0).unwrap().run();
assert_eq!(result.quick, Some(QuickSource::Embedded));
assert_eq!(result.rendered.unwrap().image.width, 768);
assert_eq!(reads.load(Ordering::SeqCst), 0);
}
#[test]
/// Preview-only raws never waste a render attempt behind their available camera JPEG.
fn import_preview_only_raw_uses_the_available_camera_jpeg_without_a_render() {
let (mut session, candidate, reads) = fixture(Some(64), false, true);
let result = session.candidate_thumb_job(&candidate, 768, 0).unwrap().run();
assert_eq!(result.quick, Some(QuickSource::Embedded));
assert_eq!(result.rendered.unwrap().image.width, 64);
assert_eq!(reads.load(Ordering::SeqCst), 0);
}
#[test]
/// A failed or absent render never discards the usable, if undersized, camera JPEG.
fn import_preview_retains_the_camera_jpeg_if_the_render_fails_or_is_absent() {
for no_render in [false, true] {
let (mut session, candidate, reads) = fixture(Some(64), false, false);
let mut job = session.candidate_thumb_job(&candidate, 768, 0).unwrap();
if no_render {
job.small = None;
}
let result = job.run();
assert_eq!(result.quick, Some(QuickSource::Embedded));
assert_eq!(result.rendered.unwrap().image.width, 64);
assert_eq!(reads.load(Ordering::SeqCst), usize::from(!no_render));
}
}
+9 -15
View File
@@ -1,4 +1,4 @@
use super::files::{expand, probe_all};
use super::files::{Seen, expand, probe_all, reusable_probes};
use super::types::ImportCandidate;
use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source};
@@ -123,20 +123,14 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
let by_path = library_files(&input.library, &files);
let todo: Vec<String> = files.iter().filter(|f| !by_path.contains_key(Path::new(f))).cloned().collect();
progress.total.store(todo.len(), Relaxed);
// probes from a preceding `scan` are reused when the file is unchanged (same size)
let cached: Vec<Option<ProbeInfo>> = todo
.iter()
.map(|f| {
let info = input.cache.remove(f)?;
// (✕ set while the files' cached probes are checked: no more round trips to the disk; what is
// not reached counts as not probed, like the files after it)
if progress.cancel.load(Relaxed) {
return None;
}
let size = std::fs::metadata(f).map(|m| m.len()).ok();
(size.is_none() || size == Some(info.file_size)).then_some(info)
})
.collect();
// probes from a preceding `scan` are reused when the file is unchanged (same size); a file that
// can't be looked at counts as unchanged (✕ set while they are checked: no more round trips to the
// disk; what is not reached counts as not probed, like the files after it)
let cached = reusable_probes(&todo, &mut input.cache, &progress.cancel, |seen, info| match seen {
Seen::At { len, .. } => len == info.file_size,
Seen::Gone => true,
Seen::Unchecked => false,
});
let missing: Vec<String> = todo.iter().zip(&cached).filter(|(_, c)| c.is_none()).map(|(f, _)| f.clone()).collect();
progress.done.store(todo.len() - missing.len(), Relaxed);
let mut fresh = probe_all(input.probe.as_ref(), &missing, &progress.done, &progress.cancel).into_iter();
+15
View File
@@ -146,6 +146,21 @@ pub struct Duplicate {
/// That photo is in Recently Deleted (see [`OnDeleted`]).
#[serde(rename = "existingDeleted", skip_serializing_if = "std::ops::Not::not")]
pub existing_deleted: bool,
/// What the file itself says, as a file import reads it; `None` when the file wasn't read (a
/// path match). A Lightroom import makes a record of its own for a duplicate by content and
/// starts it from these, not from the other photo's record, which may have been edited (#2589).
#[serde(skip)]
pub file: Option<Box<FileFacts>>,
}
/// What a file import reads from a file itself, before anything in the library is edited.
#[derive(Clone, Debug, Default)]
pub struct FileFacts {
/// The metadata the file carries (EXIF, IPTC, embedded XMP).
pub meta: lightcraft_catalog::Meta,
/// The capture time a file import gives it: the file's, else its XMP sidecar's, else the
/// file's modification time.
pub captured: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize)]
+12 -3
View File
@@ -628,10 +628,12 @@ impl Session {
// ---------------------------------------------------------------- ops, undo
/// Apply an op as one undoable step.
/// Apply an op as one undoable step. A new edit: one that would make a smart album include
/// itself is refused here, whichever command, task or caller asked ([`Catalog::apply_new`]);
/// undo, redo and opening a library bring back what was and are not held to that.
pub fn commit(&mut self, label: &str, op: Op) -> Result<()> {
let fwd = op.clone();
let inv = self.apply_catalog(op)?;
let inv = self.apply_through(op, Catalog::apply_new)?;
self.pending_log.push(fwd);
self.undo.push(UndoEntry { label: label.to_string(), op: inv, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() });
self.commits = self.commits.wrapping_add(1);
@@ -645,7 +647,14 @@ impl Session {
Ok(())
}
/// [`Catalog::apply`] for what brings back what was (an undo or a redo).
fn apply_catalog(&mut self, op: Op) -> Result<Op> {
self.apply_through(op, Catalog::apply)
}
/// Apply `op` with `apply` (the catalog's way in for a new edit or for bringing back what
/// was), then forget what the session cached of the photos it replaced.
fn apply_through(&mut self, op: Op, apply: fn(&mut Catalog, Op) -> std::result::Result<Op, lightcraft_catalog::CatalogError>) -> Result<Op> {
// Retain only cache IDs while the catalog consumes the operation. Cloning an import
// batch here also cloned every photo, although commit already keeps the journal copy.
let mut invalidated = Vec::new();
@@ -664,7 +673,7 @@ impl Session {
_ => {}
}
}
let inv = self.catalog.apply(op)?;
let inv = apply(&mut self.catalog, op)?;
for id in invalidated {
self.media.forget(id);
}
+77
View File
@@ -58,6 +58,22 @@ pub fn is_library(dir: &Path) -> bool {
dir.join(lightcraft_catalog::journal::SNAPSHOT).is_file() || dir.join(lightcraft_catalog::journal::LOG).is_file()
}
/// [`is_library`] that tells "no library there" from "can't tell": `Ok(false)` only when the
/// folder or its catalog files are definitely missing; a lookup that fails otherwise (a folder it
/// may not read, a share that timed out) is the error, so a library that is there but can't be
/// read isn't reported as gone (issue #3239).
pub fn library_state(dir: &Path) -> std::io::Result<bool> {
for name in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] {
match std::fs::metadata(dir.join(name)) {
Ok(m) if m.is_file() => return Ok(true),
Ok(_) => {}
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => {}
Err(e) => return Err(e),
}
}
Ok(false)
}
/// The default library location: `$LIGHTCRAFT_LIBRARY` if set, else `~/Pictures/LightCraft Library`
/// (`%USERPROFILE%\Pictures\LightCraft Library` on Windows).
pub fn default_dir() -> Option<PathBuf> {
@@ -68,6 +84,37 @@ pub fn default_dir() -> Option<PathBuf> {
Some(PathBuf::from(home).join("Pictures").join(DEFAULT_NAME))
}
/// The user's home folder (`%USERPROFILE%` on Windows, `$HOME` elsewhere); `None` when the host has
/// none or it is empty. The one place the home path is read for Local's built-in places, in the
/// engine's rename/move guard and in the sidebar.
pub fn home_folder() -> Option<PathBuf> {
home_folder_from(cfg!(windows), |name| std::env::var_os(name))
}
fn home_folder_from(windows: bool, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
var(if windows { "USERPROFILE" } else { "HOME" }).filter(|h| !h.is_empty()).map(PathBuf::from)
}
#[cfg(test)]
mod home_tests {
use super::home_folder_from;
use std::ffi::OsString;
#[test]
fn windows_reads_userprofile_and_the_rest_read_home() {
let env = |name: &str| match name {
"HOME" => Some(OsString::from("/home/example")),
"USERPROFILE" => Some(OsString::from("C:\\Users\\example")),
_ => None,
};
assert_eq!(home_folder_from(true, env).as_deref(), Some(std::path::Path::new("C:\\Users\\example")));
assert_eq!(home_folder_from(false, env).as_deref(), Some(std::path::Path::new("/home/example")));
// only the other platform's variable is set: no home, never a guess from it
assert_eq!(home_folder_from(true, |n| (n == "HOME").then(|| OsString::from("/home/example"))), None);
assert_eq!(home_folder_from(false, |_| Some(OsString::new())), None);
}
}
pub struct Library {
/// The library directory, or a descriptive pseudo-path when the library isn't on disk.
pub dir: PathBuf,
@@ -733,6 +780,16 @@ impl Session {
result
}
/// Let go of the open library's lock (and with it the owner note, `catalog.lock.owner`) while
/// the library stays open in this session. For a host that ends the process without running
/// destructors (`std::process::exit`), after [`Session::close_library`] has saved: the OS would
/// free the lock anyway, but only the lock's `Drop` removes the note. Nothing else is
/// protected after this, so call it only when the process is about to end. A no-op without a
/// library or a lock.
pub fn release_library_lock(&mut self) {
drop(self.library.as_mut().and_then(|l| l.lock.take()));
}
fn view_json(&self) -> Vec<u8> {
let view = ViewFile {
source: self.source,
@@ -900,6 +957,26 @@ mod resolve_tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// A host that ends the process without destructors releases the lock by hand: the owner note
/// goes and another opener is let in, while the session keeps its library.
#[test]
fn release_library_lock_removes_the_owner_note() {
let dir = std::env::temp_dir().join(format!("lc-release-lock-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
s.close_library().unwrap();
assert!(dir.join(lightcraft_catalog::lock::OWNER).exists(), "close_library keeps the lock");
assert!(matches!(LibraryLock::acquire(&dir, "other"), Err(lightcraft_catalog::lock::LockError::InUse(_))));
s.release_library_lock();
assert!(!dir.join(lightcraft_catalog::lock::OWNER).exists());
drop(LibraryLock::acquire(&dir, "other").unwrap());
s.release_library_lock();
assert!(s.library.is_some(), "the library stays open");
let _ = std::fs::remove_dir_all(&dir);
}
/// `check_library` refuses what `open_library` would, without touching the open library.
#[test]
fn check_library_refuses_locked_libraries_files_and_lightroom_catalogs() {
+153 -12
View File
@@ -640,6 +640,14 @@ fn drop_copies_of(data: &mut CatalogImport, masters: &HashSet<i64>) {
data.skipped.extend(skipped);
}
/// A video the catalog lists with the format `VIDEO` and a video extension. Videos aren't image
/// types, but they become video records (never opened by the system opener), so they pass.
fn is_catalog_video(p: &CatalogPhoto) -> bool {
const EXTENSIONS: [&str; 12] = ["mp4", "mov", "m4v", "avi", "mts", "m2ts", "3gp", "mkv", "webm", "wmv", "mpg", "mpeg"];
text(&p.image, "fileFormat").eq_ignore_ascii_case("VIDEO")
&& Path::new(&p.path).extension().and_then(|e| e.to_str()).is_some_and(|e| EXTENSIONS.iter().any(|x| e.eq_ignore_ascii_case(x)))
}
/// Drop the catalog's images whose original is not a file type LightCraft reads, saying so in the
/// import's warnings.
///
@@ -656,7 +664,7 @@ pub(crate) fn refuse_non_media(data: &mut CatalogImport) {
let refused: HashSet<i64> = data
.photos
.iter()
.filter(|p| number(&p.image, "masterImage") == 0 && !crate::open_path::is_media(Path::new(&p.path)))
.filter(|p| number(&p.image, "masterImage") == 0 && !crate::open_path::is_media(Path::new(&p.path)) && !is_catalog_video(p))
.map(|p| p.source_id)
.collect();
if refused.is_empty() {
@@ -693,6 +701,7 @@ fn mapped_settings(
aspect: f64,
orientation: Orientation,
stored_aspect: f64,
user: Orientation,
) -> Result<(Value, Vec<String>), String> {
let mut root = crate::preset_import::parse_lua(text)?;
let deferred = strip_lua_sentinels(&mut root);
@@ -703,8 +712,13 @@ fn mapped_settings(
if !props.contains_key("crs:HasCrop") && CROP.iter().any(|k| props.contains_key(*k)) {
props.insert("crs:HasCrop".into(), vec!["True".into()]);
}
let (mut partial, mut unknown) = crate::crs::to_partial_report(&props, Some(&values), target, aspect);
// Mask edges are fractions of the stored image, like the crop's, so radii go to long-edge units
// with its aspect: `aspect` is the photo's in LightCraft, which is the shown one for a photo
// already in the library and only stands in when the catalog has no file size.
let mask_aspect = if stored_aspect.is_finite() && stored_aspect > 0.0 { stored_aspect } else { aspect };
let (mut partial, mut unknown) = crate::crs::to_partial_report(&props, Some(&values), target, mask_aspect);
catalog_crop(&mut partial, orientation, stored_aspect);
catalog_masks(&mut partial, in_photo_frame(orientation, user));
if deferred > 0 {
unknown.push("Deferred Lightroom adjustments (-999999)".into());
}
@@ -764,6 +778,71 @@ fn catalog_crop(partial: &mut Value, orientation: Orientation, stored_aspect: f6
geometry.insert("angle".into(), json!(angle));
}
/// The catalog's orientation (the stored image to the photo as Lightroom shows it), then the
/// photo's own Rotate Left / Right and Flip in LightCraft (`user`), which an update of a photo
/// already in the library keeps: the frame LightCraft draws masks in.
fn in_photo_frame(catalog: Orientation, user: Orientation) -> Orientation {
let (flip, turns) = user.to_parts();
let o = if flip { catalog.flipped_h() } else { catalog };
(0..turns).fold(o, |o, _| o.rotated(true))
}
/// Lightroom's masks in LightCraft's frame. Like the crop's corners, their positions are on the
/// stored image (before orientation), normalized to its size; LightCraft's are on the oriented
/// image. So the points go through the orientation, a radial's radii (in long-edge units, from the
/// stored image's aspect) swap when the axes do, and a mirror turns its angle the other way. A
/// quarter turn keeps the angle: the ellipse turned 90° is the same ellipse with its radii swapped.
fn catalog_masks(partial: &mut Value, orientation: Orientation) {
if orientation == Orientation::Normal {
return;
}
let point = |p: Option<&mut Value>| {
let Some(p) = p.and_then(Value::as_object_mut) else { return };
let (Some(x), Some(y)) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) else { return };
let (u, v) = orientation.map(x, y, 1.0, 1.0);
p.insert("x".into(), json!(u));
p.insert("y".into(), json!(v));
};
let Some(masks) = partial.get_mut("masks").and_then(Value::as_array_mut) else { return };
let components = masks.iter_mut().filter_map(|m| m.get_mut("components").and_then(Value::as_array_mut)).flatten();
for shape in components.filter_map(|c| c.get_mut("shape").and_then(Value::as_object_mut)) {
point(shape.get_mut("start"));
point(shape.get_mut("end"));
point(shape.get_mut("center"));
let strokes = shape.get_mut("strokes").and_then(Value::as_array_mut).into_iter().flatten();
for points in strokes.filter_map(|s| s.get_mut("points").and_then(Value::as_array_mut)) {
points.iter_mut().for_each(|p| point(Some(p)));
}
if shape.get("kind").and_then(Value::as_str) == Some("radial") {
if orientation.swaps_axes()
&& let (Some(rx), Some(ry)) = (shape.get("rx").cloned(), shape.get("ry").cloned())
{
shape.insert("rx".into(), ry);
shape.insert("ry".into(), rx);
}
if orientation.to_parts().0
&& let Some(angle) = shape.get("angle").and_then(Value::as_f64)
{
shape.insert("angle".into(), json!(-angle));
}
}
}
}
/// The catalog's XMP masks in LightCraft's frame, as [`catalog_masks`] puts the develop row's: they
/// are on the same stored image, and they stay when the row has no masks of its own. The packet's
/// radials come fitted to the sidecar default aspect and `sidecar::merge_into` re-fits them to the
/// photo's size, so they are fitted to the stored image to be turned (a quarter turn swaps the
/// radii) and handed back in the default aspect, for that re-fit to undo.
fn catalog_xmp_masks(partial: &mut Value, orientation: Orientation, stored_aspect: f64, photo: &Photo) {
use crate::crs_masks::{DEFAULT_ASPECT, refit_radials};
let merged = if photo.width > 0 && photo.height > 0 { photo.width as f64 / photo.height as f64 } else { DEFAULT_ASPECT };
let fit = if stored_aspect.is_finite() && stored_aspect > 0.0 { stored_aspect } else { merged };
refit_radials(partial, DEFAULT_ASPECT, fit);
catalog_masks(partial, orientation);
refit_radials(partial, merged, DEFAULT_ASPECT);
}
fn strip_lua_sentinels(value: &mut crate::preset_import::Lua) -> usize {
use crate::preset_import::Lua;
match value {
@@ -943,7 +1022,8 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
refuse_non_media(&mut data);
validate(&data).map_err(error)?;
let mut warnings = data.warnings.clone();
let duplicates: HashMap<_, _> = files.duplicates.iter().filter_map(|d| d.existing.map(|id| (key(&d.path), PhotoId(id)))).collect();
let duplicates: HashMap<_, _> =
files.duplicates.iter().filter_map(|d| d.existing.map(|id| (key(&d.path), (PhotoId(id), d.file.as_deref())))).collect();
let mut by_path: HashMap<_, _> =
s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect();
let mut ids = HashMap::new();
@@ -956,6 +1036,9 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
let mut promoted = HashSet::new();
let mut unmapped = BTreeMap::new();
let mut preserved = 0;
// Library photos in Recently Deleted that a catalog photo matched: they stay there (only an
// import of the files themselves brings a photo back, see `OnDeleted`), and the report says so.
let mut in_trash = HashSet::new();
// Masters precede their virtual copies.
let mut photos: Vec<_> = data.photos.iter().collect();
photos.sort_by_key(|p| number(&p.image, "masterImage") != 0);
@@ -980,6 +1063,9 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
.filter(|id| s.catalog.photo(*id).is_some_and(|p| source_path(p).is_some_and(|path| key(path) == key(&src.path))));
let existing_id = indexed.or_else(|| if master == 0 { by_path.get(&key(&src.path)).copied() } else { None });
let mut p = if let Some(id) = existing_id.and_then(|id| s.catalog.photo(id)) {
if id.deleted {
in_trash.insert(id.id);
}
(**id).clone()
} else if master != 0 {
let master_id = ids.get(&master).copied().ok_or_else(|| error(format!("virtual copy {}: missing master", src.source_id)))?;
@@ -991,13 +1077,55 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
p.id = s.catalog.alloc_photo_id();
p.copy_of = Some(master_id);
p.copy_name = Some(text(&src.image, "copyName").to_string());
// a new copy of a master in Recently Deleted is imported, not trashed with it
p.deleted = false;
p
} else if let Some(duplicate) = duplicates.get(&key(&src.path)).and_then(|id| s.catalog.photo(*id)) {
} else if let Some((duplicate, file)) =
duplicates.get(&key(&src.path)).and_then(|(id, meta)| s.catalog.photo(*id).cloned().map(|p| (p, *meta)))
{
// Catalogs can contain distinct originals with identical bytes and independent edits.
let mut p = (**duplicate).clone();
p.id = s.catalog.alloc_photo_id();
p.source = Source::File { path: src.path.clone() };
p.file_name = Path::new(&src.path).file_name().map(|n| n.to_string_lossy().into()).unwrap_or_else(|| src.path.clone());
// The new record takes only what the bytes determine from the photo with the same
// bytes, never that photo's own state: not its Recently Deleted (#2589), virtual copy,
// edits, history, versions, ratings, capture time or the metadata a person writes. Its
// metadata and capture time are what its own file gives it, as a file import reads them
// (copyright, creator…); the catalog's capture time, when it has one, applies on top.
let name = Path::new(&src.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| src.path.clone());
let mut p = Photo::new(
s.catalog.alloc_photo_id(),
Source::File { path: src.path.clone() },
&name,
&duplicate.format,
duplicate.width,
duplicate.height,
&now,
);
p.kind = duplicate.kind;
p.file_size = duplicate.file_size;
p.duration = duplicate.duration;
p.as_shot_wb = duplicate.as_shot_wb;
p.content_hash = duplicate.content_hash.clone();
p.embedded_lens = duplicate.embedded_lens;
p.preview_only = duplicate.preview_only.clone();
p.preview_checked = duplicate.preview_checked.clone();
if let Some(file) = file {
p.meta = file.meta.clone();
p.captured = file.captured.clone();
} else {
// (the file wasn't read: only the exposure description, which no command edits;
// not GPS, which placing a photo on the map does, nor the capture time, which
// Edit Capture Time does)
let m = &duplicate.meta;
p.meta.camera = m.camera.clone();
p.meta.lens = m.lens.clone();
p.meta.focal_mm = m.focal_mm;
p.meta.aperture = m.aperture;
p.meta.shutter = m.shutter.clone();
p.meta.iso = m.iso;
p.meta.focus = m.focus.clone();
}
// the settings a file import gives it (as-shot white balance, embedded lens
// corrections, the default preset); the catalog's settings apply on top
crate::import::apply_import_defaults(s, &mut p);
p
} else {
let id = s.catalog.alloc_photo_id();
@@ -1016,6 +1144,10 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
}
p
};
// Offline videos bypass file probing; Lightroom's format still identifies their kind.
if text(&src.image, "fileFormat").eq_ignore_ascii_case("VIDEO") {
p.kind = lightcraft_catalog::MediaKind::Video;
}
ids.insert(src.source_id, p.id);
index.photos.insert(identity(&data, src), p.id.0);
let keep_develop = existing_id.is_some() && p.edited.is_some() && !update_existing;
@@ -1023,11 +1155,14 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
if keep_develop {
preserved += 1;
}
let orientation = lightroom_orientation(text(&src.image, "orientation")).unwrap_or_default();
let stored_aspect = number(&src.image, "fileWidth") as f64 / number(&src.image, "fileHeight") as f64;
if !src.xmp.is_empty() {
match crate::sidecar::parse_sidecar(&src.xmp, crate::crs::Target::for_photo(&p)) {
Ok(mut sc) => {
if let Some(crate::sidecar::DevelopPatch::Partial(partial)) = &mut sc.develop {
strip_xmp_sentinels(partial);
catalog_xmp_masks(partial, in_photo_frame(orientation, p.develop.orientation), stored_aspect, &p);
}
crate::sidecar::merge_into(&mut p, &sc, &now);
}
@@ -1048,14 +1183,13 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
p.meta.keywords = src.keywords.clone();
}
if !src.settings.is_empty() && !keep_develop {
let orientation = lightroom_orientation(text(&src.image, "orientation")).unwrap_or_default();
let stored_aspect = number(&src.image, "fileWidth") as f64 / number(&src.image, "fileHeight") as f64;
match mapped_settings(
&src.settings,
crate::crs::Target::for_photo(&p),
p.width.max(1) as f64 / p.height.max(1) as f64,
orientation,
stored_aspect,
p.develop.orientation,
) {
Ok((partial, unknown)) => {
p.develop = Arc::new(lightcraft_develop::apply_partial(&p.develop, &partial, 1.0));
@@ -1080,7 +1214,14 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
if copy_masters.contains(&src.source_id) {
planned.insert(photo_id, p.clone());
}
if s.catalog.photo(p.id).is_some() {
if let Some(old) = s.catalog.photo(p.id) {
if old.kind != p.kind {
// Repair older imports with existing reversible operations. Removing just the
// record leaves album/stack membership intact; the enclosing batch is atomic.
let mut repaired = (**old).clone();
repaired.kind = p.kind;
ops.extend([Op::RemovePhoto { id: p.id }, Op::AddPhoto { photo: Box::new(repaired) }]);
}
if was_local && promoted.insert(p.id) {
imported += 1;
ops.push(Op::SetLocal { id: p.id, local: false });
@@ -1105,7 +1246,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
}
s.merge_undo(s.undo.len().saturating_sub(undo0), "Import Lightroom Catalog");
Ok(AppliedImport {
report: json!({"source":data.source,"photos":ids.len(),"imported":imported,"library":s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.to_string_lossy()),"collections":album_count,"preservedExistingEdits":preserved,"missing":missing,"failed":files.failed,"warnings":warnings,"skipped":data.skipped,"unmapped":unmapped,"archive":archive_path,"mapping":ids}),
report: json!({"source":data.source,"photos":ids.len(),"imported":imported,"library":s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.to_string_lossy()),"collections":album_count,"preservedExistingEdits":preserved,"inRecentlyDeleted":in_trash.len(),"missing":missing,"failed":files.failed,"warnings":warnings,"skipped":data.skipped,"unmapped":unmapped,"archive":archive_path,"mapping":ids}),
index: index.clone(),
})
}
+496 -13
View File
@@ -157,6 +157,254 @@ fn imports_copies_collections_ratings_and_mapped_edits_in_one_undo_step() {
assert!(s.catalog.albums().next().is_none());
assert!(data.photos[1].settings.contains("CameraProfile")); // unmapped source stays intact
}
/// A library photo at `path`, already committed.
fn library_photo(s: &mut crate::Session, path: &str, edit: impl FnOnce(&mut Photo)) -> PhotoId {
let id = s.catalog.alloc_photo_id();
let mut p = Photo::new(id, Source::File { path: path.into() }, "a.ARW", "ARW", 20, 10, "before");
p.content_hash = Some("same-bytes".into());
edit(&mut p);
s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).unwrap();
id
}
/// A catalog photo whose file has the same bytes as a library photo in Recently Deleted (or a
/// virtual copy) is a new record of its own: it was counted as imported but landed in Recently
/// Deleted (or became a "copy" of nothing it was copied from), so a large import into a library
/// with a trash went missing photo by photo (#2589).
#[test]
fn a_content_duplicate_of_a_trashed_photo_or_virtual_copy_is_a_new_live_photo() {
let trashed: fn(&mut Photo) = |p| p.deleted = true;
let virtual_copy: fn(&mut Photo) = |p| {
p.copy_of = Some(PhotoId(999));
p.copy_name = Some("Copy 1".into());
};
for (case, edit) in [("trashed", trashed), ("virtual copy", virtual_copy)] {
let mut s = crate::Session::new();
let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| {
edit(p);
// the other photo's own state, which the new record must not inherit
let mut d = (*p.develop).clone();
d.light.shadows = 77.0;
p.develop = std::sync::Arc::new(d);
p.edited = Some("earlier".into());
p.history.push(lightcraft_catalog::HistoryStep { label: "Other photo's edit".into(), settings: p.develop.clone() });
p.versions.push(lightcraft_catalog::Version {
name: "Other photo's version".into(),
created: "before".into(),
settings: p.develop.clone(),
auto: false,
});
p.meta.title = "Other photo's title".into();
p.meta.keywords = vec!["other-photo".into()];
p.local_baseline = Some(7);
// what the bytes determine is shared
p.meta.camera = "Same Camera".into();
p.file_size = 4096;
});
let mut data = sample();
data.photos.retain(|p| number(&p.image, "masterImage") == 0);
let files = crate::import::ImportReport {
duplicates: vec![crate::import::Duplicate {
path: "/missing/test.ARW".into(),
existing: Some(other.0),
reason: "content",
existing_deleted: case == "trashed",
// what the file itself carries
file: Some(Box::new(crate::import::FileFacts {
meta: lightcraft_catalog::Meta { camera: "Same Camera".into(), ..Default::default() },
captured: None,
})),
}],
..Default::default()
};
let undo0 = s.undo.len();
let r = apply_prepared(
&mut s,
data,
ApplyPrepared {
update_existing: false,
files,
index: &mut ImportIndex::default(),
archive_path: None,
missing_sources: &HashSet::new(),
undo0,
},
)
.unwrap()
.report;
assert_eq!(r["imported"], 1, "{case}: {r}");
assert_eq!(r["inRecentlyDeleted"], 0, "{case}: {r}");
let new = s.catalog.photo(PhotoId(r["mapping"]["1"].as_u64().unwrap())).unwrap();
assert_ne!(new.id, other, "{case}");
assert!(!new.deleted, "{case}: the new record must not be in Recently Deleted");
assert_eq!((new.copy_of, new.copy_name.as_deref()), (None, None), "{case}: the new record is no virtual copy");
assert_ne!(new.imported, "before", "{case}: imported now, not when the other photo was");
assert_eq!(new.rating, 5, "{case}: the catalog's own metadata applies");
assert_ne!(new.develop.light.shadows, 77.0, "{case}: no edits from the other photo");
assert!(new.history.iter().all(|h| h.label != "Other photo's edit"), "{case}: no history from the other photo");
assert!(new.versions.is_empty(), "{case}: no versions from the other photo");
assert_ne!(new.meta.title, "Other photo's title", "{case}");
assert!(!new.meta.keywords.iter().any(|k| k == "other-photo"), "{case}");
assert_eq!(new.local_baseline, None, "{case}");
assert_eq!((new.meta.camera.as_str(), new.file_size), ("Same Camera", 4096), "{case}: what the bytes determine is kept");
assert_eq!(new.content_hash.as_deref(), Some("same-bytes"), "{case}");
assert_eq!(s.catalog.photo(other).unwrap().deleted, case == "trashed", "{case}: the other photo is left as it was");
}
}
/// A content duplicate starts from the settings a file import gives a raw (its as-shot white
/// balance and embedded lens corrections), as its file would on its own, before the catalog's
/// settings go on top; not from the generic defaults (#2589).
#[test]
fn a_content_duplicate_raw_starts_from_its_camera_defaults() {
let mut s = crate::Session::new();
let other = library_photo(&mut s, "/elsewhere/a.DNG", |p| {
p.deleted = true;
p.format = "DNG".into();
p.kind = lightcraft_catalog::MediaKind::Raw;
p.as_shot_wb = Some((5200.0, 4.0));
p.embedded_lens = Some(lightcraft_develop::EmbeddedLens::default());
});
let mut data = sample();
data.photos.retain(|p| number(&p.image, "masterImage") == 0);
// a catalog row with no develop settings of its own
data.photos[0].settings.clear();
let files = crate::import::ImportReport {
duplicates: vec![crate::import::Duplicate {
path: "/missing/test.ARW".into(),
existing: Some(other.0),
reason: "content",
existing_deleted: true,
file: None,
}],
..Default::default()
};
let undo0 = s.undo.len();
let r = apply_prepared(
&mut s,
data,
ApplyPrepared {
update_existing: false,
files,
index: &mut ImportIndex::default(),
archive_path: None,
missing_sources: &HashSet::new(),
undo0,
},
)
.unwrap()
.report;
let new = s.catalog.photo(PhotoId(r["mapping"]["1"].as_u64().unwrap())).unwrap();
assert_eq!(*new.develop, new.camera_defaults(), "{r}");
assert_eq!((new.develop.wb.temp, new.develop.wb.tint), (5200.0, 4.0), "the file's as-shot white balance");
assert!(new.develop.optics.lens_profile, "the file's embedded lens corrections are on");
}
/// A content duplicate keeps the metadata its file carries (copyright, rights, creator) and the
/// capture time its file gives it, as a file import of it would, when the catalog doesn't restate
/// them; it reads the file's, not the other photo's, which a person may have edited (#2589).
#[test]
fn a_content_duplicate_keeps_the_rights_metadata_and_capture_time_in_its_file() {
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-duplicate-rights-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("Photos")).unwrap();
let source = dir.join("source.lrcat");
std::fs::write(dir.join("Photos/test.ARW"), b"same bytes").unwrap();
std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap();
let mut s = crate::Session::new();
let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| {
p.deleted = true;
// edited on the other record after its import
p.meta.copyright = "Other photo's notice".into();
p.meta.creator = "Other photo's creator".into();
p.meta.gps = Some((1.0, 2.0));
p.captured = Some("1999-12-31T23:00:00".into());
});
let file_meta = lightcraft_catalog::Meta {
camera: "Same Camera".into(),
copyright: "© Jo Example".into(),
copyright_status: lightcraft_catalog::CopyrightStatus::Copyrighted,
usage_terms: "No reuse".into(),
creator: "Jo Example".into(),
..Default::default()
};
let probed = file_meta.clone();
s.media.file_probe = Some(Arc::new(move |_| {
Ok(crate::media::ProbeInfo {
format: "ARW".into(),
width: 20,
height: 10,
content_hash: Some("same-bytes".into()),
meta: probed.clone(),
captured: Some("2024-05-06T07:08:09".into()),
..Default::default()
})
}));
let mut job = crate::lightroom_job::LightroomJob::new(&mut s, source, false).unwrap();
let prepared = job.prepare(&AtomicBool::new(false)).unwrap();
let r = crate::lightroom_job::commit_prepared(&mut s, prepared).unwrap().report;
let new = s.catalog.photos().find(|p| p.id != other).unwrap_or_else(|| panic!("no new record: {r}"));
assert_eq!(new.content_hash.as_deref(), Some("same-bytes"), "{r}");
assert_eq!(new.rating, 5, "the catalog's own metadata applies: {r}");
let m = &new.meta;
assert_eq!(
(m.copyright.as_str(), m.copyright_status, m.usage_terms.as_str(), m.creator.as_str(), m.camera.as_str()),
("© Jo Example", file_meta.copyright_status, "No reuse", "Jo Example", "Same Camera"),
"the file's own metadata: {r}"
);
assert_eq!(m.gps, None, "nothing from the other photo's record");
// the catalog row has no capture time: the file's, not the other photo's edited one
assert_eq!(new.captured.as_deref(), Some("2024-05-06T07:08:09"), "{r}");
std::fs::remove_dir_all(dir).unwrap();
}
/// A catalog photo matched (by path) to a library photo in Recently Deleted leaves it there, as
/// the import was set up to do (a Lightroom import doesn't restore, see `OnDeleted`), and the report
/// counts it so the photos don't go missing unexplained (#2589). A new virtual copy of it is
/// imported, not trashed with its master.
#[test]
fn a_catalog_photo_matching_a_trashed_record_stays_there_and_is_counted() {
let mut s = crate::Session::new();
let trashed = library_photo(&mut s, "/missing/test.ARW", |p| p.deleted = true);
let r = apply(&mut s, sample(), false).unwrap();
assert_eq!(r["mapping"]["1"], trashed.0, "{r}");
assert!(s.catalog.photo(trashed).unwrap().deleted, "the photo stays in Recently Deleted");
assert_eq!(r["inRecentlyDeleted"], 1, "{r}");
let copy = s.catalog.photos().find(|p| p.copy_of == Some(trashed)).unwrap();
assert!(!copy.deleted, "the new virtual copy is imported, not trashed");
assert_eq!(r["imported"], 1, "only the copy was added: {r}");
}
/// Importing the catalog again after its master and virtual copy were both moved to Recently
/// Deleted matches each through the import index: each is counted once, and neither is restored.
#[test]
fn a_reimport_counts_each_trashed_match_once() {
let mut s = crate::Session::new();
// one import index across both imports, as a library on disk keeps in Interop/
let mut index = ImportIndex::default();
let mut import = |s: &mut crate::Session| {
let undo0 = s.undo.len();
apply_prepared(
s,
sample(),
ApplyPrepared {
update_existing: false,
files: Default::default(),
index: &mut index,
archive_path: None,
missing_sources: &HashSet::new(),
undo0,
},
)
.unwrap()
.report
};
let first = import(&mut s);
let ids: Vec<PhotoId> = ["1", "2"].iter().map(|k| PhotoId(first["mapping"][k].as_u64().unwrap())).collect();
for id in &ids {
s.commit("Delete", Op::SetDeleted { id: *id, deleted: true }).unwrap();
}
let r = import(&mut s);
assert_eq!(r["mapping"], first["mapping"], "{r}");
assert_eq!(r["inRecentlyDeleted"], 2, "{r}");
assert_eq!(r["imported"], 0, "{r}");
assert!(ids.iter().all(|id| s.catalog.photo(*id).unwrap().deleted));
}
#[test]
fn preserves_existing_edits_and_rejects_invalid_structure_before_mutation() {
let mut s = crate::Session::new();
@@ -173,8 +421,15 @@ fn preserves_existing_edits_and_rejects_invalid_structure_before_mutation() {
assert!(apply(&mut s, cyclic, false).is_err());
assert_eq!(s.catalog.to_snapshot(), before);
assert!(
mapped_settings(&format!("{}0{}", "{".repeat(1000), "}".repeat(1000)), crate::crs::Target::RawAbsolute, 1.0, Orientation::Normal, 1.5)
.is_err()
mapped_settings(
&format!("{}0{}", "{".repeat(1000), "}".repeat(1000)),
crate::crs::Target::RawAbsolute,
1.0,
Orientation::Normal,
1.5,
Orientation::Normal
)
.is_err()
);
}
#[test]
@@ -191,6 +446,7 @@ fn compressed_xmp_is_bounded_and_settings_are_data_only() {
1.5,
Orientation::Normal,
1.5,
Orientation::Normal,
)
.unwrap();
assert_eq!(partial["light"]["exposure"], 0.75);
@@ -202,11 +458,11 @@ fn custom_white_balance_on_relative_wb_raws_is_not_read_as_kelvin() {
// relative to its as-shot look the edit stays As Shot and is reported; a DNG keeps the Kelvin
let settings =
"s = { WhiteBalance = \"Custom\", Temperature = 3578, Tint = -5, CustomTemperature = 3578.95, CustomTint = -5, Exposure2012 = 0.5 }";
let (partial, unknown) = mapped_settings(settings, crate::crs::Target::RawRelative, 1.5, Orientation::Normal, 1.5).unwrap();
let (partial, unknown) = mapped_settings(settings, crate::crs::Target::RawRelative, 1.5, Orientation::Normal, 1.5, Orientation::Normal).unwrap();
assert_eq!(partial["wb"], json!({"mode": "asShot"}), "{partial}");
assert_eq!(partial["light"]["exposure"], 0.5);
assert!(unknown.iter().any(|k| k.starts_with("Temperature, Tint")), "{unknown:?}");
let (partial, unknown) = mapped_settings(settings, crate::crs::Target::RawAbsolute, 1.5, Orientation::Normal, 1.5).unwrap();
let (partial, unknown) = mapped_settings(settings, crate::crs::Target::RawAbsolute, 1.5, Orientation::Normal, 1.5, Orientation::Normal).unwrap();
assert_eq!(
(partial["wb"]["mode"].as_str(), partial["wb"]["temp"].as_f64(), partial["wb"]["tint"].as_f64()),
(Some("custom"), Some(3578.0), Some(-5.0))
@@ -223,6 +479,7 @@ fn catalog_crops_without_has_crop_are_imported() {
1.5,
Orientation::Normal,
1.5,
Orientation::Normal,
)
.unwrap();
let crop = &partial["crop"]["geometry"];
@@ -233,11 +490,13 @@ fn catalog_crops_without_has_crop_are_imported() {
assert_eq!(crop["angle"], 0.0);
assert!(!unknown.iter().any(|k| k.starts_with("CropLeft")), "{unknown:?}");
// an angle alone still means a crop (Lightroom's angle turns the other way to LightCraft's)
let (partial, unknown) = mapped_settings("s = { CropAngle = -1.5 }", crate::crs::Target::RawAbsolute, 1.5, Orientation::Normal, 1.5).unwrap();
let (partial, unknown) =
mapped_settings("s = { CropAngle = -1.5 }", crate::crs::Target::RawAbsolute, 1.5, Orientation::Normal, 1.5, Orientation::Normal).unwrap();
assert_eq!(partial["crop"]["geometry"]["angle"], 1.5);
assert!(!unknown.iter().any(|k| k.starts_with("CropAngle")), "{unknown:?}");
// no crop fields: the crop stays untouched
let (partial, _) = mapped_settings("s = { Exposure2012 = 0.5 }", crate::crs::Target::RawAbsolute, 1.5, Orientation::Normal, 1.5).unwrap();
let (partial, _) =
mapped_settings("s = { Exposure2012 = 0.5 }", crate::crs::Target::RawAbsolute, 1.5, Orientation::Normal, 1.5, Orientation::Normal).unwrap();
assert!(partial.get("crop").is_none());
}
@@ -261,7 +520,7 @@ fn lightroom_orientation_codes() {
fn catalog_crops_follow_the_photo_orientation() {
let crop = |o: Orientation| {
let settings = "s = { CropLeft = 0.1, CropRight = 0.6, CropTop = 0.2, CropBottom = 0.9 }";
let (partial, _) = mapped_settings(settings, crate::crs::Target::RawAbsolute, 1.5, o, 1.5).unwrap();
let (partial, _) = mapped_settings(settings, crate::crs::Target::RawAbsolute, 1.5, o, 1.5, Orientation::Normal).unwrap();
let g = &partial["crop"]["geometry"];
let r = &g["rect"];
[r["x0"].as_f64(), r["y0"].as_f64(), r["x1"].as_f64(), r["y1"].as_f64(), g["angle"].as_f64()].map(|v| (v.unwrap() * 1e9).round() / 1e9)
@@ -274,16 +533,74 @@ fn catalog_crops_follow_the_photo_orientation() {
assert_eq!(crop(Orientation::FlipH), [0.4, 0.2, 0.9, 0.9, 0.0]);
// a mirror turns the straighten the other way
let angle = |o: Orientation| {
let (partial, _) = mapped_settings("s = { CropAngle = 2 }", crate::crs::Target::RawAbsolute, 1.5, o, 1.5).unwrap();
let (partial, _) = mapped_settings("s = { CropAngle = 2 }", crate::crs::Target::RawAbsolute, 1.5, o, 1.5, Orientation::Normal).unwrap();
partial["crop"]["geometry"]["angle"].as_f64().unwrap()
};
assert_eq!(angle(Orientation::Rotate90), -2.0);
assert_eq!(angle(Orientation::FlipH), 2.0);
// no crop: nothing to orient
let (partial, _) = mapped_settings("s = { Exposure2012 = 0.5 }", crate::crs::Target::RawAbsolute, 1.5, Orientation::Rotate90, 1.5).unwrap();
let (partial, _) =
mapped_settings("s = { Exposure2012 = 0.5 }", crate::crs::Target::RawAbsolute, 1.5, Orientation::Rotate90, 1.5, Orientation::Normal).unwrap();
assert!(partial.get("crop").is_none());
}
#[test]
fn catalog_masks_follow_the_photo_orientation() {
// #1806, EMY_9996 (EXIF 8, shown a quarter turn counter-clockwise): a horizon gradient along
// the stored image's x axis runs along the shown photo's y axis
let s = r#"s = { MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = -0.1, CorrectionMasks = {
{ What = "Mask/Gradient", MaskValue = 1, ZeroX = 0.362544, ZeroY = 0.481093, FullX = 0.451639, FullY = 0.480645 } } } } }"#;
let (partial, _) = mapped_settings(s, crate::crs::Target::RawAbsolute, 1.5, Orientation::Rotate270, 1.5, Orientation::Normal).unwrap();
let g = &partial["masks"][0]["components"][0]["shape"];
let close = |v: &Value, want: f64| (v.as_f64().unwrap() - want).abs() < 1e-9;
assert!(close(&g["start"]["x"], 0.480645) && close(&g["start"]["y"], 1.0 - 0.451639), "{g}");
assert!(close(&g["end"]["x"], 0.481093) && close(&g["end"]["y"], 1.0 - 0.362544), "{g}");
let masks = |o: Orientation| {
let s = r#"s = {
MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.1, CorrectionMasks = {
{ What = "Mask/Gradient", FullX = 0.1, FullY = 0.2, ZeroX = 0.3, ZeroY = 0.6 },
{ What = "Mask/CircularGradient", Left = 0, Right = 0.2, Top = 0.1, Bottom = 0.3, Angle = 10, Feather = 50, Version = 2, Flipped = true },
{ What = "Mask/Paint", Radius = 0.05, MaskValue = 1, Dabs = { "d 0.1 0.2", "d 0.3 0.6" } } } } } }"#;
let (partial, _) = mapped_settings(s, crate::crs::Target::RawAbsolute, 1.5, o, 1.5, Orientation::Normal).unwrap();
let c = &partial["masks"][0]["components"];
let (linear, radial, brush) = (&c[0]["shape"], &c[1]["shape"], &c[2]["shape"]["strokes"][0]["points"]);
[
&linear["start"]["x"],
&linear["start"]["y"],
&linear["end"]["x"],
&linear["end"]["y"],
&radial["center"]["x"],
&radial["center"]["y"],
&radial["rx"],
&radial["ry"],
&radial["angle"],
&brush[0]["x"],
&brush[0]["y"],
&brush[1]["x"],
&brush[1]["y"],
]
.map(|v| (v.as_f64().unwrap() * 1e9).round() / 1e9)
};
// (x, y) of the stored image → (1 − y, x) a quarter turn clockwise, (y, 1 − x) counter-clockwise;
// a radial's radii (in long-edge units) swap with the axes, and a mirror turns its angle the
// other way
let r = (0.1, (0.1_f64 / 1.5 * 1e9).round() / 1e9);
assert_eq!(masks(Orientation::Normal), [0.1, 0.2, 0.3, 0.6, 0.1, 0.2, r.0, r.1, 10.0, 0.1, 0.2, 0.3, 0.6]);
assert_eq!(masks(Orientation::Rotate90), [0.8, 0.1, 0.4, 0.3, 0.8, 0.1, r.1, r.0, 10.0, 0.8, 0.1, 0.4, 0.3]);
assert_eq!(masks(Orientation::Rotate270), [0.2, 0.9, 0.6, 0.7, 0.2, 0.9, r.1, r.0, 10.0, 0.2, 0.9, 0.6, 0.7]);
assert_eq!(masks(Orientation::Rotate180), [0.9, 0.8, 0.7, 0.4, 0.9, 0.8, r.0, r.1, 10.0, 0.9, 0.8, 0.7, 0.4]);
assert_eq!(masks(Orientation::FlipH), [0.9, 0.2, 0.7, 0.6, 0.9, 0.2, r.0, r.1, -10.0, 0.9, 0.2, 0.7, 0.6]);
assert_eq!(masks(Orientation::Transpose), [0.2, 0.1, 0.6, 0.3, 0.2, 0.1, r.1, r.0, -10.0, 0.2, 0.1, 0.6, 0.3]);
// a photo already in the library has its shown size (portrait here), but Lightroom's edges are
// fractions of the stored image: a circle on a 3:2 stored image stays a circle
let s = r#"s = { MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.1, CorrectionMasks = {
{ What = "Mask/CircularGradient", Left = 0.3, Right = 0.5, Top = 0.3, Bottom = 0.6, Version = 2, Flipped = true } } } } }"#;
let (partial, _) = mapped_settings(s, crate::crs::Target::RawAbsolute, 1.0 / 1.5, Orientation::Rotate90, 1.5, Orientation::Normal).unwrap();
let radial = &partial["masks"][0]["components"][0]["shape"];
assert!(close(&radial["rx"], 0.1) && close(&radial["ry"], 0.1), "{radial}");
}
/// The `crs` corners and angle Lightroom would store for LightCraft crop `g` on a stored image
/// of aspect `w` (height 1) shown with orientation `o`.
fn lightroom_crop(g: CropGeometry, o: Orientation, w: f64) -> String {
@@ -306,7 +623,8 @@ fn straightened_catalog_crops_round_trip() {
for o in [Orientation::Normal, Orientation::Rotate90, Orientation::Rotate270, Orientation::Rotate180, Orientation::FlipH] {
for angle in [6.5, -6.5] {
let g = CropGeometry { angle, ..g };
let (partial, _) = mapped_settings(&lightroom_crop(g, o, 1.5), crate::crs::Target::RawAbsolute, 1.5, o, 1.5).unwrap();
let (partial, _) =
mapped_settings(&lightroom_crop(g, o, 1.5), crate::crs::Target::RawAbsolute, 1.5, o, 1.5, Orientation::Normal).unwrap();
let got: CropGeometry = serde_json::from_value(partial["crop"]["geometry"].clone()).unwrap();
let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
assert!(
@@ -336,7 +654,7 @@ fn straightened_catalog_crops_match_lightroom_exports() {
(6100.0, 9150.0),
),
] {
let (partial, _) = mapped_settings(settings, crate::crs::Target::RawAbsolute, 1.5, o, 9504.0 / 6336.0).unwrap();
let (partial, _) = mapped_settings(settings, crate::crs::Target::RawAbsolute, 1.5, o, 9504.0 / 6336.0, Orientation::Normal).unwrap();
let r: Rect = serde_json::from_value(partial["crop"]["geometry"]["rect"].clone()).unwrap();
let (ow, oh) = if o.swaps_axes() { (6336.0, 9504.0) } else { (9504.0, 6336.0) };
let (w, h) = (r.width() * ow, r.height() * oh);
@@ -359,6 +677,87 @@ fn imported_crops_use_the_catalog_orientation() {
assert_eq!(r, [0.1, 0.1, 0.8, 0.6]);
}
/// Masks only the catalog's XMP has (the develop row has none to replace them) are on the stored
/// image too: on a vertical shot (`DA`) they turn like the row's, and a radial keeps its shape on
/// the 2:1 stored image, also for a photo already in the library at its shown 10 × 20.
#[test]
fn catalog_xmp_masks_follow_the_photo_orientation() {
let mut data = sample();
data.photos.truncate(1);
data.photos[0].image.remove("masterImage");
data.photos[0].image.insert("orientation".into(), json!("DA"));
data.photos[0].image.insert("fileWidth".into(), json!(20));
data.photos[0].image.insert("fileHeight".into(), json!(10));
data.photos[0].settings = "s = { Exposure2012 = 0.5 }".into();
data.photos[0].xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/">
<crs:MaskGroupBasedCorrections><rdf:Seq>
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionAmount="1" crs:LocalExposure2012="-0.25">
<crs:CorrectionMasks><rdf:Seq>
<rdf:li crs:What="Mask/Gradient" crs:FullX="0.1" crs:FullY="0.2" crs:ZeroX="0.3" crs:ZeroY="0.6"/>
<rdf:li crs:What="Mask/CircularGradient" crs:Left="0.3" crs:Right="0.5" crs:Top="0.3" crs:Bottom="0.6" crs:Flipped="true" crs:Version="2"/>
</rdf:Seq></crs:CorrectionMasks>
</rdf:Description></rdf:li>
</rdf:Seq></crs:MaskGroupBasedCorrections>
</rdf:Description></rdf:RDF></x:xmpmeta>"#
.into();
let mut s = crate::Session::new();
let id = s.catalog.alloc_photo_id();
let shown = Photo::new(id, Source::File { path: "/missing/test.ARW".into() }, "test.ARW", "ARW", 10, 20, "before");
s.commit("Browse folder", Op::AddPhoto { photo: Box::new(shown) }).unwrap();
apply(&mut s, data, true).unwrap();
assert_eq!(s.catalog.len(), 1, "the catalog's photo is the one already in the library");
let p = s.catalog.photo(id).unwrap();
assert_eq!(p.develop.light.exposure, 0.5, "the develop row is applied too");
let c = &serde_json::to_value(&p.develop.masks).unwrap()[0]["components"];
let (linear, radial) = (&c[0]["shape"], &c[1]["shape"]);
let r = [&linear["start"]["x"], &linear["start"]["y"], &linear["end"]["x"], &linear["end"]["y"], &radial["center"]["x"], &radial["center"]["y"]]
.map(|v| (v.as_f64().unwrap() * 1e9).round() / 1e9);
// (x, y) → (y, 1 − x), a quarter turn counter-clockwise
assert_eq!(r, [0.2, 0.9, 0.6, 0.7, 0.45, 0.6], "{c}");
// 4 × 3 px of a 20 × 10 stored image, in long-edge units, with the axes swapped
let radii = [&radial["rx"], &radial["ry"]].map(|v| (v.as_f64().unwrap() * 1e9).round() / 1e9);
assert_eq!(radii, [0.075, 0.1], "{radial}");
}
/// A photo already in the library keeps its Rotate Left / Right on update, so the catalog's masks
/// go through it too: an upright (`AB`) photo turned right in LightCraft gets its gradient turned.
#[test]
fn updated_masks_follow_the_rotation_kept_from_the_library() {
let mut data = sample();
data.photos.truncate(1);
data.photos[0].image.remove("masterImage");
data.photos[0].image.insert("orientation".into(), json!("AB"));
data.photos[0].settings =
r#"s = { MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.1, CorrectionMasks = {
{ What = "Mask/Gradient", FullX = 0.1, FullY = 0.2, ZeroX = 0.3, ZeroY = 0.6 } } } } }"#
.into();
data.photos[0].xmp = String::new();
let mut s = crate::Session::new();
apply(&mut s, data.clone(), false).unwrap();
let id = s.catalog.photos().next().unwrap().id;
let turned = lightcraft_develop::DevelopSettings { orientation: Orientation::Rotate90, ..Default::default() };
s.set_develop(id, turned, "Rotate Right").unwrap();
apply(&mut s, data, true).unwrap();
let p = s.catalog.photo(id).unwrap();
assert_eq!(p.develop.orientation, Orientation::Rotate90, "the update keeps the photo's rotation");
let g = &serde_json::to_value(&p.develop.masks).unwrap()[0]["components"][0]["shape"];
let r = [&g["start"]["x"], &g["start"]["y"], &g["end"]["x"], &g["end"]["y"]].map(|v| (v.as_f64().unwrap() * 1e9).round() / 1e9);
// (x, y) → (1 − y, x), a quarter turn clockwise
assert_eq!(r, [0.8, 0.1, 0.4, 0.3], "{g}");
// the catalog's orientation first, then the photo's own, for every pair
for a in 1..=8 {
for b in 1..=8 {
let (a, b) = (Orientation::from_exif(a), Orientation::from_exif(b));
for (x, y) in [(0.1, 0.2), (0.7, 0.4)] {
let (u, v) = a.map(x, y, 1.0, 1.0);
let ((p, q), (want_p, want_q)) = (in_photo_frame(a, b).map(x, y, 1.0, 1.0), b.map(u, v, 1.0, 1.0));
assert!((p - want_p).abs() < 1e-9 && (q - want_q).abs() < 1e-9, "{a:?} then {b:?}: ({p}, {q}) for ({want_p}, {want_q})");
}
}
}
}
#[test]
fn deferred_auto_tone_sentinels_never_become_real_slider_values() {
let mut data = sample();
@@ -374,8 +773,15 @@ fn deferred_auto_tone_sentinels_never_become_real_slider_values() {
assert_eq!(p.develop.light.shadows, 65.0);
assert_eq!(p.develop.light.blacks, -22.0);
assert!(report["unmapped"]["2"].as_array().unwrap().iter().any(|v| v.as_str().is_some_and(|v| v.contains("Deferred"))));
let (partial, _) =
mapped_settings("s = { Exposure2012 = -5, Contrast2012 = -100 }", crate::crs::Target::RawAbsolute, 1.0, Orientation::Normal, 1.5).unwrap();
let (partial, _) = mapped_settings(
"s = { Exposure2012 = -5, Contrast2012 = -100 }",
crate::crs::Target::RawAbsolute,
1.0,
Orientation::Normal,
1.5,
Orientation::Normal,
)
.unwrap();
assert_eq!(partial["light"]["exposure"], -5.0);
assert_eq!(partial["light"]["contrast"], -100.0);
}
@@ -548,6 +954,83 @@ fn photo_tables(root: (&str, &str)) -> Vec<(&'static str, &'static str, Vec<SqlV
]
}
#[test]
fn native_video_import_is_visible_in_video_filter() {
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-video-filter-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("videos.lrcat");
let mut tables = photo_tables((dir.to_str().unwrap(), ""));
tables[2].2[2] = SqlValue::Text("clip.MOV".into());
tables[3].2[3] = SqlValue::Text("VIDEO".into());
std::fs::write(&path, native_catalog(&tables)).unwrap();
let mut s = crate::Session::new();
let imported = s.execute("library.importLightroom", &json!({"path": path})).unwrap();
let id = PhotoId(imported["mapping"]["1"].as_u64().unwrap());
assert_eq!(s.catalog.photo(id).unwrap().kind, lightcraft_catalog::MediaKind::Video);
s.execute("library.filter", &json!({"kind": "video"})).unwrap();
assert_eq!(s.visible(), &[id]);
s.execute("library.filter", &json!({"kind": "image"})).unwrap();
assert!(s.visible().is_empty());
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.catalog.is_empty());
s.execute("edit.redo", &json!({})).unwrap();
s.execute("library.filter", &json!({"kind": "video"})).unwrap();
assert_eq!(s.visible(), &[id]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn native_video_reimport_repairs_kind_without_losing_edits_or_memberships() {
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-video-reimport-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("videos.lrcat");
let mut tables = photo_tables((dir.to_str().unwrap(), ""));
tables[2].2[2] = SqlValue::Text("clip.MOV".into());
tables[3].2[3] = SqlValue::Text("VIDEO".into());
std::fs::write(&path, native_catalog(&tables)).unwrap();
let mut s = crate::Session::new();
let id = s.catalog.alloc_photo_id();
let mut photo =
Photo::new(id, Source::File { path: dir.join("Photos/clip.MOV").to_string_lossy().into() }, "clip.MOV", "VIDEO", 1920, 1080, "before");
photo.rating = 5;
photo.flag = Flag::Pick;
photo.file_size = 1234;
photo.content_hash = Some("existing-content".into());
s.commit("Previous import", Op::AddPhoto { photo: Box::new(photo) }).unwrap();
let mut settings = lightcraft_develop::DevelopSettings::default();
settings.light.exposure = 0.75;
s.set_develop(id, settings, "Personal edit").unwrap();
let peer_id = s.catalog.alloc_photo_id();
let peer = Photo::new(peer_id, Source::File { path: "/missing/peer.jpg".into() }, "peer.jpg", "JPEG", 20, 10, "before");
s.commit("Peer", Op::AddPhoto { photo: Box::new(peer) }).unwrap();
let mut album = Album::new(s.catalog.alloc_album_id(), "Personal album");
album.photos = vec![id, peer_id];
s.commit("Album", Op::AddAlbum { album: album.clone() }).unwrap();
let stack = lightcraft_catalog::Stack { id: s.catalog.alloc_stack_id(), photos: vec![id, peer_id], collapsed: false };
s.commit("Stack", Op::AddStack { stack: stack.clone() }).unwrap();
let before = s.catalog.to_snapshot();
let mut expected = (**s.catalog.photo(id).unwrap()).clone();
expected.kind = lightcraft_catalog::MediaKind::Video;
s.execute("library.filter", &json!({"kind": "video"})).unwrap();
assert!(s.visible().is_empty());
let result = s.execute("library.importLightroom", &json!({"path": path})).unwrap();
assert_eq!(result["mapping"]["1"], id.0);
assert_eq!(result["imported"], 0);
assert_eq!(result["preservedExistingEdits"], 1);
assert_eq!(s.catalog.photo(id).unwrap().as_ref(), &expected);
assert_eq!(s.visible(), &[id]);
let after = s.catalog.to_snapshot();
assert_eq!(s.catalog.album(album.id), Some(&album));
assert_eq!(s.catalog.stack(stack.id), Some(&stack));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.catalog.to_snapshot(), before);
assert!(s.visible().is_empty());
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.catalog.to_snapshot(), after);
assert_eq!(s.visible(), &[id]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn reads_native_sqlite_tables_without_lightroom_or_external_processes() {
let bytes = native_catalog(&photo_tables(("/catalog/", "")));
+15 -2
View File
@@ -25,6 +25,10 @@ pub struct QuickJob {
pub cached: Vec<(Arc<PreviewCache>, Hash128)>,
/// Embedded preview of an unedited raw: (path, loader, max edge).
pub embedded: Option<(String, PreviewLoader, usize)>,
/// Import tiles need this many pixels when a render can provide them. `None` accepts any
/// camera JPEG immediately (ordinary transient stand-ins and preview-only imports).
/// An undersized JPEG remains the fallback if the render fails or is unavailable.
pub minimum_embedded_edge: Option<usize>,
/// Last resort: run this thumbnail job.
pub small: Option<Box<RenderJob>>,
}
@@ -72,14 +76,23 @@ impl QuickJob {
return done(rendered(Arc::unwrap_or_clone(img)), Some(QuickSource::Cached));
}
}
let mut embedded_fallback = None;
if let Some((path, loader, edge)) = &self.embedded
&& let Some(image) = loader(path, *edge)
{
return done(rendered(image), Some(QuickSource::Embedded));
if self.minimum_embedded_edge.is_none_or(|minimum| image.width.max(image.height) >= minimum) {
return done(rendered(image), Some(QuickSource::Embedded));
}
embedded_fallback = Some(image);
}
if let Some(job) = self.small {
let r = job.run();
return RenderResult { request_id, key, quick: Some(QuickSource::Small), ..r };
if r.rendered.is_ok() || embedded_fallback.is_none() {
return RenderResult { request_id, key, quick: Some(QuickSource::Small), ..r };
}
}
if let Some(image) = embedded_fallback {
return done(rendered(image), Some(QuickSource::Embedded));
}
done(Err("no quick preview".into()), None)
}
+14 -1
View File
@@ -270,11 +270,24 @@ impl RenderJob {
// Thumbnails (many small jobs side by side) stay on the CPU; views and exports use
// the GPU when there is one.
let gpu = self.cache.is_none();
let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &self.request, self.stages.as_deref(), gpu);
// a clipping preview tests sRGB values, like the histogram: rendered in sRGB, then
// converted for the display below
let clip_view = self.request.overlay.is_clipping();
let request = if clip_view { RenderRequest { display: None, ..self.request } } else { self.request };
let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu);
// for a display profile: the image goes to the display's values, the histogram
// and the cached view preview stay sRGB
let mut srgb = None;
let display = match (&self.display, self.request.display) {
// a diagnostic view: the histogram stays the photo's (taken before the overlay
// was drawn), and nothing goes to the view cache
(Some(d), Some(_)) if self.request.overlay != lightcraft_pipeline::Overlay::None => {
let converted = if clip_view { d.profile.from_srgb(&mut rendered.image) } else { d.profile.correct(&mut rendered.image) };
if let Err(e) = converted {
log::warn!("display profile: {e}");
}
Some(d.id())
}
(Some(d), Some(_)) => {
let keep = self.view_cache.is_some() && self.request.quality == Quality::Full;
let (s, h) = crate::display::finish_render(&mut rendered.image, d, keep);
+17 -1
View File
@@ -11,7 +11,11 @@ impl crate::Session {
/// A grid/filmstrip thumbnail job: the long edge is rounded up to one of [`THUMB_SIZES`]
/// (≥ `long_edge`) and the result comes from / goes to the thumbnail cache (memory + disk).
/// `None` for a video: the image decoders can't read one, so none is asked to (issue #2682).
pub fn thumb_job(&mut self, id: PhotoId, long_edge: usize) -> Option<RenderJob> {
if self.catalog.photo(id).is_some_and(|p| p.is_video()) {
return None;
}
let b = thumb_bucket(long_edge);
let mut job = self.build_job(id, b, b, false, true, Some(b))?;
// (a thumbnail may develop a smaller copy of the raw image that the file keeps)
@@ -342,7 +346,7 @@ impl crate::Session {
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).finish();
let key = h.0 as u64;
let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));
Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, small: apply_crop.then(|| Box::new(small)) })
Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, minimum_embedded_edge: None, small: apply_crop.then(|| Box::new(small)) })
}
/// A first grid thumbnail for an unedited raw: the cached render for `job` (the real
@@ -361,6 +365,7 @@ impl crate::Session {
key: job.key,
cached: job.cache.clone().into_iter().collect(),
embedded: Some((path, l, edge)),
minimum_embedded_edge: None,
small: Some(Box::new(job.clone())),
})
}
@@ -399,6 +404,7 @@ impl crate::Session {
/// Synchronous render (CLI, MCP, tests).
pub fn render_now(&mut self, id: PhotoId, max_w: usize, max_h: usize) -> Result<Rendered, String> {
lightcraft_pipeline::check_output_size(max_w, max_h)?;
let job = self.render_job(id, max_w, max_h, false, true).ok_or("no such photo")?;
let r = job.run();
self.accept(&r);
@@ -429,7 +435,17 @@ impl crate::Session {
space: lightcraft_pipeline::OutputSpace,
depth: lightcraft_pipeline::OutputDepth,
) -> Result<RenderJob, String> {
lightcraft_pipeline::check_output_size(max_w, max_h)?;
let mut job = self.render_job(id, max_w, max_h, false, true).ok_or("no such photo")?;
// An export develops from a source at least twice its size, so it is resized down with a good filter
// rather than made from a preview just covering it (for a raw, a binned and box-reduced image)
let p = self.catalog.photo(id).ok_or("no such photo")?.clone();
let level = SourceLevel::for_size(source_edge_needed(&p, &job.settings, true, max_w.max(max_h)).saturating_mul(2));
if level.max_edge() > job.level.max_edge() {
job.source = self.media.source_ref(&p, level);
job.key ^= ((job.level as u64) << 60) ^ ((level as u64) << 60);
job.level = level;
}
// An export renders the full image: never a thumbnail's source developed from a smaller copy of the raw
// image that the file keeps (Lightroom's merged DNGs)
let reduced = match &job.source {
+7 -3
View File
@@ -1,7 +1,7 @@
use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 72;
pub const RENDER_CACHE_VERSION: u64 = 73;
/// 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];
@@ -59,10 +59,14 @@ impl SourceLevel {
/// Pixels along the source's long edge that an output `out_long` pixels long needs: a crop shows
/// only part of the photo, so its pixels come from a source that many times larger (the source
/// level is chosen from this, or a tight crop shown at its own pixels would be a stretched preview).
/// The crop is bounded as the render bounds it (issue #2555), so one reaching far past the photo
/// doesn't pick a source too small for the frame it renders. Its rect is in the photo as shown
/// (turned by its orientation), so it is measured with the turned size.
pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_crop: bool, out_long: usize) -> usize {
let (w, h) = (f64::from(p.width.max(1)), f64::from(p.height.max(1)));
let r = settings.crop.geometry.rect;
let shown = if apply_crop { (r.width() * w).max(r.height() * h) } else { w.max(h) };
let (ow, oh) = if settings.orientation.swaps_axes() { (h, w) } else { (w, h) };
let r = settings.crop.geometry.bounded(ow, oh).rect;
let shown = if apply_crop { (r.width() * ow).max(r.height() * oh) } else { w.max(h) };
if !shown.is_finite() || shown < 1.0 {
return out_long;
}
+123
View File
@@ -297,6 +297,54 @@ fn work_gate_waits_for_room() {
drop(g.acquire(1000));
}
/// Issue #2576: work weighed with saturating maths can ask for `usize::MAX` bytes. Adding to
/// that overflowed (a panic with the gate's mutex held in a debug build, a wrapped count that
/// let everything in for a release one). The count is now exact past `usize::MAX`: later work
/// waits, whichever permit is released first, and even on a gate whose limit is `usize::MAX`.
#[test]
fn work_gate_counts_past_usize_max_instead_of_overflowing() {
use crate::memory::WorkGate;
// a holder of one byte, on its own thread; still waiting 50 ms later
let waiting = |g: &Arc<WorkGate>| {
let g2 = g.clone();
let t = std::thread::spawn(move || {
let _b = g2.acquire(1);
g2.usage().0
});
std::thread::sleep(std::time::Duration::from_millis(50));
assert!(!t.is_finished(), "the next holder waits");
t
};
// the huge permit released first: the urgent one is still counted
let g = Arc::new(WorkGate::new(100));
let huge = g.acquire(usize::MAX);
let urgent = g.acquire_urgent(101);
assert_eq!(g.usage().0, usize::MAX, "reported saturated");
drop(huge);
assert_eq!(g.usage().0, 101);
let t = waiting(&g);
drop(urgent);
assert_eq!(t.join().unwrap(), 1);
assert_eq!(g.usage().0, 0);
// the urgent permit released first
let huge = g.acquire(usize::MAX);
drop(g.acquire_urgent(1));
assert_eq!(g.usage().0, usize::MAX);
let t = waiting(&g);
drop(huge);
assert_eq!(t.join().unwrap(), 1);
assert_eq!(g.usage().0, 0);
// a gate without a practical limit is still full when it holds usize::MAX
let g = Arc::new(WorkGate::new(usize::MAX));
let huge = g.acquire(usize::MAX);
let t = waiting(&g);
drop(huge);
assert_eq!(t.join().unwrap(), 1);
}
#[test]
fn levels_cover_sizes_and_large_exports_use_the_original() {
assert_eq!(SourceLevel::for_size(256), SourceLevel::Thumb);
@@ -368,6 +416,62 @@ fn a_tight_crop_reads_the_source_level_its_pixels_need() {
assert_eq!(s.render_job(id, 600, 600, false, true).unwrap().level, SourceLevel::Preview);
}
// Issue #2555: a turned crop reaching far past the photo (from a sidecar or an agent) is rendered
// bounded to the turned photo, so its source is sized from that bounded crop: shown 1600 px long it
// needs the preview, not the 512 px thumbnail its rect of 1000 photos across asked for
#[test]
fn a_crop_far_past_the_photo_reads_the_source_its_bounded_frame_needs() {
let mut s = crate::Session::with_demo();
let id = s.catalog.photos().next().unwrap().id;
let wild = lightcraft_geom::CropGeometry { rect: lightcraft_geom::Rect::new(0.0, 0.0, 1000.0, 1000.0), angle: 5.0 };
let mut d = (*s.develop_of(id).unwrap()).clone();
d.crop.geometry = wild;
s.set_develop(id, d, "Crop").unwrap();
assert_eq!(s.render_job(id, 1600, 1600, false, true).unwrap().level, SourceLevel::Preview);
// bounded in the frame the render bounds it in: the photo's own, or turned a quarter
let p = s.catalog.photo(id).unwrap().clone();
let (w, h) = (f64::from(p.width), f64::from(p.height));
assert_ne!(w, h, "a square photo can't tell the two frames apart");
for orientation in [lightcraft_geom::Orientation::Normal, lightcraft_geom::Orientation::Rotate90] {
let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) };
let mut d = lightcraft_develop::DevelopSettings { orientation, ..Default::default() };
d.crop.geometry = wild;
let r = wild.bounded(ow, oh).rect;
let expected = (1600.0 * w.max(h) / (r.width() * ow).max(r.height() * oh)) as usize;
assert_eq!(super::source::source_edge_needed(&p, &d, true, 1600), expected, "{orientation:?}");
}
}
// …while every crop the crop tools make, turned or not, on a photo shown upright or turned a
// quarter, still asks for exactly the source its own rect needs
#[test]
fn crops_on_the_photo_keep_the_source_size_they_need() {
use lightcraft_geom::{Orientation, crop_fit_angle};
let s = crate::Session::with_demo();
let p = s.catalog.photos().next().unwrap().clone();
let (w, h) = (f64::from(p.width), f64::from(p.height));
for orientation in [Orientation::Normal, Orientation::Rotate90] {
let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) };
for angle in [-45.0, -12.5, 0.0, 7.0, 45.0] {
for aspect in [None, Some(1.0), Some(3.0), Some(0.25)] {
let mut d = lightcraft_develop::DevelopSettings { orientation, ..Default::default() };
d.crop.geometry = crop_fit_angle(ow, oh, angle, aspect);
// the rect is in the photo as shown, so its pixels are counted in the turned size
let r = d.crop.geometry.rect;
let expected = (1600.0 * w.max(h) / (r.width() * ow).max(r.height() * oh)) as usize;
assert_eq!(super::source::source_edge_needed(&p, &d, true, 1600), expected, "{orientation:?} {angle} {aspect:?}");
}
}
}
// a square crop of the photo turned a quarter is the photo's short side across: shown 2000 px
// long it needs more than the 2560 px preview (counted in the unturned size, it asked for 2000)
let mut d = lightcraft_develop::DevelopSettings { orientation: Orientation::Rotate90, ..Default::default() };
d.crop.geometry = crop_fit_angle(h, w, 0.0, Some(1.0));
let needed = super::source::source_edge_needed(&p, &d, true, 2000);
assert_eq!(needed, (2000.0 * w.max(h) / w.min(h)) as usize);
assert_eq!(SourceLevel::for_size(needed), SourceLevel::Full, "{needed}");
}
// a window whose spot reads from further away than a render can hold is refused
#[test]
fn a_region_job_is_refused_when_a_spot_reads_beyond_what_fits() {
@@ -517,3 +621,22 @@ fn variant_jobs_have_their_own_keys_and_hit_the_cache() {
assert_ne!(pv.key, s.render_job(id, 800, 600, false, true).unwrap().key);
assert_eq!(*pv.settings, a);
}
/// An export develops from a source at least twice its long edge (a 2000 px export of a 6000 px
/// photo from the original, not the 2560 px preview, which for a raw is binned and box-reduced),
/// while on-screen views keep the cheap preview.
#[test]
fn an_export_develops_from_a_source_twice_its_size() {
use lightcraft_pipeline::{OutputDepth, OutputSpace};
let mut s = crate::Session::with_demo();
let id = s.active().unwrap();
let p = s.catalog.photo(id).unwrap().clone();
assert!(p.width.max(p.height) >= 6000, "a camera-sized demo: {}×{}", p.width, p.height);
let job = s.export_job(id, 2000, 2000, OutputSpace::Srgb, OutputDepth::U8).unwrap();
assert_eq!(job.level, SourceLevel::Full, "2000 px export");
for edge in [200, 600, 1280, 1281, 2560] {
let job = s.export_job(id, edge, edge, OutputSpace::Srgb, OutputDepth::U8).unwrap();
assert!(job.level.max_edge() >= 2 * edge, "{edge} px export from {:?}", job.level);
}
assert_eq!(s.render_job(id, 1600, 1600, false, true).unwrap().level, SourceLevel::Preview, "a view keeps the preview");
}
@@ -107,6 +107,7 @@ fn a_render_that_panics_fails_instead_of_never_answering() {
key: 9,
cached: Vec::new(),
embedded: Some(("x.arw".into(), Arc::new(|_: &str, _: usize| -> Option<Rgba8> { panic!("preview reader bug") }), 256)),
minimum_embedded_edge: None,
small: None,
};
let r = quick.run();
Loaded 100 of 380 files, more files were not shown because too many files have changed in this diff. Show more