diff --git a/AGENTS.md b/AGENTS.md index 4044a6563e..f10fedb20b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — 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.]` 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. diff --git a/CLAUDE.md b/CLAUDE.md index 9b384fc6c2..0597cbf465 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — 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`, diff --git a/Cargo.lock b/Cargo.lock index 17f738ea5e..8063ed5a40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index a59de44ec4..0d2a65d715 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 } diff --git a/README.md b/README.md index ba094749ce..1f01e291f0 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/README.zh-hans.md b/README.zh-hans.md index fa782ba10f..a577a8db7b 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -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)。 diff --git a/README.zh-hant.md b/README.zh-hant.md index 07ac908d2d..f2c223897a 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -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 配接器、語料庫、字型)以及每一項 diff --git a/ROADMAP.md b/ROADMAP.md index daad94027d..0571abfb99 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~14 points and ~340–600 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-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 | diff --git a/apps/lightcraft-cli/Cargo.toml b/apps/lightcraft-cli/Cargo.toml index b82aca1d59..e55d458b32 100644 --- a/apps/lightcraft-cli/Cargo.toml +++ b/apps/lightcraft-cli/Cargo.toml @@ -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"] diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index d510e1801d..ffad0ff1be 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -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 = std::env::args().skip(1).collect(); + let mut args: Vec = 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 = 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, 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 = 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); + } +} diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs index 8a11f5c9ab..613197459c 100644 --- a/apps/lightcraft-cli/tests/it/cli.rs +++ b/apps/lightcraft-cli/tests/it/cli.rs @@ -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 = "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 = 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 = 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, 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, 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}"); // `:` 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=` 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()) diff --git a/apps/lightcraft/src/control_server.rs b/apps/lightcraft/src/control_server.rs index 95aa108964..f606696407 100644 --- a/apps/lightcraft/src/control_server.rs +++ b/apps/lightcraft/src/control_server.rs @@ -87,7 +87,7 @@ fn serve(stream: TcpStream, tx: &Sender, 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, 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) { + 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, max: usize) -> Result { +fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { 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, 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(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(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:?}"); } } diff --git a/apps/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index a7b8904d62..13edce0fd5 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -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, Vec) { +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, Vec) { - 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, + env: Option<&std::path::PathBuf>, + argument: Option, +) -> (Option, 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, + pub(crate) library: Option, + pub(crate) notices: Vec, +} + +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`). diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index f87f0dc726..2f98abafe1 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -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); 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::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; diff --git a/apps/lightcraft/src/native_menu.rs b/apps/lightcraft/src/native_menu.rs index d25b565661..17f01a2c74 100644 --- a/apps/lightcraft/src/native_menu.rs +++ b/apps/lightcraft/src/native_menu.rs @@ -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(nodes: &[MenuNode], items: &mut HashMap, 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, want: Option, native_call_worked: bool) -> Option { @@ -311,6 +379,50 @@ fn tidy_separators(nodes: Vec) -> Vec { 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 { + 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, +} + +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 { + 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 = 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, 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::>(), &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 = 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 = 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> = 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, + } + 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| MenuNode::Item { + id: cmd.into(), + params: Value::Null, + label: label.into(), + shortcut: None, + enabled, + checked, + }; + let model = |a: (&str, bool, Option), b: (&str, bool, Option), c: (&str, bool, Option), d: (&str, bool, Option)| { + 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 = 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| 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"); diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index b886b472f7..7d9db79bdb 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -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) { 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, seed_demo: bool) -> (Session, Option) { +/// 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, remembered: bool, seed_demo: bool) -> (Session, Option) { 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, 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!( diff --git a/apps/lightcraft/src/tests.rs b/apps/lightcraft/src/tests.rs index 0afbc4b2c6..286838175e 100644 --- a/apps/lightcraft/src/tests.rs +++ b/apps/lightcraft/src/tests.rs @@ -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 = ["", " ", ".", "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); +} diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index fefa65a516..e8caedf738 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -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, forced: Option, 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) -> Option<(WindowRenderer, Option)> { +fn pick_probed(order: &[WindowRenderer], problems: &mut Vec, compose_window: bool) -> Option<(WindowRenderer, Option)> { 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) -> Option<( } /// Create a device on `backends` and build egui's pipeline on it; any wgpu error is returned. -fn probe(backends: Backends) -> Result { +fn probe(backends: Backends, compose_window: bool) -> Result { 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)); + } } diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index e5ed8090e7..d95e95b415 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -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. diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 2a6dd4b88f..ff6aafd659 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -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 diff --git a/contributors/people.toml b/contributors/people.toml index 7518acd388..836a3d801f 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -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" diff --git a/crates/catalog/Cargo.toml b/crates/catalog/Cargo.toml index b12e188036..aecd1f97d0 100644 --- a/crates/catalog/Cargo.toml +++ b/crates/catalog/Cargo.toml @@ -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 } diff --git a/crates/catalog/src/dates.rs b/crates/catalog/src/dates.rs index 2dfebbf906..3635bfe332 100644 --- a/crates/catalog/src/dates.rs +++ b/crates/catalog/src/dates.rs @@ -49,7 +49,12 @@ pub fn weekday(iso: &str) -> Option<&'static str> { pub fn shift_iso(iso: &str, secs: i64) -> Option { let iso = iso.trim(); let tail = iso.get(tail_start(iso)?..)?; - let t = iso_seconds(iso)?.checked_add(secs)?; + let 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")); diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index 40e0015380..d36ab11cd6 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -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::>().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, + /// 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, +} + +/// 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 = keywords.iter().map(|k| clean(k)).collect(); + dedupe(&mut paths); + let mut flat: Vec = 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 { + 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 = + 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 { diff --git a/crates/catalog/src/keywords/tests.rs b/crates/catalog/src/keywords/tests.rs index df65606ef4..6f50bd482e 100644 --- a/crates/catalog/src/keywords/tests.rs +++ b/crates/catalog/src/keywords/tests.rs @@ -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::>(); + 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 = 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 diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a697..7995546434 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -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>, + guard: std::sync::OnceLock, +} + +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 { + 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 { + 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 = 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 = 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 { 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 { + 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 { // 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 { 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>>, +} + +impl AlbumGraph { + fn of<'a>(albums: impl Iterator) -> 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 { + // 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 = testing.iter().enumerate().map(|(i, (id, _))| (*id, i)).collect(); + let leads: Vec> = 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; diff --git a/crates/catalog/src/lock.rs b/crates/catalog/src/lock.rs index f701087a69..5534e86cc5 100644 --- a/crates/catalog/src/lock.rs +++ b/crates/catalog/src/lock.rs @@ -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. diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index b405e1db96..eebc9b3e45 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -354,6 +354,17 @@ pub fn preview_stamp(preview_only: &Option) -> 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 { 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"); diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index 94cfa17640..7b5ad5ecd0 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -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, + /// 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, pub kind: Option, pub edited: Option, pub album: Option, @@ -72,6 +76,11 @@ pub struct Filter { pub rule_set: Option, } +/// 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, D::Error> { + Ok(Option::>::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, only: Option>, + /// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]); + /// `None` tests them as written. + rules: Option, } /// 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> { + 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 = 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::>().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 { + 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, within: &Filter) -> Vec { - 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 { let listed: std::collections::HashSet = was.iter().copied().filter(|id| touched.binary_search(id).is_ok()).collect(); let mut ids: Vec = 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 { let filter = Filter { person: None, ..filter.clone() }; let mut m: std::collections::HashMap = 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 = Vec::new(); for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) { diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index ec92dc7246..50960cc9a8 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -488,6 +488,12 @@ fn pass_answer(id: crate::AlbumId, photo: crate::PhotoId) -> Option { }) } +#[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 = 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 { + 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(op: &str, path: &str, want: &str) -> Option { + 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; diff --git a/crates/catalog/src/rules/tests_path_fold.rs b/crates/catalog/src/rules/tests_path_fold.rs new file mode 100644 index 0000000000..fbb5d45f27 --- /dev/null +++ b/crates/catalog/src/rules/tests_path_fold.rs @@ -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 { + 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 { + 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::(), op in prop::sample::select(OPS.to_vec())) { + let chars: Vec = 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 = (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?}"); + } +} diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index 32392469c9..0b31ca9750 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -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(); diff --git a/crates/catalog/src/tests_album_loops.rs b/crates/catalog/src/tests_album_loops.rs new file mode 100644 index 0000000000..c378ca4f7e --- /dev/null +++ b/crates/catalog/src/tests_album_loops.rs @@ -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 = 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 = (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(); +} diff --git a/crates/catalog/src/tests_journal.rs b/crates/catalog/src/tests_journal.rs index 26b4e902ab..d50c0e533b 100644 --- a/crates/catalog/src/tests_journal.rs +++ b/crates/catalog/src/tests_journal.rs @@ -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())); diff --git a/crates/catalog/src/tests_repair.rs b/crates/catalog/src/tests_repair.rs index 9feb038a53..0c35aca1fd 100644 --- a/crates/catalog/src/tests_repair.rs +++ b/crates/catalog/src/tests_repair.rs @@ -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![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"); +} diff --git a/crates/catalog/src/tests_rule_order.rs b/crates/catalog/src/tests_rule_order.rs new file mode 100644 index 0000000000..d3f4486742 --- /dev/null +++ b/crates/catalog/src/tests_rule_order.rs @@ -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 , ]`, 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) { + let mut c = Catalog::new(); + let ids: Vec = (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 = (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 = 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 = (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 = [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 = (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 = (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 = 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 = ["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::>() + }; + 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 = (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); +} diff --git a/crates/catalog/tests/path_fold_heap.rs b/crates/catalog/tests/path_fold_heap.rs new file mode 100644 index 0000000000..4fc1c8ef14 --- /dev/null +++ b/crates/catalog/tests/path_fold_heap.rs @@ -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 = ["/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 = [ + ("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> = 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()); +} diff --git a/crates/codecs/README.md b/crates/codecs/README.md index c9d5cec7df..b993c52efe 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -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 | diff --git a/crates/codecs/src/convert.rs b/crates/codecs/src/convert.rs index 2cdf67381b..76f0c3a550 100644 --- a/crates/codecs/src/convert.rs +++ b/crates/codecs/src/convert.rs @@ -78,6 +78,8 @@ pub(crate) struct Raw { #[derive(Default)] pub(crate) struct Meta { pub icc: Option>, + /// An ICC profile was declared by the container but its sequence was invalid. + pub icc_invalid: bool, pub exif: Option>, pub xmp: Option, /// 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)) } diff --git a/crates/codecs/src/jpeg.rs b/crates/codecs/src/jpeg.rs index d8b0241a13..89af1372bf 100644 --- a/crates/codecs/src/jpeg.rs +++ b/crates/codecs/src/jpeg.rs @@ -24,6 +24,8 @@ pub(crate) struct Markers { pub exif_offset: usize, pub xmp: Option, pub icc: Option>, + /// An ICC_PROFILE APP2 segment was present but its sequence was invalid. + pub icc_invalid: bool, pub adobe_transform: Option, /// Offset of the MPF TIFF header within the file and its bytes. pub mpf: Option<(usize, Vec)>, @@ -45,7 +47,8 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option { 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 { 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 { } } 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 { } _ => {} } - 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 { + 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) -> Result { + 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 { + 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]) -> Vec { + 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)); diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index a20a47d14c..8210f33f01 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -207,6 +207,7 @@ pub fn read_header_unguarded(bytes: &[u8], format: Format) -> Result
{ 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))?; diff --git a/crates/codecs/src/other.rs b/crates/codecs/src/other.rs index ebba2eaedf..021cb08c82 100644 --- a/crates/codecs/src/other.rs +++ b/crates/codecs/src/other.rs @@ -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 { + 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::); + 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 { 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 { 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}"); + } + } } diff --git a/crates/codecs/tests/it/fuzz.rs b/crates/codecs/tests/it/fuzz.rs index bfee84dfe4..5139d71ba9 100644 --- a/crates/codecs/tests/it/fuzz.rs +++ b/crates/codecs/tests/it/fuzz.rs @@ -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 { + 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 { + 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 { + 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 { + 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]); diff --git a/crates/codecs/tests/it/header.rs b/crates/codecs/tests/it/header.rs index 6ff12d08b4..f6ce7d3216 100644 --- a/crates/codecs/tests/it/header.rs +++ b/crates/codecs/tests/it/header.rs @@ -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 { + // 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) -> Vec { + 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() { diff --git a/crates/color/src/spline.rs b/crates/color/src/spline.rs index c8860d9509..c2c75f305d 100644 --- a/crates/color/src/spline.rs +++ b/crates/color/src/spline.rs @@ -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)) { diff --git a/crates/develop/src/controls.rs b/crates/develop/src/controls.rs index 715e8ac339..9d384f57c4 100644 --- a/crates/develop/src/controls.rs +++ b/crates/develop/src/controls.rs @@ -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 Result { + 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 = 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); + } } diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index b3edc801cd..d5a658f51c 100644 --- a/crates/develop/src/presets.rs +++ b/crates/develop/src/presets.rs @@ -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::(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 = 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); + } } diff --git a/crates/develop/src/segmask.rs b/crates/develop/src/segmask.rs index 172d53fce1..de0aede09d 100644 --- a/crates/develop/src/segmask.rs +++ b/crates/develop/src/segmask.rs @@ -104,9 +104,14 @@ fn base64_encode(bytes: &[u8]) -> String { fn base64_decode(s: &str) -> Option> { 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> { 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] diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index a40f094c25..739171abd9 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -134,6 +134,7 @@ pub struct DevelopSettings { pub orientation: Orientation, pub masks: Vec, pub spots: Vec, + /// Red eye corrections; the first [`MAX_RED_EYES`] render. pub red_eye: Vec, 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, 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>(self, mut seq: A) -> Result, 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::()?.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)] diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index bbeead9552..d177df84e7 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -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 { diff --git a/crates/engine/src/camera_preview/colour.rs b/crates/engine/src/camera_preview/colour.rs index 2681466a91..6befe7ce1a 100644 --- a/crates/engine/src/camera_preview/colour.rs +++ b/crates/engine/src/camera_preview/colour.rs @@ -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) { 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) }, ); diff --git a/crates/engine/src/camera_preview/look_fit.rs b/crates/engine/src/camera_preview/look_fit.rs index 9968998a52..6605caf4d8 100644 --- a/crates/engine/src/camera_preview/look_fit.rs +++ b/crates/engine/src/camera_preview/look_fit.rs @@ -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, 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, 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)> { + 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. diff --git a/crates/engine/src/camera_preview/mono.rs b/crates/engine/src/camera_preview/mono.rs index 3c0bd57364..6939c39adf 100644 --- a/crates/engine/src/camera_preview/mono.rs +++ b/crates/engine/src/camera_preview/mono.rs @@ -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 { +/// 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 { 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; } diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 81d7fe351e..dd5ad2fcb6 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -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)> { 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::>(); + // 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::>() + }; let high = |l: &[f64]| -> Vec { (0..w * h) .map(|i| { diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 4b65ed6459..f805b34183 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -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 = pairs.iter().map(|p| p.0).collect(); + let mut ys: Vec = 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) { 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 = (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 = (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 diff --git a/crates/engine/src/camera_preview/tone.rs b/crates/engine/src/camera_preview/tone.rs index f16b8e8994..52598d35c2 100644 --- a/crates/engine/src/camera_preview/tone.rs +++ b/crates/engine/src/camera_preview/tone.rs @@ -133,7 +133,106 @@ pub(super) fn fit_tone(pairs: Vec<(f64, f64)>) -> Option { 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::()) + }; + 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 = (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 { @@ -182,5 +281,5 @@ pub(super) fn fit_tone_conditional(mut pairs: Vec<(f64, f64)>) -> Option 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 diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index b24246592e..49f75181ca 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -256,10 +256,11 @@ pub fn specs() -> Vec { "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 { "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 { + 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::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::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::>()) { + 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); + } +} diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index fbc3d4041a..df1089925d 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -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 { + 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 { + 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> { v?.as_array()?.iter().map(Value::as_f64).collect() @@ -256,8 +330,10 @@ pub fn specs() -> Vec { 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 { "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 { 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::>(); s.commit(&format!("Preset: {}", preset.name), Op::Batch { ops })?; ok() diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index e3b385e2c1..15519fc757 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -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"); diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index ebed426fae..0e612227f1 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -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 { 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> { + 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 = 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::>()?, + None | Some(Value::Null) => Vec::new(), + Some(_) => return Err(invalid()), + }; + let mut out: Vec = 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 { 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 { 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 = 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()) }), diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 5d1b0fef12..4bf9654250 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -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; diff --git a/crates/engine/src/cmd/library/gps.rs b/crates/engine/src/cmd/library/gps.rs index 44f0e02c5f..de969b37cf 100644 --- a/crates/engine/src/cmd/library/gps.rs +++ b/crates/engine/src/cmd/library/gps.rs @@ -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 { + 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 { - 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 = - up.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|x| !x.is_empty()).map(|x| x.parse::().ok()).collect::>()?; - 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, explicit_sign: &mut Option) -> Option<()> { + if token.is_empty() { + return Some(()); + } + if components.len() == 3 { + return None; + } + let value = token.parse::().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); } } diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 8437bf1658..2a663b79de 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -66,6 +66,10 @@ pub fn import_params(s: &Session, p: &Value) -> Result { } 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 { 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), diff --git a/crates/engine/src/cmd/library/selection.rs b/crates/engine/src/cmd/library/selection.rs index 723b7c3316..964b2a8c85 100644 --- a/crates/engine/src/cmd/library/selection.rs +++ b/crates/engine/src/cmd/library/selection.rs @@ -35,10 +35,22 @@ pub(super) fn strs(p: &Value, key: &str) -> Vec { /// 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) -> (Vec, usize) { - let before = targets.len(); - let kept: Vec = 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 = 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) } diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 2e7c1311d0..a2a842106a 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -87,7 +87,7 @@ pub fn specs() -> Vec { "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 { 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 = 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 { 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 { "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 { 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 { 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 { 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 = 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 = 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 = al.photos.iter().copied().collect(); - let all_in = !targets.is_empty() && targets.iter().all(|t| held.contains(t)); - let photos: Vec = if all_in { - let targets: std::collections::HashSet = 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 = al.photos.iter().copied().collect(); + let all_in = targets.iter().all(|t| held.contains(t)); + let photos: Vec = if all_in { + let targets: std::collections::HashSet = 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 { "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)?; diff --git a/crates/engine/src/cmd/library/tests_clear_label.rs b/crates/engine/src/cmd/library/tests_clear_label.rs new file mode 100644 index 0000000000..87a2dee554 --- /dev/null +++ b/crates/engine/src/cmd/library/tests_clear_label.rs @@ -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 { + 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> { + (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"); +} diff --git a/crates/engine/src/cmd/library/tests_enable_filters.rs b/crates/engine/src/cmd/library/tests_enable_filters.rs index 9eb3c1ad03..1a40a17923 100644 --- a/crates/engine/src/cmd/library/tests_enable_filters.rs +++ b/crates/engine/src/cmd/library/tests_enable_filters.rs @@ -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)); +} diff --git a/crates/engine/src/cmd/library/tests_rated_out.rs b/crates/engine/src/cmd/library/tests_rated_out.rs index 49c36596bd..e1785a7484 100644 --- a/crates/engine/src/cmd/library/tests_rated_out.rs +++ b/crates/engine/src/cmd/library/tests_rated_out.rs @@ -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(); diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index 2fd44d5665..5fc083f51f 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -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 { 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(); diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index c06997eefb..e5a17ab5db 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -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) -> 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> { + 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 { pub fn specs() -> Vec { 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", diff --git a/crates/engine/src/cmd/organize.rs b/crates/engine/src/cmd/organize.rs index dbd0aa8422..84d82c7c9c 100644 --- a/crates/engine/src/cmd/organize.rs +++ b/crates/engine/src/cmd/organize.rs @@ -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>> { + 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> { +/// 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> { 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 { |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); } } diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index e1b33cc714..dc1f2c864a 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -320,9 +320,13 @@ fn build(s: &mut Session, p: &Value) -> Result { type SmartJob = (lightcraft_catalog::PhotoId, std::path::PathBuf, Option, 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] diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index a3926bc514..5ceacb9539 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -142,7 +142,7 @@ pub fn specs() -> Vec { .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 { "versions": ph.versions.iter().map(|v| json!({"name": v.name, "created": v.created})).collect::>(), })) }), - 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(), diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index f47e099b65..34840e46d3 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -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())); diff --git a/crates/engine/src/doc_path.rs b/crates/engine/src/doc_path.rs index d3f455b81c..b1c48762fa 100644 --- a/crates/engine/src/doc_path.rs +++ b/crates/engine/src/doc_path.rs @@ -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"))); diff --git a/crates/engine/src/export/prepare.rs b/crates/engine/src/export/prepare.rs index 0a3dce119e..d71a60e0b7 100644 --- a/crates/engine/src/export/prepare.rs +++ b/crates/engine/src/export/prepare.rs @@ -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" )); } } diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index 139939a1d9..b8482a7df2 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -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() }; diff --git a/crates/engine/src/files/fs.rs b/crates/engine/src/files/fs.rs index 7012211af6..549c83b19c 100644 --- a/crates/engine/src/files/fs.rs +++ b/crates/engine/src/files/fs.rs @@ -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(path: &str, max_edge: usize, load: impl FnOnce(Vec) -> 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 { - let t = std::fs::metadata(path).ok()?.modified().ok()?; +fn modified_iso(meta: &std::fs::Metadata) -> Option { + 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)) } diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 600d3b187a..2537afba2c 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -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. diff --git a/crates/engine/src/fonts.rs b/crates/engine/src/fonts.rs index db9e658d07..c45f5f94b2 100644 --- a/crates/engine/src/fonts.rs +++ b/crates/engine/src/fonts.rs @@ -3,7 +3,7 @@ //! Built with `CRAFT_FONTS_DIR=`, [`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 { diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 4ab53179aa..3149fa2ae6 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -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. diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 6fe6658966..6a6b6e6a70 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -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)] diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 7d1a69fddb..a731488a00 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -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)), diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index 0997945977..39c55f56ff 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -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 { + 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(limit: std::time::Duration, probe: impl FnOnce() -> Option + Send + 'static) -> Option { + 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) -> Option { + 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, + deadline: std::time::Instant, +) -> Option { 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(items: &[T], cancel: &std::sync::atomic::AtomicBool, ask: impl Fn(&T) -> R + Sync) -> Vec> { + use std::sync::atomic::Ordering::Relaxed; + let mut answers: Vec> = 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> = 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 { + 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 + Sync, +) -> Vec> { + 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, + cancel: &std::sync::atomic::AtomicBool, + ok: impl Fn(Seen, &ProbeInfo) -> bool, +) -> Vec> { + let held: Vec> = 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 = (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 = (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 = (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::::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 = (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> = (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#""#; + let files: Vec = ["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); + } } diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 1730518d54..3269edb02a 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -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, file_bytes: Option, /// Probes from a preceding scan (not read again). - cache: HashMap, + pub(super) cache: HashMap, naming: crate::sidecar::SidecarNaming, now: String, - seq: usize, + /// Next rename number; `None` once the final representable value has been reserved. + seq: Option, /// Files found so far (folders expanded) and handled so far, for progress. pub total: std::sync::Arc, pub done: std::sync::Arc, @@ -73,6 +74,8 @@ pub(super) enum PreparedItem { existing: Option, reason: &'static str, hash: Option, + /// What the file itself says, when it was read ([`Duplicate::file`]). + file: Option>, }, 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> = 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 = 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; diff --git a/crates/engine/src/import/job/tests.rs b/crates/engine/src/import/job/tests.rs new file mode 100644 index 0000000000..82490915b7 --- /dev/null +++ b/crates/engine/src/import/job/tests.rs @@ -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, renderable: bool, preview_only: bool) -> (Session, ImportCandidate, Arc) { + 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)); + } +} diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index ef925fa059..57ee995f26 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -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, progress: &Sc let by_path = library_files(&input.library, &files); let todo: Vec = 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> = 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 = 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(); diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index 6ad3e21539..f342bf4c92 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -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>, +} + +/// 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, } #[derive(Clone, Debug, Default, Serialize)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa180700..163a102680 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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 { + 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) -> Result { // 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); } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a5071b4b35..caf51a0ab6 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -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 { + 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 { @@ -68,6 +84,37 @@ pub fn default_dir() -> Option { 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 { + home_folder_from(cfg!(windows), |name| std::env::var_os(name)) +} + +fn home_folder_from(windows: bool, var: impl Fn(&str) -> Option) -> Option { + 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 { 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() { diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 3066187ce3..c7bf8611b8 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -640,6 +640,14 @@ fn drop_copies_of(data: &mut CatalogImport, masters: &HashSet) { 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 = 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> { 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(), }) } diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 654b40458c..a85828d63f 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -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 = ["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#" + + + + + + + + + +"# + .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, 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, /// Last resort: run this thumbnail job. pub small: Option>, } @@ -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) } diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index a87a0792c4..4c28e1214f 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -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); diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index b222739fed..79cfa556c8 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -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 { + 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 { + 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 { + 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 { diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index bf2e81804d..08ba806170 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -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; } diff --git a/crates/engine/src/media/tests.rs b/crates/engine/src/media/tests.rs index d362842625..efa6a504ca 100644 --- a/crates/engine/src/media/tests.rs +++ b/crates/engine/src/media/tests.rs @@ -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| { + 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"); +} diff --git a/crates/engine/src/media/thumbnail_hash_tests.rs b/crates/engine/src/media/thumbnail_hash_tests.rs index fdbd20f803..3c23e9db95 100644 --- a/crates/engine/src/media/thumbnail_hash_tests.rs +++ b/crates/engine/src/media/thumbnail_hash_tests.rs @@ -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 { panic!("preview reader bug") }), 256)), + minimum_embedded_edge: None, small: None, }; let r = quick.run(); diff --git a/crates/engine/src/memory.rs b/crates/engine/src/memory.rs index 49094a1f3c..61a41f99c0 100644 --- a/crates/engine/src/memory.rs +++ b/crates/engine/src/memory.rs @@ -99,7 +99,10 @@ pub fn cache_share(budget: usize) -> usize { /// A weighted semaphore over bytes of working memory: [`WorkGate::acquire`] waits while other /// holders already use the limit (one holder may always proceed, whatever its size). pub struct WorkGate { - state: Mutex<(usize, usize)>, + /// Bytes held and the limit. Held is a `u128`: callers weigh work with saturating maths, so a + /// permit may hold `usize::MAX`, and the exact total of several such permits still fits, so + /// releasing one in any order leaves the others counted (issue #2576). + state: Mutex<(u128, usize)>, cv: Condvar, } @@ -114,7 +117,7 @@ impl WorkGate { WorkGate { state: Mutex::new((0, limit)), cv: Condvar::new() } } - fn lock(&self) -> std::sync::MutexGuard<'_, (usize, usize)> { + fn lock(&self) -> std::sync::MutexGuard<'_, (u128, usize)> { self.state.lock().unwrap_or_else(|e| e.into_inner()) } @@ -123,24 +126,27 @@ impl WorkGate { self.cv.notify_all(); } - /// Bytes held now and the limit. + /// Bytes held now (at most `usize::MAX`) and the limit. pub fn usage(&self) -> (usize, usize) { - *self.lock() + let g = self.lock(); + (usize::try_from(g.0).unwrap_or(usize::MAX), g.1) } - /// Hold `bytes`, waiting until they fit (or nothing else is held). + /// Hold `bytes`, waiting until they fit (or nothing else is held). Even `usize::MAX` bytes on + /// a gate whose limit is `usize::MAX` make the next holder wait. pub fn acquire(&self, bytes: usize) -> Permit<'_> { let mut g = self.lock(); - while g.0 > 0 && g.0 + bytes > g.1 { + while g.0 > 0 && g.0.saturating_add(bytes as u128) > g.1 as u128 { g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner()); } - g.0 += bytes; + g.0 = g.0.saturating_add(bytes as u128); Permit { gate: self, bytes } } /// Hold `bytes` without waiting (interactive work): counted, so background work waits for it. pub fn acquire_urgent(&self, bytes: usize) -> Permit<'_> { - self.lock().0 += bytes; + let mut g = self.lock(); + g.0 = g.0.saturating_add(bytes as u128); Permit { gate: self, bytes } } } @@ -148,7 +154,7 @@ impl WorkGate { impl Drop for Permit<'_> { fn drop(&mut self) { let mut g = self.gate.lock(); - g.0 = g.0.saturating_sub(self.bytes); + g.0 = g.0.saturating_sub(self.bytes as u128); drop(g); self.gate.cv.notify_all(); } diff --git a/crates/engine/src/originals.rs b/crates/engine/src/originals.rs index af2fc5d14b..7a82b3a93c 100644 --- a/crates/engine/src/originals.rs +++ b/crates/engine/src/originals.rs @@ -127,7 +127,8 @@ impl OriginalGuard { put(format!("{name}.xmp"), PathBuf::from(format!("{}.xmp", path.to_string_lossy())), format!("the XMP sidecar of {label}")); } - /// `Err` (a message for the user) when writing `target` would replace a protected file. + /// `Err` (a message for the user) when writing `target` would replace a protected file, or + /// create a protected sidecar that isn't there yet. pub fn check(&self, target: &Path) -> Result<(), String> { self.check_target(target, false) } @@ -141,7 +142,7 @@ impl OriginalGuard { fn check_target(&self, target: &Path, hard_links: bool) -> Result<(), String> { if std::fs::symlink_metadata(target).is_err() { - return Ok(()); // nothing there to replace + return self.check_new(target); // nothing there to replace } let mut names: Vec = target.file_name().map(|n| n.to_string_lossy().to_lowercase()).into_iter().collect(); if let Some(n) = std::fs::canonicalize(target).ok().and_then(|c| c.file_name().map(|n| n.to_string_lossy().to_lowercase())) { @@ -186,6 +187,30 @@ impl OriginalGuard { } Ok(()) } + + /// A new file with a sidecar's name in that sidecar's folder would be read back as the + /// photo's edits. The folders are compared by identity, so `sub/../` or a link counts. + fn check_new(&self, target: &Path) -> Result<(), String> { + if !is_xmp(target) { + return Ok(()); + } + let Some(name) = target.file_name().map(|n| n.to_string_lossy().to_lowercase()) else { return Ok(()) }; + for (p, what) in self.by_name.get(&name).into_iter().flatten() { + if same_file(folder_of(p), folder_of(target)) { + return Err(format!("{} would become {what} in the library (choose another folder or file name)", target.display())); + } + } + Ok(()) + } +} + +fn is_xmp(path: &Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) +} + +/// The folder `path` is in (`.` for a bare file name). +fn folder_of(path: &Path) -> &Path { + path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")) } impl crate::Session { @@ -194,12 +219,13 @@ impl crate::Session { OriginalGuard::new(&self.catalog) } - /// `Err` when writing `path` would replace a catalogued photo's original or sidecar. A free - /// path (the usual case) is answered without building the guard over the whole library. + /// `Err` when writing `path` would replace a catalogued photo's original or sidecar, or + /// create one of its sidecars. A free path that isn't an `.xmp` (the usual case) is answered + /// without building the guard over the whole library. pub fn check_write_target(&self, path: &str) -> Result<(), String> { let path = Path::new(path); - if std::fs::symlink_metadata(path).is_err() { - return Ok(()); // nothing there to replace + if std::fs::symlink_metadata(path).is_err() && !is_xmp(path) { + return Ok(()); // nothing there to replace, and no sidecar to create } self.original_guard().check(path) } @@ -214,6 +240,10 @@ impl crate::Session { let parent = p.parent().filter(|d| !d.as_os_str().is_empty()).and_then(|d| std::fs::canonicalize(d).ok()); match std::fs::symlink_metadata(p) { Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + // nothing there yet, but a new file with a photo's sidecar name would be read as its edits + if is_xmp(p) { + self.original_guard().check(p)?; + } Ok(WriteTarget { path: path.to_string(), state: WriteTargetState::Absent, parent }) } Err(error) => Err(format!("{path}: {error}")), @@ -294,6 +324,32 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + #[test] + fn a_sidecar_that_isnt_there_yet_is_protected_too() { + let d = std::env::temp_dir().join(format!("lc-originals-new-sidecar-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(d.join("sub")).unwrap(); + let orig = d.join("IMG_1.jpg"); + std::fs::write(&orig, b"original").unwrap(); + let mut c = Catalog::default(); + let p = Photo::new(PhotoId(1), Source::File { path: orig.to_string_lossy().to_string() }, "IMG_1.jpg", "JPEG", 10, 10, "2026-01-01"); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let g = OriginalGuard::new(&c); + assert!(g.check(&d.join("IMG_1.xmp")).unwrap_err().contains("XMP sidecar of IMG_1.jpg")); + assert!(g.check(&d.join("IMG_1.jpg.xmp")).is_err(), "the appended spelling"); + assert!(g.check(&d.join("sub/../IMG_1.xmp")).is_err(), "another spelling of the folder"); + assert!(g.check(&d.join("sub/IMG_1.xmp")).is_ok(), "the same name in another folder"); + assert!(g.check(&d.join("other.xmp")).is_ok(), "no photo of that name"); + assert!(g.check(&d.join("missing/IMG_1.xmp")).is_ok(), "a folder that isn't there"); + // a write pinned ahead of time (a queued screenshot) is refused the same way + let mut s = crate::Session::new(); + s.catalog = c; + let pinned = s.pin_write_target(&d.join("IMG_1.xmp").to_string_lossy()); + assert!(pinned.unwrap_err().contains("XMP sidecar of IMG_1.jpg")); + assert!(s.pin_write_target(&d.join("sub/IMG_1.xmp").to_string_lossy()).is_ok(), "the same name in another folder"); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn write_targets_pin_absent_paths_and_recheck_the_current_library() { let d = std::env::temp_dir().join(format!("lc-write-targets-{}", std::process::id())); @@ -370,7 +426,21 @@ mod tests { // identity of either name cannot be read while it is held. let held = std::fs::OpenOptions::new().read(true).share_mode(0).open(&original).unwrap(); let refused = s.pin_write_target(&linked.to_string_lossy()).unwrap_err(); - assert!(refused.contains("cannot tell whether"), "{refused}"); + // Except with SeBackupPrivilege enabled (an admin's Git Bash, so every Windows CI gate leg): + // a backup-semantics open of both names, as the guard's identity read uses, gets past the + // held handle. The guard then sees the link and refuses it as the original instead (#3228). + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; + let backup_open = |p: &std::path::Path| std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_BACKUP_SEMANTICS).open(p).is_ok(); + if backup_open(&original) && backup_open(&linked) { + assert!(refused.contains("is the original"), "{refused}"); + assert!(!refused.contains("cannot tell whether"), "{refused}"); + lightcraft_testkit::skip!( + System, + "a backup-semantics open gets past share_mode(0) here (SeBackupPrivilege is enabled), so the \"cannot tell whether\" refusal can't be tested" + ); + } else { + assert!(refused.contains("cannot tell whether"), "{refused}"); + } drop(held); let refused = s.pin_write_target(&linked.to_string_lossy()).unwrap_err(); diff --git a/crates/engine/src/preset_luminar.rs b/crates/engine/src/preset_luminar.rs index e883045684..73b008d9ff 100644 --- a/crates/engine/src/preset_luminar.rs +++ b/crates/engine/src/preset_luminar.rs @@ -89,8 +89,9 @@ fn unescape(t: &str) -> String { _ => ent .strip_prefix("#x") .or_else(|| ent.strip_prefix("#X")) + .filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) .and_then(|h| u32::from_str_radix(h, 16).ok()) - .or_else(|| ent.strip_prefix('#').and_then(|d| d.parse().ok())) + .or_else(|| ent.strip_prefix('#').filter(|d| d.bytes().all(|b| b.is_ascii_digit())).and_then(|d| d.parse().ok())) .and_then(char::from_u32), }; match c { @@ -485,6 +486,12 @@ mod tests { use crate::preset_import::read_presets; use serde_json::json; + #[test] + fn unescape_rejects_signed_numeric_references() { + assert_eq!(unescape("&#+65;&#x+41;"), "&#+65;&#x+41;"); + assert_eq!(unescape("AA"), "AA"); + } + /// One effect's parameter as Luminar writes it. fn param(name: &str, v: f64) -> String { format!("{name}OptionalDataType0Value{v}") diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index d13b951257..9f3e518a49 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -76,16 +76,37 @@ pub fn find_sidecar(original: &str, naming: SidecarNaming) -> Option { sidecar_candidates(original, naming).find(|p| p.is_file()) } +/// Where to look for a catalogued photo's sidecar: how the library names it, and whether the photo +/// may read the shared stem sidecar (`IMG_0001.xmp`) of its stem. A photo that shares its stem +/// with a file that owns that sidecar (see [`Session::sidecar_naming`]) reads its own `.xmp` +/// and never the packet of the sibling that owns the stem one (issue #1523). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SidecarLookup { + pub naming: SidecarNaming, + /// False when another file with the same stem owns the stem sidecar. + pub owns_stem: bool, +} + +impl SidecarLookup { + /// The names a sidecar for `original` can have, in the order they are looked for: those of + /// [`sidecar_candidates`], without the shared stem sidecar when the photo does not own it. + pub(crate) fn candidates(self, original: &str) -> impl Iterator { + let shared = (!self.owns_stem).then(|| xmp_cases(sidecar_path(original, SidecarNaming::Stem))); + sidecar_candidates(original, self.naming).filter(move |p| shared.as_ref().is_none_or(|shared| !shared.contains(p))) + } + + /// [`find_sidecar`], except that a photo that does not own its stem sidecar never reads it. + pub fn find(self, original: &str) -> Option { + self.candidates(original).find(|p| p.is_file()) + } +} + /// Find the sidecar for a file an import is adding, by the ownership [`ImportStems`] worked out /// (issue #1905): [`find_sidecar`] with the library's naming, except that a file which does not /// own its stem sidecar reads its own `.xmp` (the name it writes) and never the packet of /// the sibling that owns the stem one. pub(crate) fn find_sidecar_for_import(stems: &ImportStems, naming: SidecarNaming, original: &str) -> Option { - if stems.owns(original) { - return find_sidecar(original, naming); - } - let shared = xmp_cases(sidecar_path(original, SidecarNaming::Stem)); - sidecar_candidates(original, SidecarNaming::Full).filter(|p| !shared.contains(p)).find(|p| p.is_file()) + SidecarLookup { naming, owns_stem: stems.owns(original) }.find(original) } /// The names `original`'s sidecar can have, in the order they are looked for: under `naming`, @@ -202,7 +223,8 @@ pub fn parse_sidecar(xmp: &str, target: crate::crs::Target) -> std::result::Resu out.label = Some(ColorLabel::parse(l.trim())); out.label_text = Some(l.trim().to_string()); } - let full = d.lc_settings.as_deref().and_then(|j| serde_json::from_str::(j).ok()).and_then(|v| DevelopSettings::from_json(&v).ok()); + let full = + d.lc_settings.as_deref().and_then(|j| serde_json::from_str::(j).ok()).and_then(|v| DevelopSettings::from_untrusted_json(&v).ok()); out.develop = match full { Some(s) => Some(DevelopPatch::Full(Box::new(s))), None if crate::crs::has_adjustments(&d.properties) => { @@ -354,6 +376,8 @@ pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String { /// `remove_location` is set (an export with "Remove location info"). pub fn sidecar_packet_with(p: &Photo, cat: &lightcraft_catalog::Catalog, remove_location: bool) -> String { let nz = |s: &str| (!s.trim().is_empty()).then(|| s.to_string()); + // Names in `dc:subject`, paths in `lr:hierarchicalSubject` (`keywords::to_file`). + let keywords = lightcraft_catalog::keywords::to_file(&p.meta.keywords); let meta = lightcraft_meta::Metadata { software: Some("LightCraft".into()), title: nz(&p.meta.title), @@ -369,7 +393,8 @@ pub fn sidecar_packet_with(p: &Photo, cat: &lightcraft_catalog::Catalog, remove_ usage_terms: nz(&p.meta.usage_terms), copyright_url: nz(&p.meta.copyright_url), artist: nz(&p.meta.creator), - keywords: p.meta.keywords.clone(), + keywords: keywords.flat, + hierarchical_keywords: keywords.hierarchical, rating: Some(p.rating.min(5) as i8), label: p.label.map(|l| cat.label_name(l)), capture_time: p.captured.as_deref().and_then(lightcraft_meta::DateTime::parse_iso), @@ -404,6 +429,7 @@ pub const OWNED: &[&str] = &[ "dc:rights", "dc:creator", "dc:subject", + "lr:hierarchicalSubject", "Iptc4xmpCore:Location", "Iptc4xmpCore:AltTextAccessibility", "Iptc4xmpCore:ExtDescrAccessibility", @@ -523,8 +549,8 @@ fn file_path(p: &Photo) -> Option<&str> { } /// The XMP packet that describes a photo on disk: its sidecar, else embedded raw/DNG or JPEG XMP. -pub fn read_packet(original: &str, kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { - if let Some(sc) = find_sidecar(original, naming) { +pub fn read_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Option<(String, PathBuf)> { + if let Some(sc) = lookup.find(original) { // A discovered sidecar keeps precedence even when reading it fails. return std::fs::read_to_string(&sc).ok().map(|s| (s, sc)); } @@ -675,6 +701,11 @@ impl StemOwners { StemOwners(best.into_iter().filter(|(_, v)| v.2 > 1).map(|(k, v)| (k, v.1)).collect()) } + /// Whether photo `p` may read the shared stem sidecar of its stem: no other file owns it. + fn owns(&self, p: &Photo) -> bool { + file_path(p).is_none_or(|path| self.0.get(&stem_key(path)).is_none_or(|owner| *owner == p.id)) + } + /// `naming` for photo `p`, except that a stem sidecar another file owns becomes Full. fn naming(&self, p: &Photo, naming: SidecarNaming) -> SidecarNaming { match (naming, file_path(p)) { @@ -747,11 +778,16 @@ impl ImportStems { /// How the sidecar of each of photos `ids` is named in library `cat`, whose naming is `naming` /// ([`Session::sidecar_namings`], for a thread that has the library and not the session). pub(crate) fn namings_in(cat: &lightcraft_catalog::Catalog, naming: SidecarNaming, ids: &[PhotoId]) -> Vec { - let owners = (naming == SidecarNaming::Stem).then(|| StemOwners::among(cat, ids)); + lookups_in(cat, naming, ids).into_iter().map(|l| l.naming).collect() +} + +/// [`namings_in`], with whether each photo may read the stem sidecar of its stem. +pub(crate) fn lookups_in(cat: &lightcraft_catalog::Catalog, naming: SidecarNaming, ids: &[PhotoId]) -> Vec { + let owners = StemOwners::among(cat, ids); ids.iter() - .map(|id| match (cat.photo(*id), &owners) { - (Some(p), Some(o)) => o.naming(p, naming), - _ => naming, + .map(|id| match cat.photo(*id) { + Some(p) => SidecarLookup { naming: owners.naming(p, naming), owns_stem: owners.owns(p) }, + None => SidecarLookup { naming, owns_stem: true }, }) .collect() } @@ -767,6 +803,16 @@ impl Session { namings_in(&self.catalog, self.xmp.naming, ids) } + /// [`Session::sidecar_naming`] and the stem-sidecar ownership of photo `id`, for reading its sidecar. + pub fn sidecar_lookup(&self, id: PhotoId) -> SidecarLookup { + lookups_in(&self.catalog, self.xmp.naming, &[id]).into_iter().next().unwrap_or(SidecarLookup { naming: self.xmp.naming, owns_stem: true }) + } + + /// [`Session::sidecar_lookup`] for many photos, their stems' owners worked out once. + pub fn sidecar_lookups(&self, ids: &[PhotoId]) -> Vec { + lookups_in(&self.catalog, self.xmp.naming, ids) + } + pub fn sidecar_naming(&self, id: PhotoId) -> SidecarNaming { match self.catalog.photo(id) { Some(p) if self.xmp.naming == SidecarNaming::Stem => StemOwners::among(&self.catalog, &[id]).naming(p, self.xmp.naming), @@ -830,7 +876,7 @@ impl Session { pub fn read_sidecar_op_with_warnings(&self, id: PhotoId) -> Result)>> { let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let Some(orig) = file_path(p) else { return Ok(None) }; - let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_naming(id)) else { return Ok(None) }; + let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { return Ok(None) }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; let mut warnings = sc.warnings.clone(); for warning in &mut warnings { @@ -980,6 +1026,23 @@ mod tests { assert_eq!(sc.keywords, Some(vec!["Places|Lisbon".to_string()])); } + /// Issue #2556: a sidecar's `lc:settings` colour-range mask keeps at most `MAX_COLOR_RANGE_SAMPLES` samples. + #[test] + fn sidecar_color_range_samples_are_capped() { + use lightcraft_develop::{MAX_COLOR_RANGE_SAMPLES, Mask, MaskComponent, MaskOp, MaskShape}; + let samples: Vec<[f64; 3]> = (0..1000).map(|i| [i as f64 / 1000.0, 0.1, -0.1]).collect(); + let mut d = DevelopSettings::default(); + let shape = MaskShape::ColorRange { samples: samples.clone(), refine: 50.0 }; + d.masks.push(Mask { id: 1, components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape }], ..Default::default() }); + let xmp = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata::default(), Some(&d.to_json().to_string())); + let sc = super::parse_sidecar(&xmp, crate::crs::Target::Rendered).unwrap(); + let Some(DevelopPatch::Full(s)) = sc.develop else { panic!("expected full settings") }; + let Some(MaskShape::ColorRange { samples: got, .. }) = s.masks.first().and_then(|m| m.components.first()).map(|c| &c.shape) else { + panic!("expected a colour range") + }; + assert_eq!(got.as_slice(), &samples[..MAX_COLOR_RANGE_SAMPLES]); + } + use super::*; use lightcraft_catalog::Meta; diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index f20ad9c95e..3e69a074e9 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -46,7 +46,7 @@ use serde::Serialize; use crate::import::{ImportCandidate, ImportMode, ImportOptions, ScanInput, ScanProgress}; use crate::media::ProbeInfo; -use crate::sidecar::SidecarNaming; +use crate::sidecar::{SidecarLookup, SidecarNaming}; use crate::{EngineError, Result, Session}; /// The largest XMP sidecar read when looking for metadata updates; a bigger one is skipped. @@ -216,8 +216,8 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges { } // (how each photo's sidecar is named: a pass over the library, made here and not while the // session waits, and not at all for a folder that is not there) - let namings = crate::sidecar::namings_in(&labels, naming, &ids); - let photos: Vec<(Arc, SidecarNaming)> = + let namings = crate::sidecar::lookups_in(&labels, naming, &ids); + let photos: Vec<(Arc, SidecarLookup)> = ids.iter().zip(namings).filter_map(|(id, naming)| labels.photo(*id).map(|p| (Arc::clone(p), naming))).collect(); // The folder is walked once, and its listing answers for the library's photos in it: on a // network share that is one request for a folder's names where it was several for each @@ -509,7 +509,7 @@ impl Listing { } } -fn check_photo(p: &Photo, naming: SidecarNaming, labels: &Catalog, listing: &Listing) -> Check { +fn check_photo(p: &Photo, naming: SidecarLookup, labels: &Catalog, listing: &Listing) -> Check { let Some(file) = crate::cmd::missing::checked_path(p) else { return Check::Nothing }; let file = Path::new(file); if !listing.or_ask(listing.exists(file), || file.exists()) { @@ -523,11 +523,11 @@ fn check_photo(p: &Photo, naming: SidecarNaming, labels: &Catalog, listing: &Lis /// [`check_photo`] for each photo, in order, on several threads (each file is a wait on the /// disk, not work for the CPU). Photos not reached before a cancel count as nothing found. -fn check_photos(photos: &[(Arc, SidecarNaming)], labels: &Catalog, listing: &Listing, progress: &SyncProgress) -> Vec { +fn check_photos(photos: &[(Arc, SidecarLookup)], labels: &Catalog, listing: &Listing, progress: &SyncProgress) -> Vec { use std::sync::atomic::Ordering::Relaxed; progress.to_check.store(photos.len(), Relaxed); let cancel = &progress.files.cancel; - let check = |p: &Photo, naming: SidecarNaming| { + let check = |p: &Photo, naming: SidecarLookup| { let c = check_photo(p, naming, labels, listing); progress.checked.fetch_add(1, Relaxed); c @@ -596,12 +596,12 @@ impl Session { /// Whether `p`'s XMP sidecar file was saved after the library last had its say about the photo /// (imported, or edited here) and says something the library doesn't. -fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarNaming, listing: &Listing) -> bool { +fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarLookup, listing: &Listing) -> bool { let Source::File { path } = &p.source else { return false }; // ([`crate::sidecar::find_sidecar`], each name looked up in the listing before the disk) // (a name the listing holds is read for its date next, and one that can't be read is passed // over for the next name, as a name that is no file was) - let found = crate::sidecar::sidecar_candidates(path, naming).find_map(|c| { + let found = naming.candidates(path).find_map(|c| { let there = listing.or_ask(listing.is_file(&c), || c.is_file()); let meta = there.then(|| std::fs::metadata(&c).ok()).flatten().filter(std::fs::Metadata::is_file)?; Some((c, meta)) @@ -654,7 +654,7 @@ pub struct SyncWork { moved: Vec, missing: Vec, /// (photo, its file, how its sidecar is named) - sidecars: Vec<(PhotoId, String, SidecarNaming, crate::crs::Target)>, + sidecars: Vec<(PhotoId, String, SidecarLookup, crate::crs::Target)>, } /// The catalog half of a synchronize (see [`SyncJob`]). @@ -702,7 +702,7 @@ impl SyncJob { }; let now = import.as_ref().map_or_else(|| (s.clock)(), |(j, _)| j.now().to_string()); let sidecars = if choice.read_metadata { - let namings = s.sidecar_namings(&metadata.iter().map(|m| PhotoId(m.id)).collect::>()); + let namings = s.sidecar_lookups(&metadata.iter().map(|m| PhotoId(m.id)).collect::>()); metadata .into_iter() .zip(namings) @@ -794,8 +794,8 @@ impl SyncWork { } /// Read and parse photo file `path`'s XMP sidecar file. -fn read_sidecar(path: &str, naming: SidecarNaming, target: crate::crs::Target) -> std::result::Result { - let file = crate::sidecar::find_sidecar(path, naming).ok_or_else(|| "no XMP sidecar".to_string())?; +fn read_sidecar(path: &str, naming: SidecarLookup, target: crate::crs::Target) -> std::result::Result { + let file = naming.find(path).ok_or_else(|| "no XMP sidecar".to_string())?; let len = std::fs::metadata(&file).map_err(|e| format!("{}: {e}", file.display()))?.len(); if len > MAX_SIDECAR_BYTES { return Err(format!("{}: too large for an XMP sidecar", file.display())); diff --git a/crates/engine/src/sync/tests_listing.rs b/crates/engine/src/sync/tests_listing.rs index 4348ca830f..099b5dd0f9 100644 --- a/crates/engine/src/sync/tests_listing.rs +++ b/crates/engine/src/sync/tests_listing.rs @@ -8,6 +8,11 @@ use super::*; use crate::walk::EntryKind::{File, Folder, Other}; +/// The lookup of a photo that owns its stem sidecar, as every photo in these listings does. +fn owner(naming: SidecarNaming) -> SidecarLookup { + SidecarLookup { naming, owns_stem: true } +} + fn listing(folders: &[(&str, &[(&str, crate::walk::EntryKind)], bool)]) -> Listing { let mut l = Listing::default(); for (dir, names, complete) in folders { @@ -154,17 +159,17 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { let nothing = Listing::default(); for naming in [SidecarNaming::Stem, SidecarNaming::Full] { for p in &photos { - let from_disk = check_photo(p, naming, &c, ¬hing); - assert_eq!(check_photo(p, naming, &c, &l), from_disk, "{:?} {naming:?}", p.file_name); + let from_disk = check_photo(p, owner(naming), &c, ¬hing); + assert_eq!(check_photo(p, owner(naming), &c, &l), from_disk, "{:?} {naming:?}", p.file_name); } } let expected = [Check::Nothing, Check::News, Check::News, Check::News, Check::News, Check::News, Check::Missing, Check::Missing, Check::Missing]; - assert_eq!(photos.iter().map(|p| check_photo(p, SidecarNaming::Stem, &c, &l)).collect::>(), expected); + assert_eq!(photos.iter().map(|p| check_photo(p, owner(SidecarNaming::Stem), &c, &l)).collect::>(), expected); // what the disk was asked about the same photos, with the listing and without: fewer questions with it let asked = |l: &Listing| { for p in &photos { - check_photo(p, SidecarNaming::Stem, &c, l); + check_photo(p, owner(SidecarNaming::Stem), &c, l); } l.asked.load(std::sync::atomic::Ordering::Relaxed) }; @@ -193,7 +198,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { let mut c2 = Catalog::new(); for (name, expected) in [("deep.jpg", Check::News), ("gone.jpg", Check::Missing), ("gone.jpg.xmp", Check::Missing)] { let p = photo(&mut c2, &sub.join(name)); - assert_eq!(check_photo(&p, SidecarNaming::Stem, &c2, &only_plain), expected, "{name}"); + assert_eq!(check_photo(&p, owner(SidecarNaming::Stem), &c2, &only_plain), expected, "{name}"); } assert_eq!(only_plain.asked.load(std::sync::atomic::Ordering::Relaxed), 0, "every answer came from the listing"); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae03859d21..37b300dbfc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2,6 +2,8 @@ use serde_json::{Value, json}; use crate::{Selection, Session, command_specs}; +mod album_loops; +mod album_missing; mod album_order; mod album_remove; mod albums_local; @@ -42,6 +44,7 @@ mod process; mod recheck; mod segment; mod settings_files; +mod shelved_folder; mod slide; mod slideshow_export; mod spots; @@ -412,6 +415,17 @@ fn connected_brush_strokes_start_where_the_last_one_ended() { assert_eq!(strokes(&s).len(), 2); } +#[test] +fn a_mask_id_at_the_limit_does_not_overflow_the_next_masks() { + let mut s = demo(); + s.execute("develop.merge", &json!({"settings": {"masks": [{"id": u32::MAX, "name": "Pasted"}]}})).unwrap(); + s.execute("mask.add", &json!({"kind": "radial"})).unwrap(); + s.execute("mask.duplicate", &json!({})).unwrap(); + let ids: Vec = active_dev(&s).masks.iter().map(|m| m.id).collect(); + assert_eq!(ids.len(), 3); + assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "distinct ids: {ids:?}"); +} + #[test] fn brush_strokes_keep_pen_pressure_and_refuse_bad_lists() { let mut s = demo(); diff --git a/crates/engine/src/tests/album_loops.rs b/crates/engine/src/tests/album_loops.rs new file mode 100644 index 0000000000..f010d8ae19 --- /dev/null +++ b/crates/engine/src/tests/album_loops.rs @@ -0,0 +1,102 @@ +//! A smart album never comes to include itself by a new edit, whatever makes the edit +//! (`Session::commit` keeps the catalog's rule, `Catalog::apply_new`); a library that already +//! holds such a loop opens, works and can be mended, and undo and redo move across it freely. +//! +//! Scenarios: +//! - When an edit that no command checked (an op committed on its own, in a batch of edits that +//! are fine one by one, or as a new album) would put a smart album on a loop, then it is +//! refused, and there is nothing to undo or to journal. +//! - When commands make the edits, then every way to a loop stays refused and ordinary edits go +//! on, one undo step each. +//! - Given a library that holds a loop, then edits that add none go through, and undo and redo +//! bring the loop back and take it away without being refused. + +use lightcraft_catalog::{Album, AlbumId, Filter, Op}; +use serde_json::json; + +use crate::Session; + +fn tests(albums: &[(&str, u64)]) -> Filter { + let rules: Vec<_> = albums.iter().map(|(op, a)| json!({"field": "album", "op": op, "value": a})).collect(); + serde_json::from_value(json!({"ruleSet": {"match": "all", "rules": rules}})).unwrap() +} + +fn smart(s: &mut Session, name: &str, rules: serde_json::Value) -> u64 { + s.execute("album.createSmart", &json!({"name": name, "rules": rules})).unwrap()["id"].as_u64().unwrap() +} + +fn set(id: u64, rules: Filter) -> Op { + Op::SetAlbumRules { id: AlbumId(id), rules: Box::new(rules) } +} + +#[test] +fn an_edit_no_command_checked_cant_make_a_loop() { + let mut s = Session::new(); + let a = smart(&mut s, "A", json!({"rating": 1})); + let b = smart(&mut s, "B", json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": a}]}})); + let (x, y) = (smart(&mut s, "X", json!({"rating": 2})), smart(&mut s, "Y", json!({"rating": 3}))); + let gone = smart(&mut s, "Gone", json!({"rating": 4})); + let waits = smart(&mut s, "Waits", json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": gone}]}})); + s.execute("album.delete", &json!({"id": gone})).unwrap(); + let (steps, logged, snapshot) = (s.undo.len(), s.pending_log.len(), s.catalog.to_snapshot()); + let back = Album { smart: Some(Box::new(tests(&[("is", waits)]))), ..Album::new(AlbumId(gone), "Back") }; + for (what, op) in [ + ("rules that test an album that tests it", set(a, tests(&[("is", b)]))), + ("two edits, each fine alone", Op::Batch { ops: vec![set(x, tests(&[("is", y)])), set(y, tests(&[("is", x)]))] }), + ("a new album that takes the id of one a rule tests", Op::AddAlbum { album: back }), + ] { + let e = s.commit("Edit", op).unwrap_err().to_string(); + assert!(e.contains("include itself"), "{what}: {e}"); + assert_eq!((s.undo.len(), s.pending_log.len()), (steps, logged), "{what}: nothing to undo, nothing journaled"); + assert_eq!(s.catalog.to_snapshot(), snapshot, "{what}: nothing changed"); + } +} + +#[test] +fn commands_refuse_every_way_to_a_loop_and_ordinary_edits_go_on() { + let mut s = Session::with_demo(); + let a = smart(&mut s, "A", json!({"rating": 1})); + let b = smart(&mut s, "B", json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": a}]}})); + let steps = s.undo.len(); + let looping = |s: &mut Session, params: serde_json::Value| { + let e = s.execute("album.setRules", ¶ms).unwrap_err().to_string(); + assert!(e.contains("include itself"), "{e}"); + }; + looping(&mut s, json!({"id": a, "rules": {"ruleSet": {"rules": [{"field": "album", "op": "is", "value": b}]}}})); + looping(&mut s, json!({"id": a, "name": "Renamed too", "rules": {"ruleSet": {"rules": [{"field": "album", "op": "is", "value": a}]}}})); + assert_eq!((s.undo.len(), s.catalog.album(AlbumId(a)).map(|x| x.name.clone())), (steps, Some("A".into()))); + // ordinary edits: a rename together with new rules is one undo step + s.execute("album.setRules", &json!({"id": b, "name": "B2", "rules": {"rating": 2}})).unwrap(); + s.execute("album.rename", &json!({"id": a, "name": "A2"})).unwrap(); + assert_eq!(s.undo.len(), steps + 2); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.album(AlbumId(b)).map(|x| x.name.clone()), Some("B".into())); +} + +#[test] +fn a_library_that_holds_a_loop_goes_on_and_undo_and_redo_cross_it() { + let mut s = Session::with_demo(); + let a = smart(&mut s, "A", json!({"rating": 1})); + let b = smart(&mut s, "B", json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": a}]}})); + // as a version without the rule saved it + s.catalog.apply(set(a, tests(&[("is", b)]))).unwrap(); + let on_a_loop = |s: &Session| { + [a, b] + .into_iter() + .filter(|id| s.catalog.smart_album_problems(AlbumId(*id)).iter().any(|p| p.issue == lightcraft_catalog::rules::Issue::AlbumLoop)) + .count() + }; + assert_eq!(on_a_loop(&s), 2); + // edits that add no loop: a rename, a change that leaves the rule as it is, a new album + s.execute("album.rename", &json!({"id": a, "name": "Still looping"})).unwrap(); + s.execute("album.setRules", &json!({"id": a, "rules": {"rating": 3}})).unwrap(); + smart(&mut s, "Reads the loop", json!({"ruleSet": {"rules": [{"field": "album", "op": "is", "value": a}]}})); + // mending it is one step; undo brings back what was and is not refused; redo mends again + s.execute("album.setRules", &json!({"id": b, "replace": true, "rules": {"rating": 2}})).unwrap(); + assert_eq!(on_a_loop(&s), 0); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(on_a_loop(&s), 2, "undo is no new edit"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(on_a_loop(&s), 0); +} diff --git a/crates/engine/src/tests/album_missing.rs b/crates/engine/src/tests/album_missing.rs new file mode 100644 index 0000000000..451f7a4074 --- /dev/null +++ b/crates/engine/src/tests/album_missing.rs @@ -0,0 +1,167 @@ +//! Album commands only take photos the catalog has, and a call that changes nothing records +//! nothing. +//! +//! Scenarios: +//! - Given ids the catalog doesn't have (named outright, or still selected after an undo took the +//! photos away), when they are added to an album, toggled into the target album, or used for a +//! new album, then they reach no album. +//! - Given nothing is left to add, or every photo is in the album already, then there is no undo +//! step and redo is left alone. +//! - Given a normal add or toggle, then one step is recorded and one undo restores the album. + +use lightcraft_catalog::{AlbumId, PhotoId}; +use serde_json::json; + +use crate::{Selection, Session}; + +const GONE: PhotoId = PhotoId(987_654); + +fn album(s: &mut Session, name: &str) -> AlbumId { + AlbumId(s.execute("album.create", &json!({"name": name})).unwrap()["id"].as_u64().unwrap()) +} + +/// A demo session, an album, and a redo entry waiting (a rating set, then undone). +fn with_redo() -> (Session, AlbumId, PhotoId) { + let mut s = Session::with_demo(); + let photo = s.catalog.photos().next().unwrap().id; + let a = album(&mut s, "Trip"); + s.execute("photo.rate", &json!({"ids": [photo.0], "rating": 4})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.redo.len(), 1); + (s, a, photo) +} + +#[test] +fn photos_the_catalog_lacks_reach_no_album() { + let (mut s, a, photo) = with_redo(); + let (undo, redo) = (s.undo.len(), s.redo.len()); + let r = s.execute("album.addPhotos", &json!({"id": a.0, "ids": [GONE.0]})).unwrap(); + assert_eq!((r["added"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(0)), "{r}"); + assert!(s.catalog.album(a).unwrap().photos.is_empty()); + assert_eq!((s.undo.len(), s.redo.len()), (undo, redo), "no step, redo kept"); + + // a mix: the one that is there goes in, the other doesn't + let r = s.execute("album.addPhotos", &json!({"id": a.0, "ids": [GONE.0, photo.0]})).unwrap(); + assert_eq!(r["added"], 1, "{r}"); + assert_eq!(s.catalog.album(a).unwrap().photos, vec![photo]); + assert_eq!(s.undo.len(), undo + 1); + assert_eq!(s.redo.len(), 0, "a real change clears redo"); + + // toggling: nothing is made or changed for ids that are gone + let r = s.execute("album.toggleTarget", &json!({"ids": [GONE.0]})).unwrap(); + assert!(r["added"].is_null() && r["toggled"] == 0, "{r}"); + assert!(s.catalog.quick_collection().is_none(), "no Quick Collection for nothing"); + assert_eq!(s.undo.len(), undo + 1); + + // a new album from a selection that is gone starts empty + s.selection = Selection::single(GONE); + let r = s.execute("album.create", &json!({"name": "New", "addSelected": true})).unwrap(); + let new = s.catalog.album(AlbumId(r["id"].as_u64().unwrap())).unwrap(); + assert!(new.photos.is_empty() && new.cover.is_none(), "{r}"); +} + +/// Leaves one redo entry waiting: a rating set, then undone. +fn leave_redo(s: &mut Session, photo: PhotoId) { + s.execute("photo.rate", &json!({"ids": [photo.0], "rating": 4})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.redo.len(), 1); +} + +#[test] +fn toggling_gone_photos_leaves_the_target_album_and_redo_alone() { + let mut s = Session::with_demo(); + let photo = s.catalog.photos().next().unwrap().id; + let a = album(&mut s, "Trip"); + s.execute("album.setTarget", &json!({"id": a.0})).unwrap(); + s.execute("album.toggleTarget", &json!({"ids": [photo.0]})).unwrap(); + leave_redo(&mut s, photo); + let undo = s.undo.len(); + let r = s.execute("album.toggleTarget", &json!({"ids": [GONE.0]})).unwrap(); + assert_eq!(r["album"].as_u64(), Some(a.0), "{r}"); + assert!(r["added"].is_null() && r["toggled"] == 0, "{r}"); + assert_eq!(s.catalog.album(a).unwrap().photos, vec![photo]); + assert_eq!((s.undo.len(), s.redo.len()), (undo, 1)); +} + +#[test] +fn adding_photos_that_are_all_there_already_records_nothing() { + let mut s = Session::with_demo(); + let photo = s.catalog.photos().next().unwrap().id; + let a = album(&mut s, "Trip"); + s.execute("album.addPhotos", &json!({"id": a.0, "ids": [photo.0]})).unwrap(); + leave_redo(&mut s, photo); + let undo = s.undo.len(); + let r = s.execute("album.addPhotos", &json!({"id": a.0, "ids": [photo.0]})).unwrap(); + assert_eq!(r["added"], 0, "{r}"); + assert_eq!((s.undo.len(), s.redo.len()), (undo, 1), "no step, redo kept"); +} + +#[test] +fn a_normal_add_or_toggle_is_one_step_and_one_undo_restores_it() { + let (mut s, a, photo) = with_redo(); + let undo = s.undo.len(); + s.execute("album.addPhotos", &json!({"id": a.0, "ids": [photo.0]})).unwrap(); + assert_eq!(s.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.album(a).unwrap().photos.is_empty()); + + s.execute("album.setTarget", &json!({"id": a.0})).unwrap(); + let undo = s.undo.len(); + let r = s.execute("album.toggleTarget", &json!({"ids": [GONE.0, photo.0]})).unwrap(); + assert_eq!((r["added"].as_bool(), r["toggled"].as_u64(), s.undo.len()), (Some(true), Some(1), undo + 1), "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.album(a).unwrap().photos.is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + // toggled off: also one step, one undo puts the photo back + let undo = s.undo.len(); + let r = s.execute("album.toggleTarget", &json!({"ids": [photo.0]})).unwrap(); + assert_eq!((r["added"].as_bool(), r["toggled"].as_u64(), s.undo.len()), (Some(false), Some(1), undo + 1), "{r}"); + assert!(s.catalog.album(a).unwrap().photos.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.album(a).unwrap().photos, vec![photo]); +} + +#[test] +fn a_toggle_counts_only_the_photos_it_added() { + let mut s = Session::with_demo(); + let ids: Vec = s.catalog.photos().take(3).map(|p| p.id).collect(); + let a = album(&mut s, "Trip"); + s.execute("album.setTarget", &json!({"id": a.0})).unwrap(); + s.execute("album.addPhotos", &json!({"id": a.0, "ids": [ids[0].0, ids[1].0]})).unwrap(); + let all: Vec = ids.iter().map(|p| p.0).collect(); + let r = s.execute("album.toggleTarget", &json!({"ids": all})).unwrap(); + assert_eq!((r["added"].as_bool(), r["toggled"].as_u64()), (Some(true), Some(1)), "two were in already: {r}"); + assert_eq!(s.catalog.album(a).unwrap().photos.len(), 3); +} + +#[test] +fn photos_named_outright_reach_the_album_commands_with_nothing_selected() { + let mut s = Session::with_demo(); + let photo = s.catalog.photos().next().unwrap().id; + let a = album(&mut s, "Trip"); + s.execute("album.setTarget", &json!({"id": a.0})).unwrap(); + s.selection = Selection::default(); + + // ids the library lacks: the no-op result, not a refusal + let r = s.execute("album.addPhotos", &json!({"id": a.0, "ids": [GONE.0]})).unwrap(); + assert_eq!((r["added"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(0)), "{r}"); + let r = s.execute("album.toggleTarget", &json!({"ids": [GONE.0]})).unwrap(); + assert!(r["added"].is_null(), "{r}"); + + // ids the library has: they go in + let r = s.execute("album.addPhotos", &json!({"id": a.0, "ids": [photo.0]})).unwrap(); + assert_eq!(r["added"], 1, "{r}"); + let r = s.execute("album.toggleTarget", &json!({"ids": [photo.0]})).unwrap(); + assert_eq!((r["added"].as_bool(), r["toggled"].as_u64()), (Some(false), Some(1)), "{r}"); +} + +#[test] +fn the_album_an_add_names_is_not_a_photo_that_skips_the_selection_check() { + let mut s = Session::with_demo(); + let a = album(&mut s, "Trip"); + s.selection = Selection::default(); + // no `ids`: the selection is what is added, and it is empty + assert!(matches!(s.execute("album.addPhotos", &json!({"id": a.0})), Err(crate::EngineError::Disabled(..)))); + assert!(matches!(s.execute("album.addPhotos", &json!({"id": a.0, "ids": null})), Err(crate::EngineError::Disabled(..)))); + assert!(matches!(s.execute("album.toggleTarget", &json!({})), Err(crate::EngineError::Disabled(..)))); +} diff --git a/crates/engine/src/tests/color.rs b/crates/engine/src/tests/color.rs index e526d4c47b..4805c70ece 100644 --- a/crates/engine/src/tests/color.rs +++ b/crates/engine/src/tests/color.rs @@ -75,6 +75,12 @@ fn red_eye_commands_and_controls() { assert_eq!(active_dev(&s).red_eye.len(), 1); assert!(s.execute("redeye.delete", &json!({"index": 5})).is_err()); assert!(s.execute("redeye.add", &json!({"rx": 0.03})).is_err()); + // at most MAX_RED_EYES: every pixel goes through every eye (issue #2556) + while active_dev(&s).red_eye.len() < lightcraft_develop::MAX_RED_EYES { + s.execute("redeye.add", &json!({"center": [0.5, 0.5], "rx": 0.01, "ry": 0.01})).unwrap(); + } + assert!(s.execute("redeye.add", &json!({"center": [0.5, 0.5], "rx": 0.01, "ry": 0.01})).is_err()); + assert_eq!(active_dev(&s).red_eye.len(), lightcraft_develop::MAX_RED_EYES); let d = active_dev(&s); assert_eq!(lightcraft_develop::DevelopSettings::from_json(&d.to_json()).unwrap(), d); } @@ -220,3 +226,247 @@ fn white_balance_commands_write_kelvin_on_raws_whose_camera_has_matrices() { fn lightcraft_engine_effective(info: &lightcraft_pipeline::SourceInfo, d: &lightcraft_develop::DevelopSettings) -> (f64, f64) { lightcraft_pipeline::local::effective_wb(info, d) } + +/// Issue #2910: a `develop.merge` white-balance partial that names only `temp` or only `tint` is resolved against +/// the photo, so the field the partial does not name keeps the look it had instead of being re-read on the +/// partial's scale. The partial's own number keeps the meaning an unmentioned scale always had (relative), and a +/// partial that says `scale: "kelvin"` is read in Kelvin. +#[test] +fn one_field_wb_partial_merge_keeps_the_other_field_on_its_scale() { + use lightcraft_catalog::{MediaKind, Op, Photo, Source}; + use lightcraft_develop::{DevelopSettings, WbMode, WbScale}; + let mut s = Session::new(); + let add = |s: &mut Session, name: &str, camera: &str, as_shot: (f64, f64)| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/photos/{name}") }, name, "ARW", 64, 64, "2026-01-01T00:00:00"); + p.kind = MediaKind::Raw; + p.meta.camera = camera.into(); + p.as_shot_wb = Some(as_shot); + p.develop = std::sync::Arc::new(p.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let as_shot = (4986.0, -2.0); + let kelvin = add(&mut s, "a.arw", "SONY ILCE-7M3", as_shot); + let relative = add(&mut s, "b.arw", "SONY ILCE-200", (6500.0, 0.0)); + let dev = |s: &Session, id| (*s.develop_of(id).unwrap()).clone(); + let l2k = |t, ti| lightcraft_pipeline::local::legacy_to_kelvin(t, ti, as_shot); + let k2l = |t, ti| lightcraft_pipeline::local::kelvin_to_legacy(t, ti, as_shot).unwrap(); + // two whites this close in (u, v) read as the same colour change; the bug's re-read of one kept field moves + // the white by ~8e-4 here, so a same-white check with this tolerance catches it + let close = |a: (f64, f64), b: (f64, f64)| { + let (au, av) = lightcraft_color::cct::xy_to_uv(lightcraft_color::cct::temp_tint_to_xy(a.0, a.1)); + let (bu, bv) = lightcraft_color::cct::xy_to_uv(lightcraft_color::cct::temp_tint_to_xy(b.0, b.1)); + (au - bu).hypot(av - bv) < 2e-4 + }; + // a stored white balance equal to an expected conversion, forgiving the last bits of the two code paths and + // the round-trip of the scale conversions; the bug moved the tint by 2+ units, far outside this + let nearly = |wb: &lightcraft_develop::WhiteBalance, want: &(f64, f64), why: &str| { + assert!((wb.temp - want.0).abs() < 1.0 && (wb.tint - want.1).abs() < 0.5, "{why}: {wb:?} vs {want:?}"); + }; + s.execute("library.select", &json!({"ids": [kelvin.0], "active": kelvin.0})).unwrap(); + + // a temp-only partial on a photo edited in Kelvin: the tint keeps its Kelvin look (the bug re-read it as a + // relative shift and moved the green/magenta balance although the partial never touched tint) + let edited = DevelopSettings { + wb: lightcraft_develop::WhiteBalance { mode: WbMode::Custom, temp: 5000.0, tint: 12.0, scale: WbScale::Kelvin }, + ..DevelopSettings::for_raw(as_shot.0, as_shot.1) + }; + s.set_develop(kelvin, edited.clone(), "kelvin edit").unwrap(); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0}}})).unwrap(); + let d = dev(&s, kelvin); + let keep = k2l(5000.0, 12.0); + assert_eq!(d.wb.scale, WbScale::Kelvin, "the photo goes back on the scale it is edited on: {:?}", d.wb); + nearly(&d.wb, &l2k(5800.0, keep.1), "the partial's number keeps the meaning an unmarked scale always had"); + // restating the photo's own temperature (the value it carries on the scale an unmarked partial means) leaves + // its white exactly where it was: on main the kept tint was re-read as a relative shift, drifting the white + s.set_develop(kelvin, edited.clone(), "kelvin edit").unwrap(); + let look = lightcraft_engine_effective(&s.source_info(kelvin), &edited); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": keep.0}}})).unwrap(); + let again = lightcraft_engine_effective(&s.source_info(kelvin), &dev(&s, kelvin)); + assert!(close(look, again), "a restated one-field partial leaves the white alone: {look:?} -> {again:?}"); + // and the reverse: a tint-only partial keeps the temperature's look + s.execute("develop.merge", &json!({"settings": {"wb": {"tint": -20.0}}})).unwrap(); + let d = dev(&s, kelvin); + nearly(&d.wb, &l2k(keep.0, -20.0), "a tint-only partial keeps the temperature's look"); + // a partial that names its scale is read on it: the same temperature asked for in Kelvin, kept tint unharmed + s.set_develop(kelvin, edited.clone(), "kelvin edit").unwrap(); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.mode, d.wb.temp, d.wb.tint, d.wb.scale), (WbMode::Custom, 5800.0, 12.0, WbScale::Kelvin), "{:?}", d.wb); + + // from As Shot as well: the as-shot tint keeps its meaning (the bug read it as a relative shift from as shot) + s.execute("develop.merge", &json!({"settings": {"wb": {"mode": "asShot"}}})).unwrap(); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0}}})).unwrap(); + let d = dev(&s, kelvin); + nearly(&d.wb, &l2k(5800.0, 0.0), "the as-shot tint keeps its meaning"); + assert_eq!(d.wb.scale, WbScale::Kelvin); + + // A mode that answers its own white (As Shot, or a named preset on a raw edited in Kelvin) ignores the numbers + // stored on the photo, so a one-field partial naming its scale landed on a white balance that stored the number + // where no render would read it: the panel showed 5800 while the photo stayed at as shot. The white the photo + // really renders is written out as Custom values first, so the named number means what it says and the field the + // partial leaves out carries that same white (review of #2952). + let as_shot_photo = DevelopSettings { + wb: lightcraft_develop::WhiteBalance { mode: WbMode::AsShot, temp: 4986.0, tint: -2.0, scale: WbScale::Kelvin }, + ..DevelopSettings::for_raw(as_shot.0, as_shot.1) + }; + s.set_develop(kelvin, as_shot_photo.clone(), "as shot").unwrap(); + assert_eq!(lightcraft_engine_effective(&s.source_info(kelvin), &as_shot_photo), as_shot, "as shot renders the file's own white"); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.mode, d.wb.temp, d.wb.tint, d.wb.scale), (WbMode::Custom, 5800.0, -2.0, WbScale::Kelvin), "{:?}", d.wb); + assert_eq!(lightcraft_engine_effective(&s.source_info(kelvin), &d), (5800.0, -2.0), "the temperature the partial asked for renders"); + // the tint side of the same hole + s.set_develop(kelvin, as_shot_photo.clone(), "as shot").unwrap(); + s.execute("develop.merge", &json!({"settings": {"wb": {"tint": 20.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.mode, d.wb.temp, d.wb.tint, d.wb.scale), (WbMode::Custom, as_shot.0, 20.0, WbScale::Kelvin), "{:?}", d.wb); + assert_eq!(lightcraft_engine_effective(&s.source_info(kelvin), &d), (as_shot.0, 20.0)); + // a named preset mode answers its own Kelvin white on such a raw, so its numbers are swallowed the same way + let preset_photo = DevelopSettings { + wb: lightcraft_develop::WhiteBalance { mode: WbMode::Cloudy, temp: 4986.0, tint: -2.0, scale: WbScale::Kelvin }, + ..DevelopSettings::for_raw(as_shot.0, as_shot.1) + }; + s.set_develop(kelvin, preset_photo.clone(), "cloudy").unwrap(); + let cloudy = lightcraft_engine_effective(&s.source_info(kelvin), &preset_photo); + assert_ne!(cloudy, (4986.0, -2.0), "the preset mode renders its own white, not the stored numbers"); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.mode, d.wb.temp, d.wb.tint, d.wb.scale), (WbMode::Custom, 5800.0, cloudy.1, WbScale::Kelvin), "{:?}", d.wb); + assert_eq!(lightcraft_engine_effective(&s.source_info(kelvin), &d), (5800.0, cloudy.1), "the kept tint is that white's own tint"); + // `Auto` resolves its gray when the mode is set and reads its stored numbers back: its mode stays, nothing frozen + let auto_photo = DevelopSettings { + wb: lightcraft_develop::WhiteBalance { mode: WbMode::Auto, temp: 5100.0, tint: 3.0, scale: WbScale::Kelvin }, + ..DevelopSettings::for_raw(as_shot.0, as_shot.1) + }; + s.set_develop(kelvin, auto_photo, "auto").unwrap(); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.mode, d.wb.temp, d.wb.tint), (WbMode::Auto, 5800.0, 3.0), "{:?}", d.wb); + // a partial that names a mode stays authoritative: naming `asShot` puts the photo back on the file's white + s.set_develop(kelvin, as_shot_photo.clone(), "as shot").unwrap(); + s.execute("develop.merge", &json!({"settings": {"wb": {"mode": "asShot", "temp": 5800.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.mode, lightcraft_engine_effective(&s.source_info(kelvin), &d)), (WbMode::AsShot, as_shot), "{:?}", d.wb); + // the same swallow on a source without the Kelvin scale (a raw with no matrices): the number was stored and read + // by nothing there too, and now reaches the render + s.execute("library.select", &json!({"ids": [relative.0], "active": relative.0})).unwrap(); + let before = dev(&s, relative); + assert_eq!(lightcraft_engine_effective(&s.source_info(relative), &before), (6500.0, 0.0), "as shot on this body is 6500 / 0"); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0}}})).unwrap(); + let d = dev(&s, relative); + assert_eq!((d.wb.mode, d.wb.temp, d.wb.tint, d.wb.scale), (WbMode::Custom, 5800.0, 0.0, WbScale::Legacy), "{:?}", d.wb); + assert_eq!(lightcraft_engine_effective(&s.source_info(relative), &d), (5800.0, 0.0), "the number the partial named renders"); + s.execute("library.select", &json!({"ids": [kelvin.0], "active": kelvin.0})).unwrap(); + + // the other direction: an old relative Custom value (no scale) plus a Kelvin temp-only partial — the photo's + // white balance is taken onto the Kelvin scale first, so the kept tint is the Kelvin value of the photo's look + let old = DevelopSettings { + wb: lightcraft_develop::WhiteBalance { mode: WbMode::Custom, temp: 5800.0, tint: 20.0, scale: WbScale::Legacy }, + ..DevelopSettings::for_raw(6500.0, 0.0) + }; + s.set_develop(kelvin, old.clone(), "old relative").unwrap(); + let keep = l2k(5800.0, 20.0); + assert!(!close((5800.0, 20.0), (keep.0, keep.1)), "the two readings really differ on this camera, so the next check can catch the bug"); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.mode, d.wb.scale), (WbMode::Custom, WbScale::Kelvin), "{:?}", d.wb); + nearly(&d.wb, &(5800.0, keep.1), "the kept tint is the old relative tint carried onto the Kelvin scale"); + + // a partial naming both fields, or neither, behaves exactly as before + s.execute("develop.merge", &json!({"settings": {"wb": {"mode": "custom", "temp": 6500.0, "tint": 0.0}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!(d.wb.scale, WbScale::Legacy, "a partial without a scale keeps the relative meaning"); + assert_eq!(lightcraft_engine_effective(&s.source_info(kelvin), &d), (as_shot.0, as_shot.1), "6500 / 0 without a scale is as shot"); + // the whole white balance arrives on the photo's scale when the partial says both fields and the scale + s.execute("develop.merge", &json!({"settings": {"wb": {"mode": "custom", "temp": 5200.0, "tint": 7.0, "scale": "kelvin"}}})).unwrap(); + let d = dev(&s, kelvin); + assert_eq!((d.wb.temp, d.wb.tint, d.wb.scale), (5200.0, 7.0, WbScale::Kelvin), "{:?}", d.wb); + // a one-field partial on a photo edited on the relative scale (no Kelvin scale there): unchanged behaviour, stays relative + s.execute("library.select", &json!({"ids": [relative.0], "active": relative.0})).unwrap(); + let before = dev(&s, relative); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0}}})).unwrap(); + let d = dev(&s, relative); + assert_eq!((d.wb.temp, d.wb.tint, d.wb.scale), (5800.0, before.wb.tint, WbScale::Legacy), "{:?}", d.wb); + // a non-white-balance partial merges through the same path unchanged + let wb_before = dev(&s, relative).wb; + s.execute("develop.merge", &json!({"settings": {"light": {"contrast": 20}}})).unwrap(); + let d = dev(&s, relative); + assert_eq!(d.light.contrast, 20.0); + assert_eq!(d.wb, wb_before, "the white balance is untouched"); +} + +/// The issue asks for one photo-aware merge in every caller that writes settings onto a photo, and that includes +/// `preset.apply`: a preset a person or an agent authors by hand can name a single white balance number, and on a +/// photo edited in Kelvin that demoted the field it never mentioned to the relative scale, exactly as +/// `develop.merge` did. Presets the app makes and the crs / Luminar importers name `mode`, `temp`, `tint` and +/// `scale` together, and those keep their old path through `Preset::apply` → `apply_partial` unchanged. +#[test] +fn one_field_wb_preset_apply_keeps_the_other_field_on_its_scale() { + use lightcraft_catalog::{MediaKind, Op, Photo, Source}; + use lightcraft_develop::{DevelopSettings, WbMode, WbScale}; + let mut s = Session::new(); + let add = |s: &mut Session, name: &str, camera: &str, as_shot: (f64, f64)| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/photos/{name}") }, name, "ARW", 64, 64, "2026-01-01T00:00:00"); + p.kind = MediaKind::Raw; + p.meta.camera = camera.into(); + p.as_shot_wb = Some(as_shot); + p.develop = std::sync::Arc::new(p.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let as_shot = (4986.0, -2.0); + let kelvin = add(&mut s, "preset-wb.arw", "SONY ILCE-7M3", as_shot); + let l2k = |t, ti| lightcraft_pipeline::local::legacy_to_kelvin(t, ti, as_shot); + let k2l = |t, ti| lightcraft_pipeline::local::kelvin_to_legacy(t, ti, as_shot).unwrap(); + let nearly = |wb: &lightcraft_develop::WhiteBalance, want: &(f64, f64), why: &str| { + assert!((wb.temp - want.0).abs() < 1.0 && (wb.tint - want.1).abs() < 0.5, "{why}: {wb:?} vs {want:?}"); + }; + s.execute("library.select", &json!({"ids": [kelvin.0], "active": kelvin.0})).unwrap(); + let edited = DevelopSettings { + wb: lightcraft_develop::WhiteBalance { mode: WbMode::Custom, temp: 5000.0, tint: 12.0, scale: WbScale::Kelvin }, + ..DevelopSettings::for_raw(as_shot.0, as_shot.1) + }; + s.set_develop(kelvin, edited.clone(), "kelvin edit").unwrap(); + + // a hand-written preset naming one number: the tint it never mentions keeps its Kelvin look, instead of the + // old path that stored 5800 and re-read the photo's +12 tint as a relative shift + s.presets.push(lightcraft_develop::Preset { + id: "user.temp-only".into(), + name: "Temp only".into(), + group: "User".into(), + settings: json!({"wb": {"temp": 5800.0}}), + favorite: false, + builtin: false, + }); + s.execute("preset.apply", &json!({"id": "user.temp-only"})).unwrap(); + let d = (*s.develop_of(kelvin).unwrap()).clone(); + let keep = k2l(5000.0, 12.0); + assert_eq!(d.wb.mode, WbMode::Custom, "{:?}", d.wb); + assert_eq!(d.wb.scale, WbScale::Kelvin, "the preset left the photo on the scale it is edited on: {:?}", d.wb); + nearly(&d.wb, &l2k(5800.0, keep.1), "the preset's number keeps the meaning an unmarked scale always had"); + // an amount below 100 % blends between the photo's own white and the preset's, on one scale, and never + // mentions the other field at all + s.set_develop(kelvin, edited.clone(), "kelvin edit").unwrap(); + s.execute("preset.apply", &json!({"id": "user.temp-only", "amount": 50})).unwrap(); + let half = (*s.develop_of(kelvin).unwrap()).clone(); + let full = l2k(5800.0, keep.1); + assert_eq!(half.wb.scale, WbScale::Kelvin, "{:?}", half.wb); + assert!(half.wb.temp < 5000.0 && half.wb.temp > full.0, "between the photo's own white and the preset's: {:?}", half.wb); + nearly(&half.wb, &(half.wb.temp, 12.0), "the tint the preset never named stays exactly the photo's"); + // the same number through `develop.merge` gives the same white: that is the point of one shared merge + s.set_develop(kelvin, edited.clone(), "kelvin edit").unwrap(); + s.execute("develop.merge", &json!({"settings": {"wb": {"temp": 5800.0}}})).unwrap(); + let merged = (*s.develop_of(kelvin).unwrap()).clone(); + nearly(&merged.wb, &(d.wb.temp, d.wb.tint), "preset apply and develop.merge agree on a one-field white balance"); + // a preset made from the photo names the whole white balance: its own path, unchanged + s.execute("preset.create", &json!({"name": "My kelvin look", "groups": ["whiteBalance"]})).unwrap(); + let made = s.presets.iter().find(|p| p.name == "My kelvin look").cloned().unwrap(); + let look = (*s.develop_of(kelvin).unwrap()).clone(); + s.execute("develop.merge", &json!({"settings": {"wb": {"mode": "asShot"}}})).unwrap(); + s.execute("preset.apply", &json!({"id": made.id})).unwrap(); + let back = (*s.develop_of(kelvin).unwrap()).clone(); + assert_eq!(back.wb, look.wb, "a preset made from the photo puts its whole white balance back: {:?} vs {:?}", back.wb, look.wb); +} diff --git a/crates/engine/src/tests/export.rs b/crates/engine/src/tests/export.rs index d0f1742451..27268e463a 100644 --- a/crates/engine/src/tests/export.rs +++ b/crates/engine/src/tests/export.rs @@ -6,6 +6,14 @@ use crate::Session; use crate::export::{ExportFormat, ExportOptions, export_photo}; use crate::tests_xmp::{synthetic_dng_with, synthetic_psd_with_metadata, temp_dir}; +fn jpeg_with_xmp(metadata: &lightcraft_meta::Metadata) -> Vec { + let pixels = [96u8; 12]; + let image = lightcraft_codecs::EncodeImage::new(2, 2, 3, lightcraft_codecs::Samples::U8(&pixels)); + let xmp = lightcraft_meta::write_xmp(metadata, None); + let encoded = lightcraft_codecs::EncodeMeta { xmp: Some(&xmp), ..Default::default() }; + lightcraft_codecs::encode_jpeg(&image, 90, lightcraft_codecs::ChromaSubsampling::S444, &encoded).unwrap() +} + #[test] fn full_size_export_of_a_cropped_photo_is_not_upscaled() { let mut s = Session::with_demo(); @@ -313,6 +321,26 @@ fn curve_preset_export_never_overwrites_originals_or_sidecars() { preset_export_preserves_originals("curve.exportPresets", json!({"names": ["Linear"]}), "curve-export-guard"); } +/// A new file named like a photo's sidecar, in the photo's folder, would be read back as that +/// photo's edits: refused even though nothing is there yet. +#[test] +fn preset_export_never_creates_a_photos_sidecar() { + let (mut s, _, dir, _, _) = library_with_jpeg("preset-export-new-sidecar"); + std::fs::create_dir_all(dir.join("presets")).unwrap(); + for name in ["IMG_1.xmp", "IMG_1.jpg.xmp", "presets/../IMG_1.xmp"] { + let path = dir.join(name); + assert!(!path.exists(), "{name} isn't there before the export"); + let error = s.execute("preset.export", &json!({"ids": ["lc.warm-glow"], "path": path.to_string_lossy()})).unwrap_err().to_string(); + assert!(error.contains("XMP sidecar of IMG_1.jpg"), "{error}"); + assert!(!path.exists(), "{name} was not created"); + } + // the same name in another folder is an ordinary preset file + let elsewhere = dir.join("presets/IMG_1.xmp"); + s.execute("preset.export", &json!({"ids": ["lc.warm-glow"], "path": elsewhere.to_string_lossy()})).unwrap(); + assert!(elsewhere.exists()); + let _ = std::fs::remove_dir_all(dir); +} + /// #1944: Export Keywords went straight to `std::fs::write`, replacing a library original. #[test] fn keyword_export_never_overwrites_originals_or_sidecars() { @@ -640,6 +668,168 @@ fn remove_location_holds_for_original_and_dng_exports() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn remove_location_refuses_original_with_embedded_place_names() { + let dir = temp_dir("export-noloc-place-fields"); + let value = "Embedded Place"; + let cases = [ + ("sublocation", lightcraft_meta::Metadata { sublocation: Some(value.into()), ..Default::default() }), + ("city", lightcraft_meta::Metadata { city: Some(value.into()), ..Default::default() }), + ("state", lightcraft_meta::Metadata { state: Some(value.into()), ..Default::default() }), + ("country", lightcraft_meta::Metadata { country: Some(value.into()), ..Default::default() }), + ]; + let mut paths = Vec::new(); + for (name, metadata) in &cases { + let path = dir.join(format!("{name}.jpg")); + std::fs::write(&path, jpeg_with_xmp(metadata)).unwrap(); + paths.push(path.to_string_lossy().to_string()); + } + + let mut session = Session::new().with_fs(); + session.execute("library.import", &json!({"paths": paths})).unwrap(); + let options = ExportOptions { format: ExportFormat::Original, remove_location: true, ..Default::default() }; + for (name, _) in cases { + let photo_id = session.catalog.photos().find(|p| p.file_name == format!("{name}.jpg")).unwrap().id; + let original = std::fs::read(dir.join(format!("{name}.jpg"))).unwrap(); + let embedded = lightcraft_meta::try_extract(&original).unwrap(); + assert!(embedded.gps.is_none(), "{name} fixture should isolate place names"); + let place_name = match name { + "sublocation" => embedded.sublocation.as_deref(), + "city" => embedded.city.as_deref(), + "state" => embedded.state.as_deref(), + "country" => embedded.country.as_deref(), + _ => None, + }; + assert_eq!(place_name, Some(value), "{name} fixture should be parsed"); + let error = export_photo(&mut session, photo_id, &options, 1).err().expect("embedded place name should refuse Original export"); + assert!(error.contains("place names") && error.contains("export as JPEG or TIFF"), "{name}: {error}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn remove_location_refuses_original_with_unreadable_non_psd_xmp() { + let dir = temp_dir("export-noloc-malformed-xmp"); + let path = dir.join("Unreadable.jpg"); + let pixels = [96u8; 12]; + let image = lightcraft_codecs::EncodeImage::new(2, 2, 3, lightcraft_codecs::Samples::U8(&pixels)); + let xmp = " Result<(), String> { + writes.push(path.to_string()); + std::fs::write(path, bytes).map_err(|error| error.to_string()) + }; + let exists = |path: &str| std::path::Path::new(path).exists(); + let result = run_batch(items, &options, &destination, &mut write, &exists, true, &mut |_, _| true); + + let error = result.unwrap_err(); + assert!(error.contains("place names"), "{error}"); + assert!(writes.is_empty(), "refused export called the writer: {writes:?}"); + assert!(!output.join("City.jpg").exists()); + assert!(!output.join("City.xmp").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn remove_location_checks_embedded_places_after_catalog_clear() { + let dir = temp_dir("export-noloc-place-catalog-clear"); + let source = dir.join("City.jpg"); + let original = jpeg_with_xmp(&lightcraft_meta::Metadata { city: Some("Embedded Place".into()), ..Default::default() }); + std::fs::write(&source, &original).unwrap(); + + let mut session = Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [source.to_string_lossy()]})).unwrap(); + let id = session.catalog.photos().next().unwrap().id; + assert_eq!(session.catalog.photo(id).unwrap().meta.city, "Embedded Place"); + session.execute("photo.setMeta", &json!({"ids": [id.0], "city": ""})).unwrap(); + assert!(session.catalog.photo(id).unwrap().meta.city.is_empty()); + assert_eq!(lightcraft_meta::try_extract(&std::fs::read(&source).unwrap()).unwrap().city.as_deref(), Some("Embedded Place")); + + let options = ExportOptions { format: ExportFormat::Original, remove_location: true, ..Default::default() }; + let error = export_photo(&mut session, id, &options, 1).err().expect("embedded place name should refuse Original export"); + assert!(error.contains("place names"), "{error}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn remove_location_allows_original_without_embedded_location() { + let dir = temp_dir("export-noloc-place-controls"); + let embedded_path = dir.join("Embedded.jpg"); + let no_location_path = dir.join("NoLocation.jpg"); + let blank_path = dir.join("Blank.jpg"); + let embedded = jpeg_with_xmp(&lightcraft_meta::Metadata { city: Some("Embedded Place".into()), ..Default::default() }); + let no_location = jpeg_with_xmp(&Default::default()); + let blank = jpeg_with_xmp(&lightcraft_meta::Metadata { city: Some(" \t".into()), ..Default::default() }); + std::fs::write(&embedded_path, &embedded).unwrap(); + std::fs::write(&no_location_path, &no_location).unwrap(); + std::fs::write(&blank_path, &blank).unwrap(); + assert!(lightcraft_meta::try_extract(&blank).unwrap().city.is_none(), "whitespace-only XMP place names are blank"); + + let mut session = Session::new().with_fs(); + session + .execute( + "library.import", + &json!({"paths": [embedded_path.to_string_lossy(), no_location_path.to_string_lossy(), blank_path.to_string_lossy()]}), + ) + .unwrap(); + let photo_id = |name: &str| session.catalog.photos().find(|p| p.file_name == name).unwrap().id; + let embedded_id = photo_id("Embedded.jpg"); + let no_location_id = photo_id("NoLocation.jpg"); + let blank_id = photo_id("Blank.jpg"); + + let keep = ExportOptions { format: ExportFormat::Original, ..Default::default() }; + let kept = export_photo(&mut session, embedded_id, &keep, 1).unwrap(); + assert_eq!(kept.bytes, embedded, "removeLocation=false still copies the source byte for byte"); + assert_eq!(lightcraft_meta::try_extract(&kept.bytes).unwrap().city.as_deref(), Some("Embedded Place")); + + let remove = ExportOptions { format: ExportFormat::Original, remove_location: true, ..Default::default() }; + for (id, source) in [(no_location_id, &no_location), (blank_id, &blank)] { + let exported = export_photo(&mut session, id, &remove, 1).unwrap(); + assert_eq!(&exported.bytes, source); + } + + session.execute("photo.setMeta", &json!({"ids": [no_location_id.0], "city": "Catalog-only Place"})).unwrap(); + let catalog_only = export_photo(&mut session, no_location_id, &remove, 1).unwrap(); + let sidecar = catalog_only.sidecars.first().unwrap().1.as_slice(); + let packet = std::str::from_utf8(sidecar).unwrap(); + assert!(lightcraft_meta::parse_xmp(packet).unwrap().metadata.city.is_none(), "catalog-only place name is removed from the sidecar"); + + let _ = std::fs::remove_dir_all(&dir); +} + /// `metadata: "NONE"` as `app.export` sends it: the JPEG carries no location or camera data /// (it used to be read as `all` and carry both). #[test] @@ -1203,3 +1393,39 @@ fn same_folder_as_original_refuses_photos_without_a_folder() { assert!(e.contains("folder is missing") && e.contains(&gone), "{e}"); let _ = std::fs::remove_dir_all(&dir); } + +/// Issue #2882: the demo photo's 16-bit TIFF export (2000 px long edge) with ZIP (the default) is +/// never larger than the same export uncompressed. +#[test] +fn sixteen_bit_zip_tiff_export_is_never_larger_than_uncompressed() { + use crate::export::TiffCompression; + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let size = |s: &mut Session, tiff_compression| { + let o = ExportOptions { + format: ExportFormat::Tiff, + bit_depth: Some(16), + tiff_compression, + ..ExportOptions::from_json(&json!({"longEdge": 2000})) + }; + export_photo(s, id, &o, 1).unwrap().bytes.len() + }; + let none = size(&mut s, TiffCompression::None); + let zip = size(&mut s, TiffCompression::Deflate); + let lzw = size(&mut s, TiffCompression::Lzw); + eprintln!("demo photo, 16-bit TIFF: none {none} B, ZIP {zip} B, LZW {lzw} B"); + assert!(zip <= none, "16-bit ZIP {zip} B is larger than uncompressed {none} B"); +} + +/// An absurd export size is refused, not a multiply overflow (it panicked before the fix). +#[test] +fn huge_export_size_is_an_error() { + use lightcraft_pipeline::{OutputDepth, OutputSpace}; + let mut s = Session::with_demo(); + let id = s.active().unwrap(); + let huge = usize::MAX >> 8; + assert!(s.render_export(id, huge, huge, OutputSpace::Srgb, OutputDepth::U8).is_err()); + assert!(s.render_export(id, 70_000, 10, OutputSpace::Srgb, OutputDepth::U8).is_err()); + assert!(s.render_now(id, huge, huge).is_err()); + assert!(s.render_now(id, 10, 70_000).is_err()); +} diff --git a/crates/engine/src/tests/ids_params.rs b/crates/engine/src/tests/ids_params.rs index 8ce772ded7..021298e905 100644 --- a/crates/engine/src/tests/ids_params.rs +++ b/crates/engine/src/tests/ids_params.rs @@ -66,6 +66,20 @@ fn library_select_refuses_ids_that_are_not_photo_ids() { assert_eq!(s.selection.ids, vec![vis[2]]); } +/// Replacing the selection with a repeated id holds each photo once, in the order first given. +#[test] +fn library_select_replace_drops_repeated_ids() { + let (mut s, vis, _) = session(); + let (a, b) = (vis[0], vis[1]); + s.execute("library.select", &json!({"ids": [a.0, b.0, a.0]})).unwrap(); + assert_eq!(s.selection.ids, vec![a, b]); + assert_eq!(s.selection.active, Some(a)); + let r = s.execute("library.select", &json!({"ids": [b.0, a.0, b.0, b.0], "active": a.0})).unwrap(); + assert_eq!(s.selection.ids, vec![b, a]); + assert_eq!(s.selection.active, Some(a)); + assert_eq!(r["selected"], 2); +} + /// The same for a single `id`: a value that isn't a photo id used to mean the active photo /// (`photo.relink` then relinked the active photo to the file, `photo.removeRegion` removed its face /// box), or, for `denoise.cancel`, every photo. (The stack commands share the helper; `in_stack` diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index dc1c6c8f20..18a9659618 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -13,6 +13,9 @@ use crate::Session; fn temp_dir(tag: &str) -> std::path::PathBuf { let d = std::env::temp_dir().join(format!("lc-import-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); + // Tests that take a folder "offline" rename it to this sibling; a left-over one (from a run + // whose process id is reused) is non-empty and would make that rename fail. + let _ = std::fs::remove_dir_all(d.with_extension("offline")); std::fs::create_dir_all(&d).unwrap(); d } @@ -30,6 +33,34 @@ fn write_png(path: &Path, seed: u8) { std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap(); } +fn exif_clock_block(original: Option<&str>, digitized: Option<&str>) -> Vec { + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + + let mut exif = IfdBuilder::new(); + if let Some(value) = original { + exif.set(0x9003, Value::Ascii(value.into())); + } + if let Some(value) = digitized { + exif.set(0x9004, Value::Ascii(value.into())); + } + let mut ifd0 = IfdBuilder::new(); + ifd0.set_child(0x8769, exif); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() +} + +fn write_png_with_metadata(path: &Path, seed: u8, exif: Option<&[u8]>, xmp: Option<&str>) { + let (w, h) = (48usize, 32usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let metadata = lightcraft_codecs::EncodeMeta { exif, xmp, ..Default::default() }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &metadata).unwrap(); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + // Keep the same known file-date fallback as write_png, distinct from the regression timestamp. + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328); + std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap(); +} + fn ids(v: &Value, key: &str) -> usize { v[key].as_array().map(Vec::len).unwrap_or(0) } @@ -39,7 +70,9 @@ fn recursive_discovery_includes_sony_sr2_and_srf_case_insensitively() { let src = temp_dir("sony-discovery"); std::fs::create_dir_all(src.join("trip/day2")).unwrap(); let names = ["r1.SR2", "f828.srf", "trip/r1.sr2", "trip/f828.SRF", "trip/day2/r1.Sr2", "trip/day2/f828.SrF", "control.JPG"]; - let mut expected: Vec = names.iter().map(|name| src.join(name).to_string_lossy().into_owned()).collect(); + // one component at a time: `join("trip/r1.sr2")` keeps the `/`, discovery yields the platform's separator + let mut expected: Vec = + names.iter().map(|name| name.split('/').fold(src.clone(), |p, c| p.join(c)).to_string_lossy().into_owned()).collect(); for path in &expected { std::fs::write(path, b"discovery only, not a decoded photo").unwrap(); } @@ -128,6 +161,106 @@ fn civil_dates() { assert_eq!(crate::import::civil(1_790_000_000), "2026-09-21T14:13:20"); } +#[test] +fn exif_clock_import_uses_valid_fallback_dates_and_keeps_raw_tags() { + const INVALID: &str = "2026:01:01 12:34:56:99"; + const XMP: &str = r#""#; + let dir = temp_dir("exif-clock-fallbacks"); + let digitized_path = dir.join("digitized.png"); + let digitized_exif = exif_clock_block(Some(INVALID), Some("2026:01:02 10:00:00")); + write_png_with_metadata(&digitized_path, 1, Some(&digitized_exif), None); + let xmp_path = dir.join("xmp.png"); + let malformed_only_exif = exif_clock_block(Some(INVALID), None); + write_png_with_metadata(&xmp_path, 2, Some(&malformed_only_exif), Some(XMP)); + + let mut s = Session::new().with_fs(); + let imported = s.execute("library.import", &json!({"paths": [digitized_path.to_string_lossy(), xmp_path.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&imported, "imported"), 2, "{imported}"); + let digitized = s.catalog.photos().find(|photo| photo.file_name == "digitized.png").unwrap(); + let digitized_id = digitized.id.0; + assert_eq!(digitized.captured.as_deref(), Some("2026-01-02T10:00:00")); + let xmp = s.catalog.photos().find(|photo| photo.file_name == "xmp.png").unwrap(); + let xmp_id = xmp.id.0; + assert_eq!(xmp.captured.as_deref(), Some("2026-01-05T10:00:00+00:00")); + + let all = s.execute("photo.allMetadata", &json!({"id": digitized_id})).unwrap(); + assert!(all["exif"].as_array().unwrap().iter().any(|row| row["tag"] == json!(0x9003) && row["value"] == INVALID), "{all}"); + let all = s.execute("photo.allMetadata", &json!({"id": xmp_id})).unwrap(); + assert!(all["exif"].as_array().unwrap().iter().any(|row| row["tag"] == json!(0x9003) && row["value"] == INVALID), "{all}"); + assert!(all["xmp"].as_array().unwrap().iter().any(|row| row["name"] == "xmp:CreateDate" && row["value"] == "2026-01-05T10:00:00Z"), "{all}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn exif_clock_malformed_capture_cannot_fabricate_tracklog_match() { + use lightcraft_catalog::PhotoId; + + const INVALID: &str = "2026:01:01 12:34:56:99"; + const GPX: &str = r#""#; + let dir = temp_dir("exif-clock-tracklog"); + let malformed_path = dir.join("malformed.png"); + let malformed_exif = exif_clock_block(Some(INVALID), None); + write_png_with_metadata(&malformed_path, 3, Some(&malformed_exif), None); + let valid_path = dir.join("valid.png"); + let valid_exif = exif_clock_block(Some("2026:01:01 12:34:56"), None); + write_png_with_metadata(&valid_path, 4, Some(&valid_exif), None); + + let mut s = Session::new().with_fs(); + let imported = s.execute("library.import", &json!({"paths": [malformed_path.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&imported, "imported"), 1, "{imported}"); + let bad_id = imported["imported"][0].as_u64().unwrap(); + assert_eq!( + s.catalog.photo(PhotoId(bad_id)).unwrap().captured.as_deref(), + Some("2026-01-14T05:58:48"), + "malformed EXIF must leave the normal file-date fallback in effect" + ); + let all = s.execute("photo.allMetadata", &json!({"id": bad_id})).unwrap(); + assert!( + all["exif"].as_array().unwrap().iter().any(|row| row["tag"] == json!(0x9003) && row["value"] == INVALID), + "raw EXIF remains available: {all}" + ); + + // Leave both undo and redo populated so a no-match call must preserve the existing history branch. + s.execute("photo.setMeta", &json!({"ids": [bad_id], "title": "history control"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("library.select", &json!({"ids": [bad_id]})).unwrap(); + assert!(!s.undo.is_empty() && !s.redo.is_empty()); + let state = |session: &Session| { + ( + session.catalog.to_snapshot(), + session.catalog.revision, + session.selection.clone(), + session.commits(), + session.undo.iter().map(|entry| (entry.label.clone(), entry.op.clone())).collect::>(), + session.redo.iter().map(|entry| (entry.label.clone(), entry.op.clone())).collect::>(), + ) + }; + let before = state(&s); + let dry = s.execute("photo.autoTagTracklog", &json!({"gpx": GPX, "ids": [bad_id], "maxGap": 0, "dryRun": true})).unwrap(); + assert_eq!(dry["tagged"], 0, "{dry}"); + assert_eq!(dry["skipped"]["outside"], 1, "the file-date fallback is outside the one-point track: {dry}"); + assert_eq!(state(&s), before, "dry-run changed catalog, selection or history"); + let actual = s.execute("photo.autoTagTracklog", &json!({"gpx": GPX, "ids": [bad_id], "maxGap": 0})).unwrap(); + assert_eq!(actual["tagged"], 0, "{actual}"); + assert_eq!(actual["skipped"]["outside"], 1, "{actual}"); + assert_eq!(state(&s), before, "unmatched tracklog call changed catalog, selection or history"); + assert_eq!(s.catalog.photo(PhotoId(bad_id)).unwrap().meta.gps, None); + + let imported = s.execute("library.import", &json!({"paths": [valid_path.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&imported, "imported"), 1, "{imported}"); + let valid_id = imported["imported"][0].as_u64().unwrap(); + assert_eq!(s.catalog.photo(PhotoId(valid_id)).unwrap().captured.as_deref(), Some("2026-01-01T12:34:56")); + s.execute("library.select", &json!({"ids": [valid_id]})).unwrap(); + let undo_before = s.undo.len(); + let tagged = s.execute("photo.autoTagTracklog", &json!({"gpx": GPX, "ids": [valid_id], "maxGap": 0})).unwrap(); + assert_eq!(tagged["tagged"], 1, "{tagged}"); + assert_eq!(s.catalog.photo(PhotoId(valid_id)).unwrap().meta.gps, Some((45.0, 7.0))); + assert_eq!(s.undo.len(), undo_before + 1, "valid tagging is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(PhotoId(valid_id)).unwrap().meta.gps, None); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn browsing_a_folder_lists_its_photos_without_adding_them() { use crate::LibrarySource; @@ -465,6 +598,210 @@ fn copy_with_destination_organize_rename_and_metadata_preset() { } } +#[test] +fn import_rename_sequence_uses_the_last_value_once() { + let base = temp_dir("rename-sequence-last"); + let (src, dest, lib) = (base.join("source"), base.join("destination"), base.join("library")); + write_png(&src.join("one.png"), 1); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + + let last = usize::MAX; + let r = s + .execute( + "library.import", + &json!({ + "paths": [src.join("one.png").to_string_lossy()], + "mode": "copy", "destination": dest.to_string_lossy(), "organize": "flat", + "rename": "Shot-{seq}", "renameStart": last as u64 + }), + ) + .unwrap(); + + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(0), "{r}"); + assert!(dest.join(format!("Shot-{last}.png")).is_file()); + assert_eq!(s.catalog.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.len(), 0, "the import remains one undo step"); + assert!(dest.join(format!("Shot-{last}.png")).is_file(), "undo leaves a successful copy on disk"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn import_rename_sequence_reports_exhaustion_and_keeps_prior_successes() { + let base = temp_dir("rename-sequence-exhausted"); + let (src, dest, lib) = (base.join("source"), base.join("destination"), base.join("library")); + let paths: Vec<_> = (1..=3) + .map(|i| { + let path = src.join(format!("{i:02}.png")); + write_png(&path, i as u8); + path + }) + .collect(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + + let start = usize::MAX - 1; + let r = s + .execute( + "library.import", + &json!({ + "paths": paths.iter().map(|p| p.to_string_lossy()).collect::>(), + "mode": "copy", "destination": dest.to_string_lossy(), "organize": "flat", + "rename": "Shot-{seq}", "renameStart": start as u64 + }), + ) + .unwrap(); + + assert_eq!(ids(&r, "imported"), 2, "the final two representable values are used: {r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(1), "{r}"); + let failure = r["failed"][0][1].as_str().unwrap_or_default(); + assert!(failure.contains("sequence") && failure.contains("renameStart"), "actionable failure: {failure}"); + assert_eq!(s.catalog.len(), 2); + assert!(dest.join(format!("Shot-{start}.png")).is_file()); + assert!(dest.join(format!("Shot-{}.png", usize::MAX)).is_file()); + assert_eq!(std::fs::read_dir(&dest).unwrap().count(), 2, "the exhausted file gets no destination entry"); + assert!(!paths[2].file_name().is_some_and(|name| dest.join(name).exists()), "the exhausted source gets no copy"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn import_rename_sequence_keeps_flushed_copy_and_move_results() { + for mode in ["copy", "move"] { + let base = temp_dir(&format!("rename-sequence-flush-{mode}")); + let (src, dest, lib) = (base.join("source"), base.join("destination"), base.join("library")); + let paths: Vec<_> = (1..=4) + .map(|i| { + let path = src.join(format!("{i:02}.png")); + write_png(&path, i as u8); + path + }) + .collect(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + + let start = usize::MAX - 2; + let r = s + .execute( + "library.import", + &json!({ + "paths": paths.iter().map(|p| p.to_string_lossy()).collect::>(), + "mode": mode, "destination": dest.to_string_lossy(), "organize": "flat", + "rename": "Holiday", "renameStart": start as u64 + }), + ) + .unwrap(); + + assert_eq!(ids(&r, "imported"), 3, "{mode}: earlier transfers survive sequence exhaustion: {r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(1), "{mode}: {r}"); + assert_eq!(s.catalog.len(), 3, "{mode}: all successful transfers are catalogued"); + let mut output_names: Vec<_> = std::fs::read_dir(&dest) + .unwrap() + .filter_map(std::result::Result::ok) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect(); + output_names.sort(); + assert_eq!(output_names, ["Holiday-1.png", "Holiday-2.png", "Holiday.png"], "{mode}"); + match mode { + "copy" => assert!(paths.iter().all(|path| path.is_file()), "copy leaves every source in place"), + "move" => { + assert!(paths.iter().take(3).all(|path| !path.exists()), "successful moves remove sources after cataloguing"); + assert!(paths[3].is_file(), "the failed source remains in place"); + assert_eq!(r["moved"].as_array().map(Vec::len), Some(3), "{r}"); + } + _ => unreachable!(), + } + let _ = std::fs::remove_dir_all(base); + } +} + +#[test] +fn import_rename_sequence_exhaustion_persists_across_batches() { + let base = temp_dir("rename-sequence-batches"); + let (src, dest, lib) = (base.join("source"), base.join("destination"), base.join("library")); + let first = src.join("one.png"); + let second = src.join("two.png"); + write_png(&first, 1); + write_png(&second, 2); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let opts = crate::import::ImportOptions { + mode: crate::import::ImportMode::Copy, + destination: Some(dest.to_string_lossy().into_owned()), + organize: crate::import::Organize::Flat, + rename: Some("Shot-{seq}".into()), + rename_start: usize::MAX, + ..Default::default() + }; + let mut job = crate::import::ImportJob::new(&mut s, opts).unwrap(); + let cancel = std::sync::atomic::AtomicBool::new(false); + + let prepared = job.prepare(std::slice::from_ref(&first.to_string_lossy().to_string()), &cancel); + let first_result = crate::import::commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap(); + assert_eq!(ids(&serde_json::to_value(first_result).unwrap(), "imported"), 1); + let prepared = job.prepare(std::slice::from_ref(&second.to_string_lossy().to_string()), &cancel); + let second_result = crate::import::commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap(); + let second_result = serde_json::to_value(second_result).unwrap(); + + assert_eq!(ids(&second_result, "imported"), 0, "the exhausted job does not restart its sequence"); + assert_eq!(second_result["failed"].as_array().map(Vec::len), Some(1), "{second_result}"); + assert_eq!(s.catalog.len(), 1); + assert!(dest.join(format!("Shot-{}.png", usize::MAX)).is_file()); + assert!(!dest.join("Shot-1.png").exists(), "no wraparound or reuse"); + assert_eq!( + (job.done.load(std::sync::atomic::Ordering::Relaxed), job.total.load(std::sync::atomic::Ordering::Relaxed)), + (2, 2), + "both the copied and exhausted files advance import progress" + ); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn import_rename_sequence_controls_ignore_the_counter_when_not_renaming() { + let base = temp_dir("rename-sequence-controls"); + let (src, dest, lib) = (base.join("source"), base.join("destination"), base.join("library")); + let added = src.join("add.png"); + let copied = src.join("copy.png"); + write_png(&added, 1); + write_png(&copied, 2); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + + let added_report = s + .execute( + "library.import", + &json!({ + "paths": [added.to_string_lossy()], "mode": "add", "rename": "Ignored-{seq}", "renameStart": usize::MAX as u64 + }), + ) + .unwrap(); + let copied_report = s + .execute( + "library.import", + &json!({ + "paths": [copied.to_string_lossy()], "mode": "copy", "destination": dest.to_string_lossy(), "organize": "flat", + "renameStart": usize::MAX as u64 + }), + ) + .unwrap(); + + assert_eq!(ids(&added_report, "imported"), 1, "Add does not use rename numbering: {added_report}"); + assert_eq!(ids(&copied_report, "imported"), 1, "an empty rename template does not use the counter: {copied_report}"); + assert!(dest.join("copy.png").is_file()); + assert_eq!(s.catalog.len(), 2); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(target_pointer_width = "32")] +#[test] +fn import_rename_sequence_rejects_a_start_outside_usize() { + let s = Session::new(); + let too_large = u64::from(u32::MAX) + 1; + let parsed = crate::cmd::library::import_params(&s, &json!({"paths": ["unused.png"], "renameStart": too_large})); + assert!(parsed.is_err(), "32-bit import parameters must not truncate renameStart"); +} + /// Copy with a custom folder template: `{date:%Y}/{date:%Y%m%d}` files a photo under /// `2026/20260114/` (an undated file by the import time); templates that would leave the /// destination are refused. @@ -1229,6 +1566,11 @@ fn smart_previews_folder_is_chosen_per_library() { let r = again.execute("library.smartPreviewsLocation", &json!({"reset": true})).unwrap(); assert_eq!(r["custom"], false, "{r}"); assert_eq!(r["path"], lib.join("Smart Previews").to_string_lossy().as_ref()); + // (the open library's files are removed below: on Windows an open file cannot be) + drop(again); + for d in [&lib, &away, &src.with_extension("offline")] { + let _ = std::fs::remove_dir_all(d); + } } /// Missing Photos covers library photos only: a small library next to many Local browse @@ -1259,6 +1601,76 @@ fn missing_photos_skip_local_browse_records() { assert_eq!(s.visible_cloned().len(), 4, "the view lists what the count counts"); } +/// `library.missing` asks the session's existence check (the one the availability cache and +/// the tests replace), and a sweep on another thread answers what the command does: the same +/// files in the same order, progress on the way, and a stop that leaves the rest unchecked. +#[test] +fn missing_sweep_answers_what_the_command_does_and_can_stop() { + use lightcraft_catalog::{Op, Photo, PhotoId, Source}; + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut s = Session::new(); + let mut ops = Vec::new(); + for i in 0..200u64 { + let path = format!("/share/IMG_{i:04}.jpg"); + let p = Photo::new(PhotoId(i + 1), Source::File { path }, &format!("IMG_{i:04}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00"); + ops.push(Op::AddPhoto { photo: Box::new(p) }); + } + s.commit("Add", Op::Batch { ops }).unwrap(); + // the first hundred files are gone + s.media.availability.set_probe(std::sync::Arc::new(|f| !f.contains("_00"))); + let asked = s.execute("library.missing", &json!({})).unwrap(); + assert_eq!(asked.as_array().map(Vec::len), Some(100), "the command used the session's check: {asked}"); + + let files = crate::cmd::missing::checked(&s.catalog); + assert_eq!(files.len(), 200); + let reports = AtomicUsize::new(0); + let probe = s.media.availability.probe(); + let swept = crate::cmd::missing::sweep( + files.clone(), + |f| probe(f), + || false, + |_| { + reports.fetch_add(1, Ordering::Relaxed); + }, + ); + assert_eq!(crate::cmd::missing::missing_json(swept.unwrap()), asked); + assert!(reports.load(Ordering::Relaxed) >= 2, "progress is reported on the way"); + + // stopped after 10 files: nothing is answered, and the rest is not looked at + let looked = AtomicUsize::new(0); + let stopped = crate::cmd::missing::sweep( + files, + |_| { + looked.fetch_add(1, Ordering::Relaxed); + true + }, + || looked.load(Ordering::Relaxed) >= 10, + |_| {}, + ); + assert_eq!((stopped, looked.load(Ordering::Relaxed)), (None, 10)); +} + +/// A stop that arrives while the last file is being checked is honoured: no answer. +#[test] +fn missing_sweep_honours_a_stop_during_the_last_check() { + use lightcraft_catalog::PhotoId; + use std::sync::atomic::{AtomicBool, Ordering}; + let stop = AtomicBool::new(false); + let files = vec![(PhotoId(1), "/a".to_string()), (PhotoId(2), "/b".to_string())]; + let swept = crate::cmd::missing::sweep( + files, + |f| { + if f == "/b" { + stop.store(true, Ordering::Relaxed); + } + false + }, + || stop.load(Ordering::Relaxed), + |_| {}, + ); + assert_eq!(swept, None); +} + /// `library.browse` follows `library.source`'s rule for the active photo (issue #1447): a library /// photo the folder doesn't show gives way to the folder's first photo; one it shows stays. #[test] @@ -2053,6 +2465,49 @@ fn heic_imports_as_a_normal_photo_or_says_why_not() { let _ = std::fs::remove_dir_all(&src); } +/// Issue #2284: a photo taken at 13:00 in UTC-5 must be catalogued as 13:00. HEICs carried no Exif +/// (issue #1233), so every one of them fell back to the file's modification time, which the import +/// writes as UTC: an iPhone photo landed five hours late and after 19:00 on the wrong day. +#[test] +fn a_heic_is_dated_by_its_exif_and_not_by_the_file() { + use lightcraft_heif::testdata::{Spec, build}; + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + let src = temp_dir("heic-capture-time"); + let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150]; + let mut exif = IfdBuilder::new(); + exif.set(t::DATE_TIME_ORIGINAL, Value::Ascii("2026:10:18 13:00:00".into())); + exif.set(t::OFFSET_TIME_ORIGINAL, Value::Ascii("-05:00".into())); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Apple".into())); + ifd0.set(t::MODEL, Value::Ascii("iPhone 15 Pro".into())); + // HEIF turns the picture in the container; its Exif Orientation only mirrors that, so reading + // the Exif must not turn it a second time. + ifd0.set(t::ORIENTATION, Value::Short(vec![6])); + ifd0.set_child(t::EXIF_IFD, exif); + let exif = TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap(); + let bytes = build(&Spec { exif: Some(exif), ..Spec::new(96, 64, &photo) }); + let path = src.join("IMG_0002.HEIC"); + std::fs::write(&path, &bytes).unwrap(); + // The probe reads the metadata in every build; only decoding the picture needs the feature. + let info = crate::files::probe_bytes("IMG_0002.HEIC", &bytes); + if lightcraft_codecs::Format::Heif.can_decode() { + let info = info.unwrap(); + assert_eq!(info.captured.as_deref(), Some("2026-10-18T13:00:00-05:00")); + assert_eq!(info.meta.camera, "Apple iPhone 15 Pro"); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!((ids(&r, "imported"), ids(&r, "failed")), (1, 0), "{r}"); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.captured.as_deref(), Some("2026-10-18T13:00:00-05:00"), "the time the camera wrote, not the file's"); + assert_eq!((p.width, p.height), (96, 64), "upright: the container's own transforms, not the Exif tag as well"); + assert_eq!(lightcraft_catalog::dates::display_time(p.date()), "October 18, 2026 at 1:00:00 PM"); + } else { + assert!(info.is_err(), "without the feature a HEIC cannot be opened at all"); + assert_eq!(lightcraft_meta::extract(&bytes).capture_time.map(|d| d.to_iso()).as_deref(), Some("2026-10-18T13:00:00-05:00")); + } + let _ = std::fs::remove_dir_all(&src); +} + /// Issue #705: Nikon (and most cameras) write `.JPG` and `.NEF`, and a user may rename to `.Jpg`. /// The folder scan, `library.browse` and the sidecar lookup match extensions in any letter /// case. (The file dialog's filters, the one place that was case-sensitive on Linux before diff --git a/crates/engine/src/tests/keyword_list.rs b/crates/engine/src/tests/keyword_list.rs index 94ff599887..e50d0d7b14 100644 --- a/crates/engine/src/tests/keyword_list.rs +++ b/crates/engine/src/tests/keyword_list.rs @@ -184,6 +184,128 @@ fn a_set_keyword_toggles_whatever_its_case() { assert!(ids.iter().all(|id| keywords_of(&s, *id).is_empty()), "taken off both"); } +/// The keyword shortcut (Set Keyword Shortcut, ⌘⌥⇧K) holds the keywords typed with commas +/// between them, each once whatever its case and spelled as the library spells it; ⇧K adds them to +/// the target photos unless every one has them all, and then takes them off. With no keyword +/// shortcut set, ⇧K leaves the photos' keywords as they were. +#[test] +fn the_keyword_shortcut_adds_and_removes_its_keywords() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + s.execute("photo.setMeta", &json!({"ids": [ids[0]], "keywords": ["beach"]})).unwrap(); + s.execute("photo.setMeta", &json!({"ids": [ids[1]], "keywords": []})).unwrap(); + let r = s.execute("keyword.setShortcut", &json!({"keywords": " Beach , sunset,, BEACH"})).unwrap(); + assert_eq!(r["keywords"], json!(["beach", "sunset"])); + assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["beach", "sunset"])); + let r = s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap(); + assert_eq!(r["added"], true, "{r}"); + assert_eq!(keywords_of(&s, ids[0]), ["beach", "sunset"], "a keyword it has isn't added again"); + assert_eq!(keywords_of(&s, ids[1]), ["beach", "sunset"]); + let r = s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap(); + assert_eq!(r["added"], false, "{r}"); + assert!(ids.iter().all(|id| keywords_of(&s, *id).is_empty()), "every photo had both: taken off"); + // both photos have one of the two keywords: both keywords are added to both photos + s.execute("photo.setMeta", &json!({"ids": ids, "keywords": ["sunset"]})).unwrap(); + assert_eq!(s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap()["added"], true); + assert!(ids.iter().all(|id| keywords_of(&s, *id).len() == 2)); + // with nothing typed the keyword shortcut is cleared, and ⇧K leaves the photos' keywords as they were + assert_eq!(s.execute("keyword.setShortcut", &json!({"keywords": " , "})).unwrap()["keywords"], json!([])); + let r = s.execute("keyword.toggleShortcut", &json!({"ids": ids})).unwrap(); + assert_eq!(r["changed"], 0, "{r}"); + assert!(ids.iter().all(|id| keywords_of(&s, *id).len() == 2)); +} + +/// A keyword with a comma in its name stays one keyword when Set Keyword Shortcut… is confirmed +/// with the text it showed; other text is split at its commas. +#[test] +fn the_keyword_shortcut_keeps_a_name_with_a_comma() { + let mut s = Session::with_demo(); + s.execute("keyword.create", &json!({"name": "Paris, France"})).unwrap(); + s.execute("keyword.create", &json!({"name": "Trips"})).unwrap(); + s.execute("keyword.setShortcut", &json!({"keywords": ["Paris, France", "Trips"]})).unwrap(); + let r = s.execute("keyword.setShortcut", &json!({"keywords": "Paris, France, Trips"})).unwrap(); + assert_eq!(r["keywords"], json!(["Paris, France", "Trips"]), "the text it showed, confirmed as it was"); + let r = s.execute("keyword.setShortcut", &json!({"keywords": "Paris, France"})).unwrap(); + assert_eq!(r["keywords"], json!(["France", "Paris"]), "changed text is split at its commas"); +} + +/// A `keywords` value that is neither text nor a list of text is an error, and the keyword +/// shortcut keeps its keywords. +#[test] +fn the_keyword_shortcut_refuses_keywords_that_are_not_text() { + let mut s = Session::with_demo(); + s.execute("keyword.setShortcut", &json!({"keywords": ["beach", "sunset"]})).unwrap(); + for keywords in [json!(7), json!(["beach", 7]), json!({"name": "beach"})] { + let e = s.execute("keyword.setShortcut", &json!({"keywords": keywords})).unwrap_err().to_string(); + assert!(e.contains("`keywords` must be a string or an array of strings"), "{keywords}: {e}"); + assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["beach", "sunset"]), "{keywords}"); + } + // parameters that are not an object are an error too, not a request to clear it + for params in [json!(7), json!("beach"), json!(["beach"])] { + let e = s.execute("keyword.setShortcut", ¶ms).unwrap_err().to_string(); + assert!(e.contains("parameters must be an object"), "{params}: {e}"); + assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["beach", "sunset"]), "{params}"); + } +} + +/// ⇧K with an `ids` or `id` that is not photo ids is an error, with or without a keyword shortcut set. +#[test] +fn the_keyword_shortcut_refuses_targets_that_are_not_photo_ids() { + let mut s = Session::with_demo(); + let id = s.visible_cloned()[0].0; + s.execute("library.select", &json!({"ids": [id]})).unwrap(); + for shortcut in [json!([]), json!(["beach"])] { + s.execute("keyword.setShortcut", &json!({"keywords": shortcut})).unwrap(); + for params in [json!({"ids": "x"}), json!({"ids": ["x"]}), json!({"id": "x"})] { + let e = s.execute("keyword.toggleShortcut", ¶ms).unwrap_err().to_string(); + assert!(e.contains("must be photo ids"), "{shortcut} {params}: {e}"); + } + } +} + +/// The keyword shortcut follows its keywords when they are moved, renamed or merged, and loses one +/// that is deleted; setting it is one undo step, and undo brings a deleted one back. +#[test] +fn the_keyword_shortcut_follows_its_keywords() { + let mut s = Session::with_demo(); + for name in ["Weddings", "Events", "Trips"] { + s.execute("keyword.create", &json!({"name": name})).unwrap(); + } + let undo = s.undo.len(); + s.execute("keyword.setShortcut", &json!({"keywords": ["Weddings", "Trips"]})).unwrap(); + assert_eq!(s.undo.len(), undo + 1, "one undo step"); + let shortcut = |s: &mut Session| s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"].clone(); + s.execute("keyword.move", &json!({"keyword": "Weddings", "parent": "Events"})).unwrap(); + assert_eq!(shortcut(&mut s), json!(["Events|Weddings", "Trips"]), "moved"); + s.execute("keyword.edit", &json!({"keyword": "Events|Weddings", "name": "Marriages"})).unwrap(); + assert_eq!(shortcut(&mut s), json!(["Events|Marriages", "Trips"]), "renamed"); + s.execute("keyword.merge", &json!({"from": ["Trips"], "into": "Events|Marriages"})).unwrap(); + assert_eq!(shortcut(&mut s), json!(["Events|Marriages"]), "merged, and kept once"); + s.execute("keyword.delete", &json!({"keyword": "Events"})).unwrap(); + assert_eq!(shortcut(&mut s), json!([]), "deleted with the keyword it was inside"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(shortcut(&mut s), json!(["Events|Marriages"]), "undo brings it back"); +} + +/// A new name in the keyword shortcut goes inside the default parent, as the Keywording box puts +/// it; a keyword the library has stays where it is. The keyword shortcut is kept with the library. +#[test] +fn the_keyword_shortcut_is_kept_with_the_library() { + let dir = temp_dir("keyword-shortcut"); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + s.execute("keyword.create", &json!({"name": "Travel"})).unwrap(); + s.execute("keyword.create", &json!({"name": "Events"})).unwrap(); + s.execute("keyword.setDefaultParent", &json!({"keyword": "events"})).unwrap(); + let r = s.execute("keyword.setShortcut", &json!({"keywords": ["Travel", "Birthdays"]})).unwrap(); + assert_eq!(r["keywords"], json!(["Events|Birthdays", "Travel"])); + drop(s); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + assert_eq!(s.execute("keyword.shortcut", &json!({})).unwrap()["keywords"], json!(["Events|Birthdays", "Travel"])); + let _ = std::fs::remove_dir_all(&dir); +} + fn set_named(s: &mut Session, name: &str) -> serde_json::Value { let sets = s.execute("keyword.sets", &json!({})).unwrap(); sets["sets"].as_array().unwrap().iter().find(|x| x["name"] == name).cloned().unwrap_or(serde_json::Value::Null) diff --git a/crates/engine/src/tests/libops.rs b/crates/engine/src/tests/libops.rs index b35167c1ba..e33d614e3e 100644 --- a/crates/engine/src/tests/libops.rs +++ b/crates/engine/src/tests/libops.rs @@ -467,6 +467,93 @@ fn tracklog_auto_tag() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn tracklog_auto_tag_decodes_character_references_and_undoes_once() { + use lightcraft_catalog::Op; + + const PLAIN: &str = r#" + + + "#; + const ENCODED: &str = r#" + + + "#; + + let mut s = Session::with_demo(); + let Some(id) = s.visible_cloned().first().copied() else { + panic!("the demo library has a photo"); + }; + s.commit("test capture time", Op::SetCaptured { id, captured: Some("2026-01-01T00:01:00".into()) }).unwrap(); + let original_gps = s.catalog.photo(id).unwrap().meta.gps; + let params = |gpx: &str, dry_run| json!({"gpx": gpx, "ids": [id.0], "dryRun": dry_run}); + + let plain = s.execute("photo.autoTagTracklog", ¶ms(PLAIN, true)).unwrap(); + let encoded = s.execute("photo.autoTagTracklog", ¶ms(ENCODED, true)).unwrap(); + assert_eq!(plain, encoded); + assert_eq!(encoded["photos"][0]["gps"], json!([46.0, 8.0])); + assert_eq!(s.catalog.photo(id).unwrap().meta.gps, original_gps, "dry run leaves GPS unchanged"); + + let undo_depth = s.undo.len(); + s.execute("photo.autoTagTracklog", ¶ms(ENCODED, false)).unwrap(); + assert_eq!(s.undo.len(), undo_depth + 1); + assert_eq!(s.catalog.photo(id).unwrap().meta.gps, Some((46.0, 8.0))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.gps, original_gps); +} + +#[test] +fn tracklog_auto_tag_rejects_malformed_capture_time_without_history_changes() { + let mut s = Session::with_demo(); + let id = s.visible_cloned().first().map(|id| id.0).unwrap(); + s.execute("library.select", &json!({"ids": [id]})).unwrap(); + s.execute("photo.setCaptureTime", &json!({"time": "2026-01-01T00:00:00", "each": true})).unwrap(); + s.execute("photo.setMeta", &json!({"ids": [id], "gps": null, "title": "before"})).unwrap(); + s.execute("photo.setMeta", &json!({"ids": [id], "title": "after"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.undo.is_empty() && !s.redo.is_empty(), "test starts with undo and redo history"); + + let gpx = r#" + + + "#; + let photo = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap(); + assert_eq!(photo.meta.gps, None); + assert_eq!(photo.meta.title.as_str(), "before"); + + let before_catalog = s.catalog.to_snapshot(); + let before_revision = s.catalog.revision; + let before_selection = s.selection.clone(); + let before_commits = s.commits(); + let before_history = |entries: &[crate::UndoEntry]| entries.iter().map(|entry| (entry.label.clone(), entry.op.clone())).collect::>(); + let before_undo = before_history(&s.undo); + let before_redo = before_history(&s.redo); + + for dry_run in [true, false] { + let result = s.execute("photo.autoTagTracklog", &json!({"gpx": gpx, "ids": [id], "maxGap": 0, "dryRun": dry_run})).unwrap(); + assert_eq!(result["tagged"], 0, "{result}"); + assert_eq!(s.catalog.to_snapshot(), before_catalog); + assert_eq!(s.catalog.revision, before_revision); + assert_eq!(s.selection, before_selection); + assert_eq!(s.commits(), before_commits); + assert_eq!(before_history(&s.undo), before_undo); + assert_eq!(before_history(&s.redo), before_redo); + } + + let valid_midnight = r#" + + "#; + let undo_depth = s.undo.len(); + let commits = s.commits(); + let result = s.execute("photo.autoTagTracklog", &json!({"gpx": valid_midnight, "ids": [id], "maxGap": 0})).unwrap(); + assert_eq!(result["tagged"], 1, "{result}"); + assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().meta.gps, Some((45.0, 7.0))); + assert_eq!(s.undo.len(), undo_depth + 1); + assert_eq!(s.commits(), commits + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().meta.gps, None); +} + // ---- random sort: Given the library, When the user picks Random, Then the grid is a stable shuffle #[test] diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index b2eb8cb949..32b4130ac7 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -357,6 +357,61 @@ fn filter_any_of_several_labels() { assert!(s.visible_cloned().len() > want); } +/// The filter bar's flag multi-select (#2588): Picked and Unflagged together hide only the rejects, +/// as Lightroom Classic's flag toggles do; one chip clears both, and the old single `flag` still filters. +#[test] +fn filter_any_of_several_flags() { + use lightcraft_catalog::Flag; + let mut s = crate::Session::with_demo(); + let ids: Vec = s.catalog.photos().take(4).map(|p| p.id.0).collect(); + for (id, f) in ids.iter().zip(["pick", "pick", "reject", "none"]) { + s.execute("photo.flag", &json!({"ids": [id], "flag": f})).unwrap(); + } + let count = |s: &Session, want: &[Flag]| s.catalog.photos().filter(|p| p.in_library() && want.contains(&p.flag)).count(); + let (picks, rejects, all) = (count(&s, &[Flag::Pick]), count(&s, &[Flag::Reject]), count(&s, &[Flag::Pick, Flag::Reject, Flag::None])); + assert!(picks >= 2 && rejects >= 1 && all > picks + rejects, "picks {picks}, rejects {rejects}, all {all}"); + s.execute("library.filter", &json!({"flags": ["pick", "none"]})).unwrap(); + let vis = s.visible_cloned(); + assert_eq!(vis.len(), all - rejects); + assert!(vis.iter().all(|id| s.catalog.photo(*id).unwrap().flag != Flag::Reject)); + assert!(s.filter.describe().contains("flag pick or none"), "{}", s.filter.describe()); + let chips = crate::filter_chips(&s.filter, &s.catalog); + let chip = chips.iter().find(|c| c.label.starts_with("Flag")).expect("a flag chip"); + assert_eq!(chip.label, "Flag: pick or none"); + s.execute("library.filter", &chip.clear).unwrap(); + assert_eq!(s.visible_cloned().len(), all); + // `null` clears the list, as it clears the single flag + s.execute("library.filter", &json!({"flags": ["reject"]})).unwrap(); + assert_eq!(s.visible_cloned().len(), rejects); + s.execute("library.filter", &json!({"flags": null})).unwrap(); + assert!(s.filter.flags.is_empty()); + assert_eq!(s.visible_cloned().len(), all); + // the single flag of saved filters and agents filters as before + s.execute("library.filter", &json!({"flag": "pick"})).unwrap(); + assert_eq!(s.visible_cloned().len(), picks); +} + +/// `flag` and `flags` set together (only through `library.filter`) AND, and the chip says what +/// they let through, not their union. +#[test] +fn filter_flag_and_flags_together_chip() { + use lightcraft_catalog::Flag; + let mut s = crate::Session::with_demo(); + let ids: Vec = s.catalog.photos().take(3).map(|p| p.id.0).collect(); + for (id, f) in ids.iter().zip(["pick", "reject", "none"]) { + s.execute("photo.flag", &json!({"ids": [id], "flag": f})).unwrap(); + } + let picks = s.catalog.photos().filter(|p| p.in_library() && p.flag == Flag::Pick).count(); + let chip = |s: &Session| crate::filter_chips(&s.filter, &s.catalog).into_iter().find(|c| c.label.starts_with("Flag")).expect("a flag chip").label; + s.execute("library.filter", &json!({"flag": "pick", "flags": ["pick", "none"]})).unwrap(); + assert_eq!(s.visible_cloned().len(), picks); + assert_eq!(chip(&s), "Flag: pick"); + // nothing passes both: the chip names both constraints + s.execute("library.filter", &json!({"flag": "pick", "flags": ["reject", "none"]})).unwrap(); + assert_eq!(s.visible_cloned().len(), 0); + assert_eq!(chip(&s), "Flag: pick and (reject or none)"); +} + /// Quick Collection / target album: B toggles the selection in it (created on first use); /// another album can be the target; clear empties it; all undoable. #[test] @@ -654,6 +709,24 @@ fn set_rules_with_a_name_is_one_step() { assert_eq!(album(&s).name, "Old"); } +/// The rules dialog sends `replace` and has no album field: a view of an album saved as a smart +/// album stays limited to that album after OK, until a call says `album: null`. +#[test] +fn editing_a_smart_album_made_from_an_album_view_keeps_the_album() { + use lightcraft_catalog::AlbumId; + let mut s = crate::Session::with_demo(); + let trip = s.execute("album.create", &serde_json::json!({"name": "Trip", "addSelected": false})).unwrap()["id"].as_u64().unwrap(); + let all = s.catalog.photos().map(|p| p.id.0).collect::>(); + s.execute("album.addPhotos", &serde_json::json!({"id": trip, "ids": [all[0], all[1]]})).unwrap(); + s.execute("library.source", &serde_json::json!({"kind": "album", "id": trip})).unwrap(); + let id = s.execute("album.createSmart", &serde_json::json!({"name": "From Trip"})).unwrap()["id"].as_u64().unwrap(); + let album_of = |s: &crate::Session| s.catalog.album(AlbumId(id)).unwrap().smart.as_ref().unwrap().album; + let r = s.execute("album.setRules", &serde_json::json!({"id": id, "replace": true, "rules": {"ruleSet": {"rules": []}}})).unwrap(); + assert_eq!((album_of(&s), r["count"].as_u64()), (Some(AlbumId(trip)), Some(2)), "still limited to the album: {r}"); + let r = s.execute("album.setRules", &serde_json::json!({"id": id, "replace": true, "rules": {"album": null}})).unwrap(); + assert_eq!(album_of(&s), None, "and dropped on purpose: {r}"); +} + /// albums.list says which smart albums have rules that no longer check, and why. #[test] fn album_list_reports_problems() { diff --git a/crates/engine/src/tests/organize.rs b/crates/engine/src/tests/organize.rs index ea04142561..efd345cc6c 100644 --- a/crates/engine/src/tests/organize.rs +++ b/crates/engine/src/tests/organize.rs @@ -4,7 +4,7 @@ use lightcraft_catalog::Flag; use serde_json::json; -use crate::{LibrarySource, Session}; +use crate::{EngineError, LibrarySource, Session}; fn temp_dir(tag: &str) -> std::path::PathBuf { let d = std::env::temp_dir().join(format!("lc-organize-{tag}-{}", std::process::id())); @@ -18,6 +18,13 @@ fn open(dir: &std::path::Path) -> Session { s } +fn leave_redo_entry(s: &mut Session, id: lightcraft_catalog::PhotoId) { + let rating = if s.catalog.photo(id).unwrap().rating == 5 { 4 } else { 5 }; + s.execute("photo.rate", &json!({"ids": [id.0], "rating": rating})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.redo.is_empty()); +} + #[test] fn smart_album_from_view_updates_live_and_persists() { let dir = temp_dir("smart"); @@ -141,6 +148,119 @@ fn virtual_copies_are_independent_and_persist() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn virtual_copy_explicit_name_bypasses_exhausted_counter() { + let mut s = Session::with_demo(); + let visible = s.visible_cloned(); + let src = visible[0]; + s.execute("photo.virtualCopy", &json!({"ids": [src.0], "name": "Copy 4294967295"})).unwrap(); + + let result = s.execute("photo.virtualCopy", &json!({"ids": [src.0], "name": "Proof copy"})); + assert!(result.is_ok(), "an explicit name does not need a numeric suffix: {result:?}"); + let id = lightcraft_catalog::PhotoId(result.unwrap()["ids"][0].as_u64().unwrap()); + let copy = s.catalog.photo(id).unwrap(); + assert_eq!(copy.copy_of, Some(src)); + assert_eq!(copy.copy_name.as_deref(), Some("Proof copy")); +} + +#[test] +fn virtual_copy_exhausted_counter_returns_bad_params() { + let mut s = Session::with_demo(); + let visible = s.visible_cloned(); + let src = visible[0]; + s.execute("photo.virtualCopy", &json!({"ids": [src.0], "name": "Copy 4294967295"})).unwrap(); + leave_redo_entry(&mut s, visible[1]); + + let before = s.catalog.to_snapshot(); + let revision = s.catalog.revision; + let selection = (s.selection.ids.clone(), s.selection.active); + let commits = s.commits(); + let undo = s.undo.iter().map(|entry| entry.label.clone()).collect::>(); + let redo = s.redo.iter().map(|entry| entry.label.clone()).collect::>(); + + let result = s.execute("photo.virtualCopy", &json!({"ids": [src.0]})); + let actionable = + matches!(&result, Err(EngineError::BadParams { cmd, msg }) if cmd == "photo.virtualCopy" && msg.contains("provide an explicit name")); + assert_eq!(s.catalog.to_snapshot(), before, "exhaustion must not allocate IDs or mutate the catalog"); + assert_eq!(s.catalog.revision, revision); + assert_eq!((s.selection.ids.clone(), s.selection.active), selection); + assert_eq!(s.commits(), commits); + assert_eq!(s.undo.iter().map(|entry| entry.label.clone()).collect::>(), undo); + assert_eq!(s.redo.iter().map(|entry| entry.label.clone()).collect::>(), redo); + assert!(actionable, "expected actionable parameter error, got {result:?}"); +} + +#[test] +fn virtual_copy_numbering_failure_does_not_partially_change_batch() { + let mut s = Session::with_demo(); + let visible = s.visible_cloned(); + let (first, second) = (visible[0], visible[1]); + s.execute("photo.virtualCopy", &json!({"ids": [second.0], "name": "Copy 4294967295"})).unwrap(); + leave_redo_entry(&mut s, visible[2]); + s.execute("library.select", &json!({"ids": [first.0, second.0], "active": first.0})).unwrap(); + + let before = s.catalog.to_snapshot(); + let revision = s.catalog.revision; + let selection = (s.selection.ids.clone(), s.selection.active); + let commits = s.commits(); + let undo = s.undo.iter().map(|entry| entry.label.clone()).collect::>(); + let redo = s.redo.iter().map(|entry| entry.label.clone()).collect::>(); + + let result = s.execute("photo.virtualCopy", &json!({"ids": [first.0, second.0]})); + let bad_params = matches!(&result, Err(EngineError::BadParams { cmd, .. }) if cmd == "photo.virtualCopy"); + assert_eq!(s.catalog.to_snapshot(), before, "a later exhausted master must not leave earlier copies behind"); + assert_eq!(s.catalog.revision, revision); + assert_eq!((s.selection.ids.clone(), s.selection.active), selection); + assert_eq!(s.commits(), commits); + assert_eq!(s.undo.iter().map(|entry| entry.label.clone()).collect::>(), undo); + assert_eq!(s.redo.iter().map(|entry| entry.label.clone()).collect::>(), redo); + assert!(bad_params, "expected batch preflight error, got {result:?}"); +} + +#[test] +fn virtual_copy_batch_reserves_numbers_for_the_same_master() { + let mut s = Session::with_demo(); + let visible = s.visible_cloned(); + let src = visible[0]; + let near_limit = lightcraft_catalog::PhotoId( + s.execute("photo.virtualCopy", &json!({"ids": [src.0], "name": "Copy 4294967294"})).unwrap()["ids"][0].as_u64().unwrap(), + ); + leave_redo_entry(&mut s, visible[1]); + s.execute("library.select", &json!({"ids": [src.0, near_limit.0], "active": src.0})).unwrap(); + + let before = s.catalog.to_snapshot(); + let revision = s.catalog.revision; + let selection = (s.selection.ids.clone(), s.selection.active); + let commits = s.commits(); + let undo = s.undo.iter().map(|entry| entry.label.clone()).collect::>(); + let redo = s.redo.iter().map(|entry| entry.label.clone()).collect::>(); + + let result = s.execute("photo.virtualCopy", &json!({"ids": [src.0, near_limit.0]})); + let bad_params = matches!(&result, Err(EngineError::BadParams { cmd, .. }) if cmd == "photo.virtualCopy"); + assert_eq!(s.catalog.to_snapshot(), before, "same-master reservations must be checked before either copy is added"); + assert_eq!(s.catalog.revision, revision); + assert_eq!((s.selection.ids.clone(), s.selection.active), selection); + assert_eq!(s.commits(), commits); + assert_eq!(s.undo.iter().map(|entry| entry.label.clone()).collect::>(), undo); + assert_eq!(s.redo.iter().map(|entry| entry.label.clone()).collect::>(), redo); + assert!(bad_params, "a shared master has only one number left: {result:?}"); +} + +#[test] +fn virtual_copy_last_valid_number_can_be_created_and_undone() { + let mut s = Session::with_demo(); + let src = s.visible_cloned()[0]; + s.execute("photo.virtualCopy", &json!({"ids": [src.0], "name": "Copy 4294967294"})).unwrap(); + + let result = s.execute("photo.virtualCopy", &json!({"ids": [src.0]})).unwrap(); + let id = lightcraft_catalog::PhotoId(result["ids"][0].as_u64().unwrap()); + assert_eq!(s.catalog.photo(id).unwrap().copy_name.as_deref(), Some("Copy 4294967295")); + assert_eq!(s.catalog.photo(id).unwrap().copy_of, Some(src)); + + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.photo(id).is_none(), "one undo removes the last valid copy"); +} + /// Issue #1493: soft-delete must drop the copy from the stack so `1/2` does not linger, and /// deleting `2/3` renumbers the rest to `1/2` `2/2`. Undo restores the stack. #[test] diff --git a/crates/engine/src/tests/process.rs b/crates/engine/src/tests/process.rs index d101073ecf..39747b1a18 100644 --- a/crates/engine/src/tests/process.rs +++ b/crates/engine/src/tests/process.rs @@ -187,6 +187,23 @@ fn process_numbers_survive_a_reopen_and_develop_get_reports_them() { let _ = std::fs::remove_dir_all(&dir); } +/// Issue #2555: a sidecar's `lc:settings` became the photo's settings without the range checks +/// presets and `develop.merge` get, so sliders and the crop angle kept any value. +#[test] +fn sidecar_settings_are_kept_in_range() { + use crate::sidecar::{DevelopPatch, parse_sidecar}; + let mut wild = lightcraft_develop::DevelopSettings::default(); + wild.light.exposure = 1e9; + wild.crop.geometry = lightcraft_geom::CropGeometry { rect: lightcraft_geom::Rect::new(0.0, 0.0, 1000.0, 1000.0), angle: 400.0 }; + let json = wild.to_json().to_string(); + let packet = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata::default(), Some(&json)); + let Some(DevelopPatch::Full(d)) = parse_sidecar(&packet, crate::crs::Target::Rendered).unwrap().develop else { panic!("no lc:settings") }; + assert!(d.light.exposure <= 10.0, "exposure {}", d.light.exposure); + assert_eq!(d.crop.geometry.angle, 45.0); + let (w, h) = lightcraft_pipeline::native_output_size(6000, 4000, &d); + assert!(w <= 12_000.0 && h <= 8_000.0, "{w} x {h}"); +} + #[test] fn sidecars_keep_the_process_and_interchange_edits_get_the_latest() { use crate::sidecar::{DevelopPatch, merge_into, parse_sidecar, sidecar_packet}; diff --git a/crates/engine/src/tests/shelved_folder.rs b/crates/engine/src/tests/shelved_folder.rs new file mode 100644 index 0000000000..c29453df61 --- /dev/null +++ b/crates/engine/src/tests/shelved_folder.rs @@ -0,0 +1,83 @@ +//! A filter Enable Filters (Cmd+L) put aside and a folder moved on disk meanwhile: switched back +//! on, the filter is the one put aside, and a folder it names is where the folder went. + +use lightcraft_catalog::{Op, Photo, Source}; +use serde_json::json; + +use crate::Session; + +fn add(s: &mut Session, path: &str, rating: u8) { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + p.rating = rating; + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); +} + +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-shelved-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("trip")).unwrap(); + std::fs::create_dir_all(dir.join("archive")).unwrap(); + Scratch(dir) + } + fn path(&self, rel: &str) -> String { + self.0.join(rel).components().collect::().to_string_lossy().to_string() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn a_folder_in_the_filter_put_aside_follows_a_move() { + let dir = Scratch::new("filter"); + let (trip, archive) = (dir.path("trip"), dir.path("archive")); + let mut s = Session::new(); + add(&mut s, &format!("{trip}/a.jpg"), 0); + add(&mut s, &dir.path("elsewhere.jpg"), 0); + s.execute("library.filter", &json!({"folder": trip})).unwrap(); + assert_eq!(s.visible().len(), 1, "the filter hides a photo, or a stale folder would look alike"); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("folder.move", &json!({"path": trip, "into": archive})).unwrap(); + let r = s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(r["enabled"], json!(true)); + assert_eq!(s.filter.folder.as_deref(), Some(dir.path("archive/trip").as_str()), "the folder where it went"); + assert_eq!(s.visible().len(), 1, "the moved photo, as before the move"); +} + +#[test] +fn a_folder_in_the_filter_follows_a_move_with_filters_on() { + let dir = Scratch::new("live"); + let (trip, archive) = (dir.path("trip"), dir.path("archive")); + let mut s = Session::new(); + add(&mut s, &format!("{trip}/a.jpg"), 0); + add(&mut s, &dir.path("elsewhere.jpg"), 0); + s.execute("library.filter", &json!({"folder": trip})).unwrap(); + assert_eq!(s.visible().len(), 1, "the filter hides a photo, or a stale folder would look alike"); + s.execute("folder.move", &json!({"path": trip, "into": archive})).unwrap(); + assert_eq!(s.filter.folder.as_deref(), Some(dir.path("archive/trip").as_str()), "the folder where it went"); + assert_eq!(s.visible().len(), 1, "the moved photo, as before the move"); +} + +#[test] +fn moving_the_browsed_folder_while_off_brings_back_the_filter_put_aside() { + let dir = Scratch::new("browse"); + let (trip, archive) = (dir.path("trip"), dir.path("archive")); + let mut s = Session::new(); + s.execute("library.browse", &json!({"path": trip})).unwrap(); + s.execute("library.filter", &json!({"rating": 4})).unwrap(); + let set = s.filter.clone(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("folder.move", &json!({"path": trip, "into": archive})).unwrap(); + assert!(s.filters_off(), "still off after the move"); + let r = s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(r["enabled"], json!(true), "Cmd+L turns filtering back on"); + assert_eq!(s.filter, set, "the stars put aside, nothing added"); +} diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 129662e4dc..a9314c2173 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -288,6 +288,80 @@ fn a_crs_change_after_a_read_is_taken_with_auto_write_on() { let _ = std::fs::remove_dir_all(&src); } +/// A sidecar with keywords as Lightroom Classic and darktable write them: names in `dc:subject`, +/// paths in `lr:hierarchicalSubject`. +const KEYWORDED: &str = r#" + + + + PlacesItalyRomesunset + Places|Italy|Romesunset + + + +"#; + +/// Saving a sidecar keeps keywords where other applications look for them: names in `dc:subject` +/// and paths in `lr:hierarchicalSubject`, each property once. LightCraft 0.13 wrote the paths into +/// `dc:subject` (`Places|Italy|Rome`), so after any change, even a rating, a search for "Rome" in +/// another DAM no longer found the photo. A sidecar written that way is put right on the next save, +/// and keywords added here keep their hierarchy when the sidecar is read back. +#[test] +fn saving_a_sidecar_writes_keyword_names_flat_and_paths_hierarchical() { + let src = temp_dir("keywords-flat"); + write_png(&src.join("rome.png"), 8); + let sidecar = src.join("rome.xmp"); + std::fs::write(&sidecar, KEYWORDED).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = only(&s); + assert_eq!(s.catalog.photo(id).unwrap().meta.keywords, ["Places|Italy|Rome", "sunset"]); + s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap(); + s.execute("photo.rate", &json!({"ids": [id.0], "rating": 3})).unwrap(); + + let lists = |text: &str| { + let x = lightcraft_meta::parse_xmp(text).unwrap(); + (x.metadata.keywords, x.metadata.hierarchical_keywords) + }; + let text = std::fs::read_to_string(&sidecar).unwrap(); + let (flat, hierarchical) = lists(&text); + assert_eq!(flat, ["Places", "Italy", "Rome", "sunset"], "names, not paths, in dc:subject:\n{text}"); + assert_eq!(hierarchical, ["Places|Italy|Rome", "sunset"], "{text}"); + assert_eq!(text.matches("").count(), 1, "{text}"); + assert_eq!(text.matches("lr:hierarchicalSubject>").count(), 2, "one lr:hierarchicalSubject, opened and closed:\n{text}"); + assert!(text.contains("3") && text.contains(r#"crs:Exposure2012="+0.40""#), "{text}"); + + // a keyword added here keeps its hierarchy through the file + s.execute("photo.setMeta", &json!({"ids": [id.0], "keywords": ["Places|Italy|Rome", "sunset", "people|Ada"]})).unwrap(); + let (flat, hierarchical) = lists(&std::fs::read_to_string(&sidecar).unwrap()); + assert_eq!(flat, ["Places", "Italy", "Rome", "sunset", "people", "Ada"]); + assert_eq!(hierarchical, ["Places|Italy|Rome", "sunset", "people|Ada"]); + s.execute("photo.setMeta", &json!({"ids": [id.0], "keywords": []})).unwrap(); + let text = std::fs::read_to_string(&sidecar).unwrap(); + assert!(!text.contains("dc:subject") && !text.contains("lr:hierarchicalSubject"), "clearing keywords clears both lists:\n{text}"); + s.execute("edit.undo", &json!({})).unwrap(); // undo rewrites the sidecar with the three keywords + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.keywords, ["Places|Italy|Rome", "sunset", "people|Ada"], "read back as written"); + + // a sidecar from LightCraft 0.13 (paths in dc:subject) reads as paths and is written properly + let old = KEYWORDED + .replace("PlacesItalyRome", "Places|Italy|Rome") + .replace("Places|Italy|Romesunset", ""); + std::fs::write(&sidecar, old).unwrap(); + s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.keywords, ["Places|Italy|Rome", "sunset"]); + s.execute("photo.rate", &json!({"ids": [id.0], "rating": 4})).unwrap(); + let (flat, hierarchical) = lists(&std::fs::read_to_string(&sidecar).unwrap()); + assert_eq!(flat, ["Places", "Italy", "Rome", "sunset"]); + assert_eq!(hierarchical, ["Places|Italy|Rome", "sunset"]); + let _ = std::fs::remove_dir_all(&src); +} + /// Lightroom's default profiles (`Adobe Standard`, `Adobe Color`) are named by nearly every sidecar /// and our own starting look stands in for them: importing one gives no camera-profile warning. #[test] @@ -1576,6 +1650,39 @@ fn files_sharing_a_stem_get_their_own_sidecars() { let _ = std::fs::remove_dir_all(&lib); } +/// A file that shares its stem with another catalogued file never reads the stem sidecar the +/// other one owns, whichever naming the library uses (issue #1523). +#[test] +fn a_non_owner_does_not_read_its_siblings_stem_sidecar() { + let src = temp_dir("stem-read"); + let lib = temp_dir("stem-read-lib"); + write_png(&src.join("IMG_1.png"), 1); + let img = lightcraft_raster::Rgba8::from_fn(40, 24, |x, y| [(x * 6) as u8, (y * 9) as u8, 7, 255]); + let jpg = + crate::export::encode_image(&img, &crate::export::ExportOptions { format: crate::export::ExportFormat::Jpeg, ..Default::default() }).unwrap(); + std::fs::write(src.join("IMG_1.jpg"), jpg).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = |s: &Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().id; + let (j, p) = (id(&s, "IMG_1.jpg"), id(&s, "IMG_1.png")); + s.execute("photo.rate", &json!({"ids": [j.0], "rating": 2})).unwrap(); + s.execute("photo.saveMetadataToFile", &json!({"ids": [j.0]})).unwrap(); + assert!(src.join("IMG_1.xmp").is_file()); + assert!(!src.join("IMG_1.png.xmp").exists()); + for naming in [crate::sidecar::SidecarNaming::Stem, crate::sidecar::SidecarNaming::Full] { + s.xmp.naming = naming; + // the owner reads its packet; the other file has none of its own + assert!(s.read_sidecar_op(j).unwrap().is_some(), "{naming:?}"); + assert!(s.read_sidecar_op(p).unwrap().is_none(), "{naming:?}"); + let (jpg_file, png_file) = (src.join("IMG_1.jpg"), src.join("IMG_1.png")); + assert_eq!(s.sidecar_lookup(j).find(&jpg_file.to_string_lossy()), Some(src.join("IMG_1.xmp")), "{naming:?}"); + assert_eq!(s.sidecar_lookup(p).find(&png_file.to_string_lossy()), None, "{naming:?}"); + } + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&lib); +} + /// Lossy DNG export: demosaiced JPEG tiles at the resize long edge, smaller than lossless, colour tags kept. #[test] fn lossy_dng_export_scales_and_shrinks() { diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index dbfb0fade6..73ec0352b2 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -158,8 +158,18 @@ pub fn filter_chips(f: &Filter, cat: &Catalog) -> Vec { }; add(format!("Rating {op} {}★", f.rating), json!({"rating": 0})); } - if let Some(fl) = f.flag { - add(format!("Flag: {}", format!("{fl:?}").to_lowercase()), json!({"flag": Null})); + if let Some(shown) = f.flags_shown() { + let name = |fl: &lightcraft_catalog::Flag| format!("{fl:?}").to_lowercase(); + let or = |fls: &[lightcraft_catalog::Flag]| fls.iter().map(name).collect::>().join(" or "); + // empty: `flag` and `flags` exclude each other, so name both constraints + let names = if shown.is_empty() { + // parenthesised when plural, so "pick and reject or none" cannot read as "(pick and reject) or none" + let plural = if f.flags.len() > 1 { format!("({})", or(&f.flags)) } else { or(&f.flags) }; + format!("{} and {plural}", f.flag.as_ref().map(name).unwrap_or_default()) + } else { + or(&shown) + }; + add(format!("Flag: {names}"), json!({"flag": Null, "flags": []})); } if let Some(shown) = f.labels_shown() { let or = |ls: &[lightcraft_catalog::ColorLabel]| ls.iter().map(|l| cat.label_name(*l)).collect::>().join(" or "); diff --git a/crates/faces/src/matching.rs b/crates/faces/src/matching.rs index de50ad3e47..d4f1e5484d 100644 --- a/crates/faces/src/matching.rs +++ b/crates/faces/src/matching.rs @@ -32,10 +32,24 @@ pub fn cosine(a: &[f32], b: &[f32]) -> Option { if a.len() != b.len() || a.is_empty() { return None; } - let d: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); + let d = dot(a, b); d.is_finite().then_some(d) } +/// The dot product of two vectors of the same length, summed in eight lanes so the compiler can use the processor's +/// vector instructions (one running sum can't be: each addition waits for the one before). Some four times faster on +/// 512-long embeddings; the result differs from a plain running sum only in the last bits. +fn dot(a: &[f32], b: &[f32]) -> f32 { + let mut lanes = [0f32; 8]; + let ((ca, ra), (cb, rb)) = (a.as_chunks::<8>(), b.as_chunks::<8>()); + for (x, y) in ca.iter().zip(cb) { + for ((l, x), y) in lanes.iter_mut().zip(x).zip(y) { + *l += x * y; + } + } + lanes.iter().sum::() + ra.iter().zip(rb).map(|(x, y)| x * y).sum::() +} + /// Rank the people in `gallery` (a name and one face's embedding per entry; a person appears once per face), /// best first. Names are compared case-insensitively and shown as first seen. pub fn rank(query: &[f32], gallery: &[(&str, &[f32])]) -> Vec { @@ -60,6 +74,31 @@ pub fn rank(query: &[f32], gallery: &[(&str, &[f32])]) -> Vec { out } +/// One person's score for `query`, as [`rank`] gives it, when all of `gallery` is that person: the mean of the `top` +/// (1 to 8) faces most like it, or of all of them when they have fewer. `None` when no face compares. Made for scoring +/// many faces against one person: no names to group by and nothing allocated, so it can run on every core. +pub fn person_score(query: &[f32], gallery: &[&[f32]], top: usize) -> Option { + const MOST: usize = 8; + let top = top.clamp(1, MOST); + // the best similarities so far, highest first + let mut best = [f32::NEG_INFINITY; MOST]; + let mut seen = 0usize; + for face in gallery { + let Some(c) = cosine(query, face) else { continue }; + seen += 1; + if c > best[top - 1] { + let mut i = top - 1; + while i > 0 && best[i - 1] < c { + best[i] = best[i - 1]; + i -= 1; + } + best[i] = c; + } + } + let n = seen.min(top); + (n > 0).then(|| best[..n].iter().sum::() / n as f32) +} + /// The best person if they pass both bars: a score of at least `threshold`, and at least `margin` ahead of the /// next person (when there is one). pub fn suggest(ranked: &[Ranked], threshold: f32, margin: f32) -> Option { @@ -95,6 +134,37 @@ mod tests { assert_eq!(r2[0].name, "Di", "{r2:?}"); } + #[test] + fn a_persons_score_is_the_one_ranking_gives_them() { + // pseudo-random unit vectors, the same on every run + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5 + }; + let mut face = || unit(&(0..16).map(|_| next()).collect::>()); + let gallery: Vec> = (0..40).map(|_| face()).collect(); + let refs: Vec<&[f32]> = gallery.iter().map(Vec::as_slice).collect(); + let named: Vec<(&str, &[f32])> = refs.iter().map(|e| ("Ann", *e)).collect(); + for _ in 0..50 { + let q = face(); + let ranked = rank(&q, &named); + let score = person_score(&q, &refs, TOP_FACES).unwrap(); + assert!((score - ranked[0].score).abs() < 1e-6, "{score} against {}", ranked[0].score); + } + // fewer faces than asked, bad embeddings skipped, nothing to compare, and any count + let q = face(); + assert!((person_score(&q, &refs[..1], 4).unwrap() - cosine(&q, refs[0]).unwrap()).abs() < 1e-6); + let nan = [f32::NAN; 16]; + assert_eq!(person_score(&q, &[&nan[..], refs[0]], 2), person_score(&q, &refs[..1], 2)); + assert_eq!(person_score(&q, &[], 2), None); + assert_eq!(person_score(&q, &[&nan[..]], 2), None); + assert_eq!(person_score(&q, &refs, 0), person_score(&q, &refs, 1)); + assert_eq!(person_score(&q, &refs, 1000), person_score(&q, &refs, 8)); + } + #[test] fn a_suggestion_needs_a_strong_match_clearly_ahead() { let r = |name: &str, score: f32| Ranked { name: name.into(), score, faces: 1 }; diff --git a/crates/fetch/src/http.rs b/crates/fetch/src/http.rs index c95478388a..f5ae5e410a 100644 --- a/crates/fetch/src/http.rs +++ b/crates/fetch/src/http.rs @@ -137,7 +137,8 @@ impl Url { } }; let port = match port { - Some(p) => p.parse::().ok().filter(|p| *p != 0).ok_or_else(|| bad("bad port"))?, + Some(p) if p.bytes().all(|b| b.is_ascii_digit()) => p.parse::().ok().filter(|p| *p != 0).ok_or_else(|| bad("bad port"))?, + Some(_) => return Err(bad("bad port")), None if tls => 443, None => 80, }; @@ -519,7 +520,8 @@ impl Response { if *left == 0 { let line = self.conn.line(1024, limits)?; let hex = line.split(';').next().unwrap_or_default().trim(); - let size = u64::from_str_radix(hex, 16).map_err(|_| HttpError::Protocol(format!("bad chunk size `{hex}`")))?; + let size = if hex.bytes().all(|b| b.is_ascii_hexdigit()) { u64::from_str_radix(hex, 16).ok() } else { None } + .ok_or_else(|| HttpError::Protocol(format!("bad chunk size `{hex}`")))?; if size == 0 { // trailers, up to the empty line let mut n = 0; @@ -595,7 +597,10 @@ pub fn get(url: &Url, headers: &[(&str, String)], limits: &Limits) -> Result().map_err(|_| HttpError::Protocol(format!("bad Content-Length `{n}`")))?) + // RFC 9110: `1*DIGIT`; `u64::from_str` alone would also take a leading '+' + let v = n.trim(); + let len = if !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()) { v.parse::().ok() } else { None }; + BodyMode::Length(len.ok_or_else(|| HttpError::Protocol(format!("bad Content-Length `{n}`")))?) } else { BodyMode::Close }; @@ -652,6 +657,29 @@ mod tests_connect { assert!(r.is_err()); assert!(t.elapsed() < Duration::from_millis(1500), "{:?}", t.elapsed()); } + + /// Content-Length is `1*DIGIT`: a sign, hex prefix, trailing junk or empty value is refused, not read as a length. + #[test] + fn signed_or_malformed_content_length_is_refused() { + for value in ["+3", "-3", "3x", "", "0x10", "+0"] { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let (mut s, _) = listener.accept().unwrap(); + let mut buf = [0u8; 1024]; + let _ = s.read(&mut buf); + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {value}\r\n\r\nabc").as_bytes()); + }); + let cancel = AtomicBool::new(false); + let url = Url::parse(&format!("http://127.0.0.1:{port}/f")).unwrap(); + match get(&url, &[], &limits(&cancel)) { + Err(HttpError::Protocol(m)) => assert!(m.contains("bad Content-Length"), "{value:?}: {m}"), + Err(e) => panic!("{value:?}: unexpected error {e:?}"), + Ok(r) => panic!("{value:?}: malformed Content-Length accepted (status {})", r.status), + } + server.join().unwrap(); + } + } } #[cfg(test)] @@ -713,6 +741,15 @@ mod tests { } } + #[test] + fn rejects_signed_ports() { + for bad in ["http://example.com:+80/x", "http://example.com:-80/x", "http://[::1]:+80/x"] { + assert!(Url::parse(bad).is_err(), "{bad}"); + } + assert!(Url::parse("http://a.test/").unwrap().join("http://example.com:+80/x").is_err()); + assert_eq!(Url::parse("http://example.com:80/x").unwrap().port, 80); + } + #[test] fn rejects_text_after_a_bracketed_ipv6_host() { for bad in ["http://[::1]junk/x", "https://[::1]junk/x", "http://[::1]8080/x", "http://[::1]8080"] { diff --git a/crates/fetch/src/lib.rs b/crates/fetch/src/lib.rs index 12daff541f..07552e4bb3 100644 --- a/crates/fetch/src/lib.rs +++ b/crates/fetch/src/lib.rs @@ -466,16 +466,25 @@ fn parse_content_range(v: &str) -> Option<(u64, Option)> { let v = v.trim().strip_prefix("bytes")?.trim(); let (range, total) = v.split_once('/')?; let (a, b) = range.split_once('-')?; - let (a, b) = (a.trim().parse::().ok()?, b.trim().parse::().ok()?); + let (a, b) = (digits(a)?, digits(b)?); if b < a { return None; } let total = match total.trim() { "*" => None, - t => Some(t.parse::().ok()?), + t => Some(digits(t)?), }; Some((a, total)) } +/// A non-empty run of ASCII digits as a `u64` (no sign, unlike `str::parse`). +fn digits(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + s.parse().ok() +} + #[cfg(test)] mod tests; diff --git a/crates/fetch/src/tests.rs b/crates/fetch/src/tests.rs index 08f869dcca..5144bfc097 100644 --- a/crates/fetch/src/tests.rs +++ b/crates/fetch/src/tests.rs @@ -86,6 +86,9 @@ fn handle(mut s: TcpStream, hits: &AtomicUsize) { b.extend_from_slice(&[7u8; 5000]); send(&mut s, "200 OK", "", &b) } + "signedchunk" => { + let _ = s.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n+5\r\nhello\r\n0\r\n\r\n"); + } "chunked" => { let _ = s.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n"); for c in body.chunks(70_001) { @@ -249,6 +252,16 @@ fn a_416_or_a_bad_complete_part_starts_over() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn signed_chunk_size_is_rejected() { + let srv = server(); + let dir = tmp("signedchunk"); + let f = FileSpec { name: "vocab.json", size: None, sha256: None, max: 1 << 20 }; + let r = run(&[f], &[format!("{}/signedchunk", srv.base)], &dir, &AtomicBool::new(false)).0; + assert!(r.is_err(), "a chunk size of `+5` was accepted"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn chunked_bodies_and_unpinned_files() { let srv = server(); @@ -335,6 +348,10 @@ fn content_ranges() { assert_eq!(parse_content_range("bytes 0-0/*"), Some((0, None))); assert_eq!(parse_content_range("bytes 9-1/300"), None); assert_eq!(parse_content_range("items 1-2/3"), None); + assert_eq!(parse_content_range("bytes +100-+299/+300"), None); + assert_eq!(parse_content_range("bytes 100-+299/300"), None); + assert_eq!(parse_content_range("bytes 100-299/+300"), None); + assert_eq!(parse_content_range("bytes 1-/3"), None); } /// A bearer token goes only to https, only to the host the download began at, and only when there is one. diff --git a/crates/geom/src/crop.rs b/crates/geom/src/crop.rs index cc26b40fe5..4dc25d1ba4 100644 --- a/crates/geom/src/crop.rs +++ b/crates/geom/src/crop.rs @@ -44,6 +44,31 @@ impl CropGeometry { Affine::rotate_about(-self.angle.to_radians(), c) * to_rot } + /// This crop with values no crop tool can produce taken out, for settings read from a file or an + /// agent (issue #2555): the angle within ±45° (not finite: 0), and the rect clipped to the + /// bounding box of the image turned by that angle, which holds every crop that stays on the + /// photo, so a real crop is unchanged while one reaching far past the photo can no longer make + /// a full-size output of billions of pixels. A rect with nothing left (reversed, or not finite) + /// is the whole frame. + pub fn bounded(&self, w: f64, h: f64) -> CropGeometry { + let angle = if self.angle.is_finite() { self.angle.clamp(-45.0, 45.0) } else { 0.0 }; + let (sin, cos) = angle.to_radians().sin_cos(); + let (bw, bh) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs()); + let bbox = Rect::from_center(Point::new(w / 2.0, h / 2.0), bw, bh); + let r = self.rect_px(w, h); + let finite = [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); + let inside = r.x0 >= bbox.x0 && r.y0 >= bbox.y0 && r.x1 <= bbox.x1 && r.y1 <= bbox.y1; + // a reversed rect (right edge left of its left edge, or bottom above top) has a negative size + let ordered = r.x0 <= r.x1 && r.y0 <= r.y1; + if finite && inside && ordered { + // left exactly as stored: a round trip through pixels would change its last bits + return CropGeometry { rect: self.rect, angle }; + } + let rect = if finite { r.intersect(&bbox) } else { Rect::new(0.0, 0.0, 0.0, 0.0) }; + let rect = if rect.is_empty() || w <= 0.0 || h <= 0.0 { Rect::UNIT } else { rect.scale(1.0 / w, 1.0 / h) }; + CropGeometry { rect, angle } + } + /// Whether every crop corner lies within the rotated image. pub fn is_within_image(&self, w: f64, h: f64) -> bool { let r = self.rect_px(w, h); @@ -176,6 +201,41 @@ pub fn crop_fit_angle(w: f64, h: f64, angle_deg: f64, aspect: Option) -> Cr mod tests { use super::*; + /// Issue #2555: `bounded` leaves every crop that stays on the photo exactly as it was, and + /// clips one reaching far past it to the turned photo's bounding box. + #[test] + fn bounded_keeps_real_crops_and_clips_the_rest() { + for (w, h) in [(6000.0, 4000.0), (4000.0, 6000.0), (9000.0, 1000.0)] { + for angle in [-45.0, -12.5, 0.0, 0.1, 7.0, 45.0] { + for aspect in [None, Some(1.0), Some(3.0), Some(0.25)] { + let real = crop_fit_angle(w, h, angle, aspect); + assert_eq!(real.bounded(w, h), real, "{w}x{h} {angle} {aspect:?}"); + } + } + assert_eq!(CropGeometry::default().bounded(w, h), CropGeometry::default()); + } + let (w, h) = (6000.0, 4000.0); + let wild = CropGeometry { rect: Rect::new(0.0, 0.0, 1000.0, 1000.0), angle: 5.0 }; + let b = wild.bounded(w, h).rect_px(w, h); + assert!(b.width() <= w * 1.5 && b.height() <= h * 1.5, "{b:?}"); + // angle beyond the tools' range, or not a number; a rect that is not a number + assert_eq!(CropGeometry { rect: Rect::UNIT, angle: 400.0 }.bounded(w, h).angle, 45.0); + assert_eq!(CropGeometry { rect: Rect::UNIT, angle: f64::NAN }.bounded(w, h).angle, 0.0); + let nan = CropGeometry { rect: Rect::new(f64::NAN, 0.0, 1.0, 1.0), angle: 3.0 }.bounded(w, h); + assert_eq!(nan.rect, Rect::UNIT); + // a crop entirely off the turned photo has nothing left: the whole frame + let off = CropGeometry { rect: Rect::new(50.0, 50.0, 60.0, 60.0), angle: 10.0 }.bounded(w, h); + assert_eq!(off.rect, Rect::UNIT); + // a reversed rect inside the photo is the whole frame, never a negative size + let reversed = CropGeometry { rect: Rect::new(0.8, 0.2, 0.2, 0.8), angle: 0.0 }.bounded(w, h); + assert_eq!(reversed.rect, Rect::UNIT); + let flipped = CropGeometry { rect: Rect::new(0.2, 0.8, 0.8, 0.2), angle: 3.0 }.bounded(w, h); + assert_eq!(flipped.rect, Rect::UNIT); + // a zero-size crop is left as it was + let line = CropGeometry { rect: Rect::new(0.5, 0.2, 0.5, 0.8), angle: 0.0 }; + assert_eq!(line.bounded(w, h), line); + } + #[test] fn identity_maps_pixels() { let c = CropGeometry::default(); diff --git a/crates/geom/src/crop_drag.rs b/crates/geom/src/crop_drag.rs index cdffa7cced..d9c67141fe 100644 --- a/crates/geom/src/crop_drag.rs +++ b/crates/geom/src/crop_drag.rs @@ -114,7 +114,10 @@ pub fn drag_crop(start: CropGeometry, handle: CropHandle, grab: Point, pointer: }; // straightened, go to the nearest place that fits, so the frame slides along tilted edges (#2299) let nearest = if base.angle != 0.0 { - let from = |r: Rect| nearest_move(r, base.angle, w, h, Vec2::new(dx, dy)).map(|v| r.translate(v)).filter(|r| feasible(*r)); + let from = |r: Rect| { + let corners = r.corners().map(|c| (c, Vec2::new(1.0, 1.0))); + nearest_offset(&corners, &[], base.angle, w, h, Vec2::new(dx, dy)).map(|v| r.translate(v)).filter(|r| feasible(*r)) + }; // a frame at the tolerance's edge on opposite sides moves only once it is inside it from(sr).or_else(|| shrunk_inside(sr, base.angle, w, h).and_then(from)) } else { @@ -138,8 +141,14 @@ pub fn drag_crop(start: CropGeometry, handle: CropHandle, grab: Point, pointer: let at = |t: f64| lerp_rect(cur, target, t); at(bisect(0.0, 1.0, |t| feasible(at(t)))) }; - let cur = grow(sr, dx, 0.0); - grow(cur, 0.0, dy) + // straightened, a free corner goes to the nearest place that fits, growing both sides (#2308) + let corner = (mx0 || mx1) && (my0 || my1); + let nearest = + if base.angle != 0.0 && corner { nearest_corner(sr, mx0, my0, base.angle, (w, h), min_side, Vec2::new(dx, dy)) } else { None }; + match nearest.filter(|r| feasible(*r)) { + Some(r) => r, + None => grow(grow(sr, dx, 0.0), 0.0, dy), + } } (hd, Some(a)) => { let (mx0, _, my0, _) = sides(hd); @@ -212,20 +221,22 @@ pub fn drag_crop(start: CropGeometry, handle: CropHandle, grab: Point, pointer: if [rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) { CropGeometry { rect, angle: base.angle } } else { start } } -/// The translation (pixels) nearest `want` that keeps the frame `r` inside a `w × h` image turned by `angle` degrees. -fn nearest_move(r: Rect, angle: f64, w: f64, h: f64, want: Vec2) -> Option { +/// The offset `v` (pixels) nearest `want` that keeps each `p + m ⊙ v` inside a `w × h` image turned by `angle` +/// degrees and meets the `extra` half-planes `n · v <= b`. +fn nearest_offset(points: &[(Point, Vec2)], extra: &[(Vec2, f64)], angle: f64, w: f64, h: f64, want: Vec2) -> Option { let back = Affine::rotate_about(-angle.to_radians(), Point::new(w / 2.0, h / 2.0)); let (ex, ey) = (back.apply_vec(Vec2::new(1.0, 0.0)), back.apply_vec(Vec2::new(0.0, 1.0))); - let (nx, ny) = (Vec2::new(ex.x, ey.x), Vec2::new(ex.y, ey.y)); // never tighter than where the frame is, plus a slack so a zero-width strip survives rounding let (sx, sy) = (1e-9 * w, 1e-9 * h); - let mut planes = Vec::with_capacity(16); - for c in r.corners() { - let q = back.apply(c); + let mut planes = Vec::with_capacity(4 * points.len() + extra.len()); + for (p, m) in points { + let q = back.apply(*p); + let (nx, ny) = (Vec2::new(ex.x * m.x, ey.x * m.y), Vec2::new(ex.y * m.x, ey.y * m.y)); for (n, b, s) in [(nx, w - q.x, sx), (-nx, q.x, sx), (ny, h - q.y, sy), (-ny, q.y, sy)] { planes.push((n, b.max(0.0) + s)); } } + planes.extend_from_slice(extra); if planes.iter().all(|(n, b)| n.dot(want) <= *b) { return Some(want); } @@ -261,6 +272,26 @@ fn shrunk_inside(r: Rect, angle: f64, w: f64, h: f64) -> Option { inside(lo).then(|| scaled(bisect_range(lo, 1.0, inside))) } +/// The frame `r` (pixels) with a corner dragged by `want`, the opposite one held, at the nearest place that fits. +fn nearest_corner(r: Rect, left: bool, top: bool, angle: f64, (w, h): (f64, f64), min_side: f64, want: Vec2) -> Option { + let anchor = Point::new(if left { r.x1 } else { r.x0 }, if top { r.y1 } else { r.y0 }); + let corner = Point::new(if left { r.x0 } else { r.x1 }, if top { r.y0 } else { r.y1 }); + let points = + [(corner, Vec2::new(1.0, 1.0)), (Point::new(corner.x, anchor.y), Vec2::new(1.0, 0.0)), (Point::new(anchor.x, corner.y), Vec2::new(0.0, 1.0))]; + let (sx, sy) = (if left { -1.0 } else { 1.0 }, if top { -1.0 } else { 1.0 }); + // at least `min_side`, and per axis only between where it is and where the pointer asks + let extra = [ + (Vec2::new(-sx, 0.0), sx * (corner.x - anchor.x) - min_side), + (Vec2::new(0.0, -sy), sy * (corner.y - anchor.y) - min_side), + (Vec2::new(1.0, 0.0), want.x.max(0.0)), + (Vec2::new(-1.0, 0.0), (-want.x).max(0.0)), + (Vec2::new(0.0, 1.0), want.y.max(0.0)), + (Vec2::new(0.0, -1.0), (-want.y).max(0.0)), + ]; + let v = nearest_offset(&points, &extra, angle, w, h, want)?; + Some(Rect::from_points(anchor, corner + v)) +} + /// The part of the convex polygon `poly` where `n · v <= b`. fn clip_half_plane(poly: &[Vec2], n: Vec2, b: f64) -> Vec { let mut out = Vec::with_capacity(poly.len() + 1); diff --git a/crates/geom/src/crop_drag/tests.rs b/crates/geom/src/crop_drag/tests.rs index cf57c67cb5..9b81027e43 100644 --- a/crates/geom/src/crop_drag/tests.rs +++ b/crates/geom/src/crop_drag/tests.rs @@ -301,3 +301,66 @@ fn given_a_small_frame_pushed_past_a_tilted_edge_then_it_stops_on_the_edge_and_s } assert!(b.rect.y0 > a.rect.y0 + 0.01 && a.rect.y0 > start.rect.y0, "{:?} then {:?}", a.rect, b.rect); } + +// Scenario: a free corner dragged diagonally out on a straightened photo (issue #2308) +#[test] +fn given_straightened_photo_when_a_free_corner_is_dragged_out_diagonally_then_both_sides_grow() { + for angle in [6.0, 12.0] { + let start = CropGeometry { rect: Rect::new(0.3, 0.3, 0.6, 0.6), angle }; + let g = drag(start, BottomRight, p(0.6, 0.6), p(1.2, 1.2), None); + assert!(g.is_within_image(W, H), "{angle}: {:?}", g.rect); + assert!(near(g.rect.x0, 0.3) && near(g.rect.y0, 0.3), "{angle}: the anchor corner stays: {:?}", g.rect); + // both sides grow (main stops at y1 0.600) + assert!(g.rect.x1 > 0.9 && g.rect.y1 > 0.9, "{angle}: one side only: {:?}", g.rect); + let further = drag(g, BottomRight, p(g.rect.x1, g.rect.y1), p(1.2, 1.2), None); + assert!((further.rect.x1 - g.rect.x1).abs() < 1e-4 && (further.rect.y1 - g.rect.y1).abs() < 1e-4, "{angle}: {:?}", further.rect); + } + let start = CropGeometry { rect: Rect::new(0.3, 0.3, 0.6, 0.6), angle: 8.0 }; + for (hd, from, to) in [(TopLeft, p(0.3, 0.3), p(-0.5, -0.5)), (TopRight, p(0.6, 0.3), p(1.5, -0.5)), (BottomLeft, p(0.3, 0.6), p(-0.5, 1.5))] { + let g = drag(start, hd, from, to, None); + assert!(g.is_within_image(W, H), "{hd:?}: {:?}", g.rect); + assert!(g.rect.width() > 0.5 && g.rect.height() > 0.45, "{hd:?}: one side only: {:?}", g.rect); + let (ax, ay) = (if from.x < 0.5 { g.rect.x1 } else { g.rect.x0 }, if from.y < 0.5 { g.rect.y1 } else { g.rect.y0 }); + assert!(near(ax, if from.x < 0.5 { 0.6 } else { 0.3 }) && near(ay, if from.y < 0.5 { 0.6 } else { 0.3 }), "{hd:?}: {:?}", g.rect); + } +} + +// Scenario: a free corner pushed along one axis past a tilted edge on a straightened photo +#[test] +fn given_straightened_photo_when_a_free_corner_is_pushed_sideways_past_an_edge_then_the_other_side_keeps_its_size() { + for angle in [6.0, 12.0, -8.0] { + let start = CropGeometry { rect: Rect::new(0.3, 0.3, 0.6, 0.6), angle }; + let g = drag(start, BottomRight, p(0.6, 0.6), p(1.3, 0.6), None); + assert!(g.is_within_image(W, H), "{angle}: {:?}", g.rect); + assert!(near(g.rect.y1, 0.6) && near(g.rect.x0, 0.3) && near(g.rect.y0, 0.3), "{angle}: the height changed: {:?}", g.rect); + assert!(g.rect.x1 > 0.85, "{angle}: it stopped short of the edge: {:?}", g.rect); + let g = drag(start, BottomRight, p(0.6, 0.6), p(0.6, 1.3), None); + assert!(near(g.rect.x1, 0.6) && g.rect.y1 > 0.8, "{angle}: the width changed: {:?}", g.rect); + } +} + +// Scenario: a free corner of a crop under the minimum size on a straightened photo +#[test] +fn given_straightened_photo_when_a_corner_of_a_too_small_crop_is_dragged_then_it_reaches_the_minimum() { + let start = CropGeometry { rect: Rect::new(0.3, 0.3, 0.3 + 2.0 / W, 0.6), angle: 6.0 }; + let g = drag(start, BottomRight, p(start.rect.x1, 0.6), p(start.rect.x1 + 2.0 / W, 0.62), None); + assert!(g.rect.width() * W >= MIN_CROP_FRACTION * H - EPS, "{:?}", g.rect); + assert!(g.is_within_image(W, H) && near(g.rect.x0, 0.3) && near(g.rect.y0, 0.3), "{:?}", g.rect); +} + +// Scenario: a free corner moved inside, or across its anchor, on a straightened photo +#[test] +fn given_straightened_photo_when_a_free_corner_moves_inside_then_it_follows_and_keeps_a_minimum_size() { + let start = CropGeometry { rect: Rect::new(0.3, 0.3, 0.6, 0.6), angle: 8.0 }; + let g = drag(start, BottomRight, p(0.6, 0.6), p(0.7, 0.55), None); + assert!(near(g.rect.x1, 0.7) && near(g.rect.y1, 0.55) && near(g.rect.x0, 0.3) && near(g.rect.y0, 0.3), "{:?}", g.rect); + let z = drag(start, BottomRight, p(0.6, 0.6), p(0.6, 0.6), None).rect; + assert!(near(z.x1, 0.6) && near(z.y1, 0.6), "a click moves nothing: {z:?}"); + let crossed = drag(start, BottomRight, p(0.6, 0.6), p(0.0, 0.0), None); + assert!(near(crossed.rect.x0, 0.3) && near(crossed.rect.y0, 0.3), "{:?}", crossed.rect); + assert!( + crossed.rect.width() * W >= MIN_CROP_FRACTION * H - EPS && crossed.rect.height() * H >= MIN_CROP_FRACTION * H - EPS, + "{:?}", + crossed.rect + ); +} diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 7bbbbc68d4..d3e56f7491 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -1,9 +1,7 @@ //! The wgpu device, the compiled kernels, buffers, dispatch and readback. use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; - -use wgpu::util::DeviceExt; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; /// A kernel module: WGSL source, its storage bindings (name, writable, element type) after the /// parameter block `P` (binding 0), and its entry points. @@ -77,6 +75,102 @@ struct Kernel { nbuf: usize, } +/// A module's shader and layouts, shared by the kernels of its entry points. +struct Prepared { + module: wgpu::ShaderModule, + layout: wgpu::BindGroupLayout, + pipeline_layout: wgpu::PipelineLayout, + nbuf: usize, +} + +/// Validation and internal error scopes. They belong to the thread that pushed them. +fn push_scopes(device: &wgpu::Device) -> [wgpu::ErrorScopeGuard; 2] { + [device.push_error_scope(wgpu::ErrorFilter::Validation), device.push_error_scope(wgpu::ErrorFilter::Internal)] +} + +/// The error the scopes caught, if any (popped innermost first). +fn pop_scopes(scopes: [wgpu::ErrorScopeGuard; 2]) -> Option { + let [validation, internal] = scopes; + let (internal, validation) = (pollster::block_on(internal.pop()), pollster::block_on(validation.pop())); + internal.or(validation).map(|e| e.to_string()) +} + +/// Build every kernel. A kernel the driver's compiler refuses is a validation or an internal error, +/// and then there is no GPU, not a half-built one. +/// +/// Issue #2936: built one after another, the 27 pipelines took ~2.2 s on an Intel iGPU under DX12 +/// (device start-up 1.7–4.4 s in all, 7 s on the first run after an install), where FXC (issue #471) +/// compiles each one, single-threaded, inside `create_compute_pipeline`. The +/// device takes pipeline creation from any thread, so the entry points are shared out to worker +/// threads. This thread works too: every kernel is built even when no thread can be started. +fn build_kernels(device: &wgpu::Device) -> Result, String> { + let scopes = push_scopes(device); + let consts = constants(); + let prepared: Vec = MODULES + .iter() + .map(|m| { + let src = module_source(m, &consts); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(src.into()) }); + let mut entries = vec![storage_entry(0, true)]; + entries.extend(m.bindings.iter().enumerate().map(|(i, (_, w, _))| storage_entry(i as u32 + 1, !w))); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + Prepared { module, layout, pipeline_layout, nbuf: m.bindings.len() } + }) + .collect(); + if let Some(e) = pop_scopes(scopes) { + return Err(e); + } + let jobs: Vec<(&Prepared, &'static str)> = MODULES.iter().zip(&prepared).flat_map(|(m, p)| m.entries.iter().map(move |e| (p, *e))).collect(); + let next = AtomicUsize::new(0); + let built = std::sync::Mutex::new(HashMap::with_capacity(jobs.len())); + let workers = std::thread::available_parallelism().map_or(1, |n| n.get()).min(jobs.len()).saturating_sub(1); + let errors: Vec = std::thread::scope(|s| { + let work = || build_jobs(device, &jobs, &next, &built); + let threads: Vec<_> = + (0..workers).filter_map(|_| std::thread::Builder::new().name("lc-gpu-kernels".into()).spawn_scoped(s, work).ok()).collect(); + let mut errors: Vec = work().into_iter().collect(); + for t in threads { + match t.join() { + Ok(e) => errors.extend(e), + Err(_) => errors.push("a kernel build thread panicked".into()), + } + } + errors + }); + if let Some(e) = errors.into_iter().next() { + return Err(e); + } + Ok(built.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner)) +} + +/// One worker of [`build_kernels`]: build kernels until none is left; the first error its scopes caught. +fn build_jobs( + device: &wgpu::Device, + jobs: &[(&Prepared, &'static str)], + next: &AtomicUsize, + built: &std::sync::Mutex>, +) -> Option { + let scopes = push_scopes(device); + while let Some(&(p, entry)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&p.pipeline_layout), + module: &p.module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }); + let kernel = Kernel { pipeline, layout: p.layout.clone(), nbuf: p.nbuf }; + built.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(entry, kernel); + } + pop_scopes(scopes) +} + /// A device buffer of `len` 32-bit values. /// /// Dropped buffers are recycled: they first wait in a per-thread list (commands recorded on this @@ -339,39 +433,15 @@ impl Gpu { log::error!("gpu: device lost ({reason:?}): {msg}"); crate::mark_broken(&format!("device lost ({reason:?}): {msg}")); }); - // a kernel the driver's compiler refuses is a validation or an internal error: no GPU, not a half-built one - let scopes = [device.push_error_scope(wgpu::ErrorFilter::Validation), device.push_error_scope(wgpu::ErrorFilter::Internal)]; - let consts = constants(); - let mut kernels = HashMap::new(); - for m in MODULES { - let src = module_source(m, &consts); - let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(src.into()) }); - let mut entries = vec![storage_entry(0, true)]; - entries.extend(m.bindings.iter().enumerate().map(|(i, (_, w, _))| storage_entry(i as u32 + 1, !w))); - let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries }); - let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: None, - bind_group_layouts: &[Some(&layout)], - immediate_size: 0, - }); - for e in m.entries { - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some(e), - layout: Some(&pl), - module: &module, - entry_point: Some(e), - compilation_options: Default::default(), - cache: None, - }); - kernels.insert(*e, Kernel { pipeline, layout: layout.clone(), nbuf: m.bindings.len() }); + let started = std::time::Instant::now(); + let kernels = match build_kernels(&device) { + Ok(kernels) => kernels, + Err(e) => { + log::error!("gpu: kernels failed to build on {}: {e}", info.name); + return Err(format!("{}: kernels failed to build ({e})", info.name)); } - } - let [validation, internal] = scopes; - let (internal, validation) = (pollster::block_on(internal.pop()), pollster::block_on(validation.pop())); - if let Some(e) = internal.or(validation) { - log::error!("gpu: kernels failed to build on {}: {e}", info.name); - return Err(format!("{}: kernels failed to build ({e})", info.name)); - } + }; + let build_ms = started.elapsed().as_millis(); let dummy = device.create_buffer(&wgpu::BufferDescriptor { label: Some("dummy"), size: 16, @@ -379,7 +449,7 @@ impl Gpu { mapped_at_creation: false, }); let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); - log::info!("gpu: {} ({:?}), buffers ≤ {} MiB", info.name, info.backend, max_buffer >> 20); + log::info!("gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB", info.name, info.backend, kernels.len(), max_buffer >> 20); Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer }) } @@ -520,13 +590,41 @@ impl Gpu { } // (dropping the view schedules the copy) drop(view); - return Buf { buf: Some(Tracked::new(buf)), len }; + } else { + // recorded now, not only when the error scope pops: the zeroed buffer must not be + // shared before then (`render::shared_source`) + fail(FailKind::OutOfMemory, "out of device memory: the upload's staging buffer couldn't be allocated".into()); } + // no view: the buffer couldn't be allocated (out of device memory). The error scope has recorded why and + // the render fails over to the CPU; allocating it again would only fail again (issue #1764) + return Buf { buf: Some(Tracked::new(buf)), len }; } - let buf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: bytes, usage }); + let buf = self.init_buffer(bytes, usage); Buf { buf: Some(Tracked::new(buf)), len } } + /// A buffer holding `contents` (zero-padded to the copy alignment), written through the queue. Not + /// `create_buffer_init`: it maps the new buffer, and mapping one that couldn't be allocated (out of device + /// memory) panics inside wgpu instead of raising an error the render's scopes catch (issue #1764). + fn init_buffer(&self, contents: &[u8], usage: wgpu::BufferUsages) -> wgpu::Buffer { + let align = wgpu::COPY_BUFFER_ALIGNMENT as usize; + let size = contents.len().max(align).next_multiple_of(align); + let buf = self.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: size as u64, + usage: usage | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + if size == contents.len() { + self.queue.write_buffer(&buf, 0, contents); + } else { + let mut padded = contents.to_vec(); + padded.resize(size, 0); + self.queue.write_buffer(&buf, 0, &padded); + } + buf + } + fn over_limit(&self, size: u64) { fail( FailKind::Limit, @@ -570,11 +668,7 @@ impl Gpu { return; }; assert_eq!(bufs.len(), k.nbuf, "{name}: binding count"); - let params = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, - contents: bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }), - usage: wgpu::BufferUsages::STORAGE, - }); + let params = self.init_buffer(bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }), wgpu::BufferUsages::STORAGE); let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }]; for (i, b) in bufs.iter().enumerate() { let buf = b.map(|b| b.raw()).unwrap_or(&self.dummy); @@ -793,6 +887,17 @@ pub fn groups1(n: usize) -> [u32; 3] { #[cfg(test)] mod tests { + /// Every kernel module, as it is handed to the device (the generated constants, the bindings, `common.wgsl`, the + /// module), parses and validates without a GPU. + #[test] + fn every_kernel_module_validates_without_a_gpu() { + let consts = super::constants(); + for m in super::MODULES { + let name = m.entries.first().copied().unwrap_or("?"); + assert_eq!(crate::validate_wgsl(name, &super::module_source(m, &consts)), Ok(())); + } + } + #[test] fn limits_override_parses() { assert_eq!(super::parse_limits("webgpu"), Some((128 << 20, 256 << 20))); @@ -803,6 +908,20 @@ mod tests { assert_eq!(super::parse_limits("lots"), None); } + /// Issue #2936: the kernels are built on several threads; every entry point of every module has one. + #[test] + fn every_entry_point_has_a_kernel() { + let Some(g) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + let entries: Vec<&str> = super::MODULES.iter().flat_map(|m| m.entries.iter().copied()).collect(); + assert_eq!(g.kernels.len(), entries.len()); + for e in entries { + assert!(g.kernels.contains_key(e), "no kernel for {e}"); + } + } + /// Run `child` (an ignored test in this module) in its own process: it loses the device, which /// no other test running beside it may see. Returns its stdout, or `None` without a GPU. fn run_child(child: &str) -> Option { @@ -902,6 +1021,74 @@ mod tests { println!("CHILD: survived"); } + /// A render that runs out of device memory falls back to the CPU and leaves the GPU in use: the upload + /// whose buffer couldn't be allocated used to try again through `create_buffer_init`, which panicked + /// mapping the second failed buffer, and the panic stopped GPU use for the session (issue #1764). + #[test] + fn running_out_of_device_memory_falls_back_without_stopping_the_gpu() { + if run_child("out_of_memory_child").is_none() { + lightcraft_testkit::skip!(Gpu, "no GPU device, or its memory never ran out"); + } + } + + #[test] + #[ignore = "run in its own process by running_out_of_device_memory_falls_back_without_stopping_the_gpu"] + fn out_of_memory_child() { + let Some(g) = crate::device() else { + println!("CHILD: no GPU"); + return; + }; + // hold device memory until an allocation fails: 1 GiB at a time, then smaller, so little is + // left; no larger than the device allows in one buffer, which would be a validation error + let max = g.device.limits().max_buffer_size & !(wgpu::COPY_BUFFER_ALIGNMENT - 1); + let mut sizes: Vec = [1u64 << 30, 1 << 28, 1 << 26].into_iter().map(|s| s.min(max)).collect(); + sizes.dedup(); + let mut held = Vec::new(); + let mut full = false; + for size in sizes { + for _ in 0..128 { + let validation = g.device.push_error_scope(wgpu::ErrorFilter::Validation); + let oom = g.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let usage = wgpu::BufferUsages::STORAGE; + let buf = g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size, usage, mapped_at_creation: false }); + let ran_out = pollster::block_on(oom.pop()).is_some(); + if let Some(e) = pollster::block_on(validation.pop()) { + panic!("holding {size} bytes of device memory: {e}"); + } + if ran_out { + full = true; + break; + } + held.push(buf); + } + } + if !full { + println!("CHILD: no GPU (its memory never ran out)"); + return; + } + // a render that needs more than is left: a larger one when the driver still finds room for the first + let s = lightcraft_develop::DevelopSettings::default(); + let mut ran_out = false; + for (w, h) in [(4000, 3000), (8000, 6000)] { + let src = std::sync::Arc::new(lightcraft_raster::Rgb32f { width: w, height: h, data: vec![[0.18, 0.18, 0.18]; w * h] }); + let req = lightcraft_pipeline::RenderRequest::fit(w, h); + match crate::try_render(&src, &lightcraft_pipeline::SourceInfo::default(), &s, &req, None) { + Ok(_) => continue, + Err(crate::Fallback::Failed(reason)) => assert!(reason.contains("out of device memory"), "{reason}"), + Err(crate::Fallback::NotTried) => panic!("the GPU wasn't tried"), + } + ran_out = true; + break; + } + assert_eq!(crate::unavailable_reason(), None, "the GPU stays in use"); + drop(held); + if !ran_out { + println!("CHILD: no GPU (the renders found room anyway)"); + return; + } + println!("CHILD: survived"); + } + /// Empties the buffer pool when dropped, as the UI does (`trim_pool(0)`) and as returning a /// buffer to a full pool does. struct TrimOnDrop(&'static super::Gpu); diff --git a/crates/gpu/src/faces.rs b/crates/gpu/src/faces.rs index bee9929efc..9192677867 100644 --- a/crates/gpu/src/faces.rs +++ b/crates/gpu/src/faces.rs @@ -817,6 +817,13 @@ static PER_CONV: AtomicBool = AtomicBool::new(false); mod tests { use super::*; + /// The face detector's kernels validate without a GPU. + #[test] + fn the_face_kernels_validate_without_a_gpu() { + assert_eq!(crate::validate_wgsl("faces_conv", include_str!("wgsl/faces_conv.wgsl")), Ok(())); + assert_eq!(crate::validate_wgsl("faces_ops", include_str!("wgsl/faces_ops.wgsl")), Ok(())); + } + fn gpu() -> Option> { match accelerator() { Ok(a) => Some(a), diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 452e2dd672..51a8aa45bc 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -193,7 +193,9 @@ pub fn reset_failures() { /// Allow or forbid GPU rendering at runtime (a preference). `LIGHTCRAFT_GPU=0` forbids it for the /// whole process regardless. pub fn set_enabled(on: bool) { - ENABLED.store(on, Ordering::Relaxed); + // (SeqCst, as `warm_up`'s thread reads it after releasing its start: a switch back on is + // never missed there) + ENABLED.store(on, Ordering::SeqCst); } /// Whether GPU rendering is allowed (environment, preference, no earlier failure — real, or @@ -308,13 +310,33 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> { /// Create the device and compile the kernels on a background thread now (once the window is up), /// so the first render doesn't wait ~0.3–0.4 s for it and the UI thread never does. Does nothing -/// while GPU rendering is turned off. +/// while GPU rendering is turned off. Repeated calls start one thread at most. pub fn warm_up() { #[cfg(not(target_arch = "wasm32"))] - if !env_disabled() && ENABLED.load(Ordering::Relaxed) && GPU.get().is_none() { - let _ = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(|| { - let _ = device(); + if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() { + static STARTED: AtomicBool = AtomicBool::new(false); + if STARTED.swap(true, Ordering::SeqCst) { + return; + } + let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(|| { + loop { + let _ = device(); + if GPU.get().is_some() || shutting_down() || env_disabled() { + break; + } + // turned off before the thread ran (nothing created): a later call may start + // again. Released first, then the preference read again: a call made while this + // thread still held the flag (turned back on meanwhile) returned without starting + // one, so this thread tries again itself rather than leave "starting" for good. + STARTED.store(false, Ordering::SeqCst); + if !ENABLED.load(Ordering::SeqCst) || STARTED.swap(true, Ordering::SeqCst) { + break; + } + } }); + if spawned.is_err() { + STARTED.store(false, Ordering::SeqCst); + } } } @@ -520,6 +542,9 @@ pub fn try_render( format!("{what}: {}; the GPU is not used again", f.reason) } ctx::FailKind::OutOfMemory => { + // an upload that ran out of memory left a zeroed buffer; the shared source + // may be one, and the next render of the photo would reuse it + render::release_shared_source(); gpu.trim(0); format!("{what}: {}", f.reason) } @@ -550,10 +575,33 @@ pub fn try_render( } } +/// Tests: parse and validate a WGSL module with naga, as wgpu does before it hands a shader to the driver. Needs no +/// GPU, so kernels that don't build (a duplicate definition after a merge, a type error) fail every test run, not only +/// the GPU ones. +#[cfg(test)] +pub(crate) fn validate_wgsl(name: &str, src: &str) -> Result<(), String> { + use wgpu::naga; + let module = naga::front::wgsl::parse_str(src).map_err(|e| format!("{name}: {}", e.emit_to_string(src)))?; + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()) + .validate(&module) + .map(|_| ()) + .map_err(|e| format!("{name}: {}", e.emit_to_string(src))) +} + #[cfg(test)] mod tests { use lightcraft_pipeline::{OutputDepth, Overlay}; + /// The helper refuses what a driver would: a function defined twice (what an automatic merge of two branches + /// touching the same kernel can leave). + #[test] + fn wgsl_validation_catches_a_duplicate_definition() { + let ok = "fn f() -> f32 { return 1.0; }\n@compute @workgroup_size(1) fn main() { _ = f(); }\n"; + assert_eq!(super::validate_wgsl("ok", ok), Ok(())); + let twice = format!("fn f() -> f32 {{ return 2.0; }}\n{ok}"); + assert!(super::validate_wgsl("twice", &twice).is_err()); + } + // Given a request the 8-bit kernel can't draw (high bit depth, a soft proof, Visualize HDR), // the GPU doesn't take it; the loupe and diagnostic overlays it can draw stay on the GPU #[test] diff --git a/crates/gpu/src/nn.rs b/crates/gpu/src/nn.rs index c5df00a771..235ba9be68 100644 --- a/crates/gpu/src/nn.rs +++ b/crates/gpu/src/nn.rs @@ -652,15 +652,71 @@ impl Shared { } } +/// Workspaces not in use, and how many exist (free or with a tile in flight). +struct Slots { + free: Vec, + made: usize, +} + +/// Up to `cap` workspaces shared by the threads that run tiles. The free list and the count share one lock, so a caller +/// that finds none free and waits cannot miss one being given back or forgotten in between (issue #2577). +struct Workspaces { + slots: Mutex>, + wake: Condvar, + cap: usize, +} + +impl Workspaces { + fn new(first: T, cap: usize) -> Self { + Workspaces { slots: Mutex::new(Slots { free: vec![first], made: 1 }), wake: Condvar::new(), cap } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Slots> { + self.slots.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// A free workspace, a new one from `make` when fewer than `cap` exist, else wait for one to come back or be + /// forgotten. + fn take(&self, make: impl FnOnce() -> Result) -> Result { + let mut s = self.lock(); + loop { + if let Some(w) = s.free.pop() { + return Ok(w); + } + if s.made < self.cap { + s.made += 1; + drop(s); + let w = make(); + if w.is_err() { + self.forget(); + } + return w; + } + s = self.wake.wait(s).unwrap_or_else(|e| e.into_inner()); + } + } + + fn give(&self, w: T) { + self.lock().free.push(w); + self.wake.notify_one(); + } + + /// One workspace fewer exists: a waiting caller may make another. + fn forget(&self) { + let mut s = self.lock(); + s.made = s.made.saturating_sub(1); + drop(s); + self.wake.notify_one(); + } +} + /// A network on the GPU for one tile size. Cheap to share between threads: each call takes a free workspace. pub struct NetRunner { shared: Shared, tile: usize, in_channels: usize, - free: Mutex>, - /// Workspaces made so far (they are made when a call finds none free, up to [`WORKSPACES`]). - made: Mutex, - wake: Condvar, + /// Workspaces are made when a call finds none free, up to [`WORKSPACES`]. + workspaces: Workspaces, bytes: u64, } @@ -711,7 +767,7 @@ pub fn runner(net: &Net, tile: usize) -> Result { if let Some(e) = errors.into_iter().flatten().next() { return Err(format!("{}: the denoise kernels could not be set up ({e})", d.info.name)); } - Ok(NetRunner { shared, tile, in_channels: net.in_channels, free: Mutex::new(vec![first]), made: Mutex::new(1), wake: Condvar::new(), bytes }) + Ok(NetRunner { shared, tile, in_channels: net.in_channels, workspaces: Workspaces::new(first, WORKSPACES), bytes }) } impl NetRunner { @@ -732,45 +788,30 @@ impl NetRunner { /// A free workspace, a new one when fewer than [`WORKSPACES`] exist, else wait for one to come back. fn take(&self) -> Result { - let mut free = self.free.lock().unwrap_or_else(|e| e.into_inner()); - loop { - if let Some(w) = free.pop() { - return Ok(w); + self.workspaces.take(|| { + // a caller woken by the last tiles failing on a lost device makes nothing on it + if let Some(why) = broken_reason() { + return Err(Error::Runtime(format!("the GPU is not used any more: {why}"))); } - { - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - if *made < WORKSPACES { - *made += 1; - drop(made); - drop(free); - let d = self.shared.dev; - let scopes = - [d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), d.device.push_error_scope(wgpu::ErrorFilter::Validation)]; - let w = self.shared.workspace(); - let [oom, validation] = scopes; - let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); - if let Some(e) = oom.or(validation) { - self.forget(); - return Err(Error::Runtime(format!("the GPU could not make room for another tile: {e}"))); - } - return Ok(w); - } + let d = self.shared.dev; + let scopes = [d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), d.device.push_error_scope(wgpu::ErrorFilter::Validation)]; + let w = self.shared.workspace(); + let [oom, validation] = scopes; + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom.or(validation) { + return Err(Error::Runtime(format!("the GPU could not make room for another tile: {e}"))); } - free = self.wake.wait(free).unwrap_or_else(|e| e.into_inner()); - } + Ok(w) + }) } fn give(&self, w: Workspace) { - self.free.lock().unwrap_or_else(|e| e.into_inner()).push(w); - self.wake.notify_one(); + self.workspaces.give(w); } /// A workspace is gone (dropped after a failure): room for a new one, and a waiting caller may make it. fn forget(&self) { - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - *made = made.saturating_sub(1); - drop(made); - self.wake.notify_one(); + self.workspaces.forget(); } fn execute(&self, w: &Workspace, input: &[f32]) -> Result, Error> { @@ -884,6 +925,25 @@ impl TileRunner for NetRunner { #[cfg(test)] mod tests { use super::*; + + /// The denoise kernels validate without a GPU: the pooling kernel, and the convolution for every block size the + /// planner picks for these layer widths and channel counts. + #[test] + fn the_network_kernels_validate_without_a_gpu() { + assert_eq!(crate::validate_wgsl("nn_pool", include_str!("wgsl/nn_pool.wgsl")), Ok(())); + let mut sizes: Vec<(u32, u32, u32)> = Vec::new(); + for n in [1usize, 3, 8, 16, 24, 32, 48, 64, 96, 128, 256, 512] { + for cin in [1usize, 3, 4, 8, 16, 32, 48, 64, 128, 256, 512] { + let b = blocks(n, cin); + if !sizes.contains(&b) { + sizes.push(b); + } + } + } + for (bm, bn, bk) in sizes { + assert_eq!(crate::validate_wgsl(&format!("nn_conv {bm}x{bn}x{bk}"), &conv_source(bm, bn, bk)), Ok(())); + } + } use lightcraft_denoise::{onnx, reference, synthetic}; fn net(tile: u64, ch: u64, depth: usize, seed: u64) -> Net { @@ -1117,4 +1177,60 @@ mod tests { // a buffer limit smaller than the activations assert!(plan(&n, 16, 64).is_err()); } + + /// Issue #2577: a tile failing between a caller finding every workspace in use and that caller waiting still wakes + /// it. The caller holds the lock from its check to its wait, as `Workspaces::take` does, so `forget` waits for it. A + /// wait that runs out fails, whatever the count is by then: the wakeup itself has to arrive. + #[test] + fn a_caller_that_finds_every_workspace_in_use_hears_one_being_forgotten() { + let ws = Workspaces::new(0u32, 1); + assert_eq!(ws.lock().free.pop(), Some(0)); + std::thread::scope(|scope| { + // where take() is between finding every workspace in use and waiting + let mut s = ws.lock(); + assert!(s.free.is_empty() && s.made == ws.cap); + scope.spawn(|| ws.forget()); + // the tile in flight fails now + std::thread::sleep(Duration::from_millis(50)); + // wait as take() does, and again only after a spurious wakeup that changed nothing + loop { + let (next, r) = ws.wake.wait_timeout(s, Duration::from_secs(10)).unwrap_or_else(|e| e.into_inner()); + assert!(!r.timed_out(), "the caller missed the workspace being forgotten"); + s = next; + if s.made != ws.cap { + break; + } + } + assert_eq!(s.made, 0); + }); + } + + #[test] + fn take_waits_for_a_workspace_to_come_back_or_be_forgotten() { + let ws = std::sync::Arc::new(Workspaces::new(0u32, 1)); + let fail = || Err(Error::Runtime("no room".into())); + assert_eq!(ws.take(fail).unwrap(), 0); + // a caller on a thread nobody joins: if its wakeup never comes, the test fails on its timeout instead of hanging + let caller = |made: u32| { + let (ws, (tx, rx)) = (ws.clone(), std::sync::mpsc::channel()); + std::thread::spawn(move || tx.send(ws.take(|| Ok(made)))); + rx + }; + // the only workspace is in flight: a caller waits until it is forgotten, then makes a new one + let rx = caller(1); + assert!(rx.recv_timeout(Duration::from_millis(50)).is_err(), "took a workspace while none was free"); + ws.forget(); + assert_eq!(rx.recv_timeout(Duration::from_secs(10)).unwrap().unwrap(), 1); + // or until it comes back, and takes that one + let rx = caller(2); + assert!(rx.recv_timeout(Duration::from_millis(50)).is_err(), "took a workspace while none was free"); + ws.give(1); + assert_eq!(rx.recv_timeout(Duration::from_secs(10)).unwrap().unwrap(), 1); + // a workspace that could not be made leaves room for the next try + ws.forget(); + assert!(ws.take(fail).is_err()); + assert_eq!(ws.lock().made, 0); + assert_eq!(ws.take(|| Ok(3)).unwrap(), 3); + assert_eq!(ws.lock().made, 1); + } } diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 90aed7974c..9d6172d9c3 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -466,6 +466,10 @@ fn shared_source(src: &Arc, upload: impl FnOnce() -> Buf) -> Arc { *g = None; SOURCE_UPLOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let buf = Arc::new(upload()); + // a failed upload's buffer holds zeros: this render falls back, and no other may reuse it + if crate::ctx::failed() { + return buf; + } *g = Some((Arc::downgrade(src), buf.clone())); buf } @@ -599,7 +603,10 @@ pub fn render( }; let plan = lightcraft_pipeline::plan(src, info, s, req); let (w, h) = (plan.w, plan.h); - let n = w * h; + let Some(n) = w.checked_mul(h).filter(|n| n.checked_mul(12).is_some()) else { + fail(FailKind::Limit, format!("{w}×{h} output is too large")); + return None; + }; let _limit = match fault { Some(crate::Fault::Limit(bytes)) => Some(crate::ctx::LimitOverride::new(bytes)), _ => None, @@ -783,6 +790,14 @@ pub fn render( lightcraft_pipeline::masks::evaluate_one(m, &plan.frame, w, h, &img, &l, s.light.exposure as f32, plan.mattes.as_deref()) } }); + // a sharpening view: the detail planes this render sharpened with + let overlay_mask = overlay_mask.or_else(|| { + req.overlay.reads_detail().then(|| { + let l = host.log_l.get_or_insert_with(|| Arc::new(cx.read_plane(&prep.log_l, w, h))).clone(); + let tex = prep.texture.as_deref().map(|b| cx.read_plane(b, w, h)); + lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, tex.as_ref(), plan.px_per_long) + })? + }); lightcraft_pipeline::visualize::apply(&mut image, req.overlay, &plan, overlay_mask.as_ref(), all_overlay_alphas.as_deref()); // spots grew the window the render worked on: cut it back to the request if let Some(k) = plan.keep { @@ -1017,12 +1032,26 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho } MaskShape::ColorRange { samples, refine } => { let tol = lightcraft_pipeline::masks::color_range_tolerance(*refine); + // at most the CPU's samples (`MAX_COLOR_RANGE_SAMPLES`): cost is pixels x samples + let samples = samples.iter().take(lightcraft_develop::MAX_COLOR_RANGE_SAMPLES); p.extend([tol.to_bits(), ev.exp2().to_bits(), samples.len() as u32]); - aux.extend(samples.iter().flat_map(|s| s.map(|v| v as f32))); + aux.extend(samples.flat_map(|s| s.map(|v| v as f32))); Some(3) } MaskShape::Brush { strokes } => { - let dabs: Vec<_> = strokes.iter().map(|st| lightcraft_pipeline::masks::brush_dabs(st, frame, w, h)).collect(); + // The kernel takes at most MAX_DABS across the whole mask, so no more than + // that (plus one, to tell "at it" from "past it") is ever built: each stroke + // may otherwise construct two million dabs before the sum below rejects them + // all (#1520). + let mut room = MAX_DABS + 1; + let dabs: Vec<_> = strokes + .iter() + .map(|st| { + let d = lightcraft_pipeline::masks::brush_dabs_within(st, frame, w, h, room); + room -= d.dabs.len().min(room); + d + }) + .collect(); // pen pressure varies radius and flow per dab, which the kernel doesn't take: the CPU rasterizes it if dabs.iter().map(|d| d.dabs.len()).sum::() > MAX_DABS || dabs.iter().any(|d| !d.pressure.is_empty()) { None diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 04115b945a..767ff44c99 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -106,7 +106,9 @@ fn color_ops(rgb: vec3, local_sat: f32, local_hue: f32) -> vec3 { let lab0 = oklab(rgb); var l = lab0.x; var c = sqrt(lab0.y * lab0.y + lab0.z * lab0.z); - var h = atan2(lab0.z, lab0.y); + // a neutral (black or grey) pixel has no hue: atan2(0, 0) is undefined in WGSL (NaN on some + // GPUs, which a later lightening such as the vignette then shows); the CPU's atan2 gives 0 + var h = select(atan2(lab0.z, lab0.y), 0.0, c == 0.0); if (pu(F_MIXER) != 0u) { let w = band_weights(h); var dh = 0.0; diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 26e4e77573..6509ea284d 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -494,6 +494,34 @@ fn clipped_highlights_stay_neutral_on_both() { } } +/// Black pixels have no hue. The GPU's `atan2(0, 0)` is undefined (NaN on some GPUs), which made +/// every exactly black pixel NaN once a colour tool ran, and a lightening vignette then showed it: +/// the CPU lifted the black corners, the GPU left them black. +#[test] +fn black_pixels_match_under_colour_tools_and_a_light_vignette() { + if !gpu() { + return; + } + let base = scene(0, 320, 240); + // black bars across the frame, reaching into the corners the vignette lightens + let src = Arc::new(Rgb32f::from_fn(320, 240, |x, y| if y % 40 < 8 || x % 64 < 6 { [0.0; 3] } else { base.get(x, y) })); + let info = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(320, 240); + for (name, f) in [ + ("black, light vignette + saturation", (|s: &mut DevelopSettings| s.color.saturation = 40.0) as fn(&mut DevelopSettings)), + ("black, light vignette + vibrance", |s| s.color.vibrance = 30.0), + ("black, light vignette + mixer", |s| s.mixer.yellow.hue = 30.0), + ] { + let mut s = DevelopSettings::default(); + s.vignette.amount = 25.0; + s.vignette.style = VignetteStyle::HighlightPriority; + f(&mut s); + check(name, &src, &info, &s, &req); + let gpu = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu render").image; + assert!(gpu.get(0, 0)[1] > 0, "{name}: the black corner is not lightened on the GPU"); + } +} + #[test] fn rendered_sources_and_other_scenes() { if !gpu() { @@ -693,6 +721,34 @@ fn overlays_match() { let req = RenderRequest { overlay: Overlay::Mask { id, view, color: [230, 30, 40], opacity: 50 }, ..RenderRequest::fit(640, 640) }; check(&format!("mask {id} overlay {}", view.name()), &src, &raw, &s, &req); } + // Alt-drag previews: clipping and greyscale on the finished image; the sharpening views from + // each renderer's own detail planes (with sharpening on, and off: no texture plane then). + let mut s = DevelopSettings::default(); + (s.light.whites, s.light.blacks, s.detail.sharpen_masking) = (80.0, -80.0, 40.0); + for amount in [50.0, 0.0] { + s.detail.sharpen_amount = amount; + for o in [Overlay::ClipHighlights, Overlay::ClipShadows, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask] { + let req = RenderRequest { overlay: o, ..RenderRequest::fit(640, 640) }; + if matches!(o, Overlay::ClipHighlights | Overlay::ClipShadows) { + // a binary view: a 1-LSB difference at 0 / 255 flips a channel, so compare shares + let cpu = render(&src, &raw, &s, &req).image; + let gpu = lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu").image; + let differ = cpu.data.iter().zip(&gpu.data).filter(|(a, b)| a != b).count() as f64 / cpu.data.len() as f64; + assert!(differ < 0.002, "{o:?} sharpen {amount}: {differ}"); + } else if o == Overlay::Grayscale { + check(&format!("{o:?} preview"), &src, &raw, &s, &req); + } else { + // the sharpening views amplify the detail planes (the mask through a steep + // smoothstep): allow a few larger differences where the planes differ slightly + let cpu = render(&src, &raw, &s, &req).image; + let gpu = lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu").image; + let (mean, max, _) = diff(&cpu, &gpu); + let far = cpu.data.iter().zip(&gpu.data).filter(|(a, b)| a[0].abs_diff(b[0]) > 8).count() as f64 / cpu.data.len() as f64; + eprintln!("{o:?} sharpen {amount:<4} mean {mean:.4} max {max} >8: {:.4}%", far * 100.0); + assert!(mean < 1.0 && far < 0.005, "{o:?} sharpen {amount}: mean {mean:.4}, >8 LSB {far}"); + } + } + } } #[test] diff --git a/crates/lensdb/src/lib.rs b/crates/lensdb/src/lib.rs index 93b75f68be..cf6b2ec145 100644 --- a/crates/lensdb/src/lib.rs +++ b/crates/lensdb/src/lib.rs @@ -159,17 +159,24 @@ impl LensDb { /// The camera with this EXIF make and model. pub fn find_camera(&self, make: &str, model: &str) -> Option<&Camera> { - let (mk, md) = (tokens(make), tokens(model)); + let mk = tokens(make); + let raw = tokens(model); + let md = strip_maker(raw.clone(), &mk); if md.is_empty() { return None; } - self.cameras.iter().find(|c| tokens(&c.model) == md && maker_matches(&tokens(&c.maker), &mk)) + self.cameras.iter().find(|c| { + let cm = tokens(&c.maker); + // with no EXIF make, the model may still start with the maker's word + let md = if mk.is_empty() { strip_maker(raw.clone(), &cm) } else { md.clone() }; + maker_matches(&cm, &mk) && strip_maker(tokens(&c.model), &cm) == md + }) } /// The best profile for an EXIF lens model (and lens make, when the file has one), preferring lenses for the /// camera's mount. `None` when no name is a convincing match. pub fn find_lens(&self, lens_make: Option<&str>, lens_model: &str, camera: Option<&Camera>) -> Option<&Profile> { - self.best_lens(lens_make, lens_model, camera, |_| true) + self.best_lens(lens_make, lens_model, camera, |_| true).or_else(|| self.find_fixed_lens(&tokens(lens_model), camera?)) } /// [`find_lens`](Self::find_lens) among the profiles one of whose names is exactly `name` @@ -204,6 +211,64 @@ impl LensDb { } best.map(|(_, l)| l) } + + /// Compact cameras with a built-in lens: lensfun names the lens after the camera and gives it the camera's own + /// mount, while EXIF reports only a focal / aperture range ("6.0-72.0 mm f/2.7-3.5"). Match by mount, then by + /// how much of the calibrated focal range lies inside the EXIF focal range. + fn find_fixed_lens(&self, exif: &[String], cam: &Camera) -> Option<&Profile> { + if cam.mount.is_empty() { + return None; + } + let cands: Vec<&Profile> = self + .lenses + .iter() + .filter(|l| l.mounts.iter().any(|m| m.eq_ignore_ascii_case(&cam.mount))) + .filter(|l| !l.models.iter().any(|m| tokens(m).iter().any(|t| t == "mm"))) + .collect(); + // an interchangeable mount has many lenses; a built-in lens has one or a few profiles + if cands.is_empty() || cands.len() > MAX_FIXED_CANDIDATES { + return None; + } + let Some((lo, hi)) = exif_focal_range(exif) else { + return (cands.len() == 1).then(|| cands[0]); + }; + let (lo, hi) = (lo * 0.9, hi * 1.1); + if !lo.is_finite() || !hi.is_finite() { + return None; + } + let mut best: Option<(f64, &Profile)> = None; + for p in cands { + let focals: Vec = + p.distortion.iter().map(|d| d.0).chain(p.tca.iter().map(|t| t.0)).chain(p.vignetting.iter().map(|v| v.focal)).collect(); + if focals.is_empty() { + continue; + } + let score = focals.iter().filter(|f| (lo..=hi).contains(*f)).count() as f64 / focals.len() as f64; + if score > 0.0 && best.is_none_or(|(s, _)| score > s) { + best = Some((score, p)); + } + } + best.map(|(_, p)| p) + } +} + +/// Most profiles a camera's mount may have for it to count as a built-in-lens mount. +const MAX_FIXED_CANDIDATES: usize = 4; + +/// Drop the maker's words from a model name ("Canon PowerShot S5 IS" → "powershot s5 is"). +fn strip_maker(model: Vec, maker: &[String]) -> Vec { + let first = maker.first(); + let stripped: Vec = model.iter().filter(|t| Some(*t) != first).cloned().collect(); + if stripped.is_empty() { model } else { stripped } +} + +/// The numbers before the first "mm" in tokenised EXIF lens text: (shortest, longest) focal length. +fn exif_focal_range(exif: &[String]) -> Option<(f64, f64)> { + let end = exif.iter().position(|t| t == "mm")?; + let nums: Vec = exif.get(..end)?.iter().filter_map(|t| t.parse::().ok()).filter(|v| v.is_finite() && *v > 0.0).collect(); + let lo = nums.iter().copied().fold(f64::INFINITY, f64::min); + let hi = nums.iter().copied().fold(0.0, f64::max); + (lo.is_finite() && hi > 0.0).then_some((lo, hi)) } fn read_capped(path: &Path) -> Result { diff --git a/crates/lensdb/src/tests.rs b/crates/lensdb/src/tests.rs index 6411ffd660..71c9a4a0eb 100644 --- a/crates/lensdb/src/tests.rs +++ b/crates/lensdb/src/tests.rs @@ -292,3 +292,82 @@ fn a_named_profile_is_found_behind_a_tie() { assert_eq!(db.find_lens_named(None, &name, None).unwrap().maker, "Testcam"); assert!(db.find_lens_named(None, "70-200mm f/4", None).is_none()); } + +#[test] +fn built_in_lens_matches_by_camera_mount_and_focal_range() { + let xml = r#" + CanonCanon PowerShot S5 ISPowerShot S5 IScanonS56.0 + CanonCanon PowerShot S5 IS & compatiblescanonS56.0 + + CanonCanon EF 50mm f/1.8Canon EF + +"#; + let db = LensDb::parse(xml).unwrap(); + let cam = db.find_camera("Canon", "Canon PowerShot S5 IS"); + assert!(cam.is_some()); + assert!(db.find_camera("Canon", "PowerShot S5 IS").is_some()); + let l = db.find_lens(None, "6.0-72.0 mm f/2.7-3.5", cam).unwrap(); + assert_eq!(l.mounts, ["canonS5"]); + assert!(db.find_lens(None, "6.0-72.0 mm f/2.7-3.5", None).is_none()); + // a file with no make still finds the camera by its full model name + assert!(db.find_camera("", "Canon PowerShot S5 IS").is_some()); + // the exact-name lookup never falls back to the camera's mount + assert!(db.find_lens_named(None, "6.0-72.0 mm f/2.7-3.5", cam).is_none()); + // a focal length that overflows to infinity is ignored, not taken as an unbounded range + let huge = format!("6.0-{}9 mm f/2.7-3.5", "9".repeat(400)); + assert_eq!(db.find_lens(None, &huge, cam).unwrap().mounts, ["canonS5"]); + assert_eq!(exif_focal_range(&tokens(&huge)), Some((6.0, 6.0))); +} + +/// A hand-edited or corrupt database may carry any number: infinities, NaN, enormous or negative +/// coefficients, absurd crop factors and aspect ratios. Whatever loads must give corrections that +/// are `None` or entirely finite, for any shot including nonsense ones; names of any shape find +/// nothing rather than panic. +#[test] +fn hostile_numbers_give_finite_corrections_or_none() { + let values = ["inf", "-inf", "NaN", "1e300", "-1e300", "1e-300", "0", "-1", "1e6", "99999"]; + let mut cases = 0; + for v in values { + for xml in [ + format!( + r#"MM 1{v}{v}"# + ), + format!( + r#"MM 1"# + ), + format!( + r#"MM 1"# + ), + ] { + let Ok(db) = LensDb::parse(&format!("{xml}")) else { continue }; + for p in &db.lenses { + for focal in [f64::NAN, f64::INFINITY, -1.0, 0.0, 1e-9, 8.0, 24.0, 50.0, 1e9] { + for (w, h) in [(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (6000.0, 4000.0), (1e9, 1.0), (f64::NAN, 10.0), (f64::INFINITY, 4000.0)] { + for aperture in [None, Some(f64::NAN), Some(-2.0), Some(0.0), Some(2.8), Some(1e9)] { + for crop in [None, Some(0.0), Some(f64::NAN), Some(-1.0), Some(1.5), Some(1e9)] { + let shot = Shot { focal, aperture, distance: Some(f64::NAN), crop_factor: crop, width: w, height: h }; + cases += 1; + let Some(c) = p.correction(&shot) else { continue }; + let planes = + c.warp.iter().flat_map(|wp| wp.planes.iter().flatten().copied().chain([wp.radius, wp.center.x, wp.center.y])); + let vig = c.vignette.iter().flat_map(|vg| vg.k.iter().copied().chain([vg.radius, vg.center.x, vg.center.y])); + assert!(planes.chain(vig).all(f64::is_finite), "{v}: focal {focal} {w}x{h} {aperture:?} {crop:?}"); + } + } + } + } + } + } + } + assert!(cases > 1000); + + let db = db(); + let long = "x".repeat(100_000); + for s in ["", " ", "\t\n", "\0", "ß İ Dž", "....", "1.2.3.4mm", "-mm", long.as_str()] { + let _ = db.find_camera(s, s); + let _ = db.find_lens(Some(s), s, db.cameras.first()); + let _ = db.find_lens(None, s, None); + } + assert!(db.find_camera("", "").is_none()); + assert!(db.find_lens(None, " ", None).is_none()); +} diff --git a/crates/lensdb/src/xml.rs b/crates/lensdb/src/xml.rs index 0ff0c742c3..5eed2dd288 100644 --- a/crates/lensdb/src/xml.rs +++ b/crates/lensdb/src/xml.rs @@ -43,8 +43,10 @@ fn entity(name: &str) -> Option { _ => { let n = name.strip_prefix('#')?; let v = match n.strip_prefix('x') { - Some(h) => u32::from_str_radix(h, 16).ok()?, - None => n.parse().ok()?, + Some(h) if h.bytes().all(|b| b.is_ascii_hexdigit()) => u32::from_str_radix(h, 16).ok()?, + Some(_) => return None, + None if n.bytes().all(|b| b.is_ascii_digit()) => n.parse().ok()?, + None => return None, }; char::from_u32(v)? } @@ -133,3 +135,16 @@ fn close(stack: &mut Vec) { p.children.push(n); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn entity_rejects_signed_numeric_references() { + assert_eq!(entity("#+65"), None); + assert_eq!(entity("#x+41"), None); + assert_eq!(entity("#65"), Some('A')); + assert_eq!(entity("#x41"), Some('A')); + } +} diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 6a2c2efb9f..a621f40372 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -136,39 +136,58 @@ fn peer_closed(stream: &TcpStream) -> bool { stream.set_nonblocking(false).is_err() || !open } +/// The app's idle-close notice (`apps/lightcraft/src/control_server.rs`), matched when a reply lacks +/// the `closed` marker (an app from before it). Keep the two in step. +const IDLE_CLOSE_ERROR: &str = "control connection idle read timed out; closing the connection"; + +/// True for the app's idle-close notice: an id-less error the app writes when it closes a connection +/// on which it read nothing for its idle timeout. Read in reply to a request, it means the app closed +/// the connection without reading the request (the request crossed the notice), so nothing ran. +fn is_idle_close(reply: &Value) -> bool { + reply.get("id").is_none() + && reply.get("ok").and_then(Value::as_bool) == Some(false) + && (reply.get("closed").and_then(Value::as_str) == Some("idle") || reply.get("error").and_then(Value::as_str) == Some(IDLE_CLOSE_ERROR)) +} + impl Backend for Remote { fn call(&mut self, method: &str, params: Value) -> Result { let id = self.next_id; self.next_id += 1; let line = json!({"id": id, "method": method, "params": params}).to_string(); - // Retry once with a fresh connection (the app may have restarted), but only when the request - // never reached the app. After a full write the command may have run, so resending it could - // apply a mutation twice (toggle, undo, ...): report the unknown outcome instead. - let reply = match self.roundtrip(&line) { - Ok(r) => r, - Err((_, false)) => { - self.conn = None; - self.roundtrip(&line).map_err(|(e, sent)| { + // Send again once, on a fresh connection, but only when the request never reached the app: it + // could not be written (the app restarted), or the app's idle-close notice crossed it (the app + // stopped reading before it arrived). After a full write anything else may mean the command + // ran, so resending it could apply a mutation twice (toggle, undo, ...): report the unknown + // outcome instead. One resend at most, whatever the reason, so this can't loop. + let mut resent = false; + let v = loop { + let reply = match self.roundtrip(&line) { + Ok(r) => r, + Err((e, sent)) => { self.conn = None; if sent { - self.unknown_outcome(method, &e) - } else { - format!("LightCraft app at {} is not reachable: {e} (start it with `lightcraft --control PORT`)", self.addr) + return Err(self.unknown_outcome(method, &e)); } - })? - } - Err((e, true)) => { + if resent { + return Err(format!("LightCraft app at {} is not reachable: {e} (start it with `lightcraft --control PORT`)", self.addr)); + } + resent = true; + continue; + } + }; + let v = parse_reply(&reply, id).map_err(|e| { self.conn = None; - return Err(self.unknown_outcome(method, &e)); + self.unknown_outcome(method, &e) + })?; + if v.get("id").is_none() { + self.conn = None; + if !resent && is_idle_close(&v) { + resent = true; + continue; + } } + break v; }; - let v = parse_reply(&reply, id).map_err(|e| { - self.conn = None; - self.unknown_outcome(method, &e) - })?; - if v.get("id").is_none() { - self.conn = None; - } if v.get("ok").and_then(Value::as_bool) == Some(true) { Ok(v.get("result").cloned().unwrap_or(Value::Null)) } else { @@ -275,6 +294,11 @@ mod tests { ("{\"id\":1,\"ok\":true,\"result\":null}\r\n", Ok(Value::Null)), ("{\"id\":1,\"ok\":false,\"error\":\"unknown command\"}\n", Err("unknown command".to_string())), ("{\"ok\":false,\"error\":\"too many control connections\"}\n", Err("too many control connections".to_string())), + // The idle-close text in reply to the request (it has the id) is the command's own error. + ( + "{\"id\":1,\"ok\":false,\"error\":\"control connection idle read timed out; closing the connection\"}\n", + Err(IDLE_CLOSE_ERROR.to_string()), + ), ] { with_reply(reply.as_bytes(), |remote, result| { assert_eq!(result, expected); @@ -380,51 +404,148 @@ mod tests { assert_eq!(seen.load(Ordering::SeqCst), 2); } + /// Accept the next connection within 5 s, as a blocking stream with a 3 s read timeout. + fn accept(listener: &TcpListener) -> (BufReader, TcpStream) { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(5)); + } + Err(e) => panic!("accept: {e}"), + } + }; + // BSD kernels (macOS, FreeBSD) let an accepted socket inherit the listener's non-blocking flag. + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + (BufReader::new(stream.try_clone().unwrap()), stream) + } + + fn read_request(reader: &mut BufReader) -> Value { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + serde_json::from_str(&line).unwrap() + } + + /// The app's idle-close notice, as `apps/lightcraft/src/control_server.rs` writes it. + fn idle_notice() -> Value { + json!({"ok": false, "error": IDLE_CLOSE_ERROR, "closed": "idle"}) + } + + /// Issue #3069. The app closes an idle connection with an id-less notice. Either the notice + /// arrives before the next request (the client sees the close and reconnects before sending), + /// or the request crosses it (sent just as the app stopped reading): the notice then comes + /// back as the request's reply although the app never ran it, so the client sends it once more + /// on a new connection. Both orders are forced here, so the test does not depend on timing. #[test] fn idle_close_reconnects_without_replaying_a_command() { + let _serial = crate::serial_sockets_and_children(); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); let addr = listener.local_addr().unwrap().to_string(); let (closed, expired) = std::sync::mpsc::channel(); let server = std::thread::spawn(move || { - let mut ids = Vec::new(); - for _ in 0..2 { - let deadline = std::time::Instant::now() + Duration::from_secs(5); - let stream = loop { - match listener.accept() { - Ok((stream, _)) => break stream, - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => { - std::thread::sleep(Duration::from_millis(5)); - } - Err(e) => panic!("accept: {e}"), - } - }; - stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); - let mut reader = BufReader::new(stream.try_clone().unwrap()); - let mut writer = stream; - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - let request: Value = serde_json::from_str(&line).unwrap(); - ids.push(request["id"].as_u64().unwrap()); - writeln!(writer, "{}", json!({"id": request["id"], "ok": true, "result": ids.len()})).unwrap(); - writer.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); - line.clear(); - let error = reader.read_line(&mut line).unwrap_err(); - assert!(matches!(error.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)); - assert!(line.is_empty(), "no command is resent while idle"); - writeln!(writer, "{}", json!({"ok": false, "error": "control connection idle read timed out; closing the connection"})).unwrap(); - drop(reader); - drop(writer); - closed.send(()).unwrap(); - } - ids + let mut ran = Vec::new(); + let mut run = |request: &Value, writer: &mut TcpStream| { + ran.push(request["id"].as_u64().unwrap()); + writeln!(writer, "{}", json!({"id": request["id"], "ok": true, "result": ran.len()})).unwrap(); + }; + + // 1. Idle with nothing sent: the notice (in an older app's form, without `closed`) and + // the close reach the client before its next request. + let (mut reader, mut writer) = accept(&listener); + run(&read_request(&mut reader), &mut writer); + writer.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let mut line = String::new(); + let error = reader.read_line(&mut line).unwrap_err(); + assert!(matches!(error.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)); + assert!(line.is_empty(), "no command is resent while idle"); + writeln!(writer, "{}", json!({"ok": false, "error": IDLE_CLOSE_ERROR})).unwrap(); + drop((reader, writer)); + closed.send(()).unwrap(); + + // 2. The client reconnected before sending. Its next request crosses the notice: the + // app's read timed out just before the request arrived, so it is not run. (Reading + // it here only shows that it was sent on this connection and keeps the close clean.) + let (mut reader, mut writer) = accept(&listener); + run(&read_request(&mut reader), &mut writer); + let crossed = read_request(&mut reader); + writeln!(writer, "{}", idle_notice()).unwrap(); + drop((reader, writer)); + + // 3. The crossed request, sent once more on a new connection, and nothing after it. + let (mut reader, mut writer) = accept(&listener); + let resent = read_request(&mut reader); + assert_eq!(resent, crossed, "the same request is sent again"); + run(&resent, &mut writer); + line.clear(); + assert_eq!(reader.read_line(&mut line).unwrap(), 0, "nothing else arrives: {line}"); + ran }); let mut remote = Remote::lazy(&addr); assert_eq!(remote.call("engine.execute", json!({"command": "edit.undo"})).unwrap(), json!(1)); expired.recv_timeout(Duration::from_secs(5)).unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while !remote.conn.as_ref().is_some_and(|(_, writer)| peer_closed(writer)) { + assert!(std::time::Instant::now() < deadline, "the idle close never reached the client"); + std::thread::sleep(Duration::from_millis(1)); + } assert_eq!(remote.call("engine.execute", json!({"command": "edit.undo"})).unwrap(), json!(2)); - expired.recv_timeout(Duration::from_secs(5)).unwrap(); - assert_eq!(server.join().unwrap(), [1, 2], "each command ran once on a separate connection"); + assert_eq!(remote.call("engine.execute", json!({"command": "edit.undo"})).unwrap(), json!(3)); + drop(remote); + assert_eq!(server.join().unwrap(), [1, 2, 3], "each command ran once"); + } + + /// The resend after an idle close happens once: a second notice is the call's error. + #[test] + fn idle_close_is_resent_only_once() { + let _serial = crate::serial_sockets_and_children(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let server = std::thread::spawn(move || { + for _ in 0..2 { + let (mut reader, mut writer) = accept(&listener); + assert_eq!(read_request(&mut reader)["id"], 1); + writeln!(writer, "{}", idle_notice()).unwrap(); + } + listener + }); + let mut remote = Remote::lazy(&addr); + assert_eq!(remote.call("engine.execute", json!({"command": "edit.undo"})), Err(IDLE_CLOSE_ERROR.to_string())); + assert!(remote.conn.is_none(), "the closed connection is not reused"); + drop(remote); + let listener = server.join().unwrap(); + assert_eq!(listener.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock, "a third connection was opened"); + } + + #[test] + fn only_the_idle_close_notice_counts_as_undelivered() { + let idle = [ + json!({"ok": false, "error": IDLE_CLOSE_ERROR, "closed": "idle"}), + // an app from before the `closed` marker + json!({"ok": false, "error": IDLE_CLOSE_ERROR}), + // the marker decides when present, whatever the wording + json!({"ok": false, "error": "idle, closing", "closed": "idle"}), + ]; + for reply in idle { + assert!(is_idle_close(&reply), "{reply}"); + } + let delivered = [ + // a reply to the request itself + json!({"id": 1, "ok": false, "error": IDLE_CLOSE_ERROR}), + json!({"id": 1, "ok": false, "error": IDLE_CLOSE_ERROR, "closed": "idle"}), + // other refusals and closes + json!({"ok": false, "error": "too many control connections"}), + json!({"ok": false, "error": "bad JSON; closing the connection"}), + json!({"ok": false, "error": "bad JSON; closing the connection", "closed": "junk"}), + json!({"ok": false, "error": format!("{IDLE_CLOSE_ERROR}.")}), + json!({"ok": true, "result": IDLE_CLOSE_ERROR, "closed": "idle"}), + ]; + for reply in delivered { + assert!(!is_idle_close(&reply), "{reply}"); + } } #[test] diff --git a/crates/mcp/src/base64.rs b/crates/mcp/src/base64.rs index 9c02ac327b..12ccf45bbb 100644 --- a/crates/mcp/src/base64.rs +++ b/crates/mcp/src/base64.rs @@ -20,9 +20,14 @@ pub fn base64_encode(bytes: &[u8]) -> String { pub fn base64_decode(text: &str) -> Option> { let mut out = Vec::with_capacity(text.len() / 4 * 3); let (mut acc, mut bits) = (0u32, 0u32); + let mut padded = false; for c in text.bytes().filter(|c| !c.is_ascii_whitespace()) { if c == b'=' { - break; + padded = true; + continue; + } + if padded { + return None; } let v = ALPHABET.iter().position(|&a| a == c)? as u32; acc = (acc << 6) | v; @@ -33,6 +38,9 @@ pub fn base64_decode(text: &str) -> Option> { acc &= (1 << bits) - 1; } } + if bits == 6 { + return None; + } Some(out) } @@ -57,4 +65,12 @@ mod tests { } assert!(base64_decode("not base64!").is_none()); } + + #[test] + fn rejects_malformed() { + 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"); + } } diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index d62a9a707e..94b1d26062 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -132,7 +132,7 @@ impl Backend for Headless { "engine.commands" => { let mut v: Vec = self.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); v.push(json!({"id": "app.export", "label": "Export Now", "menu": [], "shortcut": null, - "params": "{path?: output file (.jpg/.png/.tif/.webp/.avif/.jxl/.psd/.dng) | dir?, ids?, preset?, format?: jpeg|png|tiff|webp|avif|jxl|psd|dng|original, longEdge?|shortEdge?|width?|height?|megapixels?|percent? (default longEdge 3000; longEdge 0 = full size), fit?: dimensions|widthHeight (with width + height: dimensions fits either orientation, widthHeight limits the width to `width` and the height to `height`), dontEnlarge?, ppi?, quality?: 1..100, jxlLossless?, jxlEffort?: fast|normal, jxlProgressive?, limitKb?, colorSpace?: srgb|displayP3|adobeRgb|proPhoto|rec2020, bitDepth?: 8|10|16|32, hdr? (HDR output for HDR edits: gain map JPEG, PQ AVIF / PNG / JPEG XL, float TIFF), sharpen?: none|screen|matte|glossy, sharpenAmount?: low|standard|high, metadata?: all|allExceptCamera|copyright|none, removeLocation?, naming?, startNumber?, destinationMode?: specificFolder|sameAsOriginal (sameAsOriginal = each photo into its original's folder; `dir` unused), subfolder?, conflict?: unique|overwrite|skip, tiffCompression?: none|lzw|zip, dngCompression?: lossless|deflate|uncompressed, addToPhotos?: bool (macOS: then add the files written to Apple Photos; outcome in `applePhotos`), photosAlbum?: top-level album name (made when missing), watermark?: text | {text?, vertical? (upright columns, right to left), size? (text height, 0.005..0.5 of the short edge; default 0.035), opacity? (0..1; 0.7), anchor?: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight, insetX? (margin from the left/right edge, 0..0.4 of the short edge; 0.025), insetY? (from the top/bottom edge; 0.025), inset? (sets both), rotation?: 0|90|180|270 (degrees clockwise; 0), color? [r,g,b] sRGB, shadow?, image? (graphic drawn instead of the text), imageWidth? (0.01..1 of the photo's width; 0.2)}} — an unknown parameter, an out-of-range watermark size or a value of the wrong kind is an error, not a default", + "params": "{path?: output file (.jpg/.png/.tif/.webp/.avif/.jxl/.psd/.dng) | dir?, ids?, preset?, format?: jpeg|png|tiff|webp|avif|jxl|psd|dng|original, longEdge?|shortEdge?|width?|height?|megapixels?|percent? (default longEdge 3000; longEdge 0 = full size), fit?: dimensions|widthHeight (with width + height: dimensions fits either orientation, widthHeight limits the width to `width` and the height to `height`), dontEnlarge?, ppi?, quality?: 1..100, jxlLossless?, jxlEffort?: fast|normal, jxlProgressive?, limitKb?, colorSpace?: srgb|displayP3|adobeRgb|proPhoto|rec2020, bitDepth?: 8|10|16|32, hdr? (HDR output for HDR edits: gain map JPEG, PQ AVIF / PNG / JPEG XL, float TIFF), sharpen?: none|screen|matte|glossy, sharpenAmount?: low|standard|high, metadata?: all|allExceptCamera|copyright|none, removeLocation?, naming?, startNumber?, destinationMode?: specificFolder|sameAsOriginal (sameAsOriginal = each photo into its original's folder; `dir` unused), subfolder?, conflict?: unique|overwrite|skip, tiffCompression?: none|lzw|zip (default zip; lzw is usually larger and slower than zip, at 16 bit often larger than none: only for software that needs LZW), dngCompression?: lossless|deflate|uncompressed, addToPhotos?: bool (macOS: then add the files written to Apple Photos; outcome in `applePhotos`), photosAlbum?: top-level album name (made when missing), watermark?: text | {text?, vertical? (upright columns, right to left), size? (text height, 0.005..0.5 of the short edge; default 0.035), opacity? (0..1; 0.7), anchor?: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight, insetX? (margin from the left/right edge, 0..0.4 of the short edge; 0.025), insetY? (from the top/bottom edge; 0.025), inset? (sets both), rotation?: 0|90|180|270 (degrees clockwise; 0), color? [r,g,b] sRGB, shadow?, image? (graphic drawn instead of the text), imageWidth? (0.01..1 of the photo's width; 0.2)}} — an unknown parameter, an out-of-range watermark size or a value of the wrong kind is an error, not a default", "enabled": self.session.active().is_some()})); Ok(Value::Array(v)) } @@ -207,7 +207,7 @@ mod tests { fn folder_discovery_matches_engine_extensions() { let dir = std::env::temp_dir().join(format!("lc-mcp-discovery-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - let nested = dir.join("trip/day2"); + let nested = dir.join("trip").join("day2"); // not "trip/day2": discovery yields the platform's separator std::fs::create_dir_all(&nested).unwrap(); let mut expected = Vec::new(); for ext in lightcraft_engine::import::EXTENSIONS { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 59e7ba3eb6..7cc61a3186 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -539,3 +539,66 @@ fn the_clipboard_tool_cuts_copies_and_pastes_in_the_app() { assert!(!r.is_error, "{r:?}"); assert_eq!(b.0, vec![("ui.clipboard".to_string(), json!({"action": "paste", "text": "travel"}))]); } + +/// A running app that writes the PNG `ui.render` / `ui.screenshot` ask for. It notes each path and +/// what its folder looked like then; with `dies_mid_write` it leaves a half-written temp file and +/// fails instead, like an app that quits part-way through. +struct PngWriter { + seen: Vec<(std::path::PathBuf, Option)>, + dies_mid_write: bool, +} + +impl Backend for PngWriter { + fn call(&mut self, method: &str, params: Value) -> Result { + assert!(matches!(method, "ui.render" | "ui.screenshot"), "{method}"); + let path = std::path::PathBuf::from(params["path"].as_str().unwrap()); + self.seen.push((path.clone(), path.parent().and_then(|d| std::fs::symlink_metadata(d).ok()))); + if self.dies_mid_write { + std::fs::write(path.with_file_name(".lightcraft-mcp-test.tmp"), b"half a png").unwrap(); + return Err("connection closed".into()); + } + crate::write_image(&path, &lightcraft_raster::Rgba8::new(1, 1), 92)?; + Ok(json!({"width": 1, "height": 1})) + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "png writer".into() + } +} + +/// Renders and screenshots reach the agent through a PNG the app writes. In a shared /tmp other +/// users could read it or take its predictable name first and make the render fail, so it goes in +/// a new folder of its own, private on Unix, that is gone afterwards even when the write fails +/// (#2573). +#[test] +fn render_and_screenshot_pngs_go_through_a_private_folder() { + let mut b = PngWriter { seen: vec![], dies_mid_write: false }; + for (tool, args) in [("render_photo", json!({"id": 1})), ("render_preview", json!({"id": 1})), ("screenshot", json!({}))] { + let r = call_tool(&mut b, tool, &args); + assert!(!r.is_error, "{tool}: {r:?}"); + assert_eq!(r.image().map(|(_, mime)| mime), Some("image/png"), "{tool}: {r:?}"); + } + b.dies_mid_write = true; + assert!(call_tool(&mut b, "screenshot", &json!({})).is_error); + assert_eq!(b.seen.len(), 4); + let temp = std::env::temp_dir(); + let mut folders = vec![]; + for (file, folder) in &b.seen { + let dir = file.parent().unwrap(); + let meta = folder.as_ref().unwrap(); + assert!(meta.is_dir() && !meta.file_type().is_symlink(), "{}", dir.display()); + assert_ne!(dir, temp, "{} is right in the shared temp dir", file.display()); + assert_eq!(dir.parent(), Some(temp.as_path()), "{}", file.display()); + assert!(dir.file_name().unwrap().to_string_lossy().starts_with("lightcraft-mcp-"), "{}", dir.display()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(meta.permissions().mode() & 0o777, 0o700, "{}", dir.display()); + } + assert!(!dir.exists(), "{} was left behind", dir.display()); + assert!(!folders.contains(&dir), "{} was used twice", dir.display()); + folders.push(dir); + } +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 8f782bb9d9..1c7ae37011 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -2,6 +2,7 @@ //! per command in the engine's command registry (`cmd_`), all forwarded to a //! [`Backend`] as control-channel methods. +use std::hash::{BuildHasher, Hasher, RandomState}; use std::sync::atomic::{AtomicU64, Ordering}; use serde_json::{Map, Value, json}; @@ -238,7 +239,7 @@ pub fn helper_tools(has_ui: bool) -> Vec { "destinationMode": {"type": "string", "enum": ["specificFolder", "sameAsOriginal"], "description": "specificFolder (default) = everything into `dir`; sameAsOriginal = each photo into the folder of its original (+ `subfolder`); a photo with no folder on disk (demo, browser) or whose folder is gone gets an error"}, "subfolder": {"type": "string", "description": "Created inside the destination folder"}, "conflict": {"type": "string", "enum": ["unique", "overwrite", "skip"]}, - "tiffCompression": {"type": "string", "enum": ["none", "lzw", "zip"]}, + "tiffCompression": {"type": "string", "enum": ["none", "lzw", "zip"], "description": "zip (default); lzw is usually larger and slower than zip, and at 16 bit often larger than none: use it only when other software needs LZW"}, "dngCompression": {"type": "string", "enum": ["lossless", "deflate", "uncompressed", "lossy"]}, "format": {"type": "string", "enum": ["jpeg", "png", "tiff", "psd", "webp", "avif", "jxl", "original", "dng", "rendereddng"], "description": "psd = a flat PSD (no layers); rendereddng = Render to DNG, a linear 16-bit float DNG of the rendered photo with the edit baked in; original = the file as is + an XMP sidecar with the edits; dng = raw photos as DNG with the edits embedded"}, "longEdge": {"type": "integer", "description": "Output long edge in px. When no size param is given: 3000; 0 = full size (cropped, native resolution)"}, @@ -437,9 +438,48 @@ fn activate(b: &mut dyn Backend, args: &Value) -> Result<(), String> { Ok(()) } -fn temp_path(tag: &str) -> std::path::PathBuf { - static N: AtomicU64 = AtomicU64::new(0); - std::env::temp_dir().join(format!("lightcraft-mcp-{}-{}-{tag}.png", std::process::id(), N.fetch_add(1, Ordering::Relaxed))) +/// Where the backend writes a render or screenshot for us to read back: `.png` in a new +/// `lightcraft-mcp--` folder in the temp dir, private to this user on Unix (0700). +/// Straight in a shared /tmp, other users could read the PNG, and a name they took first made the +/// render fail (#2573). Dropping this removes the folder and whatever is in it. +struct TempPng { + dir: std::path::PathBuf, + file: std::path::PathBuf, +} + +impl TempPng { + fn new(tag: &str) -> Result { + static N: AtomicU64 = AtomicU64::new(0); + let temp = std::env::temp_dir(); + for _ in 0..100 { + let mut h = RandomState::new().build_hasher(); + h.write_u64(N.fetch_add(1, Ordering::Relaxed)); + let dir = temp.join(format!("lightcraft-mcp-{}-{:016x}", std::process::id(), h.finish())); + #[cfg(unix)] + let builder = { + use std::os::unix::fs::DirBuilderExt; + let mut b = std::fs::DirBuilder::new(); + b.mode(0o700); + b + }; + #[cfg(not(unix))] + let builder = std::fs::DirBuilder::new(); + // Never recursive: a name someone else made first fails and is not used. + match builder.create(&dir) { + Ok(()) => return Ok(Self { file: dir.join(format!("{tag}.png")), dir }), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(format!("cannot make a private temporary folder in {}: {e}", temp.display())), + } + } + Err(format!("cannot make a private temporary folder in {}: every name tried is taken", temp.display())) + } +} + +impl Drop for TempPng { + fn drop(&mut self) { + // Also removes the temp file a backend that died mid-write leaves next to the PNG. + let _ = std::fs::remove_dir_all(&self.dir); + } } /// Read a PNG the backend wrote, optionally downscale / re-encode as JPEG, and wrap it as image @@ -512,26 +552,32 @@ fn render_photo(b: &mut dyn Backend, args: &Value) -> ToolResult { }, }; let Some(id) = id else { return ToolResult::error("no active photo: import or select one, or pass `id`") }; - let file = temp_path("render"); - let path = file.to_string_lossy().to_string(); + let tmp = match TempPng::new("render") { + Ok(t) => t, + Err(e) => return ToolResult::error(e), + }; + let path = tmp.file.to_string_lossy().to_string(); let meta = match b.call("ui.render", json!({"id": id, "size": size, "path": path})) { Ok(m) => m, Err(e) => return ToolResult::error(e), }; let mut meta = meta; meta["id"] = json!(id); - image_result(&file, None, args.get("format").and_then(Value::as_str).unwrap_or("png"), args.get("path").and_then(Value::as_str), meta) + image_result(&tmp.file, None, args.get("format").and_then(Value::as_str).unwrap_or("png"), args.get("path").and_then(Value::as_str), meta) } fn screenshot(b: &mut dyn Backend, args: &Value) -> ToolResult { if let Err(e) = check_save_path(b, args) { return ToolResult::error(e); } - let file = temp_path("screenshot"); - let path = file.to_string_lossy().to_string(); + let tmp = match TempPng::new("screenshot") { + Ok(t) => t, + Err(e) => return ToolResult::error(e), + }; + let path = tmp.file.to_string_lossy().to_string(); match b.call("ui.screenshot", json!({"path": path})) { Ok(meta) => image_result( - &file, + &tmp.file, Some(args.get("maxSize").and_then(Value::as_u64).unwrap_or(1600).clamp(64, 8192) as u32), args.get("format").and_then(Value::as_str).unwrap_or("png"), args.get("path").and_then(Value::as_str), diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index 22538aee8e..4f2fad315e 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -16,5 +16,7 @@ quick-xml = { workspace = true } chrono = { workspace = true } [dev-dependencies] +# Lossless synthetic HEIC files: the HEIF item reader is proved against a real container writer. +lightcraft-heif = { workspace = true, features = ["testdata"] } proptest = { workspace = true } serde_json = { workspace = true } diff --git a/crates/meta/README.md b/crates/meta/README.md index 519426784a..0a7f2d8027 100644 --- a/crates/meta/README.md +++ b/crates/meta/README.md @@ -20,6 +20,11 @@ Photo metadata: EXIF, XMP (read + write), IPTC-IIM, and the containers that carr 35 mm equivalent, flash, exposure bias, program, metering, white balance), orientation, GPS, dimensions and the user fields (artist, copyright, title, caption, keywords, hierarchical keywords, rating −1…5, colour label). +EXIF capture-time candidates are tried in order: DateTimeOriginal, DateTimeDigitized, then IFD0 DateTime. A clock +with more than three colon-separated components is rejected as a whole, allowing the next valid candidate or XMP +fallback to supply the capture time. The original tag remains available in All Metadata. JPEG ICC data is exposed only when its APP2 chunks form a complete, consistent, uniquely numbered sequence; +malformed or truncated ICC sequences leave unrelated readable metadata available and produce no profile. + ## XMP namespaces Written: `dc`, `xmp`, `photoshop`, `exif`, `exifEX`, `tiff`, `lr` (`hierarchicalSubject`) and ours, @@ -42,6 +47,10 @@ XMP parser; truncation tests cut a sample JPEG at every byte and exercise trunca image-resource records with hostile declared lengths. PSD/PSB XMP resources require valid UTF-8; trailing NUL padding is trimmed after validation. +ISO capture-time parsing requires a complete clock and consumes every clock and fractional-second character. Invalid +XMP capture-time values remain available in the raw property map but are not projected into `Metadata`; a later valid +capture-time property can still supply the metadata value. Invalid GPX point times are treated as untimed. + ## Sources CIPA DC-008 (Exif 2.32), TIFF 6.0, Adobe DNG 1.7 (tag numbers), ISO 16684-1 / Adobe XMP Specification diff --git a/crates/meta/src/container.rs b/crates/meta/src/container.rs index 3cfb7e287f..0136bf6846 100644 --- a/crates/meta/src/container.rs +++ b/crates/meta/src/container.rs @@ -11,6 +11,8 @@ //! - Minolta MRW (see [`crate::mrw`]): the `TTW` block is the Exif block. //! - Canon CR3 (ISO base media file, see [`crate::cr3`]): `CMT1`/`CMT2`/`CMT4` merged into one Exif block; the //! XMP `uuid` box. +//! - HEIF/HEIC/AVIF (ISO base media file, see [`crate::heif`]): the `Exif` item's TIFF stream and the XMP +//! `mime` item. use lightcraft_tiff::{Tiff, tags}; @@ -52,6 +54,9 @@ pub fn embedded(bytes: &[u8]) -> Embedded { if let Some(c) = crate::cr3::parse_cr3(bytes) { return Embedded { exif: crate::cr3::merged_exif(&c), xmp: c.xmp.map(|b| String::from_utf8_lossy(b).into_owned()), ..Default::default() }; } + if crate::heif::is_heif(bytes) { + return crate::heif::metadata(bytes); + } if bytes.starts_with(&[0xff, 0xd8]) { jpeg_segments(bytes) } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { @@ -90,7 +95,9 @@ pub fn jpeg_segments(b: &[u8]) -> Embedded { if !b.starts_with(&[0xff, 0xd8]) { return out; } - let mut icc_parts: Vec<(u8, Vec)> = Vec::new(); + let mut icc_parts: [Option<&[u8]>; 255] = [None; 255]; + let mut icc_total = None; + let mut icc_invalid = false; let mut ext: Vec<(u32, Vec)> = Vec::new(); let mut i = 2usize; while i + 4 <= b.len() { @@ -113,8 +120,11 @@ pub fn jpeg_segments(b: &[u8]) -> Embedded { if len < 2 { break; } - let end = (i + 2 + len).min(b.len()); - let payload = &b[i + 4..end]; + let Some(start) = i.checked_add(4) else { break }; + let Some(declared_end) = i.checked_add(2).and_then(|at| at.checked_add(len)) else { break }; + let complete = declared_end <= b.len(); + let end = declared_end.min(b.len()); + let Some(payload) = b.get(start..end) else { break }; match marker { 0xe1 if payload.starts_with(b"Exif\0") && out.exif.is_none() => out.exif = Some(payload.get(6..).unwrap_or(&[]).to_vec()), 0xe1 if payload.starts_with(XMP_SIG) && out.xmp.is_none() => { @@ -128,15 +138,64 @@ pub fn jpeg_segments(b: &[u8]) -> Embedded { ext.push((off, p[40..].to_vec())); } } - 0xe2 if payload.starts_with(b"ICC_PROFILE\0") && payload.len() >= 14 => icc_parts.push((payload[12], payload[14..].to_vec())), + 0xe2 if payload.starts_with(b"ICC_PROFILE\0") => { + if !complete || payload.len() < 14 { + icc_invalid = true; + } else if let Some(header) = payload.get(12..14) { + let (Some(&sequence), Some(&total)) = (header.first(), header.get(1)) else { + icc_invalid = true; + i = end; + continue; + }; + if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) { + icc_invalid = true; + } else { + icc_total = Some(total); + if let Some(slot) = icc_parts.get_mut(usize::from(sequence - 1)) { + if slot.is_some() { + icc_invalid = true; + } else if let Some(data) = payload.get(14..) { + *slot = Some(data); + } else { + icc_invalid = true; + } + } else { + icc_invalid = true; + } + } + } else { + icc_invalid = true; + } + } 0xed if payload.starts_with(b"Photoshop 3.0\0") && out.iptc.is_none() => out.iptc = photoshop_iptc(&payload[14..]), _ => {} } i = end; } - if !icc_parts.is_empty() { - icc_parts.sort_by_key(|p| p.0); - out.icc = Some(icc_parts.into_iter().flat_map(|p| p.1).collect()); + if let Some(total) = icc_total { + let mut profile_len = 0usize; + for chunk in icc_parts.iter().take(usize::from(total)) { + let Some(bytes) = chunk else { + icc_invalid = true; + break; + }; + let Some(next_len) = profile_len.checked_add(bytes.len()) else { + 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) { + icc_invalid = true; + } + if !icc_invalid { + let mut profile = Vec::with_capacity(profile_len); + for bytes in icc_parts.iter().take(usize::from(total)).flatten() { + profile.extend_from_slice(bytes); + } + out.icc = Some(profile); + } } if !ext.is_empty() { ext.sort_by_key(|p| p.0); @@ -225,6 +284,26 @@ mod tests { v } + fn icc_seg(sequence: u8, total: u8, data: &[u8]) -> Vec { + let mut payload = b"ICC_PROFILE\0".to_vec(); + payload.extend_from_slice(&[sequence, total]); + payload.extend_from_slice(data); + seg(0xe2, &payload) + } + + fn jpeg_with_icc(parts: &[Vec]) -> Vec { + let mut jpeg = vec![0xff, 0xd8]; + let packet = crate::write_xmp(&crate::Metadata { title: Some("retained".into()), ..Default::default() }, None); + let mut xmp = XMP_SIG.to_vec(); + xmp.extend_from_slice(packet.as_bytes()); + jpeg.extend_from_slice(&seg(0xe1, &xmp)); + for part in parts { + jpeg.extend_from_slice(part); + } + jpeg.extend_from_slice(&[0xff, 0xda, 0, 2]); + jpeg + } + pub(crate) fn sample_jpeg() -> Vec { let mut j = vec![0xff, 0xd8]; j.extend(seg(0xe0, b"JFIF\0\x01\x02\0\0\x01\0\x01\0\0")); @@ -281,6 +360,49 @@ mod tests { assert_eq!(jpeg_segments(&j).xmp_extended.as_deref(), Some("helloworld")); } + #[test] + fn jpeg_icc_accepts_reordered_chunks() { + let parts = [icc_seg(2, 2, b"world"), icc_seg(1, 2, b"hello")]; + let embedded = jpeg_segments(&jpeg_with_icc(&parts)); + assert_eq!(embedded.icc.as_deref(), Some(&b"helloworld"[..])); + } + + #[test] + fn jpeg_icc_rejects_incomplete_or_incoherent_chunks() { + let cases = [ + ("missing", vec![icc_seg(1, 2, b"helloworld")]), + ("duplicate", vec![icc_seg(1, 2, b"hello"), icc_seg(1, 2, b"world")]), + ("zero sequence", vec![icc_seg(0, 1, b"helloworld")]), + ("zero total", vec![icc_seg(1, 0, b"helloworld")]), + ("out of range", vec![icc_seg(2, 1, b"helloworld")]), + ("gap", vec![icc_seg(1, 3, b"hello"), icc_seg(3, 3, b"world")]), + ("inconsistent totals", vec![icc_seg(1, 2, b"hello"), icc_seg(2, 3, b"world")]), + ("short header", vec![seg(0xe2, b"ICC_PROFILE\0\x01")]), + ]; + for (name, parts) in cases { + let embedded = jpeg_segments(&jpeg_with_icc(&parts)); + assert!(embedded.icc.is_none(), "{name} ICC chunks must be rejected"); + assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("retained")), "{name}: unrelated XMP must remain readable"); + } + } + + #[test] + fn jpeg_icc_rejects_truncated_segment_and_keeps_other_metadata() { + let mut truncated = icc_seg(1, 1, b"profile"); + let declared = u16::from_be_bytes([truncated[2], truncated[3]]).saturating_add(1); + truncated[2..4].copy_from_slice(&declared.to_be_bytes()); + let mut jpeg = vec![0xff, 0xd8]; + let xmp = crate::write_xmp(&crate::Metadata { title: Some("kept".into()), ..Default::default() }, None); + let mut packet = XMP_SIG.to_vec(); + packet.extend_from_slice(xmp.as_bytes()); + jpeg.extend_from_slice(&seg(0xe1, &packet)); + jpeg.extend_from_slice(&truncated); + + let embedded = jpeg_segments(&jpeg); + assert!(embedded.icc.is_none()); + assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("kept"))); + } + #[test] fn png_and_webp() { let exif = sample_exif(ByteOrder::Little); diff --git a/crates/meta/src/cr3.rs b/crates/meta/src/cr3.rs index 55b3ae6a6d..a95b8baada 100644 --- a/crates/meta/src/cr3.rs +++ b/crates/meta/src/cr3.rs @@ -229,7 +229,7 @@ const CANON_UUID: [u8; 16] = [0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x /// The `uuid` of the top-level box holding the XMP packet. pub const XMP_UUID: [u8; 16] = [0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac]; const MAX_DEPTH: usize = 12; -const MAX_BOXES: usize = 4096; +pub(crate) const MAX_BOXES: usize = 4096; /// A `VisualSampleEntry` (78 bytes after the box header) plus 4 bytes Canon adds before the child boxes. const CRAW_CHILDREN_AT: usize = 82; @@ -256,16 +256,16 @@ pub fn parse_cr3(bytes: &[u8]) -> Option> { Some(out) } -struct BoxRef { - kind: [u8; 4], +pub(crate) struct BoxRef { + pub(crate) kind: [u8; 4], /// Start of the payload (after the header and, for `uuid`, the 16-byte uuid). - body: usize, - end: usize, - uuid: Option<[u8; 16]>, + pub(crate) body: usize, + pub(crate) end: usize, + pub(crate) uuid: Option<[u8; 16]>, } /// The boxes directly inside `[from, to)`; stops at the first malformed header. -fn boxes(bytes: &[u8], from: usize, to: usize, budget: &mut usize) -> Vec { +pub(crate) fn boxes(bytes: &[u8], from: usize, to: usize, budget: &mut usize) -> Vec { let mut out = Vec::new(); let mut at = from; let to = to.min(bytes.len()); @@ -407,13 +407,16 @@ fn sample_entry(bytes: &[u8], e: &BoxRef, budget: &mut usize) -> Cr3TrackKind { Cr3TrackKind::Raw { width, height, cmp1, iad1 } } -fn be16(b: &[u8], at: usize) -> Option { +/// A big-endian `u16` at `at`, or `None` when the buffer is shorter than that. +pub(crate) fn be16(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(2)?).map(|s| u16::from_be_bytes([s[0], s[1]])) } -fn be32(b: &[u8], at: usize) -> Option { +/// A big-endian `u32` at `at`, or `None` when the buffer is shorter than that. +pub(crate) fn be32(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])) } -fn be64(b: &[u8], at: usize) -> Option { +/// A big-endian `u64` at `at`, or `None` when the buffer is shorter than that. +pub(crate) fn be64(b: &[u8], at: usize) -> Option { let s = b.get(at..at.checked_add(8)?)?; let mut a = [0u8; 8]; a.copy_from_slice(s); diff --git a/crates/meta/src/datetime.rs b/crates/meta/src/datetime.rs index 4b7d09634a..4141f4ae07 100644 --- a/crates/meta/src/datetime.rs +++ b/crates/meta/src/datetime.rs @@ -31,7 +31,7 @@ impl DateTime { // chrono rejects impossible days (leap years and all); the time is checked // by hand so a leap second (`second == 60`) stays acceptable. let day_ok = self.year > 0 && chrono::NaiveDate::from_ymd_opt(i32::from(self.year), u32::from(self.month), u32::from(self.day)).is_some(); - let ok = day_ok && self.hour < 24 && self.minute < 60 && self.second < 61 && self.offset_minutes.is_none_or(|o| o.abs() <= 18 * 60); + let ok = day_ok && self.hour < 24 && self.minute < 60 && self.second < 61 && self.offset_minutes.is_none_or(|o| o.unsigned_abs() <= 18 * 60); ok.then_some(self) } @@ -43,15 +43,27 @@ impl DateTime { if dp.len() != 3 { return None; } - let tp: Vec<&str> = if t.is_empty() { vec![] } else { t.split(':').collect() }; - let g = |v: &Vec<&str>, i: usize| v.get(i).map(|x| num(x.trim())).unwrap_or(Some(0)); + let (hour, minute, second) = if t.is_empty() { + (0, 0, 0) + } else { + let mut parts = t.split(':'); + let hour = num(parts.next()?.trim())?; + let minute = parts.next().map(|part| num(part.trim())).unwrap_or(Some(0))?; + let second = parts.next().map(|part| num(part.trim())).unwrap_or(Some(0))?; + // A fourth value cannot be represented; accepting only the prefix could turn a + // malformed DateTimeOriginal into a plausible capture time and block fallbacks. + if parts.next().is_some() { + return None; + } + (hour, minute, second) + }; DateTime { year: num(dp[0])?.try_into().ok()?, month: num(dp[1])?.try_into().ok()?, day: num(dp[2])?.try_into().ok()?, - hour: g(&tp, 0)?.try_into().ok()?, - minute: g(&tp, 1)?.try_into().ok()?, - second: g(&tp, 2)?.try_into().ok()?, + hour: hour.try_into().ok()?, + minute: minute.try_into().ok()?, + second: second.try_into().ok()?, millis: 0, offset_minutes: None, } @@ -74,7 +86,7 @@ impl DateTime { None if rest.len() == 4 => (num(rest.get(..2)?)?, num(rest.get(2..)?)?), None => (num(rest)?, 0), }; - if h > 18 || m > 59 { + if h > 18 || m > 59 || (h == 18 && m > 0) { return None; } Some(sign * (h * 60 + m) as i16) @@ -93,7 +105,11 @@ impl DateTime { /// ISO 8601 (XMP date): `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDThh:mm[:ss[.s+]][TZD]`. pub fn parse_iso(s: &str) -> Option { let s = s.trim(); - let (d, t) = s.split_once('T').unwrap_or((s, "")); + let (d, t) = match s.split_once('T') { + Some((d, t)) if !t.is_empty() => (d, t), + Some(_) => return None, + None => (s, ""), + }; let dp: Vec<&str> = d.split('-').collect(); let year = num(dp.first()?)?.try_into().ok()?; let month = dp.get(1).map(|m| num(m)).unwrap_or(Some(1))?.try_into().ok()?; @@ -107,13 +123,26 @@ impl DateTime { Some(i) => (&t[..i], Some(&t[i..])), None => (t, None), }; - let cp: Vec<&str> = clock.split(':').collect(); - dt.hour = num(cp.first()?)?.try_into().ok()?; - dt.minute = num(cp.get(1)?)?.try_into().ok()?; - if let Some(sec) = cp.get(2) { - let (whole, frac) = sec.split_once('.').unwrap_or((sec, "")); + let mut cp = clock.split(':'); + dt.hour = num(cp.next()?)?.try_into().ok()?; + dt.minute = num(cp.next()?)?.try_into().ok()?; + if let Some(sec) = cp.next() { + let (whole, fraction) = match sec.split_once('.') { + Some((whole, fraction)) => { + if fraction.is_empty() || !fraction.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + (whole, Some(fraction)) + } + None => (sec, None), + }; dt.second = num(whole)?.try_into().ok()?; - dt = dt.with_subsec(frac); + if let Some(fraction) = fraction { + dt = dt.with_subsec(fraction); + } + } + if cp.next().is_some() { + return None; } if let Some(o) = off { dt.offset_minutes = Some(Self::parse_offset(o)?); @@ -135,7 +164,8 @@ impl DateTime { } if let Some(o) = self.offset_minutes { let sign = if o < 0 { '-' } else { '+' }; - s += &format!("{sign}{:02}:{:02}", o.abs() / 60, o.abs() % 60); + let o = o.unsigned_abs(); + s += &format!("{sign}{:02}:{:02}", o / 60, o % 60); } s } @@ -179,16 +209,52 @@ mod tests { assert_eq!(DateTime::parse_exif("2024:06:01 13:45:59").unwrap().with_subsec("0123").millis, 12); } + #[test] + fn exif_clock_rejects_extra_components() { + for value in + ["2026:01:01 12:34:56:99", "2026:01:01 12:34:56:junk", "2026:01:01 12:34:56:", "2026:01:01 12:34:56::", "2026:01:01 12:34:56:99:junk"] + { + assert!(DateTime::parse_exif(value).is_none(), "accepted malformed EXIF clock {value:?}"); + } + } + + #[test] + fn exif_clock_supported_forms_keep_their_meaning() { + for (value, expected) in [ + ("2026:01:01", "2026-01-01T00:00:00"), + ("2026:01:01 12", "2026-01-01T12:00:00"), + ("2026:01:01 12:34", "2026-01-01T12:34:00"), + ("2026:01:01 12:34:56", "2026-01-01T12:34:56"), + ("2026-01-01T12:34:56", "2026-01-01T12:34:56"), + (" 2026:01:01 12:34:56\0", "2026-01-01T12:34:56"), + ("2026:01:01T12:34:60", "2026-01-01T12:34:60"), + ] { + assert_eq!(DateTime::parse_exif(value).map(|date| date.to_iso()), Some(expected.to_string()), "{value:?}"); + } + } + #[test] fn offsets() { assert_eq!(DateTime::parse_offset("+02:00"), Some(120)); assert_eq!(DateTime::parse_offset("-05:30"), Some(-330)); assert_eq!(DateTime::parse_offset("Z"), Some(0)); assert_eq!(DateTime::parse_offset("+0930"), Some(570)); + assert_eq!(DateTime::parse_offset("+18:00"), Some(1080)); + assert_eq!(DateTime::parse_offset("-18:00"), Some(-1080)); + assert_eq!(DateTime::parse_offset("+18:01"), None); + assert_eq!(DateTime::parse_offset("-18:01"), None); assert_eq!(DateTime::parse_offset(" : "), None); assert_eq!(DateTime::parse_offset("+99:00"), None); } + #[test] + fn extreme_offsets_do_not_overflow() { + // `DateTime` deserializes with public fields, so an offset can arrive without passing `valid()` + let d = DateTime { offset_minutes: Some(i16::MIN), ..DateTime::parse_iso("2024-06-01T13:45:59").unwrap() }; + assert_eq!(d.to_iso(), "2024-06-01T13:45:59-546:08"); + assert_eq!(d.valid(), None); + } + #[test] fn unicode_offsets_are_rejected_without_panicking() { for offset in ["+1€", "-1€", "+€1", "-€1"] { @@ -215,6 +281,36 @@ mod tests { assert!(DateTime::parse_iso("2019-07-04Tab:cd").is_none()); } + #[test] + fn iso_rejects_incomplete_or_unconsumed_clock_text() { + for value in [ + "2026-01-01T", + "2026-01-01T12:34:56:99Z", + "2026-01-01T12:34:56.Z", + "2026-01-01T12:34:56.123junkZ", + "2026-01-01T12:34:56.1.2Z", + "2026-01-01T12:34:56.12 3Z", + "2026-01-01T12:34:56:99Z", + "2026-01-01T12::34Z", + ] { + assert!(DateTime::parse_iso(value).is_none(), "accepted malformed timestamp {value:?}"); + } + } + + #[test] + fn iso_validates_clock_while_preserving_supported_forms() { + assert_eq!(DateTime::parse_iso("2019").unwrap().to_iso(), "2019-01-01T00:00:00"); + assert_eq!(DateTime::parse_iso("2019-07").unwrap().to_iso(), "2019-07-01T00:00:00"); + assert_eq!(DateTime::parse_iso("2019-07-04").unwrap().to_iso(), "2019-07-04T00:00:00"); + assert_eq!(DateTime::parse_iso("2019-07-04T10:11").unwrap().to_iso(), "2019-07-04T10:11:00"); + assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12").unwrap().to_iso(), "2019-07-04T10:11:12"); + assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12Z").unwrap().offset_minutes, Some(0)); + assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12-05:30").unwrap().offset_minutes, Some(-330)); + assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12.123456Z").unwrap().millis, 123); + assert_eq!(DateTime::parse_iso(" 2019-07-04T10:11:12.5Z ").unwrap().millis, 500); + assert_eq!(DateTime::parse_iso("2019-07-04T10:11:60Z").unwrap().second, 60); + } + #[test] fn unix() { assert_eq!(DateTime::parse_iso("1970-01-01T00:00:00Z").unwrap().unix_seconds(), 0); diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index adcba0f807..259fc5f9f3 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -27,9 +27,9 @@ pub fn try_read_exif_with(bytes: &[u8], opts: &ParseOptions) -> Result Option { panasonic_lens(data, &Tiff::parse(data).ok()?) } +/// Canon maker note tag `0x0095` (LensModel in the ExifTool Canon tag names): the lens name as ASCII. Older +/// bodies instead record a numeric LensType (CameraSettings, tag `0x0001`, index 22), which is no name to read. +const CANON_LENS_MODEL: u16 = 0x0095; + +/// The lens name in a Canon maker note of this Exif stream (`data` starts at its TIFF header): the note of +/// its own Exif IFD. Only consulted when Make is Canon, so other vendors' plain notes are never read as lenses. +fn canon_maker_note_lens(data: &[u8], tiff: &Tiff) -> Option { + let make = tiff.ifds.first().and_then(|i| i.string(t::MAKE)).unwrap_or_default(); + if !make.trim().to_ascii_uppercase().starts_with("CANON") { + return None; + } + let exif = tiff.exif()?; + let e = exif.get(t::MAKER_NOTE)?; + let mn = lightcraft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?; + text(Some(&mn.ifd), CANON_LENS_MODEL) +} + /// Nikon maker note tag `0x0084` (Lens in the ExifTool Nikon tag names): shortest and longest focal length, then the /// widest aperture at each, as rationals, like Exif LensSpecification. Zero for a lens that doesn't report itself. const NIKON_LENS: u16 = 0x0084; @@ -225,6 +242,53 @@ pub(crate) mod tests { use super::*; use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + fn capture_time_tiff(original: Option<&str>, digitized: Option<&str>, ifd0_time: Option<&str>, xmp: Option<&str>) -> Vec { + let mut exif = IfdBuilder::new(); + if let Some(value) = original { + exif.set(t::DATE_TIME_ORIGINAL, Value::Ascii(value.into())); + } + if let Some(value) = digitized { + exif.set(t::DATE_TIME_DIGITIZED, Value::Ascii(value.into())); + } + let mut ifd0 = IfdBuilder::new(); + if let Some(value) = ifd0_time { + ifd0.set(t::DATE_TIME, Value::Ascii(value.into())); + } + ifd0.set_child(t::EXIF_IFD, exif); + if let Some(packet) = xmp { + ifd0.set(t::XMP, Value::Byte(packet.as_bytes().to_vec())); + } + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() + } + + #[test] + fn exif_clock_invalid_original_uses_the_next_valid_exif_time() { + let invalid = "2026:01:01 12:34:56:99"; + let digitized = capture_time_tiff(Some(invalid), Some("2026:01:02 10:00:00"), Some("2026:01:03 11:00:00"), None); + assert_eq!(read_exif(&digitized).capture_time.map(|date| date.to_iso()), Some("2026-01-02T10:00:00".into())); + + let ifd0 = capture_time_tiff(Some(invalid), Some("2026:01:02 10:00:00:"), Some("2026:01:03 11:00:00"), None); + assert_eq!(read_exif(&ifd0).capture_time.map(|date| date.to_iso()), Some("2026-01-03T11:00:00".into())); + + let none = capture_time_tiff(Some(invalid), Some("2026:01:02 10:00:00:junk"), Some("2026:01:03 11:00:00:"), None); + assert_eq!(read_exif(&none).capture_time, None); + + let original = capture_time_tiff(Some("2026:01:04 12:00:00"), Some("2026:01:02 10:00:00"), Some("2026:01:03 11:00:00"), None); + assert_eq!(read_exif(&original).capture_time.map(|date| date.to_iso()), Some("2026-01-04T12:00:00".into())); + } + + #[test] + fn exif_clock_invalid_original_allows_xmp_fallback_and_keeps_raw_tag() { + let capture = DateTime::parse_iso("2026-01-02T10:00:00Z"); + let packet = crate::write_xmp(&Metadata { capture_time: capture, ..Default::default() }, None); + let bytes = capture_time_tiff(Some("2026:01:01 12:34:56:99"), None, None, Some(&packet)); + assert_eq!(crate::extract(&bytes).capture_time.map(|date| date.to_iso()), Some("2026-01-02T10:00:00+00:00".into())); + + let without_fallback = capture_time_tiff(Some("2026:01:01 12:34:56:junk"), None, None, None); + assert_eq!(crate::extract(&without_fallback).capture_time, None); + assert!(crate::embedded(&without_fallback).exif.is_some(), "rejecting the projection must retain the embedded EXIF block"); + } + /// An Exif block from a Panasonic body: no LensModel, the lens name in maker note tag 0x0051, whose value /// lies outside the note's IFD at an offset relative to the Exif TIFF header (as Panasonic writes it). pub(crate) fn panasonic_exif(order: ByteOrder, lens: Option<&str>, lens_model: Option<&str>) -> Vec { @@ -297,6 +361,68 @@ pub(crate) mod tests { assert_eq!(crate::extract(&rw2).lens_model.as_deref(), Some("LUMIX S 85/F1.8")); } + /// Canon maker note tags: `0x0095` holds the lens name as ASCII; `0x0001` is CameraSettings, a table of + /// int16s whose index 22 is the numeric LensType. + const CANON_LENS_MODEL_TAG: u16 = 0x0095; + const CANON_CAMERA_SETTINGS: u16 = 0x0001; + + /// An Exif block from a Canon EOS 5D: `Canon` / `Canon EOS 5D` in IFD0, no LensModel tag, and a plain maker + /// note whose IFD (value offsets relative to the enclosing TIFF header, as Canon writes it) records + /// CameraSettings with the numeric LensType at index 22 and, when `lens` is given, the name at `0x0095`. + fn canon_exif(order: ByteOrder, lens: Option<&str>) -> Vec { + let note = |at: u32| { + // The plain IFD: entry count, one or two 12-byte entries and the next-IFD pointer, then the + // out-of-line values (CameraSettings, then the lens name when present). + // pointer, then the out-of-line values (CameraSettings, then the lens name when present). + let settings_at = at + 2 + 12 * (1 + lens.is_some() as u32) + 4; + let name_at = settings_at + 60; + let mut v = Vec::new(); + let entry = |v: &mut Vec, tag: u16, kind: u16, count: u32, off: u32| { + order.put_u16(v, tag); + order.put_u16(v, kind); + order.put_u32(v, count); + order.put_u32(v, off); + }; + order.put_u16(&mut v, 1 + lens.is_some() as u16); + entry(&mut v, CANON_CAMERA_SETTINGS, 3, 30, settings_at); + if let Some(name) = lens { + entry(&mut v, CANON_LENS_MODEL_TAG, 2, name.len() as u32, name_at); + } + order.put_u32(&mut v, 0); + for i in 0..30u16 { + order.put_u16(&mut v, if i == 22 { 178 } else { 0 }); // 22: numeric LensType, no name + } + if let Some(name) = lens { + v.extend_from_slice(name.as_bytes()); + } + v + }; + let build = |at: u32| { + let mut exif = IfdBuilder::new(); + exif.set(t::MAKER_NOTE, Value::Undefined(note(at))); + exif.set(t::FOCAL_LENGTH, Value::Rational(vec![(50, 1)])); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Canon".into())); + ifd0.set(t::MODEL, Value::Ascii("Canon EOS 5D".into())); + ifd0.set_child(t::EXIF_IFD, exif); + TiffWriter::new(order, false).write(&[ifd0]).unwrap() + }; + // the note's own offset is only known once it is laid out; its length doesn't change + let first = build(0); + let at = Tiff::parse(&first).unwrap().exif().unwrap().get(t::MAKER_NOTE).unwrap().offset as u32; + build(at) + } + + #[test] + fn canon_maker_note_lens_fills_lens_model() { + for order in [ByteOrder::Little, ByteOrder::Big] { + let m = read_exif(&canon_exif(order, Some("Canon EF 50mm f/1.8 II"))); + assert_eq!(m.lens_model.as_deref(), Some("Canon EF 50mm f/1.8 II")); + // a note that only records the numeric LensType has no name to fill in + assert_eq!(read_exif(&canon_exif(order, None)).lens_model, None); + } + } + /// An Exif block from a Nikon body whose maker note records the lens (tag 0x0084) and no LensModel or /// LensSpecification, as the D700, D750, D80 and D5300 write it. fn nikon_exif(make: &str, lens: Option<[(u32, u32); 4]>, spec: Option<[(u32, u32); 4]>) -> Vec { @@ -512,6 +638,20 @@ pub fn write_exif(meta: &Metadata) -> Vec { ex.set(tag, v); } } + if let Some(d) = meta.capture_time { + // an offset past 18 h is not a real one (a deserialized value can be anything): write none + let offset = d.offset_minutes.filter(|o| o.unsigned_abs() <= 18 * 60).map(|o| { + let sign = if o < 0 { '-' } else { '+' }; + format!("{sign}{:02}:{:02}", o.unsigned_abs() / 60, o.unsigned_abs() % 60) + }); + let subsec = (d.millis != 0).then(|| format!("{:03}", d.millis)); + for (tag, v) in [(t::OFFSET_TIME, &offset), (t::OFFSET_TIME_ORIGINAL, &offset), (t::SUBSEC_TIME, &subsec), (t::SUBSEC_TIME_ORIGINAL, &subsec)] + { + if let Some(v) = v { + ex.set(tag, Value::Ascii(v.clone())); + } + } + } ifd0.set_child(t::EXIF_IFD, ex); if let Some(g) = meta.gps { let dms = |v: f64| { @@ -540,6 +680,25 @@ pub fn write_exif(meta: &Metadata) -> Vec { mod write_tests { use super::*; + #[test] + fn capture_time_offset_and_subsec_round_trip() { + for iso in ["2026-09-20T05:40:00.250+02:00", "2026-09-20T05:40:00.005-03:30", "2026-09-20T05:40:00"] { + let m = Metadata { capture_time: DateTime::parse_iso(iso), ..Default::default() }; + assert_eq!(read_exif(&write_exif(&m)).capture_time, m.capture_time, "{iso}"); + } + } + + /// A deserialized offset can be any i16, `i16::MIN` included: writing must not overflow. + #[test] + fn extreme_capture_time_offsets_do_not_panic() { + for o in [i16::MIN, i16::MAX, -1081, 1081] { + let mut dt = DateTime::parse_iso("2026-09-20T05:40:00").unwrap(); + dt.offset_minutes = Some(o); + let m = Metadata { capture_time: Some(dt), ..Default::default() }; + assert_eq!(read_exif(&write_exif(&m)).capture_time.map(|d| d.offset_minutes), Some(None), "{o}"); + } + } + #[test] fn exif_round_trips() { let m = Metadata { diff --git a/crates/meta/src/gpx.rs b/crates/meta/src/gpx.rs index 204e391162..691a2b7e19 100644 --- a/crates/meta/src/gpx.rs +++ b/crates/meta/src/gpx.rs @@ -101,6 +101,7 @@ pub fn parse_gpx(s: &str) -> Result { reader.config_mut().check_end_names = true; let mut path: Vec> = Vec::new(); let mut seen_gpx = false; + let mut seen_root = false; let mut log = Tracklog::default(); let mut segment: u32 = 0; let mut pt: Option = None; @@ -111,6 +112,12 @@ pub fn parse_gpx(s: &str) -> Result { Event::Start(ref e) | Event::Empty(ref e) => { let name = local(e.name().as_ref()).to_vec(); let parent = path.last().map(Vec::as_slice); + if path.is_empty() { + if seen_root { + return Err(GpxError::Xml("multiple document elements".into())); + } + seen_root = true; + } match name.as_slice() { b"gpx" if path.is_empty() => seen_gpx = true, b"trk" if parent == Some(b"gpx") => log.tracks += 1, @@ -118,10 +125,19 @@ pub fn parse_gpx(s: &str) -> Result { b"trkpt" if parent == Some(b"trkseg") => { let mut p = Pending::default(); for a in e.attributes().with_checks(false).flatten() { - let v = String::from_utf8_lossy(&a.value); match local(a.key.as_ref()) { - b"lat" => p.lat = v.trim().parse().ok(), - b"lon" => p.lon = v.trim().parse().ok(), + b"lat" => { + let v = a + .decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder()) + .map_err(|e| GpxError::Xml(e.to_string()))?; + p.lat = v.trim().parse().ok(); + } + b"lon" => { + let v = a + .decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder()) + .map_err(|e| GpxError::Xml(e.to_string()))?; + p.lon = v.trim().parse().ok(); + } _ => {} } } @@ -141,6 +157,16 @@ pub fn parse_gpx(s: &str) -> Result { } Event::Text(t) => text.push_str(&t.decode().map_err(|e| GpxError::Xml(e.to_string()))?), Event::CData(t) => text.push_str(&String::from_utf8_lossy(&t)), + Event::GeneralRef(r) => { + if let Some(c) = r.resolve_char_ref().map_err(|e| GpxError::Xml(e.to_string()))? { + text.push(c); + } else { + let name = r.decode().map_err(|e| GpxError::Xml(e.to_string()))?; + let entity = format!("&{name};"); + let value = quick_xml::escape::unescape(&entity).map_err(|e| GpxError::Xml(e.to_string()))?; + text.push_str(value.as_ref()); + } + } Event::End(_) => { let Some(name) = path.pop() else { continue }; let parent = path.last().map(Vec::as_slice); @@ -303,6 +329,19 @@ mod tests { assert_eq!(log.points[0].time, 1_777_629_600.0); } + #[test] + fn malformed_iso_time_is_untimed_and_cannot_match_midnight() { + let source = r#" + + + "#; + let log = parse_gpx(source).unwrap(); + assert_eq!(log.untimed, 1); + assert_eq!(log.points.len(), 1); + assert_eq!((log.points[0].latitude, log.points[0].longitude), (46.0, 8.0)); + assert!(log.locate(t("2026-01-01T00:00:00Z"), 0.0).is_none()); + } + #[test] fn interpolates_within_a_segment() { let log = parse_gpx(LOG).unwrap(); @@ -351,6 +390,60 @@ mod tests { assert_eq!(log.points[1].time - log.points[0].time, 60.0); } + fn point_document(lat: &str, lon: &str, ele: &str, time: &str) -> String { + format!( + r#"{ele}"# + ) + } + + #[test] + fn character_reference_elevation_is_not_truncated() { + let log = parse_gpx(&point_document("45", "7", "123", "2026-01-01T00:00:00Z")).unwrap(); + assert_eq!(log.points.first().and_then(|p| p.elevation), Some(123.0)); + } + + #[test] + fn character_reference_latitude_is_not_dropped() { + let log = parse_gpx(&point_document("45", "7.5", "123", "2026-01-01T00:00:00Z")).unwrap(); + let point = log.points.first().copied(); + assert_eq!(log.points.len(), 1); + assert_eq!(point.map(|p| (p.latitude, p.longitude)), Some((45.0, 7.5))); + } + + #[test] + fn character_reference_time_is_not_shifted() { + let encoded = parse_gpx(&point_document("45", "7", "123", "2026-01-01T00:00:30Z")).unwrap(); + let plain = parse_gpx(&point_document("45", "7", "123", "2026-01-01T00:00:30Z")).unwrap(); + assert_eq!(encoded.points.first().map(|p| p.time), plain.points.first().map(|p| p.time)); + assert_eq!(encoded.points.first().map(|p| p.time), Some(1_767_225_630.0)); + } + + #[test] + fn predefined_entities_are_decoded_once_and_cdata_stays_literal() { + let with_predefined_entity = point_document("45", "7", "1&23", "2026-01-01T00:00:00Z"); + let log = parse_gpx(&with_predefined_entity).unwrap(); + assert_eq!(log.points.first().and_then(|p| p.elevation), None); + + let cdata = point_document("45", "7", "", "2026-01-01T00:00:00Z"); + let log = parse_gpx(&cdata).unwrap(); + assert_eq!(log.points.first().and_then(|p| p.elevation), None); + } + + #[test] + fn unknown_and_malformed_character_references_are_rejected() { + let unknown = point_document("45", "7", "&undeclared;", "2026-01-01T00:00:00Z"); + assert!(matches!(parse_gpx(&unknown), Err(GpxError::Xml(_)))); + + let malformed = point_document("45", "7", "&#xZZ;", "2026-01-01T00:00:00Z"); + assert!(matches!(parse_gpx(&malformed), Err(GpxError::Xml(_)))); + + let unknown_attribute = point_document("4&undeclared;", "7", "123", "2026-01-01T00:00:00Z"); + assert!(matches!(parse_gpx(&unknown_attribute), Err(GpxError::Xml(_)))); + + let malformed_attribute = point_document("&#xZZ;", "7", "123", "2026-01-01T00:00:00Z"); + assert!(matches!(parse_gpx(&malformed_attribute), Err(GpxError::Xml(_)))); + } + #[test] fn non_finite_elevation_is_dropped() { for ele in ["inf", "-inf", "NaN", "infinity"] { @@ -371,6 +464,11 @@ mod tests { assert!((g.longitude - -179.5).abs() < 1e-9, "{g:?}"); } + #[test] + fn rejects_multiple_document_roots() { + assert!(matches!(parse_gpx(""), Err(GpxError::Xml(_)))); + } + #[test] fn rejects_non_gpx_and_bad_input() { assert_eq!(parse_gpx(""), Err(GpxError::NotGpx)); diff --git a/crates/meta/src/heif.rs b/crates/meta/src/heif.rs new file mode 100644 index 0000000000..1d768f7a69 --- /dev/null +++ b/crates/meta/src/heif.rs @@ -0,0 +1,405 @@ +//! HEIF / HEIC / AVIF metadata: the `Exif` and XMP items of the ISO base media file container +//! (box structure from ISO/IEC 14496-12, item model from ISO/IEC 23008-12). +//! +//! HEIC is what iPhones and Macs write. Its pixels need an HEVC decoder (the optional +//! `lightcraft-heif` crate), its metadata does not, so this reader is in every build: a HEIC +//! imports with its capture time, camera and lens whether or not the build can show the picture. +//! +//! The `meta` box holds an item information box (`iinf`, one `infe` per item) naming each item's +//! type, and an item location box (`iloc`) saying where its bytes are: in the file, or in the +//! `idat` box next to it. The `Exif` item is a four-byte offset followed by a TIFF stream; the XMP +//! packet is a `mime` item whose content type is `application/rdf+xml`. The ICC profile is an item +//! *property*, not an item, and is read by the decoder instead. + +use crate::container::Embedded; +use crate::cr3::{MAX_BOXES, be16, be32, be64, boxes}; + +/// Brands that declare a still image in the ISO base media container. +const IMAGE_BRANDS: [&[u8]; 12] = [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"hevm", b"hevs", b"mif1", b"msf1", b"avif", b"avis"]; + +/// Longest `ftyp` box this reads brands from. +const MAX_FTYP: usize = 4096; +/// Most items one file's `iinf` / `iloc` describes (an iPhone HEIC has a handful). +const MAX_ITEMS: usize = 1024; +/// Most extents one item's bytes are split into. +const MAX_EXTENTS: u16 = 1024; +/// Largest metadata item this returns; a real photo's Exif and XMP are a few hundred kilobytes. +const MAX_ITEM: usize = 32 << 20; + +/// Does this file declare an ISO base media still image (HEIF / HEIC / AVIF)? +pub fn is_heif(bytes: &[u8]) -> bool { + if bytes.get(4..8) != Some(b"ftyp".as_slice()) { + return false; + } + let Some(size) = be32(bytes, 0).map(|v| v as usize) else { + return false; + }; + let end = size.min(bytes.len()).min(MAX_FTYP); + let brand = |at: usize| bytes.get(at..at.saturating_add(4)).is_some_and(|b| IMAGE_BRANDS.contains(&b)); + // the major brand, then (after the minor version) the compatible brands + brand(8) || (16..end).step_by(4).any(brand) +} + +/// The Exif and XMP blocks of a HEIF file. Anything malformed is left out rather than reported: +/// a file whose items can't be located simply has no metadata, as before this reader existed. +pub fn metadata(bytes: &[u8]) -> Embedded { + let mut out = Embedded::default(); + let mut budget = MAX_BOXES; + let Some(meta) = boxes(bytes, 0, bytes.len(), &mut budget).into_iter().find(|b| &b.kind == b"meta") else { + return out; + }; + // `meta` is a FullBox: a version and flags before its children + let (mut items, mut locs, mut idat) = (Vec::new(), Vec::new(), None); + for b in boxes(bytes, meta.body.saturating_add(4), meta.end, &mut budget) { + match &b.kind { + b"iinf" => items = item_infos(bytes, &b, &mut budget), + b"iloc" => locs = item_locations(bytes.get(b.body..b.end).unwrap_or_default()), + b"idat" => idat = bytes.get(b.body..b.end), + _ => {} + } + } + for (id, kind, content_type) in items { + let want_exif = &kind == b"Exif" && out.exif.is_none(); + let want_xmp = &kind == b"mime" && content_type == "application/rdf+xml" && out.xmp.is_none(); + if !want_exif && !want_xmp { + continue; + } + let Some(loc) = locs.iter().find(|l| l.id == id) else { continue }; + let Some(block) = item_bytes(bytes, idat, loc) else { continue }; + if want_exif { + // ISO/IEC 23008-12 A.2.1: a four-byte offset from the end of itself to the TIFF header + let skip = be32(&block, 0).and_then(|v| usize::try_from(v).ok()).and_then(|v| v.checked_add(4)); + out.exif = skip.and_then(|at| block.get(at..)).filter(|b| !b.is_empty()).map(<[u8]>::to_vec); + } else { + out.xmp = Some(String::from_utf8_lossy(&block).trim_end_matches('\0').to_string()); + } + } + out +} + +/// `iinf` → one `(item_ID, item_type, content_type)` per `infe` entry. Entries of version 0 and 1 +/// name no item type and are skipped; HEIF files use version 2 or 3. +fn item_infos(bytes: &[u8], iinf: &crate::cr3::BoxRef, budget: &mut usize) -> Vec<(u32, [u8; 4], String)> { + // FullBox version and flags, then a 16- or 32-bit entry count before the `infe` boxes + let version = *bytes.get(iinf.body).unwrap_or(&0); + let entries_at = iinf.body.saturating_add(if version == 0 { 6 } else { 8 }); + let mut out = Vec::new(); + for b in boxes(bytes, entries_at, iinf.end, budget) { + if &b.kind != b"infe" || out.len() >= MAX_ITEMS { + continue; + } + let Some(e) = bytes.get(b.body..b.end) else { continue }; + let (id, kind_at) = match *e.first().unwrap_or(&0) { + 2 => (be16(e, 4).map(u32::from), 8), + 3 => (be32(e, 4), 10), + _ => continue, + }; + let (Some(id), Some(kind)) = (id, e.get(kind_at..kind_at + 4)) else { continue }; + let mut kind4 = [0u8; 4]; + kind4.copy_from_slice(kind); + // the item name, then (for a `mime` item) the content type, both NUL-terminated + let mut strings = e.get(kind_at + 4..).unwrap_or_default().split(|&c| c == 0).skip(1); + let content_type = String::from_utf8_lossy(strings.next().unwrap_or_default()).into_owned(); + out.push((id, kind4, content_type)); + } + out +} + +/// Where one item's bytes are. +struct Loc { + id: u32, + /// 0 = offsets into the file, 1 = into the `idat` box, 2 = another item (not read). + construction: u8, + base: u64, + /// `(offset, length)` per extent, in order. + extents: Vec<(u64, u64)>, +} + +/// `iloc` (payload after the box header) → one [`Loc`] per entry, stopping at the first +/// unreadable one. +fn item_locations(p: &[u8]) -> Vec { + let version = *p.first().unwrap_or(&0); + let (Some(sizes), Some(base_index)) = (p.get(4), p.get(5)) else { return Vec::new() }; + let (offset_size, length_size) = ((sizes >> 4) as usize, (sizes & 0xf) as usize); + let (base_size, index_size) = ((base_index >> 4) as usize, if version > 0 { (base_index & 0xf) as usize } else { 0 }); + let (count, mut at) = match version { + 0 | 1 => (be16(p, 6).map(usize::from), 8), + 2 => (be32(p, 6).and_then(|v| usize::try_from(v).ok()), 10), + _ => return Vec::new(), + }; + let mut out = Vec::new(); + for _ in 0..count.unwrap_or(0).min(MAX_ITEMS) { + let (id, after_id) = match version { + 2 => (be32(p, at), at + 4), + _ => (be16(p, at).map(u32::from), at + 2), + }; + // version 1 and 2 put the construction method in the low nibble of a reserved 16-bit field + let construction = if version == 0 { Some(0) } else { be16(p, after_id).map(|v| (v & 0xf) as u8) }; + let after_method = after_id + if version == 0 { 0 } else { 2 }; + // a data reference index of 0 means this file; an external reference has no bytes here + let external = be16(p, after_method).is_some_and(|v| v != 0); + let base = uint(p, after_method + 2, base_size); + let extent_at = after_method + 2 + base_size; + let (Some(id), Some(construction), Some(base), Some(extent_count)) = (id, construction, base, be16(p, extent_at)) else { + break; + }; + let stride = index_size + offset_size + length_size; + let mut extents = Vec::new(); + let mut e = extent_at + 2; + for _ in 0..extent_count.min(MAX_EXTENTS) { + let (Some(offset), Some(length)) = (uint(p, e + index_size, offset_size), uint(p, e + index_size + offset_size, length_size)) else { + return out; + }; + extents.push((offset, length)); + e += stride; + } + at = e; + if !external { + out.push(Loc { id, construction, base, extents }); + } + } + out +} + +/// A big-endian unsigned integer of `size` bytes; `size` 0 is the value 0, and the item boxes +/// allow no other width than 4 or 8. +fn uint(b: &[u8], at: usize, size: usize) -> Option { + match size { + 0 => Some(0), + 4 => be32(b, at).map(u64::from), + 8 => be64(b, at), + _ => None, + } +} + +/// An item's bytes, its extents concatenated. `None` when they don't fit the file (or the `idat` +/// box), when the item is built by referencing another one, or when it is implausibly large. +fn item_bytes(bytes: &[u8], idat: Option<&[u8]>, loc: &Loc) -> Option> { + let src = match loc.construction { + 0 => bytes, + 1 => idat?, + _ => return None, + }; + let mut out = Vec::new(); + for &(offset, length) in &loc.extents { + let at = loc.base.checked_add(offset)?; + let (start, end) = (usize::try_from(at).ok()?, usize::try_from(at.checked_add(length)?).ok()?); + let extent = src.get(start..end)?; + if out.len().checked_add(extent.len())? > MAX_ITEM { + return None; + } + out.extend_from_slice(extent); + } + (!out.is_empty()).then_some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + // the whole routing, not just this module: a HEIC must reach the HEIF branch of `embedded` + use crate::embedded; + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + + /// One box: its own size, its four-letter kind, then its payload. + fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut v = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); + v.extend_from_slice(kind); + v.extend_from_slice(payload); + v + } + + /// A FullBox: a box whose payload begins with a version byte and three flag bytes. + fn full_box(kind: &[u8; 4], version: u8, payload: &[u8]) -> Vec { + bx(kind, &[&[version, 0, 0, 0][..], payload].concat()) + } + + struct Item<'a> { + kind: &'a [u8; 4], + content_type: &'a str, + data: Vec, + } + + /// A HEIC-shaped file holding `items`: `ftyp`, a `meta` box with one `infe` per item, and the + /// item bytes in `idat` (`in_idat`, construction method 1) or in `mdat` (method 0). + fn heic(items: &[Item<'_>], iloc_version: u8, in_idat: bool) -> Vec { + let mut iinf = (items.len() as u16).to_be_bytes().to_vec(); + for (i, it) in items.iter().enumerate() { + let mut e = vec![2u8, 0, 0, 0]; // version 2, flags + e.extend_from_slice(&(i as u16 + 1).to_be_bytes()); + e.extend_from_slice(&[0, 0]); // protection index + e.extend_from_slice(it.kind); + e.extend_from_slice(b"an item\0"); + if it.kind == b"mime" { + e.extend_from_slice(it.content_type.as_bytes()); + e.push(0); + } + iinf.extend_from_slice(&bx(b"infe", &e)); + } + let iinf = full_box(b"iinf", 0, &iinf); + let payload: Vec = items.iter().flat_map(|i| i.data.iter().copied()).collect(); + let idat = if in_idat { bx(b"idat", &payload) } else { Vec::new() }; + let iloc = |base: u32| { + // four-byte offsets and lengths, no base offset and no extent index + let mut l = vec![0x44, 0x00]; + match iloc_version { + 2 => l.extend_from_slice(&(items.len() as u32).to_be_bytes()), + _ => l.extend_from_slice(&(items.len() as u16).to_be_bytes()), + } + let mut at = base; + for (i, it) in items.iter().enumerate() { + match iloc_version { + 2 => l.extend_from_slice(&(i as u32 + 1).to_be_bytes()), + _ => l.extend_from_slice(&(i as u16 + 1).to_be_bytes()), + } + if iloc_version > 0 { + l.extend_from_slice(&[0, u8::from(in_idat)]); // construction method + } + l.extend_from_slice(&[0, 0]); // data reference index: this file + l.extend_from_slice(&[0, 1]); // one extent + l.extend_from_slice(&at.to_be_bytes()); + l.extend_from_slice(&(it.data.len() as u32).to_be_bytes()); + at += it.data.len() as u32; + } + full_box(b"iloc", iloc_version, &l) + }; + let ftyp = bx(b"ftyp", b"heic\0\0\0\0mif1heic"); + let meta = |base| full_box(b"meta", 0, &[iloc(base), iinf.clone(), idat.clone()].concat()); + if in_idat { + // the offsets are into `idat`, so they don't depend on where the box lands + return [ftyp, meta(0)].concat(); + } + let base = (ftyp.len() + meta(0).len() + 8) as u32; + [ftyp, meta(base), bx(b"mdat", &payload)].concat() + } + + /// What an iPhone writes: the civil time it was taken at, plus the UTC offset it was taken in. + fn iphone_exif(date: &str, offset: &str) -> Vec { + let mut exif = IfdBuilder::new(); + exif.set(t::DATE_TIME_ORIGINAL, Value::Ascii(date.into())); + exif.set(t::OFFSET_TIME_ORIGINAL, Value::Ascii(offset.into())); + exif.set(t::ISO_SPEED, Value::Short(vec![64])); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Apple".into())); + ifd0.set(t::MODEL, Value::Ascii("iPhone 15 Pro".into())); + ifd0.set_child(t::EXIF_IFD, exif); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap_or_default() + } + + /// An `Exif` item's payload: the offset from the end of this field to the TIFF header, then + /// `skip` bytes of padding, then the TIFF stream. + fn exif_item(tiff: &[u8], skip: usize) -> Vec { + [&(skip as u32).to_be_bytes()[..], &vec![0u8; skip], tiff].concat() + } + + /// One `Exif` item holding `tiff`, the only item in the file. + fn exif_only(tiff: &[u8]) -> Vec> { + vec![Item { kind: b"Exif", content_type: "", data: exif_item(tiff, 0) }] + } + + /// Issue #2284: a photo taken at 13:00 in UTC-5 must stay 13:00, not become 18:00. Before the + /// HEIF items were read a HEIC carried no capture time at all, and the import fell back to the + /// file's modification time, which LightCraft writes as UTC. + #[test] + fn an_iphone_heic_keeps_the_time_the_camera_wrote() { + let file = heic(&exif_only(&iphone_exif("2026:10:18 13:00:00", "-05:00")), 1, false); + let m = crate::extract(&file); + let captured = m.capture_time.expect("a capture time"); + assert_eq!(captured.hour, 13); + assert_eq!(captured.offset_minutes, Some(-5 * 60)); + assert_eq!(captured.to_iso(), "2026-10-18T13:00:00-05:00"); + assert_eq!(m.model.as_deref(), Some("iPhone 15 Pro")); + assert_eq!(m.iso, Some(64)); + } + + /// The XMP packet is the `mime` item that declares `application/rdf+xml`, not any other one. + #[test] + fn the_xmp_packet_is_the_rdf_mime_item() { + let xmp = crate::write_xmp(&crate::Metadata { title: Some("Cusco".into()), ..Default::default() }, None); + let items = vec![ + Item { kind: b"mime", content_type: "text/plain", data: b"not the packet".to_vec() }, + Item { kind: b"mime", content_type: "application/rdf+xml", data: xmp.clone().into_bytes() }, + Item { kind: b"Exif", content_type: "", data: exif_item(&iphone_exif("2026:10:18 13:00:00", "-05:00"), 0) }, + ]; + let e = embedded(&heic(&items, 1, false)); + assert_eq!(e.xmp.as_deref(), Some(xmp.as_str())); + assert!(e.exif.is_some()); + assert_eq!(crate::extract(&heic(&items, 1, false)).title.as_deref(), Some("Cusco")); + } + + /// Every item location box the format allows: counts and ids are 16-bit before version 2 and + /// 32-bit in it, and the bytes live in `mdat` or in `idat` next to the location box itself. + #[test] + fn items_are_located_in_every_iloc_version() { + let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); + for (version, in_idat) in [(0, false), (1, false), (1, true), (2, false), (2, true)] { + let file = heic(&exif_only(&tiff), version, in_idat); + let found = embedded(&file).exif; + assert_eq!(found.as_deref(), Some(tiff.as_slice()), "iloc v{version}, idat {in_idat}"); + } + } + + /// The `Exif` item's leading offset may point past padding, not only straight at the TIFF + /// header, and the reader has to follow it. + #[test] + fn the_exif_items_tiff_header_offset_is_honoured() { + let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); + let items = vec![Item { kind: b"Exif", content_type: "", data: exif_item(&tiff, 6) }]; + assert_eq!(embedded(&heic(&items, 1, false)).exif.as_deref(), Some(tiff.as_slice())); + } + + /// Which `ftyp` brands count as a still image in this container, major or compatible. + #[test] + fn brands() { + for brand in ["heic", "heix", "mif1", "avif", "hevc", "msf1"] { + let file = bx(b"ftyp", format!("{brand}\0\0\0\0mif1").as_bytes()); + assert!(is_heif(&file), "{brand}"); + } + // a compatible brand counts too, a CR3, a JPEG XL and a non-ISO file do not + assert!(is_heif(&bx(b"ftyp", b"mp41\0\0\0\0isomheic"))); + assert!(!is_heif(&bx(b"ftyp", b"crx \0\0\0\0crx isom"))); + assert!(!is_heif(&bx(b"ftyp", b"jxl \0\0\0\0jxl "))); + assert!(!is_heif(b"\xff\xd8\xff\xe1 a jpeg")); + assert!(!is_heif(b"")); + } + + /// A truncated or scrambled file must come back empty, never panic (the never-crash rule). + #[test] + fn broken_files_yield_nothing_without_panicking() { + let good = heic( + &[ + Item { kind: b"Exif", content_type: "", data: exif_item(&iphone_exif("2026:10:18 13:00:00", "-05:00"), 0) }, + Item { kind: b"mime", content_type: "application/rdf+xml", data: b"".to_vec() }, + ], + 1, + false, + ); + for cut in 0..good.len() { + let _ = embedded(&good[..cut]); + } + for at in 0..good.len() { + let mut bad = good.clone(); + bad[at] ^= 0xff; + let _ = embedded(&bad); + } + // an item whose extent is outside the file, and a `meta` box that claims more than it has + let mut lying = good.clone(); + let item_count = u32::MAX.to_be_bytes(); + if let Some(at) = lying.windows(4).position(|w| w == b"iloc") { + lying.splice(at + 8..at + 12, item_count); + } + assert!(embedded(&lying).exif.is_none()); + } + + /// The real container writer of `lightcraft-heif`, so the reader is proved against the layout + /// a HEIF encoder produces and not only against this module's own test builder. + #[test] + fn a_synthetic_heif_file_carries_its_exif() { + let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); + let mut spec = lightcraft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]); + spec.exif = Some(tiff.clone()); + let file = lightcraft_heif::testdata::build(&spec); + assert!(is_heif(&file)); + assert_eq!(embedded(&file).exif.as_deref(), Some(tiff.as_slice())); + assert_eq!(crate::extract(&file).capture_time.map(|d| d.to_iso()).as_deref(), Some("2026-10-18T13:00:00-05:00")); + } +} diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 07887bbdc6..a6c36bb846 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -1,4 +1,4 @@ -//! Photo metadata for LightCraft: EXIF (TIFF/raw files, JPEG APP1, PNG `eXIf`, WebP `EXIF`), XMP packets +//! Photo metadata for LightCraft: EXIF (TIFF/raw files, JPEG APP1, PNG `eXIf`, WebP `EXIF`, HEIF items), XMP packets //! (read + write, standard namespaces plus our own `lc:` namespace) and basic IPTC-IIM. //! //! Entry points: @@ -7,8 +7,10 @@ //! - [`parse_xmp`] / [`write_xmp`] — XMP packets (interchange fields + the opaque `lc:settings` JSON). //! - [`parse_iptc`] — IPTC-IIM record 2 datasets. //! - [`parse_gpx`] — GPS track logs (GPX) for geotagging by capture time. -//! - [`extract`] — all of the above for a whole file (JPEG, PNG, WebP, TIFF/DNG/raw, PSD/PSB, Canon CR3). +//! - [`extract`] — all of the above for a whole file (JPEG, PNG, WebP, TIFF/DNG/raw, PSD/PSB, Canon CR3, +//! HEIF/HEIC/AVIF). //! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks). +//! - [`heif`] — the HEIF/HEIC/AVIF container's Exif and XMP items (no HEVC decoder needed). #![forbid(unsafe_code)] mod container; @@ -18,6 +20,7 @@ mod exif; pub mod focus; mod focus_read; mod gpx; +pub mod heif; mod iptc; pub mod mrw; mod psd; diff --git a/crates/meta/src/tags.rs b/crates/meta/src/tags.rs index 30069dea1a..643d0fb28d 100644 --- a/crates/meta/src/tags.rs +++ b/crates/meta/src/tags.rs @@ -156,7 +156,12 @@ fn rational(n: f64, d: f64) -> String { } fn list(v: &[T]) -> String { - let shown: Vec = v.iter().take(16).map(|x| x.to_string()).collect(); + list_with(v, T::to_string) +} + +/// The first 16 values of `v` written by `f`, and how many there are when that's not all of them. +fn list_with(v: &[T], f: impl Fn(&T) -> String) -> String { + let shown: Vec = v.iter().take(16).map(f).collect(); if v.len() > 16 { format!("{} … ({} values)", shown.join(", "), v.len()) } else { shown.join(", ") } } @@ -249,8 +254,8 @@ fn value_text(group: &str, tag: u16, v: &Value) -> String { } Value::Rational(a) if tag == 0x829d && group != "GPS" && a.len() == 1 => format!("f/{}", rational(a[0].0 as f64, a[0].1 as f64)), Value::Rational(a) if tag == 0x920a && group != "GPS" && a.len() == 1 => format!("{} mm", rational(a[0].0 as f64, a[0].1 as f64)), - Value::Rational(a) => a.iter().map(|(n, d)| rational(*n as f64, *d as f64)).collect::>().join(", "), - Value::SRational(a) => a.iter().map(|(n, d)| rational(*n as f64, *d as f64)).collect::>().join(", "), + Value::Rational(a) => list_with(a, |(n, d)| rational(*n as f64, *d as f64)), + Value::SRational(a) => list_with(a, |(n, d)| rational(*n as f64, *d as f64)), Value::Byte(b) | Value::Undefined(b) => { // version tags and short printable values read as text let printable = b.len() <= 64 && b.iter().all(|c| c.is_ascii_graphic() || *c == b' ' || *c == 0); @@ -387,6 +392,18 @@ mod tests { assert_eq!(rational(5.0, 2.0), "2.5"); } + /// Rational lists were joined whole, unlike every other list (#2579): a tag of millions of + /// fractions became a string as long in the tag panel. + #[test] + fn rational_lists_show_sixteen_values_like_other_lists() { + let first16 = (1..=16).map(|i| i.to_string()).collect::>().join(", "); + let many: Vec<(u32, u32)> = (1..=1000).map(|i| (i, 1)).collect(); + assert_eq!(value_text("EXIF", 0x9999, &Value::Rational(many)), format!("{first16} … (1000 values)")); + let signed: Vec<(i32, i32)> = (1..=1000).map(|i| (-i, 1)).collect(); + assert!(value_text("EXIF", 0x9999, &Value::SRational(signed)).ends_with("-16 … (1000 values)")); + assert_eq!(value_text("EXIF", 0x9999, &Value::Rational(vec![(1, 2), (3, 4)])), "0.5, 0.75"); + } + #[test] fn rows_from_written_exif() { let m = crate::Metadata { diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 8ca82da019..44edc04b8a 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -208,8 +208,10 @@ fn entity(name: &str) -> Option { _ => { let n = name.strip_prefix('#')?; let v = match n.strip_prefix(['x', 'X']) { - Some(h) => u32::from_str_radix(h, 16).ok()?, - None => n.parse().ok()?, + Some(h) if h.bytes().all(|b| b.is_ascii_hexdigit()) => u32::from_str_radix(h, 16).ok()?, + Some(_) => return None, + None if n.bytes().all(|b| b.is_ascii_digit()) => n.parse().ok()?, + None => return None, }; char::from_u32(v).filter(|&c| is_xml_char(c))? } @@ -547,8 +549,8 @@ pub fn parse_xmp(s: &str) -> Result { metering_mode: num("exif:MeteringMode").map(|v| v as u16), white_balance: num("exif:WhiteBalance").map(|v| v as u16), orientation: num("tiff:Orientation").map(|v| v as u16).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif), - width: num("tiff:ImageWidth").or_else(|| num("exif:PixelXDimension")).map(|v| v as u32), - height: num("tiff:ImageLength").or_else(|| num("exif:PixelYDimension")).map(|v| v as u32), + width: num("tiff:ImageWidth").filter(|v| *v >= 0.0).or_else(|| num("exif:PixelXDimension").filter(|v| *v >= 0.0)).map(|v| v as u32), + height: num("tiff:ImageLength").filter(|v| *v >= 0.0).or_else(|| num("exif:PixelYDimension").filter(|v| *v >= 0.0)).map(|v| v as u32), title: first("dc:title"), caption: first("dc:description"), alt_text: first("Iptc4xmpCore:AltTextAccessibility"), diff --git a/crates/meta/src/xmp/tests.rs b/crates/meta/src/xmp/tests.rs index 3939d2753d..acf1d9fcef 100644 --- a/crates/meta/src/xmp/tests.rs +++ b/crates/meta/src/xmp/tests.rs @@ -178,6 +178,22 @@ fn non_positive_iso_is_ignored() { assert_eq!(read(r#"exif:ISOSpeedRatings="200""#), Some(200)); } +#[test] +fn negative_xmp_pixel_width_is_ignored() { + let read = |attrs: &str| { + let x = format!( + r#" + + "# + ); + parse_xmp(&x).unwrap().metadata.width + }; + + assert_eq!(read(r#"tiff:ImageWidth="-1""#), None); + assert_eq!(read(r#"tiff:ImageWidth="-1" exif:PixelXDimension="640""#), Some(640)); + assert_eq!(read(r#"exif:PixelXDimension="-1""#), None); +} + #[test] fn malformed_inputs() { assert!(parse_xmp("").is_ok() || parse_xmp("").is_err()); @@ -483,3 +499,30 @@ fn flattened_keys_stay_within_the_cumulative_budget() { assert!(d.properties.len() < 3000, "keys stop being added once the budget is spent"); assert!(!d.properties.is_empty(), "properties parsed before the budget are kept"); } + +#[test] +fn entity_rejects_signed_numeric_references() { + assert_eq!(entity("#+65"), None); + assert_eq!(entity("#x+41"), None); + assert_eq!(entity("#65"), Some('A')); + assert_eq!(entity("#x41"), Some('A')); +} + +#[test] +fn malformed_capture_time_falls_back_and_keeps_raw_property() { + let packet = r#""#; + let parsed = parse_xmp(packet).unwrap(); + assert_eq!( + parsed.metadata.capture_time.map(|d| (d.year, d.month, d.day, d.hour, d.minute, d.second, d.offset_minutes)), + Some((2026, 1, 2, 10, 0, 0, Some(0))) + ); + assert_eq!(parsed.properties["exif:DateTimeOriginal"], vec!["2026-01-01T".to_string()]); +} + +#[test] +fn malformed_capture_time_without_fallback_is_not_projected() { + let packet = r#""#; + let parsed = parse_xmp(packet).unwrap(); + assert_eq!(parsed.metadata.capture_time, None); + assert_eq!(parsed.properties["exif:DateTimeOriginal"], vec!["2026-01-01T".to_string()]); +} diff --git a/crates/meta/tests/it/robust.rs b/crates/meta/tests/it/robust.rs index cd60e00a92..7a3179d579 100644 --- a/crates/meta/tests/it/robust.rs +++ b/crates/meta/tests/it/robust.rs @@ -4,9 +4,11 @@ use proptest::prelude::*; proptest! { #![proptest_config(ProptestConfig { cases: 1500, .. ProptestConfig::default() })] + /// Random bytes behind each container's magic: reading them yields whatever can be read and + /// never panics. #[test] - fn random_containers_never_panic(mut data in proptest::collection::vec(any::(), 0..600), kind in 0usize..6) { - let heads: [&[u8]; 6] = [b"\xff\xd8\xff\xe1", b"\x89PNG\r\n\x1a\n", b"RIFF\0\0\0\0WEBP", b"II*\0", b"MM\0*", b"\0\0\0\x18ftypcrx "]; + fn random_containers_never_panic(mut data in proptest::collection::vec(any::(), 0..600), kind in 0usize..7) { + let heads: [&[u8]; 7] = [b"\xff\xd8\xff\xe1", b"\x89PNG\r\n\x1a\n", b"RIFF\0\0\0\0WEBP", b"II*\0", b"MM\0*", b"\0\0\0\x18ftypcrx ", b"\0\0\0\x18ftypheic"]; let h = heads[kind]; if data.len() >= h.len() { data[..h.len()].copy_from_slice(h); diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 4fccd11342..aa194252e9 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -20,6 +20,15 @@ fn smooth(e0: f32, e1: f32, x: f32) -> f32 { t * t * (3.0 - 2.0 * t) } +/// How much of the sharpening a pixel gets (0..1) under Masking `masking` (0..1), from its fine +/// detail `det` (log luminance minus its texture blur): 1 everywhere at 0, only stronger edges +/// as it rises. The GPU kernel (`finish.wgsl`) computes the same; Alt-drag on Masking shows it +/// ([`crate::Overlay::SharpenMask`]). +#[inline] +pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 } +} + /// Parametric region curve (encoded domain) composed with the master point curve. fn curve_luts(c: &ToneCurve) -> Option<[Lut1; 3]> { let parametric = c.highlights != 0.0 || c.lights != 0.0 || c.darks != 0.0 || c.shadows != 0.0; @@ -78,6 +87,10 @@ pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_ #[inline] fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { + // A degenerate frame (zero-width crop) maps pixels to NaN/inf coordinates: no grain there. + if !x.is_finite() || !y.is_finite() { + return 0.0; + } let (x0, y0) = (x.floor(), y.floor()); let (fx, fy) = (x - x0, y - y0); let h = |i: i32, j: i32| { @@ -208,7 +221,15 @@ impl FinishParams { }; let ev = s.light.exposure as f32; let gain = 2f32.powf(ev); - let grain = (s.grain.amount > 0.0 && effects).then(|| { + // A degenerate frame (zero-width crop, zero scale) has no finite grain mapping: skip grain (CPU and GPU). + let out_to_norm = frame.out_to_norm(w, h); + let finite_frame = px_per_long.is_finite() + && px_per_long > 0.0 + && frame.ow.is_finite() + && frame.oh.is_finite() + && frame.ow.max(frame.oh) > 0.0 + && out_to_norm.0.iter().all(|v| v.is_finite()); + let grain = (s.grain.amount > 0.0 && effects && finite_frame).then(|| { let cell = (0.0006 + (s.grain.size / 100.0) as f32 * 0.0024) * px_per_long as f32; ((s.grain.amount / 100.0) as f32 * 0.13, cell.max(0.6), (s.grain.roughness / 100.0) as f32, s.grain.seed) }); @@ -240,7 +261,7 @@ impl FinishParams { gain, ev, grain, - out_to_norm: frame.out_to_norm(w, h), + out_to_norm, ow: frame.ow, oh: frame.oh, w, @@ -511,7 +532,9 @@ pub(crate) fn finish_with( lum = lum.clamp(0.0, 1.0); } let k = amt * g * (0.35 + 2.6 * lum * (1.0 - lum)); - e = e.map(|v| v + k); + if k.is_finite() { + e = e.map(|v| v + k); + } } let e = match &p_lut { Some((l, k)) if hdr => { @@ -647,7 +670,7 @@ fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1 let tame = 1.0 - 0.6 * smooth(0.4, 1.6, detail.abs()); delta += texture * 1.1 * detail.clamp(-1.0, 1.0) * tame; if sharpen != 0.0 { - let mask = if fp.sharpen_mask > 0.0 { smooth(fp.sharpen_mask * 0.25, fp.sharpen_mask * 0.25 + 0.15, detail.abs()) } else { 1.0 }; + let mask = sharpen_mask_weight(fp.sharpen_mask, detail); delta += sharpen * 1.3 * detail.clamp(-0.8, 0.8) * mask; } } @@ -764,6 +787,13 @@ fn enc(v: f32) -> u8 { mod tests { use super::*; + #[test] + fn grain_noise_is_finite_for_degenerate_coordinates() { + for (x, y) in [(f32::NAN, 1.0), (1.0, f32::INFINITY), (f32::NEG_INFINITY, f32::NAN)] { + assert_eq!(grain_noise(x, y, 7), 0.0); + } + } + #[test] fn refine_saturation_restores_the_pre_curve_saturation() { let before = [0.5, 0.3, 0.2]; diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 3f2766750c..641d50216b 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -54,7 +54,8 @@ impl Frame { pub fn with_lens(src_w: usize, src_h: usize, s: &DevelopSettings, apply_crop: bool, lens: Option<&EmbeddedLens>) -> Frame { let orient = s.orientation; let (ow, oh) = if orient.swaps_axes() { (src_h as f64, src_w as f64) } else { (src_w as f64, src_h as f64) }; - let crop = if apply_crop { s.crop.geometry } else { CropGeometry::default() }; + // bounded: a crop from a sidecar or an agent can reach far past the photo (issue #2555) + let crop = if apply_crop { s.crop.geometry.bounded(ow, oh) } else { CropGeometry::default() }; let lens = lens.map(|l| reorient_lens(l, orient, src_w as f64, src_h as f64)); let mut warp = Warp::from_settings(ow, oh, s, lens.as_ref()); let persp = perspective(s, ow, oh); @@ -355,6 +356,18 @@ pub const FULL: Rect = Rect::UNIT; mod tests { use super::*; + /// Issue #2555: a turned crop rect of 0..1000 (from a sidecar or an agent) made the native size + /// of a 6000 × 4000 photo ~2.4·10¹³ pixels, which a full-size export allocated. + #[test] + fn a_crop_far_past_the_photo_keeps_the_native_size_near_the_source() { + let mut s = DevelopSettings::default(); + s.crop.geometry = lightcraft_geom::CropGeometry { rect: lightcraft_geom::Rect::new(0.0, 0.0, 1000.0, 1000.0), angle: 5.0 }; + let (w, h) = crate::native_output_size(6000, 4000, &s); + assert!(w <= 12_000.0 && h <= 8_000.0, "{w} x {h}"); + // an untouched photo is its own size + assert_eq!(crate::native_output_size(6000, 4000, &DevelopSettings::default()), (6000.0, 4000.0)); + } + #[test] fn default_frame_is_identity() { let s = DevelopSettings::default(); diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 8f2702760d..d56e8fe82d 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -40,6 +40,7 @@ pub mod output; pub mod profiles; pub mod redeye; pub mod spots; +pub mod straighten; pub mod tone; pub mod transform; pub mod upright; @@ -173,6 +174,21 @@ impl PixelWindow { } } +/// The longest output side a render may be asked for (TIFF/PNG/JPEG all fit within it). +pub const MAX_OUTPUT_SIDE: usize = 65_535; +/// The most output pixels a render may be asked for (the box it fits into, ≈ 1.07 Gpx). +pub const MAX_OUTPUT_PIXELS: usize = 1 << 30; + +/// Rejects an output box past [`MAX_OUTPUT_SIDE`] or [`MAX_OUTPUT_PIXELS`] before anything is +/// sized from it. +pub fn check_output_size(max_w: usize, max_h: usize) -> Result<(), String> { + let pixels = max_w.checked_mul(max_h); + if max_w > MAX_OUTPUT_SIDE || max_h > MAX_OUTPUT_SIDE || pixels.is_none_or(|n| n > MAX_OUTPUT_PIXELS) { + return Err(format!("output size {max_w}×{max_h} is too large (at most {MAX_OUTPUT_SIDE} px per side and {MAX_OUTPUT_PIXELS} pixels)")); + } + Ok(()) +} + impl RenderRequest { pub fn fit(max_w: usize, max_h: usize) -> Self { Self { @@ -664,9 +680,12 @@ pub fn color_range_sample(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, Some(acc.map(|v| v / n)) } -/// The alpha plane a mask overlay shows: the one the render evaluated, or (for a hidden mask) a -/// fresh evaluation. +/// The plane an overlay shows: a sharpening view's detail plane, or the alpha of a mask overlay +/// (the one the render evaluated, or for a hidden mask a fresh evaluation). fn overlay_alpha(o: Overlay, plan: &Plan<'_>, prep: &Prepared) -> Option { + if o.reads_detail() { + return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, prep.texture_blur.as_deref(), plan.px_per_long); + } let m = o.mask(&plan.settings)?; if let Some(e) = prep.masks.iter().find(|e| e.id == m.id) { return Some(e.alpha.clone()); diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index c91872d388..6d09cf7557 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -140,6 +140,39 @@ pub fn legacy_to_kelvin(temp: f64, tint: f64, as_shot: (f64, f64)) -> (f64, f64) } } +/// The relative-scale `(temp, tint)` that [`legacy_to_kelvin`] would read as the Kelvin `(temp, tint)` on a source +/// whose real as-shot white is `as_shot`: the inverse of [`legacy_white`]'s composition. It runs the Bradford step +/// backwards — the old target's cone response times the old reference's over the as-shot white's — and reads the +/// result back through [`xy_to_temp_tint`]. `(6500, 0)` is the relative scale's as-shot reference, so the Kelvin +/// white of the source itself maps exactly to it. `None` when the arithmetic has nowhere to go (a non-finite input, +/// a white outside the chromaticity plane, or an as-shot cone response of zero, where the forward step discarded it). +pub fn kelvin_to_legacy(temp: f64, tint: f64, as_shot: (f64, f64)) -> Option<(f64, f64)> { + use lightcraft_color::{BRADFORD, Xy}; + if !(temp.is_finite() && tint.is_finite() && as_shot.0.is_finite() && as_shot.1.is_finite()) { + return None; + } + if (temp - as_shot.0).abs() < 1e-9 && (tint - as_shot.1).abs() < 1e-9 { + // the source's own white: the relative scale's as-shot reference, exactly + return Some((6500.0, 0.0)); + } + let cones = |t: f64, tint: f64| BRADFORD.apply(temp_tint_to_xy(t, tint).to_xyz()); + let (target, reference, shot) = (cones(temp, tint), cones(6500.0, 0.0), cones(as_shot.0, as_shot.1)); + let inverse = BRADFORD.inverse()?; + let mut old = [0.0; 3]; + for i in 0..3 { + if shot[i].abs() < 1e-12 { + return None; + } + old[i] = target[i] * reference[i] / shot[i]; + } + let xy = Xy::from_xyz(inverse.apply(old)); + if !(xy.x.is_finite() && xy.y.is_finite() && xy.y > 0.0) { + return None; + } + let (t, tint) = xy_to_temp_tint(xy); + (t.is_finite() && tint.is_finite()).then_some((t, tint)) +} + /// Bring the white balance of `d` onto the scale `info` is edited on, before a new value is written into it: on a /// raw with a Kelvin scale the values are marked Kelvin, and ones still on the relative scale become the Custom /// Kelvin / tint that renders the same ([`legacy_to_kelvin`]; a preset mode's look is kept as that custom @@ -557,6 +590,11 @@ pub struct PlaneSigmas { pub chroma: Option, } +/// Gaussian sigma (pixels) of the texture / sharpening band at `px_per_long`. +pub fn texture_sigma(px_per_long: f64) -> f32 { + (0.0018 * px_per_long as f32).max(0.6) +} + pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneSigmas { let ppl = px_per_long as f32; // A hidden mask, or one with no components, does not change the picture. Its sliders must @@ -581,7 +619,7 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS || local_any(|a| a.sharpness) || local_any(|a| a.noise) || s.masks.iter().filter(live).any(|m| m.adjust.defringe > 0.0)) - .then(|| (0.0018 * ppl).max(0.6)); + .then(|| texture_sigma(px_per_long)); let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0)); let chroma = (local_any(|a| a.moire) || s.masks.iter().filter(live).any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0)); let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 }; @@ -703,6 +741,7 @@ pub fn airlight_of(mut v: Vec) -> f32 { #[cfg(test)] mod tests { use super::*; + use lightcraft_color::cct::xy_to_uv; #[test] fn guided_preserves_step_edges_and_flattens_texture() { @@ -796,6 +835,70 @@ mod tests { scene_linear_pre(&mut img, &SourceInfo::default(), &s); assert!((img.get(1, 1)[2] - 0.6).abs() < 1e-5); } + + /// [`kelvin_to_legacy`] inverts [`legacy_to_kelvin`] over the whole relative slider range and back: the + /// round trip returns the start, in both directions, to the precision of the Kelvin / tint parametrisation. + #[test] + fn kelvin_to_legacy_inverts_legacy_to_kelvin() { + for as_shot in [(4986.0, -2.0), (6500.0, 0.0), (3200.0, 14.0), (9500.0, -12.0)] { + // the relative slider's whole reach: temp 0..100 (2000–13550 K around 6500), tint −150..150 + for pct in [0.0, 12.5, 25.0, 50.0, 75.0, 100.0] { + for tint in [-150.0, -40.0, 0.0, 33.0, 150.0] { + let (lt, ltint) = controls_relative(pct, tint); + let (kt, ktint) = legacy_to_kelvin(lt, ltint, as_shot); + // past the Kelvin parametrisation's own reach (its search runs 1000–50000 K) the forward + // conversion has already clamped, so the pair is not expected to come back + if !(1050.0..=49_000.0).contains(&kt) { + continue; + } + let back = kelvin_to_legacy(kt, ktint, as_shot).unwrap(); + let (x1, y1) = xy_to_uv(temp_tint_to_xy(lt, ltint)); + let (x2, y2) = xy_to_uv(temp_tint_to_xy(back.0, back.1)); + // the pair may differ by more than the slider's own step at the extreme corners (the Kelvin + // parametrisation is read back through a search), but never by much, and the white it renders + // is the same + assert!( + (back.0 - lt).abs() <= lt.abs() * 0.01 && (back.1 - ltint).abs() < 0.5, + "as shot {as_shot:?}: relative ({lt}, {ltint}) -> kelvin ({kt}, {ktint}) -> {back:?}" + ); + assert!((x1 - x2).hypot(y1 - y2) < 1e-3, "as shot {as_shot:?}: relative ({lt}, {ltint}) -> kelvin ({kt}, {ktint}) -> {back:?}"); + } + } + // the other direction: every white the relative scale can hold maps back to a pair that renders the same + for kt in [as_shot.0, 2500.0, 4200.0, 6500.0, 12000.0] { + for ktint in [-60.0, 0.0, 45.0] { + let Some((lt, ltint)) = kelvin_to_legacy(kt, ktint, as_shot) else { continue }; + // outside the slider's reach the relative scale has no value for this white: the forward + // conversion would clamp, so the round trip is not expected to close there + if !(2000.0..=13550.0).contains(<) || ltint.abs() > 150.0 { + continue; + } + let (kt2, ktint2) = legacy_to_kelvin(lt, ltint, as_shot); + let (x1, y1) = xy_to_uv(temp_tint_to_xy(kt, ktint)); + let (x2, y2) = xy_to_uv(temp_tint_to_xy(kt2, ktint2)); + assert!( + (x1 - x2).hypot(y1 - y2) < 1e-3, + "as shot {as_shot:?}: kelvin ({kt}, {ktint}) -> relative ({lt}, {ltint}) -> ({kt2}, {ktint2})" + ); + } + } + // the source's own white is the relative scale's as-shot reference, exactly + assert_eq!(kelvin_to_legacy(as_shot.0, as_shot.1, as_shot), Some((6500.0, 0.0))); + } + // the exact inverse of the special case inside legacy_to_kelvin + assert_eq!(kelvin_to_legacy(4986.0, -2.0, (4986.0, -2.0)), Some((6500.0, 0.0))); + assert_eq!(legacy_to_kelvin(6500.0, 0.0, (4986.0, -2.0)), (4986.0, -2.0)); + // hostile numbers answer None, never a panic or a plausible lie + assert_eq!(kelvin_to_legacy(f64::NAN, 0.0, (5000.0, 0.0)), None); + assert_eq!(kelvin_to_legacy(5000.0, f64::INFINITY, (5000.0, 0.0)), None); + assert_eq!(kelvin_to_legacy(5000.0, 0.0, (f64::NAN, 0.0)), None); + } + + /// The relative scale's `(temp, tint)` for a slider temperature at `pct` % (2000–7000 K fill the left half) and tint. + fn controls_relative(pct: f64, tint: f64) -> (f64, f64) { + let t = if pct <= 50.0 { 2000.0 + pct * 100.0 } else { 7000.0 + (pct - 50.0) * 131.0 }; + (t, tint) + } } #[cfg(test)] diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index 73383d1d4a..ca182ea81d 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -251,7 +251,9 @@ pub fn shape_alpha(shape: &MaskShape, frame: &Frame, w: usize, h: usize, img: &R } MaskShape::ColorRange { samples, refine } => { let tol = color_range_tolerance(*refine); - let samples: Vec<[f32; 3]> = samples.iter().map(|s| [s[0] as f32, s[1] as f32, s[2] as f32]).collect(); + // (a settings value built in code can skip the deserializer's cap: cost is pixels x samples) + let samples: Vec<[f32; 3]> = + samples.iter().take(lightcraft_develop::MAX_COLOR_RANGE_SAMPLES).map(|s| [s[0] as f32, s[1] as f32, s[2] as f32]).collect(); for (v, c) in out.data.iter_mut().zip(&img.data) { let lab = lightcraft_color::perceptual::oklab_from_2020(tonemap_for_select(c.map(|v| v * gain))); let d = samples @@ -281,7 +283,7 @@ pub fn shape_alpha(shape: &MaskShape, frame: &Frame, w: usize, h: usize, img: &R // 2 % of the long edge, so previews and exports match) let e = (*edge / 100.0).clamp(-1.0, 1.0) as f32; let gain = if e < 0.0 { 1.0 - 7.0 * e } else { 1.0 }; - sample_seg(seg.as_ref(), detail, gain, frame, w, h, &mut out); + sample_seg(seg.as_ref(), detail, gain, frame, w, h, log_l, &mut out); if e > 0.0 { smooth_plane(&mut out, e * 0.02 * frame_px(frame, w)); } @@ -343,13 +345,40 @@ impl SegGrid { let bot = at(x0, y0 + 1) * (1.0 - tx) + at(x0 + 1, y0 + 1) * tx; top * (1.0 - ty) + bot * ty } + + /// Output pixels per grid cell (the longer side of a cell: the grid is square over a + /// rectangle). + fn cell_px(&self, frame: &Frame, w: usize) -> f64 { + let px = frame.px_per_long(w) / frame.ow.max(frame.oh).max(1e-9); + ((self.r[2] - self.r[0]) * frame.ow).max((self.r[3] - self.r[1]) * frame.oh) * px / self.side.max(1) as f64 + } } +/// [`sample_seg`]'s window, in grid cells (Gaussian sigma): the width of the band bilinear +/// enlargement leaves uncertain, about a cell on either side of the contour. +const SEG_WINDOW: f64 = 1.5; +/// [`sample_seg`]'s guided-filter regularization (EV² of log luminance): an edge of ~0.1 EV +/// contrast counts half. +const SEG_EPS: f32 = 0.01; + /// Stored model segmentations at each output pixel: the zoomed-in `detail` passes inside /// their rectangles (the highest of them where they overlap), the whole-photo `seg` /// elsewhere; the logit (times `gain`: > 1 is a harder edge) through a sigmoid. Damaged /// data selects nothing. -fn sample_seg(seg: Option<&SegMask>, detail: &[SegMask], gain: f32, frame: &Frame, w: usize, h: usize, out: &mut Plane) { +/// +/// Issue #3272: a model's grid is much coarser than an export (a 288² grid has ~20 px cells on +/// 24 MP), and its bilinear contour passes up to a cell from the photo's edge, so the mask spilled +/// onto the background (a bright outline under a raised Exposure). Where the grid is coarser than +/// the output, the logits are guided-filtered by the photo's log luminance ([`guided_cross_fast`]; a +/// window of [`SEG_WINDOW`] cells, so previews and exports draw the same edge): near the contour +/// the logit follows the photo's tones and its edge lands on the photo's. Filtering logits, not +/// coverage, makes the confident side win (a strip at 0.3 between 1 and 0 goes to 0, not 0.1), +/// and leaves a linear ramp of logits, where the photo has no edge, as it was. Pixels whose +/// window is all inside or all outside (|mean logit| ≥ 7, times `gain`) keep their sample exactly, +/// as do those where the photo has no edge to follow. Refine Edges +/// then works on the combined mask ([`evaluate_one`]) and finds these edges already in place. +#[allow(clippy::too_many_arguments)] +fn sample_seg(seg: Option<&SegMask>, detail: &[SegMask], gain: f32, frame: &Frame, w: usize, h: usize, log_l: &Plane, out: &mut Plane) { let coarse = seg.and_then(SegGrid::new); // (capped: a hostile document can hold many) let patches: Vec = detail.iter().take(lightcraft_develop::segmask::MAX_DETAIL).filter_map(SegGrid::new).collect(); @@ -361,10 +390,15 @@ fn sample_seg(seg: Option<&SegMask>, detail: &[SegMask], gain: f32, frame: &Fram for (x, v) in row.iter_mut().enumerate() { let n = m.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); let fine = patches.iter().filter(|p| p.contains(n)).map(|p| p.logit(n)).reduce(f32::max); - let l = fine.or_else(|| coarse.as_ref().map(|c| c.logit(n))).unwrap_or(-16.0); - *v = 1.0 / (1.0 + (-l * gain).exp()); + *v = fine.or_else(|| coarse.as_ref().map(|c| c.logit(n))).unwrap_or(-16.0) * gain; } }); + // (the coarsest grid sets the window: it leaves the widest uncertain band) + let cell = coarse.iter().chain(&patches).map(|g| g.cell_px(frame, w)).fold(0.0, f64::max); + if cell >= 1.0 { + guided_cross_fast(log_l, out, (SEG_WINDOW * cell) as f32, SEG_EPS, |mean| 1.0 - smooth(3.0 * gain, 7.0 * gain, mean.abs())); + } + out.map_in_place(|l| 1.0 / (1.0 + (-l).exp())); } fn frame_px(frame: &Frame, w: usize) -> f32 { @@ -524,6 +558,19 @@ pub const MAX_STROKE_DABS: usize = 2_000_000; /// The dabs of stroke `s` in a `w × h` output. pub fn brush_dabs(s: &BrushStroke, frame: &Frame, w: usize, h: usize) -> BrushDabs { + brush_dabs_within(s, frame, w, h, MAX_STROKE_DABS) +} + +/// [`brush_dabs`] stopping at `max` dabs instead of [`MAX_STROKE_DABS`]. +/// +/// For a caller that discards a stroke past a threshold of its own: it builds to that threshold +/// rather than to the stroke budget and throws the difference away. The GPU path rejects a brush +/// mask past 4096 dabs in total and the Auto Mask spot window past 200,000, both far below the +/// two million a single stroke may otherwise construct first (#1520). +/// +/// Ask for one more than the threshold to tell "at it" from "past it": a result shorter than +/// `max` is the whole stroke. +pub fn brush_dabs_within(s: &BrushStroke, frame: &Frame, w: usize, h: usize, max: usize) -> BrushDabs { let to_out = frame.norm_to_out(w, h); let ppl = frame.px_per_long(w); let r = (s.size * ppl).max(0.5); @@ -536,10 +583,14 @@ pub fn brush_dabs(s: &BrushStroke, frame: &Frame, w: usize, h: usize) -> BrushDa let with_pressure = !s.pressure.is_empty(); let mut prev = None; let mut prev_p = 1.0; + let mut emitted = 0usize; for (i, p) in s.points.iter().enumerate() { + if emitted >= max { + break; + } let q = to_out.apply(*p); let before = dabs.len(); - if push_dabs(&mut dabs, prev, q, r) { + if push_dabs_within(&mut dabs, &mut emitted, prev, q, r, max) { let pq = s.pressure_at(i); if with_pressure { // the first dab of the stroke has nothing to interpolate from @@ -585,7 +636,16 @@ pub fn push_dabs(dabs: &mut Vec, prev: Option, q: Point, r: f64) - /// dabs no longer held in `dabs`. Incremental callers retain `emitted` when clearing their buffer; /// it advances only by the number actually appended. Acceptance and spacing match [`push_dabs`]. pub fn push_dabs_counted(dabs: &mut Vec, emitted: &mut usize, prev: Option, q: Point, r: f64) -> bool { - let room = MAX_STROKE_DABS.saturating_sub(*emitted); + push_dabs_within(dabs, emitted, prev, q, r, MAX_STROKE_DABS) +} + +/// [`push_dabs_counted`] against a caller's own budget rather than [`MAX_STROKE_DABS`]. +/// +/// A caller that will not look at more than `max` dabs should build no more than `max`: a length +/// check after the vector exists bounds nothing, it only throws away what was already paid for +/// (#1520). +pub fn push_dabs_within(dabs: &mut Vec, emitted: &mut usize, prev: Option, q: Point, r: f64, max: usize) -> bool { + let room = max.min(MAX_STROKE_DABS).saturating_sub(*emitted); if room == 0 || !(q.x.is_finite() && q.y.is_finite()) { return false; } @@ -598,7 +658,7 @@ pub fn push_dabs_counted(dabs: &mut Vec, emitted: &mut usize, prev: Optio let n = (dist / dab_spacing(r)).ceil(); // a hostile or degenerate segment (huge) gets no in-between dabs rather than a huge // allocation: 1 M dabs is far more than any on-screen stroke needs - let n = if n.is_finite() { n.clamp(0.0, 1_000_000.0) as usize } else { 0 }; + let n = if n.is_finite() && n <= 1_000_000.0 { n.max(0.0) as usize } else { 0 }; // the in-between dabs and `q` together fit what is left of the stroke's budget let n = n.min(room); for k in 1..n { @@ -665,9 +725,20 @@ pub fn auto_refine(r: f64) -> (f32, f32) { ((0.25 * r).max(1.0) as f32, 0.02) } -/// Guided filter of `p` steered by `guide` (He et al.), clamped to 0..1: `p`'s edges snap to the -/// guide's. -pub fn guided_cross(guide: &Plane, p: &Plane, sigma: f32, eps: f32) -> Plane { +/// A guided filter's linear model at each pixel (`q = a · guide + b`, coefficients averaged over +/// the windows that hold the pixel), the window mean of the filtered plane and, when asked for, +/// how much of an edge the guide has there (`var / (var + eps)`, averaged like the coefficients: +/// 0 where the guide is flat and the model is only a blur). +struct Guided { + a: Plane, + b: Plane, + mean: Plane, + edge: Option, +} + +/// The guided filter (He, Sun and Tang) of `p` steered by `guide`, both the same size: Gaussian +/// windows of `sigma` px, `eps` the regularization (in guide units squared). +fn guided_coeffs(guide: &Plane, p: &Plane, sigma: f32, eps: f32, with_edge: bool) -> Guided { use lightcraft_raster::blur::gaussian; let mi = gaussian(guide, sigma); let mp = gaussian(p, sigma); @@ -675,20 +746,70 @@ pub fn guided_cross(guide: &Plane, p: &Plane, sigma: f32, eps: f32) -> Plane { let cii = gaussian(&guide.map(|a| a * a), sigma); let mut a = Plane::new(p.width, p.height); let mut b = Plane::new(p.width, p.height); + let mut edge = Plane::new(if with_edge { p.width } else { 0 }, if with_edge { p.height } else { 0 }); for i in 0..p.data.len() { let var = (cii.data[i] - mi.data[i] * mi.data[i]).max(0.0); let k = (cip.data[i] - mi.data[i] * mp.data[i]) / (var + eps); a.data[i] = k; b.data[i] = mp.data[i] - k * mi.data[i]; + if let Some(e) = edge.data.get_mut(i) { + *e = var / (var + eps); + } } - let (ma, mb) = (gaussian(&a, sigma), gaussian(&b, sigma)); + Guided { a: gaussian(&a, sigma), b: gaussian(&b, sigma), mean: mp, edge: with_edge.then(|| gaussian(&edge, sigma)) } +} + +/// Guided filter of `p` steered by `guide` (He et al.), clamped to 0..1: `p`'s edges snap to the +/// guide's. +pub fn guided_cross(guide: &Plane, p: &Plane, sigma: f32, eps: f32) -> Plane { + let g = guided_coeffs(guide, p, sigma, eps, false); let mut q = Plane::new(p.width, p.height); for i in 0..q.data.len() { - q.data[i] = (ma.data[i] * guide.data[i] + mb.data[i]).clamp(0.0, 1.0); + q.data[i] = (g.a.data[i] * guide.data[i] + g.b.data[i]).clamp(0.0, 1.0); } q } +/// [`guided_cross`] in its subsampled form (He and Sun, "Fast Guided Filter", 2015, as +/// [`crate::local::guided_fast`] is of the self-guided filter, at its step), in place and +/// unclamped, for a `p` that is smooth at the window's scale (a mask enlarged from a model's grid): +/// the linear model is fitted on both planes box-reduced to about 3 px of window, sampled +/// bilinearly and applied to the full-resolution guide, which is where the edge comes from. A +/// pixel moves to the filtered value by `weight` of its window mean of `p` times how much of an +/// edge the guide has there (0 keeps it exactly: where the photo is flat the filter could only +/// blur `p`). Extra memory: the reduced planes only (the coefficients are sampled per pixel, not +/// enlarged into planes). +fn guided_cross_fast(guide: &Plane, p: &mut Plane, sigma: f32, eps: f32, weight: impl Fn(f32) -> f32 + Sync + Send) { + use lightcraft_raster::resample::{Filter, resize}; + let (w, h) = (p.width, p.height); + if guide.width != w || guide.height != h || w == 0 || h == 0 || !sigma.is_finite() { + return; + } + // (a window past the whole frame fits one model to it all) + let sigma = sigma.clamp(0.5, w.max(h) as f32); + let s = crate::local::guided_fast_step(sigma); + let (lw, lh) = (w.div_ceil(s).max(1), h.div_ceil(s).max(1)); + let g = guided_coeffs(&resize(guide, lw, lh, Filter::Box), &resize(p, lw, lh, Filter::Box), sigma / s as f32, eps, true); + let Some(edge) = &g.edge else { + return; + }; + // (the reduced planes span the same frame: their pixel per full pixel) + let (kx, ky) = (lw as f32 / w as f32, lh as f32 / h as f32); + for_rows(&mut p.data, w, |y, row| { + let fy = (y as f32 + 0.5) * ky; + for (x, (v, i)) in row.iter_mut().zip(guide.row(y)).enumerate() { + let fx = (x as f32 + 0.5) * kx; + let k = weight(bilinear(&g.mean, fx, fy)); + // (no edge in the photo: nothing to follow, keep the sample) + let k = if k > 0.0 { k * smooth(0.05, 1.0, bilinear(edge, fx, fy)) } else { 0.0 }; + if k > 0.0 { + let q = bilinear(&g.a, fx, fy) * i + bilinear(&g.b, fx, fy); + *v += (q - *v) * k; + } + } + }); +} + /// Stamp brush strokes into `out` (max-combine; erase strokes subtract). Auto Mask strokes weight /// each dab by [`auto_similarity`] to the pixel under its centre and are refined with /// [`guided_cross`] on log luminance. diff --git a/crates/pipeline/src/masks/tests.rs b/crates/pipeline/src/masks/tests.rs index a3f776d0d7..3d0356e980 100644 --- a/crates/pipeline/src/masks/tests.rs +++ b/crates/pipeline/src/masks/tests.rs @@ -89,6 +89,115 @@ fn the_edge_setting_hardens_or_feathers_the_transition() { assert!(hard < plain && plain < soft, "transition widths {hard} < {plain} < {soft}"); } +/// A dark disc (radius 0.3 of the frame) on a light background, `n × n`: the photo and its log +/// luminance, and a model's view of it on a `side²` grid (each cell's logit from how much of the +/// cell the disc covers, as a low-resolution segmenter sees it). +fn disc_scene(n: usize, side: usize) -> (Rgb32f, Plane, SegMask) { + const R: f64 = 0.3; + let dark = |x: f64, y: f64| (x - 0.5).hypot(y - 0.5) < R; + let lum = |x: usize, y: usize| if dark((x as f64 + 0.5) / n as f64, (y as f64 + 0.5) / n as f64) { 0.05f32 } else { 0.6 }; + let img = Rgb32f::from_fn(n, n, |x, y| [lum(x, y); 3]); + let log_l = img.map(crate::local::log_lum); + let logits: Vec = (0..side * side) + .map(|i| { + let (cx, cy) = (i % side, i / side); + let sub = 8; + let cover = (0..sub * sub) + .filter(|k| { + dark((cx as f64 + (k % sub) as f64 / sub as f64) / side as f64, (cy as f64 + (k / sub) as f64 / sub as f64) / side as f64) + }) + .count() as f32 + / (sub * sub) as f32; + 12.0 * (2.0 * cover - 1.0) + }) + .collect(); + (img, log_l, SegMask::from_logits(side, &logits)) +} + +/// Alpha along the disc's horizontal radius, `d` px outside (> 0) or inside (< 0) its edge. +fn across_disc_edge(a: &Plane, d: i32) -> f32 { + let n = a.width; + let edge = (0.8 * n as f64).round() as i32; // first background pixel on the right + let x = if d > 0 { edge + d - 1 } else { edge + d }; + a.get(x as usize, n / 2) +} + +/// Issue #3272: a mask from a low-resolution model grid spilled 1–2 px onto the background (a bright +/// outline once its Exposure was raised). Enlarged along the photo's edges, it is ≈ 0 one and two +/// pixels outside the subject, ≈ 1 inside, and exactly what it was away from the edge. +#[test] +fn ai_masks_follow_the_photos_edge_when_enlarged() { + let (n, side) = (512, 32); // 16 px cells, as a 288² grid on a ~4600 px export + let (img, log_l, seg) = disc_scene(n, side); + let shape = MaskShape::Prompt { text: "disc".into(), seg: Some(seg), detail: vec![], edge: 0.0 }; + let f = frame(n, n); + let a = shape_alpha(&shape, &f, n, n, &img, &log_l, 0.0, None); + for d in [1, 2] { + assert!(across_disc_edge(&a, d) < 0.05, "{d} px outside: {}", across_disc_edge(&a, d)); + assert!(across_disc_edge(&a, -d) > 0.95, "{d} px inside: {}", across_disc_edge(&a, -d)); + } + // all around the disc, not only along one row + let r_px = 0.3 * n as f64; + for k in 0..64 { + let t = k as f64 / 64.0 * std::f64::consts::TAU; + let at = |r: f64| a.get((256.0 + r * t.cos()) as usize, (256.0 + r * t.sin()) as usize); + assert!(at(r_px + 2.5) < 0.05 && at(r_px - 2.5) > 0.95, "at {t:.2} rad: {} / {}", at(r_px + 2.5), at(r_px - 2.5)); + } + // away from the edge the selection is the plain sample of the grid, to the bit + let flat = Plane::new(n, n); + let plain = shape_alpha(&shape, &f, n, n, &img, &flat, 0.0, None); + for (x, y) in [(256, 256), (200, 300), (10, 10), (500, 256), (256, 505)] { + assert_eq!(a.get(x, y), plain.get(x, y), "({x}, {y})"); + } +} + +/// Refine Edges on top of an enlarged AI mask: the second filter finds the edge already in place, so +/// there is no second halo and the edge doesn't move inwards. +#[test] +fn refine_edges_on_an_enlarged_ai_mask_neither_halos_nor_tightens() { + let (n, side) = (512, 32); + let (img, log_l, seg) = disc_scene(n, side); + let f = frame(n, n); + let mask = |refine: f64| Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Prompt { text: "disc".into(), seg: Some(seg.clone()), detail: vec![], edge: 0.0 }, + }], + refine, + ..Default::default() + }; + let crossing = |a: &Plane| (0..n).rev().find(|x| a.get(*x, n / 2) > 0.5).unwrap_or(0); + let plain = evaluate_one(&mask(0.0), &f, n, n, &img, &log_l, 0.0, None); + for refine in [50.0, 100.0] { + let a = evaluate_one(&mask(refine), &f, n, n, &img, &log_l, 0.0, None); + for d in [1, 2] { + assert!(across_disc_edge(&a, d) < 0.05, "refine {refine}, {d} px outside: {}", across_disc_edge(&a, d)); + assert!(across_disc_edge(&a, -d) > 0.95, "refine {refine}, {d} px inside: {}", across_disc_edge(&a, -d)); + } + assert!(crossing(&a).abs_diff(crossing(&plain)) <= 1, "refine {refine}: edge at {} vs {}", crossing(&a), crossing(&plain)); + } +} + +/// The window follows the grid, not the output: a preview and an export put the edge in the same +/// place of the photo (and on its edge). +#[test] +fn enlarged_ai_masks_put_the_edge_in_the_same_place_at_any_size() { + let side = 32; + let mut edges = Vec::new(); + for n in [256, 512, 1024] { + let (img, log_l, seg) = disc_scene(n, side); + let shape = MaskShape::Prompt { text: "disc".into(), seg: Some(seg), detail: vec![], edge: 0.0 }; + let a = shape_alpha(&shape, &frame(n, n), n, n, &img, &log_l, 0.0, None); + // the edge's sub-pixel position along the row: the integral of alpha past the centre + let covered: f32 = (n / 2..n).map(|x| a.get(x, n / 2)).sum(); + edges.push((n / 2) as f64 + covered as f64); + let x = edges.last().copied().unwrap_or(0.0) / n as f64; + assert!((x - 0.8).abs() < 1.0 / n as f64, "{n} px: edge at {x:.4} of the width, the disc's at 0.8"); + } +} + #[test] fn ai_shapes_without_a_segmentation_select_nothing() { let f = frame(30, 30); @@ -115,6 +224,52 @@ fn radial_inside_and_invert() { assert!(e[0].alpha.get(50, 50) < 0.01); } +/// #1520: a caller that will not look past its own threshold builds to that threshold, not to +/// the stroke budget. Each segment here is admissible on its own and together they want far +/// more than any threshold the callers apply, which is the aggregate the issue describes +/// rather than one hostile segment. +#[test] +fn a_stroke_is_built_only_as_far_as_the_caller_will_look() { + let f = frame(4000, 4000); + // Twenty long sweeps across the output: tens of thousands of dabs between them. + let points: Vec = + (0..20).map(|i| if i % 2 == 0 { Point::new(0.02, 0.02 + i as f64 * 0.04) } else { Point::new(0.98, 0.02 + i as f64 * 0.04) }).collect(); + let s = BrushStroke { points, size: 0.002, feather: 50.0, flow: 100.0, density: 100.0, ..Default::default() }; + + let whole = brush_dabs(&s, &f, 4000, 4000); + assert!(whole.dabs.len() > 20_000, "the stroke really is large: {}", whole.dabs.len()); + assert!(whole.dabs.len() <= MAX_STROKE_DABS); + + // Each caller gets what it asked for and no more, however large the stroke is. 4097 and + // 200_001 are what the GPU path and the Auto Mask spot window now ask for. + for max in [1usize, 2, 4097, 200_001] { + let got = brush_dabs_within(&s, &f, 4000, 4000, max); + assert!(got.dabs.len() <= max, "asked for at most {max}, built {}", got.dabs.len()); + assert_eq!(got.r, whole.r, "the brush itself is unchanged"); + } + + // A budget the stroke never reaches changes nothing: it only ever truncates. + let generous = brush_dabs_within(&s, &f, 4000, 4000, whole.dabs.len() + 1000); + assert_eq!(generous.dabs, whole.dabs, "an unreached budget leaves the stroke alone"); + + // The guarantee the callers rely on: a result short of the budget was never truncated, + // so it is the stroke itself. Both callers ask for one more than they will accept, so + // anything they keep is identical to what they drew before this change, and anything + // truncated is something they were going to reject anyway. + // + // A truncated one is not a prefix: running out of room makes a segment lay its remaining + // dabs further apart rather than stop mid-segment, which is how `push_dabs_counted` + // already behaved at MAX_STROKE_DABS. That only ever reaches a caller that rejects it. + let cut = brush_dabs_within(&s, &f, 4000, 4000, 500); + assert_eq!(cut.dabs.len(), 500, "a stroke past the budget fills it exactly"); + for max in [700usize, 5_000, whole.dabs.len()] { + let got = brush_dabs_within(&s, &f, 4000, 4000, max); + if got.dabs.len() < max { + assert_eq!(got.dabs, whole.dabs, "a result short of its budget is the whole stroke"); + } + } +} + /// Issue #517: dabs along a long segment (a fast stroke: two pointer samples far apart) are at /// most [`dab_spacing`] apart, painting dab by dab (the live stroke) or the whole path at once /// (the committed one). @@ -148,7 +303,8 @@ fn a_long_segment_gets_dabs_at_most_the_spacing_apart() { } assert_eq!(committed.dabs, again); assert!(committed.dabs.windows(2).all(|w| w[0].dist(w[1]) <= dab_spacing(committed.r) + 1e-9)); - // many huge segments stop at the stroke budget instead of adding up without bound + // a huge segment lays only its end point, so many of them add one dab each instead of + // filling the stroke budget with intermediate dabs let mut big = Vec::new(); let mut at = Point::new(0.0, 0.0); for i in 0..5 { @@ -157,8 +313,9 @@ fn a_long_segment_gets_dabs_at_most_the_spacing_apart() { at = q; } } - assert!(big.len() <= MAX_STROKE_DABS, "{} dabs", big.len()); - assert!(!push_dabs(&mut big, Some(at), Point::new(5.0, 5.0), 1.0), "a full stroke takes no more"); + assert_eq!(big.len(), 5, "an extreme segment lays no intermediate dabs"); + let mut spent = MAX_STROKE_DABS; + assert!(!push_dabs_counted(&mut big, &mut spent, Some(at), Point::new(5.0, 5.0), 1.0), "a full stroke takes no more"); // a hostile segment places no in-between dabs let mut v = Vec::new(); assert!(!push_dabs(&mut v, Some(Point::new(f64::NAN, 0.0)), Point::new(1.0, 1.0), r)); @@ -167,6 +324,23 @@ fn a_long_segment_gets_dabs_at_most_the_spacing_apart() { assert!(v.len() <= 1_000_002, "{}", v.len()); } +#[test] +fn oversized_brush_segments_skip_intermediate_dabs() { + let mut dabs = vec![Point::new(10.0, 10.0)]; + let far = Point::new(10_000_000.0, 10.0); + assert!(push_dabs(&mut dabs, Some(Point::new(10.0, 10.0)), far, 2.0)); + assert_eq!(dabs.len(), 2, "an extreme segment must not allocate a million intermediate dabs"); + assert_eq!(dabs.last(), Some(&far)); + + // Ordinary feathered-brush paths still get overlapping dabs and their endpoint. + let mut regular = vec![Point::new(10.0, 10.0)]; + let end = Point::new(30.0, 10.0); + assert!(push_dabs(&mut regular, Some(Point::new(10.0, 10.0)), end, 4.0)); + assert_eq!(regular.len(), 21); + assert_eq!(regular.last(), Some(&end)); + assert!(regular.windows(2).all(|pair| pair[0].dist(pair[1]) <= dab_spacing(4.0))); +} + /// A temporary output buffer must spend the same stroke budget as a retained one. #[test] fn incremental_dab_buffers_share_the_stroke_budget() { diff --git a/crates/pipeline/src/redeye.rs b/crates/pipeline/src/redeye.rs index 3bad1d6348..bb29443881 100644 --- a/crates/pipeline/src/redeye.rs +++ b/crates/pipeline/src/redeye.rs @@ -142,6 +142,7 @@ pub fn resolve(src: &Rgb32f, eyes: &[RedEye], orientation: Orientation, frame: & } let to_out = frame.norm_to_out(w, h); eyes.iter() + .take(lightcraft_develop::MAX_RED_EYES) .map(|e| { let p = detect(src, orientation, frame.ow, frame.oh, e); let r = (p.radius * (0.5 + e.pupil_size.clamp(0.0, 100.0) / 100.0)).min(e.rx.max(e.ry) * 1.1); @@ -246,6 +247,16 @@ mod tests { assert!(!detect(&plain, Orientation::Normal, 200.0, 100.0, &eye).found); } + #[test] + fn at_most_max_red_eyes_render() { + // a sidecar, preset or agent can hold any number; each one costs a pass over every pixel (issue #2556) + let src = eye_image(40, 20, 18.0, 10.0, 2.0, [0.5, 0.04, 0.04]); + let s = lightcraft_develop::DevelopSettings { red_eye: vec![RedEye::default(); 10_000], ..Default::default() }; + let frame = Frame::new(40, 20, &s, true); + let eyes = resolve(&src, &s.red_eye, Orientation::Normal, &frame, 40, 20, 40.0); + assert_eq!(eyes.len(), lightcraft_develop::MAX_RED_EYES); + } + #[test] fn renders_fix_the_red_pupil_at_any_size() { use crate::{RenderRequest, SourceInfo, render}; diff --git a/crates/pipeline/src/spots.rs b/crates/pipeline/src/spots.rs index 315f7f9568..a875ffb7fc 100644 --- a/crates/pipeline/src/spots.rs +++ b/crates/pipeline/src/spots.rs @@ -206,7 +206,9 @@ pub fn window_for_reads_checked( // refine the stroke over a couple of radii: each dab matters to pixels within 2.5 radii let mut dab_boxes: Vec<[f64; 4]> = Vec::new(); for st in autos { - let dabs = crate::masks::brush_dabs(st, frame, full_w, full_h); + // One more than the window takes, so a stroke past it is still recognised as past it + // without the other 1.8 million dabs being built first (#1520). + let dabs = crate::masks::brush_dabs_within(st, frame, full_w, full_h, MAX_DABS_CONSIDERED + 1); let r = dabs.r; if dabs.dabs.len() > MAX_DABS_CONSIDERED { continue; diff --git a/crates/pipeline/src/straighten.rs b/crates/pipeline/src/straighten.rs new file mode 100644 index 0000000000..481f4c8ef3 --- /dev/null +++ b/crates/pipeline/src/straighten.rs @@ -0,0 +1,186 @@ +//! Auto straighten: the crop angle that levels a photo, from three cues on the analysis image +//! ([`crate::upright::analysis_plane`]), tried in this order: +//! +//! 1. **Plumb lines**: the roll from the vertical vanishing point. Verticals that converge in +//! perspective (a building shot upward) still name the camera's roll, where their mean tilt +//! doesn't. Only a vanishing point backed by many lines across the frame counts. +//! 2. **The horizon**: the straight line across the whole width along which it is brighter on one +//! side than on the other (sky and sea, sky and land). It is scored by its weaker columns, so +//! the edges of waves, clouds or a ridge, which hold only in places, don't make one. +//! 3. **Long lines**: the consensus of near-horizontal or near-vertical segments (the rule Upright +//! Level uses), with at least [`MIN_LINES`] agreeing. It also vetoes a horizon it disagrees with. +//! +//! Nothing past [`MAX_DEGREES`] is levelled. +//! +//! Measured on 113 photos straightened by hand in Lightroom Classic, against the long lines alone: +//! 50 instead of 29 come out straighter, 10 (as before) more tilted, and the mean error is 0.82° +//! instead of 1.01°. Of 300 photos left as shot, 11 instead of 8 are turned by more than 3°. + +use lightcraft_raster::Plane; + +use crate::upright::{Analysis, Segment, detect_segments, level_angle_within, vanishing_point, vp_error}; + +/// The most Auto straighten turns a photo (degrees). None of the 113 photos straightened by hand +/// needed more than 6.1°, and larger "levels" came from texture (planks, a branch, a bird's wing). +pub const MAX_DEGREES: f64 = 5.0; + +/// The fewest agreeing long lines that level a photo on their own: one line (the frame of a +/// window, a branch) said nothing about the horizon. +pub const MIN_LINES: usize = 3; + +/// Long lines read up to this angle, so that a steeper consensus can veto a horizon. +const LINES_MAX_DEGREES: f64 = 10.0; +/// A horizon the long lines disagree with by more than this (degrees) is not used. +const VETO_DEGREES: f64 = 1.0; + +/// Plumb lines: fewest inliers of the vertical vanishing point, their least total length and the +/// least spread across the frame (both in half long edges), and the most a vertical may lean. +const PLUMB_MIN_LINES: usize = 8; +const PLUMB_MIN_LENGTH: f64 = 1.5; +const PLUMB_MIN_SPREAD: f64 = 0.6; +const PLUMB_MAX_LEAN: f64 = 20.0; + +/// Horizon: blur (px), rows averaged on each side of the line, the share of columns that may be +/// weaker than the score, the least score (relative to the image's strongest edges), and the +/// share of the height at the top and bottom a horizon doesn't lie in. +const HORIZON_SIGMA: f32 = 1.5; +const HORIZON_ROWS: usize = 4; +const HORIZON_QUANTILE: f64 = 0.3; +const HORIZON_MIN_SCORE: f64 = 0.3; +const HORIZON_MARGIN: f64 = 0.05; +/// Horizon search: the angles tried (degrees) before the limit applies, and their steps. +const HORIZON_SEARCH: f64 = 10.0; +const HORIZON_STEP: f64 = 0.25; +const HORIZON_FINE_STEP: f64 = 0.02; + +/// The crop angle (degrees, clockwise +) that levels the photo whose analysis image is `lum` and +/// whose segments are analysed in `a`, or `None` when no cue can be trusted. +pub(crate) fn decide(lum: &Plane, a: &Analysis) -> Option { + if let Some(roll) = plumb_roll(&a.vertical) { + return Some(roll); + } + let lines = level_angle_within(&a.vertical, &a.horizontal, LINES_MAX_DEGREES, MIN_LINES); + match (horizon(lum), lines) { + (Some(h), Some(l)) => ((h - l).abs() <= VETO_DEGREES).then_some(h), + (h, l) => h.or(l.filter(|l| l.abs() <= MAX_DEGREES)), + } +} + +/// [`decide`] for an analysis image alone (its segments detected here). +pub fn level_plane(lum: &Plane) -> Option { + decide(lum, &crate::upright::analyze(&detect_segments(lum))) +} + +fn fold(a: f64) -> f64 { + if a > 90.0 { + a - 180.0 + } else if a < -90.0 { + a + 180.0 + } else { + a + } +} + +/// The roll named by the vanishing point of the near-vertical segments. +fn plumb_roll(vertical: &[Segment]) -> Option { + let lines: Vec = vertical.iter().copied().filter(|s| s.tilt_from_vertical() < PLUMB_MAX_LEAN).collect(); + let (v, _) = vanishing_point(&lines)?; + let thr = 2f64.to_radians(); + let inliers: Vec<&Segment> = lines.iter().filter(|s| vp_error(s, v) < thr).collect(); + let length: f64 = inliers.iter().map(|s| s.len()).sum(); + let (lo, hi) = inliers.iter().map(|s| s.mid().x).fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x))); + if inliers.len() < PLUMB_MIN_LINES || length < PLUMB_MIN_LENGTH || hi - lo < PLUMB_MIN_SPREAD { + return None; + } + // a vanishing point inside or near the frame is a scene feature, not the camera's roll + let finite = v[2].abs() > 1e-9; + if finite && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0 { + return None; + } + let (vx, vy) = if finite { (v[0] / v[2], v[1] / v[2]) } else { (v[0], v[1]) }; + let roll = fold(vx.atan2(vy).to_degrees()); + (roll.is_finite() && roll.abs() <= MAX_DEGREES).then_some(roll) +} + +/// The crop angle that levels the horizon of `lum`, if it has one: the straight line across the +/// width along which the rows above are brighter (or darker) than those below in most columns. +fn horizon(lum: &Plane) -> Option { + let img = lightcraft_raster::blur::gaussian(lum, HORIZON_SIGMA); + let (w, h) = (img.width, img.height); + let k = HORIZON_ROWS; + if w < 32 || h < 4 * k + 8 || img.data.len() < w * h { + return None; + } + // per sampled column: the mean of the k rows above each row minus that of the k rows below + let cols: Vec = (0..w).step_by(2).collect(); + let mut diff = vec![0f32; cols.len() * h]; + let mut prefix = vec![0f64; h + 1]; + for (ci, &x) in cols.iter().enumerate() { + for y in 0..h { + prefix[y + 1] = prefix[y] + f64::from(img.data[y * w + x]); + } + for y in k..h - k { + let above = (prefix[y] - prefix[y - k]) / k as f64; + let below = (prefix[y + k] - prefix[y]) / k as f64; + diff[ci * h + y] = (above - below) as f32; + } + } + let mut strengths: Vec = diff.iter().map(|d| d.abs()).filter(|d| *d > 0.0).collect(); + if strengths.len() < 100 { + return None; + } + let p99 = strengths.len() * 99 / 100; + strengths.select_nth_unstable_by(p99, f32::total_cmp); + let norm = f64::from(strengths[p99]).max(1e-4); + let cx = w as f64 / 2.0; + let rows = ((h as f64 * HORIZON_MARGIN) as isize).max(k as isize)..((h as f64 * (1.0 - HORIZON_MARGIN)) as isize).min((h - k) as isize); + let mut column = Vec::with_capacity(cols.len()); + // the score of the line through (cx, b) with slope t: the contrast most of its columns reach + let mut score = |t: f64, b: f64, sign: f32| -> f64 { + column.clear(); + for (ci, &x) in cols.iter().enumerate() { + let y = (b + t * (x as f64 - cx)).round() as isize; + if rows.contains(&y) { + column.push(sign * diff[ci * h + y as usize]); + } + } + // a line that leaves the frame for more than a fifth of the width is not a horizon + if column.len() * 5 < cols.len() * 4 { + return f64::MIN; + } + let i = ((column.len() - 1) as f64 * HORIZON_QUANTILE) as usize; + column.select_nth_unstable_by(i, f32::total_cmp); + f64::from(column[i]) + }; + let mut best = (f64::MIN, 0.0f64, 0.0f64, 1.0f32); + for sign in [1.0f32, -1.0] { + let mut deg = -HORIZON_SEARCH; + while deg <= HORIZON_SEARCH { + let t = deg.to_radians().tan(); + for b in rows.clone().step_by(2) { + let s = score(t, b as f64, sign); + if s > best.0 { + best = (s, deg, b as f64, sign); + } + } + deg += HORIZON_STEP; + } + } + let (coarse_deg, coarse_b, sign) = (best.1, best.2, best.3); + let mut deg = coarse_deg - 0.3; + while deg <= coarse_deg + 0.3 { + let t = deg.to_radians().tan(); + let mut b = coarse_b - 3.0; + while b <= coarse_b + 3.0 { + let s = score(t, b, sign); + if s > best.0 { + best = (s, deg, b, sign); + } + b += 0.5; + } + deg += HORIZON_FINE_STEP; + } + let (s, deg) = (best.0 / norm, best.1); + // a line descending `deg` to the right is levelled by the crop angle −deg + (s >= HORIZON_MIN_SCORE && deg.abs() <= MAX_DEGREES).then_some(-deg) +} diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index d2074fb5d4..aa0d0a1dc6 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -906,3 +906,19 @@ fn negative_channels_render_finite_everywhere() { assert!(t.is_finite() && k.is_finite(), "auto WB {t} {k}"); assert!(auto::scene_log_mean(&src, &info, &pushed).is_none_or(f64::is_finite)); } + +/// A crop of no width used to give grain NaN coordinates (and NaN pixels); the render stays finite. +#[test] +fn zero_width_crop_with_grain_renders_finite_pixels() { + let mut s = DevelopSettings::default(); + s.grain.amount = 60.0; + s.crop.geometry.rect = lightcraft_geom::Rect::new(0.5, 0.1, 0.5, 0.9); + let mut req = RenderRequest::fit(240, 240); + req.depth = crate::OutputDepth::F32Linear; + let r = render(&scene(), &SourceInfo::default(), &s, &req); + if let Some(d) = r.deep + && let crate::DeepSamples::F32(v) = d.samples + { + assert!(v.iter().all(|x| x.is_finite()), "non-finite sample in a zero-width crop with grain"); + } +} diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index ac244cb0dc..d88b6cf5dd 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -469,12 +469,12 @@ fn debug_upright_scene() { } } -/// Sign convention for Auto straighten: a horizon descending 6° to the right needs crop angle −6°, +/// Sign convention for Auto straighten: a horizon descending 4° to the right needs crop angle −4°, /// which `level_degrees` must report (the crop panel uses it as the crop angle directly). #[test] fn level_degrees_sign_matches_crop_angle() { let (w, h) = (900usize, 600usize); - let t = 6f32.to_radians().tan(); + let t = 4f32.to_radians().tan(); let src = Rgb32f::from_fn(w, h, |x, y| { let yh = h as f32 / 2.0 + (x as f32 - w as f32 / 2.0) * t; if (y as f32) < yh { @@ -486,7 +486,7 @@ fn level_degrees_sign_matches_crop_angle() { } }); let deg = crate::upright::level_degrees(&src, &SourceInfo::default(), &DevelopSettings::default()).expect("lines found"); - assert!((deg + 6.0).abs() < 0.5, "{deg}"); + assert!((deg + 4.0).abs() < 0.5, "{deg}"); } /// A "horizon" of `deg` degrees: sky above, below it bands of `band` px (0: one edge only). @@ -505,22 +505,114 @@ fn tilted_scene(deg: f32, band: f32) -> Rgb32f { }) } -/// Auto straighten acts on several agreeing lines only: one edge (the frame of a window, a branch) -/// turned straight photos in a measurement on real ones, so it is left alone. -#[test] -fn auto_straighten_needs_more_than_one_line() { - let level = |src: &Rgb32f| crate::upright::level_degrees(src, &SourceInfo::default(), &DevelopSettings::default()); - assert_eq!(level(&tilted_scene(4.0, 0.0)), None, "one edge"); - let deg = level(&tilted_scene(4.0, 30.0)).expect("a horizon and the bands below it"); - assert!((deg + 4.0).abs() < 0.5, "{deg}"); +fn auto_level(src: &Rgb32f) -> Option { + crate::upright::level_degrees(src, &SourceInfo::default(), &DevelopSettings::default()) } -/// Auto straighten turns by at most `STRAIGHTEN_MAX_DEGREES`: larger "levels" came from texture -/// (planks, a bird's wing) on photos that were straight. +/// Thick dark lines on a light ground, each from `a` to `b` in centred coordinates (half the long +/// edge = 1). +fn line_drawing(lines: &[((f32, f32), (f32, f32))]) -> Rgb32f { + let (w, h) = (900usize, 600usize); + let half = w as f32 / 2.0; + Rgb32f::from_fn(w, h, |x, y| { + let p = ((x as f32 - w as f32 / 2.0) / half, (y as f32 - h as f32 / 2.0) / half); + let near = lines.iter().any(|&((ax, ay), (bx, by))| { + let (dx, dy) = (bx - ax, by - ay); + let t = (((p.0 - ax) * dx + (p.1 - ay) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + let (qx, qy) = (ax + t * dx - p.0, ay + t * dy - p.1); + qx.hypot(qy) * half < 3.0 + }); + if near { [0.05, 0.05, 0.05] } else { [0.8, 0.8, 0.8] } + }) +} + +/// A single short line (the frame of a window, a branch) levels nothing: it turned straight +/// photos in a measurement on real ones. +#[test] +fn auto_straighten_ignores_a_single_short_line() { + let t = 4f32.to_radians().tan(); + assert_eq!(auto_level(&line_drawing(&[((-0.3, -0.3 * t), (0.3, 0.3 * t))])), None, "one short line"); + // a horizon is one straight edge too, but across the whole width + let deg = auto_level(&tilted_scene(4.0, 0.0)).expect("a horizon"); + assert!((deg + 4.0).abs() < 0.3, "{deg}"); +} + +/// Auto straighten turns by at most `straighten::MAX_DEGREES` (5°): none of 113 photos +/// straightened by hand needed more than 6.1°, and larger "levels" came from texture. #[test] fn auto_straighten_leaves_steep_lines_alone() { - let level = |src: &Rgb32f| crate::upright::level_degrees(src, &SourceInfo::default(), &DevelopSettings::default()); - assert_eq!(level(&tilted_scene(20.0, 30.0)), None, "20° is not a horizon to level"); - let deg = level(&tilted_scene(8.0, 30.0)).expect("8° is"); - assert!((deg + 8.0).abs() < 0.5, "{deg}"); + assert_eq!(auto_level(&tilted_scene(20.0, 30.0)), None, "20° is not a horizon to level"); + assert_eq!(auto_level(&tilted_scene(8.0, 30.0)), None, "nor is 8°"); + let deg = auto_level(&tilted_scene(4.0, 30.0)).expect("4° is"); + assert!((deg + 4.0).abs() < 0.3, "{deg}"); +} + +/// A sea horizon among ripples: the short, randomly tilted edges of the water outnumber the +/// horizon, which the line consensus took for no answer (or the ripples' angle), but the horizon +/// runs across the whole width and levels the photo. +#[test] +fn auto_straighten_finds_a_sea_horizon_among_ripples() { + let (w, h) = (900usize, 600usize); + let t = 2f32.to_radians().tan(); + let mut seed = 7u32; + let mut rnd = || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }; + // ripples: short bright dashes tilted up to ±12° + let ripples: Vec<(f32, f32, f32, f32)> = + (0..400).map(|_| (rnd() * w as f32, rnd() * h as f32, (rnd() - 0.5) * 0.4, 8.0 + rnd() * 25.0)).collect(); + let src = Rgb32f::from_fn(w, h, |x, y| { + let (x, y) = (x as f32, y as f32); + let yh = h as f32 * 0.4 + (x - w as f32 / 2.0) * t; + if y < yh { + return [0.75, 0.8, 0.9]; + } + let lit = ripples.iter().any(|&(rx, ry, slope, len)| { + let dx = x - rx; + dx.abs() < len && (y - ry - slope * dx).abs() < 1.2 && ry > yh + 4.0 + }); + if lit { [0.5, 0.55, 0.6] } else { [0.1, 0.15, 0.25] } + }); + let deg = auto_level(&src).expect("the horizon"); + assert!((deg + 2.0).abs() < 0.3, "{deg}"); +} + +/// A building shot upward and rolled 3°: its verticals converge on a vanishing point above the +/// frame. Their mean tilt depends on where in the frame they stand (here all right of centre); +/// the vanishing point gives the roll. +#[test] +fn auto_straighten_takes_the_roll_from_converging_verticals() { + let roll = 3f32.to_radians(); + let vp = (6.0 * roll.sin(), -6.0 * roll.cos()); + let lines: Vec<_> = (0..12) + .map(|i| { + let x = 0.05 + i as f32 * 0.07; + let bottom = (x, 0.6); + // two thirds of the way from the bottom towards the vanishing point, ending in the frame + let top_t = (0.6 + 0.6) / (0.6 - vp.1); + (bottom, (x + (vp.0 - x) * top_t, 0.6 + (vp.1 - 0.6) * top_t)) + }) + .collect(); + let deg = auto_level(&line_drawing(&lines)).expect("the vanishing point"); + assert!((deg + 3.0).abs() < 0.3, "{deg}"); +} + +/// The Upright analysis cache tells apart what changes the analysis image: another lens (`info.lens`) +/// or the optics section switched off (review of #2809). +#[test] +fn the_analysis_cache_tells_lenses_and_optics_apart() { + let src = tilted_scene(2.0, 30.0); + let s = DevelopSettings::default(); + let plain = SourceInfo::default(); + let vignette = lightcraft_develop::EmbeddedVignette::default(); + let lens = + SourceInfo { lens: Some(lightcraft_develop::EmbeddedLens { vignette: Some(vignette), ..Default::default() }), ..SourceInfo::default() }; + let key = crate::upright::analysis_key; + assert_eq!(key(&src, &plain, &s), key(&src, &plain.clone(), &s), "the same source, settings and lens"); + assert_ne!(key(&src, &plain, &s), key(&src, &lens, &s), "another lens"); + let mut off = s.clone(); + off.disabled_sections.push("optics".into()); + assert!(!off.section_enabled("optics")); + assert_ne!(key(&src, &plain, &s), key(&src, &plain, &off), "the optics section off"); } diff --git a/crates/pipeline/src/tests_window.rs b/crates/pipeline/src/tests_window.rs index b82a19f459..0d7508bc20 100644 --- a/crates/pipeline/src/tests_window.rs +++ b/crates/pipeline/src/tests_window.rs @@ -156,6 +156,18 @@ fn windows_outside_or_degenerate_are_clamped() { } } +/// A model's segmentation on a `side²` grid: an ellipse in the middle of the photo. +fn middle_seg(side: usize) -> lightcraft_develop::SegMask { + let logits: Vec = (0..side * side) + .map(|i| { + let (x, y) = (((i % side) as f32 + 0.5) / side as f32, ((i / side) as f32 + 0.5) / side as f32); + let r = (((x - 0.5) / 0.3).powi(2) + ((y - 0.5) / 0.25).powi(2)).sqrt(); + (12.0 * (1.0 - r) * 4.0).clamp(-12.0, 12.0) + }) + .collect(); + lightcraft_develop::SegMask::from_logits(side, &logits) +} + /// A textured, noisy source: what noise reduction and edge refinement act on. fn noisy_scene() -> Rgb32f { let base = scene(); @@ -216,6 +228,8 @@ fn a_mask_overlay_window_matches_the_whole_render() { ("radial", MaskShape::Radial { center: Point::new(0.5, 0.5), rx: 0.2, ry: 0.15, angle: 20.0, feather: 50.0, invert: false }, 0.0), ("linear refined", MaskShape::Linear { start: Point::new(0.45, 0.5), end: Point::new(0.55, 0.5) }, 100.0), ("sky", MaskShape::Sky, 0.0), + // a model's grid, enlarged along the photo's edges (issue #3272) + ("prompt", MaskShape::Prompt { text: "middle".into(), seg: Some(middle_seg(32)), detail: vec![], edge: 0.0 }, 0.0), ]; for (name, shape, refine) in shapes { let mut s = DevelopSettings::default(); diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 58a61adbe2..a77369eb4b 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -40,7 +40,7 @@ impl Segment { pub fn is_empty(&self) -> bool { self.len() == 0.0 } - fn mid(&self) -> Point { + pub(crate) fn mid(&self) -> Point { self.a.lerp(self.b, 0.5) } /// Homogeneous line through the endpoints, normalized so (a, b) is a unit normal. @@ -50,7 +50,7 @@ impl Segment { [l[0] / n, l[1] / n, l[2] / n] } /// Angle from vertical in degrees (0 = vertical), folded to 0..90. - fn tilt_from_vertical(&self) -> f64 { + pub(crate) fn tilt_from_vertical(&self) -> f64 { let (dx, dy) = (self.b.x - self.a.x, self.b.y - self.a.y); dx.abs().atan2(dy.abs()).to_degrees() } @@ -200,7 +200,7 @@ pub fn detect_segments(lum: &Plane) -> Vec { // ------------------------------------------------------------------------------------------ vanishing points /// Angular error (radians) between a segment and the direction from its midpoint to the (homogeneous) point `v`. -fn vp_error(s: &Segment, v: [f64; 3]) -> f64 { +pub(crate) fn vp_error(s: &Segment, v: [f64; 3]) -> f64 { let m = s.mid(); let (dx, dy) = (v[0] - m.x * v[2], v[1] - m.y * v[2]); let (sx, sy) = (s.b.x - s.a.x, s.b.y - s.a.y); @@ -380,7 +380,7 @@ fn level_angle(vert: &[Segment], horiz: &[Segment]) -> Option { /// [`level_angle`] that only answers for at most `max` degrees, backed by at least `min_lines` /// agreeing segments. -fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, min_lines: usize) -> Option { +pub(crate) fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, min_lines: usize) -> Option { let dev = |s: &Segment, vertical: bool| { let (dx, dy) = (s.b.x - s.a.x, s.b.y - s.a.y); // signed deviation in degrees of the segment from the axis @@ -547,26 +547,13 @@ const ANALYSIS_LONG: usize = 1024; /// segment detection and vanishing points. Cached per source + optics settings. pub fn analyze_source(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Analysis { static CACHE: Mutex> = Mutex::new(Vec::new()); - let mut base = s.clone(); - base.geometry = Geometry::default(); - base.crop = Crop::default(); - let key = crate::optics::fingerprint(src) - ^ lightcraft_develop::DevelopSettings { optics: s.optics, orientation: s.orientation, ..Default::default() }.hash64().rotate_left(17); + let key = analysis_key(src, info, s); if let Ok(c) = CACHE.lock() && let Some((_, a)) = c.iter().find(|(k, _)| *k == key) { return a.clone(); } - let frame = crate::frame_for(src, info, &base, false); - let (w, h) = frame.fit(ANALYSIS_LONG, ANALYSIS_LONG); - let img = frame.sample(src, w, h); - // perceptual lightness, normalized to the image's bright end - let lum = img.luminance(); - let mut v: Vec = lum.data.iter().copied().filter(|x| x.is_finite()).collect(); - v.sort_by(f32::total_cmp); - let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4); - let lum = lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4)); - let a = analyze(&detect_segments(&lum)); + let a = analyze(&detect_segments(&analysis_plane(src, info, s))); if let Ok(mut c) = CACHE.lock() { c.push((key, a.clone())); if c.len() > 8 { @@ -576,27 +563,41 @@ pub fn analyze_source(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> A a } -/// The most Auto straighten turns a photo (degrees). Measured on 68 photos straightened by hand -/// in Lightroom Classic and 300 left as shot: none was turned by more than 6°, while a larger -/// "level" came from texture (wooden planks, a branch, a bird's wing) and turned photos that were -/// straight. -pub const STRAIGHTEN_MAX_DEGREES: f64 = 10.0; - -/// The fewest agreeing lines Auto straighten acts on: one line (the frame's edge, a branch) said -/// nothing about the horizon in that measurement. -pub const STRAIGHTEN_MIN_LINES: usize = 3; - -/// The rotation (degrees, clockwise +) that levels `src`'s dominant horizon/plumb lines, if they agree -/// (the consensus rule of Upright Level), within [`STRAIGHTEN_MAX_DEGREES`] and backed by at least -/// [`STRAIGHTEN_MIN_LINES`] lines. Used by the crop panel's Auto straighten. -pub fn level_degrees(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Option { - let a = analyze_source(src, info, s); - straighten_angle(&a) +/// What an analysis depends on: the source (by its sampled fingerprint), the optics and +/// orientation settings, whether the optics section is on, and the lens the frame is corrected for +/// (`info.lens`, which [`analysis_plane`] reads through the frame). +pub(crate) fn analysis_key(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> u64 { + use std::hash::{Hash, Hasher}; + let mut more = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}", info.lens).hash(&mut more); + s.section_enabled("optics").hash(&mut more); + crate::optics::fingerprint(src) + ^ lightcraft_develop::DevelopSettings { optics: s.optics, orientation: s.orientation, ..Default::default() }.hash64().rotate_left(17) + ^ more.finish().rotate_left(29) } -/// [`level_degrees`] of an analysis. -pub fn straighten_angle(a: &Analysis) -> Option { - level_angle_within(&a.vertical, &a.horizontal, STRAIGHTEN_MAX_DEGREES, STRAIGHTEN_MIN_LINES) +/// The image an analysis reads: the lens-corrected source (optics applied, no perspective or crop) +/// at [`ANALYSIS_LONG`] px, as perceptual lightness normalized to its bright end. +pub(crate) fn analysis_plane(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Plane { + let mut base = s.clone(); + base.geometry = Geometry::default(); + base.crop = Crop::default(); + let frame = crate::frame_for(src, info, &base, false); + let (w, h) = frame.fit(ANALYSIS_LONG, ANALYSIS_LONG); + let img = frame.sample(src, w, h); + let lum = img.luminance(); + let mut v: Vec = lum.data.iter().copied().filter(|x| x.is_finite()).collect(); + v.sort_by(f32::total_cmp); + let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4); + lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4)) +} + +/// The crop angle (degrees, clockwise +) Auto straighten levels `src` by, if it finds a horizon or +/// plumb lines it can trust ([`crate::straighten`]). Used by the crop panel's Auto straighten. It +/// reads the horizon and the segments from the same analysis image, built here (not through +/// [`analyze_source`]'s cache: it runs once per click). +pub fn level_degrees(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Option { + crate::straighten::level_plane(&analysis_plane(src, info, s)) } /// The automatic Upright correction for `mode` on `src` (identity for Off and Guided). diff --git a/crates/pipeline/src/visualize.rs b/crates/pipeline/src/visualize.rs index 8f3cf18846..cda511baa8 100644 --- a/crates/pipeline/src/visualize.rs +++ b/crates/pipeline/src/visualize.rs @@ -9,6 +9,11 @@ //! - **Mask overlay** (Masking): the evaluated alpha of one mask, drawn as a colour tint, a colour //! tint on a black-and-white image, the image on black / white, or the alpha as white on black //! ([`MaskView`]). Both renderers hand the same alpha plane (the one the render used) to [`apply`]. +//! - **Alt/Option-drag previews** (Lightroom's temporary views while a slider is dragged with the +//! modifier held; [`Overlay::for_control`] picks one per control): shadow / highlight clipping +//! (white or black, with the clipped channels shown), greyscale (Sharpening Amount), the fine +//! detail band sharpening works on (Radius / Detail) and the sharpening mask (Masking). The +//! sharpening views read the render's own detail planes ([`sharpen_plane`]). use std::borrow::Cow; @@ -39,6 +44,19 @@ pub enum Overlay { /// Visualize HDR (photos edited in HDR): the SDR image dimmed to grey, with every pixel the HDR /// rendition puts above SDR white painted by how far above it is ([`HDR_BANDS`]). HdrRange, + /// Shadow clipping (Alt-drag on Blacks / Shadows): white, a channel at 0 drops out of the + /// colour, so pixels clipped in every channel are black and partly clipped ones are coloured. + ClipShadows, + /// Highlight clipping (Alt-drag on Exposure / Highlights / Whites): black, a channel at 255 + /// shows in the colour, so pixels clipped in every channel are white. + ClipHighlights, + /// The photo in greyscale (Alt-drag on Sharpening Amount). + Grayscale, + /// The fine detail band sharpening amplifies, as grey ± detail (Alt-drag on Sharpening Radius + /// / Detail). + SharpenDetail, + /// The sharpening mask, white where sharpening applies (Alt-drag on Sharpening Masking). + SharpenMask, } /// [`Overlay::HdrRange`] colours (sRGB) for 0–1, 1–2, 2–3 and ≥ 3 stops above SDR white. @@ -125,6 +143,11 @@ impl Overlay { Overlay::Mask { id, view, color, opacity } => (3, pack_mask(id, view, color, opacity) as f64), Overlay::AllMasks { view, color, opacity } => (5, pack_mask(0, view, color, opacity) as f64), Overlay::HdrRange => (4, 0.0), + Overlay::ClipShadows => (6, 0.0), + Overlay::ClipHighlights => (7, 0.0), + Overlay::Grayscale => (8, 0.0), + Overlay::SharpenDetail => (9, 0.0), + Overlay::SharpenMask => (10, 0.0), } } @@ -143,6 +166,11 @@ impl Overlay { opacity: ((v as u64 >> 44) & 0x7f).min(100) as u8, } } + 6 => Overlay::ClipShadows, + 7 => Overlay::ClipHighlights, + 8 => Overlay::Grayscale, + 9 => Overlay::SharpenDetail, + 10 => Overlay::SharpenMask, _ => Overlay::None, } } @@ -156,9 +184,44 @@ impl Overlay { Overlay::Mask { id, view, color, opacity } => 3 << 60 | pack_mask(id, view, color, opacity), Overlay::AllMasks { view, color, opacity } => 5 << 60 | pack_mask(0, view, color, opacity), Overlay::HdrRange => 0x4000, + Overlay::ClipShadows => 0x5000, + Overlay::ClipHighlights => 0x5001, + Overlay::Grayscale => 0x5002, + Overlay::SharpenDetail => 0x5003, + Overlay::SharpenMask => 0x5004, } } + /// The temporary preview Lightroom shows while develop control `id` is dragged with Alt + /// (Option on macOS) held, if it has one. + pub fn for_control(id: &str) -> Option { + match id { + "light.exposure" | "light.highlights" | "light.whites" => Some(Overlay::ClipHighlights), + "light.shadows" | "light.blacks" => Some(Overlay::ClipShadows), + "detail.sharpenAmount" | "detail.nrLuminance" | "detail.nrDetail" | "detail.nrContrast" => Some(Overlay::Grayscale), + "detail.sharpenRadius" | "detail.sharpenDetail" => Some(Overlay::SharpenDetail), + "detail.sharpenMasking" => Some(Overlay::SharpenMask), + _ => None, + } + } + + /// The clipping previews, which test the sRGB values the histogram counts (a render for a + /// display profile draws them in sRGB, then converts). + pub fn is_clipping(self) -> bool { + matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights) + } + + /// Whether the overlay draws from the render's detail planes ([`sharpen_plane`]). + pub fn reads_detail(self) -> bool { + matches!(self, Overlay::SharpenDetail | Overlay::SharpenMask) + } + + /// Whether the overlay works pixel by pixel on the finished image, so a window render shows + /// the same as the whole frame would. + pub fn per_pixel(self) -> bool { + matches!(self, Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::Grayscale) + } + /// The mask an [`Overlay::Mask`] shows (if it exists in `s` and has components). pub fn mask(self, s: &DevelopSettings) -> Option<&lightcraft_develop::Mask> { match self { @@ -180,10 +243,45 @@ pub fn adjust_settings(o: Overlay, s: &mut Cow<'_, DevelopSettings>) { } } -/// Draw overlay `o` over `img` (rendered with `plan`). `mask` is the evaluated alpha of the mask -/// an [`Overlay::Mask`] shows, at the image's size (see [`Overlay::mask`]); `masks` is the set of -/// alphas an [`Overlay::AllMasks`] shows, one per visible mask with components. -pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, mask: Option<&Plane>, masks: Option<&[Plane]>) { +/// The plane a sharpening view draws ([`Overlay::reads_detail`]), from the render's log luminance +/// `log_l` and its texture blur (`None` when the render didn't need it: blurred here with the same +/// sigma). [`Overlay::SharpenDetail`]: the detail band (log luminance minus its blur, in EV); +/// [`Overlay::SharpenMask`]: the sharpening weight under the photo's Masking. Both renderers call +/// this with their own planes. +pub fn sharpen_plane(o: Overlay, s: &DevelopSettings, log_l: &Plane, texture: Option<&Plane>, px_per_long: f64) -> Option { + if !o.reads_detail() { + return None; + } + let own; + let blur = match texture.filter(|b| (b.width, b.height) == (log_l.width, log_l.height)) { + Some(b) => b, + None => { + own = lightcraft_raster::blur::gaussian(log_l, crate::local::texture_sigma(px_per_long)); + &own + } + }; + let masking = (s.detail.sharpen_masking / 100.0).clamp(0.0, 1.0) as f32; + let mask = o == Overlay::SharpenMask; + let data = log_l + .data + .iter() + .zip(&blur.data) + .map(|(l, b)| { + let det = l - b; + if mask { crate::finish::sharpen_mask_weight(masking, det) } else { det } + }) + .collect(); + Some(Plane { width: log_l.width, height: log_l.height, data }) +} + +/// [`Overlay::SharpenDetail`]: encoded grey per EV of detail (±0.4 EV spans black to white). +const DETAIL_GAIN: f32 = 320.0; + +/// Draw overlay `o` over `img` (rendered with `plan`). `plane` is what the overlay shows, at the +/// image's size: the evaluated alpha of the mask an [`Overlay::Mask`] shows (see +/// [`Overlay::mask`]) or a sharpening view's [`sharpen_plane`]; `masks` is the set of alphas an +/// [`Overlay::AllMasks`] shows, one per visible mask with components. +pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, plane: Option<&Plane>, masks: Option<&[Plane]>) { match o { // drawn by the renderer from the HDR rendition ([`hdr_range`]) Overlay::None | Overlay::HdrRange => {} @@ -194,10 +292,27 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, mask: Option<&Plane>, } Overlay::Spots(t) => spots(img, t, plan.px_per_long), Overlay::Mask { view, color, opacity, .. } => { - if let Some(a) = mask.filter(|a| (a.width, a.height) == (img.width, img.height)) { + if let Some(a) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) { mask_view(img, a, view, color, opacity); } } + Overlay::ClipShadows => clipping(img, false), + Overlay::ClipHighlights => clipping(img, true), + Overlay::Grayscale => grayscale(img), + Overlay::SharpenDetail | Overlay::SharpenMask => { + if let Some(p) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) { + let detail = o == Overlay::SharpenDetail; + let w = img.width; + for_rows(&mut img.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let v = p.data[y * w + x]; + let g = if detail { 128.0 + v * DETAIL_GAIN } else { 255.0 * v }; + let g = g.round().clamp(0.0, 255.0) as u8; + *px = [g, g, g, 255]; + } + }); + } + } Overlay::AllMasks { view, color, opacity } => { // one view of the union of the masks: painting the planes one after another // overwrites (White on Black, Image on Black…) or compounds (Color) the earlier ones @@ -215,6 +330,36 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, mask: Option<&Plane>, } } +/// [`Overlay::ClipHighlights`] (`high`) or [`Overlay::ClipShadows`]: each channel shows only +/// whether it is clipped, on black (highlights) or white (shadows). +pub fn clipping(img: &mut Rgba8, high: bool) { + let w = img.width; + for_rows(&mut img.data, w, |_, row| { + for px in row.iter_mut() { + for c in &mut px[..3] { + *c = if high { + if *c == 255 { 255 } else { 0 } + } else if *c == 0 { + 0 + } else { + 255 + }; + } + px[3] = 255; + } + }); +} + +fn grayscale(img: &mut Rgba8) { + let w = img.width; + for_rows(&mut img.data, w, |_, row| { + for px in row.iter_mut() { + let g = (0.2126 * px[0] as f32 + 0.7152 * px[1] as f32 + 0.0722 * px[2] as f32).round().clamp(0.0, 255.0) as u8; + *px = [g, g, g, 255]; + } + }); +} + /// Draw mask alpha `a` over `img` as `view`. pub fn mask_view(img: &mut Rgba8, a: &Plane, view: MaskView, color: [u8; 3], opacity: u8) { let op = opacity.min(100) as f32 / 100.0; @@ -409,6 +554,121 @@ mod tests { assert_eq!(MaskView::parse("colorOnBw"), Some(MaskView::ColorOnBw)); } + #[test] + fn clipping_views_show_the_clipped_channels() { + let mut img = Rgba8 { + width: 5, + height: 1, + data: vec![[0, 0, 0, 255], [255, 255, 255, 255], [255, 40, 0, 255], [0, 128, 200, 255], [120, 130, 140, 255]], + }; + let mut hi = img.clone(); + clipping(&mut hi, true); + // black background, white where every channel clips, the clipped channels' colour otherwise + assert_eq!(hi.data, vec![[0, 0, 0, 255], [255; 4], [255, 0, 0, 255], [0, 0, 0, 255], [0, 0, 0, 255]]); + clipping(&mut img, false); + // white background, black where every channel clips, the unclipped channels' colour otherwise + assert_eq!(img.data, vec![[0, 0, 0, 255], [255; 4], [255, 255, 0, 255], [0, 255, 255, 255], [255; 4]]); + } + + #[test] + fn clipping_previews_follow_the_rendered_clipping() { + // left: deep shadow, middle: grey, right: bright highlight + let src = Rgb32f::from_fn(60, 20, |x, _| match x / 20 { + 0 => [0.0; 3], + 1 => [0.18; 3], + _ => [3.0; 3], + }); + let info = SourceInfo::default(); + let mut s = DevelopSettings::default(); + s.light.blacks = -100.0; + s.light.whites = 100.0; + let req = |o| RenderRequest { overlay: o, ..RenderRequest::fit(60, 20) }; + let plain = render(&src, &info, &s, &req(Overlay::None)); + let hi = render(&src, &info, &s, &req(Overlay::ClipHighlights)); + let lo = render(&src, &info, &s, &req(Overlay::ClipShadows)); + let at = |i: &Rgba8, x: usize| i.data[10 * 60 + x]; + assert_eq!(at(&plain.image, 55), [255; 4], "the highlight clips"); + assert_eq!(at(&plain.image, 5), [0, 0, 0, 255], "the shadow clips"); + assert_eq!((at(&hi.image, 55), at(&hi.image, 30), at(&hi.image, 5)), ([255; 4], [0, 0, 0, 255], [0, 0, 0, 255])); + assert_eq!((at(&lo.image, 5), at(&lo.image, 30), at(&lo.image, 55)), ([0, 0, 0, 255], [255; 4], [255; 4])); + // a preview only: the histogram is the photo's + assert_eq!(hi.histogram, plain.histogram); + assert_eq!(render(&src, &info, &s, &req(Overlay::None)).image, plain.image); + } + + #[test] + fn sharpening_previews_show_the_mask_and_detail() { + // a smooth ramp (left) and a hard edge (at x = 60) + let src = Rgb32f::from_fn(80, 40, |x, _| if x < 60 { [0.05 + 0.002 * x as f32; 3] } else { [0.6; 3] }); + let info = SourceInfo::default(); + let mut s = DevelopSettings::default(); + s.detail.sharpen_amount = 60.0; + let shot = |s: &DevelopSettings, o| render(&src, &info, s, &RenderRequest { overlay: o, ..RenderRequest::fit(80, 40) }).image; + let (flat, edge) = (20 * 80 + 20, 20 * 80 + 60); + // Masking 0 sharpens everything: an all-white mask + let m = shot(&s, Overlay::SharpenMask); + assert!(m.data.iter().all(|p| *p == [255; 4])); + // Masking 100 keeps the edge, protects the ramp + s.detail.sharpen_masking = 100.0; + let m = shot(&s, Overlay::SharpenMask); + assert_eq!((m.data[edge], m.data[flat]), ([255; 4], [0, 0, 0, 255])); + // the same without sharpening on (the render has no texture plane then) + s.detail.sharpen_amount = 0.0; + assert_eq!(shot(&s, Overlay::SharpenMask), m); + // detail: mid grey on the ramp, light / dark either side of the edge + let d = shot(&s, Overlay::SharpenDetail); + assert!(d.data[flat][0].abs_diff(128) <= 3, "{:?}", d.data[flat]); + assert!(d.data[edge][0] > 200 && d.data[edge - 1][0] < 60, "{:?} {:?}", d.data[edge], d.data[edge - 1]); + // greyscale + let src = Rgb32f::from_fn(8, 8, |_, _| [0.4, 0.1, 0.05]); + let g = render(&src, &info, &s, &RenderRequest { overlay: Overlay::Grayscale, ..RenderRequest::fit(8, 8) }).image; + assert!(g.data.iter().all(|p| p[0] == p[1] && p[1] == p[2] && p[0] > 0)); + } + + #[test] + fn alt_previews_map_to_controls_and_round_trip() { + assert_eq!(Overlay::for_control("light.blacks"), Some(Overlay::ClipShadows)); + assert_eq!(Overlay::for_control("light.shadows"), Some(Overlay::ClipShadows)); + assert_eq!(Overlay::for_control("light.whites"), Some(Overlay::ClipHighlights)); + assert_eq!(Overlay::for_control("light.exposure"), Some(Overlay::ClipHighlights)); + assert_eq!(Overlay::for_control("light.highlights"), Some(Overlay::ClipHighlights)); + assert_eq!(Overlay::for_control("detail.sharpenAmount"), Some(Overlay::Grayscale)); + assert_eq!(Overlay::for_control("detail.sharpenDetail"), Some(Overlay::SharpenDetail)); + assert_eq!(Overlay::for_control("detail.sharpenMasking"), Some(Overlay::SharpenMask)); + for c in ["detail.nrLuminance", "detail.nrDetail", "detail.nrContrast"] { + assert_eq!(Overlay::for_control(c), Some(Overlay::Grayscale), "{c}"); + } + assert_eq!(Overlay::for_control("detail.nrColor"), None); + assert_eq!(Overlay::for_control("light.contrast"), None); + // every mapped id is a real control (a rename would silently drop its preview) + for c in [ + "light.exposure", + "light.highlights", + "light.whites", + "light.shadows", + "light.blacks", + "detail.sharpenAmount", + "detail.sharpenRadius", + "detail.sharpenDetail", + "detail.sharpenMasking", + "detail.nrLuminance", + "detail.nrDetail", + "detail.nrContrast", + ] { + assert!(lightcraft_develop::controls::find(c).is_some(), "{c}"); + assert!(Overlay::for_control(c).is_some(), "{c}"); + } + assert!(Overlay::ClipShadows.is_clipping() && Overlay::ClipHighlights.is_clipping() && !Overlay::Grayscale.is_clipping()); + let all = [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask]; + for o in all { + let (k, v) = o.to_parts(); + assert_eq!(Overlay::from_parts(k, v), o); + assert_eq!(all.iter().filter(|p| p.key() == o.key()).count(), 1); + assert_ne!(o.key(), Overlay::HdrRange.key()); + } + assert!(Overlay::ClipShadows.per_pixel() && !Overlay::SharpenDetail.per_pixel()); + } + #[test] fn all_masks_overlay_shows_every_visible_mask_at_once() { use lightcraft_develop::{Mask, MaskComponent, MaskOp, MaskShape}; diff --git a/crates/raw/proptest-regressions/vendor/rafc.txt b/crates/raw/proptest-regressions/vendor/rafc.txt new file mode 100644 index 0000000000..7633abe0fb --- /dev/null +++ b/crates/raw/proptest-regressions/vendor/rafc.txt @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 8cb6b5999a8279e655a148a18b220d75b02c519f644583f4593166286297a3f4 # shrinks to data = [0, 0, 0, 8], reads = [(false, 13, 0), (true, 0, 15)] diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 75f7674ac3..245586f39a 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -260,6 +260,53 @@ mod tests { assert!(xp > 20.0 && xp >= xb - 0.5, "xtrans directional {xp:.1} bilinear {xb:.1}"); } + /// Mean anisotropy of a demosaiced picture's fine luminance detail: per pixel, how much more its 3 × 3 high-pass + /// correlates with its horizontal neighbours than with its vertical ones (or the reverse). Noise has none; the + /// short horizontal and vertical strokes of a maze pattern have a lot. + fn anisotropy(img: &Rgb32f) -> f64 { + let (w, h) = (img.width, img.height); + let lum: Vec = img.data.iter().map(|p| 0.25 * p[0] + 0.5 * p[1] + 0.25 * p[2]).collect(); + let mean3 = |x: usize, y: usize| (0..9).map(|k| lum[(y + k / 3 - 1) * w + x + k % 3 - 1]).sum::() / 9.0; + let hp: Vec = + (0..w * h).map(|i| if i % w == 0 || i % w == w - 1 || i < w || i >= w * (h - 1) { 0.0 } else { lum[i] - mean3(i % w, i / w) }).collect(); + let (mut sum, mut n) = (0f64, 0f64); + for y in 2..h - 2 { + for x in 2..w - 2 { + let i = y * w + x; + sum += f64::from((hp[i] * (hp[i - 1] + hp[i + 1] - hp[i - w] - hp[i + w])).abs()); + n += 1.0; + } + } + sum / n + } + + #[test] + fn flat_noise_does_not_turn_into_a_maze() { + // a flat grey patch with sensor-like noise: AHD picked horizontal or vertical candidates per pixel by a + // homogeneity count that noise alone decides, so the picture became short horizontal and vertical strokes + let (w, h) = (192, 160); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut noise = || { + // sum of four uniforms ≈ Gaussian, σ ≈ 0.02 + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5 + }) + .sum::() + * 0.035 + }; + let cfa = Cfa::bayer("RGGB").unwrap(); + let data = (0..w * h).map(|_| 0.2 + noise()).collect(); + let n = Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; + let (ahd, bilinear) = (anisotropy(&demosaic(&n, Method::Ahd)), anisotropy(&demosaic(&n, Method::Bilinear))); + eprintln!("anisotropy: ahd {ahd:.3e}, bilinear {bilinear:.3e}"); + // the hard choice gave about 11 times bilinear's, the blend about 7.5 times + assert!(ahd < 9.0 * bilinear, "ahd {ahd:.3e} bilinear {bilinear:.3e}"); + } + #[test] fn tiny_and_degenerate_inputs() { let cfa = Cfa::bayer("RGGB").unwrap(); @@ -277,6 +324,20 @@ mod tests { assert_eq!(demosaic(&n, Method::Ahd).data, vec![[0.1, 0.2, 0.3]]); } + #[test] + fn a_nan_sample_spreads_no_further_than_the_chosen_candidate_takes_it() { + // vertical stripes: the vertical candidate wins outright beside them, and the horizontal one, which reads two + // samples to each side, is the only one that sees a NaN two columns away + let img = Rgb32f::from_fn(32, 24, |x, _| if (x / 2) % 2 == 0 { [0.2, 0.3, 0.25] } else { [0.7, 0.8, 0.6] }); + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut n = mosaic_from_rgb(&img, &cfa); + n.data[12 * 32 + 16] = f32::NAN; + let out = demosaic(&n, Method::Ahd); + let bad = out.data.iter().filter(|p| p.iter().any(|v| !v.is_finite())).count(); + // the pixels that read the NaN sample themselves, as many as the outright pick gave; the blend made it 33 + assert!(bad <= 9, "{bad} pixels not finite"); + } + #[test] fn non_finite_samples_do_not_panic() { // regression: NaN samples (a float DNG) gave AHD and PPG NaN bounds for `f32::clamp`, which panics diff --git a/crates/raw/src/demosaic/ahd.rs b/crates/raw/src/demosaic/ahd.rs index 6afcd92511..9a1d477e8f 100644 --- a/crates/raw/src/demosaic/ahd.rs +++ b/crates/raw/src/demosaic/ahd.rs @@ -6,7 +6,8 @@ //! 2. Complete each candidate with red/blue by colour-difference (C − G) interpolation. //! 3. Convert both candidates to CIELab and measure, per pixel, how many of its 4 neighbours lie within the //! adaptive luminance / chrominance tolerances (ε_L, ε_C from the paper) — the homogeneity. -//! 4. Sum homogeneity over a 3×3 window and pick the more homogeneous candidate (average on ties). +//! 4. Sum homogeneity over a 3×3 window and pick the more homogeneous candidate. The paper picks one outright; +//! we blend the two by how far apart their sums are (see [`BLEND`]), so a clear edge still takes one candidate. //! //! Work is done in overlapping tiles (bounded memory, rayon-parallel), one band of tiles at a time written //! straight into the output. Each step runs only where the tile's output depends on it: the choice reads the @@ -19,6 +20,11 @@ use rayon::prelude::*; const TILE: usize = 128; const MARGIN: usize = 6; +/// Difference of the two candidates' 3×3 homogeneity sums (each 0–36) from which the more homogeneous one is taken +/// alone; closer sums blend the two linearly, equal sums half and half. In a flat, noisy area noise alone decides +/// which sum is larger, and picking outright turned the noise into short horizontal and vertical strokes (a maze, +/// coloured where white balance is strong). 12 keeps the PSNR of the outright pick on the edge tests. +const BLEND: f32 = 12.0; pub(crate) fn ahd(m: &Mosaic) -> Rgb32f { ahd_window(m, 0, 0, m.w, m.h) @@ -157,12 +163,16 @@ fn tile(m: &Mosaic, x0: usize, y0: usize, tw: usize, th: usize) -> Vec<[f32; 3]> sh += hh[j] as u32; sv += hv[j] as u32; } - out.push(if sh > sv { + let wh = (0.5 + (sh as f32 - sv as f32) / (2.0 * BLEND)).clamp(0.0, 1.0); + // a candidate taken alone is copied, and one that isn't finite (beside a float raw's NaN sample) is left out, + // so the other's value doesn't become 0 · NaN + let finite = |p: &[f32; 3]| p.iter().all(|v| v.is_finite()); + out.push(if wh >= 1.0 || !finite(&rv[i]) { rh[i] - } else if sv > sh { + } else if wh <= 0.0 || !finite(&rh[i]) { rv[i] } else { - [(rh[i][0] + rv[i][0]) * 0.5, (rh[i][1] + rv[i][1]) * 0.5, (rh[i][2] + rv[i][2]) * 0.5] + [0, 1, 2].map(|c| rh[i][c] * wh + rv[i][c] * (1.0 - wh)) }); } out diff --git a/crates/raw/src/kelvin_presets.rs b/crates/raw/src/kelvin_presets.rs index 4db0a521eb..58ed396257 100644 --- a/crates/raw/src/kelvin_presets.rs +++ b/crates/raw/src/kelvin_presets.rs @@ -22,6 +22,11 @@ //! - The isotherms are not perpendicular to the curve in these coordinates: an offset also changes mired by //! [`ISOTHERM_TILT`] times the mired the same distance along the curve would. //! +//! Fujifilm X-Trans III bodies (X-T20, X-T2, X-Pro2, X-E3, X-H1, X100F) store no such presets but the camera's own +//! neutral multipliers for Illuminant A and D65 (`0xf00c`, [`KelvinPresets::from_neutral_pair`], tag number from +//! a black-box `exiftool -v3`). The pair gives a two-point line in the same coordinates; mired is linear along it, +//! isotherms are perpendicular to it, and tint is scaled by the CIE locus spacing. No other camera's data is used. +//! //! The two constants come from the 14 Sony bodies that have both measured matrices and the presets (one CC0 //! raw.pixls.us sample each for the presets, a grid of multipliers through `crate::spectral` for the matrices): //! the tilt measured 0.59–0.84 (mean 0.74), the tint spacing 0.90–1.04 of the locus's (mean 0.98, taken as 1). @@ -55,6 +60,11 @@ const MODELS: &[(&str, &str)] = &[ ("CANON", "PowerShot G1 X Mark III"), ]; +/// Fujifilm's X-Trans III bodies, whose raws carry the camera's own neutral multipliers for Illuminant A and D65 +/// (`vendor::raf`, tag `0xf00c`; see [`KelvinPresets::from_neutral_pair`]): checked on the files of each (X-T20, +/// X-T2, X-Pro2, X-E3, X-H1, X100F), the Exif model as Fujifilm writes it. +const FUJI_MODELS: &[&str] = &["X-T20", "X-T2", "X-Pro2", "X-E3", "X-H1", "X100F"]; + /// Whether a raw of this Exif make and model is edited in Kelvin through its presets (when it has no colour /// matrices of its own or measured: see [`crate::spectral::find`], which comes first), from the file's presets or /// built-in ones ([`crate::kelvin_builtin`]). @@ -64,14 +74,16 @@ pub fn covers(make: Option<&str>, model: &str) -> bool { } let model = model.trim(); let brand = make.and_then(|m| m.split_whitespace().next()); - MODELS.iter().any(|(b, m)| { - let bare = model + let bare_of = |b: &str| { + model .get(..b.len()) .zip(model.get(b.len()..)) .filter(|(p, rest)| p.eq_ignore_ascii_case(b) && rest.starts_with(' ')) - .map_or(model, |(_, rest)| rest.trim_start()); - brand.is_none_or(|x| x.eq_ignore_ascii_case(b)) && bare.eq_ignore_ascii_case(m) - }) + .map_or(model, |(_, rest)| rest.trim_start()) + }; + let listed = MODELS.iter().any(|(b, m)| brand.is_none_or(|x| x.eq_ignore_ascii_case(b)) && bare_of(b).eq_ignore_ascii_case(m)); + let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM")) && FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m)); + listed || fuji } /// [`covers`] for make and model joined by a space, as the catalog keeps them (`"SONY ILCA-99M2"`). @@ -88,8 +100,17 @@ const MAX_POINTS: usize = 32; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KelvinPresets { points: Vec<(f32, [f32; 3])>, + /// The camera's neutral multipliers for Illuminant A and D65 when the presets come from such a pair + /// ([`Self::from_neutral_pair`]); the points are then the line between them at five temperatures. + #[serde(default)] + pair: Option<[[f32; 3]; 2]>, } +/// Illuminant A and D65 as chromaticities (CIE). +const A_XY: Xy = Xy::new(0.44757, 0.40745); +const D65_XY: Xy = Xy::new(0.31271, 0.32902); +const POINT_KELVIN: [f32; 5] = [2500.0, 3200.0, 4500.0, 6000.0, 8500.0]; + fn usable(m: [f32; 3]) -> bool { m.iter().all(|v| *v > 0.0 && v.is_finite()) } @@ -113,7 +134,7 @@ impl KelvinPresets { let (a, b) = (log_point(w[0].1), log_point(w[1].1)); w[0].0 < w[1].0 && b[0] > a[0] && b[1] < a[1] }); - ok.then(|| KelvinPresets { points: points.into_iter().map(|(k, m)| (k, [m[0] / m[1], 1.0, m[2] / m[1]])).collect() }) + ok.then(|| KelvinPresets { points: points.into_iter().map(|(k, m)| (k, [m[0] / m[1], 1.0, m[2] / m[1]])).collect(), pair: None }) } /// A curve from presets in any order, as a camera lists them by name (Canon's Daylight, Shade, Cloudy, …): @@ -135,6 +156,51 @@ impl KelvinPresets { KelvinPresets::new(kept) } + /// Presets from a camera's own neutral multipliers (red, green, blue, green = 1) for Illuminant A and D65, as + /// Fujifilm stores them in `WB_GRBLevelsStandard`. Two whites fix the camera's response only on the line + /// between them, and nothing but the colorimetry of the two lights is used to place a white off it: in + /// `(ln R/G, ln B/G)` mired is linear along the line (extended past both ends), the isotherms are taken + /// perpendicular to it (no tilt), and the tint is the Planckian locus's own CIE 1960 spacing per unit length + /// plus the tint the two lights themselves have (A is on the locus, D65 is about +9.5 off it). No other camera's + /// data is involved. `None` for unusable multipliers or two that make no curve. + pub fn from_neutral_pair(a: [f32; 3], d65: [f32; 3]) -> Option { + if !usable(a) || !usable(d65) { + return None; + } + let (a, d65) = ([a[0] / a[1], 1.0, a[2] / a[1]], [d65[0] / d65[1], 1.0, d65[2] / d65[1]]); + let (pa, pd) = (log_point(a), log_point(d65)); + let (ma, md) = (1e6 / cct::xy_to_temp_tint(A_XY).0, 1e6 / cct::xy_to_temp_tint(D65_XY).0); + let points = POINT_KELVIN.map(|k| { + let f = (1e6 / k as f64 - ma) / (md - ma); + let q = [pa[0] + f * (pd[0] - pa[0]), pa[1] + f * (pd[1] - pa[1])]; + (k, [q[0].exp() as f32, 1.0, q[1].exp() as f32]) + }); + let mut out = KelvinPresets::new(points)?; + out.pair = Some([a, d65]); + Some(out) + } + + /// [`Self::temp_tint`] for a neutral pair (see [`Self::from_neutral_pair`]). + fn pair_temp_tint(pair: [[f32; 3]; 2], q: [f64; 2]) -> Option<(f64, f64)> { + let (pa, pd) = (log_point(pair[0]), log_point(pair[1])); + let d = [pd[0] - pa[0], pd[1] - pa[1]]; + let len = d[0].hypot(d[1]); + // only a deserialized pair can repeat a point + if !(len > 0.0 && len.is_finite()) { + return None; + } + let t = [d[0] / len, d[1] / len]; + let n = if t[0] - t[1] < 0.0 { [t[1], -t[0]] } else { [-t[1], t[0]] }; + let r = [q[0] - pa[0], q[1] - pa[1]]; + let along = (r[0] * t[0] + r[1] * t[1]) / len; + let off = r[0] * n[0] + r[1] * n[1]; + let ((ta, tint_a), (td, tint_d)) = (cct::xy_to_temp_tint(A_XY), cct::xy_to_temp_tint(D65_XY)); + let ((u0, v0), (u1, v1)) = (locus_uv(ta), locus_uv(td)); + let tint_per_len = cct::TINT_SCALE * (u1 - u0).hypot(v1 - v0) / len; + let mired = 1e6 / ta + along * (1e6 / td - 1e6 / ta); + Some((1e6 / mired.clamp(1e6 / MAX_K, 1e6 / MIN_K), tint_a + along * (tint_d - tint_a) + tint_per_len * off)) + } + /// Temperature (K) and tint of the white these multipliers balance (see the module docs); `None` for unusable /// multipliers. pub fn temp_tint(&self, wb_multipliers: [f32; 3]) -> Option<(f64, f64)> { @@ -142,6 +208,10 @@ impl KelvinPresets { return None; } let q = log_point(wb_multipliers); + if let Some(pair) = self.pair { + let (t, tint) = Self::pair_temp_tint(pair, q)?; + return Some((t, tint.clamp(-MAX_TINT, MAX_TINT))); + } let last = self.points.len().saturating_sub(2); let mut best: Option<(f64, f64, f64)> = None; for (i, w) in self.points.windows(2).enumerate() { @@ -290,9 +360,52 @@ mod tests { assert_eq!(KelvinPresets::from_unordered([(5000.0, g(1400.0, 1400.0)), (6000.0, g(1500.0, 1300.0))]), None); assert_eq!(KelvinPresets::from_unordered(std::iter::empty()), None); // a stored curve with a repeated point (only deserializing can make one) reads without dividing by zero - let bad = KelvinPresets { points: vec![(5000.0, g(1400.0, 1400.0)); 3] }; + let bad = KelvinPresets { points: vec![(5000.0, g(1400.0, 1400.0)); 3], pair: None }; assert_eq!(bad.temp_tint(g(1400.0, 1400.0)), None); - assert_eq!(KelvinPresets { points: vec![] }.temp_tint(g(1400.0, 1400.0)), None); + assert_eq!(KelvinPresets { points: vec![], pair: None }.temp_tint(g(1400.0, 1400.0)), None); + // and so does a stored neutral pair with equal endpoints + let same = KelvinPresets { points: vec![], pair: Some([[1.0, 1.0, 1.0]; 2]) }; + assert_eq!(same.temp_tint(g(1400.0, 1400.0)), None); + } + + /// An X-T20's stored pair (`302 366 866 17 302 646 498 21`). + fn xt20() -> (KelvinPresets, [f32; 3], [f32; 3]) { + let (a, d) = ([366.0 / 302.0, 1.0, 866.0 / 302.0], [646.0 / 302.0, 1.0, 498.0 / 302.0]); + (KelvinPresets::from_neutral_pair(a, d).unwrap(), a, d) + } + + #[test] + fn a_neutral_pair_reads_back_as_its_own_illuminants() { + let (p, a, d) = xt20(); + let (ta, tint_a) = p.temp_tint(a).unwrap(); + let (td, tint_d) = p.temp_tint(d).unwrap(); + let (want_t, want_tint) = cct::xy_to_temp_tint(D65_XY); + assert!((ta - cct::xy_to_temp_tint(A_XY).0).abs() < 2.0 && (tint_a - cct::xy_to_temp_tint(A_XY).1).abs() < 0.5, "{ta} {tint_a}"); + assert!((td - want_t).abs() < 2.0 && (tint_d - want_tint).abs() < 0.5, "{td} {tint_d}"); + // the points are the same reading at their temperatures, on the locus + for (k, m) in p.points.clone() { + let (t, tint) = p.temp_tint(m).unwrap(); + assert!((t - k as f64).abs() < 2.0 && tint.abs() < 12.0, "{k}: {t} {tint}"); + } + // greener light than the daylight pair: positive tint, as for a matrix camera + let (_, green) = p.temp_tint([d[0] * 1.06, 1.0, d[2] * 1.06]).unwrap(); + let (_, magenta) = p.temp_tint([d[0] / 1.06, 1.0, d[2] / 1.06]).unwrap(); + assert!(green > magenta + 15.0, "{green} {magenta}"); + } + + #[test] + fn unusable_pairs_give_nothing() { + assert_eq!(KelvinPresets::from_neutral_pair([0.0, 1.0, 1.0], [2.0, 1.0, 1.5]), None); + } + + #[test] + fn fujifilm_x_trans_iii_models_are_covered() { + for c in ["FUJIFILM X-T20", "Fujifilm X-T2", "FUJIFILM X100F", "FUJIFILM X-H1", "FUJIFILM X-Pro2", "FUJIFILM X-E3"] { + assert!(covers_camera(c), "{c}"); + } + for c in ["FUJIFILM X-T3", "FUJIFILM X-T30", "SONY X-T20", "FUJIFILM GFX 100"] { + assert!(!covers_camera(c), "{c}"); + } } #[test] diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 2047174da2..2b16c441ad 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -16,12 +16,13 @@ pub enum PreviewColorSpace { /// The colour space the raw says its embedded JPEG is in, for a JPEG that declares none itself (no ICC profile, /// no EXIF), first available first: the Nikon maker-note ColorSpace (0x001e: 1 = sRGB, 2 = Adobe RGB, per Nikon -/// tag documentation); the raw's own EXIF ColorSpace (0xA001: 1 = sRGB), or Uncalibrated (0xFFFF) with the -/// Interoperability IFD's InteropIndex "R03", the DCF option file for Adobe RGB (as a Sony body shot in Adobe RGB -/// writes, issue #778; per the Exif and DCF specifications), not for a DNG. This is a fallback only: a JPEG's own ICC/EXIF colour +/// tag documentation); for a Canon CR2 or CR3, the Canon maker-note ColorSpace (0x00b4: 1 = sRGB, 2 = Adobe RGB); +/// the raw's own EXIF ColorSpace (0xA001: 1 = sRGB), or Uncalibrated (0xFFFF) with the Interoperability IFD's +/// InteropIndex "R03", the DCF option file for Adobe RGB (as a Sony body shot in Adobe RGB writes, issue #778; per +/// the Exif and DCF specifications), not for a DNG. This is a fallback only: a JPEG's own ICC/EXIF colour /// declaration takes precedence. pub fn embedded_preview_color_space(bytes: &[u8]) -> Option { - let tiff = Tiff::parse(bytes).ok()?; + let Ok(tiff) = Tiff::parse(bytes) else { return cr3_color_space(bytes) }; let make = tiff.ifds.first()?.string(t::MAKE).unwrap_or_default(); let exif = tiff.exif()?; if make.to_ascii_uppercase().starts_with("NIKON") @@ -33,6 +34,13 @@ pub fn embedded_preview_color_space(bytes: &[u8]) -> Option { if tiff.ifds.first()?.contains(t::DNG_VERSION) { return None; } + if make.to_ascii_uppercase().starts_with("CANON") + && let Some(e) = exif.get(t::MAKER_NOTE) + && let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make) + && let Some(space) = canon_color_space(&mn.ifd) + { + return Some(space); + } match exif.u16(0xA001)? { 1 => Some(PreviewColorSpace::Srgb), 0xFFFF if exif.interop.as_deref()?.bytes(0x0001)?.starts_with(b"R03") => Some(PreviewColorSpace::AdobeRgb), @@ -40,6 +48,29 @@ pub fn embedded_preview_color_space(bytes: &[u8]) -> Option { } } +/// A CR3 keeps its EXIF and maker note in `CMT2`/`CMT3` TIFF blocks and its JPEGs carry no EXIF; a body shot in +/// Adobe RGB writes ColorSpace Uncalibrated (0xFFFF) with no Interoperability IFD (issue #2654), so the Canon +/// maker note says which, else an EXIF ColorSpace of sRGB is taken. +fn cr3_color_space(bytes: &[u8]) -> Option { + let cr3 = lightcraft_meta::cr3::parse_cr3(bytes)?; + let first = |i: usize| cr3.cmt[i].and_then(|b| Tiff::parse(b).ok()).and_then(|t| t.ifds.into_iter().next()); + if let Some(space) = first(2).and_then(|mn| canon_color_space(&mn)) { + return Some(space); + } + (first(1)?.u16(0xA001)? == 1).then_some(PreviewColorSpace::Srgb) +} + +/// The Canon maker-note ColorSpace (0x00b4: 1 = sRGB, 2 = Adobe RGB, per ExifTool's published Canon tag names). +/// A Canon body shot in Adobe RGB writes EXIF ColorSpace Uncalibrated (0xFFFF) with InteropIndex "R98" in a CR2 +/// and no Interoperability IFD in a CR3, so the EXIF alone does not say Adobe RGB (issue #2654). +fn canon_color_space(note: &Ifd) -> Option { + match note.u16(0x00b4)? { + 1 => Some(PreviewColorSpace::Srgb), + 2 => Some(PreviewColorSpace::AdobeRgb), + _ => None, + } +} + fn nikon_color_space(bytes: &[u8], tiff: &Tiff, exif: &Ifd, make: &str) -> Option { let e = exif.get(t::MAKER_NOTE)?; let mn = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, make)?; @@ -438,10 +469,12 @@ fn cr3_preview_boxes(bytes: &[u8]) -> Option<&[u8]> { let be32 = |at: usize| bytes.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); let (Some(size), Some(len)) = (be32(start), be32(start + 20)) else { continue }; let j = start + 24; - if len < 4 || j + len > start + size.max(24) || j + len > bytes.len() { + // 32-bit box lengths can wrap `usize` on wasm32: check the sums, then slice with `get` + let (Some(end), Some(lim)) = (j.checked_add(len), start.checked_add(size.max(24))) else { continue }; + if len < 4 || end > lim { continue; } - let jpeg = &bytes[j..j + len]; + let Some(jpeg) = bytes.get(j..end) else { continue }; // One that doesn't fit the budget left is skipped; a smaller one later may still fit. if walked + jpeg.len() > CR3_MAX_WALK { continue; diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index 2ee098414f..7eb9b8dc16 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -199,6 +199,20 @@ fn picks_largest_dct_jpeg() { } } +/// #2569: `PRVW` box and JPEG lengths near `u32::MAX` (which wrap `usize` on wasm32) find no preview, never panic. +#[test] +fn cr3_preview_box_huge_lengths_are_rejected() { + let j = fake_jpeg(300); + for (size, len) in [(u32::MAX, u32::MAX), (u32::MAX, u32::MAX - 23), (24 + j.len() as u32, u32::MAX - 3)] { + let mut cr3 = b"\x00\x00\x00\x18ftypcrx \x00\x00\x00\x01crx isom".to_vec(); + cr3.extend_from_slice(&size.to_be_bytes()); + cr3.extend_from_slice(b"PRVW\x00\x00\x00\x00\x00\x01\x06T\x048\x00\x01"); + cr3.extend_from_slice(&len.to_be_bytes()); + cr3.extend_from_slice(&j); + assert_eq!(cr3_preview_boxes(&cr3), None, "size {size:#x}, len {len:#x}"); + } +} + /// A JPEG like [`fake_jpeg`] whose frame header says `w` x `h` with `nc` components. fn sized_jpeg(w: u16, h: u16, nc: u8, n: usize) -> Vec { let mut j = vec![0xff, 0xd8, 0xff, 0xc0, 0x00, 8 + 3 * nc, 8]; @@ -282,6 +296,72 @@ fn cr3_prefers_the_full_size_jpeg_track() { assert_eq!(embedded_preview(&file).unwrap(), small); } +/// A minimal CR3 whose Canon box holds `CMT2` (EXIF ColorSpace `exif`) and `CMT3` (maker-note ColorSpace `note`). +fn cr3_with_color_space(exif: Option, note: Option) -> Vec { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let block = |tag: u16, v: Option| { + let ifd = + v.map_or_else(|| IfdBuilder::new().with(t::ISO_SPEED, Value::Short(vec![100])), |v| IfdBuilder::new().with(tag, Value::Short(vec![v]))); + TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap() + }; + let cmt1 = + TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[IfdBuilder::new().with(t::MAKE, Value::Ascii("Canon".into()))]).unwrap(); + let canon_uuid = [0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48]; + let boxes = [bx(b"CMT1", &cmt1), bx(b"CMT2", &block(0xA001, exif)), bx(b"CMT3", &block(0x00b4, note))].concat(); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &bx(b"uuid", &[&canon_uuid[..], &boxes].concat()))); + file +} + +/// A CR3 (not TIFF-based) says its preview's colour space in the Canon maker note (`CMT3` 0x00b4), else an +/// EXIF ColorSpace of sRGB in `CMT2`: an EOS R shot in Adobe RGB writes Uncalibrated with no interop (issue #2654). +#[test] +fn cr3_preview_colour_space_comes_from_the_canon_maker_note() { + use PreviewColorSpace::{AdobeRgb, Srgb}; + let space = |exif, note| embedded_preview_color_space(&cr3_with_color_space(exif, note)); + assert_eq!(space(Some(0xFFFF), Some(2)), Some(AdobeRgb)); + assert_eq!(space(Some(1), Some(1)), Some(Srgb)); + assert_eq!(space(Some(1), Some(2)), Some(AdobeRgb), "the maker note wins"); + assert_eq!(space(Some(1), None), Some(Srgb), "no maker-note value: the EXIF sRGB"); + assert_eq!(space(Some(0xFFFF), Some(0xFFFF)), None, "neither says"); + assert_eq!(space(Some(0xFFFF), None), None); + assert_eq!(space(None, None), None); + let f = cr3_with_color_space(Some(0xFFFF), Some(2)); + for n in 0..f.len() { + let _ = embedded_preview_color_space(&f[..n]); + } +} + +/// A CR2 shot in Adobe RGB writes EXIF ColorSpace Uncalibrated with InteropIndex "R98", not "R03": the Canon +/// maker note (0x00b4) says Adobe RGB (issue #2654). Another make's note is not read for it. +#[test] +fn cr2_preview_colour_space_comes_from_the_canon_maker_note() { + use PreviewColorSpace::{AdobeRgb, Srgb}; + let cr2 = |make: &str, exif_space: u16, note: Option| { + let mut exif = IfdBuilder::new(); + exif.set(0xA001, Value::Short(vec![exif_space])); + exif.set_child(t::INTEROP_IFD, IfdBuilder::new().with(0x0001, Value::Undefined(b"R98".to_vec()))); + if let Some(v) = note { + // a plain one-entry IFD, its SHORT value inline + let mut mn = 1u16.to_le_bytes().to_vec(); + mn.extend([0x00b4u16.to_le_bytes(), 3u16.to_le_bytes()].concat()); + mn.extend(1u32.to_le_bytes()); + mn.extend([v.to_le_bytes(), [0, 0]].concat()); + mn.extend(0u32.to_le_bytes()); + exif.set(t::MAKER_NOTE, Value::Undefined(mn)); + } + let mut ifd0 = IfdBuilder::new().with(t::MAKE, Value::Ascii(make.into())); + ifd0.set_child(t::EXIF_IFD, exif); + TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[ifd0]).unwrap() + }; + assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, Some(2))), Some(AdobeRgb)); + assert_eq!(embedded_preview_color_space(&cr2("Canon", 1, Some(1))), Some(Srgb)); + assert_eq!(embedded_preview_color_space(&cr2("Canon", 1, None)), Some(Srgb), "no maker note: the EXIF"); + assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, None)), None, "R98 is not Adobe RGB's R03"); + assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, Some(0xFFFF))), None); + assert_eq!(embedded_preview_color_space(&cr2("Leica", 0xFFFF, Some(2))), None, "only a Canon note"); +} + /// A structurally complete DCT JPEG (no real image data): `nc` components, `n` entropy bytes. fn scan_jpeg(nc: u8, n: usize) -> Vec { let mut j = vec![0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00]; diff --git a/crates/raw/src/spectral.rs b/crates/raw/src/spectral.rs index b80442c025..3a3e74262a 100644 --- a/crates/raw/src/spectral.rs +++ b/crates/raw/src/spectral.rs @@ -43,15 +43,17 @@ impl Camera { /// `(make, model as sold, table model)`: bodies sharing a table camera's sensor that rawtoaces-data's alias list /// doesn't name, kept here because the table is generated. Fujifilm's 26.1 MP X-Trans CMOS 4 bodies use the X-T3's -/// sensor (X-T30 issue: a black-and-white Acros camera JPEG gives no colour to fit, and without matrices the photo +/// or X-T4's sensor (X-T30 issue: a black-and-white Acros camera JPEG gives no colour to fit, and without matrices the photo /// opened in the muted neutral fallback). const SAME_SENSOR: &[(&str, &str, &str)] = &[ ("Fujifilm", "X-T30", "X-T3"), ("Fujifilm", "X-T30 II", "X-T3"), ("Fujifilm", "X-Pro3", "X-T3"), ("Fujifilm", "X100V", "X-T3"), - ("Fujifilm", "X-S10", "X-T3"), + ("Fujifilm", "X-S10", "X-T4"), ("Fujifilm", "X-E4", "X-T3"), + ("Fujifilm", "X-S20", "X-T4"), + ("Fujifilm", "X-M5", "X-T3"), ]; /// Model names compared without case, the brand, a leading `EOS` or a trailing `DIGITAL` @@ -164,6 +166,7 @@ mod tests { ("FUJIFILM", "X-T30", "X-T3"), ("FUJIFILM", "X-T30 II", "X-T3"), ("FUJIFILM", "X100V", "X-T3"), + ("FUJIFILM", "X-S20", "X-T4"), ] { assert_eq!(find(Some(make), model).map(|c| c.model), Some(row), "{make} {model}"); } diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index b6a1971ceb..75186d2d3b 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -54,6 +54,14 @@ pub fn check_image(data: &[u8], info: &ImageInfo) -> Result { if chunks.len() < expected { return Err(RawError::Corrupt(format!("{} image data chunks, expected {expected}", chunks.len()))); } + // Tile sizes don't depend on the image size, and every tile is decoded at its nominal size and held until the copy: + // a grid of tiles no larger than the image covers less than twice its width and height, so more than four times + // its samples (or one tile of more than TILE_SAMPLES_FLOOR on a tiny image) is no picture (issue #2554). + let ccpp = if info.planar == 2 { 1 } else { cpp as u64 }; + let nominal = chunks.iter().fold(0u64, |sum, c| sum.saturating_add(u64::from(c.width).saturating_mul(u64::from(c.height)).saturating_mul(ccpp))); + if nominal > (total as u64).saturating_mul(4).max(TILE_SAMPLES_FLOOR) { + return Err(RawError::Limit("image data chunks far larger than the image")); + } // Plausibility bound before allocating: no supported coding stores more than ~2000 samples per byte // (Deflate of constant data is the extreme), so tiny files cannot trigger huge allocations. let available: u64 = chunks.iter().map(|c| chunk_bytes(data, c).map_or(0, |s| s.len() as u64)).sum(); @@ -95,6 +103,9 @@ pub(crate) fn read_image_in(mode: crate::Mode, data: &[u8], info: &ImageInfo, or } } +/// The nominal samples of all chunks [`check_image`] allows whatever the image size: one 2048 × 2048 tile. +const TILE_SAMPLES_FLOOR: u64 = 1 << 22; + /// Decode all chunks of `info` into one buffer of `width × height × cpp` samples. pub fn read_image(data: &[u8], info: &ImageInfo, order: ByteOrder, packing: Packing) -> Result { let (w, h) = (info.width as usize, info.height as usize); @@ -493,8 +504,9 @@ mod lossy_tests { assert!(read_image(&file, &past_end, ByteOrder::Little, Packing::Msb).is_err()); } - /// A small image whose uncompressed tile claims to be enormous (16384 x 16384 nominal, a few bytes of data) is - /// refused before that tile is allocated (issue #1512); an edge tile stored at its full nominal size decodes. + /// A small image whose uncompressed tile claims to be enormous (2048 x 2048 nominal, a few bytes of data) is + /// refused before that tile is allocated (issue #1512); an edge tile stored at its full nominal size decodes. (A + /// tile larger still is refused by `check_image` before any decode: `tiles_far_larger_than_the_image_are_refused`.) #[test] fn a_huge_nominal_uncompressed_tile_with_little_data_is_refused() { let info = |tile: u32, bytes: u64| ImageInfo { @@ -515,7 +527,37 @@ mod lossy_tests { let small = vec![1u8; 2 * 16 * 16]; assert!(read_image(&small, &info(16, small.len() as u64), ByteOrder::Little, Packing::Msb).is_ok()); let data = vec![1u8; 4096]; - assert!(matches!(read_image(&data, &info(16384, data.len() as u64), ByteOrder::Little, Packing::Msb), Err(RawError::Corrupt(_)))); + assert!(matches!(read_image(&data, &info(2048, data.len() as u64), ByteOrder::Little, Packing::Msb), Err(RawError::Corrupt(_)))); + } + + /// A 16 × 16 image whose lossless-JPEG tile claims to be 16384 × 16384 (coded only as tall as the image, so the + /// file is small) is refused before the tile is allocated, by the header check too (issue #2554); a 256 × 256 + /// tile on the same image, as a writer with a fixed tile size stores it, still decodes. + #[test] + fn tiles_far_larger_than_the_image_are_refused() { + let read = |tile: u32, mode: crate::Mode| { + let t = ljpeg::encode(&vec![300u16; tile as usize * 16], tile as usize, 16, 1, 12, 1, 0); + let info = ImageInfo { + width: 16, + height: 16, + bits_per_sample: vec![12], + samples_per_pixel: 1, + compression: comp::JPEG, + photometric: 32803, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Tiles { tile_width: tile, tile_height: tile }, + offsets: vec![0], + byte_counts: vec![t.len() as u64], + }; + read_image_in(mode, &t, &info, ByteOrder::Little, Packing::Msb) + }; + assert_eq!(read(256, crate::Mode::Full), Ok(RawData::U16(vec![300; 16 * 16]))); + for mode in [crate::Mode::Header, crate::Mode::Full] { + assert!(matches!(read(16384, mode), Err(RawError::Limit(_)))); + } } /// A lossless-JPEG tile may be coded only as tall as the part inside the image, never shorter. diff --git a/crates/raw/src/vendor.rs b/crates/raw/src/vendor.rs index b0f65f49e5..1610f20ee5 100644 --- a/crates/raw/src/vendor.rs +++ b/crates/raw/src/vendor.rs @@ -225,9 +225,61 @@ fn solve4(mut a: [[f64; 4]; 4], mut b: [f64; 4]) -> Option<[f64; 4]> { x.iter().all(|v| v.is_finite()).then_some(x) } +/// Test helper: make the single-strip `StripByteCounts` entry (LONG, count 1) that holds `len` declare `declared` +/// bytes instead, as a file cut short or a hostile header does. +#[cfg(test)] +pub(crate) fn declare_strip_len(file: &mut [u8], len: u32, declared: u32) { + let big = file.starts_with(b"MM"); + let entry = |v: u32| -> Vec { + if big { + [&279u16.to_be_bytes()[..], &4u16.to_be_bytes(), &1u32.to_be_bytes(), &v.to_be_bytes()].concat() + } else { + [&279u16.to_le_bytes()[..], &4u16.to_le_bytes(), &1u32.to_le_bytes(), &v.to_le_bytes()].concat() + } + }; + let (old, new) = (entry(len), entry(declared)); + let at: Vec = file.windows(old.len()).enumerate().filter(|(_, w)| *w == old.as_slice()).map(|(i, _)| i).collect(); + assert_eq!(at.len(), 1, "one StripByteCounts entry of {len} bytes"); + file[at[0]..at[0] + new.len()].copy_from_slice(&new); +} + #[cfg(test)] mod tests { use super::*; + use lightcraft_tiff::tags as t; + + /// `file`, whose image IFD holds one strip, as two strips at the same offset whose StripByteCounts are LONG8 (which + /// classic TIFF readers accept) `[u64::MAX, 1]`: their sum is past `u64::MAX`. + pub(super) fn huge_strip_counts(mut file: Vec) -> Vec { + let tiff = Tiff::parse(&file).unwrap(); + let o = tiff.order; + let ifd = tiff.all_ifds().into_iter().find(|i| i.contains(t::STRIP_OFFSETS)).unwrap(); + let (base, rows, offset) = (ifd.offset as usize, ifd.u32(t::IMAGE_LENGTH).unwrap(), ifd.u32(t::STRIP_OFFSETS).unwrap()); + assert!(rows >= 2); + let at = file.len() as u32; + // appended: the two strip offsets (LONG), then the two byte counts (LONG8) + let mut tail = Vec::new(); + o.put_u32(&mut tail, offset); + o.put_u32(&mut tail, offset); + o.put_u64(&mut tail, u64::MAX); + o.put_u64(&mut tail, 1); + for i in 0..usize::from(o.read_u16(&file, base).unwrap()) { + let e = base + 2 + 12 * i; + let (ty, count, value) = match o.read_u16(&file, e).unwrap() { + t::STRIP_OFFSETS => (4u16, 2u32, at), + t::ROWS_PER_STRIP => (4, 1, rows.div_ceil(2)), + t::STRIP_BYTE_COUNTS => (16, 2, at + 8), + _ => continue, + }; + let mut entry = Vec::new(); + o.put_u16(&mut entry, ty); + o.put_u32(&mut entry, count); + o.put_u32(&mut entry, value); + file[e + 2..e + 12].copy_from_slice(&entry); + } + file.extend_from_slice(&tail); + file + } #[test] fn black_columns_by_parity() { diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index 3938fa50dd..b1a9983caa 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -628,7 +628,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let bits = info.bits() as u32; let linear_rgb = info.compression == 7 && info.photometric == photometric::YCBCR; let chunks = info.chunks(bytes.len() as u64); - let strip_len: u64 = chunks.iter().map(|c| c.len).sum(); + let strip_len = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)); // The row-per-w-bytes (ARW2) layout stores exactly one byte per pixel in a single strip; all 108 such files in the test // archive measure exactly width x height. A200/A230/A350 files carry a strip 4-23 % larger than that (and A290/A390 one // smaller), which is a different packing, so they are refused rather than read with the wrong layout. @@ -642,6 +642,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } 32767 if one_byte_per_sample => { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; + if src.len() as u64 != strip_len { + return Err(RawError::Corrupt("raw strip shorter than its rows".into())); + } let curve = code_curve(&raw.u64s(TONE_CURVE).unwrap_or_else(|| vec![8000, 10400, 12900, 14100])); let mut data = vec![0u16; samples as usize]; data.par_chunks_mut(w).enumerate().for_each(|(y, out)| { @@ -659,6 +662,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } 32767 if packed12 => { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; + if src.len() as u64 != strip_len { + return Err(RawError::Corrupt("raw strip shorter than its rows".into())); + } let row_bytes = w / 2 * 3; let mut data = vec![0u16; samples as usize]; data.par_chunks_mut(w).enumerate().for_each(|(y, out)| { @@ -900,6 +906,15 @@ mod tests { TiffWriter::default().write(&[raw]).unwrap() } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. + #[test] + fn strip_byte_counts_past_u64_max_do_not_overflow() { + let file = crate::vendor::tests::huge_strip_counts(arw_with_strip(32 * 4)); + for mode in [Mode::Header, Mode::Full] { + let _ = super::decode(&file, mode); + } + } + /// The ILCE-7RM6's distortion table reaches `OpcodeList3`, in the headers-only probe and in the full decode, as /// one plane, also with a CA table (lateral CA is off by default); another body's tables don't (see /// [`super::super::arw_lens_rm6`]). @@ -1561,4 +1576,28 @@ mod tests { assert!(is_quad_tiled(&file, &info)); assert_eq!(read_quad_tiles(&file, &info).unwrap(), mosaic); } + + /// #2561: a small file whose one-byte or packed 12-bit strip declares a large frame is refused before the full + /// decode allocates the frame. + #[test] + fn a_strip_cut_short_is_refused_before_allocating() { + use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + let (w, h) = (3000u32, 2000u32); + for declared in [w * h, w * h / 2 * 3] { + let mut raw = IfdBuilder::new(); + raw.set(t::MAKE, Value::Ascii("SONY".into())); + raw.set(t::MODEL, Value::Ascii("DSLR-A100".into())); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); + raw.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); + raw.set(t::COMPRESSION, Value::Short(vec![32767])); + raw.set(TONE_CURVE, Value::Short(vec![8000, 10400, 12900, 14100])); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![vec![0u8; 12]] }); + let mut f = TiffWriter::default().write(&[raw]).unwrap(); + crate::vendor::declare_strip_len(&mut f, 12, declared); + assert!(matches!(decode(&f, Mode::Full), Err(RawError::Corrupt(_))), "{declared} bytes declared"); + } + } } diff --git a/crates/raw/src/vendor/arw_lens_rm6.rs b/crates/raw/src/vendor/arw_lens_rm6.rs index cc3a23e612..1130abc6d7 100644 --- a/crates/raw/src/vendor/arw_lens_rm6.rs +++ b/crates/raw/src/vendor/arw_lens_rm6.rs @@ -23,7 +23,7 @@ //! crop and reads only inside it: the largest `S(ρ/z)/ρ` over the crop border radii `ρ` is 1. 0.596 px over the 34 //! measurable corrected photos (budget 0.75 px; corners and edge midpoints 0.570 px). //! - `WarpRectilinear`'s 4-term odd polynomial fits that map within 2.35·10⁻⁴ of the DNG radius (0.220 px) on every -//! photo, at its 65 fit samples. A table it fits worse than 0.25 px at the samples the crop shows is refused (the +//! photo, at its 65 fit samples. A table it fits worse than 0.25 px (0.5 px on an APS-C body) at the samples the crop shows is refused (the //! photo stays uncorrected rather than wrongly warped). Between samples the error is somewhat larger: 0.071 against //! 0.049 px for the full-frame 16–35 mm example in the tests. //! - vignetting: read but never applied. The camera JPEGs keep the uncorrected render's radial falloff (median @@ -37,10 +37,12 @@ //! them on in code, pass `true` there. When on, a CA value beyond [`CA_MAX_RELATIVE`] or a colour plane that fails //! the fit gate above drops both colour planes, and G alone is applied to all three channels. //! -//! The correction is produced whatever the in-camera flag says. Only bodies listed in [`FULL_FRAME_CROP`] get it: the -//! unit and the knot spacing are verified on the ILCE-7RM6 alone. Another body is added by repeating the measurement -//! on its photos shot with distortion correction on and listing its full-frame default crop. The method and the -//! numbers: docs/sony-ilce7rm6-lens-corrections.md. +//! The correction is produced whatever the in-camera flag says. Only bodies listed in [`FULL_FRAME_CROP`] or +//! [`APSC_BODIES`] get it: the unit and the knot spacing are verified on the ILCE-7RM6 and, for distortion, on the +//! ILCE-6700 (APS-C, 11 knots spanning its own crop, the same unit 15000: 0.73 px worst over 27 photos with three +//! lenses as rendered, 1.38 px at the 10–18 mm's 10 mm end). Another body is added by repeating the measurement on its photos shot +//! with distortion correction on and listing its full-frame default crop (or, for an APS-C body, its model). The method +//! and the numbers: docs/sony-ilce7rm6-lens-corrections.md. use super::fit_radial_warp; use crate::opcodes::max_radius; @@ -57,6 +59,9 @@ pub(crate) const CA_FLAG: u16 = 0x7034; /// The bodies whose tables are verified (Exif `Model`), with their full-frame default crop (width, height) in px. const FULL_FRAME_CROP: &[(&str, (f64, f64))] = &[("ILCE-7RM6", (9984.0, 6656.0))]; +/// The verified APS-C bodies (Exif `Model`): their knots span the file's own default crop, the last knot at its corner. +/// Measured on the ILCE-6700 (docs/sony-ilce7rm6-lens-corrections.md → ILCE-6700). +const APSC_BODIES: &[&str] = &["ILCE-6700"]; /// The distortion table's value of 1 (relative radius); a global least-squares fit over the 34 photos gives 15000.7. const DISTORTION_UNIT: f64 = 15000.0; /// The CA table's value of 1 (relative to the green source radius). Provisional: the median best unit of the 20 @@ -70,6 +75,10 @@ const CA_MAX_RELATIVE: f64 = 2e-3; const ZOOM_SCAN: usize = 4096; /// Largest polynomial fit error accepted at the fit samples the crop shows, px at a 1440 px long edge. const FIT_ERROR_PX_AT_1440: f64 = 0.25; +/// The fit gate of [`APSC_BODIES`]: their 11 knots over a smaller crop bend more sharply than the polynomial follows +/// (worst 0.44 px over the 30 measured ILCE-6700 tables; 13 of them exceed 0.25 px), while the fitted polynomial +/// matches the camera JPEG as well as the exact table (p95 0.22–0.73 px against 0.23–0.68 px, 10 mm aside). +const APSC_FIT_ERROR_PX_AT_1440: f64 = 0.5; /// A file's lens tables: the first `count` values of each (CA: red, blue); `None` when absent or malformed. /// `vignetting` and `flags` are parsed for the tests and the docs only: don't build an opcode from them (the camera @@ -106,10 +115,19 @@ pub(crate) fn read_tables(raw: &Ifd) -> LensTables { } } -/// The knot spacing (px) of a verified body: its full-frame default-crop half diagonal / 15. -fn knot_spacing(model: &str) -> Option { +/// The knot spacing (px) of a verified body: a full-frame body's full-frame default-crop half diagonal / 15 (fixed on +/// the sensor, so in its APS-C crop mode too); an APS-C body's default-crop `crop` half diagonal / (`knots` − 1). Both +/// put the last knot at the corner of the crop the table was written for (the ILCE-7RM6's APS-C mode, 11 knots, gives +/// 392 px that way, which fits its files as well as the sensor-fixed 400 px). `None` for an unverified body, or an +/// APS-C body with fewer than two knots or a crop that isn't 3:2 (the only shape measured; empty crops included). +fn knot_spacing(model: &str, knots: usize, crop: Rect) -> Option { let model = model.trim(); - FULL_FRAME_CROP.iter().find(|(m, _)| *m == model).map(|&(_, (w, h))| w.hypot(h) / 30.0) + if let Some(&(_, (w, h))) = FULL_FRAME_CROP.iter().find(|(m, _)| *m == model) { + return Some(w.hypot(h) / 30.0); + } + let gaps = knots.checked_sub(1).filter(|&n| n > 0)?; + let half_diagonal = (crop.width as f64).hypot(crop.height as f64) / 2.0; + (APSC_BODIES.contains(&model) && super::arw_lens::is_3_2(crop)).then(|| half_diagonal / gaps as f64) } /// The knot table at radius `r` px: knot `i` at `i · spacing`, linear in between, the last segment extended beyond @@ -161,6 +179,11 @@ fn fill_zoom(source: &dyn Fn(f64) -> f64, x: f64, y: f64) -> Option { /// worse than 0.25 px at a 1440 px long edge at one of the fit samples within the crop (a padded active area, as in /// lossless files, reaches radii that are never shown). pub(crate) fn warp_opcode(t: &LensTables, knot_spacing: f64, active: Rect, crop: Rect, lateral_ca: bool) -> Option { + gated_warp_opcode(t, knot_spacing, active, crop, lateral_ca, FIT_ERROR_PX_AT_1440) +} + +/// [`warp_opcode`] with the fit gate `fit_error_px` (px at a 1440 px long edge) instead of 0.25 px. +fn gated_warp_opcode(t: &LensTables, knot_spacing: f64, active: Rect, crop: Rect, lateral_ca: bool, fit_error_px: f64) -> Option { let v = t.distortion.as_deref().filter(|v| v.iter().any(|&x| x != 0.0))?; let (aw, ah) = (active.width as f64, active.height as f64); if aw < 2.0 || ah < 2.0 || crop.width == 0 || crop.height == 0 { @@ -172,7 +195,7 @@ pub(crate) fn warp_opcode(t: &LensTables, knot_spacing: f64, active: Rect, crop: // DNG's normalisation: pixel-index units, radius 1 = the farthest active-area corner let (cx, cy) = (crop.x as f64 + (cw - 1.0) / 2.0, crop.y as f64 + (ch - 1.0) / 2.0); let m = max_radius(cx, cy, aw - 1.0, ah - 1.0); - let max_fit_error = FIT_ERROR_PX_AT_1440 * (cw.max(ch) / 1440.0) / m; + let max_fit_error = fit_error_px * (cw.max(ch) / 1440.0) / m; let shown = (cw / 2.0).hypot(ch / 2.0) / m; // output radius (px) → green source radius let green = |r: f64| source(r / z); @@ -204,8 +227,15 @@ pub(crate) fn warp_opcode(t: &LensTables, knot_spacing: f64, active: Rect, crop: /// CA went from rms 0.032 / max 0.125 px (off) to 0.052 / 0.219 px (on) at a 1440 px long edge; only the 16–35 mm /// improved. Follow-up: warp the CFA colour planes before demosaic, then turn the planes on here. pub(crate) fn lens_opcodes(raw: &Ifd, model: &str, active: Rect, crop: Rect) -> Vec { - let Some(spacing) = knot_spacing(model) else { return Vec::new() }; - warp_opcode(&read_tables(raw), spacing, active, crop, false).into_iter().collect() + let tables = read_tables(raw); + let knots = tables.distortion.as_ref().map_or(0, Vec::len); + let Some(spacing) = knot_spacing(model, knots, crop) else { return Vec::new() }; + let op = if APSC_BODIES.contains(&model.trim()) { + gated_warp_opcode(&tables, spacing, active, crop, false, APSC_FIT_ERROR_PX_AT_1440) + } else { + warp_opcode(&tables, spacing, active, crop, false) + }; + op.into_iter().collect() } #[cfg(test)] @@ -253,7 +283,7 @@ mod tests { const APSC_B: [f64; 4] = [1.016155702, -0.06162477627, 0.02753315326, -0.005554915901]; fn knots() -> f64 { - knot_spacing("ILCE-7RM6").unwrap() + knot_spacing("ILCE-7RM6", 16, FF_CROP).unwrap() } fn ifd(tags: Vec<(u16, Value)>) -> Ifd { @@ -525,6 +555,49 @@ mod tests { assert!(matches!(op, Some(Opcode::WarpRectilinear { .. })), "{op:?}"); } + /// An ILCE-6700 file (Sigma 10–18 mm at 10 mm): 11 knots, the strongest table of the measured set. + const A6700_DISTORTION: [i16; 17] = [11, 90, 11, -90, -205, -345, -500, -676, -852, -1031, -1190, -1333, -1333, -1333, -1333, -1333, -1333]; + const A6700_CROP: Rect = Rect { x: 0, y: 0, width: 6192, height: 4128 }; + /// An ILCE-6700 file (Tamron 17–70 mm at 32 mm), on the decoded geometry: the polynomial fits it within 0.44 px. + const A6700_32MM_DISTORTION: [i16; 17] = [11, 7, 0, 7, 29, 58, 101, 158, 230, 323, 446, 611, 611, 611, 611, 611, 611]; + const A6700_ACTIVE: Rect = Rect { x: 0, y: 0, width: 6656, height: 4608 }; + const A6700_DECODED_CROP: Rect = Rect { x: 26, y: 20, width: 6192, height: 4128 }; + + #[test] + fn apsc_body_knots_span_its_own_crop() { + // half diagonal 3720.9 px / 10 + let s = knot_spacing("ILCE-6700", 11, A6700_CROP).unwrap(); + assert!((s - 372.0929).abs() < 1e-3, "{s}"); + // the full-frame body keeps its sensor-fixed spacing whatever the crop and count + assert_eq!(knot_spacing("ILCE-7RM6", 11, APSC_CROP), knot_spacing("ILCE-7RM6", 16, FF_CROP)); + // degenerate counts and crops give no spacing instead of a division by zero + assert_eq!(knot_spacing("ILCE-6700", 1, A6700_CROP), None); + assert_eq!(knot_spacing("ILCE-6700", 0, A6700_CROP), None); + assert_eq!(knot_spacing("ILCE-6700", 11, Rect { x: 0, y: 0, width: 0, height: 0 }), None); + // the spacing comes from the crop, so a crop of another shape than the measured 3:2 gets no correction + let square = Rect { width: A6700_CROP.height, ..A6700_CROP }; + assert_eq!(knot_spacing("ILCE-6700", 11, square), None); + let ifd = sony_lens_ifd(&A6700_DISTORTION, &APSC_VIGNETTING, &APSC_CA, [1, 2, 1]); + let ops = lens_opcodes(&ifd, "ILCE-6700", A6700_CROP, A6700_CROP); + let gated = gated_warp_opcode(&read_tables(&ifd), s, A6700_CROP, A6700_CROP, false, APSC_FIT_ERROR_PX_AT_1440); + assert_eq!(ops, gated.into_iter().collect::>()); + assert_eq!(ops.len(), 1); + // other APS-C bodies stay unverified + assert!(lens_opcodes(&ifd, "ILCE-6600", A6700_CROP, A6700_CROP).is_empty()); + } + + /// The APS-C fit gate: a table the polynomial fits within 0.44 px is applied on the ILCE-6700, while the + /// full-frame 0.25 px gate refuses it. + #[test] + fn apsc_body_uses_its_wider_fit_gate() { + let ifd = sony_lens_ifd(&A6700_32MM_DISTORTION, &APSC_VIGNETTING, &APSC_CA, [1, 2, 1]); + let t = read_tables(&ifd); + let s = knot_spacing("ILCE-6700", 11, A6700_DECODED_CROP).unwrap(); + assert_eq!(warp_opcode(&t, s, A6700_ACTIVE, A6700_DECODED_CROP, false), None); + let ops = lens_opcodes(&ifd, "ILCE-6700", A6700_ACTIVE, A6700_DECODED_CROP); + assert!(matches!(ops.as_slice(), [Opcode::WarpRectilinear { planes, .. }] if planes.len() == 1), "{ops:?}"); + } + #[test] fn unknown_model_gets_no_opcodes() { let ifd = sony_lens_ifd(&FF_DISTORTION, &FF_VIGNETTING, &FF_CA, [0, 2, 1]); diff --git a/crates/raw/src/vendor/orf.rs b/crates/raw/src/vendor/orf.rs index 92caeec265..172f83013b 100644 --- a/crates/raw/src/vendor/orf.rs +++ b/crates/raw/src/vendor/orf.rs @@ -206,7 +206,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let (w, h) = (info.width as usize, info.height as usize); let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; let chunks = info.chunks(bytes.len() as u64); - let total: u64 = chunks.iter().map(|c| c.len).sum(); + let total = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)); let stated = cfa_from_exif(&tiff); let mut two_field = false; let (mut data, bits) = if info.compression != 1 { @@ -394,6 +394,15 @@ mod tests { b } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. + #[test] + fn strip_byte_counts_past_u64_max_do_not_overflow() { + let file = crate::vendor::tests::huge_strip_counts(orf(4, 2, 16, vec![0; 16])); + for mode in [Mode::Header, Mode::Full] { + let _ = super::decode(&file, mode); + } + } + /// An old-style little-endian Olympus maker note (`OLYMP\0`, version 1, then the IFD) of SHORT (type 3) or /// UNDEFINED (type 7) entries. Values longer than four bytes follow the IFD; their offsets count from the TIFF /// header, so `at` is where the note sits in the file. diff --git a/crates/raw/src/vendor/pef.rs b/crates/raw/src/vendor/pef.rs index 9b7d92bc7e..45efeec685 100644 --- a/crates/raw/src/vendor/pef.rs +++ b/crates/raw/src/vendor/pef.rs @@ -267,14 +267,14 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let chunks = info.chunks(bytes.len() as u64); let first = chunks.first().ok_or_else(|| RawError::Corrupt("PEF without image data".into()))?; let mut c = *first; - c.len = chunks.iter().map(|c| c.len).sum::().max(first.len); + c.len = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)).max(first.len); let src = chunk_bytes(bytes, &c) .or_else(|| bytes.get(first.offset as usize..)) .ok_or_else(|| RawError::Corrupt("PEF data outside file".into()))?; if read == Mode::Full { RawData::U16(decode_huffman(src, &huff, w, hgt, bits)?) } else { RawData::U16(Vec::new()) } } 1 => { - let strip: u64 = info.chunks(bytes.len() as u64).iter().map(|c| c.len).sum(); + let strip = info.chunks(bytes.len() as u64).iter().fold(0u64, |a, c| a.saturating_add(c.len)); let packing = if strip >= (w * hgt * 2) as u64 { Packing::Word16 } else { Packing::Msb }; read_image_in(read, bytes, &info, tiff.order, packing)? } @@ -707,4 +707,16 @@ mod tests { let file = pef_with_black_point(w, h, 64, |x, y| 64 + ((x * 7 + y * 13) % 5) as u16); assert_eq!(decode(&file, Mode::Full).unwrap().active_area, Rect::new(0, 0, w, h)); } + + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow, + /// for the Huffman-coded and the uncompressed samples. + #[test] + fn strip_byte_counts_past_u64_max_do_not_overflow() { + for compression in [65535u16, 1] { + let file = crate::vendor::tests::huge_strip_counts(pef_with_pattern(compression, [0, 1, 1, 2])); + for mode in [Mode::Header, Mode::Full] { + let _ = decode(&file, mode); + } + } + } } diff --git a/crates/raw/src/vendor/raf.rs b/crates/raw/src/vendor/raf.rs index 42ed29ce82..b60a742660 100644 --- a/crates/raw/src/vendor/raf.rs +++ b/crates/raw/src/vendor/raf.rs @@ -118,6 +118,19 @@ pub(crate) fn unpack_row(src: &[u8], bits: u32, words32: bool, out: &mut [u16]) } } +/// The Kelvin scale of a body without colour matrices, from tag `0xf00c` (`WB_GRBLevelsStandard`; tag number from +/// `exiftool -v3` run as a black-box tool on the files): `G R B 17 G R B 21`, the camera's own neutral multipliers +/// for Illuminant A and D65 (see [`crate::kelvin_presets::KelvinPresets::from_neutral_pair`]). +fn fuji_kelvin_presets(ifd: &Ifd) -> Option { + let v = ifd.f64s(0xf00c).filter(|v| v.len() >= 8)?; + let grb = |at: usize, code: f64| { + (v[at + 3] == code && v[at] > 0.0 && v[at + 1] > 0.0 && v[at + 2] > 0.0) + .then(|| [(v[at + 1] / v[at]) as f32, 1.0, (v[at + 2] / v[at]) as f32]) + }; + let (a, d65) = (grb(0, 17.0)?, grb(4, 21.0)?); + crate::kelvin_presets::KelvinPresets::from_neutral_pair(a, d65) +} + pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let h = header(bytes)?; let raw = h.raw.ok_or_else(|| RawError::Corrupt("RAF without raw data".into()))?; @@ -191,6 +204,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let wb = ifd.f64s(0xf00e).filter(|v| v.len() >= 3 && v.iter().take(3).all(|x| *x > 0.0)).map(|v| [(v[1] / v[0]) as f32, 1.0, (v[2] / v[0]) as f32]); let white = white_from_data(&data, bits); + let kelvin_presets = fuji_kelvin_presets(&ifd); let mut metadata = h.jpeg.map(lightcraft_meta::extract).unwrap_or_default(); metadata.width = Some(active.width as u32); @@ -209,7 +223,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { active_area: active, crop: Rect::new(0, 0, active.width, active.height), orientation, - color: ColorData::default(), + color: ColorData { kelvin_presets, ..Default::default() }, wb_multipliers: wb, linearized: false, pixel_aspect: 1.0, diff --git a/crates/raw/src/vendor/raf_lens.rs b/crates/raw/src/vendor/raf_lens.rs index a976751d26..283a3d0ea3 100644 --- a/crates/raw/src/vendor/raf_lens.rs +++ b/crates/raw/src/vendor/raf_lens.rs @@ -15,7 +15,7 @@ //! - distortion: percent, the bracket `1 + D/100` multiplies the radius; the camera's JPEG samples the raw at //! `source = z · r · (1 + D(source)/100)`, radii in half diagonals, with the zoom `z` that keeps the output //! rectangle inside the source (`1 / max` of the bracket over the frame's border radii). -//! - vignetting: relative illumination in percent at the source radius; the correction is the gain `100 / V`. +//! - vignette: relative illumination in percent at the source radius; the correction is the gain `100 / V`. use crate::{Opcode, Rect}; use lightcraft_tiff::Ifd; @@ -34,6 +34,14 @@ const FIT_ROUNDS: usize = 40; /// understood). const SCALE_TOLERANCE: f64 = 0.005; +/// Dimensions and half diagonals of the 26.1 MP (`6240 × 4160`) and 40 MP (`7728 × 5152`) active areas in pixels. +/// The X-S20 writes `scale × n = 4643` (the 40 MP half diagonal) on its uncropped 26.1 MP frame (`3749` px +/// half diagonal), while indexing the 9 knots `√(k/8)` over the 26.1 MP active area. +const XTRANS4_26MP_WIDTH: usize = 6240; +const XTRANS4_26MP_HEIGHT: usize = 4160; +const XTRANS4_26MP_HALF_DIAGONAL: f64 = 3749.0; +const XTRANS5_40MP_HALF_DIAGONAL: f64 = 4643.0; + /// Camera models whose tables were checked against the camera's own JPEG (distortion within 0.01 of the best free /// radial fit's correlation on at least one lens, see docs/fuji-lens-corrections.md). Other bodies stay uncorrected. /// The nine-knot bodies other than the X-T4 were checked with their tables read at `knot_last · r`; the plain radius @@ -106,9 +114,22 @@ struct Table { values: Vec, } +/// Whether `scale × n` matches the recorded image's `half_diagonal` (or, on an uncropped 26.1 MP X-S20 frame, +/// the 40 MP reference half diagonal that its firmware writes). +fn scale_matches(model: &str, scale_times_n: f64, half_diagonal: f64, w: usize, h: usize) -> bool { + if (scale_times_n / half_diagonal - 1.0).abs() <= SCALE_TOLERANCE { + return true; + } + model == "X-S20" + && w == XTRANS4_26MP_WIDTH + && h == XTRANS4_26MP_HEIGHT + && (half_diagonal / XTRANS4_26MP_HALF_DIAGONAL - 1.0).abs() <= SCALE_TOLERANCE + && (scale_times_n / XTRANS5_40MP_HALF_DIAGONAL - 1.0).abs() <= SCALE_TOLERANCE +} + /// Read and sanity-check a table. `half_diagonal` is the recorded image's half diagonal in pixels, which /// `scale × n` must reproduce. -fn read(ifd: &Ifd, tag: u16, half_diagonal: f64) -> Option { +fn read(model: &str, ifd: &Ifd, tag: u16, half_diagonal: f64, w: usize, h: usize) -> Option
{ let v = ifd.f64s(tag)?; if v.is_empty() || v.iter().any(|x| !x.is_finite()) { return None; @@ -118,7 +139,7 @@ fn read(ifd: &Ifd, tag: u16, half_diagonal: f64) -> Option
{ return None; } let scale = v[0]; - if scale <= 0.0 || (scale * n as f64 / half_diagonal - 1.0).abs() > SCALE_TOLERANCE { + if scale <= 0.0 || !scale_matches(model, scale * n as f64, half_diagonal, w, h) { return None; } let knots = v[1..1 + n].to_vec(); @@ -261,9 +282,9 @@ fn solve(mut a: [[f64; N]; N], mut b: [f64; N]) -> Option<[f64; } /// The warp (distortion with the frame-filling zoom) for a recorded image of `w × h` pixels. -fn warp(ifd: &Ifd, w: usize, h: usize) -> Option { +fn warp(model: &str, ifd: &Ifd, w: usize, h: usize) -> Option { let half = (w as f64).hypot(h as f64) / 2.0; - let table = read(ifd, DISTORTION, half)?; + let table = read(model, ifd, DISTORTION, half, w, h)?; // Percent: anything beyond a third is not distortion; an all-zero table has nothing to correct. if table.values.iter().any(|d| d.abs() > 30.0) || table.values.iter().all(|d| *d == 0.0) { return None; @@ -278,9 +299,9 @@ fn warp(ifd: &Ifd, w: usize, h: usize) -> Option { } /// Radial illumination gain `100 / V` as DNG `FixVignetteRadial` (`1 + k0 r² + … + k4 r¹⁰`). -fn vignette(ifd: &Ifd, w: usize, h: usize) -> Option { +fn vignette(model: &str, ifd: &Ifd, w: usize, h: usize) -> Option { let half = (w as f64).hypot(h as f64) / 2.0; - let t = read(ifd, VIGNETTING, half)?; + let t = read(model, ifd, VIGNETTING, half, w, h)?; if t.values.iter().any(|v| !(10.0..=130.0).contains(v)) { return None; } @@ -303,10 +324,11 @@ fn vignette(ifd: &Ifd, w: usize, h: usize) -> Option { /// The lens corrections of a RAF whose camera `model` was validated (anything else, and any table that is not in /// the understood layout and scale, is left uncorrected). `active` is the recorded image (the raw crop). pub(super) fn corrections(model: &str, raw: &Ifd, active: Rect) -> Vec { - if !VALIDATED.contains(&model.trim()) || active.width < 2 || active.height < 2 { + let model = model.trim(); + if !VALIDATED.contains(&model) || active.width < 2 || active.height < 2 { return Vec::new(); } - warp(raw, active.width, active.height).into_iter().chain(vignette(raw, active.width, active.height)).collect() + warp(model, raw, active.width, active.height).into_iter().chain(vignette(model, raw, active.width, active.height)).collect() } #[cfg(test)] @@ -401,8 +423,20 @@ mod tests { fn rejects_unknown_scale_layout_and_values() { let scale = 3749.0 / 9.0; let bad = |ifd: Ifd| corrections("X-T4", &ifd, XT4_AREA); - // another normalisation (X-S20 stores the 40 MP half diagonal), non-increasing knots, wrong lengths, garbage + // another normalisation (ignoring camera exceptions like the X-S20 which writes the 40 MP half diagonal), non-increasing knots, wrong lengths, garbage assert!(bad(only(DISTORTION, table(4643.0 / 9.0, &KNOTS9, &XT4_DIST))).is_empty()); + // X-S20 accepts the 40 MP normalization on its uncropped 26 MP sensor, but rejects in-camera crops + let xs20_ops = corrections("X-S20", &only(DISTORTION, table(4643.0 / 9.0, &KNOTS9, &XT4_DIST)), XT4_AREA); + assert!(matches!(xs20_ops.as_slice(), [Opcode::WarpRectilinear { .. }]), "{xs20_ops:?}"); + // Nonzero active-frame offsets are permitted as long as dimensions are 6240 × 4160 + let offset_area = Rect::new(32, 20, 6240, 4160); + let xs20_offset_ops = corrections("X-S20", &only(DISTORTION, table(4643.0 / 9.0, &KNOTS9, &XT4_DIST)), offset_area); + assert!(matches!(xs20_offset_ops.as_slice(), [Opcode::WarpRectilinear { .. }]), "{xs20_offset_ops:?}"); + let cropped = Rect::new(0, 0, 4992, 3328); + assert!(corrections("X-S20", &only(DISTORTION, table(4643.0 / 9.0, &KNOTS9, &XT4_DIST)), cropped).is_empty()); + // Differing active dimensions are rejected even if hypothetically close in half-diagonal + let wrong_dim = Rect::new(0, 0, 6242, 4157); + assert!(corrections("X-S20", &only(DISTORTION, table(4643.0 / 9.0, &KNOTS9, &XT4_DIST)), wrong_dim).is_empty()); let mut flat = KNOTS9; flat[3] = flat[2]; assert!(bad(only(DISTORTION, table(scale, &flat, &XT4_DIST))).is_empty()); @@ -447,6 +481,27 @@ mod tests { assert!((at_edge - planes[0][0]).abs() < 0.004); } + #[test] + fn xs20_40mp_scale_table_produces_warp_and_vignette() { + let scale = 4643.0 / 9.0; + let ifd = Ifd { + entries: vec![ + Entry { tag: DISTORTION, value: table(scale, &KNOTS9, &XT4_DIST), offset: 0 }, + Entry { tag: VIGNETTING, value: table(scale, &KNOTS9, &XT4_VIG), offset: 0 }, + ], + ..Default::default() + }; + // X-S20 on its uncropped 26 MP sensor emits both WarpRectilinear and FixVignetteRadial + let ops = corrections("X-S20", &ifd, XT4_AREA); + let [Opcode::WarpRectilinear { planes, center: wc }, Opcode::FixVignetteRadial { k, center: vc }] = ops.as_slice() else { + panic!("expected warp and vignette for X-S20: {ops:?}"); + }; + assert_eq!((*wc, *vc), ([0.5, 0.5], [0.5, 0.5])); + assert_eq!(planes.len(), 1); + assert!((planes[0][0] - 1.03).abs() < 0.02); + assert!((k[0]).abs() > 0.0); + } + #[test] fn a_vignette_table_works_without_a_distortion_table() { let scale = 3749.0 / 9.0; diff --git a/crates/raw/src/vendor/rafc.rs b/crates/raw/src/vendor/rafc.rs index f3b925b512..fd08f9869e 100644 --- a/crates/raw/src/vendor/rafc.rs +++ b/crates/raw/src/vendor/rafc.rs @@ -114,26 +114,57 @@ impl<'a> Bits<'a> { Self { src, pos: 0, acc: 0, available: 0 } } + /// Tops the accumulator up to at least 57 bits, or to every remaining byte near the end of the stream. #[inline] - fn get(&mut self, n: u32) -> Result { - while self.available < n { - let b = self.src.get(self.pos).copied().ok_or_else(|| corrupt("truncated entropy stream"))?; + fn refill(&mut self) { + while self.available <= 56 { + let Some(&b) = self.src.get(self.pos) else { return }; self.pos += 1; self.acc = (self.acc << 8) | u64::from(b); self.available += 8; } + } + + #[inline] + fn get(&mut self, n: u32) -> Result { + if self.available < n { + self.refill(); + if self.available < n { + return Err(corrupt("truncated entropy stream")); + } + } self.available -= n; Ok(((self.acc >> self.available) & ((1u64 << n) - 1)) as u32) } - fn residual(&mut self, k: u32, bits: u32, range: u32, limit: u32) -> Result { + /// Reads the unary prefix: the zeros before the next one bit, which is consumed. Errors exactly where reading + /// bit by bit would: more than `limit` zeros, or a stream that ends first. + #[inline] + fn zeros(&mut self, limit: u32) -> Result { let mut zeros = 0; - while self.get(1)? == 0 { - zeros += 1; - if zeros > limit { + loop { + if self.available == 0 { + self.refill(); + if self.available == 0 { + return Err(corrupt("truncated entropy stream")); + } + } + // the unread bits, left-aligned; the zeros shifted in below them are cut off by `min` + let run = (self.acc << (64 - self.available)).leading_zeros().min(self.available); + if zeros + run > limit { return Err(corrupt("invalid residual escape")); } + zeros += run; + if run < self.available { + self.available -= run + 1; + return Ok(zeros); + } + self.available = 0; } + } + + fn residual(&mut self, k: u32, bits: u32, range: u32, limit: u32) -> Result { + let zeros = self.zeros(limit)?; let code = if zeros == limit { self.get(bits)? + 1 } else { (zeros << k) | self.get(k)? }; if code > range { return Err(corrupt(&format!( @@ -501,5 +532,48 @@ mod tests { src.extend_from_slice(&data); let _ = decode(&src, 780, 6, bits, xtrans, Mode::Full); } + + /// The word-at-a-time reader returns what reading bit by bit returns, and fails where it fails: long zero + /// runs, the escape limit and the end of the stream included. + #[test] + fn bit_reader_matches_reading_bit_by_bit( + data in prop::collection::vec(prop_oneof![3 => Just(0u8), 1 => any::()], 0..64), + reads in prop::collection::vec((any::(), 0u32..=24, 0u32..=63), 1..200), + ) { + let bit = |i: usize| data.get(i / 8).map(|b| (b >> (7 - i % 8)) & 1 == 1); + let mut at = 0usize; + let mut reader = Bits::new(&data); + for (prefix, n, limit) in reads { + let expected = if prefix { + let mut zeros = 0; + loop { + let Some(b) = bit(at) else { break Err("truncated") }; + at += 1; + if b { + break Ok(zeros); + } + zeros += 1; + if zeros > limit { + break Err("escape"); + } + } + } else if at + n as usize > data.len() * 8 { + Err("truncated") + } else { + let value = (0..n as usize).fold(0, |v, i| (v << 1) | u32::from(bit(at + i) == Some(true))); + at += n as usize; + Ok(value) + }; + let actual = if prefix { reader.zeros(limit) } else { reader.get(n) }; + match (expected, actual) { + (Ok(want), Ok(got)) => prop_assert_eq!(want, got), + (Err(want), Err(got)) => { + prop_assert!(got.to_string().contains(want), "{got}"); + break; + } + (want, got) => prop_assert!(false, "expected {want:?}, got {got:?}"), + } + } + } } } diff --git a/crates/raw/src/vendor/srw.rs b/crates/raw/src/vendor/srw.rs index b22faeec00..dbdb21b52f 100644 --- a/crates/raw/src/vendor/srw.rs +++ b/crates/raw/src/vendor/srw.rs @@ -62,7 +62,8 @@ fn keyed(mn: &Ifd, tag: u16, sign: i64) -> Option> { let key = mn.u64s(ENCRYPTION_KEY).filter(|k| k.len() == 11)?; let vals = mn.f64s(tag)?; // 32-bit entries: the stored value wraps modulo 2^32 (a negative number stored as a LONG) - Some(vals.iter().enumerate().map(|(i, &v)| i64::from((v as i64).wrapping_add(sign * key[i % 11] as i64) as i32)).collect()) + // (a key value past i64::MAX must not overflow the multiply: only the low 32 bits are kept) + Some(vals.iter().enumerate().map(|(i, &v)| i64::from((v as i64).wrapping_add((key[i % 11] as i64).wrapping_mul(sign)) as i32)).collect()) } /// The raw image's IFD: the one with a private compression value. @@ -97,7 +98,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let (w, h) = (info.width as usize, info.height as usize); let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; let chunks = info.chunks(bytes.len() as u64); - let strip: u64 = chunks.iter().map(|c| c.len).sum(); + let strip = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)); let Some(coding) = coding(info.compression, w, h, strip).filter(|_| chunks.len() == 1) else { return Err(RawError::Unsupported(format!( "Samsung compressed raw (compression {}, {:.2} stored bits per sample)", @@ -107,6 +108,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { }; let data = if mode == Mode::Full { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("SRW strip outside file".into()))?; + if src.len() as u64 != strip { + return Err(RawError::Corrupt("SRW strip shorter than its rows".into())); + } let mut d = vec![0u16; n]; match coding { Coding::Words => read_u16s(src, ByteOrder::Little, &mut d), @@ -283,19 +287,25 @@ mod tests { /// A maker note in the Samsung layout: a big-endian IFD of LONG vectors, offsets relative to the note's start. fn note(entries: &[(u16, Vec)]) -> Vec { + let typed: Vec<_> = entries.iter().map(|(tag, v)| (*tag, 4, v.len() as u32, v.iter().flat_map(|x| x.to_be_bytes()).collect())).collect(); + note_typed(&typed) + } + + /// [`note`] with any entry types: `(tag, type, count, big-endian value bytes)`. + fn note_typed(entries: &[(u16, u16, u32, Vec)]) -> Vec { let mut head = Vec::new(); let mut tail = Vec::new(); head.extend_from_slice(&(entries.len() as u16).to_be_bytes()); let values_at = 2 + 12 * entries.len() + 4; - for (tag, v) in entries { + for (tag, kind, count, v) in entries { head.extend_from_slice(&tag.to_be_bytes()); - head.extend_from_slice(&4u16.to_be_bytes()); - head.extend_from_slice(&(v.len() as u32).to_be_bytes()); - if v.len() == 1 { - head.extend_from_slice(&v[0].to_be_bytes()); + head.extend_from_slice(&kind.to_be_bytes()); + head.extend_from_slice(&count.to_be_bytes()); + if v.len() <= 4 { + head.extend(v.iter().copied().chain(std::iter::repeat(0)).take(4)); } else { head.extend_from_slice(&((values_at + tail.len()) as u32).to_be_bytes()); - tail.extend(v.iter().flat_map(|x| x.to_be_bytes())); + tail.extend_from_slice(v); } } head.extend_from_slice(&[0; 4]); @@ -355,6 +365,23 @@ mod tests { TiffWriter::new(lightcraft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. + #[test] + fn strip_byte_counts_past_u64_max_do_not_overflow() { + let file = crate::vendor::tests::huge_strip_counts(srw(Spec { + w: 4, + h: 2, + compression: 32769, + strip: vec![0; 16], + pattern: None, + note: None, + picture: None, + })); + for mode in [Mode::Header, Mode::Full] { + let _ = super::decode(&file, mode); + } + } + /// The camera-stated description every test file carries: JPEG framing, white balance, levels. fn full_note(area: [u32; 4], white: i64, black: i64) -> Vec { let mut levels = vec![0i64; 4]; @@ -510,6 +537,27 @@ mod tests { assert!(matches!(decode(&bytes), Err(RawError::Unsupported(w)) if w.contains("CFAPattern"))); } + /// An encryption key value past i64::MAX (LONG8) overflowed `-1 * key` in debug builds. + #[test] + fn a_huge_encryption_key_does_not_panic() { + let key: Vec = std::iter::repeat_n((1u64 << 63).to_be_bytes(), 11).flatten().collect(); + let note = note_typed(&[(ENCRYPTION_KEY, 16, 11, key), (WB_UNCORRECTED, 4, 4, [0u8; 16].to_vec()), (WB_BLACK, 4, 4, [0u8; 16].to_vec())]); + let bytes = srw(Spec { + w: 64, + h: 32, + compression: 32770, + strip: pack12(&ramp(64, 32, 4096)), + pattern: Some([2, 1, 1, 0]), + note: Some(note), + picture: None, + }); + let mn = maker_note(&bytes, &Tiff::parse(&bytes).unwrap()).unwrap(); + assert_eq!(mn.u64s(ENCRYPTION_KEY).map(|k| k[0]), Some(1 << 63), "the key reaches keyed()"); + assert_eq!(keyed(&mn, WB_BLACK, -1), Some(vec![0; 4]), "(2^63 mod 2^32 is 0)"); + assert!(decode(&bytes).is_ok()); + assert!(probe_info(&bytes).is_ok()); + } + /// A framing rectangle outside the array, or reversed, is ignored; truncated files fail without panicking. #[test] fn hostile_framing_and_truncation_do_not_panic() { @@ -540,4 +588,16 @@ mod tests { let _ = probe_info(&bytes[..cut]); } } + + /// #2561: a small file whose strip declares a large frame is refused before the full decode allocates the frame. + #[test] + fn a_strip_cut_short_is_refused_before_allocating() { + let (w, h) = (3000u32, 2000u32); + for (compression, declared) in [(32769, w * h * 2), (32770, w * h / 2 * 3)] { + let mut f = srw(Spec { w, h, compression, strip: vec![0u8; 12], pattern: Some([0, 1, 1, 2]), note: None, picture: None }); + crate::vendor::declare_strip_len(&mut f, 12, declared); + assert_eq!(probe(&f), Some(crate::RawFormat::Srw)); + assert!(matches!(decode(&f), Err(RawError::Corrupt(_))), "compression {compression}"); + } + } } diff --git a/crates/raw/tests/it/corpus.rs b/crates/raw/tests/it/corpus.rs index 7f7074f911..85792c79a7 100644 --- a/crates/raw/tests/it/corpus.rs +++ b/crates/raw/tests/it/corpus.rs @@ -1443,7 +1443,7 @@ fn corpus_kodak_dcs520c() { /// Fujifilm RAF lens tables (`0xf00b` distortion, `0xf010` vignetting) become a warp and a vignette gain for the /// cameras whose geometry was checked against the camera JPEG (docs/fuji-lens-corrections.md). Reads `LIGHTCRAFT_FUJI` (a folder -/// of RAFs or of per-model folders, e.g. the CC0 pixls set) or the corpus' `raf-fuji-*` files; skips when absent. +/// of RAFs or of per-model folders, e.g. the CC0 pixls set) or the corpus' `raf-fuji*` files; skips when absent. #[test] fn fuji_embedded_lens_tables_follow_the_validated_models() { fn collect(dir: &Path, depth: usize, out: &mut Vec) { @@ -1462,7 +1462,7 @@ fn fuji_embedded_lens_tables_follow_the_validated_models() { Some(dir) => collect(Path::new(&dir), 0, &mut files), None => { collect(&corpus_root().join("raw"), 1, &mut files); - files.retain(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("raf-fuji-"))); + files.retain(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("raf-fuji"))); } } files.sort(); diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6c24d0836f..6fd077ff96 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -149,6 +149,7 @@ impl Sam3 { return Err(Error::Missing(dir.to_path_buf())); } let weights = weights::Weights::open(&dir.join(WEIGHTS_FILE))?; + hugging_face_format(&weights)?; let backbone = vit::Vit::new(Self::vb(&weights, &device).pp("detector_model.vision_encoder.backbone"))?; Ok(Self { dir: dir.to_path_buf(), device, weights, backbone, tracker_neck: None, tracker: None, detector: None, tokenizer: None }) } @@ -260,6 +261,20 @@ impl Encoded { } } +#[cfg(not(target_arch = "wasm32"))] +/// Meta's original checkpoint (`sam3.pt`, or a `sam3.safetensors` conversion of it as on community +/// mirrors) names its tensors differently: say so, rather than name the first tensor it lacks (#3378). +fn hugging_face_format(weights: &weights::Weights) -> Result<()> { + let first = "detector_model.vision_encoder.backbone.embeddings.patch_embeddings.projection.weight"; + if !weights.contains(first) && (weights.has_prefix("detector.backbone.") || weights.has_prefix("tracker.")) { + return Err(Error::Model(format!( + "{WEIGHTS_FILE} is Meta's original checkpoint (sam3.pt, or a sam3.safetensors conversion of it as on community mirrors); \ + LightCraft needs the Hugging Face format: {WEIGHTS_FILE} from facebook/sam3" + ))); + } + Ok(()) +} + #[cfg(not(target_arch = "wasm32"))] fn sigmoid(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) @@ -273,3 +288,22 @@ pub use detector::Output as DetectorOutput; pub fn sync(model: &Sam3) -> Result<()> { Ok(model.device.synchronize()?) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn meta_original_checkpoint_is_named_as_such() { + // #3378: a community mirror's `sam3.safetensors` (Meta's key names, C64 RoPE tables) saved as model.safetensors + let dir = std::env::temp_dir().join(format!("lc-sam3-original-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let header = r#"{"detector.backbone.vision_backbone.trunk.blocks.0.attn.freqs_cis":{"dtype":"C64","shape":[2],"data_offsets":[0,16]},"tracker.sam_mask_decoder.iou_token.weight":{"dtype":"F32","shape":[2],"data_offsets":[16,24]}}"#; + std::fs::rename(weights::tests::write("original", header, 24), dir.join(WEIGHTS_FILE)).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + let err = Sam3::load_cpu(&dir).err().unwrap().to_string(); + assert!(err.contains("Meta's original checkpoint") && err.contains("facebook/sam3"), "{err}"); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/segment/src/weights.rs b/crates/segment/src/weights.rs index 48ec2ef65f..ef47a7230a 100644 --- a/crates/segment/src/weights.rs +++ b/crates/segment/src/weights.rs @@ -16,6 +16,9 @@ use candle_nn::var_builder::SimpleBackend; use crate::{Error, Result}; struct Entry { + /// `Err`: the header's name for a dtype LightCraft doesn't read (Meta's original checkpoint + /// stores its RoPE tables as C64); the tensor is listed, and reading it fails + dtype: std::result::Result, shape: Vec, start: u64, end: u64, @@ -48,8 +51,8 @@ impl Weights { continue; } let dtype = match v.get("dtype").and_then(|d| d.as_str()) { - Some("F32") => DType::F32, - other => return Err(Error::Model(format!("{name}: unsupported dtype {other:?} (the SAM 3 checkpoint is F32)"))), + Some("F32") => Ok(DType::F32), + other => Err(format!("{other:?}")), }; let shape: Vec = v .get("shape") @@ -59,15 +62,18 @@ impl Weights { let offsets: Vec = v.get("data_offsets").and_then(|s| s.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64()).collect()).unwrap_or_default(); let [start, end] = offsets[..] else { return Err(Error::Model(format!("{name}: bad data_offsets"))) }; - let want = shape.iter().try_fold(dtype.size_in_bytes(), |a, d| a.checked_mul(*d)); - if end.checked_sub(start) != want.map(|w| w as u64) { - return Err(Error::Model(format!("{name}: size does not match its shape"))); + // an unreadable tensor's size isn't checked: its bytes are never read + if let Ok(dtype) = dtype { + let want = shape.iter().try_fold(dtype.size_in_bytes(), |a, d| a.checked_mul(*d)); + if end.checked_sub(start) != want.map(|w| w as u64) { + return Err(Error::Model(format!("{name}: size does not match its shape"))); + } } // the bytes must be in the file (a damaged or truncated download fails here, not later) if (8 + n).checked_add(end).is_none_or(|e| e > file_len) { return Err(Error::Model(format!("{}: tensor {name} lies outside the file (incomplete or damaged download?)", path.display()))); } - entries.insert(name, Entry { shape, start, end }); + entries.insert(name, Entry { dtype, shape, start, end }); } Ok(Arc::new(Self { file: Mutex::new(file), entries, data_start: 8 + n })) } @@ -76,6 +82,11 @@ impl Weights { self.entries.contains_key(name) } + /// Whether any tensor's name starts with `prefix`. + pub fn has_prefix(&self, prefix: &str) -> bool { + self.entries.keys().any(|k| k.starts_with(prefix)) + } + /// The shape stored in the header for `name`, without reading its data. pub fn shape(&self, name: &str) -> Option<&[usize]> { self.entries.get(name).map(|e| e.shape.as_slice()) @@ -84,6 +95,9 @@ impl Weights { /// Tensor `name` as stored, on the CPU. pub fn read(&self, name: &str) -> Result { let e = self.entries.get(name).ok_or_else(|| Error::Model(format!("missing tensor `{name}`")))?; + if let Err(dtype) = &e.dtype { + return Err(Error::Model(format!("{name}: unsupported dtype {dtype} (the SAM 3 checkpoint is F32)"))); + } // checked against the file's length in `open` let len = usize::try_from(e.end.saturating_sub(e.start)).map_err(|_| Error::Model(format!("{name}: too large")))?; let mut bytes = vec![0u8; len]; @@ -122,10 +136,10 @@ impl SimpleBackend for Backend { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; - fn write(name: &str, header: &str, data_len: usize) -> std::path::PathBuf { + pub(crate) fn write(name: &str, header: &str, data_len: usize) -> std::path::PathBuf { let p = std::env::temp_dir().join(format!("lc-weights-{name}-{}.safetensors", std::process::id())); let mut b = (header.len() as u64).to_le_bytes().to_vec(); b.extend_from_slice(header.as_bytes()); @@ -147,6 +161,22 @@ mod tests { let _ = std::fs::remove_file(p); } + #[test] + fn a_tensor_of_another_dtype_fails_when_read_not_when_opened() { + // Meta's original checkpoint stores RoPE tables as C64 next to its F32 weights (#3378) + let p = write( + "c64", + r#"{"freqs_cis":{"dtype":"C64","shape":[2],"data_offsets":[0,16]},"a":{"dtype":"F32","shape":[2],"data_offsets":[16,24]}}"#, + 24, + ); + let w = Weights::open(&p).unwrap(); + assert!(w.contains("freqs_cis")); + let err = w.read("freqs_cis").unwrap_err().to_string(); + assert!(err.contains("unsupported dtype") && err.contains("C64"), "{err}"); + assert_eq!(w.read("a").unwrap().dims(), &[2]); + let _ = std::fs::remove_file(p); + } + #[test] fn tensors_must_lie_inside_the_file() { let ok = write("ok", r#"{"a":{"dtype":"F32","shape":[2,2],"data_offsets":[0,16]}}"#, 16); diff --git a/crates/sysmem/Cargo.toml b/crates/sysmem/Cargo.toml index a7f0492c6e..52ad5d2067 100644 --- a/crates/sysmem/Cargo.toml +++ b/crates/sysmem/Cargo.toml @@ -6,8 +6,7 @@ license.workspace = true description = "LightCraft sysmem (L0): returns freed allocator memory to the OS. The workspace's only crate allowed `unsafe` (one FFI call)." # Opts out of the workspace lints only to keep `unsafe_code = "deny"` overridable for the single FFI -# module below; every other crate root has `#![forbid(unsafe_code)]`. See AGENTS.md and craftrules -# standards/never-crash.md ("isolated helper library crate"). +# module below; every other crate root has `#![forbid(unsafe_code)]`. See AGENTS.md. [lints.rust] unsafe_code = "deny" diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 9d8300e8e9..a0b453f24b 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -12,8 +12,8 @@ //! macro's last arm. `i18n::tests::translation_gaps_report` lists the gaps per language. //! //! It also bakes the contributor credits into the binary as static Rust tables (`$OUT_DIR/credits.rs`, -//! included by `src/credits.rs`; craftrules `standards/contributors.md`): commit stats from -//! `contributors/contributors.json` (generated by craftrules `scripts/contributors.py`) and the names +//! included by `src/credits.rs`): commit stats from +//! `contributors/contributors.json` and the names //! people chose for themselves from `contributors/people.toml`. Nothing is read at run time. A //! missing or malformed file gives empty tables (or usernames only) and a warning, never a failed build. use std::{ diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d..e0ec9f1baa 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -33,6 +33,7 @@ "Added {n} photo{} to “{}”": "Do „{1}“ přidáno fotografií: {n}{0:.0}", "Added {what} to {name}": "Přidáno {what} do {name}", "Added “{keyword}” to {n} photo{}": "K fotografiím přidáno „{keyword}“: {n}{:.0}", + "Add Keyword “{keywords}”": "Přidat klíčové slovo „{keywords}“", "Adding photos… {} of {}": "Přidávání fotografií… {} z {}", "All {n} selected photos move by the same amount.": "Všech {n} vybraných fotografií se posune o stejnou hodnotu.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Již v knihovně, v nedávno odstraněných: vybrané fotografie: {}{:.0} · pravé tlačítko → Obnovit, nebo Trvale odstranit pro nový import", @@ -46,10 +47,11 @@ "Build Standard-Sized Previews ({scope})": "Vytvořit standardní náhledy ({scope})", "Building previews for {} photos…": "Vytváření náhledů pro fotografie: {}…", "Click {}:1": "Kliknutí {}:1", + "Collapse {name}": "Sbalit {name}", "Couldn't open the editor: {e}": "Editor se nepodařilo otevřít: {e}", "Create Keyword Tag Inside “{name}”…": "Vytvořit značku klíčového slova uvnitř „{name}“…", "Create {n} Virtual Copies": "Vytvořit virtuální kopie: {n}", - "Creates {} stacks from {} of {scope}": "Vytvoří {} sad z {} v {scope}", + "Creates {stacks} stack{} from {photos} of {scope}": "Vytvoří sady: {stacks} z fotografií: {photos} ({scope}){:.0}", "Decoder: {reason}": "Dekodér: {reason}", "Delete \"{label}\"": "Odstranit „{label}“", "Delete \"{label}\" (and the mask)": "Odstranit „{label}“ (i masku)", @@ -62,6 +64,7 @@ "Downloads from {host}. Once it has arrived and checked out, LightCraft installs it, {after}.": "Stahuje se z {host}. Po stažení a ověření jej LightCraft nainstaluje a {after}.", "Duplicate \"{label}\"": "Duplikovat „{label}“", "Example: {example}": "Příklad: {example}", + "Expand {name}": "Rozbalit {name}", "Exported {n} keyword{}": "Exportovaná klíčová slova: {n}{:.0}", "Exported {n} photo{}": "Exportováno fotografií: {n}{:.0}", "Exported {ok} of {total} photo{}": "Exportováno fotografií: {ok} z {total}{:.0}", @@ -76,6 +79,7 @@ "Healed {n} dust spot{}": "Retušované prachové skvrny: {n}{:.0}", "Import cancelled · {} photo{} added": "Import byl zrušen · přidáno fotografií: {}{:.0}", "Import failed: {e}": "Import selhal: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importujte fotografie přes Soubor → Importovat fotografie… ({}) nebo je přetáhněte sem", "Import warnings ({n}):\n{warnings}": "Varování importu ({n}):\n{warnings}", "Imported {n} point curve preset{}": "Importovaná přednastavení bodové křivky: {n}{:.0}", "Imported {n} preset{}": "Importovaná přednastavení: {n}{:.0}", @@ -108,6 +112,7 @@ "Moved; {} photo(s) relinked": "Přesunuto; znovu propojeno fotografií: {}", "Named ({named_n})": "Pojmenované ({named_n})", "New Folder in “{name}”": "Nová složka v „{name}“", + "Created folder “{name}” in “{parent}”": "Vytvořena složka „{name}“ v „{parent}“", "On {have} of {of} selected photos": "Na {have} z {of} vybraných fotografií", "Painting “{k}”: click photos to add or remove it · Esc stops": "Nanášení „{k}“: kliknutím na fotografie přidáte nebo odeberete slovo · Esc ukončí režim", "Paste into {n} photo{} — only settings that were copied are pasted": "Vložit do fotografií: {n}{:.0} — vloží se pouze zkopírovaná nastavení", @@ -137,6 +142,7 @@ "Rendering on the CPU: {why}": "Vykreslování na CPU: {why}", "Replace {} with:": "Nahradit {} za:", "Reset {name}": "Obnovit {name}", + "{name} value": "{name} – hodnota", "Reset {} Channel": "Obnovit kanál {}", "Restore {}": "Obnovit {}", "Restore {} Photo{}": "Obnovit fotografie: {}{:.0}", @@ -267,6 +273,7 @@ "Update “{name}” with Current Settings": "Aktualizovat „{name}“ podle aktuálního nastavení", "{n} preset{}": "Přednastavení: {n}{:.0}", "{count} more warnings.": "Další varování: {count}.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "Fotografie katalogu v nedávno odstraněných této knihovny: {in_trash}. Zůstávají tam; chcete-li je vidět, obnovte je z nedávno odstraněných.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Neimportované obrázky katalogu: {skipped}. Jejich záznamy v katalogu jsou neúplné.", "{photos} catalog records processed; {collections} collections.": "Zpracováno záznamů katalogu: {photos}; kolekcí: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Chybějící originály: {missing}. Jejich záznamy jsou v katalogu dostupné; použijte Najít chybějící fotografie a znovu je propojte.", @@ -279,7 +286,7 @@ "Skipped {problem}": "Přeskočeno: {problem}", "…and {more} more": "…a další: {more}", "Template preview: {name}": "Náhled šablony: {name}", - "{n} photos in view · {slides} slides · {time}": "Fotografie v zobrazení: {n} · snímky: {slides} · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "Fotografií v zobrazení: {n} · snímků: {slides} · {time}{:.0}{:.0}", "{n} pages": "Stránky: {n}", "{n} JPEG files": "Soubory JPEG: {n}", "{s} s of AV1 video": "Video AV1: {s} s", @@ -293,7 +300,7 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Přidáno sloučení {what} v rozlišení {mp}: plné rozlišení {full} vyžaduje více paměti, než má tento počítač", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Přidáno sloučení {what} v rozlišení {mp}, což je nejvyšší možné rozlišení panoramatu (plné rozlišení je {full})", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Barevný prostor: Rec. 2020 {curve} (HDR AVIF)", - "{n} selected photos · {pages} pages": "Vybrané fotografie: {n} · stránky: {pages}", + "{n} selected photo{} · {pages} page{}": "Vybrané fotografie: {n} · stránek: {pages}{:.0}{:.0}", "Already in “{}”": "Již v „{}“", "Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "Soubor {name} se nepodařilo přečíst: {e}", "Added {n} photo{}": "Přidáno fotografií: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})", + "Photo: {name}": "Fotografie: {name}", + "Panel layout could not be restored: {error}": "Rozložení panelů se nepodařilo obnovit: {error}", + "Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}", + "{name} is installed": "{name} je nainstalován", + "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524..6a056bbfb9 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -57,6 +57,7 @@ "Add to Local": "Přidat do místních souborů", "Add to My Photos": "Přidat do mých fotografií", "Can't be moved here": "Sem nelze přesunout", + "Import photos with File → Import Photos…, or drop them here": "Importujte fotografie přes Soubor → Importovat fotografie… nebo je přetáhněte sem", "This row covers more than one disk: drop on a folder inside it": "Tento řádek zahrnuje více disků: přetáhněte položky na některou ze složek v něm", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Místní fotografie zatím nejsou v knihovně: nejprve použijte Přidat do mých fotografií a pak je přesuňte", "Add to My Photos First": "Nejprve přidat do mých fotografií", @@ -254,6 +255,7 @@ "Auto-Tag Photos from Tracklog": "Doplnit polohu fotografií ze záznamu trasy", "Auto-Tag from Tracklog": "Doplnit polohu ze záznamu trasy", "Auto-Tag from Tracklog…": "Doplnit polohu ze záznamu trasy…", + "Add Locations": "Doplnit polohy", "Automatic": "Automatické", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Automatický režim vykresluje detail podle velikosti zobrazení, nejvýše v rozlišení fotografie. Zvolením velikosti nastavíte limit: menší je rychlejší.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "Automatický režim používá grafickou kartu tam, kde je rychlejší než procesor: při prvním zpracování fotografie se na tomto počítači změří obě možnosti.", @@ -402,7 +404,6 @@ "Close file": "Zavřít soubor", "Close panel": "Zavřít boční panel", "Cloudy": "Zataženo", - "Collapse": "Sbalit", "Collapse All Stacks": "Sbalit všechny sady", "Collapse Stack": "Sbalit sadu", "Color": "Barva", @@ -499,6 +500,9 @@ "Cropped": "Oříznuto", "Cross Process": "Křížové vyvolání", "Culling": "Třídění", + "Cull": "Roztřídit", + "Create Stacks": "Vytvořit sady", + "Change Time": "Změnit čas", "Curve": "Křivka", "Custom": "Vlastní", "Custom template…": "Vlastní šablona…", @@ -600,6 +604,7 @@ "Download Place Names (GeoNames)": "Stáhnout názvy míst (GeoNames)", "Download the SAM 3 Model?": "Stáhnout model SAM 3?", "Downloaded and checked. Installing…": "Staženo a ověřeno. Probíhá instalace…", + "The download failed": "Stažení se nezdařilo", "Downloading model": "Stahování modelu", "Downloading place names": "Stahování názvů míst", "Downloads": "Stažené soubory", @@ -624,6 +629,7 @@ "Edit Date": "Datum úprav", "Edit Info": "Upravit informace", "Edit Keyword Set": "Upravit sadu klíčových slov", + "Edit Keywords": "Upravit klíčová slova", "Edit Keyword Tag": "Upravit značku klíčového slova", "Edit Keyword Tag…": "Upravit značku klíčového slova…", "Edit Label Names": "Upravit názvy štítků", @@ -647,6 +653,7 @@ "Effects": "Efekty", "Empty Recently Deleted": "Vyprázdnit nedávno odstraněné", "Enable Lens Corrections": "Zapnout korekce objektivu", + "Enable Painting": "Zapnout nanášení", "Enable Profile Corrections": "Zapnout korekce podle profilu", "End Interaction": "Ukončit interakci", "English": "English", @@ -900,7 +907,6 @@ "Import from Device": "Importovat ze zařízení", "Import from Folder…": "Importovat ze složky…", "Import new photos": "Importovat nové fotografie", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importujte fotografie přes Soubor → Importovat fotografie… (Cmd+Shift+I) nebo je přetáhněte sem", "Imported": "Importováno", "Imported Photos": "Importované fotografie", "Importing": "Importování", @@ -975,6 +981,7 @@ "Keyword Suggestions": "Návrhy klíčových slov", "Keyword Tag Options": "Možnosti značky klíčového slova", "Keyword to paint": "Klíčové slovo k nanášení", + "Type a keyword to paint in the Keywords panel": "Zadejte klíčové slovo k nanášení v panelu Klíčová slova", "Keywords": "Klíčová slova", "Keywords & People": "Klíčová slova a lidé", "Keywords (K)": "Klíčová slova (K)", @@ -1020,6 +1027,9 @@ "LightCraft could not start": "LightCraft se nepodařilo spustit", "LightCraft couldn't find where to keep your library.": "LightCraft nedokázal najít místo pro uložení knihovny.", "LightCraft couldn't open the library at": "LightCraft nedokázal otevřít knihovnu v umístění", + "There is no LightCraft library in this folder any more.": "V této složce už žádná knihovna LightCraft není.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Knihovna tu není: byla přesunuta nebo přejmenována, nebo není připojen její disk či síťové úložiště.", + "This folder can't be read:": "Tuto složku nelze přečíst:", "LightCraft does not know this model, so it assumed:": "LightCraft tento model nezná, a proto předpokládá:", "LightCraft on GitHub": "LightCraft na GitHubu", "LightCraft website": "Web LightCraft", @@ -1434,6 +1444,12 @@ "Purple Luminance": "Jas fialové", "Purple Saturation": "Sytost fialové", "Put New Keywords Inside This Keyword": "Vkládat nová klíčová slova pod toto klíčové slovo", + "Use This as Keyword Shortcut": "Použít jako zkratku klíčových slov", + "Set Keyword Shortcut": "Nastavit zkratku klíčových slov", + "Set Keyword Shortcut…": "Nastavit zkratku klíčových slov…", + "Add or Remove Keyword Shortcut": "Přidat nebo odebrat zkratku klíčových slov", + "Keyword Shortcut": "Zkratka klíčových slov", + "Part of the keyword shortcut": "Součást zkratky klíčových slov", "Put the locations you removed from Local back (no files change)": "Vrátit místa odebraná z místních souborů (žádné soubory se nemění)", "Quality": "Kvalita", "Query Photos": "Vyhledat fotografie dotazem", @@ -1886,6 +1902,7 @@ "Table": "Tabulka", "Tags": "Značky", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Značky: viz Značky vedle šablony. Soubory se přejmenují na disku (s přidruženými XMP); existující názvy získají -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Tlačítko Značky vypíše zástupné symboly pro šablonu, například {date} nebo {seq}. Každý soubor se na disku přejmenuje spolu s doprovodným souborem XMP; obsazený název dostane příponu -1, -2…", "Take a snapshot": "Pořídit snímek stavu", "Targeted Adjustment": "Cílená úprava", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Cílená úprava: tažením nahoru/dolů po fotografii upravíte barvy v daném místě", @@ -2237,6 +2254,7 @@ "Select none": "Zrušit celý výběr", "Select all": "Vybrat vše", "Visualize HDR": "Zobrazit rozsah HDR", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Zabránit blikání G-SYNC/FreeSync (platí po dalším spuštění)", "Add a Face Recognition Model": "Přidat model rozpoznávání obličejů", "Choose Monitor Profile": "Vybrat profil monitoru", "Display profile not used": "Profil displeje nebyl použit", @@ -2407,6 +2425,18 @@ "Dropped Files": "Přetažené soubory", "Import dropped files without review": "Importovat přetažené soubory bez kontroly", "An import is running": "Import už běží", + "The photos are imported once it ends": "Fotky se naimportují potom", "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", - "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky" + "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", + "Import Thumbnail Size": "Velikost miniatur při importu", + "Face recognition is on": "Rozpoznávání obličejů je zapnuto", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Rozpoznávání obličejů je vypnuto. Zapněte je, abyste dostávali návrhy jmen a viděli podobné obličeje pohromadě.", + "Turn on": "Zapnout", + "Set up face recognition": "Nastavit rozpoznávání obličejů", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Rozpoznávání obličejů potřebuje model, aby mohlo navrhovat jména: jednorázové stažení v Nastavení.", + "Turn on name suggestions": "Zapnout návrhy jmen", + "Set up name suggestions…": "Nastavit návrhy jmen…", + "Top bar": "Horní lišta", + "Tool strip": "Pruh nástrojů", + "Bottom bar": "Dolní lišta" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f1364..782886be84 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -36,10 +36,11 @@ "Build Standard-Sized Previews ({scope})": "Standardvorschauen erstellen ({scope})", "Building previews for {} photos…": "Vorschauen für {} Fotos werden erstellt…", "Click {}:1": "Klick {}:1", + "Collapse {name}": "{name} einklappen", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Farbraum: Rec. 2020 {curve} (HDR-AVIF)", "Couldn't open the editor: {e}": "Editor konnte nicht geöffnet werden: {e}", "Create {n} Virtual Copies": "{n} virtuelle Kopien erstellen", - "Creates {} stacks from {} of {scope}": "Erstellt {} Stapel aus {} von {scope}", + "Creates {stacks} stack{} from {photos} of {scope}": "Erstellt {stacks} Stapel aus {photos} von {scope}{:.0}", "Decoder: {reason}": "Decoder: {reason}", "Delete \"{label}\"": "„{label}“ löschen", "Delete \"{label}\" (and the mask)": "„{label}“ löschen (und die Maske)", @@ -49,6 +50,7 @@ "Done ({what}): {done} photo{plural}": "Fertig ({what}): {done} Foto{plural}", "Duplicate \"{label}\"": "„{label}“ duplizieren", "Example: {example}": "Beispiel: {example}", + "Expand {name}": "{name} ausklappen", "Exported {n} photo{}": "{n} Foto{} exportiert", "Exported {ok} of {total} photo{}": "{ok} von {total} Foto{} exportiert", "Exported {} point curve preset{}": "Exportierte Punktkurvenvorgaben: {}{:.0}", @@ -61,6 +63,7 @@ "Healed {n} dust spot{}": "Reparierte Staubflecken: {n}{:.0}", "Import cancelled · {} photo{} added": "Import abgebrochen · {} Foto{} hinzugefügt", "Import failed: {e}": "Import fehlgeschlagen: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importiere Fotos über Datei → Fotos importieren… ({}) oder lege sie hier ab", "Import warnings ({n}):\n{warnings}": "Importwarnungen ({n}):\n{warnings}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Die XMP-Begleitdateien von {n} Fotos konnten nicht geschrieben werden (ist ihr Ordner offline?). LightCraft versucht es weiter.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "XMP-Profil „{profile}“ wurde für {path} nicht angewendet; Farben können von Lightroom abweichen.", @@ -115,6 +118,7 @@ "Rendering on the CPU: {why}": "Rendering auf der CPU: {why}", "Replace {} with:": "{} ersetzen durch:", "Reset {name}": "{name} zurücksetzen", + "{name} value": "{name}: Wert", "Reset {} Channel": "Kanal {} zurücksetzen", "Restore {}": "{} wiederherstellen", "Restore {} Photo{}": "{} Foto{} wiederherstellen", @@ -163,7 +167,6 @@ "{n} photo{}": "{n} Foto{}", "{n} photo{} match · updates automatically as photos change": "Passende Fotos: {n}{:.0} · wird bei Änderungen an Fotos automatisch aktualisiert", "{n} photo{} now · updates automatically as photos change": "Derzeit {n} Foto{} · wird bei Änderungen an Fotos automatisch aktualisiert", - "{n} selected photos · {pages} pages": "{n} ausgewählte Fotos · {pages} Seiten", "{pid} (missing)": "{pid} (fehlt)", "{sel_n} selected · {counted}": "{sel_n} ausgewählt · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", @@ -227,6 +230,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "„{parent}“ enthält bereits „{name}“. Beide zusammenführen?", "There is a “{name}” at the top level already. Merge the two?": "Auf der obersten Ebene gibt es bereits „{name}“. Beide zusammenführen?", "Added “{keyword}” to {n} photo{}": "„{keyword}“ zu {n} Foto{} hinzugefügt", + "Add Keyword “{keywords}”": "Stichwort „{keywords}“ hinzufügen", "On {have} of {of} selected photos": "Bei {have} von {of} ausgewählten Fotos", "Remove “{name}”": "„{name}“ entfernen", "There is a keyword set “{name}” already": "Es gibt bereits einen Stichwortsatz „{name}“", @@ -248,6 +252,7 @@ "{what} merge cancelled": "{what}-Zusammenfügung abgebrochen", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Übersprungen: {n} lokale Fotos{0:.0} – Alben enthalten Bibliotheksfotos (zuerst zu „Meine Fotos“ hinzufügen)", "New Folder in “{name}”": "Neuer Ordner in „{name}“", + "Created folder “{name}” in “{parent}”": "Ordner „{name}“ in „{parent}“ erstellt", "Moved {} photo(s)": "{} Foto(s) verschoben", "not added to Apple Photos: {e}": "nicht zu Apple Fotos hinzugefügt: {e}", "{n} added to Apple Photos album “{album}”": "{n} zum Apple-Fotos-Album „{album}“ hinzugefügt", @@ -269,6 +274,7 @@ "{n} originals opened in the other editor": "{n} Originale im anderen Editor geöffnet", "· {in_source} identical copies": "· {in_source} identische Kopien", "{count} more warnings.": "{count} weitere Warnungen.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} Katalogfotos liegen in dieser Bibliothek unter „Zuletzt gelöscht“ und bleiben dort; stelle sie dort wieder her, um sie zu sehen.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} Katalogbilder wurden nicht importiert, weil ihre Einträge im Katalog unvollständig sind.", "{photos} catalog records processed; {collections} collections.": "{photos} Katalogeinträge verarbeitet; {collections} Sammlungen.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} Originale fehlen. Ihre Katalogeinträge sind verfügbar; verwende „Fehlende Fotos suchen“, um sie neu zu verknüpfen.", @@ -281,7 +287,8 @@ "Skipped {problem}": "Übersprungen: {problem}", "…and {more} more": "…und {more} weitere", "Template preview: {name}": "Vorlagenvorschau: {name}", - "{n} photos in view · {slides} slides · {time}": "{n} Fotos in der Ansicht · {slides} Dias · {time}", + "{n} selected photo{} · {pages} page{}": "Ausgewählte Fotos: {n} · Seiten: {pages}{:.0}{:.0}", + "{n} photo{} in view · {slides} slide{} · {time}": "Fotos in der Ansicht: {n} · Folien: {slides} · {time}{:.0}{:.0}", "{n} pages": "{n} Seiten", "{n} JPEG files": "{n} JPEG-Dateien", "{s} s of AV1 video": "{s} s AV1-Video", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "{name} konnte nicht gelesen werden: {e}", "Added {n} photo{}": "{n} Foto{} hinzugefügt", "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})", + "Photo: {name}": "Foto: {name}", + "Panel layout could not be restored: {error}": "Die Bereichsanordnung konnte nicht wiederhergestellt werden: {error}", + "Panel move was not applied: {error}": "Das Verschieben des Bereichs wurde nicht ausgeführt: {error}", + "{name} is installed": "{name} ist installiert", + "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782..405c54a464 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -57,6 +57,7 @@ "Add to Local": "Zu „Lokal“ hinzufügen", "Add to My Photos": "Zu „Meine Fotos“ hinzufügen", "Can't be moved here": "Hierher nicht verschiebbar", + "Import photos with File → Import Photos…, or drop them here": "Importiere Fotos über Datei → Fotos importieren… oder lege sie hier ab", "This row covers more than one disk: drop on a folder inside it": "Diese Zeile umfasst mehr als ein Laufwerk: auf einem Ordner darin ablegen", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Lokale Fotos sind noch nicht in der Bibliothek: erst zu „Meine Fotos“ hinzufügen, dann verschieben", "Add to Selected Photos": "Zu ausgewählten Fotos hinzufügen", @@ -135,6 +136,7 @@ "Auto-Tag from Tracklog": "Anhand eines GPS-Tracks automatisch verorten", "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "Automatisches Verorten anhand eines GPS-Tracks: GPS-Orte für deine Fotos aus einem GPX-Track, abgeglichen nach Aufnahmezeit.", "Auto-Tag from Tracklog…": "Anhand eines GPS-Tracks automatisch verorten…", + "Add Locations": "Orte hinzufügen", "Automatic": "Automatisch", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Automatisch rendert die Detailansicht in der angezeigten Größe, bis zu den eigenen Pixeln des Fotos. Eine Größe wählen, um sie zu begrenzen: kleiner ist schneller.", "Automatically Write Changes into XMP": "Änderungen automatisch in XMP schreiben", @@ -261,7 +263,6 @@ "Close panel": "Bedienfeld schließen", "Cloudy": "Bewölkt", "Cmd+Shift+R, keeps the photo and clears its edits.)": "mit ⌘⇧R die Bearbeitungen zurück und behält das Foto.", - "Collapse": "Einklappen", "Collapse All Stacks": "Alle Stapel einklappen", "Collapse Stack": "Stapel einklappen", "Color": "Farbe", @@ -360,6 +361,9 @@ "Crop, Rotate, Geometry": "Zuschnitt, Drehung, Geometrie", "Cross Process": "Crossentwicklung", "Culling": "Fotoauswahl", + "Cull": "Auswählen", + "Create Stacks": "Stapel erstellen", + "Change Time": "Zeit ändern", "Curve": "Kurve", "Custom": "Benutzerdefiniert", "Custom template…": "Benutzerdefinierte Vorlage…", @@ -481,6 +485,7 @@ "Effects": "Effekte", "Empty Recently Deleted": "„Zuletzt gelöscht“ leeren", "Enable Lens Corrections": "Objektivkorrekturen aktivieren", + "Enable Painting": "Auftragen aktivieren", "Enable Profile Corrections": "Profilkorrekturen aktivieren", "End Interaction": "Interaktion beenden", "English": "English", @@ -709,7 +714,6 @@ "Import as new": "Neu importieren", "Import from Device": "Von Gerät importieren", "Import from Folder…": "Aus Ordner importieren…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importiere Fotos über Datei → Fotos importieren… (⌘⇧I) oder lege sie hier ab", "Import presets from other editors: XMP presets, classic `.lrtemplate` files, \"DNG presets\" from mobile apps and `.zip`": "Vorgaben aus anderen Editoren importieren: XMP-Vorgaben, klassische `.lrtemplate`-Dateien, „DNG-Vorgaben“ aus mobilen Apps und `.zip`-Pakete.", "Import ▸ Copy verifies every copy, like Move (issue #96): each file is written as a new file, synced to disk and": "Import → Kopieren prüft jede Kopie wie beim Verschieben (Issue #96): Jede Datei wird neu geschrieben, auf den Datenträger synchronisiert", "Import ▸ Move: photos go into the destination (with the same folders and renaming as Copy, e.g.": "Import → Verschieben: Fotos gehen mit derselben Ordnerstruktur und Umbenennung wie beim Kopieren in den Zielordner, etwa", @@ -765,6 +769,7 @@ "Keyword Sets": "Stichwortsätze", "Keyword Suggestions": "Stichwortvorschläge", "Keyword to paint": "Stichwort zum Auftragen", + "Type a keyword to paint in the Keywords panel": "Stichwort zum Auftragen im Bedienfeld Stichwörter eingeben", "Keywords": "Stichwörter", "Keywords (K)": "Stichwörter (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "Hinzugefügte Stichwörter erscheinen hier; ⌥1–⌥9 wendet sie an.", @@ -801,6 +806,9 @@ "LightCraft could not start": "LightCraft konnte nicht starten", "LightCraft couldn't find where to keep your library.": "LightCraft konnte keinen Speicherort für deine Bibliothek finden.", "LightCraft couldn't open the library at": "LightCraft konnte die Bibliothek nicht öffnen unter", + "There is no LightCraft library in this folder any more.": "In diesem Ordner ist keine LightCraft-Bibliothek mehr.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Die Bibliothek ist nicht da: Sie wurde verschoben oder umbenannt, oder ihr Laufwerk bzw. ihre Netzwerkfreigabe ist nicht verbunden.", + "This folder can't be read:": "Dieser Ordner kann nicht gelesen werden:", "LightCraft no longer crashes at launch on Windows PCs whose Vulkan driver is broken (issue #136, e.g. some Intel UHD": "LightCraft stürzt beim Start auf Windows-PCs mit defektem Vulkan-Treiber nicht mehr ab (Issue #136, etwa bestimmte Intel-UHD-630-Treiber).", "LightCraft on GitHub": "LightCraft auf GitHub", "LightCraft website": "LightCraft-Website", @@ -1522,6 +1530,7 @@ "Table": "Tabelle", "Tags": "Platzhalter", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Platzhalter: Siehe „Platzhalter“ neben der Vorlage. Dateien werden auf dem Datenträger umbenannt (mit ihren XMP-Begleitdateien); vorhandene Namen erhalten -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Die Schaltfläche „Platzhalter“ zeigt, was in der Vorlage stehen kann, z. B. {date} oder {seq}. Jede Datei wird auf dem Datenträger zusammen mit ihrer XMP-Begleitdatei umbenannt; ein bereits vergebener Name erhält -1, -2…", "Take a snapshot": "Schnappschuss erstellen", "Targeted Adjustment": "Gezielte Anpassung", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Gezielte Anpassung: Im Foto nach oben/unten ziehen, um die dortigen Farben anzupassen", @@ -1871,6 +1880,7 @@ "Denoise Settings": "Entrauschungseinstellungen", "Denoise all photos with an Amount": "Alle Fotos mit einer Stärke entrauschen", "Downloaded and checked. Installing…": "Heruntergeladen und geprüft. Wird installiert…", + "The download failed": "Der Download ist fehlgeschlagen", "Failed its last test": "Letzter Test fehlgeschlagen", "Graphics card": "Grafikkarte", "I have read these terms and accept them for my own use": "Ich habe diese Bedingungen gelesen und akzeptiere sie für meine eigene Nutzung", @@ -2034,6 +2044,12 @@ "No photo has it; the keywords below it go too.": "Kein Foto verwendet es; die Stichwörter darunter werden ebenfalls gelöscht.", "Edit Keyword Tag…": "Stichwort bearbeiten…", "Put New Keywords Inside This Keyword": "Neue Stichwörter in dieses Stichwort einfügen", + "Use This as Keyword Shortcut": "Als Stichwortkürzel verwenden", + "Set Keyword Shortcut": "Stichwortkürzel festlegen", + "Set Keyword Shortcut…": "Stichwortkürzel festlegen…", + "Add or Remove Keyword Shortcut": "Stichwortkürzel hinzufügen oder entfernen", + "Keyword Shortcut": "Stichwortkürzel", + "Part of the keyword shortcut": "Teil des Stichwortkürzels", "Purge Unused Keywords": "Nicht verwendete Stichwörter löschen", "Delete Keyword…": "Stichwort löschen…", "Drop here for the top level": "Hier ablegen für die oberste Ebene", @@ -2045,6 +2061,7 @@ "& Containing": "& Übergeordnete", "Edit Set…": "Satz bearbeiten…", "Edit Keyword Set": "Stichwortsatz bearbeiten", + "Edit Keywords": "Stichwörter bearbeiten", "Keywords (⌥1–⌥9)": "Stichwörter (⌥1–⌥9)", "A keyword set needs a name": "Ein Stichwortsatz braucht einen Namen", "Save as a new set": "Als neuen Satz speichern", @@ -3439,6 +3456,19 @@ "Dropped Files": "Abgelegte Dateien", "Import dropped files without review": "Abgelegte Dateien ohne Prüfung importieren", "An import is running": "Ein Import läuft", + "The photos are imported once it ends": "Die Fotos werden danach importiert", "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", - "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst" + "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", + "Import Thumbnail Size": "Vorschaubildgröße beim Import", + "Face recognition is on": "Gesichtserkennung ist eingeschaltet", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Gesichtserkennung ist ausgeschaltet. Schalte sie ein, um Namensvorschläge zu erhalten und ähnliche Gesichter zusammen zu sehen.", + "Turn on": "Einschalten", + "Set up face recognition": "Gesichtserkennung einrichten", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Die Gesichtserkennung braucht ein Modell, um Namen vorzuschlagen: ein einmaliger Download in den Einstellungen.", + "Turn on name suggestions": "Namensvorschläge einschalten", + "Set up name suggestions…": "Namensvorschläge einrichten…", + "Top bar": "Obere Leiste", + "Tool strip": "Werkzeugleiste", + "Bottom bar": "Untere Leiste", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6..41ae09d66e 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -36,10 +36,11 @@ "Build Standard-Sized Previews ({scope})": "Generar vistas previas de tamaño estándar ({scope})", "Building previews for {} photos…": "Generando vistas previas de {} fotos…", "Click {}:1": "Clic {}:1", + "Collapse {name}": "Contraer {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Espacio de color: Rec. 2020 {curve} (AVIF HDR)", "Couldn't open the editor: {e}": "No se pudo abrir el editor: {e}", "Create {n} Virtual Copies": "Crear {n} copias virtuales", - "Creates {} stacks from {} of {scope}": "Crea {} pilas a partir de {} de {scope}", + "Creates {stacks} stack{} from {photos} of {scope}": "Crea {stacks} pila{} a partir de {photos} de {scope}", "Decoder: {reason}": "Decodificador: {reason}", "Delete \"{label}\"": "Eliminar \"{label}\"", "Delete \"{label}\" (and the mask)": "Eliminar \"{label}\" (y la máscara)", @@ -49,6 +50,7 @@ "Done ({what}): {done} photo{plural}": "Listo ({what}): {done} foto{plural}", "Duplicate \"{label}\"": "Duplicar \"{label}\"", "Example: {example}": "Ejemplo: {example}", + "Expand {name}": "Expandir {name}", "Exported {n} photo{}": "{n} foto{0} exportada{0}", "Exported {ok} of {total} photo{}": "Exportadas {ok} de {total} foto{}", "Exported {} point curve preset{}": "{0} ajuste{1} preestablecido{1} de curva de puntos exportado{1}", @@ -61,6 +63,7 @@ "Healed {n} dust spot{}": "{n} mancha{0} de polvo corregida{0}", "Import cancelled · {} photo{} added": "Importación cancelada · {0} foto{1} añadida{1}", "Import failed: {e}": "Error de importación: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importar fotos con Archivo → Importar fotos… ({}) o soltarlas aquí", "Import warnings ({n}):\n{warnings}": "Avisos de importación ({n}):\n{warnings}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "No se pudieron escribir los archivos XMP de {n} fotos (¿su carpeta está desconectada?). LightCraft lo sigue intentando.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "El perfil XMP \"{profile}\" no se aplicó a {path}; los colores pueden diferir de Lightroom.", @@ -115,6 +118,7 @@ "Rendering on the CPU: {why}": "Renderizado en la CPU: {why}", "Replace {} with:": "Reemplazar {} por:", "Reset {name}": "Restablecer {name}", + "{name} value": "Valor de {name}", "Reset {} Channel": "Restablecer canal {}", "Restore {}": "Restaurar {}", "Restore {} Photo{}": "Restaurar {} foto{}", @@ -163,7 +167,7 @@ "{n} photo{}": "{n} foto{}", "{n} photo{} match · updates automatically as photos change": "{n} foto{0} coincidente{0} · se actualiza automáticamente cuando cambian las fotos", "{n} photo{} now · updates automatically as photos change": "{n} foto{} ahora · se actualiza automáticamente cuando cambian las fotos", - "{n} selected photos · {pages} pages": "{n} fotos seleccionadas · {pages} páginas", + "{n} selected photo{} · {pages} page{}": "{n} foto{0} seleccionada{0} · {pages} página{1}", "{pid} (missing)": "{pid} (falta)", "{sel_n} selected · {counted}": "{sel_n} seleccionadas · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", @@ -227,6 +231,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "“{parent}” ya tiene “{name}”. ¿Combinar las dos?", "There is a “{name}” at the top level already. Merge the two?": "Ya hay “{name}” en el nivel superior. ¿Combinar las dos?", "Added “{keyword}” to {n} photo{}": "Se añadió “{keyword}” a {n} foto{}", + "Add Keyword “{keywords}”": "Añadir palabra clave “{keywords}”", "On {have} of {of} selected photos": "En {have} de {of} fotos seleccionadas", "Remove “{name}”": "Quitar “{name}”", "There is a keyword set “{name}” already": "Ya hay un conjunto de palabras clave “{name}”", @@ -248,6 +253,7 @@ "{what} merge cancelled": "Combinación {what} cancelada", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Fotos locales omitidas: {n}{0:.0} — los álbumes contienen fotos de la biblioteca (añádelas primero a Mis fotos)", "New Folder in “{name}”": "Nueva carpeta en «{name}»", + "Created folder “{name}” in “{parent}”": "Carpeta «{name}» creada en «{parent}»", "Moved {} photo(s)": "{} foto(s) movida(s)", "not added to Apple Photos: {e}": "no se añadieron a Fotos de Apple: {e}", "{n} added to Apple Photos album “{album}”": "{n} añadidas al álbum “{album}” de Fotos de Apple", @@ -269,6 +275,7 @@ "{n} originals opened in the other editor": "{n} originales abiertos en el otro editor", "· {in_source} identical copies": "· {in_source} copias idénticas", "{count} more warnings.": "{count} advertencias más.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} fotos del catálogo están en Eliminadas recientemente de esta biblioteca y permanecen allí; restáuralas desde Eliminadas recientemente para verlas.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "No se importaron {skipped} imágenes del catálogo porque sus registros en el catálogo están incompletos.", "{photos} catalog records processed; {collections} collections.": "{photos} registros del catálogo procesados; {collections} colecciones.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Faltan {missing} originales. Sus registros del catálogo están disponibles; usa Buscar fotos que faltan para volver a vincularlos.", @@ -281,7 +288,7 @@ "Skipped {problem}": "Omitido: {problem}", "…and {more} more": "…y {more} más", "Template preview: {name}": "Vista previa de la plantilla: {name}", - "{n} photos in view · {slides} slides · {time}": "{n} fotos en la vista · {slides} diapositivas · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto{0} en la vista · {slides} diapositiva{1} · {time}", "{n} pages": "{n} páginas", "{n} JPEG files": "{n} archivos JPEG", "{s} s of AV1 video": "{s} s de vídeo AV1", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "No se pudo leer {name}: {e}", "Added {n} photo{}": "{n} foto{0} añadida{0}", "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})", + "Photo: {name}": "Foto: {name}", + "Panel layout could not be restored: {error}": "No se pudo restablecer la disposición de paneles: {error}", + "Panel move was not applied: {error}": "No se aplicó el movimiento del panel: {error}", + "{name} is installed": "{name} está instalado", + "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff..e43ae8c49b 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -42,6 +42,7 @@ "Add to Local": "Añadir a Local", "Add to My Photos": "Añadir a Mis fotos", "Can't be moved here": "No se pueden mover aquí", + "Import photos with File → Import Photos…, or drop them here": "Importar fotos con Archivo → Importar fotos… o soltarlas aquí", "This row covers more than one disk: drop on a folder inside it": "Esta fila abarca más de un disco: suéltalas en una carpeta dentro de ella", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Las fotos locales aún no están en la biblioteca: primero Añadir a Mis fotos y luego muévelas", "Add to Selected Photos": "Añadir a las fotos seleccionadas", @@ -118,6 +119,7 @@ "Auto-Tag Photos from Tracklog": "Etiquetar fotos automáticamente desde el registro de ruta", "Auto-Tag from Tracklog": "Etiquetar automáticamente desde el registro de ruta", "Auto-Tag from Tracklog…": "Etiquetar automáticamente desde el registro de ruta…", + "Add Locations": "Añadir ubicaciones", "Automatic": "Automático", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Automático muestra la vista Detalle al tamaño en que se ve, hasta los píxeles propios de la foto. Elegir un tamaño para limitarla: cuanto más pequeño, más rápido.", "Automatically Write Changes into XMP": "Escribir automáticamente los cambios en XMP", @@ -253,7 +255,6 @@ "Close file": "Cerrar archivo", "Close panel": "Cerrar panel", "Cloudy": "Nublado", - "Collapse": "Contraer", "Collapse All Stacks": "Contraer todas las pilas", "Collapse Stack": "Contraer pila", "Color": "Color", @@ -350,6 +351,9 @@ "Crop, Rotate, Geometry": "Recorte, rotación, geometría", "Cross Process": "Proceso cruzado", "Culling": "Selección", + "Cull": "Seleccionar", + "Create Stacks": "Crear pilas", + "Change Time": "Cambiar hora", "Curve": "Curva", "Custom": "Personalizado", "Custom template…": "Plantilla personalizada…", @@ -473,6 +477,7 @@ "Effects": "Efectos", "Empty Recently Deleted": "Vaciar Eliminadas recientemente", "Enable Lens Corrections": "Activar correcciones de lente", + "Enable Painting": "Activar pintura", "Enable Profile Corrections": "Activar correcciones de perfil", "End Interaction": "Finalizar interacción", "English": "Inglés", @@ -525,6 +530,7 @@ "Faded Matte": "Mate desvaído", "Faded Slide": "Diapositiva desvaída", "Faded Urban": "Urbano desvaído", + "Favorite": "Favorito", "Favorite Preset": "Ajuste preestablecido favorito", "Favorite Profile": "Perfil favorito", "Favorites": "Favoritos", @@ -715,7 +721,6 @@ "Import as new": "Importar como nuevas", "Import from Device": "Importar desde dispositivo", "Import from Folder…": "Importar desde carpeta…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importar fotos con Archivo → Importar fotos… (Cmd+Mayús+I) o soltarlas aquí", "Imported": "Importadas", "Imported Photos": "Fotos importadas", "Importing": "Importando", @@ -766,6 +771,7 @@ "Keyword Sets": "Conjuntos de palabras clave", "Keyword Suggestions": "Sugerencias de palabras clave", "Keyword to paint": "Palabra clave para pintar", + "Type a keyword to paint in the Keywords panel": "Escribir una palabra clave para pintar en el panel Palabras clave", "Keywords": "Palabras clave", "Keywords (K)": "Palabras clave (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "Las palabras clave añadidas aparecen aquí; ⌥1–⌥9 las aplican.", @@ -806,6 +812,9 @@ "LightCraft could not start": "No se pudo iniciar LightCraft", "LightCraft couldn't find where to keep your library.": "LightCraft no encontró dónde guardar la biblioteca.", "LightCraft couldn't open the library at": "LightCraft no pudo abrir la biblioteca en", + "There is no LightCraft library in this folder any more.": "Ya no hay ninguna biblioteca de LightCraft en esta carpeta.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "La biblioteca no está: se movió o se le cambió el nombre, o su disco o carpeta de red no está conectado.", + "This folder can't be read:": "No se puede leer esta carpeta:", "LightCraft on GitHub": "LightCraft en GitHub", "LightCraft website": "Sitio web de LightCraft", "LightCraft — Second Window": "LightCraft: segunda ventana", @@ -1538,6 +1547,7 @@ "Table": "Tabla", "Tags": "Etiquetas", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Etiquetas: ver Etiquetas junto a la plantilla. Los archivos cambian de nombre en el disco (con sus archivos XMP complementarios); los nombres existentes reciben -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "El botón Etiquetas muestra los marcadores que puedes usar en la plantilla, como {date} o {seq}. Cada archivo cambia de nombre en el disco junto con su archivo XMP; si el nombre ya existe, se le añade -1, -2…", "Take a snapshot": "Crear una instantánea", "Targeted Adjustment": "Ajuste selectivo", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Ajuste selectivo: arrastrar hacia arriba/abajo en la foto para ajustar los colores de ese punto", @@ -1885,6 +1895,7 @@ "Denoise Settings": "Ajustes de reducción de ruido", "Denoise all photos with an Amount": "Reducir el ruido de todas las fotos con una cantidad", "Downloaded and checked. Installing…": "Descargado y comprobado. Instalando…", + "The download failed": "La descarga ha fallado", "Failed its last test": "Falló en su última prueba", "Graphics card": "Tarjeta gráfica", "I have read these terms and accept them for my own use": "He leído estas condiciones y las acepto para mi propio uso", @@ -2062,6 +2073,12 @@ "No photo has it; the keywords below it go too.": "Ninguna foto la tiene; las palabras clave que contiene también se eliminan.", "Edit Keyword Tag…": "Editar palabra clave…", "Put New Keywords Inside This Keyword": "Poner las nuevas palabras clave dentro de esta", + "Use This as Keyword Shortcut": "Usar como atajo de palabras clave", + "Set Keyword Shortcut": "Definir atajo de palabras clave", + "Set Keyword Shortcut…": "Definir atajo de palabras clave…", + "Add or Remove Keyword Shortcut": "Añadir o quitar el atajo de palabras clave", + "Keyword Shortcut": "Atajo de palabras clave", + "Part of the keyword shortcut": "Forma parte del atajo de palabras clave", "Purge Unused Keywords": "Eliminar palabras clave no usadas", "Delete Keyword…": "Eliminar palabra clave…", "Drop here for the top level": "Soltar aquí para el nivel superior", @@ -2073,6 +2090,7 @@ "& Containing": "y contenedoras", "Edit Set…": "Editar conjunto…", "Edit Keyword Set": "Editar conjunto de palabras clave", + "Edit Keywords": "Editar palabras clave", "Keywords (⌥1–⌥9)": "Palabras clave (⌥1–⌥9)", "A keyword set needs a name": "Un conjunto de palabras clave necesita un nombre", "Save as a new set": "Guardar como conjunto nuevo", @@ -2357,6 +2375,20 @@ "Dropped Files": "Archivos soltados", "Import dropped files without review": "Importar los archivos soltados sin revisión", "An import is running": "Hay una importación en curso", + "The photos are imported once it ends": "Las fotos se importarán después", "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", - "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos" + "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", + "Thumbnail size": "Tamaño de las miniaturas", + "Import Thumbnail Size": "Tamaño de las miniaturas de importación", + "Face recognition is on": "El reconocimiento facial está activado", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "El reconocimiento facial está desactivado. Actívalo para obtener sugerencias de nombres y ver juntas las caras parecidas.", + "Turn on": "Activar", + "Set up face recognition": "Configurar el reconocimiento facial", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "El reconocimiento facial necesita un modelo para sugerir nombres: una descarga única, en Ajustes.", + "Turn on name suggestions": "Activar sugerencias de nombres", + "Set up name suggestions…": "Configurar sugerencias de nombres…", + "Top bar": "Barra superior", + "Tool strip": "Barra de herramientas", + "Bottom bar": "Barra inferior", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9..720519a1cc 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -37,6 +37,7 @@ "Added {n} photo{} to “{}”": "Lisättyjä kuvia kohteeseen ”{1}”: {n}{0:.0}", "Added {what} to {name}": "{what} lisätty kohteeseen {name}", "Added “{keyword}” to {n} photo{}": "Avainsana ”{keyword}” lisätty kuviin: {n}{:.0}", + "Add Keyword “{keywords}”": "Lisää avainsana ”{keywords}”", "Adding photos… {} of {}": "Lisätään kuvia… {} / {}", "All {n} selected photos move by the same amount.": "Kaikkia valittuja kuvia ({n}) siirretään saman verran.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Jo kirjastossa, Äskettäin poistetuissa: valittuja kuvia {}{:.0} · napsauta hiiren kakkospainikkeella → Palauta tai Poista pysyvästi tuodaksesi uudelleen", @@ -53,12 +54,13 @@ "Build Standard-Sized Previews ({scope})": "Luo vakiokokoiset esikatselut ({scope})", "Building previews for {} photos…": "Luodaan esikatseluja {} kuvalle…", "Click {}:1": "Napsautus {}:1", + "Collapse {name}": "Tiivistä {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Väriavaruus: Rec. 2020 {curve} (HDR AVIF)", "Couldn't open the editor: {e}": "Muokkausohjelmaa ei voitu avata: {e}", "Create Keyword Tag Inside “{name}”…": "Luo avainsanatunniste kohteen ”{name}” sisään…", "Create the keyword “{name}”": "Luo avainsana ”{name}”", "Create {n} Virtual Copies": "Luo {n} virtuaalikopiota", - "Creates {} stacks from {} of {scope}": "Luo pinoja: {} · kuvia: {} ({scope})", + "Creates {stacks} stack{} from {photos} of {scope}": "Luo pinoja: {stacks}, kuvia: {photos} ({scope}){:.0}", "Decoder: {reason}": "Purkaja: {reason}", "Delete \"{label}\"": "Poista ”{label}”", "Delete \"{label}\" (and the mask)": "Poista ”{label}” (ja maski)", @@ -76,6 +78,7 @@ "Duplicate \"{label}\"": "Monista ”{label}”", "Effect: {name}": "Tehoste: {name}", "Example: {example}": "Esimerkki: {example}", + "Expand {name}": "Laajenna {name}", "Exported to {path}": "Viety kohteeseen {path}", "Exported {n} keyword{}": "Viety avainsanoja: {n}{:.0}", "Exported {n} photo{}": "Viety kuvia: {n}{:.0}", @@ -92,6 +95,7 @@ "Healed {n} dust spot{}": "Korjattuja pölyhiukkasia: {n}{:.0}", "Import cancelled · {} photo{} added": "Tuonti peruttu · lisättyjä kuvia: {}{:.0}", "Import failed: {e}": "Tuonti epäonnistui: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Tuo kuvia valitsemalla Tiedosto → Tuo kuvia… ({}) tai pudota ne tähän", "Import warnings ({n}):\n{warnings}": "Tuontivaroitukset ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", "Imported {name}": "{name} tuotu", @@ -121,7 +125,7 @@ "Lightroom import complete: {imported} photos added; index warning: {warning}": "Lightroom-tuonti valmis: lisättyjä kuvia {imported}; hakemistovaroitus: {warning}", "Lightroom import failed: {e}{warning}": "Lightroom-tuonti epäonnistui: {e}{warning}", "Lightroom inspection failed: {e}{warning}": "Lightroom-tarkastelu epäonnistui: {e}{warning}", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "Listing folders — folders: {folders}, files: {files}": "Listataan kansioita — kansiot: {folders}, tiedostot: {files}", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Fontit: {} (OFL). Kuvakkeet: omat.", "Making the denoised picture… {}%": "Tehdään kohinanpoistettua kuvaa… {}%", "Matches: {}": "Täsmäävät: {}", @@ -134,6 +138,7 @@ "Moved; {} photo(s) relinked": "Siirretty; yhdistetty uudelleen kuvia: {}", "Named ({named_n})": "Nimetyt ({named_n})", "New Folder in “{name}”": "Uusi kansio kohteessa ”{name}”", + "Created folder “{name}” in “{parent}”": "Kansio ”{name}” luotu kohteeseen ”{parent}”", "On {have} of {of} selected photos": "{have} / {of} valitulla kuvalla", "Painting “{k}”: click photos to add or remove it · Esc stops": "Maalataan ”{k}”: napsauta kuvia lisätäksesi tai poistaaksesi sen · Esc lopettaa", "Paste into {n} photo{} — only settings that were copied are pasted": "Liitä kuviin: {n}{:.0} — vain kopioidut asetukset liitetään", @@ -165,6 +170,7 @@ "Rendering on the CPU: {why}": "Renderöidään suorittimella: {why}", "Replace {} with:": "Korvaa {} seuraavalla:", "Reset {name}": "Nollaa {name}", + "{name} value": "{name}: arvo", "Reset {} Channel": "Nollaa kanava {}", "Restore {}": "Palauta {}", "Restore {} Photo{}": "Palauta kuvia: {}{:.0}", @@ -240,15 +246,15 @@ "{n} originals opened in the other editor": "Toisessa muokkausohjelmassa avattuja alkuperäisiä: {n}", "{n} pages": "Sivuja: {n}", "{n} photos": "Kuvia: {n}", - "{n} photos in view · {slides} slides · {time}": "Kuvia näkymässä: {n} · dioja: {slides} · {time}", "{n} photos in {} are hidden by the filters above": "Yllä olevat suodattimet piilottavat kuvia kohteessa {}: {n}", "{n} photos opened for editing; each is stacked with its original": "Muokattavaksi avattuja kuvia: {n}; kukin pinotaan alkuperäisensä kanssa", "{n} photo{}": "Kuvia: {n}{:.0}", + "{n} photo{} in view · {slides} slide{} · {time}": "Kuvia näkymässä: {n} · dioja: {slides} · {time}{:.0}{:.0}", "{n} photo{} match · updates automatically as photos change": "Täsmääviä kuvia: {n}{:.0} · päivittyy automaattisesti kuvien muuttuessa", "{n} photo{} now · updates automatically as photos change": "Kuvia nyt: {n}{:.0} · päivittyy automaattisesti kuvien muuttuessa", "{n} preset{}": "Esiasetuksia: {n}{:.0}", "{n} raws can now be developed from their raw data": "Raw-kuvia, jotka voidaan nyt kehittää raakadatastaan: {n}", - "{n} selected photos · {pages} pages": "Valittuja kuvia: {n} · sivuja: {pages}", + "{n} selected photo{} · {pages} page{}": "Valittuja kuvia: {n} · sivuja: {pages}{:.0}{:.0}", "{n} similar photo{} · View ▸ Clear Filters to see all": "Samankaltaisia kuvia: {n}{:.0} · Näytä → Tyhjennä suodattimet näyttääksesi kaikki", "{n} tasks are still running: {names}. Quitting stops them.": "Käynnissä olevia tehtäviä: {n}: {names}. Lopettaminen pysäyttää ne.", "{n} {noun}": "{n} {noun}", @@ -257,6 +263,7 @@ "{pid} (missing)": "{pid} (puuttuu)", "{sel_n} selected · {counted}": "Valittu: {sel_n} · {counted}", "{size} GB": "{size} Gt", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "Katalogin kuvia tämän kirjaston Äskettäin poistetuissa: {in_trash}. Ne jäävät sinne; palauta ne Äskettäin poistetuista nähdäksesi ne.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", "{stage}… {:.0}%": "{stage}… {:.0}%", "{s} s of AV1 video": "{s} s AV1-videota", @@ -305,5 +312,10 @@ "Drop to import {n} preset{}": "Pudota tuodaksesi esiasetuksia: {n}{:.0}", "Drop to review {n} item{} for import": "Pudota tarkistaaksesi ennen tuontia (kohteita: {n}){:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Minne Lightroom-luettelo ”{catalog}” tuodaan?", - "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})", + "Photo: {name}": "Kuva: {name}", + "Panel layout could not be restored: {error}": "Paneelien asettelua ei voitu palauttaa: {error}", + "Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}", + "{name} is installed": "{name} on asennettu", + "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e0a8c622a3..ff7e03c066 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -45,6 +45,7 @@ "Add Catchlight": "Lisää silmänvalo", "Add Face Model…": "Lisää kasvomalli…", "Add Folder to Local": "Lisää kansio paikalliseen", + "Add Locations": "Lisää sijainnit", "Add Mask": "Lisää maski", "Add Object Click": "Lisää kohdenapsautus", "Add Point Color Sample": "Lisää pistevärin näyte", @@ -269,6 +270,7 @@ "Center": "Keskellä", "Change": "Muuta", "Change Component Mode": "Vaihda komponenttitilaa", + "Change Time": "Muuta aikaa", "Characters not allowed in file names (/ \\ : * ? \" < > |) become -; an existing name gets -1, -2….": "Tiedostonimissä kiellettyjä merkkejä (/ \\ : * ? \" < > |) korvataan merkillä -; olemassa oleva nimi saa lopun -1, -2….", "Charcoal": "Hiili", "Check All": "Valitse kaikki", @@ -338,7 +340,6 @@ "Close file": "Sulje tiedosto", "Close panel": "Sulje paneeli", "Cloudy": "Pilvinen", - "Collapse": "Tiivistä", "Collapse All Stacks": "Tiivistä kaikki pinot", "Collapse Stack": "Tiivistä pino", "Color": "Väri", @@ -430,6 +431,7 @@ "Create Smart Album from Filter…": "Luo älyalbumi suodattimesta…", "Create Smart Album…": "Luo älyalbumi…", "Create Stack": "Luo pino", + "Create Stacks": "Luo pinot", "Create Version": "Luo versio", "Create Version from Step": "Luo versio vaiheesta", "Create Virtual Copy": "Luo virtuaalikopio", @@ -444,6 +446,7 @@ "Crop, Rotate, Geometry": "Rajaus, kierto, geometria", "Cropped": "Rajattu", "Cross Process": "Ristiinkäsittely", + "Cull": "Karsi", "Culling": "Karsinta", "Curve": "Käyrä", "Curve channel": "Käyrän kanava", @@ -557,6 +560,7 @@ "Download Place Names (GeoNames)": "Lataa paikannimet (GeoNames)", "Download the SAM 3 Model?": "Ladataanko SAM 3 -malli?", "Downloaded and checked. Installing…": "Ladattu ja tarkistettu. Asennetaan…", + "The download failed": "Lataus epäonnistui", "Downloading model": "Ladataan mallia", "Downloading place names": "Ladataan paikannimiä", "Downloads": "Lataukset", @@ -587,6 +591,7 @@ "Edit Info": "Muokkaa tietoja", "Edit Keyword": "Muokkaa avainsanaa", "Edit Keyword Set": "Muokkaa avainsanajoukkoa", + "Edit Keywords": "Muokkaa avainsanoja", "Edit Keyword Tag": "Muokkaa avainsanatunnistetta", "Edit Keyword Tag…": "Muokkaa avainsanatunnistetta…", "Edit Label Names": "Muokkaa merkintöjen nimiä", @@ -610,6 +615,7 @@ "Effects": "Tehosteet", "Empty Recently Deleted": "Tyhjennä Äskettäin poistetut", "Enable Lens Corrections": "Ota objektiivikorjaukset käyttöön", + "Enable Painting": "Ota maalaus käyttöön", "Enable Profile Corrections": "Ota profiilikorjaukset käyttöön", "End": "Loppu", "End Interaction": "Lopeta vuorovaikutus", @@ -908,7 +914,7 @@ "Import from Folder…": "Tuo kansiosta…", "Import new photos": "Tuo uudet kuvat", "Import photos to get started": "Aloita tuomalla kuvia", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Tuo kuvia valitsemalla Tiedosto → Tuo kuvia… (Cmd+Shift+I) tai pudota ne tähän", + "Import photos with File → Import Photos…, or drop them here": "Tuo kuvia valitsemalla Tiedosto → Tuo kuvia… tai pudota ne tähän", "Imported": "Tuotu", "Imported Photos": "Tuodut kuvat", "Importing": "Tuodaan", @@ -988,6 +994,7 @@ "Keyword Suggestions": "Avainsanaehdotukset", "Keyword Tag Options": "Avainsanatunnisteen asetukset", "Keyword to paint": "Maalattava avainsana", + "Type a keyword to paint in the Keywords panel": "Kirjoita maalattava avainsana Avainsanat-paneeliin", "Keywords": "Avainsanat", "Keywords & People": "Avainsanat ja henkilöt", "Keywords (K)": "Avainsanat (K)", @@ -1040,6 +1047,9 @@ "LightCraft could not start": "LightCraft ei voinut käynnistyä", "LightCraft couldn't find where to keep your library.": "LightCraft ei löytänyt paikkaa kirjastosi säilytykselle.", "LightCraft couldn't open the library at": "LightCraft ei voinut avata kirjastoa kohteessa", + "There is no LightCraft library in this folder any more.": "Tässä kansiossa ei ole enää LightCraft-kirjastoa.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Kirjastoa ei löydy: se on siirretty tai nimetty uudelleen, tai sen asemaa tai verkkojakoa ei ole yhdistetty.", + "This folder can't be read:": "Tätä kansiota ei voi lukea:", "LightCraft does not know this model, so it assumed:": "LightCraft ei tunne tätä mallia, joten se oletti:", "LightCraft on GitHub": "LightCraft GitHubissa", "LightCraft stopped": "LightCraft pysähtyi", @@ -1497,6 +1507,12 @@ "Purple Saturation": "Violetin värikylläisyys", "Put New Keywords Inside": "Lisää uudet avainsanat sisään", "Put New Keywords Inside This Keyword": "Lisää uudet avainsanat tämän avainsanan sisään", + "Use This as Keyword Shortcut": "Käytä avainsanojen pikavalintana", + "Set Keyword Shortcut": "Aseta avainsanojen pikavalinta", + "Set Keyword Shortcut…": "Aseta avainsanojen pikavalinta…", + "Add or Remove Keyword Shortcut": "Lisää tai poista avainsanojen pikavalinta", + "Keyword Shortcut": "Avainsanojen pikavalinta", + "Part of the keyword shortcut": "Osa avainsanojen pikavalintaa", "Put the locations you removed from Local back (no files change)": "Palauta Paikallisesta poistamasi sijainnit (tiedostot eivät muutu)", "Quality": "Laatu", "Query Photos": "Kysele kuvia", @@ -1996,6 +2012,7 @@ "That includes the photos in the folders inside it.": "Tämä sisältää myös sen sisällä olevien kansioiden kuvat.", "That key can't be used as a shortcut": "Tätä näppäintä ei voi käyttää pikanäppäimenä", "The SAM 3 model is installed: Object and Describe masks are ready.": "SAM 3 -malli on asennettu: Kohde- ja Kuvaile-maskit ovat valmiita.", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Tunnisteet-painike näyttää mallin paikkamerkit, kuten {date} tai {seq}. Jokainen tiedosto nimetään levyllä uudelleen yhdessä XMP-sivutiedostonsa kanssa; jo käytetty nimi saa lopuksi -1, -2…", "The denoise model is installed and in use: the AI Denoise Amount slider under Detail now works": "Kohinanpoistomalli on asennettu ja käytössä: Tekoälykohinanpoiston Määrä-liukusäädin Tarkastelun alla toimii nyt", "The download didn't work:": "Lataus ei onnistunut:", "The ending screen, after the last photo.": "Lopetusnäyttö viimeisen kuvan jälkeen.", @@ -2320,6 +2337,7 @@ "Mask Pins": "Maskin nastat", "Photo Counts": "Kuvamäärät", "An import is running": "Tuonti on käynnissä", + "The photos are imported once it ends": "Kuvat tuodaan sen jälkeen", "An import is running. Drop photos when it has finished": "Tuonti on käynnissä. Pudota kuvat, kun se on valmis", "Close the open dialog to drop files here": "Sulje avoin valintaikkuna pudottaaksesi tiedostot tähän", "Close the open dialog, then drop the files again": "Sulje avoin valintaikkuna ja pudota tiedostot sitten uudelleen", @@ -2327,5 +2345,16 @@ "Drop to open the face model": "Pudota avataksesi kasvomallin", "Dropped Files": "Pudotetut tiedostot", "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", - "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta" + "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", + "Import Thumbnail Size": "Tuonnin pienoiskuvien koko", + "Face recognition is on": "Kasvojentunnistus on päällä", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Kasvojentunnistus on pois päältä. Ota se käyttöön, niin saat nimiehdotuksia ja näet samannäköiset kasvot yhdessä.", + "Turn on": "Ota käyttöön", + "Set up face recognition": "Määritä kasvojentunnistus", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Kasvojentunnistus tarvitsee mallin nimien ehdottamiseen: kertaluonteinen lataus Asetuksissa.", + "Turn on name suggestions": "Ota nimiehdotukset käyttöön", + "Set up name suggestions…": "Määritä nimiehdotukset…", + "Top bar": "Yläpalkki", + "Tool strip": "Työkalupalkki", + "Bottom bar": "Alapalkki" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e..fc46d653c6 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -36,10 +36,11 @@ "Build Standard-Sized Previews ({scope})": "Créer les aperçus de taille standard ({scope})", "Building previews for {} photos…": "Création des aperçus pour {} photos…", "Click {}:1": "Cliquer sur {}:1", + "Collapse {name}": "Réduire {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Espace colorimétrique : Rec. 2020 {curve} (AVIF HDR)", "Couldn't open the editor: {e}": "Impossible d’ouvrir l’éditeur : {e}", "Create {n} Virtual Copies": "Créer {n} copies virtuelles", - "Creates {} stacks from {} of {scope}": "Crée {} piles à partir de {} parmi {scope}", + "Creates {stacks} stack{} from {photos} of {scope}": "Crée {stacks} pile{} à partir de {photos} parmi {scope}", "Decoder: {reason}": "Décodeur : {reason}", "Delete \"{label}\"": "Supprimer « {label} »", "Delete \"{label}\" (and the mask)": "Supprimer « {label} » (et le masque)", @@ -49,6 +50,7 @@ "Done ({what}): {done} photo{plural}": "Terminé ({what}) : {done} photo{plural}", "Duplicate \"{label}\"": "Dupliquer « {label} »", "Example: {example}": "Exemple : {example}", + "Expand {name}": "Développer {name}", "Exported {n} photo{}": "{n} photo{} exportée(s)", "Exported {ok} of {total} photo{}": "{ok} photo{} exportée(s) sur {total}", "Exported {} point curve preset{}": "{} préréglage{} de courbe à points exporté(s)", @@ -61,6 +63,7 @@ "Healed {n} dust spot{}": "{n} tache{} de poussière corrigée(s)", "Import cancelled · {} photo{} added": "Importation annulée · {} photo{} ajoutée(s)", "Import failed: {e}": "Échec de l’importation : {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importez des photos avec Fichier → Importer des photos… ({}) ou déposez-les ici", "Import warnings ({n}):\n{warnings}": "Avertissements d’importation ({n}) :\n{warnings}", "Imported {n} point curve preset{}": "{n} préréglage{} de courbe à points importé(s)", "Imported {n} preset{}": "{n} préréglage{} importé(s)", @@ -115,6 +118,7 @@ "Rendering on the CPU: {why}": "Rendu sur le processeur : {why}", "Replace {} with:": "Remplacer {} par :", "Reset {name}": "Réinitialiser {name}", + "{name} value": "{name} : valeur", "Reset {} Channel": "Réinitialiser le canal {}", "Restore {}": "Restaurer {}", "Restore {} Photo{}": "Restaurer {} photo{}", @@ -163,7 +167,7 @@ "{n} photo{}": "{n} photo{}", "{n} photo{} match · updates automatically as photos change": "{n} photo{} correspondante(s) · mise à jour automatique lorsque les photos changent", "{n} photo{} now · updates automatically as photos change": "{n} photo{} actuellement · mise à jour automatique lorsque les photos changent", - "{n} selected photos · {pages} pages": "{n} photos sélectionnées · {pages} pages", + "{n} selected photo{} · {pages} page{}": "{n} photo{0} sélectionnée{0} · {pages} page{1}", "{pid} (missing)": "{pid} (manquant)", "{sel_n} selected · {counted}": "{sel_n} sélectionné(s) · {counted}", "{stage}… {:.0}%": "{stage}… {:.0} %", @@ -227,6 +231,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "« {parent} » contient déjà « {name} ». Fusionner les deux ?", "There is a “{name}” at the top level already. Merge the two?": "Il existe déjà « {name} » au premier niveau. Fusionner les deux ?", "Added “{keyword}” to {n} photo{}": "« {keyword} » ajouté à {n} photo{}", + "Add Keyword “{keywords}”": "Ajouter le mot-clé « {keywords} »", "On {have} of {of} selected photos": "Sur {have} des {of} photos sélectionnées", "Remove “{name}”": "Retirer « {name} »", "There is a keyword set “{name}” already": "Un jeu de mots-clés « {name} » existe déjà", @@ -248,6 +253,7 @@ "{what} merge cancelled": "Fusion {what} annulée", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Photos locales ignorées : {n}{0:.0} — les albums contiennent des photos de la bibliothèque (ajoutez-les d’abord à Mes photos)", "New Folder in “{name}”": "Nouveau dossier dans « {name} »", + "Created folder “{name}” in “{parent}”": "Dossier « {name} » créé dans « {parent} »", "Moved {} photo(s)": "{} photo(s) déplacée(s)", "not added to Apple Photos: {e}": "non ajouté à Apple Photos : {e}", "{n} added to Apple Photos album “{album}”": "{n} ajouté(s) à l'album Apple Photos « {album} »", @@ -269,6 +275,7 @@ "{n} originals opened in the other editor": "{n} originaux ouverts dans l’autre éditeur", "· {in_source} identical copies": "· {in_source} copies identiques", "{count} more warnings.": "{count} avertissements supplémentaires.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} photos du catalogue sont dans « Supprimés récemment » de cette photothèque et y restent ; restaurez-les depuis « Supprimés récemment » pour les voir.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} images du catalogue n’ont pas été importées, car leurs entrées dans le catalogue sont incomplètes.", "{photos} catalog records processed; {collections} collections.": "{photos} entrées du catalogue traitées ; {collections} collections.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originaux sont manquants. Leurs entrées de catalogue sont disponibles ; utilisez Rechercher les photos manquantes pour rétablir les liens.", @@ -281,7 +288,7 @@ "Skipped {problem}": "Ignoré : {problem}", "…and {more} more": "…et {more} de plus", "Template preview: {name}": "Aperçu du modèle : {name}", - "{n} photos in view · {slides} slides · {time}": "{n} photos affichées · {slides} diapositives · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "{n} photo{0} affichée{0} · {slides} diapositive{1} · {time}", "{n} pages": "{n} pages", "{n} JPEG files": "{n} fichiers JPEG", "{s} s of AV1 video": "{s} s de vidéo AV1", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "Impossible de lire {name} : {e}", "Added {n} photo{}": "{n} photo{} ajoutée(s)", "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", - "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})" + "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})", + "Photo: {name}": "Photo : {name}", + "Panel layout could not be restored: {error}": "La disposition des panneaux n'a pas pu être restaurée : {error}", + "Panel move was not applied: {error}": "Le déplacement du panneau n'a pas été appliqué : {error}", + "{name} is installed": "{name} est installé", + "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda..e032cf52f3 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -42,6 +42,7 @@ "Add to Local": "Ajouter à Local", "Add to My Photos": "Ajouter à Mes photos", "Can't be moved here": "Impossible de les déplacer ici", + "Import photos with File → Import Photos…, or drop them here": "Importez des photos avec Fichier → Importer des photos… ou déposez-les ici", "This row covers more than one disk: drop on a folder inside it": "Cette ligne couvre plusieurs disques : déposez-les sur un dossier qu’elle contient", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Les photos locales ne sont pas encore dans la bibliothèque : Ajouter à Mes photos d’abord, puis déplacez-les", "Add to Selected Photos": "Ajouter aux photos sélectionnées", @@ -117,6 +118,7 @@ "Auto-Tag Photos from Tracklog": "Géolocaliser automatiquement les photos à partir d'une trace GPS", "Auto-Tag from Tracklog": "Géolocaliser automatiquement à partir d'une trace GPS", "Auto-Tag from Tracklog…": "Géolocaliser automatiquement à partir d'une trace GPS…", + "Add Locations": "Ajouter les lieux", "Automatic": "Automatique", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Automatique calcule la vue Détail à la taille affichée, jusqu'aux pixels de la photo elle-même. Choisissez une taille pour la plafonner : plus petit, c'est plus rapide.", "Automatically Write Changes into XMP": "Écrire automatiquement les modifications dans XMP", @@ -238,7 +240,6 @@ "Close all": "Tout fermer", "Close file": "Fermer le fichier", "Cloudy": "Nuageux", - "Collapse": "Réduire", "Collapse All Stacks": "Réduire toutes les piles", "Collapse Stack": "Réduire la pile", "Color": "Couleur", @@ -333,6 +334,9 @@ "Crop, Rotate, Geometry": "Recadrage, rotation, géométrie", "Cross Process": "Traitement croisé", "Culling": "Tri", + "Cull": "Trier", + "Create Stacks": "Créer les piles", + "Change Time": "Changer l'heure", "Curve": "Courbe", "Custom": "Personnalisé", "Custom template…": "Modèle personnalisé…", @@ -451,6 +455,7 @@ "Effects": "Effets", "Empty Recently Deleted": "Vider Supprimées récemment", "Enable Lens Corrections": "Activer les corrections d'objectif", + "Enable Painting": "Activer le pinceau", "Enable Profile Corrections": "Activer les corrections de profil", "End Interaction": "Terminer l'interaction", "English": "Anglais", @@ -490,6 +495,7 @@ "Faded Matte": "Mat délavé", "Faded Slide": "Diapositive délavée", "Faded Urban": "Urbain délavé", + "Favorite": "Favori", "Favorite Preset": "Préréglage favori", "Favorite Profile": "Profil favori", "Favorites": "Favoris", @@ -673,7 +679,6 @@ "Import as new": "Importer comme nouvelles", "Import from Device": "Importer depuis un appareil", "Import from Folder…": "Importer depuis un dossier…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importez des photos avec Fichier → Importer des photos… (Cmd+Maj+I) ou déposez-les ici", "Imported": "Importées", "Imported Photos": "Photos importées", "Importing": "Importation en cours", @@ -724,6 +729,7 @@ "Keyword Sets": "Jeux de mots-clés", "Keyword Suggestions": "Suggestions de mots-clés", "Keyword to paint": "Mot-clé à appliquer", + "Type a keyword to paint in the Keywords panel": "Saisissez un mot-clé à appliquer dans le panneau Mots-clés", "Keywords": "Mots-clés", "Keywords (K)": "Mots-clés (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "Les mots-clés que vous ajoutez apparaissent ici ; ⌥1–⌥9 les appliquent.", @@ -759,6 +765,8 @@ "LightCraft could not start": "LightCraft n'a pas pu démarrer", "LightCraft couldn't find where to keep your library.": "LightCraft n'a pas trouvé où conserver votre bibliothèque.", "LightCraft couldn't open the library at": "LightCraft n'a pas pu ouvrir la bibliothèque à l'emplacement", + "There is no LightCraft library in this folder any more.": "Ce dossier ne contient plus de bibliothèque LightCraft.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "La bibliothèque est introuvable : elle a été déplacée ou renommée, ou son disque ou son partage réseau n'est pas connecté.", "LightCraft on GitHub": "LightCraft sur GitHub", "LightCraft website": "Site web de LightCraft", "LightCraft — Second Window": "LightCraft : deuxième fenêtre", @@ -1454,6 +1462,7 @@ "Table": "Tableau", "Tags": "Balises", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Balises : voir Balises à côté du modèle. Les fichiers sont renommés sur le disque (avec leurs fichiers annexes XMP) ; les noms existants reçoivent -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Le bouton Balises liste les éléments utilisables dans le modèle, comme {date} ou {seq}. Chaque fichier est renommé sur le disque avec son fichier annexe XMP ; un nom déjà pris reçoit -1, -2…", "Take a snapshot": "Créer un instantané", "Targeted Adjustment": "Réglage ciblé", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Réglage ciblé : faites glisser vers le haut/bas sur la photo pour ajuster les couleurs à cet endroit", @@ -1705,6 +1714,7 @@ "Denoise Settings": "Réglages de débruitage", "Denoise all photos with an Amount": "Débruiter toutes les photos ayant une Quantité", "Downloaded and checked. Installing…": "Téléchargé et vérifié. Installation en cours…", + "The download failed": "Le téléchargement a échoué", "Failed its last test": "Échec lors de son dernier test", "Graphics card": "Carte graphique", "I have read these terms and accept them for my own use": "J'ai lu ces conditions et je les accepte pour mon propre usage", @@ -1870,6 +1880,12 @@ "No photo has it; the keywords below it go too.": "Aucune photo ne l'a ; les mots-clés qu'il contient sont aussi supprimés.", "Edit Keyword Tag…": "Modifier le mot-clé…", "Put New Keywords Inside This Keyword": "Placer les nouveaux mots-clés dans celui-ci", + "Use This as Keyword Shortcut": "Utiliser comme raccourci de mots-clés", + "Set Keyword Shortcut": "Définir le raccourci de mots-clés", + "Set Keyword Shortcut…": "Définir le raccourci de mots-clés…", + "Add or Remove Keyword Shortcut": "Ajouter ou retirer le raccourci de mots-clés", + "Keyword Shortcut": "Raccourci de mots-clés", + "Part of the keyword shortcut": "Fait partie du raccourci de mots-clés", "Purge Unused Keywords": "Purger les mots-clés inutilisés", "Delete Keyword…": "Supprimer le mot-clé…", "Drop here for the top level": "Déposez ici pour le niveau supérieur", @@ -1881,6 +1897,7 @@ "& Containing": "et parents", "Edit Set…": "Modifier le jeu…", "Edit Keyword Set": "Modifier le jeu de mots-clés", + "Edit Keywords": "Modifier les mots-clés", "Keywords (⌥1–⌥9)": "Mots-clés (⌥1–⌥9)", "A keyword set needs a name": "Un jeu de mots-clés doit avoir un nom", "Save as a new set": "Enregistrer comme nouveau jeu", @@ -2353,6 +2370,7 @@ "Dropped Files": "Fichiers déposés", "Import dropped files without review": "Importer les fichiers déposés sans vérification", "An import is running": "Une importation est en cours", + "The photos are imported once it ends": "Les photos seront importées ensuite", "An import is running. Drop photos when it has finished": "Une importation est en cours. Déposez les photos quand elle sera terminée", "Finish Lightroom catalog import before adding photos": "Terminez l'importation du catalogue Lightroom avant d'ajouter des photos", "The library is empty: the catalog's photos, collections and edits become its first.": "La bibliothèque est vide : les photos, collections et retouches du catalogue seront les premières.", @@ -2390,5 +2408,1170 @@ "Checking recent libraries": "Vérification des bibliothèques récentes", "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", - "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :" + "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", + "Face recognition is on": "La reconnaissance des visages est activée", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "La reconnaissance des visages est désactivée. Activez-la pour obtenir des suggestions de noms et voir ensemble les visages qui se ressemblent.", + "Turn on": "Activer", + "Set up face recognition": "Configurer la reconnaissance des visages", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "La reconnaissance des visages a besoin d'un modèle pour suggérer des noms : un téléchargement unique, dans Réglages.", + "Turn on name suggestions": "Activer les suggestions de noms", + "Set up name suggestions…": "Configurer les suggestions de noms…", + "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "Une diapositive reste affichée pendant sa durée, fondu d'entrée compris. Un fondu de 0 enchaîne par une coupe franche.", + "Add Print Cell": "Ajouter une cellule d'impression", + "Add a Face Recognition Model": "Ajouter un modèle de reconnaissance faciale", + "Add a cell": "Ajouter une cellule", + "Add a model file…": "Ajouter un fichier de modèle…", + "Adding photos…": "Ajout des photos…", + "Already installed. Installing again is harmless.": "Déjà installé. Réinstaller est sans danger.", + "Also the masks of the same name on the other selected photos": "Aussi les masques du même nom sur les autres photos sélectionnées", + "Apple Photos Imports": "Importations Apple Photos", + "Apply Mask Effect": "Appliquer l'effet de masque", + "Apply Print Template": "Appliquer le modèle d'impression", + "Apply Slideshow Template": "Appliquer le modèle de diaporama", + "Apply to All Masks": "Appliquer à tous les masques", + "Arrange Print Cell": "Réordonner la cellule d'impression", + "Auto Layout": "Disposition automatique", + "Background Tasks": "Tâches d'arrière-plan", + "Burst: how alike (loose … strict)": "Rafale : degré de ressemblance (souple … strict)", + "Burst: shots at most this far apart": "Rafale : écart maximal entre les prises de vue", + "Camera & Lens": "Appareil photo et objectif", + "Cancel Background Task": "Annuler la tâche d'arrière-plan", + "Choose Layout Image…": "Choisir l'image de mise en page…", + "Choose Monitor Profile": "Choisir le profil du moniteur", + "Choose Profile…": "Choisir un profil…", + "Choose a group": "Choisir un groupe", + "Choose at least one setting to include": "Choisissez au moins un réglage à inclure", + "Clear Print Layout": "Effacer la mise en page d'impression", + "Click a cell to move, resize or arrange it": "Cliquez sur une cellule pour la déplacer, la redimensionner ou la réordonner", + "Click to hide clipping warnings for shadows and highlights.": "Cliquez pour masquer les avertissements d'écrêtage des ombres et des hautes lumières.", + "Click to name this face": "Cliquez pour nommer ce visage", + "Click to show clipping warnings for shadows and highlights.": "Cliquez pour afficher les avertissements d'écrêtage des ombres et des hautes lumières.", + "Close a dialog by clicking outside it": "Fermer une boîte de dialogue en cliquant à l'extérieur", + "Color Overlay": "Incrustation de couleur", + "Color Overlay on B&W": "Incrustation de couleur sur N&B", + "Color space: Rec. 2020 HLG (HDR AVIF)": "Espace colorimétrique : Rec. 2020 HLG (AVIF HDR)", + "Color wheel": "Roue chromatique", + "Combine with the existing person": "Combiner avec la personne existante", + "Contact Sheet PDF…": "PDF de planche contact…", + "Copy Settings…": "Copier les réglages…", + "Create Keyword": "Créer le mot-clé", + "Curve channel": "Canal de la courbe", + "Cycle Flag": "Parcourir les drapeaux", + "Cycle Tool Overlay": "Parcourir les incrustations d'outil", + "Decrease Flag Status": "Réduire le statut du drapeau", + "Decrease Grid Thumbnail Size": "Réduire la taille des miniatures de la grille", + "Delete Cell": "Supprimer la cellule", + "Delete Mask Effect": "Supprimer l'effet de masque", + "Delete Print Cell": "Supprimer la cellule d'impression", + "Delete Print Template": "Supprimer le modèle d'impression", + "Delete Slideshow Template": "Supprimer le modèle de diaporama", + "Delete…": "Supprimer…", + "Display": "Écran", + "Display Profile": "Profil d'écran", + "Display profile not used": "Profil d'écran non utilisé", + "Drag to set hue and saturation. Hold Shift to keep the hue, Cmd/Ctrl to keep the saturation, Alt/Option to fine-adjust. Double-click to reset.": "Faites glisser pour régler la teinte et la saturation. Maintenez Maj pour conserver la teinte, Cmd/Ctrl pour conserver la saturation, Alt/Option pour un réglage fin. Double-cliquez pour réinitialiser.", + "Duplicate Mask Effect": "Dupliquer l'effet de masque", + "Edit In": "Modifier dans", + "Edit Keyword": "Modifier le mot-clé", + "Edit in HDR: highlights above SDR white, for HDR exports and displays": "Retoucher en HDR : hautes lumières au-delà du blanc SDR, pour les exportations et les écrans HDR", + "Edit in Other Editor": "Modifier dans un autre éditeur", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Modifier dans un autre éditeur (⌥⌘E) ouvre la copie dans cette application (un nom d'application sous macOS, un chemin de programme ailleurs).", + "End Slideshow": "Terminer le diaporama", + "Enter to confirm, Esc to cancel": "Entrée pour confirmer, Échap pour annuler", + "Export Contact Sheet PDF": "Exporter le PDF de planche contact", + "Export Effect Presets": "Exporter les préréglages d'effets", + "Export Effect Presets…": "Exporter les préréglages d'effets…", + "Export Mask Effects": "Exporter les effets de masque", + "External Editing": "Retouche externe", + "Face Models on the GPU": "Modèles de visages sur le GPU", + "Face models (ONNX)": "Modèles de visages (ONNX)", + "Fade": "Fondu", + "Fade duration": "Durée du fondu", + "Favorite Mask Effect": "Effet de masque favori", + "Filters": "Filtres", + "Find Blemishes": "Rechercher les imperfections", + "Found automatically": "Trouvé automatiquement", + "Grid: add the next photo to the selection": "Grille : ajouter la photo suivante à la sélection", + "Grid: add the previous photo to the selection": "Grille : ajouter la photo précédente à la sélection", + "Grid: first photo of the view": "Grille : première photo de la vue", + "Grid: last photo of the view": "Grille : dernière photo de la vue", + "Group (optional)": "Groupe (facultatif)", + "HDR": "HDR", + "HDR Headroom": "Marge HDR", + "Hide this wheel's effect": "Masquer l'effet de cette roue", + "Highlighted: sliders this mask changes. Sliders left out stay as they are when the preset is applied.": "En surbrillance : curseurs que ce masque modifie. Les curseurs non retenus restent inchangés quand le préréglage est appliqué.", + "ICC Profiles": "Profils ICC", + "Image on Black": "Image sur noir", + "Image on White": "Image sur blanc", + "Import Mask Effects": "Importer des effets de masque", + "Import Slideshow Template": "Importer un modèle de diaporama", + "Include Amount": "Inclure la quantité", + "Include brush size, feather and flow": "Inclure la taille, le contour progressif et le flux du pinceau", + "Include selected photos": "Inclure les photos sélectionnées", + "Increase Flag Status": "Augmenter le statut du drapeau", + "Increase Grid Thumbnail Size": "Augmenter la taille des miniatures de la grille", + "It is not a denoise model LightCraft understands": "Ce n'est pas un modèle de réduction du bruit pris en charge par LightCraft", + "Keyword Info": "Infos sur le mot-clé", + "LUT-based": "Basé sur LUT", + "Layout Image Matte": "Mat de l'image de mise en page", + "Layout Image Opacity": "Opacité de l'image de mise en page", + "Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.": "Gauche : la plage standard (SDR) jusqu'au blanc SDR. Droite : la plage HDR, une bande par diaphragme au-dessus du blanc SDR (la ligne orange : la marge HDR). Quand Visualiser la plage HDR est activé, les bandes en prennent les couleurs.", + "LightCraft Effect Presets": "Préréglages d'effets LightCraft", + "Loupe Info 1": "Infos de la loupe 1", + "Loupe Info 2": "Infos de la loupe 2", + "Loupe Overlay": "Incrustation de la loupe", + "Loupe View": "Vue Loupe", + "Lower it when a panning or moving burst splits into several groups.": "Diminuez-la quand une rafale en panoramique ou en mouvement se scinde en plusieurs groupes.", + "M50, R100 and R8. CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100 et R8. Les fichiers CR3 que le décodeur ne sait pas encore lire s'ouvrent toujours à partir de leur JPEG intégré, comme avant.", + "Manage Effect Presets…": "Gérer les préréglages d'effets…", + "Manage Presets…": "Gérer les préréglages…", + "Managed by Printer (Adobe RGB)": "Géré par l'imprimante (Adobe RGB)", + "Managed by Printer (sRGB)": "Géré par l'imprimante (sRGB)", + "Mask": "Masque", + "Mask Effect Presets": "Préréglages d'effets de masque", + "Masks keep their sliders. Export presets first to keep a copy.": "Les masques conservent leurs curseurs. Exportez d'abord les préréglages pour en garder une copie.", + "Matrix/TRC": "Matrice/TRC", + "Monitor profile": "Profil du moniteur", + "Move Keyword": "Déplacer le mot-clé", + "Move Mask Effect to Group": "Déplacer l'effet de masque vers un groupe", + "Move Print Cell": "Déplacer la cellule d'impression", + "Move Print Cell to Page": "Déplacer la cellule d'impression vers la page", + "Move to Group…": "Déplacer vers le groupe…", + "My Preset": "Mon préréglage", + "Name the preset": "Nommez le préréglage", + "New Print Page": "Nouvelle page d'impression", + "New group — Return": "Nouveau groupe — Entrée", + "New spot (Return adds it here)": "Nouvelle tache (Entrée l'ajoute ici)", + "Next History Step": "Étape d'historique suivante", + "Next Slide": "Diapositive suivante", + "Next page": "Page suivante", + "Nikon High Efficiency NEF (HE / HE★) uses intoPIX TicoRAW compression. LightCraft does not currently have a license for this codec, so only the camera's embedded JPEG preview is available, not the raw sensor data. To edit raw data, shoot Lossless compressed NEF or convert existing HE files to DNG using a licensed converter.": "Le NEF Nikon High Efficiency (HE / HE★) utilise la compression TicoRAW d'intoPIX. LightCraft ne dispose pas actuellement de licence pour ce codec : seul l'aperçu JPEG intégré à l'appareil est disponible, pas les données brutes du capteur. Pour retoucher les données RAW, photographiez en NEF compressé sans perte ou convertissez les fichiers HE existants en DNG avec un convertisseur sous licence.", + "No Matte": "Sans mat", + "No change": "Aucun changement", + "No clipping detected in this preview.": "Aucun écrêtage détecté dans cet aperçu.", + "No effect matches": "Aucun effet ne correspond", + "No effect presets yet": "Aucun préréglage d'effet pour l'instant", + "No faces by that name": "Aucun visage portant ce nom", + "No horizon or vertical lines to level by": "Aucun horizon ni ligne verticale pour redresser", + "No named people yet. Name the faces below to start.": "Aucune personne nommée pour l'instant. Nommez les visages ci-dessous pour commencer.", + "No people yet": "Aucune personne pour l'instant", + "No person by that name": "Aucune personne de ce nom", + "No unnamed faces. Faces found in your photos appear here until you name them.": "Aucun visage sans nom. Les visages trouvés dans vos photos apparaissent ici tant que vous ne les avez pas nommés.", + "None (the display is treated as sRGB)": "Aucun (l'écran est traité comme sRGB)", + "One photo fills each page inside the margins.": "Une photo remplit chaque page à l'intérieur des marges.", + "Open Original in Other Editor (RAW, no copy)": "Ouvrir l'original dans un autre éditeur (RAW, sans copie)", + "Open Settings": "Ouvrir les réglages", + "Other editor": "Autre éditeur", + "Overlay color": "Couleur de l'incrustation", + "Page": "Page", + "Page Options": "Options de page", + "Pause / Resume Slideshow": "Mettre en pause / reprendre le diaporama", + "Photo Above": "Photo au-dessus", + "Photo Below": "Photo en dessous", + "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Photo → Modifier dans → Modifier dans PhotoCraft (⇧⌘E, ou clic droit sur une photo) calcule une copie avec vos retouches, l'empile avec l'original et l'ouvre dans PhotoCraft. Enregistrez-y votre travail : la copie se met à jour ici. Au format PSD, PhotoCraft enregistre directement dans ce fichier. Laissez l'emplacement vide, sauf si vous utilisez une copie portable.", + "PhotoCraft": "PhotoCraft", + "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Les photos sont affichées à travers le profil ICC de votre moniteur : les couleurs sont donc justes sur les écrans à large gamme de couleurs et calibrés, et la vue Détail utilise toute la gamme de couleurs de l'écran. L'histogramme, les caches d'aperçus et les exportations ne sont pas affectés.", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Les photos restent dans Toutes les photos. Supprimer un dossier supprime aussi ses albums. Vous pouvez annuler cette action.", + "Previous History Step": "Étape d'historique précédente", + "Previous Slide": "Diapositive précédente", + "Previous page": "Page précédente", + "Primaries (x, y)": "Primaires (x, y)", + "Print Settings": "Réglages d'impression", + "Print Templates": "Modèles d'impression", + "Print to PDF": "Imprimer en PDF", + "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "Les profils attribués dans les réglages de couleur de votre bureau se trouvent généralement dans ~/.local/share/icc.", + "Progressive": "Progressif", + "Put New Keywords Inside": "Placer les nouveaux mots-clés à l'intérieur", + "Read Focus Points in the Background": "Lire les points de mise au point en arrière-plan", + "Reading photos…": "Lecture des photos…", + "Recheck Preview-Only Raws": "Revérifier les RAW en aperçu seul", + "Remove Folder Color Label": "Retirer l'étiquette de couleur du dossier", + "Remove region": "Retirer la zone", + "Rename Mask Effect": "Renommer l'effet de masque", + "Rename Mask Effect Group": "Renommer le groupe d'effets de masque", + "Rename Person": "Renommer la personne", + "Rename Person…": "Renommer la personne…", + "Rename Slideshow Template": "Renommer le modèle de diaporama", + "Renders the next slides while the current one is up, so fades never wait. Off: each slide renders when it is due (less memory and work).": "Prépare les diapositives suivantes pendant que celle en cours est affichée, pour que les fondus n'attendent jamais. Désactivé : chaque diapositive est calculée au moment voulu (moins de mémoire et de travail).", + "Reset Print Settings": "Réinitialiser les réglages d'impression", + "Reset Sliders": "Réinitialiser les curseurs", + "Resize Print Cell": "Redimensionner la cellule d'impression", + "Resize region": "Redimensionner la zone", + "SDR": "SDR", + "SDR Brightness": "Luminosité SDR", + "SDR Clarity": "Clarté SDR", + "SDR Contrast": "Contraste SDR", + "SDR Highlights": "Hautes lumières SDR", + "SDR Shadows": "Ombres SDR", + "SDR Whites": "Blancs SDR", + "Save Current Settings as New Effect Preset…": "Enregistrer les réglages actuels comme nouveau préréglage d'effet…", + "Save Current Settings as New Preset…": "Enregistrer les réglages actuels comme nouveau préréglage…", + "Save Mask Effect": "Enregistrer l'effet de masque", + "Save Print Template": "Enregistrer le modèle d'impression", + "Save Slideshow Template": "Enregistrer le modèle de diaporama", + "Scan Folder for Changes": "Rechercher les changements dans le dossier", + "Search effects": "Rechercher des effets", + "Select Only Active Photo": "Sélectionner uniquement la photo active", + "Select a mask to apply or update presets.": "Sélectionnez un masque pour appliquer ou mettre à jour des préréglages.", + "Select all": "Tout sélectionner", + "Select none": "Ne rien sélectionner", + "Set Effect for New Masks": "Définir l'effet des nouveaux masques", + "Set Folder Color Label": "Définir l'étiquette de couleur du dossier", + "Set Print Cell Photo": "Définir la photo de la cellule d'impression", + "Set Print Settings": "Définir les réglages d'impression", + "Show / hide": "Afficher / masquer", + "Show Info Overlay": "Afficher l'incrustation d'infos", + "Show Layout Image": "Afficher l'image de mise en page", + "Show in Compare": "Afficher dans Comparer", + "Show mask": "Afficher le masque", + "Show photos": "Afficher les photos", + "Show this wheel's effect": "Afficher l'effet de cette roue", + "Slide duration": "Durée de la diapositive", + "Slideshow Export Status": "État de l'exportation du diaporama", + "Slideshow Layout Settings": "Réglages de disposition du diaporama", + "Slideshow Options…": "Options du diaporama…", + "Slideshow Overlay Settings": "Réglages des incrustations du diaporama", + "Slideshow Playback Settings": "Réglages de lecture du diaporama", + "Slideshow Slide Preview": "Aperçu de diapositive du diaporama", + "Slideshow Title Settings": "Réglages des titres du diaporama", + "Slideshow in the View menu plays the photos in view from the selected one. These settings are saved with the library.": "Diaporama, dans le menu Affichage, lit les photos de la vue à partir de la photo sélectionnée. Ces réglages sont enregistrés avec la bibliothèque.", + "Targeted adjustment on: drag up or down on the photo · Esc to stop": "Réglage ciblé activé : faites glisser vers le haut ou le bas sur la photo · Échap pour arrêter", + "Template name": "Nom du modèle", + "The layout image can't be shown": "L'image de mise en page ne peut pas être affichée", + "Their photos in the grid": "Leurs photos dans la grille", + "This page setup is not valid": "Cette mise en page n'est pas valide", + "Thumbnail size": "Taille des vignettes", + "Import Thumbnail Size": "Taille des vignettes d’importation", + "Title bar": "Barre de titre", + "To hand this editor the original file itself instead (the raw, without a copy: DxO PhotoLab, for example), right-click a photo → Edit In → Open Original in Other Editor (RAW, no copy).": "Pour confier plutôt à cet éditeur le fichier original lui-même (le RAW, sans copie : DxO PhotoLab, par exemple), faites un clic droit sur une photo → Modifier dans → Ouvrir l'original dans un autre éditeur (RAW, sans copie).", + "Tool Overlay": "Incrustation d'outil", + "Tool Overlay: Always": "Incrustation d'outil : toujours", + "Tool Overlay: Auto": "Incrustation d'outil : auto", + "Tool Overlay: Never": "Incrustation d'outil : jamais", + "Tool Overlay: Selected": "Incrustation d'outil : sélectionné", + "Ungrouped": "Sans groupe", + "Unknown date": "Date inconnue", + "Unnamed face": "Visage sans nom", + "Update Mask Effect": "Mettre à jour l'effet de masque", + "Update Slideshow Template": "Mettre à jour le modèle de diaporama", + "Update to Current Process": "Mettre à jour vers le traitement actuel", + "Use Defaults": "Utiliser les valeurs par défaut", + "Use Screen Profile": "Utiliser le profil de l'écran", + "Use sRGB": "Utiliser sRGB", + "View Options": "Options d'affichage", + "View Options…": "Options d'affichage…", + "View → View Options chooses the lines Info 1 and Info 2 show.": "Affichage → Options d'affichage choisit les lignes que montrent Infos 1 et Infos 2.", + "Visualize HDR": "Visualiser le HDR", + "When pins show on the photo (Shift+H cycles)": "Quand les épingles s'affichent sur la photo (Maj+H pour parcourir)", + "White on Black": "Blanc sur noir", + "Width × Height": "Largeur × hauteur", + "Write Waiting XMP Sidecars": "Écrire les fichiers annexes XMP en attente", + "cells": "cellules", + "cells overlap": "des cellules se chevauchent", + "current edits": "retouches actuelles", + "or drop a .onnx file on the window": "ou déposez un fichier .onnx sur la fenêtre", + "size": "taille", + "source": "source", + "this screen's profile": "le profil de cet écran", + "★ Favorites": "★ Favoris", + "\"24.0-70.0 mm f/2.8\". Those cameras don't write a lens name, so the lens field was empty and you couldn't filter or": "« 24.0-70.0 mm f/2.8 ». Ces appareils n'écrivent pas de nom d'objectif : le champ était vide et il était impossible de filtrer ou de", + "\"Albums\" header takes it back to the top level; Esc cancels; holding a dragged album or photos near the top or bottom edge of the sidebar scrolls it). Drop on the top or bottom half of another album,": "en-tête « Albums » le remet au premier niveau ; Échap annule ; maintenir un album ou des photos glissés près du bord haut ou bas de la barre latérale la fait défiler). Déposez sur la moitié haute ou basse d'un autre album,", + "\"Canon CRX adaptive QP value 172\" or \"175\". They now decode from the sensor data. Photos imported before this": "« Canon CRX adaptive QP value 172 » ou « 175 ». Ils se décodent désormais à partir des données du capteur. Les photos importées avant cela", + "\"File exists\".": "« File exists ».", + "\"HEIC/HEIF support isn't included in this build\" for each `.heic`/`.heif` at import.": "« HEIC/HEIF support isn't included in this build » pour chaque `.heic`/`.heif` à l'importation.", + "\"If file exists\" works per folder as usual, and an original is never written over.": "« Si le fichier existe » fonctionne dossier par dossier comme d'habitude, et un original n'est jamais écrasé.", + "\"LightCraft stopped unexpectedly\" and why, instead of \"could not open its window\", and the next start renders": "« LightCraft s'est arrêté de façon inattendue » et pourquoi, au lieu de « impossible d'ouvrir sa fenêtre », et le démarrage suivant calcule les rendus", + "\"Rendering…\" on the photo": "« Rendu en cours… » sur la photo", + "#1236). The D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,": "#1236). Les D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,", + "#1440): a Sony α1 face reads 8 MB instead of 70 MB, an A7S III face about 1 MB instead of 24 MB, several times": "#1440) : un visage du Sony α1 lit 8 Mo au lieu de 70 Mo, un visage de l'A7S III environ 1 Mo au lieu de 24 Mo, plusieurs fois", + "#1447), or keeps the photo you had when the folder holds it. Before, the photo from the previous view stayed active:": "#1447), ou conserve la photo que vous aviez quand le dossier la contient. Auparavant, la photo de la vue précédente restait active :", + "(\"Failed to associate portal window with parent window\" in the portal's log): tiling compositors put it beside the": "(« Failed to associate portal window with parent window » dans le journal du portail) : les compositeurs en mosaïque la plaçaient à côté de", + "(Esc keeps the old angle; a decimal comma works too), or click the Straighten value; hovering any slider's value now says it can be typed.": "(Échap conserve l'ancien angle ; la virgule décimale fonctionne aussi), ou cliquez sur la valeur de Redresser ; survoler la valeur d'un curseur indique désormais qu'elle peut être saisie.", + "(Space, G, X, ⌫) and ⌘ shortcuts were not affected.": "(Espace, G, X, ⌫) et les raccourcis ⌘ n'étaient pas concernés.", + "(`album.setRules` takes `name`).": "(`album.setRules` accepte `name`).", + "(`id`, `parent?`, `before?`) and `album.sort`.": "(`id`, `parent?`, `before?`) et `album.sort`.", + "(`render in.raw -o out.jxl`). Quality as for JPEG, or Lossless; Effort (Fast / Normal) trades time for a": "(`render in.raw -o out.jxl`). Qualité comme pour le JPEG, ou Sans perte ; Effort (Rapide / Normal) échange du temps contre un", + "(`slideshow.exportStatus` for the result).": "(`slideshow.exportStatus` pour le résultat).", + "(checked on one CC0 iPhone 12 Pro ProRAW). Photos without mattes are unchanged.": "(vérifié sur un ProRAW CC0 d'iPhone 12 Pro). Les photos sans mattes sont inchangées.", + "(folders open on click) or finds them as you type part of a name or folder (↑ / ↓ and Enter to pick); albums that": "(les dossiers s'ouvrent au clic) ou les trouve pendant que vous saisissez une partie d'un nom d'album ou de dossier (↑ / ↓ et Entrée pour choisir) ; les albums qui", + "(issue #1455), up to 512 MP and 65,000 pixels on the long edge, as in Lightroom. When the full size needs more": "(ticket #1455), jusqu'à 512 Mpx et 65 000 pixels sur le grand côté, comme dans Lightroom. Quand la taille complète demande plus de", + "(issue #256): the correction the camera records in the file is applied under Lens Corrections ▸ Enable Profile": "(ticket #256) : la correction que l'appareil enregistre dans le fichier est appliquée sous Corrections de l'objectif → Activer les", + "(issue #706; before, the import skipped it as \"already in the library\" while the grid showed it deleted). The": "(ticket #706 ; auparavant, l'importation l'ignorait comme « déjà dans la bibliothèque » alors que la grille la montrait supprimée). La", + "(issue #735).": "(ticket #735).", + "(issue #782).": "(ticket #782).", + "(issues #187, #298). Importing files that are in Recently Deleted asks whether to leave them there, restore them": "(tickets #187, #298). Importer des fichiers qui sont dans Supprimées récemment demande s'il faut les y laisser, les restaurer", + "(its width over its height was 0 / 0, which stopped debug builds); it shows as a single pixel's colour.": "(son rapport largeur sur hauteur valait 0 / 0, ce qui arrêtait les builds de débogage) ; elle s'affiche avec la couleur d'un seul pixel.", + "(macOS, Windows, Linux, FreeBSD, Nix) now really are built with HEIC support; a build without it reports": "(macOS, Windows, Linux, FreeBSD, Nix) sont désormais réellement compilés avec la prise en charge du HEIC ; une version sans elle signale", + "(now 0.05 s). The scan looks up only the files it finds and the contents it reads, on its own thread.": "(désormais 0,05 s). L'analyse ne consulte que les fichiers qu'elle trouve et les contenus qu'elle lit, sur son propre fil.", + "(with their edits) or import them as new; the trash view's Photo menu has Empty Recently Deleted.": "(avec leurs retouches) ou les importer comme nouveaux ; le menu Photo de la vue corbeille propose Vider Supprimées récemment.", + "(~0.6 s per slider tick); now the list is saved only after it changes, and a slider tick takes ~2 ms.": "(~0,6 s par cran de curseur) ; désormais la liste n'est enregistrée qu'après un changement, et un cran de curseur prend ~2 ms.", + ")": ")", + "**Import Lightroom Catalog…** with that catalog, or Cancel. `lightcraft-cli --library` refuses those folders too.": "**Importer un catalogue Lightroom…** avec ce catalogue, ou Annuler. `lightcraft-cli --library` refuse aussi ces dossiers.", + "**JPEG:** numbered files (`Holiday-001.jpg`, `Holiday-002.jpg`…) in a new folder.": "**JPEG :** fichiers numérotés (`Holiday-001.jpg`, `Holiday-002.jpg`…) dans un nouveau dossier.", + "**PDF:** one page per slide at 1024, 1920 or 3840 pixels on the long side, at a JPEG quality you choose. Each page": "**PDF :** une page par diapositive à 1024, 1920 ou 3840 pixels sur le grand côté, avec la qualité JPEG de votre choix. Chaque page", + "**Photos already in your library get theirs in the background**: LightCraft reads just the few kilobytes of each": "**Les photos déjà dans votre bibliothèque reçoivent le leur en arrière-plan** : LightCraft ne lit que les quelques kilo-octets de chaque", + "**Video:** AV1 video in an MP4 (or WebM) file at 720p or 1080p, 24 or 30 frames per second: each slide stays up for": "**Vidéo :** vidéo AV1 dans un fichier MP4 (ou WebM) en 720p ou 1080p, 24 ou 30 images par seconde : chaque diapositive reste affichée pendant", + "**Z zooms to it**: Toggle Zoom centres on the focus point, so checking that the subject is sharp is one key": "**Z zoome dessus** : Basculer le zoom se centre sur le point de mise au point, de sorte que vérifier la netteté du sujet revient à une seule touche", + "0.3 MB of JPEG instead of 5.6 MB and is ready several times sooner; Nikon and Panasonic raws with a mid-sized": "0,3 Mo de JPEG au lieu de 5,6 Mo et est prête plusieurs fois plus tôt ; les RAW Nikon et Panasonic avec un JPEG de taille", + "1200D (Rebel T5) and 100D (Rebel SL1) now count as clipped (issue #1272). They used to stop at 81–98% of white, so": "1200D (Rebel T5) et 100D (Rebel SL1) comptent désormais comme écrêtées (ticket #1272). Elles s'arrêtaient auparavant à 81–98 % du blanc, si bien que", + "12–32 mm kit zoom was off by about 5 % of the image width at the corners before. Files shot with the correction off": "zoom kit 12–32 mm s'écartait auparavant d'environ 5 % de la largeur de l'image dans les coins. Les fichiers pris avec la correction désactivée", + "1440 px at the corners, where it was up to 17 px off before. The camera's lateral chromatic aberration table is read": "1440 px dans les coins, alors qu'il s'écartait auparavant jusqu'à 17 px. La table d'aberration chromatique latérale de l'appareil est lue", + "16 GB, 355 MP with 32 GB) and the message says so. The merge also frees each photo's pixels once they are": "16 Go, 355 Mpx avec 32 Go) et le message le précise. La fusion libère aussi les pixels de chaque photo une fois qu'ils sont", + "16-bit Rec. 2020 PQ. Not in the web version yet.": "Rec. 2020 PQ 16 bits. Pas encore dans la version web.", + "2026-10-02": "2026-10-02", + "2026-10-05": "2026-10-05", + "2026-10-07": "2026-10-07", + "2026-10-08": "2026-10-08", + "2026-10-09": "2026-10-09", + "2026-10-10": "2026-10-10", + "2026-10-11": "2026-10-11", + "2026-10-12": "2026-10-12", + "2026-10-13": "2026-10-13", + "2026-10-14": "2026-10-14", + "3396 K, one on the Shade preset 7493 K. As for #730, only the numbers change: edits made on the old relative": "3396 K, une photo au préréglage Ombre 7493 K. Comme pour #730, seuls les nombres changent : les retouches faites sur l'ancienne échelle relative", + "67,000 photos that step went from 37 ms to under 1 ms. Still worked out whole: an edit to more than 256 photos, a": "67 000 photos, cette étape est passée de 37 ms à moins de 1 ms. Toujours recalculés en entier : une retouche de plus de 256 photos, une", + "A Folders section in the sidebar lists the folders your photos were imported from; choose one to see its photos.": "Une section Dossiers dans la barre latérale liste les dossiers depuis lesquels vos photos ont été importées ; choisissez-en un pour voir ses photos.", + "A Lightroom Classic catalog whose changes are all still in its `.lrcat-wal` file (a new catalog Lightroom has": "Un catalogue Lightroom Classic dont toutes les modifications sont encore dans son fichier `.lrcat-wal` (un nouveau catalogue que Lightroom a", + "A Synchronize Folder scan no longer asks the disk about every photo of the library in the folder (is its file": "Une analyse de Synchroniser le dossier n'interroge plus le disque pour chaque photo de la bibliothèque située dans le dossier (son fichier", + "A `thumbs` folder that holds nothing but the cache says that it is one (`CACHEDIR.TAG`), so backup programs that": "Un dossier `thumbs` qui ne contient que le cache l'indique (`CACHEDIR.TAG`), de sorte que les programmes de sauvegarde qui s'y", + "A crop a hair wide (or of no size), set by an agent or read from a sidecar, no longer crashes or hangs the": "Un recadrage large d'un cheveu (ou de taille nulle), défini par un agent ou lu dans un fichier annexe, ne fait plus planter ni se bloquer le", + "A crop of no size (from an agent or a sidecar) no longer gives the Detail view a photo of no size to lay out": "Un recadrage de taille nulle (venant d'un agent ou d'un fichier annexe) ne donne plus à la vue Détail une photo de taille nulle à disposer", + "A crop of no size with healing spots or masks no longer crashes the render: samples outside the picture read its": "Un recadrage de taille nulle avec des taches de correction ou des masques ne fait plus planter le rendu : les échantillons hors de l'image lisent son", + "A damaged or crafted raw can no longer make LightCraft set aside gigabytes of memory before finding out the file is": "Un RAW endommagé ou forgé ne peut plus faire réserver à LightCraft des gigaoctets de mémoire avant de découvrir que le fichier est", + "A demo photo whose stored size was damaged (a width of 4294967295) is rendered at its own size instead of": "Une photo de démonstration dont la taille enregistrée était endommagée (une largeur de 4294967295) est rendue à sa propre taille au lieu d'une", + "A dialog taller than the window no longer runs off it (issue #781): on a 1366×768 screen the Export dialog's title": "Une boîte de dialogue plus haute que la fenêtre ne déborde plus (ticket #781) : sur un écran de 1366×768, le titre de la boîte de dialogue Exporter", + "A dialog's confirm button says it's the next step": "Le bouton de confirmation d'une boîte de dialogue indique qu'il s'agit de l'étape suivante", + "A double-click on the thumb is a single step in History and Undo. Its first click no longer nudges the value to": "Un double-clic sur la poignée forme une seule étape dans l'historique et l'annulation. Son premier clic ne déplace plus la valeur vers", + "A file named `portable.txt` next to the LightCraft program makes it keep its settings, logs and downloaded": "Un fichier nommé `portable.txt` placé à côté du programme LightCraft lui fait conserver ses réglages, ses journaux et ses", + "A label follows its folder when it is renamed or moved in LightCraft, together with the labels of the folders": "Une étiquette suit son dossier quand il est renommé ou déplacé dans LightCraft, de même que les étiquettes des dossiers", + "A library holding thousands of presets (a Lightroom collection imported whole: 11 000 presets, a 42 MB": "Une bibliothèque contenant des milliers de préréglages (une collection Lightroom importée en entier : 11 000 préréglages, un fichier de 42 Mo", + "A library whose catalog file was damaged (or edited by hand) in a way that still reads no longer crashes": "Une bibliothèque dont le fichier de catalogue a été endommagé (ou modifié à la main) d'une manière qui reste lisible ne fait plus planter", + "A library with no photos now opens on the Photo Grid with the sidebar (Square Grid stays as it is), instead of a": "Une bibliothèque sans photo s'ouvre désormais sur la grille de photos avec la barre latérale (la grille carrée reste telle quelle), au lieu d'une", + "A name the library doesn't have is marked as a new keyword before you press Return, so a misspelling no longer": "Un nom que la bibliothèque n'a pas est signalé comme nouveau mot-clé avant que vous appuyiez sur Entrée, si bien qu'une faute de frappe ne", + "A photo that has no folder on disk (a demo photo, or one in the web version's browser storage) or whose folder": "Une photo sans dossier sur le disque (une photo de démonstration, ou une photo du stockage du navigateur de la version web) ou dont le dossier", + "A photo that runs into a bug in LightCraft while it renders (in a raw decoder or the editing pipeline) now fails": "Une photo qui tombe sur un bogue de LightCraft pendant son rendu (dans un décodeur RAW ou la chaîne de retouche) échoue désormais", + "A photo the folder lists is there for the scan, also where its file could not be opened by its path (a folder": "Une photo que le dossier liste est considérée comme présente par l'analyse, y compris quand son fichier n'a pas pu être ouvert par son chemin (un dossier", + "A photo whose Defringe amount was stored far past the sliders' 20 (in a damaged catalog or sidecar) no longer": "Une photo dont la quantité de suppression des franges était enregistrée bien au-delà des 20 du curseur (dans un catalogue ou un fichier annexe endommagé) ne", + "A photo whose file was replaced (Reload Changed Files after an outside edit) no longer keeps the faces recognition": "Une photo dont le fichier a été remplacé (Recharger les fichiers modifiés après une retouche extérieure) ne garde plus les visages que la reconnaissance", + "A preset whose lens-profile switch is off no longer turns off the lens corrections built into a DNG (iPhone ProRAW": "Un préréglage dont l'interrupteur de profil d'objectif est désactivé ne désactive plus les corrections d'objectif intégrées à un DNG (ProRAW d'iPhone", + "A raw file whose black level is stored as \"not a number\" (or infinity), or a floating-point DNG with such": "Un fichier RAW dont le niveau de noir est enregistré comme « n'est pas un nombre » (ou l'infini), ou un DNG en virgule flottante avec de tels", + "A selection without keywords now says \"No keywords yet\" where its chips would be.": "Une sélection sans mot-clé affiche désormais « Aucun mot-clé pour l'instant » à la place de ses pastilles.", + "A slideshow can now open with an intro screen and close with an ending screen, like Lightroom Classic's Titles": "Un diaporama peut maintenant s'ouvrir sur un écran d'introduction et se terminer sur un écran de fin, comme dans", + "A small edit (a keyword, a rating, a flag, a slider) no longer has the grid's list worked out again from every": "Une petite retouche (un mot-clé, une note, un drapeau, un curseur) ne fait plus recalculer la liste de la grille à partir de chaque", + "A smart album can include or exclude another smart album: \"Keywords contain travel\" and \"Album isn't Excluded Photos\"": "Un album intelligent peut inclure ou exclure un autre album intelligent : « Les mots-clés contiennent travel » et « L'album n'est pas Photos exclues »", + "A smart album whose rules no longer check (an album they test was deleted) is marked ⚠ in the sidebar; its tooltip": "Un album intelligent dont les règles ne sont plus valides (un album qu'elles testent a été supprimé) est marqué ⚠ dans la barre latérale ; son infobulle", + "A spot with Feather at 0 no longer draws black pixels exactly on its radius. This also fixes spots at 0% Opacity": "Une tache dont le contour progressif est à 0 ne dessine plus de pixels noirs exactement sur son rayon. Cela corrige aussi les taches à 0 % d'opacité qui", + "A star, the moon or a light that moves between the photos of a bracket (a night bracket on a tripod) no longer": "Une étoile, la lune ou une lumière qui bouge entre les photos d'un bracketing (un bracketing de nuit sur trépied) ne laisse plus", + "A template file that can't be used (damaged, from a newer LightCraft, too large) is listed as skipped instead of": "Un fichier de modèle inutilisable (endommagé, issu d'un LightCraft plus récent, trop volumineux) est listé comme ignoré au lieu", + "A thumbnail of the photo open in Detail is made from its already decoded preview instead of decoding the file": "Une miniature de la photo ouverte dans Détail est créée à partir de son aperçu déjà décodé au lieu de décoder le fichier", + "A view can hold its photos until you refresh it": "Une vue peut conserver ses photos jusqu'à son actualisation", + "A zoomed view keeps the GPU copy of the original while it is on screen: pausing for a few seconds between pans no": "Une vue zoomée garde la copie GPU de l'original tant qu'elle est à l'écran : faire une pause de quelques secondes entre deux déplacements ne", + "AI Denoise and Find Missing Photos. Each row has the task's name, a progress bar, the count and what it is working": "Débruitage IA et Rechercher les photos manquantes. Chaque ligne indique le nom de la tâche, une barre de progression, le compte et ce sur quoi elle", + "AI RAW denoise": "Débruitage IA des RAW", + "ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come": "ARW) donne au DNG fusionné la couleur qu'a chaque photo ouverte seule (ticket #965). Une fusion HDR de CR2 sortait auparavant", + "ASCII (an umlaut, a curly apostrophe, a dash), about every name the folder does not list. Names it does list are": "l'ASCII (un tréma, une apostrophe typographique, un tiret), à propos de presque tous les noms que le dossier ne liste pas. Les noms qu'il liste sont", + "Activity stack": "Pile d'activité", + "Add to Apple Photos (macOS)": "Ajouter à Apple Photos (macOS)", + "Agents list and stop tasks with `activity.list` and `activity.cancel`; `ui.inspect` reports them as `activity`.": "Les agents listent et arrêtent les tâches avec `activity.list` et `activity.cancel` ; `ui.inspect` les signale sous `activity`.", + "Agents use `app.newLibrary {path, name}`, `app.recentLibraries` and `app.clearRecentLibraries`.": "Les agents utilisent `app.newLibrary {path, name}`, `app.recentLibraries` et `app.clearRecentLibraries`.", + "Agents: `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` for files already on disk, and": "Agents : `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` pour les fichiers déjà sur le disque, et", + "Agents: `view.sidebarSection`, `view.sidebarMoveSection`, `view.sidebarReset`; `ui.set` takes `sidebar`.": "Agents : `view.sidebarSection`, `view.sidebarMoveSection`, `view.sidebarReset` ; `ui.set` accepte `sidebar`.", + "Album folders fold with the same disclosure triangle as Local, By Date, Folders and Keywords.": "Les dossiers d'albums se replient avec le même triangle de dévoilement que Local, Par date, Dossiers et Mots-clés.", + "Album rule is \"is\" or \"isn't\" an album, picked with the album picker.": "règle Album est « est » ou « n'est pas » un album, choisi avec le sélecteur d'album.", + "Album, New Smart Album, Rename Keyword, Merge Keywords and similar dialogs, or the name field under unnamed faces for": "l'album, Nouvel album intelligent, Renommer le mot-clé, Fusionner les mots-clés et des boîtes de dialogue similaires, ou sur le champ de nom sous les visages sans nom pour obtenir", + "Albums tree": "Arborescence des albums", + "An HDR merged from raws that LightCraft colours from the camera's JPEG (CR2, NEF, ARW…) now opens at the same": "Un HDR fusionné à partir de RAW dont LightCraft tire les couleurs du JPEG de l'appareil (CR2, NEF, ARW…) s'ouvre désormais avec la même", + "An empty library leads to Import": "Une bibliothèque vide mène à l'importation", + "An export enlarged far past the photo's size (20000 typed for 2000 with Don't Enlarge off) no longer ends": "Une exportation agrandie bien au-delà de la taille de la photo (20000 saisi au lieu de 2000 avec Ne pas agrandir désactivé) n'arrête plus", + "An uncompressed Leaf Aptus 22 MOS no longer opens as a dark, colourless picture of its sensor mosaic: it imports": "Un MOS non compressé du Leaf Aptus 22 ne s'ouvre plus comme une image sombre et sans couleur de la mosaïque de son capteur : il s'importe", + "Any Searchable Text also finds the state / province, alt text, people and a virtual copy's name.": "N'importe quel texte pouvant être recherché trouve aussi l'état / la province, le texte alternatif, les personnes et le nom d'une copie virtuelle.", + "Appearance lists the modes and themes. On Linux, Auto follows the desktop portal's colour scheme": "Apparence liste les modes et les thèmes. Sous Linux, Auto suit le schéma de couleurs du portail de bureau", + "Apple ProRAW's gain table map (its local tone mapping, `ProfileGainTableMap`) is now read and kept when a photo is": "La carte de table de gain d'Apple ProRAW (son mappage tonal local, `ProfileGainTableMap`) est désormais lue et conservée lorsqu'une photo est", + "Arabic names and other Arabic text in headings, chosen tabs and other bold places are now drawn bold, as Latin text": "Les noms arabes et autres textes arabes dans les titres, les onglets sélectionnés et d'autres emplacements en gras sont désormais dessinés en gras, comme le texte latin", + "Arrange the left sidebar your way: drag Albums, Local, By Date, Folders or Keywords by its header to move it (a line": "Organisez la barre latérale gauche à votre façon : faites glisser Albums, Local, Par date, Dossiers ou Mots-clés par son en-tête pour le déplacer (un trait", + "As Shot temperature and tint as its photos, and changing the white balance no longer turns it green. Sony ARW": "température et teinte « Tel quel » que ses photos, et modifier la balance des blancs ne le rend plus vert. Auparavant, les fusions ARW Sony", + "Aspect Ratio (a 24 MP photo cropped to a square is 16 MP).": "Ratio de format (une photo de 24 Mpx recadrée en carré fait 16 Mpx).", + "Auto use the same model. Custom white balances on these photos render slightly differently than before.": "Auto utilisent le même modèle. Les balances des blancs personnalisées de ces photos s'affichent un peu différemment d'avant.", + "Blown highlights in CR2 files from the Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),": "Les hautes lumières brûlées des fichiers CR2 des Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),", + "Bold text in other scripts": "Texte en gras dans d'autres écritures", + "Bridge and Photo Supreme (its Formatted Vocabulary File) use the same files, so keyword lists move between them and": "Bridge et Photo Supreme (son Formatted Vocabulary File) utilisent les mêmes fichiers, si bien que les listes de mots-clés circulent entre eux et", + "Building from source": "Compilation depuis les sources", + "C-RAWs imported earlier, Photo ▸ Reload from Disk picks up the raw data.": "importés auparavant, Photo → Recharger depuis le disque récupère les données RAW.", + "Cached thumbnails are redrawn.": "Les miniatures en cache sont recalculées.", + "Camera-look deep shadows": "Ombres profondes du rendu de l'appareil", + "Canon CR2 and Pentax PEF raws get the same starting look fitted to the camera's own JPEG as ARW, NEF, RW2, RAF": "Les RAW Canon CR2 et Pentax PEF reçoivent le même rendu de départ ajusté sur le JPEG de l'appareil que ARW, NEF, RW2, RAF", + "Canon CR2 highlights": "Hautes lumières des CR2 Canon", + "Canon CR2 raws no longer open too dark with blocked-up shadows: the black level was measured over border columns": "Les RAW Canon CR2 ne s'ouvrent plus trop sombres avec des ombres bouchées : le niveau de noir était mesuré sur des colonnes de bordure", + "Canon CR3 raws now develop from their sensor data: lossless RAW and C-RAW, checked sample for sample on the EOS": "Les RAW Canon CR3 se développent désormais à partir de leurs données de capteur : RAW sans perte et C-RAW, vérifiés échantillon par échantillon sur les EOS", + "Canon CRW, Minolta MRW, Sigma X3F, Kodak KDC, Leaf MOS and Epson ERF files that LightCraft can't decode yet": "Les fichiers Canon CRW, Minolta MRW, Sigma X3F, Kodak KDC, Leaf MOS et Epson ERF que LightCraft ne sait pas encore décoder", + "Canon EOS R5 Mark II": "Canon EOS R5 Mark II", + "Canon EOS R7 C-RAW files develop from their sensor data too, instead of opening from their embedded JPEG. For R7": "Les fichiers C-RAW du Canon EOS R7 se développent eux aussi à partir de leurs données de capteur, au lieu de s'ouvrir depuis leur JPEG intégré. Pour les C-RAW du R7", + "Canon PowerShot G9 raws open with the camera's white balance (White Balance ▸ As Shot); it used to start from a": "Les RAW du Canon PowerShot G9 s'ouvrent avec la balance des blancs de l'appareil (Balance des blancs → Tel quel) ; ils partaient auparavant d'une", + "Chinese (Simplified and Traditional), Japanese and Brazilian Portuguese.": "du chinois (simplifié et traditionnel), du japonais et du portugais brésilien.", + "Choice values read as words in every language: \"Public Domain\", \"Picked\", \"Black & White\" rather than ids like": "Les valeurs de choix se lisent sous forme de mots dans toutes les langues : « Domaine public », « Sélectionnée », « Noir et blanc » plutôt que des identifiants comme", + "Choosing a Lightroom Classic catalog folder in File → Open Library… (or one of its `Previews.lrdata` /": "Choisir un dossier de catalogue Lightroom Classic dans Fichier → Ouvrir la bibliothèque… (ou l'un de ses dossiers `Previews.lrdata` /", + "Choosing a date under By Date or a keyword under Keywords shows those photos from All Photos, as their counts": "Choisir une date sous Par date ou un mot-clé sous Mots-clés affiche ces photos parmi Toutes les photos, comme leurs comptes", + "Classic (issue #956). With the second, each photo is exported into the folder its original is in, plus the": "Classic (ticket #956). Avec la seconde, chaque photo est exportée dans le dossier où se trouve son original, plus le", + "Cleaner HDR merges": "Fusions HDR plus propres", + "Closer camera colour for lens-corrected raws": "Une couleur plus proche de celle de l'appareil pour les RAW corrigés de l'objectif", + "Closing a library releases its lock explicitly (issue #680). On Linux and macOS the lock used to go with the file": "La fermeture d'une bibliothèque libère explicitement son verrou (ticket #680). Sous Linux et macOS, le verrou disparaissait auparavant avec le descripteur", + "Colour labels tint thumbnail surrounds in Square Grid and the Detail filmstrip, and a translucent footer along the bottom of the photo in Photo Grid. Label confirmations use a matching pale colour.": "Les étiquettes de couleur teintent le pourtour des miniatures dans la grille carrée et la pellicule de Détail, et un pied translucide le long du bas de la photo dans la grille de photos. Les confirmations d'étiquette utilisent une couleur pâle assortie.", + "Compare and Reference View panes say \"Rendering…\" (or that the photo can't be opened) the same way, so a": "Les volets Comparer et Vue de référence affichent « Rendu en cours… » (ou que la photo ne peut pas être ouverte) de la même manière, afin qu'un", + "Confirm matching faces together": "Confirmer ensemble les visages correspondants", + "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s and Nikon 1 V1 now show": "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s et Nikon 1 V1 montrent désormais", + "Corrections, on by default for newly imported photos, with the same framing as the camera's JPEG. At 12 mm the": "corrections de profil, activée par défaut pour les photos nouvellement importées, avec le même cadrage que le JPEG de l'appareil. À 12 mm, le", + "Create keywords with + (inside the one you picked, with synonyms, and given to the selection if you like), edit one": "Créez des mots-clés avec + (à l'intérieur de celui que vous avez choisi, avec des synonymes, et attribués à la sélection si vous le souhaitez), modifiez-en un", + "Crop (issue #295): a Lock toggle keeps the aspect ratio on every handle, Custom takes your own ratio (Apply), and": "Recadrage (ticket #295) : un bouton Verrouiller conserve le format sur chaque poignée, Personnalisé accepte votre propre ratio (Appliquer), et", + "Crop rotation": "Rotation du recadrage", + "Culling.": "assisté.", + "Cut, Copy, Paste and Select All. Esc in them gives back the text from before you started typing (in the Info panel it": "Couper, Copier, Coller et Tout sélectionner. Échap dans ces champs rend le texte d'avant la saisie (dans le panneau Infos, il", + "D60, D80 and D2Xs now show the area the camera itself frames, a few pixels smaller than before.": "D60, D80 et D2Xs montrent désormais la zone que l'appareil cadre lui-même, de quelques pixels plus petite qu'avant.", + "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,": "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,", + "DNG camera identity": "Identité de l'appareil dans les DNG", + "DNG export and Convert to DNG no longer duplicate the camera make when the model already": "L'exportation DNG et Convertir en DNG ne dupliquent plus la marque de l'appareil quand le modèle la", + "Date rules have a calendar button: pick a day, a month or a whole year (Year / Month / Day), in your language; the": "Les règles de date ont un bouton de calendrier : choisissez un jour, un mois ou une année entière (Année / Mois / Jour), dans votre langue ; les", + "Daylight, Cloudy, Shade, Tungsten, Fluorescent and Flash presets set real temperatures (issue #730). The matrices": "préréglages Lumière du jour, Nuageux, Ombre, Tungstène, Fluorescent et Flash règlent de vraies températures (ticket #730). Les matrices", + "Dehaze while zoomed in": "Correction du voile en zoom avant", + "Delete in an album removes from the album only": "Supprimer dans un album retire seulement de l'album", + "Deleted, read the metadata updates. A folder on a disk that isn't connected is reported as such. Synchronizing": "récemment, lire les mises à jour de métadonnées. Un dossier sur un disque non connecté est signalé comme tel. La synchronisation", + "Detail has a per-photo AI Denoise switch and Amount. Bayer RAW photos use a disposable cache, with matching previews and exports and pure-Rust CPU/GPU inference.": "Détail propose un interrupteur Débruitage IA et une Quantité par photo. Les photos RAW Bayer utilisent un cache jetable, avec des aperçus et des exportations cohérents et une inférence CPU/GPU en Rust pur.", + "Detail view that pointed at an empty grid. The grid and Detail view offer Import Photos… and, in the desktop app,": "vue Détail qui pointait sur une grille vide. La grille et la vue Détail proposent Importer des photos… et, dans l'application de bureau,", + "Dialogs": "Boîtes de dialogue", + "Dialogs fit the window": "Les boîtes de dialogue tiennent dans la fenêtre", + "Dialogs that fit look as before.": "Les boîtes de dialogue qui tenaient déjà ont le même aspect qu'avant.", + "Dialogs' buttons and About's Discord link are drawn by one button component: primary (filled with the accent),": "Les boutons des boîtes de dialogue et le lien Discord de À propos sont dessinés par un seul composant de bouton : principal (rempli avec la couleur d'accent),", + "Dock can be attached to a bug report. `LIGHTCRAFT_LOG` works as before; `RUST_LOG` takes env_logger-style": "Dock puissent être joints à un rapport de bogue. `LIGHTCRAFT_LOG` fonctionne comme avant ; `RUST_LOG` accepte des directives de style", + "Drag a keyword onto another to nest it, or onto the list's title to bring it back to the top level; photos dragged": "Faites glisser un mot-clé sur un autre pour l'imbriquer, ou sur le titre de la liste pour le remettre au premier niveau ; les photos glissées", + "Drag an album or folder onto a folder to move it there (a closed folder opens after 0.6 s under the pointer; a": "Faites glisser un album ou un dossier sur un dossier pour l'y déplacer (un dossier fermé s'ouvre après 0,6 s sous le pointeur ; un", + "Drag anywhere inside the selected radial gradient's ellipse to move it, including rotated": "Faites glisser n'importe où dans l'ellipse du dégradé radial sélectionné pour la déplacer, y compris les", + "Dragging a Tone Curve point that sits very close to its neighbours (two clicks side by side, or a curve from a": "Faire glisser un point de la courbe des tonalités très proche de ses voisins (deux clics côte à côte, ou une courbe provenant d'un", + "Dragging a slider no longer re-renders the edited photo's filmstrip thumbnail on every frame; it follows once you": "Faire glisser un curseur ne recalcule plus à chaque image la miniature de la pellicule de la photo retouchée ; elle suit dès que vous", + "E-1, E-400 and XZ-2 corpus files: all accepted), with white balance relative to the as-shot look as for the other": "fichiers E-1, E-400 et XZ-2 du corpus : tous acceptés), avec une balance des blancs relative au rendu tel que pris comme pour les autres", + "Each sits at one of nine anchors of the slide or of the photo, moved by an offset, and never leaves the slide.": "Chacune se place à l'un des neuf points d'ancrage de la diapositive ou de la photo, déplacée par un décalage, et ne quitte jamais la diapositive.", + "Each such bug used to take one of the render threads with it, so after a few of them no photo rendered until": "Chaque bogue de ce type emportait auparavant l'un des fils de rendu, si bien qu'après quelques-uns, aucune photo ne s'affichait avant que", + "Edge, Short Edge, Aspect Ratio (landscape / portrait / square), Cropped and Treatment (in color / black & white).": "côté, Petit côté, Ratio de format (paysage / portrait / carré), Recadrée et Traitement (en couleur / noir et blanc).", + "Edit in PhotoCraft": "Modifier dans PhotoCraft", + "Editing a smart album's name and rules is one step: both or neither, and one undo takes both back": "Modifier le nom et les règles d'un album intelligent forme une seule étape : les deux ou aucun, et une annulation annule les deux", + "Edits keep up in a large library": "Les retouches suivent le rythme dans une grande bibliothèque", + "Existing smart previews are refreshed when their originals are online, and cached renders are redrawn.": "Les aperçus dynamiques existants sont actualisés quand leurs originaux sont en ligne, et les rendus en cache sont recalculés.", + "Export as JPEG XL (issue #247): Format ▸ JPEG XL in the Export dialog, `format: \"jxl\"` for agents and the CLI": "Exportation en JPEG XL (ticket #247) : Format → JPEG XL dans la boîte de dialogue Exporter, `format: \"jxl\"` pour les agents et la CLI", + "Export can write PSD too (flat, 8- or 16-bit).": "L'exportation peut aussi écrire du PSD (aplati, 8 ou 16 bits).", + "Export next to the originals": "Exporter à côté des originaux", + "Exporting a photo more than 65,535 times as long as it is wide (a one-pixel strip), or opening the Export dialog's": "L'exportation d'une photo plus de 65 535 fois plus longue que large (une bande d'un pixel), ou l'ouverture pour elle de l'aperçu du filigrane de la boîte de dialogue", + "Exports with noise reduction, Texture, Clarity, Dehaze or Highlights and Shadows can be much faster on the GPU,": "Les exportations avec réduction du bruit, Texture, Clarté, Correction du voile ou Hautes lumières et Ombres peuvent être bien plus rapides sur le GPU,", + "Faces are kept in the thumbnail cache at a few fixed sizes, so moving the thumbnail slider no longer renders them": "Les visages sont conservés dans le cache des miniatures à quelques tailles fixes, si bien que déplacer le curseur de taille des miniatures ne les recalcule plus", + "Faces load faster in the People view": "Les visages se chargent plus vite dans la vue Personnes", + "Faces on unedited raws are cut from the camera's preview inside the file instead of developing the raw (issue": "Les visages des RAW non retouchés sont découpés dans l'aperçu de l'appareil contenu dans le fichier au lieu de développer le RAW (ticket", + "Faster GPU exports": "Exportations GPU plus rapides", + "File extensions match whatever their letter case: `IMG_0001.JPG` and `DSC_0002.NEF` as Nikon writes them, `.Jpg`": "Les extensions de fichier correspondent quelle que soit leur casse : `IMG_0001.JPG` et `DSC_0002.NEF` tels que Nikon les écrit, `.Jpg`", + "File → Import Lightroom Catalog… opens `.lrcat` directly, with originals referenced in place.": "Fichier → Importer un catalogue Lightroom… ouvre directement les `.lrcat`, avec les originaux référencés sur place.", + "File ▸ Import Keywords… and Export Keywords… read and write keyword list files as Lightroom Classic does (a keyword": "Fichier → Importer des mots-clés… et Exporter les mots-clés… lisent et écrivent des fichiers de liste de mots-clés comme le fait Lightroom Classic (un mot-clé", + "File ▸ New Library… asks for a name, then where to put it, and opens the new library (issue #902).": "Fichier → Nouvelle bibliothèque… demande un nom, puis l'emplacement, et ouvre la nouvelle bibliothèque (ticket #902).", + "File ▸ Open Recent Library lists the last 8 libraries; ones that are gone (moved, drive disconnected) are greyed": "Fichier → Ouvrir une bibliothèque récente liste les 8 dernières bibliothèques ; celles qui n'existent plus (déplacées, disque déconnecté) sont", + "Five built-in templates of our own: Plain Black (the photo on black), Gallery Wall (a light wall, a white mat and a": "Cinq modèles intégrés de notre cru : Noir uni (la photo sur noir), Mur de galerie (un mur clair, un passe-partout blanc et une", + "Folder colour labels": "Étiquettes de couleur des dossiers", + "Folder…. The folder and the folders inside it are scanned in the background for photos added on disk, photos whose": "le dossier…. Le dossier et les dossiers qu'il contient sont analysés en arrière-plan pour repérer les photos ajoutées sur le disque, les photos dont le", + "For scripts: a size set with `ui.resize` is remembered like any other, so a script that needs a size sets it.": "Pour les scripts : une taille définie avec `ui.resize` est mémorisée comme les autres, donc un script qui a besoin d'une taille la définit.", + "Formats": "Formats", + "From the command line: `lightcraft-cli merge hdr-batch FOLDER`.": "En ligne de commande : `lightcraft-cli merge hdr-batch FOLDER`.", + "Fujifilm RAFs from 59 camera models now get the lens correction the camera stores in the file: distortion (with the": "Les RAF Fujifilm de 59 modèles d'appareils reçoivent désormais la correction d'objectif que l'appareil stocke dans le fichier : distorsion (avec le", + "Fujifilm lens corrections": "Corrections d'objectif Fujifilm", + "Full screen is not remembered (the app opens as a window), and neither is where on the desktop the window was:": "Le plein écran n'est pas mémorisé (l'application s'ouvre en fenêtre), pas plus que l'emplacement de la fenêtre sur le bureau :", + "Full-resolution panoramas": "Panoramas en pleine résolution", + "Grid thumbnails and the first picture in the loupe of an unedited raw now come from the smallest JPEG the camera": "Les miniatures de la grille et la première image dans la loupe d'un RAW non retouché proviennent désormais du plus petit JPEG que l'appareil", + "HDR PNG export": "Exportation PNG HDR", + "HDR and panorama merges of CR2 keep their colour": "Les fusions HDR et panorama de CR2 conservent leur couleur", + "HDR merges keep the lens correction": "Les fusions HDR conservent la correction d'objectif", + "HDR merges keep the white balance": "Les fusions HDR conservent la balance des blancs", + "HDR merges of moving lights, and many brackets at once": "Fusions HDR de lumières mobiles, et de nombreux bracketings à la fois", + "HEIC / HEIF photos (iPhone and Mac) open now: the optional `lightcraft-heif` crate (heic-rs, pure Rust) behind": "Les photos HEIC / HEIF (iPhone et Mac) s'ouvrent désormais : le crate facultatif `lightcraft-heif` (heic-rs, en Rust pur) derrière", + "HEIC colours now match libheif to within one code value (they were up to ~10 off): the HEVC stream's own": "Les couleurs HEIC correspondent désormais à libheif à une valeur de code près (elles s'écartaient jusqu'à ~10) : la signalisation propre au flux HEVC", + "Hard-edged Heal and Clone spots": "Taches de correction et de clonage à bord net", + "Help → Keyboard Shortcuts includes the number-key bindings. See [library shortcuts](library-shortcuts.md).": "Aide → Raccourcis clavier inclut les raccourcis des touches numériques. Voir [raccourcis de la bibliothèque](library-shortcuts.md).", + "Help → Open Log Folder shows that log file in the file manager (Finder, Explorer, or the folder on Linux), so it": "Aide → Ouvrir le dossier des journaux affiche ce fichier journal dans le gestionnaire de fichiers (Finder, Explorateur, ou le dossier sous Linux), afin qu'il", + "Hide the sections you don't use: View ▸ Sidebar Sections, or right-click a header ▸ Hide This Section. Right-click": "Masquez les sections que vous n'utilisez pas : Affichage → Sections de la barre latérale, ou clic droit sur un en-tête → Masquer cette section. Faites un clic droit sur", + "Highlights and Shadows (process 2)": "Hautes lumières et ombres (traitement 2)", + "Highlights and Shadows keep the fine detail of the tones they move (issue #632): pulling Highlights down on a bright": "Hautes lumières et Ombres conservent le détail fin des tons qu'elles déplacent (ticket #632) : abaisser les hautes lumières sur un ciel", + "If LightCraft can't open a photo (its original is on a drive that isn't connected, or the file is damaged) but has": "Si LightCraft ne peut pas ouvrir une photo (son original est sur un disque non connecté, ou le fichier est endommagé) mais dispose de", + "If the desktop app can't open its window (for example when no graphics device can be used), it now says so in a": "Si l'application de bureau ne peut pas ouvrir sa fenêtre (par exemple quand aucun périphérique graphique n'est utilisable), elle le signale désormais dans une", + "If you go back to an older version, it renders its thumbnails again as `.jpg`. This version then takes those": "Si vous revenez à une version plus ancienne, elle recalcule ses miniatures en `.jpg`. Cette version reprend alors celles-ci", + "Import Lightroom Catalog… as buttons, and say that photos (and, in the desktop app, folders) can be dropped into": "Importer un catalogue Lightroom… sous forme de boutons, et indiquent que l'on peut déposer des photos (et, dans l'application de bureau, des dossiers) dans", + "Import when a card is connected": "Importation à la connexion d'une carte", + "Imported `.cube` LUT profiles appear in the Profile menu and the profile browser, grouped by their folder, and stay": "Les profils LUT `.cube` importés apparaissent dans le menu Profil et dans le navigateur de profils, groupés par dossier, et restent", + "Importing XMP presets no longer lists bookkeeping fields (`Cluster`, `SortName`, `SupportsAmount2`, the as-shot": "L'importation de préréglages XMP ne liste plus les champs de gestion interne (`Cluster`, `SortName`, `SupportsAmount2`, le", + "Importing a deleted photo again": "Réimporter une photo supprimée", + "Importing a file whose photo is in Recently Deleted brings the photo back, with its edits, rating and albums": "Importer un fichier dont la photo est dans Supprimées récemment ramène la photo, avec ses retouches, sa note et ses albums", + "Importing a large collection and opening its library no longer compare every preset with every other.": "Importer une grande collection et ouvrir sa bibliothèque ne compare plus chaque préréglage avec tous les autres.", + "Importing a preset zip that unpacks to far more than any preset (a \"zip bomb\") is refused with a message naming": "L'importation d'un zip de préréglages qui se décompresse en bien plus que n'importe quel préréglage (une « bombe zip ») est refusée avec un message nommant", + "In a long section, the header stays at the top of the sidebar while you scroll through its rows, so you always see": "Dans une longue section, l'en-tête reste en haut de la barre latérale pendant que vous faites défiler ses lignes, si bien que vous voyez toujours", + "In an album, the Delete key now takes the selected photos out of the album, as in Lightroom. It used to move them": "Dans un album, la touche Supprimer retire désormais les photos sélectionnées de l'album, comme dans Lightroom. Elle les déplaçait auparavant", + "In dialogs, the confirm button is on the right with Cancel to its left, and filled with the accent when it makes or": "Dans les boîtes de dialogue, le bouton de confirmation est à droite avec Annuler à sa gauche, et rempli avec la couleur d'accent quand il crée ou", + "Inside This Keyword, Purge Unused Keywords.": "dans celui-ci, Purger les mots-clés inutilisés.", + "JPEG XL compressed DNGs (DNG 1.7) now open: lossless tiles decode sample for sample (checked on synthetic files);": "Les DNG compressés en JPEG XL (DNG 1.7) s'ouvrent désormais : les tuiles sans perte se décodent échantillon par échantillon (vérifié sur des fichiers synthétiques) ;", + "JPEG XL export": "Exportation JPEG XL", + "JPEG exports are 12–14 % smaller at the same quality, with exactly the same pixels (issue #1373): each file now": "Les exportations JPEG sont de 12–14 % plus petites à qualité égale, avec exactement les mêmes pixels (ticket #1373) : chaque fichier", + "JPEG get faster too.": "moyenne y gagnent aussi.", + "Kelvin white balance for more Sony cameras": "Balance des blancs en kelvins pour davantage d'appareils Sony", + "Kelvin white balance for raws whose camera has colour matrices": "Balance des blancs en kelvins pour les RAW d'appareils dotés de matrices de couleur", + "Keyword Set ▸ Edit Set… edits a set's nine keywords in place, one field per ⌥ key, and renames it (or saves the edits as a new": "Jeu de mots-clés → Modifier le jeu… modifie sur place les neuf mots-clés d'un jeu, un champ par touche ⌥, et le renomme (ou enregistre les modifications comme nouveau", + "Keyword lists": "Listes de mots-clés", + "Keyword sets": "Jeux de mots-clés", + "Keyword tag options decide what exported files carry: Include on Export, Export Containing Keywords, Export": "Les options du mot-clé décident de ce que portent les fichiers exportés : Inclure à l'exportation, Exporter les mots-clés parents, Exporter", + "Keywording box": "Zone d'attribution des mots-clés", + "Keywords has a + in its header, like Albums: Create Keyword Tag without opening the Keyword List.": "Mots-clés a un + dans son en-tête, comme Albums : créer un mot-clé sans ouvrir la liste des mots-clés.", + "Keywords panel": "Panneau Mots-clés", + "Languages": "Langues", + "Large libraries: Synchronize Folder, import and sidecars start sooner": "Grandes bibliothèques : Synchroniser le dossier, l'importation et les fichiers annexes démarrent plus tôt", + "Large preset collections": "Grandes collections de préréglages", + "Layout image over the loupe": "Image de mise en page sur la loupe", + "Leaf and Hasselblad raws": "RAW Leaf et Hasselblad", + "Lens corrections": "Corrections d'objectif", + "Lens names for Nikon DSLR raws": "Noms d'objectifs pour les RAW des reflex Nikon", + "Library and views": "Bibliothèque et vues", + "Library keyboard culling": "Tri au clavier dans la bibliothèque", + "Library sorting": "Tri de la bibliothèque", + "LightCraft program\" although nothing had it open. Nothing in the shipped app is known to hit the window today; it": "LightCraft program » alors que rien ne l'avait ouverte. Rien dans l'application livrée n'est connu pour toucher cette fenêtre aujourd'hui ; cela", + "LightCraft starts doesn't ask, and if a dialog is open or an import is running it waits until that's done.": "LightCraft démarre ne déclenche rien, et si une boîte de dialogue est ouverte ou si une importation est en cours, la revue attend la fin.", + "LightCraft the copy shows what you saved.": "LightCraft, la copie montre ce que vous avez enregistré.", + "LightCraft was restarted. The bug is still written to the log (Help ▸ Open Log Folder) for a report.": "LightCraft soit redémarré. Le bogue est toujours consigné dans le journal (Aide → Ouvrir le dossier des journaux) pour un signalement.", + "LightCraft when it shows a stack, or hangs it when a folder is moved: on opening, records are put back under": "LightCraft quand il affiche une pile, ni ne le bloque quand un dossier est déplacé : à l'ouverture, les enregistrements sont replacés sous", + "LightCraft's cached thumbnails no longer show up in Windows Photos / Gallery or other photo apps as pictures of": "Les miniatures en cache de LightCraft n'apparaissent plus dans Photos / Galerie de Windows ni dans d'autres applications photo comme des images", + "LightCraft's window opens at the size it had when you last used it, and zoomed (macOS) / maximized if it was: it": "La fenêtre de LightCraft s'ouvre à la taille qu'elle avait lors de la dernière utilisation, et zoomée (macOS) / agrandie si elle l'était : elle", + "LightCraft. Importing adds the keywords you don't have, in one undo step; a file it can't read says which line, or": "LightCraft. L'importation ajoute les mots-clés que vous n'avez pas, en une seule étape d'annulation ; un fichier illisible indique quelle ligne, ou", + "LightCraft: an enlargement stops at 512 megapixels, as in Lightroom, and one that needs more memory than the": "LightCraft : un agrandissement s'arrête à 512 mégapixels, comme dans Lightroom, et celui qui demande plus de mémoire que", + "Lightroom Classic catalogs": "Catalogues Lightroom Classic", + "Lightroom Classic's Export PDF, Export JPEG and Export Video: the photos in view as their slides, with the layout,": "l'exportation PDF, l'exportation JPEG et l'exportation vidéo de Lightroom Classic : les photos de la vue sous forme de diapositives, avec la disposition,", + "Lightroom catalog import": "Importation d'un catalogue Lightroom", + "Lightroom has no such view.": "Lightroom n'a pas de vue équivalente.", + "Lightroom radial masks on the right side": "Masques radiaux Lightroom du bon côté", + "Lightroom stays inverted, and older Radial Filters keep their Effect Outside / Invert Mask setting. Photos imported": "Lightroom reste inversé, et les anciens filtres radiaux conservent leur réglage Effet à l'extérieur / Inverser le masque. Les photos importées", + "Lightroom's `crs:Temperature` for these raws is read as the Kelvin it is (sidecars, Lightroom catalogs, presets);": "Le `crs:Temperature` de Lightroom pour ces RAW est lu comme les kelvins qu'il représente (fichiers annexes, catalogues Lightroom, préréglages) ;", + "Like in Lightroom, judge noise reduction at 1:1: at small sizes the noise it removes is mostly averaged away.": "Comme dans Lightroom, jugez la réduction du bruit à 1:1 : aux petites tailles, le bruit qu'elle élimine est en grande partie déjà lissé.", + "Local folders select a photo": "Les dossiers locaux sélectionnent une photo", + "Long-running tasks show in one place, top left under the top bar, as in Lightroom Classic (issue #345): imports and": "Les tâches longues s'affichent au même endroit, en haut à gauche sous la barre supérieure, comme dans Lightroom Classic (ticket #345) : importations et", + "Lossy JPEG XL files in Display P3 or Rec. 2020 now open in their real colours; saturated colours used to come in": "Les fichiers JPEG XL avec perte en Display P3 ou Rec. 2020 s'ouvrent désormais avec leurs vraies couleurs ; les couleurs saturées apparaissaient auparavant", + "Luminance and colour noise reduction no longer look much stronger in grid thumbnails and the filmstrip than in": "La réduction du bruit de luminance et de couleur ne paraît plus beaucoup plus forte dans les miniatures de la grille et la pellicule que dans", + "M50, R100, R8 and RP (on the RP also in 1.6× crop mode). CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100, R8 et RP (sur le RP aussi en mode recadrage 1,6×). Les fichiers CR3 que le décodeur ne sait pas encore lire s'ouvrent toujours à partir de leur JPEG intégré, comme avant.", + "Merging uses about a quarter less memory: three 67 MP raws need 3.8 GB instead of 4.8 GB.": "La fusion utilise environ un quart de mémoire en moins : trois RAW de 67 Mpx demandent 3,8 Go au lieu de 4,8 Go.", + "Models are installed separately after accepting their terms; no weights are bundled. See [setup and limitations](denoise.md).": "Les modèles s'installent séparément après acceptation de leurs conditions ; aucun poids n'est fourni. Voir [installation et limites](denoise.md).", + "Monitor profiles": "Profils de moniteur", + "More Canon EOS R6 Mark II C-RAW files decode": "Davantage de fichiers C-RAW du Canon EOS R6 Mark II se décodent", + "New fields: Keyword Count (\"2 or more\", \"exactly 2\"…), People and People Count (named faces), Shutter Speed (written": "Nouveaux champs : Nombre de mots-clés (« 2 ou plus », « exactement 2 »…), Personnes et Nombre de personnes (visages nommés), Vitesse d'obturation (écrite", + "Nikon D600, D610 and D5000": "Nikon D600, D610 et D5000", + "Nikon D850, Canon EOS 5D Mark III and others) now show white balance in Kelvin, as a DNG does and as Lightroom": "Nikon D850, Canon EOS 5D Mark III et d'autres) affichent désormais la balance des blancs en kelvins, comme le fait un DNG et comme", + "Nikon Z 6II, Z 8 and D5300 colour profiles": "Profils colorimétriques des Nikon Z 6II, Z 8 et D5300", + "Nikon lens corrections": "Corrections d'objectif Nikon", + "Nikon raws without coloured edge bars": "Des RAW Nikon sans barres colorées sur les bords", + "Noise reduction looks the same at every size": "La réduction du bruit a le même aspect à toutes les tailles", + "Nothing already edited changes: a Custom white balance set on the old relative scale renders pixel for pixel as": "Rien de ce qui est déjà retouché ne change : une balance des blancs Personnalisée réglée sur l'ancienne échelle relative s'affiche pixel pour pixel comme", + "Nothing else changes: the same files are found new, already there, moved or missing, and sidecars get the same": "Rien d'autre ne change : les mêmes fichiers sont trouvés nouveaux, déjà présents, déplacés ou manquants, et les fichiers annexes reçoivent les mêmes", + "Off by default (HEVC patents are the distributor's call, same as PhotoCraft); official builds pass `--features heif`.": "Désactivé par défaut (les brevets HEVC relèvent du distributeur, comme pour PhotoCraft) ; les versions officielles passent `--features heif`.", + "Older raw cameras": "Anciens appareils RAW", + "Olympus E-10 raws open with the camera's white balance (White Balance ▸ As Shot) and without the grey haze in": "Les RAW de l'Olympus E-10 s'ouvrent avec la balance des blancs de l'appareil (Balance des blancs → Tel quel) et sans le voile gris dans", + "Olympus ORF raws get the starting look fitted to the camera's own JPEG too, instead of opening flat and grey (the": "Les RAW Olympus ORF reçoivent eux aussi un rendu de départ ajusté sur le JPEG de l'appareil, au lieu de s'ouvrir plats et gris (les", + "On Linux and FreeBSD, file dialogs (Import Photos…, Open Library, Export, presets, keyword lists…) are children of": "Sous Linux et FreeBSD, les boîtes de dialogue de fichiers (Importer des photos…, Ouvrir la bibliothèque, Exporter, préréglages, listes de mots-clés…) sont des enfants de", + "On Windows and Linux, Ctrl+C outside a text field copies edit settings and Ctrl+V pastes them (⇧Ctrl+V: Paste": "Sous Windows et Linux, Ctrl+C hors d'un champ de texte copie les réglages de retouche et Ctrl+V les colle (⇧Ctrl+V : Coller", + "On a person's page, the ↑ control on a suggested face confirms it and all shown suggestions with equal or higher": "Sur la page d'une personne, la commande ↑ d'un visage suggéré le confirme ainsi que toutes les suggestions affichées dont la similarité est égale ou", + "On macOS the system does not tell LightCraft when a window is zoomed from the Window menu or resized after a": "Sous macOS, le système n'avertit pas LightCraft quand une fenêtre est zoomée depuis le menu Fenêtre ou redimensionnée après un", + "On macOS, photos are shown through the profile of the screen the window is on while no monitor profile is chosen in": "Sous macOS, les photos sont affichées à travers le profil de l'écran où se trouve la fenêtre tant qu'aucun profil de moniteur n'est choisi dans", + "On macOS, ratings `0–5`, labels `6–9` and pick/unflag `P/U` now reach the app even when shown in the native menu (issue #283; adapted from PR #261).": "Sous macOS, les notes `0–5`, les étiquettes `6–9` et le marquage sélectionnée/retrait du drapeau `P/U` atteignent désormais l'application même lorsqu'ils sont affichés dans le menu natif (ticket #283 ; adapté de la PR #261).", + "On macOS, single-key shortcuts that appear in the menu bar now work: E, C, H, M, ⇧P, I, K, D, ratings 0–5,": "Sous macOS, les raccourcis à touche unique qui apparaissent dans la barre de menus fonctionnent désormais : E, C, H, M, ⇧P, I, K, D, notes 0–5,", + "One kind of button": "Un seul type de bouton", + "Open Library knows a Lightroom catalog": "Ouvrir la bibliothèque reconnaît un catalogue Lightroom", + "Opening Synchronize Folder, an import review or an import no longer makes a table of every photo in the library": "Ouvrir Synchroniser le dossier, une revue d'importation ou une importation ne construit plus une table de toutes les photos de la bibliothèque", + "Opening a library no longer rewrites the date of every thumbnail it shows, which made them all look new at each": "L'ouverture d'une bibliothèque ne réécrit plus la date de chaque miniature affichée, ce qui les faisait toutes paraître neuves à chaque", + "Optics, Geometry and Calibration (issue #316).": "Optique, Géométrie et Calibrage (ticket #316).", + "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "SAM 3 distant facultatif : gardez l'éditeur natif en local et exécutez les inférences Objet, Décrire et de détail", + "Outside the crop box, where dragging rotates the photo, the pointer is a curved double arrow, and the angle is shown": "En dehors du cadre de recadrage, là où le glissement fait pivoter la photo, le pointeur est une double flèche courbe, et l'angle s'affiche", + "Panasonic and Leica raws (RW2, RWL) are now corrected for lens distortion the way the camera corrects its own JPEG": "Les RAW Panasonic et Leica (RW2, RWL) sont désormais corrigés de la distorsion de l'objectif comme l'appareil corrige son propre JPEG", + "Panning a photo zoomed to 1:1, or moving a slider while zoomed, no longer decodes the whole raw again each time on": "Déplacer une photo zoomée à 1:1, ou bouger un curseur en zoom, ne décode plus tout le RAW à chaque fois sur", + "Panorama and HDR Panorama merges keep the resolution of their photos instead of stopping at 40 megapixels": "Les fusions de panoramas et de panoramas HDR conservent la résolution de leurs photos au lieu de s'arrêter à 40 mégapixels", + "Pentax raws without black borders": "Des RAW Pentax sans bordures noires", + "Photo Grid marked nothing, and Detail, the histogram and the photo info showed a photo that isn't in the folder.": "la grille de photos n'en marquait aucune, et Détail, l'histogramme et les infos de la photo montraient une photo qui n'est pas dans le dossier.", + "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "La fusion de photos de Canon CR2 (et d'autres RAW dont LightCraft ajuste la couleur sur le JPEG de l'appareil, comme NEF et", + "PhotoCraft does. If that folder can't be written, the usual folder is used and the log says why.": "le fait PhotoCraft. Si ce dossier n'est pas accessible en écriture, le dossier habituel est utilisé et le journal en indique la raison.", + "Photos deleted (or moved) by another app no longer stay in a Local folder, failing to load and logging an error": "Les photos supprimées (ou déplacées) par une autre application ne restent plus dans un dossier Local, en échouant à se charger et en consignant une erreur", + "Photos from Nikon DSLRs like the D700, D750, D80 or D5300 now show which lens they were taken with, for example": "Les photos des reflex Nikon comme les D700, D750, D80 ou D5300 indiquent désormais avec quel objectif elles ont été prises, par exemple", + "Photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder": "Les photos qui commencent à correspondre apparaissent toujours immédiatement, et supprimer une photo ou la retirer de l'album ou du dossier", + "Photos that tie on the sort key (equal ratings, one import batch, a burst shot within the same second) now sort by": "Les photos à égalité sur la clé de tri (notes égales, un même lot d'importation, une rafale prise dans la même seconde) sont désormais triées par", + "Photos with deep shadows no longer have to extend the first measured tone in a straight line to black.": "Les photos aux ombres profondes n'ont plus à prolonger en ligne droite jusqu'au noir le premier ton mesuré.", + "Portable mode": "Mode portable", + "Preview or Photos. Moving the window to another screen is followed; **Use Screen Profile** goes back to it after": "Aperçu ou Photos. Le déplacement de la fenêtre vers un autre écran est suivi ; **Utiliser le profil de l'écran** y revient après", + "Previews match exports on Mac screens": "Les aperçus correspondent aux exportations sur les écrans Mac", + "ProRAW the way the iPhone renders it, turn on Profile ▸ Camera local tone mapping (shown for photos that carry the": "ProRAW tel que l'iPhone le calcule, activez Profil → Mappage local des tons de l’appareil (affiché pour les photos qui portent la", + "Process. See [process versions](process-versions.md).": "traitement actuel. Voir [versions de traitement](process-versions.md).", + "Quitting while a task that can be stopped is running asks first (\"Quit Anyway\" stops it).": "Quitter pendant qu'une tâche interruptible s'exécute demande d'abord confirmation (« Quitter quand même » l'arrête).", + "Radial masks brought over from Lightroom Classic (catalog import, XMP sidecars, edits inside DNGs and presets) now": "Les masques radiaux repris de Lightroom Classic (importation de catalogue, fichiers annexes XMP, retouches contenues dans des DNG et préréglages) appliquent", + "Ratings, flags, labels, keywords, collections/sets, virtual copies and supported edits migrate;": "Les notes, drapeaux, étiquettes, mots-clés, collections/jeux, copies virtuelles et retouches prises en charge migrent ;", + "Raw files whose raw data sits in a private block of a TIFF (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS": "Les fichiers RAW dont les données brutes se trouvent dans un bloc privé d'un TIFF (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds et Kodak DCS", + "Raws from 52 camera models (22 Canon, 11 Nikon, 11 Sony, 3 Fujifilm and 5 others, plus their other names) whose": "Les RAW de 52 modèles d'appareils (22 Canon, 11 Nikon, 11 Sony, 3 Fujifilm et 5 autres, plus leurs autres noms) dont le", + "Raws from cameras that correct their own JPEG for lens distortion (Panasonic and Fujifilm with that setting on, the": "Les RAW des appareils qui corrigent eux-mêmes la distorsion de l'objectif dans leur JPEG (Panasonic et Fujifilm avec ce réglage activé, le", + "Raws from older Nikon bodies no longer show a thin coloured or dark bar along one edge (the right edge, or the top": "Les RAW des anciens boîtiers Nikon ne montrent plus de fine barre colorée ou sombre le long d'un bord (le bord droit, ou le haut", + "Raws from the 52 camera models whose colour matrices LightCraft has measured (Sony ILCE-7M3, ILCE-7M4, ILCE-7RM3,": "Les RAW des 52 modèles d'appareils dont LightCraft a mesuré les matrices de couleur (Sony ILCE-7M3, ILCE-7M4, ILCE-7RM3,", + "Raws from the Nikon D600, D610 and D5000 no longer show a bright line down the right edge (issue #1627). Their": "Les RAW des Nikon D600, D610 et D5000 ne montrent plus de ligne claire le long du bord droit (ticket #1627). Leurs", + "Raws from the Nikon Z 6II, Z 8 and D5300 now start from a colour profile built from a few hundred photos from each camera, the same way the": "Les RAW des Nikon Z 6II, Z 8 et D5300 partent désormais d'un profil colorimétrique construit à partir de quelques centaines de photos de chaque appareil, de la même manière que les", + "Raws from the Nikon Z 6II, Z 8 and Z f now open with the camera's own distortion correction, as Lightroom applies a": "Les RAW des Nikon Z 6II, Z 8 et Z f s'ouvrent désormais avec la correction de distorsion propre à l'appareil, comme Lightroom applique un", + "Raws from the Pentax KP, KF, K-3 Mark III (and Monochrome), K-70, K-1, K-1 Mark II, K-S1, K-S2 and 645Z no longer": "Les RAW des Pentax KP, KF, K-3 Mark III (et Monochrome), K-70, K-1, K-1 Mark II, K-S1, K-S2 et 645Z ne montrent plus", + "Raws whose preview is in Adobe RGB (Sony α1 among others) no longer read the whole file for their grid thumbnail:": "Les RAW dont l'aperçu est en Adobe RGB (Sony α1 entre autres) ne lisent plus tout le fichier pour leur miniature de grille :", + "Recently Deleted is listed with All Photos, Recently Added and Picks under My Photos.": "Supprimées récemment figure avec Toutes les photos, Ajoutées récemment et Sélectionnées sous Mes photos.", + "Resetting a slider": "Réinitialiser un curseur", + "Reshuffle, another source, filter or sort, or new rules for the smart album shows what matches now.": "Mélanger à nouveau, une autre source, un autre filtre ou tri, ou de nouvelles règles pour l'album intelligent affichent ce qui correspond maintenant.", + "Resting the pointer on a slider's name or its thumb now says that a double-click resets it (\"Exposure — double-click": "Laisser le pointeur sur le nom d'un curseur ou sur sa poignée indique désormais qu'un double-clic le réinitialise (« Exposition — double-clic", + "Return presses OK in Choose Edit Settings to Copy (⇧⌘C) and Paste Selected Settings (⇧⌘V), and Esc cancels them": "Entrée appuie sur OK dans Choisir les réglages de retouche à copier (⇧⌘C) et Coller les réglages sélectionnés (⇧⌘V), et Échap les annule", + "Right-click Search Photos, a slider's typed value, the Info panel's fields, the name field of New Album, Rename": "Faites un clic droit sur Rechercher des photos, sur la valeur saisie d'un curseur, sur les champs du panneau Infos, sur le champ de nom de Nouvel album, Renommer", + "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Set Color Label ▸ a colour or None. The row": "Clic droit sur un dossier (ou un disque autre que le disque de démarrage) dans la section Dossiers de la barre latérale → Définir l'étiquette de couleur → une couleur ou Aucune. La ligne", + "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Synchronize": "Clic droit sur un dossier (ou un disque autre que le disque de démarrage) dans la section Dossiers de la barre latérale → Synchroniser", + "Right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder…": "Clic droit sur un dossier → Nouveau → Créer un album… / Créer un album intelligent… / Créer un album intelligent à partir du filtre… / Créer un dossier…", + "Right-click a photo ▸ Edit In ▸ Edit in PhotoCraft (or Photo ▸ Edit In, ⇧⌘E) renders a copy with your edits, stacks it": "Clic droit sur une photo → Modifier dans → Modifier dans PhotoCraft (ou Photo → Modifier dans, ⇧⌘E) calcule une copie avec vos retouches, l'empile", + "Right-click ▸ Put New Keywords Inside This Keyword: new keywords, made with + or typed in the box above, go inside": "Clic droit → Placer les nouveaux mots-clés dans celui-ci : les nouveaux mots-clés, créés avec + ou saisis dans le champ au-dessus, vont à l'intérieur", + "Rule problems are shown in your language and name the field the way the menu does (\"Title: needs something to look": "Les problèmes de règles s'affichent dans votre langue et nomment le champ comme le fait le menu (« Titre : il faut quelque chose à", + "Rule values are checked: a rating of 9, a date like 2026-13 or \"banana\", a \"between\" whose dates are the wrong": "Les valeurs des règles sont vérifiées : une note de 9, une date comme 2026-13 ou « banana », un « entre » dont les dates sont dans le mauvais", + "Samsung SRW files without compression now open as raws: NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1": "Les fichiers Samsung SRW non compressés s'ouvrent désormais comme des RAW : NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1", + "Save the current settings as a template of your own; right-click it to update it with the current settings, rename,": "Enregistrez les réglages actuels comme modèle personnel ; faites un clic droit dessus pour le mettre à jour avec les réglages actuels, le renommer,", + "Saving the catalog and resuming a model download no longer write through a link left at the temporary file's": "L'enregistrement du catalogue et la reprise d'un téléchargement de modèle n'écrivent plus à travers un lien laissé à l'emplacement du fichier temporaire", + "Sections are easier to tell apart: a hairline between them, the fold chevron in the same column as the rows'": "Les sections se distinguent plus facilement : un filet fin entre elles, le chevron de repli dans la même colonne que les", + "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Voir [inférence Metal distante](ai-masks.md#remote-metal-inference).", + "Select All and multi-selection show every selected photo in the grid and filmstrip, not only the active one": "Tout sélectionner et la sélection multiple affichent chaque photo sélectionnée dans la grille et la pellicule, pas seulement la photo active", + "Selected Settings). Ctrl+V only reaches LightCraft while the system clipboard holds text; otherwise use Edit ▸ Paste Edit": "les réglages sélectionnés). Ctrl+V n'atteint LightCraft que lorsque le presse-papiers du système contient du texte ; sinon, utilisez Modifier → Coller les", + "Setting or clearing a colour label shows a brief bottom confirmation, like rating a photo; custom label names appear in the message too.": "Définir ou effacer une étiquette de couleur affiche une brève confirmation en bas, comme pour noter une photo ; les noms d'étiquette personnalisés apparaissent aussi dans le message.", + "Settings stays put when you change tabs": "Les réglages restent en place quand vous changez d'onglet", + "Settings → Import → Cameras and Cards has an option to open the import review as soon as a camera or memory card": "Réglages → Importation → Appareils photo et cartes propose une option pour ouvrir la revue d'importation dès qu'un appareil photo ou une carte mémoire", + "Settings ▸ Display (issue #787). On P3 screens previews used to look more saturated than the exported files in": "Réglages → Écran (ticket #787). Sur les écrans P3, les aperçus paraissaient auparavant plus saturés que les fichiers exportés dans", + "Settings ▸ Display ▸ Choose Profile… shows photos through your monitor's ICC profile (matrix/TRC or LUT-based), so": "Réglages → Écran → Choisir un profil… affiche les photos à travers le profil ICC de votre moniteur (matrice/TRC ou LUT), de sorte que les", + "Settings ▸ General ▸ External Editing: the format (PSD or TIFF), colour space and bit depth for PhotoCraft and for": "Réglages → Général → Retouche externe : le format (PSD ou TIFF), l'espace colorimétrique et la profondeur de bits pour PhotoCraft et pour", + "Settings ▸ Interface ▸ Appearance Mode: Sync with System, Dark Mode or Light Mode, above a light": "Réglages → Interface → Mode d’apparence : Synchroniser avec le système, Mode sombre ou Mode clair, au-dessus d'une carte de thème clair", + "Settings.": "réglages de retouche.", + "Shortcuts are editable: Help ▸ Keyboard Shortcuts (⌘/) lists every command with a search box; click a shortcut and": "Les raccourcis sont modifiables : Aide → Raccourcis clavier (⌘/) liste toutes les commandes avec un champ de recherche ; cliquez sur un raccourci puis", + "Showing a Local folder now makes its first photo the active one, as albums and the other sources do (issue": "Afficher un dossier Local fait désormais de sa première photo la photo active, comme le font les albums et les autres sources (ticket", + "Sidebar sections": "Sections de la barre latérale", + "Size rules measure the photo as shown: Megapixels now counts the cropped photo, like Long Edge, Short Edge and": "Les règles de taille mesurent la photo telle qu'affichée : Mégapixels compte désormais la photo recadrée, comme Grand côté, Petit côté et", + "Sky, Subject and Background masks instead of our heuristics, so the sky is selected where the camera found it": "Sélectionner le ciel, Sélectionner le sujet et Sélectionner l'arrière-plan au lieu de nos heuristiques, si bien que le ciel est sélectionné là où l'appareil l'a trouvé", + "Slider drags follow the pointer more closely": "Le glissement des curseurs suit mieux le pointeur", + "Slider drags on large raws": "Glissement des curseurs sur les gros RAW", + "Slides can now be laid out like Lightroom Classic's Slideshow Layout, Options and Backdrop panels: margins (all four": "Les diapositives peuvent désormais être composées comme avec les panneaux Disposition, Options et Toile de fond du diaporama de Lightroom Classic : marges (les quatre", + "Slides can now carry Lightroom Classic's Slideshow overlays: an identity plate (a line of text in a colour, or an": "Les diapositives peuvent désormais porter les incrustations de diaporama de Lightroom Classic : une plaque d'identification (une ligne de texte d'une couleur, ou un", + "Slideshow export: PDF, JPEG and video": "Exportation du diaporama : PDF, JPEG et vidéo", + "Slideshow intro and ending screens": "Écrans d'introduction et de fin du diaporama", + "Slideshow layout, options and backdrop": "Disposition, options et toile de fond du diaporama", + "Slideshow overlays": "Incrustations du diaporama", + "Slideshow playback": "Lecture du diaporama", + "Slideshow templates": "Modèles de diaporama", + "Smaller JPEG exports": "Exportations JPEG plus légères", + "Smart album rules": "Règles des albums intelligents", + "Some EOS R6 Mark II C-RAW files (about 1 in 50 in one photographer's library) opened as their preview with": "Certains fichiers C-RAW de l'EOS R6 Mark II (environ 1 sur 50 dans la bibliothèque d'un photographe) s'ouvraient comme leur aperçu avec", + "Sony A7R II (and other) raws whose camera JPEG is lens-corrected no longer open grey and too dark (issue #232): the": "Les RAW du Sony A7R II (et d'autres) dont le JPEG d'appareil est corrigé de l'objectif ne s'ouvrent plus gris et trop sombres (ticket #232) : le", + "Sony A7R IVA) now start from colours closer to the camera's. The starting look was being fitted against a JPEG that": "Sony A7R IVA) partent désormais de couleurs plus proches de celles de l'appareil. Le rendu de départ était ajusté sur un JPEG qui", + "Sony A7R VI (ILCE-7RM6) raws are corrected for lens distortion from the table the camera records in each file,": "Les RAW du Sony A7R VI (ILCE-7RM6) sont corrigés de la distorsion de l'objectif à partir de la table que l'appareil enregistre dans chaque fichier,", + "Sony ILCA-99M2, ILCA-77M2, SLT-A33, DSC-RX10, ILCE-3500 and ILCE-7S raws now show white balance in Kelvin too,": "Les RAW des Sony ILCA-99M2, ILCA-77M2, SLT-A33, DSC-RX10, ILCE-3500 et ILCE-7S affichent désormais aussi la balance des blancs en kelvins,", + "Sony and Fujifilm profiles were made, instead of fitting each photo's colour on its own. Colours that one photo": "profils Sony et Fujifilm, au lieu d'ajuster la couleur de chaque photo séparément. Les couleurs dont une photo", + "Sony α1 (ILCE-1) and A7S III (ILCE-7SM3) raws for now; manual-focus shots and Wide shots that only report the frame": "Pour l'instant, les RAW du Sony α1 (ILCE-1) et de l'A7S III (ILCE-7SM3) ; les prises de vue en mise au point manuelle et en zone large qui ne signalent que le centre du cadre", + "Sort Contents A–Z (or + ▸ Sort Albums A–Z at the top level) goes back to by name. To put a folder after an open": "Trier le contenu de A à Z (ou + → Trier les albums de A à Z au premier niveau) revient au tri par nom. Pour placer un dossier après un", + "Still tallied from every photo on each edit: the filter bar's lists of cameras, lenses and keywords.": "Toujours recomptées à partir de chaque photo à chaque retouche : les listes d'appareils, d'objectifs et de mots-clés de la barre de filtres.", + "Straight brush strokes with ⇧-click": "Coups de pinceau droits avec ⇧-clic", + "Subfolder if you give one (say `Exports`), so a batch from several folders lands next to each set of originals.": "sous-dossier si vous en indiquez un (par exemple `Exports`), si bien qu'un lot provenant de plusieurs dossiers atterrit à côté de chaque ensemble d'originaux.", + "Switch to & Containing to see the keywords with the keywords containing them, or to Will Export to see what": "Passez à « et parents » pour voir les mots-clés avec les mots-clés qui les contiennent, ou à Sera exporté pour voir ce que", + "Switching libraries": "Changer de bibliothèque", + "Synchronize Folder asks a network share less": "Synchroniser le dossier interroge moins un partage réseau", + "Synonyms. Exports now write keyword names to `dc:subject` and their paths to `lr:hierarchicalSubject`, and keywords": "les synonymes. Les exportations écrivent désormais les noms de mots-clés dans `dc:subject` et leurs chemins dans `lr:hierarchicalSubject`, et les mots-clés", + "System Info, All Metadata and What's New end with one Close button, like About, instead of Cancel and OK": "Informations système, Toutes les métadonnées et Nouveautés se terminent par un seul bouton Fermer, comme À propos, au lieu de Annuler et OK", + "T) now matches.": "T) correspond désormais.", + "TIFFs) are no longer opened as a thumbnail-sized ordinary image. They are recognised as raws LightCraft can't decode": "TIFF) ne sont plus ouverts comme une image ordinaire de la taille d'une miniature. Ils sont reconnus comme des RAW que LightCraft ne sait pas décoder", + "Text fields": "Champs de texte", + "The English and Simplified Chinese build guides now describe command-local job and release": "Les guides de compilation en anglais et en chinois simplifié décrivent désormais, au niveau de la commande, les surcharges des tâches et de la", + "The Export dialog has **Add to Apple Photos**, with an optional album. The files are exported to your folder as": "La boîte de dialogue Exporter propose **Ajouter à Apple Photos**, avec un album facultatif. Les fichiers sont exportés dans votre dossier comme", + "The Export dialog has Export to: Specific folder (as before) or Same folder as original photo, like Lightroom": "La boîte de dialogue Exporter propose Exporter vers : Dossier spécifique (comme avant) ou Même dossier que la photo d’origine, comme Lightroom", + "The Hasselblad Lunar's raws (a Sony NEX-7 inside) now develop from their sensor data with every editing tool,": "Les RAW du Hasselblad Lunar (un Sony NEX-7 à l'intérieur) se développent désormais à partir de leurs données de capteur avec tous les outils de retouche,", + "The Import Photos review opens bigger and can be resized; its photo grid fills it (issue #337). Shift-click checks": "La revue d'importation de photos s'ouvre plus grande et peut être redimensionnée ; sa grille de photos la remplit (ticket #337). Le Maj-clic coche", + "The Keywords panel ends with a Keyword List, as in Lightroom Classic: every keyword with its photo count, those no": "Le panneau Mots-clés se termine par une Liste des mots-clés, comme dans Lightroom Classic : chaque mot-clé avec son nombre de photos, y compris ceux qu'aucune", + "The Presets panel builds only the rows in view (and their thumbnails) instead of every preset on every frame; the": "Le panneau Préréglages ne construit que les lignes visibles (et leurs miniatures) au lieu de tous les préréglages à chaque image ; les", + "The Settings window keeps its top edge and width when you switch tabs, so the tab row no longer jumps around": "La fenêtre Réglages conserve son bord supérieur et sa largeur quand vous changez d'onglet : la rangée d'onglets ne saute plus", + "The Tint slider works the right way round (issues #188, #321): left adds green, right adds magenta, as its track": "Le curseur Nuance fonctionne dans le bon sens (tickets #188, #321) : la gauche ajoute du vert, la droite ajoute du magenta, comme son rail", + "The Windows app no longer quits at launch with \"Parent device is lost\" when another program's `dxcompiler.dll` is": "L'application Windows ne quitte plus au lancement avec « Parent device is lost » quand le `dxcompiler.dll` d'un autre programme est", + "The Windows installer asks where to install LightCraft (Program Files by default; upgrades keep the folder you": "L'installateur Windows demande où installer LightCraft (Program Files par défaut ; les mises à jour gardent le dossier que vous", + "The catalog format is now version 3 (`Album.order`, `Op::SetAlbumOrder`). Once this version has opened a library,": "Le format de catalogue passe à la version 3 (`Album.order`, `Op::SetAlbumOrder`). Une fois que cette version a ouvert une bibliothèque,", + "The catalog format is now version 4 (`Catalog.folder_records`, `Op::SetFolderRecord`). Once this version has": "Le format de catalogue passe à la version 4 (`Catalog.folder_records`, `Op::SetFolderRecord`). Une fois que cette version a", + "The chips at the top of the Keywords panel are the keywords of every selected photo, not only the active one's; a": "Les pastilles en haut du panneau Mots-clés sont les mots-clés de toutes les photos sélectionnées, pas seulement de la photo active ; un", + "The choice is saved in export presets and Export with Previous. Agents pass": "Ce choix est enregistré dans les préréglages d'exportation et dans Exporter avec les réglages précédents. Les agents transmettent", + "The colour is described by the PNG `cICP` chunk, not an ICC profile. HDR-aware viewers (current Chromium-based": "La couleur est décrite par le bloc PNG `cICP`, et non par un profil ICC. Les visionneuses compatibles HDR (les navigateurs actuels basés sur Chromium,", + "The copy is a 16-bit PSD by default, which PhotoCraft saves straight back to with File ▸ Save; when you come back to": "La copie est un PSD 16 bits par défaut, dans lequel PhotoCraft enregistre directement avec Fichier → Enregistrer ; quand vous revenez à", + "The count beside each smart album in the left panel follows an edit the same way: the album asks only the photos": "Le nombre affiché à côté de chaque album intelligent dans le panneau de gauche suit une retouche de la même manière : l'album n'interroge que les photos", + "The desktop app keeps a log file: `logs/lightcraft.log` in its settings folder (Linux `~/.config/lightcraft/logs/`),": "L'application de bureau tient un fichier journal : `logs/lightcraft.log` dans son dossier de réglages (Linux `~/.config/lightcraft/logs/`),", + "The disk is still asked wherever a listing can't be sure what a file system would say: about a name that is": "Le disque est toujours interrogé là où une liste ne peut pas être sûre de ce que dirait un système de fichiers : à propos d'un nom qui est", + "The export runs in the background with its row in the activity stack; ✕ stops it and leaves no half-written file": "L'exportation s'exécute en arrière-plan avec sa ligne dans la pile d'activité ; × l'arrête et ne laisse aucun fichier à moitié écrit", + "The export watermark can be drawn on every slide's photo too (\"Use export watermark\" takes the one you last": "Le filigrane d'exportation peut aussi être dessiné sur la photo de chaque diapositive (« Utiliser le filigrane d'exportation » reprend celui que vous avez utilisé", + "The eye on the Light, Color and Detail section headers now hides their adjustments, as it already did for Effects,": "L'œil des en-têtes de section Lumière, Couleur et Détail masque désormais leurs réglages, comme il le faisait déjà pour Effets,", + "The first time, macOS asks whether LightCraft may control Photos. Photos may ask about duplicates; files it skips": "La première fois, macOS demande si LightCraft peut contrôler Photos. Photos peut poser des questions sur les doublons ; les fichiers qu'il ignore", + "The interface is available in Spanish (issue #371), German and Russian (Edit ▸ Language), alongside English,": "L'interface est disponible en espagnol (ticket #371), en allemand et en russe (Modifier → Langue), en plus de l'anglais,", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off (while repeating": "L'introduction est lue une fois avant la première photo ; l'écran de fin après la dernière photo quand Répéter est désactivé (en cas de répétition,", + "The kept original no longer pushes everything else out of the cache: on a 64 MP raw it filled the cache share": "L'original conservé ne chasse plus tout le reste du cache : sur un RAW de 64 Mpx, il remplissait à lui seul la part", + "The keyword set's buttons and the suggestions follow the selection too; the typing boxes get the Cut / Copy / Paste": "Les boutons du jeu de mots-clés et les suggestions suivent aussi la sélection ; les champs de saisie reçoivent le", + "The loupe says \"Rendering…\" at the bottom of the photo when what it shows isn't the finished photo yet: the": "La loupe affiche « Rendu en cours… » au bas de la photo quand ce qu'elle montre n'est pas encore la photo finie : le", + "The open library's name shows under My Photos at the top of the left panel and in the window title.": "Le nom de la bibliothèque ouverte s'affiche sous Mes photos en haut du panneau de gauche et dans le titre de la fenêtre.", + "The rule editor marks each rule that needs fixing right under it and keeps OK disabled until they are fixed. An": "L'éditeur de règles signale chaque règle à corriger juste en dessous et garde OK désactivé tant qu'elles ne sont pas corrigées. Une", + "The rule editor's field menu is grouped: Rating, Pick Flag, Color Label and Any Searchable Text at the top, then": "Le menu des champs de l'éditeur de règles est regroupé : Note, Drapeau de sélection, Étiquette de couleur et N'importe quel texte pouvant être recherché en haut, puis", + "The same photos give the same HDR whatever order they are selected in; before, a different order could change a": "Les mêmes photos donnent le même HDR quel que soit l'ordre de sélection ; auparavant, un ordre différent pouvait modifier", + "The side panels keep a tally an edit cannot have changed: a rating or a slider changes none of the folders,": "Les panneaux latéraux conservent un décompte qu'une retouche n'a pas pu modifier : une note ou un curseur ne change aucun des dossiers,", + "The starting look fitted from a raw's camera JPEG now uses its darkest tones too (issue #1307).": "Le rendu de départ ajusté à partir du JPEG de l'appareil d'un RAW utilise désormais aussi ses tons les plus sombres (ticket #1307).", + "The thumbnail cache is no longer taken for your photos": "Le cache des miniatures n'est plus pris pour vos photos", + "The thumbnail cache no longer follows a shard folder (`thumbs/ab/`) that is a symlink or junction to somewhere": "Le cache des miniatures ne suit plus un dossier de fragment (`thumbs/ab/`) qui est un lien symbolique ou une jonction vers un autre", + "The titles **Keywords** and **Keyword List** in the Keywords panel fold their sections shut and open again, so": "Les titres **Mots-clés** et **Liste des mots-clés** du panneau Mots-clés replient et déplient leurs sections, de sorte que", + "The top bar has an Import button, beside Export, in every library.": "La barre supérieure comporte un bouton Importer, à côté d'Exporter, dans toutes les bibliothèques.", + "The top bar's appearance button cycles Auto, Light, Dark (a monitor, sun or moon), and View ▸": "Le bouton d'apparence de la barre supérieure fait défiler Auto, Clair, Sombre (un moniteur, un soleil ou une lune), et Affichage →", + "The window opens at the size you left it": "La fenêtre s'ouvre à la taille où vous l'avez laissée", + "They are now kept under a name that is no picture's. The ones already there are taken over, not rendered again:": "Elles sont désormais conservées sous un nom qui n'est celui d'aucune image. Celles qui existent déjà sont reprises, pas recalculées :", + "This does not change colour matrices, camera calibration or RAW noise rendering.": "Cela ne modifie ni les matrices de couleur, ni le calibrage de l'appareil, ni le rendu du bruit des RAW.", + "Thumbnail cache stays in its folder": "Le cache des miniatures reste dans son dossier", + "Thumbnails and previews are written to the cache on disk by one background writer instead of a new thread for": "Les miniatures et les aperçus sont écrits dans le cache sur disque par un seul écrivain en arrière-plan plutôt que par un nouveau fil pour", + "Thumbnails of raw files appear sooner": "Les miniatures des fichiers RAW apparaissent plus tôt", + "Told when there is no GPU": "Avertissement quand il n'y a pas de GPU", + "Trackpads: pinch to zoom around the pointer and scroll with two fingers to pan the photo; panning keeps the photo": "Pavés tactiles : pincez pour zoomer autour du pointeur et faites défiler à deux doigts pour déplacer la photo ; le déplacement garde la photo", + "Type an exact value into any slider (issue #322): click the number next to its name, type (`1.5`, `-20`, `5600`)": "Saisissez une valeur exacte dans n'importe quel curseur (ticket #322) : cliquez sur le nombre à côté de son nom, tapez (`1.5`, `-20`, `5600`)", + "Typing in **Add keyword** offers the library's matching keywords right under the box. ↓ and Return (or a click)": "Saisir dans **Ajouter un mot-clé** propose les mots-clés correspondants de la bibliothèque juste sous le champ. ↓ et Entrée (ou un clic)", + "Upgrading from a Windows installer older than 0.6 (such as 0.5.0) keeps LightCraft in the folder it was installed": "La mise à jour depuis un installateur Windows antérieur à 0.6 (comme 0.5.0) garde LightCraft dans le dossier où il avait été", + "VLC and recent phones and TVs play it.": "VLC et les téléphones et téléviseurs récents le lisent.", + "When GPU rendering is on but no graphics processor can be found, LightCraft now says so once at start-up instead": "Quand le rendu GPU est activé mais qu'aucun processeur graphique n'est trouvé, LightCraft le signale désormais une fois au démarrage au lieu", + "When a folder holds several file types, the Import Photos review has a toggle per type (`ARW · 120`, `JPG · 120`):": "Quand un dossier contient plusieurs types de fichiers, la revue d'importation de photos propose un interrupteur par type (`ARW · 120`, `JPG · 120`) :", + "When the graphics driver resets the GPU while LightCraft is exporting or rendering (issue #1337, seen on Windows": "Quand le pilote graphique réinitialise le GPU pendant que LightCraft exporte ou calcule un rendu (ticket #1337, observé sous Windows", + "Where the camera focused": "Là où l'appareil a fait la mise au point", + "While it plays, moving the pointer shows a small control bar: previous, play / pause, next, the slide number and": "Pendant la lecture, déplacer le pointeur affiche une petite barre de commande : précédent, lecture / pause, suivant, le numéro de la diapositive et", + "White balance on DNGs (and other raws with a colour matrix) re-develops the photo for the new white through the": "La balance des blancs sur les DNG (et les autres RAW avec une matrice de couleur) redéveloppe la photo pour le nouveau blanc à travers les", + "Wide (16:9 with black bars, the title in the corner, fades through black and a closing card) and Shooting Data (the": "large (16:9 avec bandes noires, le titre dans le coin, fondus par le noir et une carte de fin) et Données de prise de vue (la", + "With **HDR output** on, a photo edited in HDR can now be exported as a **16-bit PNG** with the PQ curve in Rec. 2020,": "Avec la **sortie HDR** activée, une photo retouchée en HDR peut désormais être exportée en **PNG 16 bits** avec la courbe PQ en Rec. 2020,", + "With Dehaze on, panning a photo zoomed to 1:1 or moving a slider while zoomed no longer samples the whole": "Avec la correction du voile activée, déplacer une photo zoomée à 1:1 ou bouger un curseur en zoom n'échantillonne plus tout", + "With a GPU, a slider drag's preview is drawn in the same frame as the slider moves instead of one frame later,": "Avec un GPU, l'aperçu d'un glissement de curseur est dessiné dans la même image que le déplacement du curseur au lieu d'une image plus tard,", + "With automatic XMP writing on, an edit to a photo whose folder can't be written (a network share that dropped": "Avec l'écriture XMP automatique activée, une retouche d'une photo dont le dossier n'est pas accessible en écriture (un partage réseau qui s'est", + "With no filter set, the count of the source is taken from the list instead of from a second pass over the library.": "Sans filtre défini, le nombre de photos de la source est tiré de la liste au lieu d'un second parcours de la bibliothèque.", + "With several photos selected, the Keywords panel says how many photos its keywords belong to. The × on a keyword": "Quand plusieurs photos sont sélectionnées, le panneau Mots-clés indique à combien de photos appartiennent ses mots-clés. Le × d'un mot-clé", + "With that, the frame after a keyword is at about 29 ms there. New rules, a change to an album or the keyword list,": "Avec cela, l'image affichée après un mot-clé tombe à environ 29 ms. De nouvelles règles, une modification d'un album ou de la liste de mots-clés,", + "With the brush, click once, then ⇧-click somewhere else: the brush paints a straight line between the two, and": "Avec le pinceau, cliquez une fois, puis faites un ⇧-clic ailleurs : le pinceau trace une ligne droite entre les deux, et", + "Writing one photo's XMP sidecar (Save Metadata to File, or automatically after an edit) no longer works out who": "L'écriture du fichier annexe XMP d'une photo (Enregistrer les métadonnées dans le fichier, ou automatiquement après une retouche) ne détermine plus qui", + "XMP presets apply their red / green / blue curves only when they also have the master curve and all three channel": "Les préréglages XMP n'appliquent leurs courbes rouge / verte / bleue que s'ils ont aussi la courbe principale et les trois", + "XMP sidecars catch up after a network share comes back": "Les fichiers annexes XMP se remettent à jour au retour d'un partage réseau", + "Yes/no fields (Has Edits, Cropped, Has GPS…) read Yes / No instead of true / false. A rule sent as `\"false\"` now": "Les champs oui/non (Avec retouches, Recadrée, Avec GPS…) affichent Oui / Non au lieu de true / false. Une règle envoyée comme `\"false\"` signifie désormais", + "Zoomed 64 MP raws stay decoded": "Les RAW de 64 Mpx zoomés restent décodés", + "Zooming in with Before/After side by side decodes the original once: the Before side used to decode its own copy": "Zoomer avec Avant/Après côte à côte décode l'original une seule fois : le côté Avant décodait auparavant sa propre copie", + "[camera preview colour](camera-preview-colour.md#spectral-camera-matrices-and-the-order-of-precedence).": "[couleur d'aperçu de l'appareil](camera-preview-colour.md#spectral-camera-matrices-and-the-order-of-precedence).", + "`*.jpg` case-sensitively, so `.JPG` and `.NEF` files were hidden — issues #342 and #705).": "`*.jpg` en respectant la casse, si bien que les fichiers `.JPG` et `.NEF` étaient masqués — tickets #342 et #705).", + "`--import ` takes HEIC": "`--import ` accepte le HEIC", + "`--memory` sessions keep their promise to save nothing (issues #164, #169): UI changes made in one no longer": "Les sessions `--memory` tiennent leur promesse de ne rien enregistrer (tickets #164, #169) : les changements d'interface faits dans l'une ne", + "`.jpg`) have always been taken for the cache's, and are renamed with it.": "`.jpg`) ont toujours été pris pour ceux du cache, et sont renommés avec lui.", + "`.lrcat-data` folders, or the `.lrcat`) no longer makes an empty LightCraft library inside it (issue #891). The": "`.lrcat-data`, ou le `.lrcat`) ne crée plus de bibliothèque LightCraft vide à l'intérieur (ticket #891). La", + "`Shift+6–9` labels and advances. `Shift+P` picks and advances in Photo Grid and Square Grid; it opens Presets in other views. With Auto Advance on, Shift still moves only once.": "`Maj+6–9` attribue l'étiquette et avance. `Maj+P` marque comme sélectionnée et avance dans la grille de photos et la grille carrée ; il ouvre Préréglages dans les autres vues. Avec Avance automatique activée, Maj ne fait toujours avancer qu'une fois.", + "`destinationMode: \"sameAsOriginal\"` (or `\"specificFolder\"`) to `app.export`; `dir` is then not needed.": "`destinationMode: \"sameAsOriginal\"` (ou `\"specificFolder\"`) à `app.export` ; `dir` n'est alors pas nécessaire.", + "`develop.curve` are kept in order, and a sidecar curve with a \"NaN\" or \"inf\" point is ignored.": "`develop.curve` sont gardés dans l'ordre, et une courbe de fichier annexe contenant un point « NaN » ou « inf » est ignorée.", + "`export.photosImports`. See [Add to Apple Photos](apple-photos.md).": "`export.photosImports`. Voir [Ajouter à Apple Photos](apple-photos.md).", + "`lightcraft-cli --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`lightcraft-cli --library` appelé avec le fichier propre d'une bibliothèque (`catalog.snap`) ouvre son dossier au lieu d'échouer avec", + "`lightcraft-cli run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`lightcraft-cli run --import ` (et les outils MCP qui acceptent des dossiers) prend désormais en compte les fichiers HEIC, HEIF et Nikon NRW,", + "`lightcraft-cli` logs warnings on stderr too (issue #168); `LIGHTCRAFT_LOG` or `RUST_LOG` picks another level.": "`lightcraft-cli` consigne aussi les avertissements sur stderr (ticket #168) ; `LIGHTCRAFT_LOG` ou `RUST_LOG` choisit un autre niveau.", + "`mask.brushStroke {connect: true}` does the same for agents.": "`mask.brushStroke {connect: true}` fait de même pour les agents.", + "`publicDomain` (rules and agents keep using the ids; `album.ruleFields` adds `choiceLabels`).": "`publicDomain` (les règles et les agents continuent d'utiliser les identifiants ; `album.ruleFields` ajoute `choiceLabels`).", + "`slideshow.overlays`; `slideshow.preview` now also returns where each overlay landed.": "`slideshow.overlays` ; `slideshow.preview` renvoie désormais aussi l'emplacement de chaque incrustation.", + "`slideshow.playback`; `view.slideshow` takes any of them for one run (`interval` still sets the slide duration).": "`slideshow.playback` ; `view.slideshow` accepte n'importe lequel d'entre eux pour une lecture (`interval` règle toujours la durée de la diapositive).", + "`{file}`, `{date}`, `{exposure}` (\"1/250 s at f/8\"), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` and the": "`{file}`, `{date}`, `{exposure}` (« 1/250 s à f/8 »), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` et les", + "a Synchronize scan began (now under 1 s), 2.6 s before an import review (now 0.05 s) and 1.7 s before an import": "le début d'une analyse de synchronisation (désormais moins de 1 s), 2,6 s avant une revue d'importation (désormais 0,05 s) et 1,7 s avant une importation", + "a cast shadow (opacity, offset, radius, angle), and a backdrop colour with an optional colour wash (a gradient from a": "une ombre portée (opacité, décalage, rayon, angle), et une couleur de toile de fond avec un dégradé de couleur facultatif (un dégradé à partir d'une", + "a flag taken off in Picks, a rating that falls under the filter bar's. With it off, as before, the photo leaves the": "un drapeau retiré dans Sélectionnées, une note qui passe sous celle de la barre de filtres. Désactivée, comme avant, la photo quitte la", + "a line, a tab per level, synonyms in braces, keywords left out of export in brackets). Capture One, darktable, Adobe": "par ligne, une tabulation par niveau, les synonymes entre accolades, les mots-clés exclus de l'exportation entre crochets). Capture One, darktable, Adobe", + "a magazine cover's masthead and cover lines, so you can frame a shot for the page it is made for. It fits inside": "le bandeau-titre et les accroches d'une couverture de magazine, pour cadrer une prise de vue en fonction de la page à laquelle elle est destinée. Elle s'ajuste à l'intérieur", + "a photo stop matching the view keeps it in the view: a keyword given in a smart album of photos without keywords,": "qu'une photo cesse de correspondre à la vue la maintient dans la vue : un mot-clé attribué dans un album intelligent de photos sans mot-clé,", + "adjust or switch them off, and DNG export keeps them. Lateral chromatic aberration data is not applied: our": "les ajustent ou les désactivent, et l'exportation DNG les conserve. Les données d'aberration chromatique latérale ne sont pas appliquées : notre", + "advance (the next two slides render while the current one is up, so a fade never waits or flashes).": "l'avance (les deux diapositives suivantes sont calculées pendant que celle en cours est affichée, de sorte qu'un fondu n'attend ni ne clignote jamais).", + "after a rename, an `.XMP` sidecar. Adding photos or a folder, Browse Folder (Local), drag-and-drop, the CLI and the": "après un renommage, un fichier annexe `.XMP`. L'ajout de photos ou d'un dossier, Parcourir le dossier (Local), le glisser-déposer, la CLI et la", + "again.": "de nouveau.", + "album that is gone, or an empty group is reported with its rule (\"rule 2.1: no rating 0–5 is 9\")": "album disparu ou un groupe vide est signalé avec sa règle (« règle 2.1 : 9 n'est pas une note entre 0 et 5 »)", + "album, Delete changes nothing: its rules decide what it shows.": "intelligent, Supprimer ne change rien : ce sont ses règles qui décident de ce qu'il affiche.", + "all again.": "tous.", + "alone, so the photo's preview and thumbnail sources and its neighbours' were decoded from the raw again on every": "de cache, si bien que les sources de l'aperçu et de la miniature de la photo, et celles de ses voisines, étaient redécodées depuis le RAW à chaque", + "also holds files of yours (a library opened on a photo folder that had one) is not tagged, and your files in it": "contient aussi des fichiers à vous (une bibliothèque ouverte sur un dossier de photos qui en avait un) n'est pas balisé, et vos fichiers qu'il contient", + "an edit to more than 256 photos, and each new minute for an album that asks about \"the last N days\" are still": "une retouche de plus de 256 photos, et chaque nouvelle minute pour un album qui s'intéresse aux « N derniers jours » sont toujours", + "and CR3, instead of opening flat and desaturated (issue #310). Photos already imported pick it up when re-rendered.": "et CR3, au lieu de s'ouvrir plats et désaturés (ticket #310). Les photos déjà importées en bénéficient quand elles sont recalculées.", + "and Survey, following rotation and crops; the Info panel says how it focused (`AF-C · Wide · Animal Eye Tracking`).": "et Vue multiple, en suivant la rotation et les recadrages ; le panneau Infos indique comment elle a fait la mise au point (`AF-C · Wide · Animal Eye Tracking`).", + "and WB2000. The compressed ones (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini) still open from their": "et WB2000. Les fichiers compressés (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini) s'ouvrent toujours à partir de leur", + "and a dark theme card, each previewing its theme (dark: Charcoal, the look so far, or Midnight;": "et d'une carte de thème sombre, chacune présentant un aperçu de son thème (sombre : Anthracite, l'aspect jusqu'ici, ou Minuit ;", + "and a section with nothing in it says so instead of disappearing.": "et une section vide le dit au lieu de disparaître.", + "and a smaller export look like the full-size result scaled down; 1:1 views and full-size exports are unchanged.": "et une exportation plus petite ressemblent au résultat pleine taille réduit ; les vues 1:1 et les exportations pleine taille sont inchangées.", + "and a view that asks about \"the last N days\".": "et une vue qui s'intéresse aux « N derniers jours ».", + "and exports don't change. Agents use `app.displayProfile`. See [display profiles](display-profiles.md).": "et les exportations ne changent pas. Les agents utilisent `app.displayProfile`. Voir [profils d'écran](display-profiles.md).", + "and its Cancel / OK buttons were off screen, so it couldn't be confirmed. Now its options scroll and the title and": "et ses boutons Annuler / OK étaient hors de l'écran, si bien qu'on ne pouvait pas la valider. Désormais ses options défilent et le titre et", + "and new photos never reuse an id in use. What was repaired is written to the log.": "et les nouvelles photos ne réutilisent jamais un identifiant déjà employé. Ce qui a été réparé est consigné dans le journal.", + "and other files with embedded distortion / vignetting corrections), matching what the preset does elsewhere.": "et autres fichiers avec corrections de distorsion / vignetage intégrées), conformément à ce que fait le préréglage ailleurs.", + "and press Return; Esc keeps the old value.": "et appuyez sur Entrée ; Échap conserve l'ancienne valeur.", + "and the control bar says Intro or End while one is up (the photo count only counts photos).": "et la barre de commande indique Intro ou Fin quand l'un d'eux est affiché (le compteur de photos ne compte que les photos).", + "and the fit to the photo's own JPEG still come first, so photos that had a fitted look keep it. See": "et l'ajustement sur le JPEG propre de la photo passent toujours en premier, de sorte que les photos qui avaient un rendu ajusté le conservent. Voir", + "answered there too. In such a folder the scan saves less, and its checks now start after the listing where they": "eux aussi traités dans la liste. Dans un tel dossier, l'analyse économise moins, et ses vérifications démarrent désormais après la liste alors qu'elles", + "app, and with LightCraft fullscreen it was hidden altogether, so Import Photos… looked like a hang until the": "l'application, et avec LightCraft en plein écran elle était entièrement masquée, si bien qu'Importer des photos… ressemblait à un blocage jusqu'à ce que la", + "apply their effect inside the circle, as Lightroom does, instead of outside it (issue #1815). A mask inverted in": "désormais leur effet à l'intérieur du cercle, comme le fait Lightroom, au lieu de l'extérieur (ticket #1815). Un masque inversé dans", + "are left as they are. Note that files there named exactly like the cache's own (`ab/ab…` with 32 hex digits and": "sont laissés tels quels. Notez que les fichiers qui y portent exactement un nom comme ceux du cache (`ab/ab…` avec 32 chiffres hexadécimaux et", + "are unchanged; photos imported before this change get it when imported again.": "sont inchangés ; les photos importées avant ce changement l'obtiennent quand elles sont réimportées.", + "are unchanged; the guidance does not guarantee a build will fit every 16 GB machine.": "restent inchangés ; ces indications ne garantissent pas qu'une compilation tienne sur toutes les machines de 16 Go.", + "as 1/250), File Extension, Video Duration, Copy Name, In a Stack, Alt Text, City, State / Province, Country, Long": "comme 1/250), Extension de fichier, Durée de la vidéo, Nom de la copie, Dans une pile, Texte alternatif, Ville, État / province, Pays, Grand", + "as Exposure would; the edges between bright and dark regions stay as sharp as before. This is rendering process 2:": "comme le ferait l'exposition ; les bords entre zones claires et sombres restent aussi nets qu'avant. C'est le traitement de rendu 2 :", + "as a raw and shows its embedded preview (preview only, with the reason), as the compressed MOS files do.": "comme un RAW et affiche son aperçu intégré (aperçu uniquement, avec la raison), comme le font les fichiers MOS compressés.", + "as before.": "comme avant.", + "as it changes, without polling.": "quand il change, sans interrogation périodique.", + "at the camera JPEG's size (6016 × 4016 for the D600 and D610, 4288 × 2848 for the D5000, as the D90 already": "à la taille du JPEG de l'appareil (6016 × 4016 pour les D600 et D610, 4288 × 2848 pour le D5000, comme le D90 le", + "at their import settings). See `docs/sony-ilce7rm6-lens-corrections.md`.": "à leurs réglages d'importation). Voir `docs/sony-ilce7rm6-lens-corrections.md`.", + "bad (issue #1512): a compressed PEF whose data is too short for the size it declares, an uncompressed TIFF-based": "défectueux (ticket #1512) : un PEF compressé dont les données sont trop courtes pour la taille déclarée, un RAW non compressé de type TIFF", + "becomes a keyword unnoticed. The suggestions further down stay put while you type.": "devient plus un mot-clé sans être remarquée. Les suggestions plus bas restent en place pendant la saisie.", + "before it looks at the first file. In a library of 3.5 million photos that held the window for about 6 s before": "avant d'examiner le premier fichier. Dans une bibliothèque de 3,5 millions de photos, cela bloquait la fenêtre pendant environ 6 s avant", + "before, and becomes the Kelvin value with the same look the next time it is edited. A photo imported earlier shows": "avant, et devient la valeur en kelvins de même rendu à la prochaine retouche. Une photo importée auparavant affiche", + "before. Agents use `slideshow.layout`, and `slideshow.preview` returns one composed slide as a PNG.": "avant. Les agents utilisent `slideshow.layout`, et `slideshow.preview` renvoie une diapositive composée sous forme de PNG.", + "behaviour, `fresh` imports a clean copy and deletes the old record).": "comportement, `fresh` importe une copie neuve et supprime l'ancien enregistrement).", + "behind. A photo that can't be read is skipped and named in the message at the end. Agents use `slideshow.export`": "derrière lui. Une photo illisible est ignorée et nommée dans le message final. Les agents utilisent `slideshow.export`", + "belonged to another command moves to the new one. Menus show the new keys; agents use `app.setShortcut`.": "appartenait à une autre commande passe à la nouvelle. Les menus affichent les nouvelles touches ; les agents utilisent `app.setShortcut`.", + "beside the After's, and a window asked for again while the first was still decoding (a pan, the layout settling)": "à côté de celle du côté Après, et une fenêtre redemandée alors que la première était encore en cours de décodage (un déplacement, la disposition qui se stabilise)", + "beside them is; they used to stay at regular weight.": "qui les accompagne ; ils restaient auparavant en graisse normale.", + "between slides (a crossfade, or through black, white or any colour; 0 cuts), random order (every photo once per": "entre les diapositives (un fondu enchaîné, ou par le noir, le blanc ou n'importe quelle couleur ; 0 coupe net), ordre aléatoire (chaque photo une fois par", + "brings in something (Import N Photos, Merge, Save, Create, Download…). Delete and Remove stay plain, so a destructive": "importe quelque chose (Importer N photos, Fusionner, Enregistrer, Créer, Télécharger…). Supprimer et Retirer restent sobres, de sorte qu'un choix destructeur", + "browsers, for example) show it in HDR; **viewers that don't read `cICP` show the PQ values as if they were sRGB**,": "par exemple) l'affichent en HDR ; **les visionneuses qui ne lisent pas `cICP` affichent les valeurs PQ comme si elles étaient en sRGB**,", + "built-in profile: straight lines near the edges stay straight and the framing matches the camera's JPEG. It works": "profil intégré : les lignes droites près des bords restent droites et le cadrage correspond à celui du JPEG de l'appareil. Elle fonctionne", + "burst by file name, so the first file is the cover.": "rafale par nom de fichier, de sorte que le premier fichier sert de couverture.", + "buttons stay visible. Long lists in dialogs (What's New, All Metadata, Keyboard Shortcuts) get shorter to fit.": "les boutons restent visibles. Les longues listes des boîtes de dialogue (Nouveautés, Toutes les métadonnées, Raccourcis clavier) raccourcissent pour tenir.", + "by double-clicking it, delete one with − after a confirmation. Right-click for more: create inside, Put New Keywords": "par double-clic, supprimez-en un avec − après confirmation. Clic droit pour plus d'options : créer à l'intérieur, Placer les nouveaux mots-clés", + "camera JPEG can't be fitted no longer open with the neutral fallback: they start from colour matrices fitted to the": "JPEG d'appareil ne peut pas servir à l'ajustement ne s'ouvrent plus avec le repli neutre : ils partent de matrices de couleur ajustées sur les", + "camera JPEG. Photos already imported pick the change up on Reload.": "JPEG d'appareil. Les photos déjà importées prennent le changement en compte au rechargement.", + "camera's embedded JPEG while a raw decodes, the previous render while an edit renders, or the magnified frame": "JPEG intégré de l'appareil pendant le décodage d'un RAW, le rendu précédent pendant le calcul d'une retouche, ou l'image agrandie", + "camera's measured spectral sensitivities, from the Academy Software Foundation's rawtoaces-data. A camera profile": "sensibilités spectrales mesurées de l'appareil, issues du rawtoaces-data de l'Academy Software Foundation. Un profil d'appareil", + "camera's own colour matrices, as Lightroom does, instead of shifting the colours of the as-shot rendering: a grey": "matrices de couleur propres à l'appareil, comme le fait Lightroom, au lieu de décaler les couleurs du rendu tel que pris : un gris", + "camera's own zoom to fill the frame) and vignetting, as with Panasonic and Sony files. The Optics profile controls": "zoom propre à l'appareil pour remplir le cadre) et vignetage, comme pour les fichiers Panasonic et Sony. Les commandes de profil de la section Optique", + "can be attached to a report without hunting for the settings folder (issue #260).": "puisse être joint à un rapport sans chercher le dossier de réglages (ticket #260).", + "can't be picked, such as one that would make an album include itself, are greyed with the reason. Esc with a dropdown or calendar open in a dialog": "ne peuvent pas être choisis, comme un album qui ferait qu'un album s'inclue lui-même, sont grisés avec la raison. Échap, avec une liste déroulante ou un calendrier ouvert dans une boîte de dialogue,", + "carries Huffman tables made for its own picture instead of the standard example tables. Every viewer opens them": "contient désormais des tables de Huffman établies pour sa propre image au lieu des tables d'exemple standard. Tous les lecteurs les ouvrent", + "carries the slide duration and fade, so a PDF viewer's presentation mode plays it as a slideshow, and \"Automatically": "porte la durée et le fondu de la diapositive, de sorte que le mode présentation d'un lecteur PDF le lit comme un diaporama, et « Afficher", + "centre show nothing. More cameras will follow. Details: [focus-points.md](focus-points.md).": "n'affichent rien. D'autres appareils suivront. Détails : [focus-points.md](focus-points.md).", + "centre, and can be turned off under Lens Corrections. Vignetting correction from the file comes later.": "optique, et peut être désactivée sous Corrections de l'objectif. La correction du vignetage depuis le fichier viendra plus tard.", + "change to an album, a stack or the keyword list, an album shown in its own order, Recently Added, Missing Photos,": "modification d'un album, d'une pile ou de la liste de mots-clés, un album affiché dans son propre ordre, Ajoutées récemment, Photos manquantes,", + "changed doesn't put its faces on the new one (issue #1524).": "a changé ne place plus ses visages sur le nouveau (ticket #1524).", + "changing pixels along their edge. The hard edge now leaves pixels on the radius unchanged.": "modifiaient des pixels le long de leur bord. Le bord net laisse désormais inchangés les pixels situés sur le rayon.", + "choice is never the eye-catching default.": "ne soit jamais le choix par défaut qui attire l'œil.", + "choice next to that (Restore them / Import as new / Leave them) now starts on Restore. Files dropped on the window": "choix à côté (Les restaurer / Importer comme nouvelles / Les laisser) démarre désormais sur Les restaurer. Les fichiers déposés sur la fenêtre", + "choose what to do: import the new photos and relink the moved ones (the defaults), move the missing ones to Recently": "choisissez que faire : importer les nouvelles photos et relier celles qui ont été déplacées (les choix par défaut), déplacer les manquantes vers Supprimées", + "choosing a profile file.": "le choix d'un fichier de profil.", + "chose) and ends on a page saying it was installed, with a \"Launch LightCraft\" box. It used to finish without a word,": "avez choisi) et se termine sur une page indiquant que l'installation est faite, avec une case « Lancer LightCraft ». Il se terminait auparavant sans un mot,", + "clipped highlights.": "hautes lumières écrêtées.", + "closes just that.": "ne ferme que cela.", + "codecs' `heif` feature — 8- and 10-bit, alpha, grid tiles, the container's rotation/mirror/crop, ICC, EXIF and XMP.": "la fonctionnalité `heif` de codecs — 8 et 10 bits, alpha, tuiles en grille, rotation/miroir/recadrage du conteneur, ICC, EXIF et XMP.", + "colours are right on wide-gamut and calibrated displays instead of oversaturated. The Detail view renders straight": "couleurs soient justes sur les écrans à large gamme de couleurs et calibrés au lieu d'être sursaturées. La vue Détail calcule directement", + "comes back as large as you left it, but not as a zoomed window. That is so after a zoom from the Window menu": "revient aussi grande que vous l'avez laissée, mais pas comme une fenêtre zoomée. C'est le cas après un zoom depuis le menu Fenêtre", + "compiler built into Windows (FXC). `WGPU_DX12_COMPILER=dxc` uses a `dxcompiler.dll` instead.": "compilateur intégré à Windows (FXC). `WGPU_DX12_COMPILER=dxc` utilise plutôt un `dxcompiler.dll`.", + "computer has is refused with the size it would take, before it starts.": "l'ordinateur n'en possède est refusé avec la taille qu'il prendrait, avant de commencer.", + "contains it: `Canon EOS R6` stays `Canon EOS R6`, rather than `Canon Canon EOS R6` (the camera": "contient déjà : `Canon EOS R6` reste `Canon EOS R6`, et non `Canon Canon EOS R6` (le sous-ticket", + "controls work as they did. With the default layout (no margins, border, shadow or backdrop) it plays the photos as": "commandes de lecture fonctionnent comme avant. Avec la disposition par défaut (sans marges, contour, ombre ni toile de fond), il lit les photos comme", + "correction on (24–70 mm, 100 mm macro, 200–600 mm) the render lines up with the camera's JPEG within 0.68 px at": "correction activée (24–70 mm, macro 100 mm, 200–600 mm), le rendu s'aligne sur le JPEG de l'appareil à 0,68 px près à", + "correction, checked against Sony's exports; other Sony bodies record the same tables, but they stay uncorrected until": "correction de la distorsion, vérifiée par rapport aux exportations de Sony ; les autres boîtiers Sony enregistrent les mêmes tables, mais restent non corrigés tant que", + "counted from every photo.": "comptés à partir de chaque photo.", + "covers lossless, Compressed and Compressed HQ (ARW 6.0) ARWs alike. The A7R IVA (ILCE-7RM4A) has its own distortion": "vaut aussi bien pour les ARW sans perte que Compressed et Compressed HQ (ARW 6.0). L'A7R IVA (ILCE-7RM4A) a sa propre", + "crashes LightCraft each time it renders: the amount acts as 20.": "fait plus planter LightCraft à chaque rendu : la quantité vaut alors 20.", + "curves, as Lightroom does: a preset with just one channel curve (or no master curve) leaves the channels alone.": "courbes de canal, comme le fait Lightroom : un préréglage avec une seule courbe de canal (ou sans courbe principale) laisse les canaux intacts.", + "dark sky is now removed too.": "ciel sombre est maintenant supprimée elle aussi.", + "darkens the photo outside it. The layout stays chosen across launches.": "assombrit la photo en dehors de l'image. La mise en page reste choisie d'un lancement à l'autre.", + "default cache share (768 MB), so it was evicted as soon as it was stored. The original of the photo shown in Detail": "part de cache par défaut (768 Mo), si bien qu'il était évincé dès qu'il était stocké. L'original de la photo affichée dans Détail", + "deletes a keyword from the whole library.": "supprime plus un mot-clé de toute la bibliothèque.", + "demosaic already lines the colour planes up. Details and measurements: `docs/fuji-lens-corrections.md`.": "dématriçage aligne déjà les plans de couleur. Détails et mesures : `docs/fuji-lens-corrections.md`.", + "depending on the graphics card. On a Windows laptop with an AMD Radeon 780M, a full-size export of a 24 MP raw": "selon la carte graphique. Sur un portable Windows avec une AMD Radeon 780M, l'exportation pleine taille d'un RAW de 24 Mpx", + "dialog was found and closed.": "boîte de dialogue soit retrouvée et fermée.", + "did). On the D600 and D610 the white level is also measured inside the picture, so the filler can't pass for": "faisait déjà). Sur les D600 et D610, le niveau de blanc est aussi mesuré à l'intérieur de l'image, si bien que le remplissage ne peut pas passer pour des", + "didn't line up with the raw near the edges. Photos you already imported pick this up when their previews are rebuilt.": "ne s'alignait pas sur le RAW près des bords. Les photos déjà importées en bénéficient quand leurs aperçus sont reconstruits.", + "differ by about 7–10 % on the ILCE-7M3; which one is off is still open.": "diffèrent d'environ 7–10 % sur l'ILCE-7M3 ; laquelle des deux est décalée reste une question ouverte.", + "directives. See README → Quick start → Logs.": "env_logger. Voir README → Quick start → Logs.", + "does the photos it was made from. HDRs merged before this don't have it; merge them again.": "le fait pour les photos dont il est issu. Les HDR fusionnés avant cela ne l'ont pas ; fusionnez-les à nouveau.", + "does: As Shot reads the file's white (an ILCE-7M3 sample: 4268 K / +7), the Temp slider runs 2000–50000 K and the": "Lightroom : Tel quel lit le blanc du fichier (exemple d'un ILCE-7M3 : 4268 K / +7), le curseur Température va de 2000 à 50000 K et les", + "dragging a handle into the image edge stops there instead of pushing the crop out of shape.": "faire glisser une poignée contre le bord de l'image s'arrête là au lieu de déformer le recadrage.", + "each image (issue #1522). When renders come in faster than the disk takes them, at most 128 MB of images wait;": "chaque image (ticket #1522). Quand les rendus arrivent plus vite que le disque ne les absorbe, 128 Mo d'images au plus attendent ;", + "each of those questions is a round trip. Measured on a hard disk over SMB, for folders of 1,600 to 2,400 photos": "chacune de ces questions est un aller-retour. Mesuré sur un disque dur via SMB, pour des dossiers de 1 600 à 2 400 photos", + "each time you look (issue #1392): the next time you browse the folder, in a later session, they're left out. A photo you had rated, flagged or": "à chaque consultation (ticket #1392) : la prochaine fois que vous parcourez le dossier, lors d'une session ultérieure, elles en sont exclues. Une photo que vous aviez notée, marquée d'un drapeau ou", + "edge.": "bord.", + "edit at 1:1, every zoom out and every step to the next photo.": "retouche à 1:1, à chaque dézoom et à chaque passage à la photo suivante.", + "edited earlier may shift by a few pixels.": "retouchées auparavant peuvent se décaler de quelques pixels.", + "edited stays, marked missing, so its changes aren't lost; photos in My Photos are unchanged.": "retouchée est conservée, marquée comme manquante, afin que ses modifications ne soient pas perdues ; les photos de Mes photos ne changent pas.", + "ellipses and radial components in compound masks. Edge and rotation handles keep their existing": "ellipses pivotées et les composantes radiales des masques composés. Les poignées de bord et de rotation gardent leurs", + "else (issue #1504): trimming or clearing the cache can't delete files outside it, and thumbnails are never read": "endroit (ticket #1504) : l'élagage ou le vidage du cache ne peut pas supprimer de fichiers extérieurs, et les miniatures ne sont jamais lues à partir d'un", + "embedded JPEG.": "JPEG intégré.", + "end), a folder the scan did not walk to its end, and, in a folder that holds any name with a character outside": "fin), d'un dossier que l'analyse n'a pas parcouru jusqu'au bout, et, dans un dossier qui contient un nom comportant un caractère hors de", + "end. Space pauses, ← / → step (a cut), Esc ends. A slide's time starts once it is shown sharp.": "fin. Espace met en pause, ← / → avancent (une coupe), Échap termine. Le temps d'une diapositive démarre une fois qu'elle est affichée nette.", + "ending. They are saved with the library. Agents use `slideshow.titles`, and `slideshow.preview {title: \"intro\"}`": "l'écran de fin. Ils sont enregistrés avec la bibliothèque. Les agents utilisent `slideshow.titles`, et `slideshow.preview {title: \"intro\"}`", + "every selected photo; a chip's menu acts on the selection (add to all, remove, show photos, edit) and no longer": "toutes les photos sélectionnées ; le menu d'une pastille agit sur la sélection (ajouter à toutes, retirer, afficher les photos, modifier) et ne", + "everything about how a slideshow looks and plays: the playback timing and fades, the layout, options and backdrop,": "tout ce qui détermine l'aspect et la lecture d'un diaporama : le minutage de la lecture et les fondus, la disposition, les options et la toile de fond,", + "existing LightCraft edits are preserved by default. Source settings/history are archived, unsupported": "les retouches LightCraft existantes sont conservées par défaut. Les réglages et l'historique d'origine sont archivés, les", + "export or delete it, and import templates others share with you. Your templates are `.json` files in the settings": "l'exporter ou le supprimer, et importez les modèles que d'autres partagent avec vous. Vos modèles sont des fichiers `.json` dans le dossier", + "exported files will carry for the selection.": "les fichiers exportés porteront pour la sélection.", + "exported or converted to DNG. It is not applied by default: Lightroom Classic renders ProRAW without it. To see a": "exportée ou convertie en DNG. Elle n'est pas appliquée par défaut : Lightroom Classic calcule le ProRAW sans elle. Pour voir un", + "exported with).": "en dernier pour exporter).", + "exposure, ISO, focal length, camera and lens under each photo on a dark backdrop).": "valeur d'exposition, l'ISO, la focale, l'appareil et l'objectif sous chaque photo sur une toile de fond sombre).", + "faster on an external hard disk. A face whose preview is too small, and any edited photo, is still developed from": "plus vite sur un disque dur externe. Un visage dont l'aperçu est trop petit, et toute photo retouchée, sont toujours développés à partir", + "favourites across restarts (issue #328).": "favoris d'un redémarrage à l'autre (ticket #328).", + "few pixels.": "quelques pixels.", + "fields are reported, and the original Lightroom database stays read-only. Rendering is approximate.": "champs non pris en charge sont signalés, et la base Lightroom d'origine reste en lecture seule. Le rendu est approximatif.", + "file is gone, photos whose file was renamed or moved within the folder, and XMP sidecars changed by other apps; then": "fichier a disparu, les photos dont le fichier a été renommé ou déplacé dans le dossier, et les fichiers annexes XMP modifiés par d'autres applications ; puis", + "file name, then id, instead of import order. Recently Added keeps a batch in file name order, and Auto-Stack orders a": "nom de fichier, puis par identifiant, au lieu de l'ordre d'importation. Ajoutées récemment garde un lot dans l'ordre des noms de fichier, et l'empilement automatique ordonne une", + "file that hold the focus point (about 100 photos a second from a spinning disk), with a *Reading focus points* row": "fichier qui contiennent le point de mise au point (environ 100 photos par seconde depuis un disque à plateaux), avec une ligne *Lecture des points de mise au point*", + "files also Adobe RGB and ProPhoto), metadata as for JPEG. With HDR output, photos edited in HDR are written as": "aussi en Adobe RGB et ProPhoto), métadonnées comme pour le JPEG. Avec la sortie HDR, les photos retouchées en HDR sont écrites en", + "files in the test corpus still decode.": "fichiers du corpus de test se décodent toujours.", + "files, the same files as `library.import` (issue #1080). They used to be skipped without a word.": "soit les mêmes que `library.import` (ticket #1080). Ils étaient auparavant ignorés sans un mot.", + "folder scans, exports (and the contact sheet PDF), Synchronize Folder, Build / Smart Previews, Lightroom catalog import, Photo Merge, model downloads, the face scan,": "analyses de dossiers, exportations (et le PDF de planche contact), Synchroniser le dossier, génération des aperçus / aperçus dynamiques, importation de catalogue Lightroom, Fusion de photos, téléchargements de modèles, analyse des visages,", + "folder's `slideshow-templates` folder, shared by all your libraries.": "`slideshow-templates` du dossier de réglages, partagé par toutes vos bibliothèques.", + "folder, fold that folder first (the bottom of an open folder means \"inside\"). Agents use `album.reorder`": "dossier ouvert, repliez d'abord ce dossier (le bas d'un dossier ouvert signifie « à l'intérieur »). Les agents utilisent `album.reorder`", + "follow.": "suivront.", + "for\").": "chercher »).", + "formats. On an E-1 photo the starting render moved from ΔE00 11.3 to 8.3 against Lightroom's. Photos already": "formats. Sur une photo d'E-1, le rendu de départ est passé de ΔE00 11,3 à 8,3 par rapport à celui de Lightroom. Les photos déjà", + "forward); what was read is remembered for the session, so a full cache still lets go of what is not in use first.": "avancée) ; ce qui a été lu est mémorisé pour la session, si bien qu'un cache plein abandonne d'abord ce qui n'est pas utilisé.", + "from or written through such a link.": "tel lien ni écrites à travers lui.", + "from the grid onto a keyword get it.": "de la grille sur un mot-clé reçoivent ce mot-clé.", + "full-range/matrix signalling is honoured (iPhone photos are full range), chroma is upsampled like libheif, grids": "(plage complète/matrice) est respectée (les photos d'iPhone sont en plage complète), la chrominance est suréchantillonnée comme libheif, les grilles", + "functions, and one Undo restores the entire drag.": "fonctions actuelles, et un seul Annuler restaure tout le glissement.", + "further ⇧-clicks carry on from the last point, as in Lightroom. Change the brush size, feather or flow before the": "les ⇧-clics suivants repartent du dernier point, comme dans Lightroom. Modifiez la taille, le contour progressif ou le flux du pinceau avant le", + "give the offered keyword and keep the cursor in the box for the next one; Return alone still adds what you typed.": "attribuent le mot-clé proposé et laissent le curseur dans le champ pour le suivant ; Entrée seul ajoute toujours ce que vous avez saisi.", + "go by that can leave it out. It is safe to delete while LightCraft is closed, as before. A `thumbs` folder that": "fient peuvent l'exclure. Il peut être supprimé sans risque pendant que LightCraft est fermé, comme avant. Un dossier `thumbs` qui", + "guides, at the screen's aspect or 16:9 / 4:3). Sizes are a share of the slide, so a slide looks the same on any": "guides, au format de l'écran ou en 16:9 / 4:3). Les tailles sont une part de la diapositive, si bien qu'une diapositive a le même aspect sur n'importe quel", + "handle, and a program being started by another thread at that moment held a copy of the handle until it was fully": "de fichier, et un programme lancé par un autre fil à ce moment-là conservait une copie du descripteur jusqu'à ce qu'il soit entièrement", + "high-resolution cameras such as the Sony A7R VI (64 MP). Their decoded original (~800 MB) is bigger than the": "les appareils haute résolution comme le Sony A7R VI (64 Mpx). Leur original décodé (~800 Mo) est plus grand que la", + "highlight recovery missed them and, darkened, they took a colour cast instead of going neutral grey.": "la récupération des hautes lumières les manquait et, assombries, elles prenaient une dominante de couleur au lieu de devenir gris neutre.", + "hold (such as a name in brackets), which it leaves out so the file always reads back.": "contenir (comme un nom entre crochets), qu'elle laisse de côté pour que le fichier soit toujours relisible.", + "iPhone ProRAW and other DNGs that carry their own segmentation mattes (DNG semantic masks) use them for the Select": "Les ProRAW d'iPhone et les autres DNG qui portent leurs propres mattes de segmentation (masques sémantiques DNG) les utilisent pour les masques", + "identity subissue in #840). The separate Make and Model tags keep their original values.": "sur l'identité de l'appareil dans #840). Les balises Marque et Modèle distinctes conservent leurs valeurs d'origine.", + "image file such as a PNG logo with transparency, at a size and opacity, optionally drawn behind the photo), the": "fichier image comme un logo PNG avec transparence, à une taille et une opacité données, éventuellement dessiné derrière la photo), la", + "import only the raws and leave the JPEGs beside them (issue #344).": "importez seulement les RAW et laissez les JPEG qui les accompagnent (ticket #344).", + "import review checks such files, marks them \"Will be restored\" and counts them as \"in Recently Deleted\"; the": "revue d'importation coche ces fichiers, les marque « Sera restaurée » et les compte comme « dans Supprimées récemment » ; le", + "imported from files (or read from sidecars) keep the hierarchy `lr:hierarchicalSubject` gives them.": "importés depuis des fichiers (ou lus dans des fichiers annexes) conservent la hiérarchie que leur donne `lr:hierarchicalSubject`.", + "imported pick it up when re-rendered.": "importées en bénéficient quand elles sont recalculées.", + "in, instead of moving it back to Program Files (issue #399). If that folder has been deleted since, the upgrade": "installé, au lieu de le replacer dans Program Files (ticket #399). Si ce dossier a été supprimé depuis, la mise à jour", + "inference on a Mac through SSH. Saved masks still render and export offline.": "sur un Mac via SSH. Les masques enregistrés continuent d'être calculés et exportés hors ligne.", + "inside Pictures, so every thumbnail (one for each photo, size and state of its edits) was listed as a photo.": "dans Images, si bien que chaque miniature (une par photo, par taille et par état de ses retouches) était listée comme une photo.", + "inside it; undo and redo carry them back and forth.": "qu'il contient ; l'annulation et le rétablissement les font aller et venir.", + "inside the view. A plain mouse wheel over a zoomed photo pans it too.": "dans la vue. Une simple molette de souris sur une photo zoomée la déplace aussi.", + "installs to Program Files.": "s'installe dans Program Files.", + "instead of opening as their embedded preview. Photos imported earlier switch over with Photo ▸ Reload from Disk.": "au lieu de s'ouvrir comme leur aperçu intégré. Les photos importées auparavant basculent avec Photo → Recharger depuis le disque.", + "instead of quietly matching nothing or everything. New date rules start at the current year.": "au lieu de ne rien sélectionner ou de tout sélectionner discrètement. Les nouvelles règles de date commencent à l'année en cours.", + "into the display's own gamut; thumbnails and other previews are converted to it. Histograms, the preview caches": "dans la gamme de couleurs propre à l'écran ; les miniatures et les autres aperçus y sont convertis. Les histogrammes, les caches d'aperçus", + "is a larger target that lights up on its own, and taking a keyword off several photos at once now says which": "est une cible plus grande qui s'illumine seule, et retirer un mot-clé de plusieurs photos à la fois indique désormais quel", + "is connected, the same review File → Import from Device opens. It's off by default. A card that's already in when": "est connecté, la même revue qu'ouvre Fichier → Importer depuis un appareil. Elle est désactivée par défaut. Une carte déjà insérée quand", + "is missing (moved, drive unplugged) is not exported; it gets its own error naming it.": "est introuvable (déplacé, disque débranché) n'est pas exportée ; elle reçoit sa propre erreur qui la nomme.", + "is touched. Agents use `folder.scanChanges` and `folder.synchronize`.": "n'est touché. Les agents utilisent `folder.scanChanges` et `folder.synchronize`.", + "it slightly worse. The vignetting table is read but not applied: the camera's own JPEGs don't apply it either. This": "le résultat légèrement moins bon. La table de vignetage est lue mais pas appliquée : les JPEG de l'appareil ne l'appliquent pas non plus. Cela", + "it. The list is there with no photo selected too, to set up keywords first.": "de lui. La liste est aussi présente sans photo sélectionnée, pour préparer d'abord les mots-clés.", + "its duration and the fades are rendered frame by frame (crossfades, or fades through the fade colour). The video has": "sa durée et les fondus sont calculés image par image (fondus enchaînés, ou fondus par la couleur de fondu). La vidéo n'a", + "its embedded JPEG or a thumbnail to show, the loupe now says so at the bottom of the photo (\"Original offline · no": "son JPEG intégré ou d'une miniature à afficher, la loupe le dit désormais au bas de la photo (« Original hors ligne · aucun", + "its real As Shot temperature once the file is opened (or Reload reads it).": "sa vraie température Tel quel une fois le fichier ouvert (ou lue par Recharger).", + "its text reads at 4.5:1 or more on its fill in every theme. Dialog buttons are 30 points tall, like the welcome's.": "son texte se lit avec un contraste d'au moins 4,5:1 sur son fond dans tous les thèmes. Les boutons des boîtes de dialogue font 30 points de haut, comme ceux de l'accueil.", + "keyword only some of them have is marked with an asterisk (hover: how many). Only the × removes a keyword, from": "mot-clé que seules certaines ont est marqué d'un astérisque (au survol : combien). Seul le × retire un mot-clé, de", + "keywords, dates, people and counts; a keyword leaves the folders, the dates and the counts as they are. With both": "mots-clés, dates, personnes et décomptes ; un mot-clé laisse les dossiers, les dates et les décomptes tels quels. Avec les deux", + "labels 6–9, P / U and the rest did nothing, because macOS only passes ⌘ / ⌃ combinations and function keys": "étiquettes 6–9, P / U et le reste ne faisaient rien, car macOS ne transmet que les combinaisons ⌘ / ⌃ et les touches de fonction", + "land in `ui.json` (where they replaced the saved settings), and the GPU crash sentinel no longer creates the": "se retrouvent plus dans `ui.json` (où ils remplaçaient les réglages enregistrés), et la sentinelle de plantage GPU ne crée plus le", + "launch. Reading a thumbnail writes nothing (but for one that went unused for a week, whose date is brought": "lancement. La lecture d'une miniature n'écrit rien (sauf pour une miniature restée inutilisée une semaine, dont la date est", + "launched, so reopening the library straight away could be refused with \"This library is already open in another": "lancé, si bien que rouvrir la bibliothèque aussitôt pouvait être refusé avec « This library is already open in another", + "leaves a black hole where the middle photo had it clipped. With Deghost, the brightest photo's copy of it in a": "de trou noir là où la photo du milieu l'avait écrêtée. Avec la suppression des images fantômes, la copie qu'en donne la photo la plus claire dans un", + "leaves out whatever Excluded Photos matches, as its rules change. The album picker shows your albums as in the sidebar": "écarte tout ce qui correspond à Photos exclues, à mesure que ses règles changent. Le sélecteur d'album montre vos albums comme dans la barre latérale", + "left out, so these photos come out a little smaller, closer to the camera's own JPEG. Crops and masks on photos": "exclue, si bien que ces photos sortent un peu plus petites, plus proches du JPEG de l'appareil. Les recadrages et masques des photos", + "lens it doesn't have a name for. Newly imported photos show it.": "objectif dont il ne connaît pas le nom. Les photos importées à partir de maintenant l'affichent.", + "let go. On a 64 MP raw the first of those renders decoded the whole file again, which held up the loupe's": "relâchez. Sur un RAW de 64 Mpx, le premier de ces rendus décodait de nouveau tout le fichier, ce qui retardait les", + "library open now stays, and LightCraft says \"This is a Lightroom catalog, not a LightCraft library\" and offers": "bibliothèque ouverte reste en place, et LightCraft affiche « Ceci est un catalogue Lightroom, pas une bibliothèque LightCraft » et propose", + "light: Silver or Paper). New and existing installs stay dark; following the system is opt-in.": "clair : Argent ou Papier). Les installations, nouvelles et existantes, restent sombres ; suivre le système est facultatif.", + "like a photo that can't be opened, with the reason, instead of rendering forever; its thumbnail stops waiting too.": "comme une photo qui ne peut pas être ouverte, avec la raison, au lieu de se calculer indéfiniment ; sa miniature cesse elle aussi d'attendre.", + "like the HDR AVIF: the same brightness, with SDR white at 203 cd/m², and content light levels recorded.": "comme l'AVIF HDR : même luminosité, avec le blanc SDR à 203 cd/m², et les niveaux de lumière du contenu enregistrés.", + "linked, or each on its own), Zoom to Fill Frame (crop the photo to fill its cell), a stroke border (colour, width),": "liées, ou chacune séparément), Zoom pour remplir le cadre (recadrer la photo pour remplir sa cellule), un contour (couleur, largeur),", + "listing itself took 4 to 5 s and is as it was.": "liste elle-même prenait 4 à 5 s et reste telle quelle.", + "lit by the chosen white comes out grey and saturated colours move as the camera records them. The eyedropper and": "éclairé par le blanc choisi reste gris et les couleurs saturées bougent comme l'appareil les enregistre. La pipette et", + "longer frees it, which cost a re-upload of about a second on the next pan (800 MB for a 64 MP raw). It is freed": "la libère plus, ce qui coûtait un nouveau transfert d'environ une seconde au déplacement suivant (800 Mo pour un RAW de 64 Mpx). Elle est libérée", + "looks right everywhere, export a JPEG with HDR output on (an SDR image plus a gain map).": "s'affiche correctement partout, exportez un JPEG avec la sortie HDR activée (une image SDR plus une carte de gain).", + "lossy tiles decode too, keeping the raw values above 1.0 instead of clipping them (checked on one real file). A tile that cannot be decoded makes the file open from its embedded": "les tuiles avec perte se décodent aussi, en conservant les valeurs brutes au-dessus de 1,0 au lieu de les écrêter (vérifié sur un fichier réel). Une tuile impossible à décoder fait ouvrir le fichier à partir de son", + "macOS, Linux packages, AppImage, Flatpak), and says so if it isn't installed, before making a copy.": "macOS, paquets Linux, AppImage, Flatpak), et le signale s'il n'est pas installé, avant de créer une copie.", + "made a lock test flaky, and the fix closes the window for good.": "rendait un test de verrou instable, et le correctif referme définitivement cette fenêtre.", + "made from the old pixels: they are made again from the new file, and a scan still busy with the old file when it": "avait trouvés dans les anciens pixels : ils sont refaits à partir du nouveau fichier, et une analyse encore occupée avec l'ancien fichier quand il", + "magnified preview isn't taken for the photo when checking focus at 1:1.": "aperçu agrandi ne soit pas pris pour la photo lors de la vérification de la mise au point à 1:1.", + "makes it inside that folder (`dialog.newAlbum`, `dialog.newFolder`, `dialog.smartAlbum`, `dialog.newSmartAlbum` take `parent`).": "le crée dans ce dossier (`dialog.newAlbum`, `dialog.newFolder`, `dialog.smartAlbum`, `dialog.newSmartAlbum` acceptent `parent`).", + "many Photos added, or why it added none. Export with Previous and export presets repeat it.": "photos ont été ajoutées, ou pourquoi aucune ne l'a été. Exporter avec les réglages précédents et les préréglages d'exportation le répètent.", + "map); the option is per photo, so presets and Copy Settings carry it.": "carte) ; l'option est propre à chaque photo, si bien que les préréglages et Copier les réglages la transportent.", + "means no (it used to count as yes), and a value that is neither yes nor no is refused.": "non (elle comptait auparavant comme oui), et une valeur qui n'est ni oui ni non est refusée.", + "memory than the computer has, the panorama is made as large as fits (five 51 MP photos: up to 166 MP with": "mémoire que l'ordinateur n'en a, le panorama est créé à la plus grande taille possible (cinq photos de 51 Mpx : jusqu'à 166 Mpx avec", + "menu, and Return in the painter's box starts painting.": "menu Couper / Copier / Coller, et Entrée dans le champ du pinceau de mots-clés lance la peinture.", + "merges used to open at about 7000 K / +115 where the photos show 4000–5300 K / +8. HDRs merged before this keep": "s'ouvraient à environ 7000 K / +115 là où les photos indiquent 4000–5300 K / +8. Les HDR fusionnés avant cette correction conservent", + "message box that names the log file, instead of quitting without a trace (issue #260).": "boîte de message qui nomme le fichier journal, au lieu de quitter sans laisser de trace (ticket #260).", + "missing ones.": "manquantes.", + "missing. And a share that drops after the scan has listed a folder no longer turns that folder's photos into": "manquantes. Et un partage qui se déconnecte après que l'analyse a listé un dossier ne transforme plus les photos de ce dossier en photos", + "models in a `LightCraftData` folder beside it instead of the per-user settings folder (issue #1200), as": "modèles téléchargés dans un dossier `LightCraftData` à côté de lui plutôt que dans le dossier de réglages de l'utilisateur (ticket #1200), comme", + "moved from ΔE00 7.6 to 5.2 against Lightroom's.": "est passé de ΔE00 7,6 à 5,2 par rapport à celui de Lightroom.", + "name (`catalog.snap.tmp`, `model.onnx.part`): the link is removed and a new file made in its place, so the file it": "(`catalog.snap.tmp`, `model.onnx.part`) : le lien est supprimé et un nouveau fichier est créé à sa place, si bien que le fichier vers lequel il", + "name. Whole names, one chip per keyword, stays the default.": "mot-clé. Les noms complets, une pastille par mot-clé, restent le réglage par défaut.", + "names.": "noms.", + "neutral default.": "valeur neutre par défaut.", + "never restore anything. Agents: `library.import` → `onDeleted` defaults to `restore` (`skip` keeps the old": "ne restaurent jamais rien. Agents : `library.import` → `onDeleted` vaut `restore` par défaut (`skip` conserve l'ancien", + "new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update to Current": "les nouvelles photos (et Réinitialiser) l'obtiennent, les photos déjà retouchées gardent leur rendu jusqu'à ce que vous choisissiez Photo → Mettre à jour vers le", + "next to it while you rotate (issue #534). For an exact angle, type it in the new Angle field under Straighten and press Return": "à côté pendant la rotation (ticket #534). Pour un angle exact, saisissez-le dans le nouveau champ Angle sous Redresser et appuyez sur Entrée", + "no longer saves it). Return in those dialogs now confirms them, and their name opens selected. More fields will": "ne l'enregistre plus). Entrée dans ces boîtes de dialogue les confirme désormais, et leur nom s'ouvre sélectionné. D'autres champs", + "no sound yet. It is AV1 rather than Lightroom's H.264, which has no open encoder we can ship; current browsers,": "pas encore de son. C'est de l'AV1 plutôt que du H.264 de Lightroom, qui n'a pas d'encodeur ouvert que nous puissions livrer ; les navigateurs actuels,", + "note saying what is missing. Agents use `slideshow.templates.*`, and `slideshow.preview {template}` renders a template": "note indiquant ce qui manque. Les agents utilisent `slideshow.templates.*`, et `slideshow.preview {template}` calcule un modèle", + "noticeably duller.": "nettement plus ternes.", + "now import as \"preview only\" with their embedded JPEG instead of failing. A raw whose data is damaged but whose": "s'importent désormais en « aperçu uniquement » avec leur JPEG intégré au lieu d'échouer. Un RAW dont les données sont endommagées mais dont", + "now measured on the masked columns alone (8 corpus bodies, EOS 40D to 5DS R). On a 6D photo the starting render": "désormais mesuré sur les seules colonnes masquées (8 boîtiers du corpus, de l'EOS 40D au 5DS R). Sur une photo du 6D, le rendu de départ", + "now stays, like its preview, until another photo or view is shown.": "reste désormais, comme son aperçu, jusqu'à l'affichage d'une autre photo ou d'une autre vue.", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914). The": "d'une photo en portrait) : des colonnes masquées du capteur étaient développées comme faisant partie de l'image (tickets #976, #914). Les", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914,": "d'une photo en portrait) : des colonnes masquées du capteur étaient développées comme faisant partie de l'image (tickets #976, #914,", + "of quietly rendering everything on the CPU, much more slowly. Help ▸ System Info says why. On NixOS this happens": "de tout calculer discrètement sur le CPU, bien plus lentement. Aide → Informations système en donne la raison. Sous NixOS, cela arrive", + "older versions refuse it, as with every format change.": "les versions plus anciennes la refusent, comme à chaque changement de format.", + "on the CPU and explains how to turn the GPU back on.": "sur le CPU et explique comment réactiver le GPU.", + "on the CPU, are not waited for).": "sur le CPU, ne sont pas attendus).", + "on the DLL search path without its `dxil.dll` (issue #471): DirectX 12 shaders now always compile with the": "dans le chemin de recherche des DLL sans son `dxil.dll` (ticket #471) : les shaders DirectX 12 se compilent désormais toujours avec le", + "on the top bar it comes back zoomed. The other way round, a window you drag out until it is as wide as the": "sur la barre supérieure, elle revient zoomée. Inversement, une fenêtre que vous étirez jusqu'à ce qu'elle soit aussi large que", + "on; ✕ stops the tasks that can stop. Three rows show, then \"+N more\". The separate export panel and the progress": "travaille ; × arrête les tâches qui peuvent être arrêtées. Trois lignes s'affichent, puis « +N de plus ». Le panneau d'exportation séparé et les fenêtres de progression", + "once you zoom out or move on.": "dès que vous dézoomez ou passez à autre chose.", + "one that overflows.": "taille qui déborde.", + "only convert between the camera's multipliers and Kelvin; the colour look is what it was.": "ne font que convertir entre les multiplicateurs de l'appareil et les kelvins ; le rendu des couleurs est inchangé.", + "only the header and the preview are read, as for other raws.": "seuls l'en-tête et l'aperçu sont lus, comme pour les autres RAW.", + "open and hasn't written back yet) imports instead of failing with \"unsupported SQLite schema format\".": "ouvert et n'a pas encore réécrit) s'importe au lieu d'échouer avec « unsupported SQLite schema format ».", + "opened a library, older versions refuse it, as with every format change.": "ouvert une bibliothèque, les versions plus anciennes la refusent, comme à chaque changement de format.", + "or the edge of another folder, to place it before or after it: that folder is then ordered by hand. Right-click ▸": "ou sur le bord d'un autre dossier, pour le placer avant ou après lui : ce dossier est alors ordonné à la main. Clic droit →", + "or unchecks a range of photos (issue #338).": "ou décoche une plage de photos (ticket #338).", + "original again to find the haze colour. On a 64 MP raw (Sony A7R VI) that took ~0.2 s of CPU per pan and per": "l'original pour retrouver la couleur du voile. Sur un RAW de 64 Mpx (Sony A7R VI), cela prenait ~0,2 s de CPU par déplacement et par", + "other file-naming tokens, with a size, colour, opacity and an optional soft shadow (opacity, offset, radius, angle).": "autres jetons de nommage de fichier, avec une taille, une couleur, une opacité et une ombre douce facultative (opacité, décalage, rayon, angle).", + "out green and dark.": "verte et sombre.", + "out, a folder that went read-only) used to be written only to the library, with a line in the log, so the sidecar": "déconnecté, un dossier passé en lecture seule) n'était écrite que dans la bibliothèque, avec une ligne dans le journal, si bien que le fichier annexe", + "out. Clear Recent Libraries empties the list.": "grisées. Effacer les bibliothèques récentes vide la liste.", + "over one by one as they are used; the rest stay until the cache makes room.": "une par une à mesure qu'elles servent ; les autres restent jusqu'à ce que le cache fasse de la place.", + "overlays and the intro and ending screens, in view order.": "les incrustations et les écrans d'introduction et de fin, dans l'ordre de la vue.", + "owns every shared sidecar name in the library: 2.4 s a write in that library, now under 1 s.": "possède chaque nom de fichier annexe partagé dans la bibliothèque : 2,4 s par écriture dans cette bibliothèque, désormais moins de 1 s.", + "panel. Each is switched on on its own and has a background colour and, centred on it, your identity plate (the one": "le panneau Titres de Lightroom Classic. Chacun est activé séparément et a une couleur d'arrière-plan et, centrée dessus, votre plaque d'identification (celle", + "panels closed, from 71 ms).": "panneaux fermés, contre 71 ms auparavant).", + "pass, a new order each time round), repeat (off: the slideshow ends after the last photo) and preparing previews in": "passage, un nouvel ordre à chaque tour), répétition (désactivée : le diaporama se termine après la dernière photo) et préparation des aperçus à", + "past that a write is skipped (the image stays in memory and is written by a later render), so a slow disk can't": "au-delà, une écriture est ignorée (l'image reste en mémoire et sera écrite par un rendu ultérieur), de sorte qu'un disque lent ne peut pas", + "photo has yet too. Filter it, tick a keyword to give it to the selected photos (a dash: only some have it), or click": "photo n'a encore. Filtrez-la, cochez un mot-clé pour l'attribuer aux photos sélectionnées (un tiret : seules certaines l'ont), ou cliquez sur", + "photo's rating as stars, and any number of text overlays (up to 16) built from tokens: `{caption}`, `{title}`,": "note de la photo sous forme d'étoiles, et un nombre quelconque d'incrustations de texte (jusqu'à 16) construites à partir de jetons : `{caption}`, `{title}`,", + "photo: only the photos the edit touched are asked about again and put at their place in the order. In a library of": "photo : seules les photos concernées par la retouche sont réinterrogées et replacées à leur rang dans l'ordre. Dans une bibliothèque de", + "photos along the areas they clipped: right next to a clipped area, a photo's colour isn't used. It showed most when": "photos, le long des zones qu'elles ont écrêtées : juste à côté d'une zone écrêtée, la couleur d'une photo n'est pas utilisée. Cela se voyait surtout quand", + "pile up threads and memory.": "accumuler des fils et de la mémoire.", + "pointed to is never changed (issue #1502).": "pointait n'est jamais modifié (ticket #1502).", + "preset pickers in Import and Settings ▸ Import scroll the same way.": "sélecteurs de préréglages de l'importation et de Réglages → Importation défilent de la même façon.", + "presets.json) stays responsive. Every command used to re-serialize the whole list to see whether it had changed": "presets.json) reste réactive. Chaque commande sérialisait auparavant de nouveau toute la liste pour voir si elle avait changé", + "press the new keys (Esc cancels), × removes it, ↺ restores the original, Reset All undoes every change. A key that": "appuyez sur les nouvelles touches (Échap annule), × le supprime, ↺ rétablit l'original, Tout réinitialiser annule tous les changements. Une touche qui", + "preview is intact does the same.": "l'aperçu est intact fait de même.", + "preview, with the reason, instead of showing a black tile. A JPEG XL preview stored in the DNG is used like an": "aperçu intégré, avec la raison, au lieu d'afficher une tuile noire. Un aperçu JPEG XL stocké dans le DNG est utilisé comme un", + "previews for up to a second.": "aperçus de la loupe jusqu'à une seconde.", + "profile overrides for memory-constrained builders (issue #1196), including why packaging": "configuration release pour les machines à mémoire limitée (ticket #1196), y compris pourquoi les recettes de paquetage", + "projected, so it needs less memory than before at any size (an 81 MP stitch: 4.4 GB instead of 6.2 GB).": "projetés, si bien qu'elle demande moins de mémoire qu'avant, quelle que soit la taille (un assemblage de 81 Mpx : 4,4 Go au lieu de 6,2 Go).", + "promise, instead of filtering whatever album or folder was open, which often showed nothing (issue #341).": "l'annoncent, au lieu de filtrer l'album ou le dossier ouvert, ce qui n'affichait souvent rien (ticket #341).", + "ran beside it.": "s'exécutaient auparavant en parallèle.", + "raw whose tile claims far more samples than it holds, and an ARW6 with a broken tile are refused first. All 74": "dont une tuile annonce bien plus d'échantillons qu'elle n'en contient, et un ARW6 avec une tuile cassée sont désormais refusés d'emblée. Les 74", + "raws of other cameras keep the as-shot shift of issue #510. The two Kelvin scales come from different matrices and": "les RAW des autres appareils conservent le décalage « tel que pris » du ticket #510. Les deux échelles de kelvins viennent de matrices différentes et", + "read from the white-balance presets the camera stores in every ARW: a photo shot at 3400 K on the camera reads": "lue dans les préréglages de balance des blancs que l'appareil stocke dans chaque ARW : une photo prise à 3400 K sur l'appareil indique", + "recipes can override inherited settings. Default release profiles and application behavior": "peuvent remplacer des réglages hérités. Les profils release par défaut et le comportement de l'application", + "relinked to the file it is imported from. Browsing a folder in Local, Auto Import and a Lightroom catalog import": "reliée au fichier depuis lequel elle est importée. Parcourir un dossier dans Local, l'importation automatique et l'importation d'un catalogue Lightroom", + "remembered.": "mémorisé.", + "render with Clarity, Dehaze, Texture or Highlights / Shadows on: their blurs are held to the picture's size.": "rendu quand Clarté, Correction du voile, Texture ou Hautes lumières / Ombres sont activés : leurs flous sont limités à la taille de l'image.", + "renders a screen as a PNG.": "calcule un écran sous forme de PNG.", + "replaced are listed as \"Previous settings\" until you quit: click that to go back.": "remplacés sont listés sous « Réglages précédents » jusqu'à ce que vous quittiez : cliquez dessus pour revenir en arrière.", + "reports each row's `label`.": "signale le `label` de chaque ligne.", + "restore the photo too and say \"Restored 1 photo from Recently Deleted\". A deleted photo whose file was moved is": "restaurent aussi la photo et affichent « 1 photo restaurée depuis Supprimées récemment ». Une photo supprimée dont le fichier a été déplacé est", + "runs in the background with a row in the activity stack (✕ stops it); everything it does is one undo step, and no file on disk": "s'exécute en arrière-plan avec une ligne dans la pile d'activité (× l'arrête) ; tout ce qu'elle fait forme une seule étape d'annulation, et aucun fichier sur le disque", + "samples, no longer crashes LightCraft at 1:1 or on export: the bad values read as black.": "échantillons, ne fait plus planter LightCraft à 1:1 ni à l'exportation : les valeurs erronées sont lues comme du noir.", + "saved in an earlier version now shifts the other way; set it again (or re-run Auto / the white-balance picker).": "enregistrée dans une version antérieure se décale désormais dans l'autre sens ; redéfinissez-la (ou relancez Auto / le sélecteur de balance des blancs).", + "says what to fix, and `albums.list` reports `problems`.": "indique quoi corriger, et `albums.list` signale `problems`.", + "scale keep their look, and As Shot shows the real temperature once the file is opened.": "gardent leur rendu, et Tel quel affiche la température réelle une fois le fichier ouvert.", + "scale. Each stays up for its own duration (by default the slide duration) and fades in and out like a slide.": "échelle donnée. Chacun reste affiché pendant sa propre durée (par défaut la durée de la diapositive) et apparaît et disparaît en fondu comme une diapositive.", + "screen and nearly as tall counts as zoomed.": "l'écran et presque aussi haute est considérée comme zoomée.", + "screen readers). Each darkens a little when hovered and more when pressed, shows a ring where the keyboard is, and": "les lecteurs d'écran). Chacun s'assombrit un peu au survol et davantage à la pression, affiche un anneau là où se trouve le clavier, et", + "screen. They are saved with the library.": "écran. Elles sont enregistrées avec la bibliothèque.", + "search by lens. LightCraft now reads the lens range Nikon keeps in its own maker note, the way Lightroom shows a": "chercher par objectif. LightCraft lit désormais la plage d'objectif que Nikon conserve dans sa propre note de fabricant, à la manière de Lightroom pour un", + "second colour, at an angle and opacity) and a background image (a photo from the library, at an opacity).": "seconde couleur, selon un angle et une opacité) et une image d'arrière-plan (une photo de la bibliothèque, à une opacité donnée).", + "secondary, danger (filled red) and ghost, in three sizes, with an icon or without, and an icon alone (named for": "secondaire, danger (rempli de rouge) et fantôme, en trois tailles, avec ou sans icône, et une icône seule (nommée pour", + "sensor data runs a few columns of filler past the picture, which stayed in the image; these bodies now develop": "données de capteur comportent quelques colonnes de remplissage au-delà de l'image, qui restaient dans la photo ; ces boîtiers sont désormais développés", + "set under Overlays: its text or image) or a line of text of its own, in the plate's colour or one you pick, at a": "définie sous Incrustations : son texte ou son image) ou une ligne de texte qui lui est propre, dans la couleur de la plaque ou une couleur que vous choisissez, à une", + "set). An empty field leaves its key empty instead of moving the keywords after it; editing Recent Keywords and naming": "jeu). Un champ vide laisse sa touche vide au lieu de décaler les mots-clés suivants ; modifier Mots-clés récents et les nommer", + "settings folder there. The same goes for the temporary session offered when the library can't be opened.": "dossier de réglages dans ce cas. Il en va de même pour la session temporaire proposée quand la bibliothèque ne peut pas être ouverte.", + "settings, one after the other: each stack, and photos taken less than a second apart at different exposures.": "réglages, l'un après l'autre : chaque pile, et les photos prises à moins d'une seconde d'écart avec des expositions différentes.", + "share of the slide, so slides look the same on any screen. They are saved with the library. Agents use": "part de la diapositive, si bien que les diapositives ont le même aspect sur n'importe quel écran. Elles sont enregistrées avec la bibliothèque. Les agents utilisent", + "show a black (or, on the 645Z, white) band along one or more edges (issue #1271). The sensor's masked border is": "de bande noire (ou, sur le 645Z, blanche) le long d'un ou plusieurs bords (ticket #1271). La bordure masquée du capteur est", + "show as a partial import.": "apparaissent comme une importation partielle.", + "show full screen\" asks the viewer to open it that way.": "automatiquement en plein écran » demande au lecteur de l'ouvrir ainsi.", + "show no dialogs and take `INSTALLFOLDER=...`.": "n'affichent aucune boîte de dialogue et acceptent `INSTALLFOLDER=...`.", + "shown still takes it out of the view.": "affiché la retire toujours de la vue.", + "shows and as in Lightroom, and Tint values in Lightroom XMP sidecars now render as they do there. A custom Tint": "l'indique et comme dans Lightroom, et les valeurs de nuance des fichiers annexes XMP Lightroom s'affichent désormais comme là-bas. Une nuance personnalisée", + "shows only a little of come out closer to the camera's JPEG.": "ne montre qu'une faible part se rapprochent davantage du JPEG de l'appareil.", + "shows the label's dot before its photo count. Agents use `folder.label` (`path`, `label`); `library.folders`": "affiche le point de l'étiquette avant son nombre de photos. Les agents utilisent `folder.label` (`path`, `label`) ; `library.folders`", + "shows where it will go), or right-click a header for Move Up / Move Down.": "indique où il ira), ou faites un clic droit sur un en-tête pour Monter / Descendre.", + "side panels open, the frame after a keyword went from about 156 ms to about 54 ms in that library (2 ms with the": "panneaux latéraux ouverts, l'image affichée après un mot-clé est passée d'environ 156 ms à environ 54 ms dans cette bibliothèque (2 ms avec les", + "side under it. A long list stops after eight lines with \"+N more\", and the suggestions say only the keyword's own": "côte en dessous. Une longue liste s'arrête après huit lignes avec « +N de plus », et les suggestions n'indiquent que le nom propre du", + "sidecar lookup always did; the Add Photos dialog on Linux did not until 0.5.0 (GTK and the desktop portal match": "recherche des fichiers annexes le faisaient déjà ; la boîte de dialogue Ajouter des photos sous Linux ne le faisait pas avant la 0.5.0 (GTK et le portail de bureau comparent", + "sidecar, a preset or an agent) no longer crashes LightCraft; the point stays between them. Curve points sent to": "fichier annexe, d'un préréglage ou d'un agent) ne fait plus planter LightCraft ; le point reste entre eux. Les points de courbe envoyés à", + "similarity as one undo step. Hover or focus that face and press A for the same action; hidden suggestions stay hidden.": "supérieure, en une seule étape d'annulation. Survolez ce visage ou placez-y le focus, puis appuyez sur A pour la même action ; les suggestions masquées restent masquées.", + "sky no longer flattens the twigs, lines and texture in it, and lifting Shadows keeps the texture of dark areas, much": "clair n'aplatit plus les brindilles, les lignes et la texture qui s'y trouvent, et relever les ombres préserve la texture des zones sombres, un peu", + "slider step; a slider step now takes ~5 ms on the GPU.": "cran de curseur ; un cran de curseur prend désormais ~5 ms sur le GPU.", + "smaller file; Progressive files show a coarse version first. 8- or 16-bit, sRGB, Display P3 or Rec. 2020 (lossless": "fichier plus petit ; les fichiers Progressifs affichent d'abord une version grossière. 8 ou 16 bits, sRGB, Display P3 ou Rec. 2020 (les fichiers sans perte", + "smart preview\" or \"This photo can't be opened\", the reason on hover) instead of showing that preview as if it were": "aperçu dynamique » ou « Cette photo ne peut pas être ouverte », la raison au survol) au lieu d'afficher cet aperçu comme s'il s'agissait de", + "so a successful install looked like nothing had happened (issues #18, #399). Silent installs (`/qn`, `/passive`)": "si bien qu'une installation réussie donnait l'impression que rien ne s'était passé (tickets #18, #399). Les installations silencieuses (`/qn`, `/passive`)", + "so the picture looks flat and washed out there. That's how PQ PNG works, not a broken file: for a picture that": "si bien que l'image y paraît plate et délavée. C'est ainsi que fonctionne le PNG PQ, ce n'est pas un fichier cassé : pour une image qui", + "soft shadow, with the caption and rating under the photo), Edge to Edge (photos cropped to fill the screen), Cinema": "ombre douce, avec la légende et la note sous la photo), Bord à bord (photos recadrées pour remplir l'écran), Cinéma", + "started yet another decode.": "lançait encore un autre décodage.", + "starting look is fitted to the camera JPEG away from edges when the misaligned edges spoil the fit on all pixels.": "rendu de départ est ajusté sur le JPEG d'appareil en dehors des bords quand les bords mal alignés gâchent l'ajustement sur tous les pixels.", + "stayed behind the edit. LightCraft now says once that the sidecars are waiting, tries again every few seconds once": "restait en retard sur la retouche. LightCraft indique désormais une seule fois que les fichiers annexes sont en attente, réessaie toutes les quelques secondes dès que", + "stopping the others, and a template whose identity plate image or background photo isn't there still applies, with a": "d'arrêter les autres, et un modèle dont l'image de plaque d'identification ou la photo d'arrière-plan est absente s'applique quand même, avec une", + "stored that is big enough, not always from the largest one. On a Sony A7R VI file a 512 px thumbnail decodes": "a enregistré et qui soit assez grand, et non plus toujours du plus grand. Sur un fichier Sony A7R VI, une miniature de 512 px décode", + "submenus for Source, File, Date, Keywords & People, Description, Camera Info, Location, Size, Develop and Assisted": "des sous-menus pour Source, Fichier, Date, Mots-clés et personnes, Description, Infos de l'appareil, Lieu, Taille, Développement et Tri", + "take their tiles' ICC profile, and `imir` mirrors the way libheif writes it. Importing a HEIC reads its size from": "reprennent le profil ICC de leurs tuiles, et `imir` reflète comme libheif l'écrit. L'importation d'un HEIC lit sa taille dans", + "that had not changed: 4.6 to 7.1 s of questions after the listing (about 3 ms a photo), now under 0.05 s. The": "inchangés : 4,6 à 7,1 s de questions après la liste (environ 3 ms par photo), désormais moins de 0,05 s. La", + "that light already reaches (left of the image area Canon records), 4 % of the range too high on the EOS 6D. It is": "que la lumière atteint déjà (à gauche de la zone d'image que Canon enregistre), 4 % de la plage trop haut sur l'EOS 6D. Il est", + "that may be listed but not searched, a path longer than the system takes): such photos used to be listed as": "qui peut être listé mais pas parcouru, un chemin plus long que ce que le système accepte) : de telles photos étaient auparavant signalées comme", + "the LightCraft window. The xdg-desktop-portal picker used to open as a separate top-level window on Wayland": "la fenêtre LightCraft. Le sélecteur xdg-desktop-portal s'ouvrait auparavant comme une fenêtre de premier niveau distincte sous Wayland", + "the My Photos title to bring one back, or choose Reset Sidebar Sections. The arrangement is remembered.": "le titre Mes photos pour en ramener une, ou choisissez Réinitialiser les sections de la barre latérale. L'organisation est mémorisée.", + "the area the camera itself frames, a few pixels smaller than before.": "la zone que l'appareil cadre lui-même, de quelques pixels plus petite qu'avant.", + "the arrow to see its photos.": "la flèche pour voir ses photos.", + "the container instead of decoding it; small previews use the file's embedded thumbnail. The release packages": "le conteneur au lieu de le décoder ; les petits aperçus utilisent la miniature intégrée au fichier. Les paquets de la version", + "the edit touched, where it asked every photo of the library after each edit (about 25 ms an album in that library).": "concernées par la retouche, là où il interrogeait chaque photo de la bibliothèque après chaque retouche (environ 25 ms par album dans cette bibliothèque).", + "the file, instead of asking for gigabytes of memory, which could end LightCraft.": "le fichier, au lieu de réclamer des gigaoctets de mémoire, ce qui pouvait arrêter LightCraft.", + "the files are reachable, and says when they're written. `library.retrySidecars` does it on request.": "les fichiers sont accessibles, et signale quand ils sont écrits. `library.retrySidecars` le fait à la demande.", + "the first time a library opens after this update, \"Tidying the thumbnail cache\" shows in the activity stack": "la première fois qu'une bibliothèque s'ouvre après cette mise à jour, « Rangement du cache des miniatures » apparaît dans la pile d'activité", + "the highlights were darkened or saturated.": "les hautes lumières étaient assombries ou saturées.", + "the keyword they are inside: \"Places › Italy\" once, on a line of its own, with Rome, Venice and the others side by": "le mot-clé qui les contient : « Lieux › Italie » une seule fois, sur sa propre ligne, avec Rome, Venise et les autres côte à", + "the list of every keyword is one click away however many keywords the selected photos have. What is folded is": "la liste de tous les mots-clés est à un clic quel que soit le nombre de mots-clés des photos sélectionnées. Ce qui est replié est", + "the loupe (issue #960). Their radii are now set in the original photo's pixels, so a thumbnail, the fitted loupe": "la loupe (ticket #960). Leurs rayons sont désormais exprimés en pixels de la photo d'origine : une miniature, la loupe ajustée", + "the other editor (Edit in Other Editor, now ⌥⌘E), and where PhotoCraft is if you use a portable copy.": "l'autre éditeur (Modifier dans un autre éditeur, désormais ⌥⌘E), et l'emplacement de PhotoCraft si vous utilisez une copie portable.", + "the overlays and the intro and ending screens. Click one to apply it; point at one to see it on the selected photo in": "les incrustations et les écrans d'introduction et de fin. Cliquez sur un modèle pour l'appliquer ; pointez-en un pour le voir sur la photo sélectionnée dans", + "the photo, follows zoom and pan, and ⌥⌘O shows or hides it. The same menu sets its opacity and a matte that": "de la photo, suit le zoom et le déplacement, et ⌥⌘O l'affiche ou la masque. Le même menu règle son opacité et un mat qui", + "the photo.": "la photo.", + "the preview beside it without changing anything.": "l'aperçu à côté, sans rien modifier.", + "the raw, so it keeps its look.": "du RAW, afin de conserver leur rendu.", + "the shadows: the black level recorded in the file is now subtracted.": "les ombres : le niveau de noir enregistré dans le fichier est désormais soustrait.", + "the show runs until you stop it, so the ending doesn't come up). Random order never moves them, ←/→ step across them,": "le diaporama tourne jusqu'à ce que vous l'arrêtiez, donc l'écran de fin n'apparaît pas). L'ordre aléatoire ne les déplace jamais, ←/→ passent de l'un à l'autre,", + "the system places it.": "c'est le système qui la place.", + "the window. The shortcut they show is the one Import Photos… has now.": "la fenêtre. Le raccourci qu'ils affichent est celui qu'a Importer des photos… en ce moment.", + "their old white balance; merge them again.": "leur ancienne balance des blancs ; fusionnez-les à nouveau.", + "their own ids, stacks keep only photos that exist (at least two), folders inside themselves move to the top,": "leurs propres identifiants, les piles ne gardent que des photos qui existent (au moins deux), les dossiers contenus dans eux-mêmes remontent au sommet,", + "them saves a new set.": "enregistre un nouveau jeu.", + "there in another case, a link, a name Windows reads another way (`aux.jpg`, a `~`, a `:`, a dot or a space at the": "présent avec une autre casse, d'un lien, d'un nom que Windows lit autrement (`aux.jpg`, un `~`, un `:`, un point ou une espace à la", + "there, has it a sidecar): it has just listed the folder, and reads the answers off the listing. On a network share": "est-il là, a-t-elle un fichier annexe) : elle vient de lister le dossier et lit les réponses dans la liste. Sur un partage réseau,", + "time is typed, and picking a day replaces one). Typing still works, and \"2026-10-01 10:00\" (a space for the": "heure se saisit au clavier, et choisir un jour en remplace une). La saisie fonctionne toujours, et « 2026-10-01 10:00 » (une espace à la place du", + "to Recently Deleted, so they also left their folder's view (issue #1805). They stay in the library and in their": "vers Supprimées récemment, si bien qu'elles quittaient aussi la vue de leur dossier (ticket #1805). Elles restent dans la bibliothèque et dans leur", + "to reset it\"), in every language (issue #1436).": "pour réinitialiser »), dans toutes les langues (ticket #1436).", + "to save it as UTF-8. Exporting warns about keywords Capture One won't import, and names any keyword the format can't": "d'enregistrer en UTF-8. L'exportation avertit des mots-clés que Capture One n'importera pas, et nomme tout mot-clé que le format ne peut pas", + "to the menu bar and the app ignored those keys, assuming the menu bar would handle them. Keys outside the menus": "à la barre de menus et l'application ignorait ces touches, en supposant que la barre de menus s'en chargerait. Les touches hors des menus", + "too, but not applied by default: our demosaic already hides most of that colour fringing, and the table on top made": "elle aussi, mais pas appliquée par défaut : notre dématriçage masque déjà l'essentiel de ces franges colorées, et la table par-dessus rendait", + "triangles, a highlight under the pointer. A folded section shows how many rows it holds, counts of 0 are fainter,": "triangles des lignes, une surbrillance sous le pointeur. Une section repliée indique combien de lignes elle contient, les décomptes de 0 sont plus pâles,", + "two dates of a \"between\" can't be picked out of order; Esc closes just the calendar. It picks dates, not times (a": "deux dates d'un « entre » ne peuvent pas être choisies dans le désordre ; Échap ne ferme que le calendrier. Il choisit des dates, pas des heures (une", + "under the pointer. It used to be centred, so every tab of a different height moved it.": "sous le pointeur. Elle était auparavant centrée, si bien que chaque onglet de hauteur différente la déplaçait.", + "used to open at 1600 × 1000 every time. Double-click the top bar to zoom the window, quit, and it is zoomed when": "s'ouvrait auparavant toujours à 1600 × 1000. Double-cliquez sur la barre supérieure pour zoomer la fenêtre, quittez, et elle est zoomée quand", + "usual and then added to Photos, into a top-level album of that name (made when it's missing). The toast says how": "d'habitude puis ajoutés à Photos, dans un album de premier niveau portant ce nom (créé s'il n'existe pas). La notification indique combien de", + "watermark preview for it, no longer crashes LightCraft; the export is capped at the encoders' 65,535 pixels.": "Exporter, ne fait plus planter LightCraft ; l'exportation est plafonnée aux 65 535 pixels des encodeurs.", + "way round, \"in the last 0 days\", a colour label that doesn't exist, \"contains\" with nothing to look for, an": "sens, « dans les 0 derniers jours », une étiquette de couleur qui n'existe pas, « contient » sans rien à chercher, un", + "when a `cargo` build runs outside `nix develop` (no Vulkan loader); start it from there.": "quand une compilation `cargo` s'exécute en dehors de `nix develop` (pas de chargeur Vulkan) ; lancez-la depuis cet environnement.", + "when the preview renders in a few milliseconds (it waits at most 40 % of a frame for it; slower renders, such as": "quand l'aperçu est calculé en quelques millisecondes (il attend au plus 40 % d'une image ; les rendus plus lents, comme", + "where the pointer landed, and a single click on the thumb leaves the value alone.": "l'endroit où le pointeur s'est posé, et un simple clic sur la poignée laisse la valeur intacte.", + "which section you are in and can fold it from there.": "dans quelle section vous êtes et pouvez la replier depuis là.", + "while the 1:1 detail is on its way. It appears once that has lasted half a second, so quick renders never show it.": "pendant que le détail 1:1 arrive. Il apparaît une fois que cela dure depuis une demi-seconde, de sorte que les rendus rapides ne l'affichent jamais.", + "while they are renamed (it can be stopped, and goes on at the next open).": "pendant leur renommage (il peut être interrompu et reprend à la prochaine ouverture).", + "white, empty Point Color slots…) as settings that couldn't be carried over.": "blanc tel que pris, les emplacements de Point de couleur vides…) comme des réglages qui n'ont pas pu être repris.", + "windows and toasts are gone.": "ainsi que les notifications ont disparu.", + "with NVIDIA), LightCraft still stops, because its window can't keep drawing on the lost device, but it now says": "avec NVIDIA), LightCraft s'arrête toujours, car sa fenêtre ne peut pas continuer à dessiner sur le périphérique perdu, mais il affiche désormais", + "with Z lenses and with F-mount lenses on the FTZ adapter, follows the in-body stabilisation's shift of the optical": "avec les objectifs Z et avec les objectifs à monture F sur l'adaptateur FTZ, suit le décalage, dû à la stabilisation du boîtier, du centre", + "with the Dock at a side of the screen, or of a window already as wide as the screen. Zoomed by a double-click": "avec le Dock sur un côté de l'écran, ou pour une fenêtre déjà aussi large que l'écran. Zoomée par un double-clic", + "with the logs of the two previous runs beside it, so warnings and crashes of a run started from a desktop menu or the": "avec les journaux des deux exécutions précédentes à côté, afin que les avertissements et plantages d'une exécution lancée depuis un menu du bureau ou le", + "with the original and opens it in PhotoCraft. LightCraft finds PhotoCraft where its installer put it (Windows,": "avec l'original et l'ouvre dans PhotoCraft. LightCraft trouve PhotoCraft là où son installateur l'a placé (Windows,", + "with those edits went from about 3.7 s to 1.9 s. Photos look the same as before.": "avec ces retouches est passée d'environ 3,7 s à 1,9 s. Les photos ont le même aspect qu'avant.", + "without applying it.": "sans l'appliquer.", + "yet and import as \"preview only\", with the reason.": "encore et s'importent en « aperçu uniquement », avec la raison.", + "you come back; un-zoom it and it goes back to the size it had before.": "vous revenez ; dézoomez-la et elle retrouve la taille qu'elle avait avant.", + "yours (issues #610, #1066). They were ordinary `.jpg` files in the library's `thumbs` folder, which is usually": "vous appartenant (tickets #610, #1066). C'étaient de simples fichiers `.jpg` dans le dossier `thumbs` de la bibliothèque, qui se trouve généralement", + "zoom, so it goes by the window's size, and when in doubt takes the window for a window of the size it has: it": "zoom ; LightCraft se fie donc à la taille de la fenêtre et, dans le doute, la prend pour une simple fenêtre de cette taille : elle", + "⇧-click and the line tapers from the old values to the new ones. The whole line is one undo step.": "⇧-clic et la ligne passe progressivement des anciennes valeurs aux nouvelles. La ligne entière forme une seule étape d'annulation.", + "Top bar": "Barre supérieure", + "Tool strip": "Barre d’outils", + "Bottom bar": "Barre inférieure", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221..22eb2d49e3 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -17,6 +17,7 @@ "Auto Sync: edits apply to {n} photos": "Sinkronisasi otomatis: edit diterapkan ke {n} foto", "Automatic ({} MB)": "Otomatis ({} MB)", "Click {}:1": "Klik {}:1", + "Collapse {name}": "Ciutkan {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Ruang warna: Rec. 2020 {curve} (AVIF HDR)", "Create {n} Virtual Copies": "Buat {n} salinan virtual", "Decoder: {reason}": "Dekoder: {reason}", @@ -26,6 +27,7 @@ "Delete “{current}”": "Hapus “{current}”", "Duplicate \"{label}\"": "Duplikat \"{label}\"", "Example: {example}": "Contoh: {example}", + "Expand {name}": "Luaskan {name}", "Exported {n} photo{}": "{n} foto{:.0} diekspor", "Exported {ok} of {total} photo{}": "{ok} dari {total} foto diekspor{:.0}", "Exported {} point curve preset{}": "{} preset kurva titik{:.0} diekspor", @@ -33,6 +35,7 @@ "Exporting {} of {total}": "Mengekspor {} dari {total}", "Filter bar — {active} active filter{}": "Bilah filter — {active} filter aktif{:.0}", "Healed {n} dust spot{}": "{n} bintik debu diperbaiki{:.0}", + "Import photos with File → Import Photos… ({}), or drop them here": "Impor foto melalui File → Impor foto… ({}), atau seret ke sini", "Imported {n} point curve preset{}": "{n} preset kurva titik diimpor{:.0}", "Imported {n} preset{}": "{n} preset{:.0} diimpor", "Imported {n} preset{}, {f} file{} not readable": "{n} preset diimpor{0:.0}, {f} file tidak dapat dibaca{1:.0}", @@ -135,6 +138,7 @@ "Label Set: {name}": "Set label: {name}", "Quick Develop: {name}": "Olah cepat: {name}", "Reset {name}": "Atur ulang {name}", + "{name} value": "Nilai {name}", "Updated “{name}”": "“{name}” diperbarui", "{month}": "{month:02}", "{month} {year}": "{month:02}/{year}", @@ -230,6 +234,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "“{parent}” sudah berisi “{name}”. Gabungkan keduanya?", "There is a “{name}” at the top level already. Merge the two?": "Sudah ada “{name}” di tingkat teratas. Gabungkan keduanya?", "Added “{keyword}” to {n} photo{}": "“{keyword}” ditambahkan ke {n} foto{:.0}", + "Add Keyword “{keywords}”": "Tambahkan kata kunci “{keywords}”", "On {have} of {of} selected photos": "Pada {have} dari {of} foto yang dipilih", "Remove “{name}”": "Hapus “{name}”", "There is a keyword set “{name}” already": "Set kata kunci “{name}” sudah ada", @@ -251,6 +256,7 @@ "{what} merge cancelled": "Penggabungan {what} dibatalkan", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "{n} foto Lokal{:.0} dilewati: album hanya dapat berisi foto pustaka (tambahkan ke Foto saya terlebih dahulu)", "New Folder in “{name}”": "Folder baru di “{name}”", + "Created folder “{name}” in “{parent}”": "Folder “{name}” dibuat di “{parent}”", "Moved {} photo(s)": "{} foto dipindahkan", "not added to Apple Photos: {e}": "tidak ditambahkan ke Apple Photos: {e}", "{n} added to Apple Photos album “{album}”": "{n} ditambahkan ke album Apple Photos “{album}”", @@ -296,8 +302,9 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” sudah terdaftar sebagai orang. Jika digabungkan, keduanya menjadi satu orang; Urungkan akan memisahkannya lagi.", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}: resolusi penuhnya ({full}) memerlukan memori melebihi kapasitas komputer ini", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}, resolusi maksimum untuk panorama (resolusi penuhnya {full})", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} foto katalog ada di Baru dihapus pada pustaka ini dan tetap di sana; pulihkan dari Baru dihapus untuk melihatnya.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "Listing folders — folders: {folders}, files: {files}": "Mendata folder — folder: {folders}, file: {files}", "Added {n} photo{}": "{n} foto ditambahkan{:.0}", "Could not read {name}: {e}": "Tidak dapat membaca {name}: {e}", "Drop to import {n} item{}": "Jatuhkan untuk mengimpor {n} item{:.0}", @@ -305,5 +312,13 @@ "Drop to review {n} item{} for import": "Jatuhkan untuk meninjau {n} item sebelum impor{:.0}", "Inside: {names}": "Di dalam: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Ke mana katalog Lightroom “{catalog}” diimpor?", - "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})", + "Photo: {name}": "Foto: {name}", + "Panel layout could not be restored: {error}": "Tata letak panel tidak dapat dipulihkan: {error}", + "Panel move was not applied: {error}": "Pemindahan panel tidak diterapkan: {error}", + "{name} is installed": "{name} sudah terinstal", + "{name} is installed and in use: face recognition is on": "{name} sudah terinstal dan digunakan: pengenalan wajah aktif", + "Creates {stacks} stack{} from {photos} of {scope}": "Membuat {stacks} tumpukan dari {photos} foto ({scope}){:.0}", + "{n} selected photo{} · {pages} page{}": "{n} foto dipilih · {pages} halaman{:.0}{:.0}", + "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0d6da9b8fb..1c70f26344 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -45,6 +45,7 @@ "Add Catchlight": "Tambahkan catchlight", "Add Face Model…": "Tambahkan model wajah…", "Add Folder to Local": "Tambahkan folder ke Lokal", + "Add Locations": "Tambahkan lokasi", "Add Mask": "Tambahkan masker", "Add Object Click": "Tambahkan titik objek", "Add Point Color Sample": "Tambahkan sampel warna titik", @@ -273,6 +274,7 @@ "Center": "Tengah", "Change": "Ubah", "Change Component Mode": "Ubah mode komponen", + "Change Time": "Ubah waktu", "Characters not allowed in file names (/ \\ : * ? \" < > |) become -; an existing name gets -1, -2….": "Karakter yang tidak boleh ada di nama file (/ \\ : * ? \" < > |) diganti dengan -; nama yang sudah ada diberi akhiran -1, -2….", "Charcoal": "Abu-abu arang", "Check All": "Centang semua", @@ -340,7 +342,6 @@ "Close file": "Tutup file", "Close panel": "Tutup panel", "Cloudy": "Berawan", - "Collapse": "Ciutkan", "Collapse All Stacks": "Ciutkan semua tumpukan", "Collapse Stack": "Ciutkan tumpukan", "Color": "Warna", @@ -429,6 +430,7 @@ "Create Smart Album from Filter…": "Buat album pintar dari filter…", "Create Smart Album…": "Buat album pintar…", "Create Stack": "Buat tumpukan", + "Create Stacks": "Buat tumpukan", "Create Version": "Buat versi", "Create Version from Step": "Buat versi dari langkah ini", "Create Virtual Copy": "Buat salinan virtual", @@ -443,6 +445,7 @@ "Crop, Rotate, Geometry": "Pangkas, putar, geometri", "Cropped": "Dipangkas", "Cross Process": "Cross Process", + "Cull": "Seleksi", "Culling": "Seleksi foto", "Curve": "Kurva", "Custom": "Kustom", @@ -560,6 +563,7 @@ "Download Place Names (GeoNames)": "Unduh nama tempat (GeoNames)", "Download the SAM 3 Model?": "Unduh model SAM 3?", "Downloaded and checked. Installing…": "Sudah diunduh dan diverifikasi. Menginstal…", + "The download failed": "Pengunduhan gagal", "Downloading model": "Mengunduh model", "Downloading place names": "Mengunduh nama tempat", "Downloads": "Unduhan", @@ -591,6 +595,7 @@ "Edit Info": "Edit info", "Edit Keyword": "Edit kata kunci", "Edit Keyword Set": "Edit set kata kunci", + "Edit Keywords": "Edit kata kunci", "Edit Keyword Tag": "Edit tag kata kunci", "Edit Keyword Tag…": "Edit tag kata kunci…", "Edit Label Names": "Edit nama label", @@ -614,6 +619,7 @@ "Effects": "Efek", "Empty Recently Deleted": "Kosongkan Baru dihapus", "Enable Lens Corrections": "Aktifkan koreksi lensa", + "Enable Painting": "Aktifkan kuas", "Enable Profile Corrections": "Aktifkan koreksi profil", "End": "Akhir", "End Interaction": "Akhiri interaksi", @@ -693,6 +699,7 @@ "Failed": "Gagal", "Failed its last test": "Gagal pada pengujian terakhir", "Favorite Mask Effect": "Jadikan efek masker favorit", + "Favorite": "Favorit", "Favorite Preset": "Jadikan preset favorit", "Favorite Profile": "Jadikan profil favorit", "Favorites": "Favorit", @@ -912,7 +919,7 @@ "Import from Folder…": "Impor dari folder…", "Import new photos": "Impor foto baru", "Import photos to get started": "Impor foto untuk memulai", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Impor foto melalui File → Impor foto… (Cmd+Shift+I), atau seret ke sini", + "Import photos with File → Import Photos…, or drop them here": "Impor foto melalui File → Impor foto…, atau seret ke sini", "Imported": "Diimpor", "Imported Photos": "Foto yang diimpor", "Importing": "Mengimpor", @@ -991,6 +998,7 @@ "Keyword Suggestions": "Saran kata kunci", "Keyword Tag Options": "Opsi tag kata kunci", "Keyword to paint": "Kata kunci yang akan diterapkan", + "Type a keyword to paint in the Keywords panel": "Ketik kata kunci yang akan diterapkan di panel Kata kunci", "Keywords": "Kata kunci", "Keywords & People": "Kata kunci & orang", "Keywords (K)": "Kata kunci (K)", @@ -1041,6 +1049,9 @@ "LightCraft could not start": "LightCraft gagal dijalankan", "LightCraft couldn't find where to keep your library.": "LightCraft tidak dapat menemukan lokasi untuk menyimpan pustaka Anda.", "LightCraft couldn't open the library at": "LightCraft tidak dapat membuka pustaka di", + "There is no LightCraft library in this folder any more.": "Folder ini tidak lagi berisi pustaka LightCraft.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Pustaka tidak ada di sini: pustaka dipindahkan atau diganti namanya, atau drive atau berbagi jaringannya tidak terhubung.", + "This folder can't be read:": "Folder ini tidak dapat dibaca:", "LightCraft does not know this model, so it assumed:": "LightCraft tidak mengenali model ini, jadi menggunakan asumsi berikut:", "LightCraft on GitHub": "LightCraft di GitHub", "LightCraft stopped": "LightCraft berhenti", @@ -1483,6 +1494,12 @@ "Purple Saturation": "Saturasi ungu", "Put New Keywords Inside": "Tempatkan kata kunci baru di dalamnya", "Put New Keywords Inside This Keyword": "Masukkan kata kunci baru ke dalam kata kunci ini", + "Use This as Keyword Shortcut": "Gunakan sebagai pintasan kata kunci", + "Set Keyword Shortcut": "Atur pintasan kata kunci", + "Set Keyword Shortcut…": "Atur pintasan kata kunci…", + "Add or Remove Keyword Shortcut": "Tambah atau hapus pintasan kata kunci", + "Keyword Shortcut": "Pintasan kata kunci", + "Part of the keyword shortcut": "Bagian dari pintasan kata kunci", "Put the locations you removed from Local back (no files change)": "Kembalikan lokasi yang dikeluarkan dari Lokal (tidak ada file yang diubah)", "Quality": "Kualitas", "Query Photos": "Kueri foto", @@ -1995,6 +2012,7 @@ "That includes the photos in the folders inside it.": "Termasuk foto di dalam subfoldernya.", "That key can't be used as a shortcut": "Tombol itu tidak dapat digunakan sebagai pintasan", "The SAM 3 model is installed: Object and Describe masks are ready.": "Model SAM 3 sudah terinstal: masker Objek dan Deskripsi siap digunakan.", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Tombol Tag menampilkan placeholder untuk templat, seperti {date} atau {seq}. Setiap file diganti namanya di disk bersama file sidecar XMP-nya; nama yang sudah dipakai mendapat -1, -2…", "The denoise model is installed and in use: the AI Denoise Amount slider under Detail now works": "Model pengurangan noise sudah terinstal dan digunakan: slider Kekuatan pengurangan noise AI di panel Detail kini dapat dipakai", "The download didn't work:": "Unduhan gagal:", "The ending screen, after the last photo.": "Layar penutup, setelah foto terakhir.", @@ -2332,6 +2350,7 @@ "Mask Pins": "Pin masker", "Photo Counts": "Jumlah foto", "An import is running": "Impor sedang berjalan", + "The photos are imported once it ends": "Foto diimpor setelah selesai", "An import is running. Drop photos when it has finished": "Impor sedang berjalan. Jatuhkan foto setelah selesai", "Close the open dialog to drop files here": "Tutup dialog yang terbuka untuk menjatuhkan file di sini", "Close the open dialog, then drop the files again": "Tutup dialog yang terbuka, lalu jatuhkan file lagi", @@ -2339,5 +2358,17 @@ "Drop to open the face model": "Jatuhkan untuk membuka model wajah", "Dropped Files": "File yang dijatuhkan", "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", - "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan" + "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", + "Thumbnail size": "Ukuran gambar mini", + "Import Thumbnail Size": "Ukuran Gambar Mini Impor", + "Face recognition is on": "Pengenalan wajah aktif", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Pengenalan wajah nonaktif. Aktifkan untuk mendapatkan saran nama dan melihat wajah yang mirip bersama-sama.", + "Turn on": "Aktifkan", + "Set up face recognition": "Siapkan pengenalan wajah", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Pengenalan wajah memerlukan model untuk menyarankan nama: sekali unduh, di Pengaturan.", + "Turn on name suggestions": "Aktifkan saran nama", + "Set up name suggestions…": "Siapkan saran nama…", + "Top bar": "Bilah atas", + "Tool strip": "Bilah alat", + "Bottom bar": "Bilah bawah" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e94..4437aa644d 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -36,9 +36,10 @@ "Build Standard-Sized Previews ({scope})": "Genera anteprime di dimensione standard ({scope})", "Building previews for {} photos…": "Generazione delle anteprime per {} foto…", "Click {}:1": "Clic {}:1", + "Collapse {name}": "Comprimi {name}", "Couldn't open the editor: {e}": "Impossibile aprire l'editor: {e}", "Create {n} Virtual Copies": "Crea {n} copie virtuali", - "Creates {} stacks from {} of {scope}": "Crea pile: {} (da {} di {scope})", + "Creates {stacks} stack{} from {photos} of {scope}": "Crea pile: {stacks} (da {photos} di {scope}){:.0}", "Decoder: {reason}": "Decodificatore: {reason}", "Delete \"{label}\"": "Elimina \"{label}\"", "Delete \"{label}\" (and the mask)": "Elimina \"{label}\" (e la maschera)", @@ -48,6 +49,7 @@ "Done ({what}): {done} photo{plural}": "Fatto ({what}): {done} foto{plural:.0}", "Duplicate \"{label}\"": "Duplica \"{label}\"", "Example: {example}": "Esempio: {example}", + "Expand {name}": "Espandi {name}", "Exported {n} photo{}": "Foto esportate: {n}{:.0}", "Exported {ok} of {total} photo{}": "Foto esportate: {ok} di {total}{:.0}", "Exported {} point curve preset{}": "Preset di curva a punti esportati: {}{:.0}", @@ -60,6 +62,7 @@ "Healed {n} dust spot{}": "Macchie di polvere corrette: {n}{:.0}", "Import cancelled · {} photo{} added": "Importazione annullata · foto aggiunte: {}{:.0}", "Import failed: {e}": "Importazione non riuscita: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importa le foto con File → Importa foto… ({}), oppure trascinale qui", "Import warnings ({n}):\n{warnings}": "Avvisi di importazione ({n}):\n{warnings}", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Il profilo XMP \"{profile}\" non è stato applicato a {path}; i colori possono differire da Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "La geometria di Lightroom non è stata conservata per {path}; {mode} verrà ricalcolato.", @@ -113,6 +116,7 @@ "Rendering on the CPU: {why}": "Rendering sulla CPU: {why}", "Replace {} with:": "Sostituisci {} con:", "Reset {name}": "Reimposta {name}", + "{name} value": "Valore di {name}", "Reset {} Channel": "Reimposta canale {}", "Restore {}": "Ripristina {}", "Restore {} Photo{}": "Ripristina {} foto{:.0}", @@ -223,6 +227,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "“{parent}” ha già “{name}”. Unire le due?", "There is a “{name}” at the top level already. Merge the two?": "Al livello principale c'è già “{name}”. Unire le due?", "Added “{keyword}” to {n} photo{}": "Aggiunta “{keyword}” a {n} foto{:.0}", + "Add Keyword “{keywords}”": "Aggiungi parola chiave “{keywords}”", "On {have} of {of} selected photos": "Su {have} di {of} foto selezionate", "Remove “{name}”": "Rimuovi “{name}”", "There is a keyword set “{name}” already": "Esiste già un set di parole chiave “{name}”", @@ -240,6 +245,7 @@ "{what} merge cancelled": "Unione {what} annullata", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Foto locali saltate: {n}{0:.0}; gli album contengono foto della libreria (prima aggiungile a Le mie foto)", "New Folder in “{name}”": "Nuova cartella in “{name}”", + "Created folder “{name}” in “{parent}”": "Cartella “{name}” creata in “{parent}”", "Moved {} photo(s)": "Foto spostate: {}", "not added to Apple Photos: {e}": "non aggiunte a Foto di Apple: {e}", "{n} added to Apple Photos album “{album}”": "Aggiunte all'album “{album}” di Foto di Apple: {n}", @@ -250,6 +256,7 @@ "{s} s of AV1 video": "{s} s di video AV1", "Delete {n} effect preset{}? This can't be undone.": "Eliminare i preset effetto ({n})?{:.0} L'operazione non si può annullare.", "{count} more warnings.": "Altri avvisi: {count}.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} foto del catalogo sono in Eliminate di recente di questa libreria e vi restano; ripristinale da Eliminate di recente per vederle.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} immagini del catalogo non sono state importate perché i loro record nel catalogo sono incompleti.", "· {in_source} identical copies": "· copie identiche: {in_source}", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Unione {what} aggiunta a {mp}, la dimensione massima di un panorama (la dimensione piena è {full})", @@ -285,7 +292,7 @@ "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Inside: {names}": "Al suo interno: {names}", "Template preview: {name}": "Anteprima del modello: {name}", - "{n} photos in view · {slides} slides · {time}": "Foto nella vista: {n} · diapositive: {slides} · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "Foto nella vista: {n} · diapositive: {slides} · {time}{:.0}{:.0}", "Applied {name}": "{name} applicato", "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” è già una persona. Unirle ne crea una sola; Annulla le separa di nuovo.", "{n} originals opened in the other editor": "Originali aperti nell'altro editor: {n}", @@ -293,7 +300,7 @@ "Effect: {name}": "Effetto: {name}", " in {g} group{}": " in gruppi: {g}{:.0}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Spazio colore: Rec. 2020 {curve} (AVIF HDR)", - "{n} selected photos · {pages} pages": "Foto selezionate: {n} · pagine: {pages}", + "{n} selected photo{} · {pages} page{}": "Foto selezionate: {n} · pagine: {pages}{:.0}{:.0}", "Already in “{}”": "Già in “{}”", "Move {n} photo{} to “{}”": "Sposta foto in “{1}” ({n}){0:.0}", "Move {n} photo{} to “{}”?": "Spostare le foto in “{1}” ({n})?{0:.0}", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "Impossibile leggere {name}: {e}", "Added {n} photo{}": "Foto aggiunte: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})", + "Photo: {name}": "Foto: {name}", + "Panel layout could not be restored: {error}": "Non è stato possibile ripristinare la disposizione dei pannelli: {error}", + "Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}", + "{name} is installed": "{name} è installato", + "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d1..a0d39d0610 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -42,6 +42,7 @@ "Add to Local": "Aggiungi a Locale", "Add to My Photos": "Aggiungi a Le mie foto", "Can't be moved here": "Non si possono spostare qui", + "Import photos with File → Import Photos…, or drop them here": "Importa le foto con File → Importa foto…, oppure trascinale qui", "This row covers more than one disk: drop on a folder inside it": "Questa riga comprende più di un disco: rilascia su una cartella al suo interno", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Le foto locali non sono ancora nella libreria: prima Aggiungi a Le mie foto, poi spostale", "Add to Selected Photos": "Aggiungi alle foto selezionate", @@ -118,6 +119,7 @@ "Auto-Tag Photos from Tracklog": "Geolocalizza automaticamente le foto dal tracciato", "Auto-Tag from Tracklog": "Geolocalizza dal tracciato", "Auto-Tag from Tracklog…": "Geolocalizza dal tracciato…", + "Add Locations": "Aggiungi posizioni", "Automatic": "Automatico", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Automatico disegna la vista Dettaglio alla dimensione in cui è mostrata, fino ai pixel della foto. Scegli una dimensione per limitarla: più piccola è più veloce.", "Automatically Write Changes into XMP": "Scrivi automaticamente le modifiche nell'XMP", @@ -240,7 +242,6 @@ "Close file": "Chiudi file", "Close panel": "Chiudi pannello", "Cloudy": "Nuvoloso", - "Collapse": "Comprimi", "Collapse All Stacks": "Comprimi tutte le pile", "Collapse Stack": "Comprimi pila", "Color": "Colore", @@ -334,6 +335,9 @@ "Crop, Rotate, Geometry": "Ritaglio, rotazione, geometria", "Cross Process": "Processo incrociato", "Culling": "Selezione", + "Cull": "Seleziona", + "Create Stacks": "Crea pile", + "Change Time": "Cambia ora", "Curve": "Curva", "Custom": "Personalizzato", "Custom template…": "Modello personalizzato…", @@ -452,6 +456,7 @@ "Effects": "Effetti", "Empty Recently Deleted": "Svuota Eliminate di recente", "Enable Lens Corrections": "Attiva correzioni obiettivo", + "Enable Painting": "Attiva pennello", "Enable Profile Corrections": "Attiva correzioni del profilo", "End Interaction": "Termina interazione", "English": "Inglese", @@ -675,7 +680,6 @@ "Import as new": "Importa come nuova", "Import from Device": "Importa da dispositivo", "Import from Folder…": "Importa da cartella…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importa le foto con File → Importa foto… (Cmd+Maiusc+I), oppure trascinale qui", "Imported": "Importato", "Imported Photos": "Foto importate", "Importing": "Importazione in corso", @@ -726,6 +730,7 @@ "Keyword Sets": "Set di parole chiave", "Keyword Suggestions": "Suggerimenti di parole chiave", "Keyword to paint": "Parola chiave da applicare", + "Type a keyword to paint in the Keywords panel": "Digita una parola chiave da applicare nel pannello Parole chiave", "Keywords": "Parole chiave", "Keywords (K)": "Parole chiave (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "Le parole chiave che aggiungi compaiono qui; ⌥1-⌥9 le applicano.", @@ -761,6 +766,8 @@ "LightCraft could not start": "Impossibile avviare LightCraft", "LightCraft couldn't find where to keep your library.": "LightCraft non ha trovato dove salvare la tua libreria.", "LightCraft couldn't open the library at": "LightCraft non è riuscito ad aprire la libreria in", + "There is no LightCraft library in this folder any more.": "In questa cartella non c'è più una libreria LightCraft.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "La libreria non c'è: è stata spostata o rinominata, oppure il suo disco o la sua condivisione di rete non è collegata.", "LightCraft on GitHub": "LightCraft su GitHub", "LightCraft website": "Sito web di LightCraft", "LightCraft — Second Window": "LightCraft: seconda finestra", @@ -1485,6 +1492,7 @@ "Table": "Tabella", "Tags": "Tag", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Tag: vedi Tag accanto al modello. I file vengono rinominati sul disco (con i loro XMP collaterali); ai nomi già esistenti si aggiunge -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Il pulsante Tag elenca i segnaposto per il modello, come {date} o {seq}. Ogni file viene rinominato sul disco insieme al suo file XMP collaterale; un nome già in uso riceve -1, -2…", "Take a snapshot": "Acquisisci istantanea", "Targeted Adjustment": "Regolazione mirata", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Regolazione mirata: trascina in su o in giù sulla foto per regolare i colori in quel punto", @@ -1736,6 +1744,7 @@ "Denoise Settings": "Impostazioni della riduzione disturbo", "Denoise all photos with an Amount": "Riduci il disturbo in tutte le foto con una quantità", "Downloaded and checked. Installing…": "Scaricato e verificato. Installazione…", + "The download failed": "Download non riuscito", "Failed its last test": "Non ha superato l'ultimo test", "Graphics card": "Scheda grafica", "I have read these terms and accept them for my own use": "Ho letto queste condizioni e le accetto per uso personale", @@ -1990,6 +1999,12 @@ "No photo has it; the keywords below it go too.": "Nessuna foto ce l'ha; vengono tolte anche le parole chiave sotto di essa.", "Edit Keyword Tag…": "Modifica tag parola chiave…", "Put New Keywords Inside This Keyword": "Metti le nuove parole chiave dentro questa", + "Use This as Keyword Shortcut": "Usa come scorciatoia parole chiave", + "Set Keyword Shortcut": "Imposta scorciatoia parole chiave", + "Set Keyword Shortcut…": "Imposta scorciatoia parole chiave…", + "Add or Remove Keyword Shortcut": "Applica o togli scorciatoia parole chiave", + "Keyword Shortcut": "Scorciatoia parole chiave", + "Part of the keyword shortcut": "Fa parte della scorciatoia parole chiave", "Purge Unused Keywords": "Elimina le parole chiave non usate", "Delete Keyword…": "Elimina parola chiave…", "Drop here for the top level": "Rilascia qui per il livello principale", @@ -2001,6 +2016,7 @@ "& Containing": "e contenenti", "Edit Set…": "Modifica set…", "Edit Keyword Set": "Modifica set di parole chiave", + "Edit Keywords": "Modifica parole chiave", "Keywords (⌥1–⌥9)": "Parole chiave (⌥1-⌥9)", "A keyword set needs a name": "Un set di parole chiave ha bisogno di un nome", "Save as a new set": "Salva come nuovo set", @@ -2097,6 +2113,48 @@ "Recent Libraries": "Librerie recenti", "Clear Recent Libraries": "Cancella le librerie recenti", "No Recent Libraries": "Nessuna libreria recente", + "Always merge into the open library": "Unisci sempre alla libreria aperta", + "Another library was opened since this window appeared: nothing was imported": "Nel frattempo è stata aperta un'altra libreria: non è stato importato nulla", + "Ask me": "Chiedi ogni volta", + "Ask me lists your recent libraries at launch. Holding Alt (Option on a Mac) as the window appears asks once.": "Con Chiedi ogni volta, all'avvio compaiono le librerie recenti. Tenendo premuto Alt (Opzione su Mac) mentre compare la finestra, la domanda viene fatta una volta sola.", + "Ask where to import it": "Chiedi dove importarlo", + "At launch": "All'avvio", + "Burst: how alike (loose … strict)": "Raffica: quanto simili (poco … molto)", + "Burst: shots at most this far apart": "Raffica: scatti distanti al massimo", + "Checking recent libraries": "Controllo delle librerie recenti", + "Choose the library to open.": "Scegli la libreria da aprire.", + "Close a dialog by clicking outside it": "Chiudi una finestra di dialogo facendo clic fuori", + "Create Library and Import": "Crea libreria e importa", + "Create a new library": "Crea una nuova libreria", + "Dialogs": "Finestre di dialogo", + "Don't ask again (always merge into the open library)": "Non chiedere più (unisci sempre alla libreria aperta)", + "Last opened": "Ultima apertura", + "LightCraft opens the new library, then imports the catalog into it. Its folder must be new or empty.": "LightCraft apre la nuova libreria e poi vi importa il catalogo. La sua cartella deve essere nuova o vuota.", + "Lower it when a panning or moving burst splits into several groups.": "Abbassalo quando una raffica in panning o in movimento si divide in più gruppi.", + "No horizon or vertical lines to level by": "Nessun orizzonte o linea verticale su cui livellare", + "No recent libraries. Open one from a folder, or make a new one.": "Nessuna libreria recente. Aprine una da una cartella o creane una nuova.", + "Not answering yet: the drive may be asleep or offline": "Non risponde ancora: il disco potrebbe essere in stop o scollegato", + "Not found: moved, renamed or on a disconnected drive": "Non trovata: spostata, rinominata o su un disco scollegato", + "Open": "Apri", + "Open Another…": "Apri un'altra…", + "Open a Library": "Apri una libreria", + "Open a library first, then drop the presets again": "Apri prima una libreria, poi trascina di nuovo i preset", + "Open now": "Aperta ora", + "Open the last library": "Apri l'ultima libreria", + "Remove from List": "Rimuovi dall'elenco", + "The catalog's photos, collections and edits join the ones already in this library.": "Foto, raccolte e modifiche del catalogo si aggiungono a quelle già presenti in questa libreria.", + "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library.": "L'importazione legge il catalogo senza modificarlo. Poi scegli se foto, modifiche, parole chiave e raccolte vanno nella libreria aperta ora o in una nuova libreria.", + "The library is empty: the catalog's photos, collections and edits become its first.": "La libreria è vuota: foto, raccolte e modifiche del catalogo saranno le sue prime.", + "The library itself stays where it is.": "La libreria resta dov'è.", + "The library's catalog can't be read:": "Impossibile leggere il catalogo della libreria:", + "The photos are imported once a library is open": "Le foto vengono importate appena c'è una libreria aperta", + "There is no LightCraft library in this folder any more": "In questa cartella non c'è più una libreria LightCraft", + "This folder can't be read:": "Impossibile leggere questa cartella:", + "This is a file, not a library folder": "Questo è un file, non una cartella di libreria", + "This library couldn't be checked": "Impossibile controllare questa libreria", + "This library couldn't be checked:": "Impossibile controllare questa libreria:", + "To be asked again: Settings → General → When importing a Lightroom catalog.": "Per riavere la domanda: Impostazioni → Generale → Quando importi un catalogo Lightroom.", + "When importing a Lightroom catalog": "Quando importi un catalogo Lightroom", "New Library: Choose Where to Put It": "Nuova libreria: scegli dove metterla", "New Library": "Nuova libreria", "Library name": "Nome della libreria", @@ -2259,6 +2317,7 @@ "This build cannot run recognition models: they can be added and chosen, not used.": "Questa versione non può eseguire modelli di riconoscimento: si possono aggiungere e scegliere, non usare.", "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "Questa versione non ha dove tenere i modelli dei volti, quindi l'elenco dei modelli non è disponibile. (L'app desktop ce l'ha.)", "Unnamed Faces": "Volti senza nome", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evita lo sfarfallio G-SYNC/FreeSync (dal prossimo avvio)", "smart album value|No": "No", "smart album value|Yes": "Sì", "Add Print Cell": "Aggiungi cella di stampa", @@ -2360,6 +2419,142 @@ "Dropped Files": "File rilasciati", "Import dropped files without review": "Importa i file rilasciati senza revisione", "An import is running": "Un'importazione è in corso", + "The photos are imported once it ends": "Le foto verranno importate dopo", "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", - "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto" + "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", + "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "Una diapositiva resta visibile per la sua durata, dissolvenza d'ingresso compresa. Con una dissolvenza di 0 il passaggio è netto.", + "Add a cell": "Aggiungi una cella", + "cells": "celle", + "cells overlap": "celle sovrapposte", + "Also the masks of the same name on the other selected photos": "Anche le maschere con lo stesso nome nelle altre foto selezionate", + "Apply to All Masks": "Applica a tutte le maschere", + "Choose a group": "Scegli un gruppo", + "Choose at least one setting to include": "Scegli almeno un'impostazione da includere", + "Click a cell to move, resize or arrange it": "Fai clic su una cella per spostarla, ridimensionarla o disporla", + "Color wheel": "Ruota dei colori", + "Combine with the existing person": "Unisci alla persona esistente", + "Copy Settings…": "Copia impostazioni…", + "Curve channel": "Canale della curva", + "Delete Cell": "Elimina cella", + "Delete…": "Elimina…", + "Export Effect Presets": "Esporta preset effetto", + "Fade": "Dissolvenza", + "Fade duration": "Durata della dissolvenza", + "Favorite": "Preferito", + "Filters": "Filtri", + "Group (optional)": "Gruppo (facoltativo)", + "Highlighted: sliders this mask changes. Sliders left out stay as they are when the preset is applied.": "Evidenziati: i cursori che questa maschera modifica. I cursori esclusi restano come sono quando si applica il preset.", + "Include Amount": "Includi quantità", + "Include brush size, feather and flow": "Includi dimensione, sfumatura e flusso del pennello", + "LightCraft Effect Presets": "Preset effetto di LightCraft", + "Manage Presets…": "Gestisci preset…", + "Managed by Printer (Adobe RGB)": "Gestito dalla stampante (Adobe RGB)", + "Managed by Printer (sRGB)": "Gestito dalla stampante (sRGB)", + "Mask": "Maschera", + "Masks keep their sliders. Export presets first to keep a copy.": "Le maschere mantengono i loro cursori. Esporta prima i preset per conservarne una copia.", + "Move to Group…": "Sposta nel gruppo…", + "Name the preset": "Dai un nome al preset", + "New group — Return": "Nuovo gruppo — Invio", + "New spot (Return adds it here)": "Nuova macchia (Invio la aggiunge qui)", + "Next page": "Pagina successiva", + "No Matte": "Nessun passe-partout", + "No change": "Nessuna modifica", + "No effect matches": "Nessun effetto corrisponde", + "No effect presets yet": "Ancora nessun preset effetto", + "One photo fills each page inside the margins.": "Una foto riempie ogni pagina entro i margini.", + "Overlay color": "Colore della sovrapposizione", + "Page": "Pagina", + "Page Options": "Opzioni pagina", + "Previous page": "Pagina precedente", + "Remove region": "Rimuovi area", + "Rename Person…": "Rinomina persona…", + "Renders the next slides while the current one is up, so fades never wait. Off: each slide renders when it is due (less memory and work).": "Prepara le diapositive successive mentre è visibile quella attuale, così le dissolvenze non aspettano mai. Disattivato: ogni diapositiva viene preparata quando tocca a lei (meno memoria e meno lavoro).", + "Reset Sliders": "Reimposta cursori", + "Resize region": "Ridimensiona area", + "Save Current Settings as New Preset…": "Salva le impostazioni attuali come nuovo preset…", + "Search effects": "Cerca effetti", + "Select a mask to apply or update presets.": "Seleziona una maschera per applicare o aggiornare i preset.", + "Show / hide": "Mostra / nascondi", + "Show mask": "Mostra maschera", + "Slide duration": "Durata della diapositiva", + "Slideshow in the View menu plays the photos in view from the selected one. These settings are saved with the library.": "Presentazione nel menu Visualizza riproduce le foto della vista a partire da quella selezionata. Queste impostazioni vengono salvate con la libreria.", + "Template name": "Nome del modello", + "The layout image can't be shown": "Impossibile mostrare l'immagine di layout", + "This page setup is not valid": "Questa impostazione di pagina non è valida", + "Thumbnail size": "Dimensione delle miniature", + "Import Thumbnail Size": "Dimensione delle miniature di importazione", + "Title bar": "Barra del titolo", + "Tool Overlay": "Sovrapposizione strumento", + "Ungrouped": "Senza gruppo", + "Unknown date": "Data sconosciuta", + "Unnamed face": "Volto senza nome", + "When pins show on the photo (Shift+H cycles)": "Quando mostrare i punti sulla foto (Maiusc+H li alterna)", + "current edits": "modifiche attuali", + "★ Favorites": "★ Preferiti", + "Tool Overlay: Auto": "Sovrapposizione strumento: automatica", + "Tool Overlay: Always": "Sovrapposizione strumento: sempre", + "Tool Overlay: Selected": "Sovrapposizione strumento: solo quello selezionato", + "Tool Overlay: Never": "Sovrapposizione strumento: mai", + "It is not a denoise model LightCraft understands": "Non è un modello di riduzione disturbo che LightCraft sa leggere", + "Click to hide clipping warnings for shadows and highlights.": "Fai clic per nascondere gli avvisi di taglio per ombre e luci.", + "Click to show clipping warnings for shadows and highlights.": "Fai clic per mostrare gli avvisi di taglio per ombre e luci.", + "Hide this wheel's effect": "Nascondi l'effetto di questa ruota", + "Loupe Overlay": "Sovrapposizione lente", + "Grid: add the next photo to the selection": "Griglia: aggiungi la foto successiva alla selezione", + "Grid: add the previous photo to the selection": "Griglia: aggiungi la foto precedente alla selezione", + "Grid: first photo of the view": "Griglia: prima foto della vista", + "Grid: last photo of the view": "Griglia: ultima foto della vista", + "My Preset": "Il mio preset", + "No clipping detected in this preview.": "Nessun taglio rilevato in questa anteprima.", + "No faces by that name": "Nessun volto con quel nome", + "No named people yet. Name the faces below to start.": "Ancora nessuna persona con nome. Per iniziare, dai un nome ai volti qui sotto.", + "No people yet": "Ancora nessuna persona", + "No person by that name": "Nessuna persona con quel nome", + "No unnamed faces. Faces found in your photos appear here until you name them.": "Nessun volto senza nome. I volti trovati nelle tue foto compaiono qui finché non dai loro un nome.", + "Face recognition is on": "Il riconoscimento dei volti è attivo", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Il riconoscimento dei volti è disattivato. Attivalo per ricevere suggerimenti di nomi e vedere insieme i volti simili.", + "Turn on": "Attiva", + "Set up face recognition": "Configura il riconoscimento dei volti", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Il riconoscimento dei volti ha bisogno di un modello per suggerire i nomi: un download una tantum, in Impostazioni.", + "Turn on name suggestions": "Attiva i suggerimenti di nomi", + "Set up name suggestions…": "Configura i suggerimenti di nomi…", + "A manual slideshow shows each slide until → or ← changes it. Exports still use the slide duration.": "Una presentazione manuale mostra ogni diapositiva finché → o ← non la cambia. Le esportazioni usano comunque la durata della diapositiva.", + "Auto-Collapse Iconic Panels": "Comprimi automaticamente i pannelli a icone", + "Cache limit": "Limite della cache", + "Checking for updates…": "Verifica degli aggiornamenti in corso…", + "Close other panels in group": "Chiudi gli altri pannelli del gruppo", + "Close panel window": "Chiudi la finestra del pannello", + "Close tab group": "Chiudi il gruppo di schede", + "Collapse column": "Comprimi colonna", + "Collapse to Icons": "Comprimi in icone", + "Could not check for updates:\n{error}": "Impossibile verificare gli aggiornamenti:\n{error}", + "Expand column": "Espandi colonna", + "Expand Panels": "Espandi pannelli", + "Field": "Campo", + "Float tab group": "Sgancia il gruppo di schede", + "Hold {key} to undock": "Tieni premuto {key} per sganciare", + "LightCraft Updates": "Aggiornamenti di LightCraft", + "LightCraft {version} is currently the newest version available.": "LightCraft {version} è la versione più recente disponibile.", + "Move group to": "Sposta il gruppo in", + "Move panel column": "Sposta la colonna dei pannelli", + "Move panel window": "Sposta la finestra del pannello", + "Move tab group": "Sposta il gruppo di schede", + "Open a library first, then drop the model again": "Apri prima una libreria, poi trascina di nuovo il modello", + "Operator": "Operatore", + "Organize into": "Organizza in", + "Other preset": "Preset per le altre immagini", + "Photos whose capture time can't be read were left as they were": "Le foto di cui non si può leggere l'ora di scatto sono rimaste invariate", + "Recently deleted files": "File eliminati di recente", + "Resize": "Ridimensiona", + "Restore All": "Ripristina tutto", + "Restore the photo to use it as the reference": "Ripristina la foto per usarla come riferimento", + "Show Metadata For": "Mostra metadati per", + "size": "dimensione", + "source": "origine", + "The active photo's capture time can't be read": "Impossibile leggere l'ora di scatto della foto attiva", + "The place names list towns of 15,000 people or more: in a smaller one, City gets the nearest larger town.": "L'elenco dei luoghi comprende i centri con almeno 15.000 abitanti: per uno più piccolo, Città indica il centro più grande più vicino.", + "Unit": "Unità", + "Top bar": "Barra superiore", + "Tool strip": "Barra degli strumenti", + "Bottom bar": "Barra inferiore" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16d..2fb625ff6a 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -17,6 +17,7 @@ "Auto Sync: edits apply to {n} photos": "自動同期:{n}枚に編集を適用", "Automatic ({} MB)": "自動({}MB)", "Click {}:1": "クリック時 {}:1", + "Collapse {name}": "{name}を折りたたむ", "Color space: Rec. 2020 {curve} (HDR AVIF)": "カラースペース:Rec. 2020 {curve}(HDR AVIF)", "Create {n} Virtual Copies": "{n}枚の仮想コピーを作成", "Decoder: {reason}": "デコーダー:{reason}", @@ -26,6 +27,7 @@ "Delete “{current}”": "「{current}」を削除", "Duplicate \"{label}\"": "「{label}」を複製", "Example: {example}": "例:{example}", + "Expand {name}": "{name}を展開", "Exported {n} photo{}": "{n}枚を書き出しました{:.0}", "Exported {ok} of {total} photo{}": "{total}枚中{ok}枚を書き出しました{:.0}", "Exported {} point curve preset{}": "{}件のポイントカーブを書き出しました{:.0}", @@ -33,6 +35,7 @@ "Exporting {} of {total}": "書き出し中:{total}枚中{}枚", "Filter bar — {active} active filter{}": "フィルターバー:{active}件適用中{:.0}", "Healed {n} dust spot{}": "{n}か所のほこりを修復しました{:.0}", + "Import photos with File → Import Photos… ({}), or drop them here": "「ファイル → 写真を読み込む…」({})から読み込むか、ここに写真をドロップしてください", "Imported {n} point curve preset{}": "{n}件のポイントカーブを読み込みました{:.0}", "Imported {n} preset{}": "{n}件のプリセットを読み込みました{:.0}", "Imported {n} preset{}, {f} file{} not readable": "{n}件のプリセットを読み込みました{:.0}。{f}件は読み込めません{:.0}", @@ -99,7 +102,7 @@ "{n} photo{}": "{n}枚{:.0}", "{n} photo{} match · updates automatically as photos change": "{n}枚が一致{:.0}・写真の変更に応じて自動更新", "{n} photo{} now · updates automatically as photos change": "現在{n}枚{:.0}・写真の変更に応じて自動更新", - "{n} selected photos · {pages} pages": "選択した写真 {n} 枚 · {pages} ページ", + "{n} selected photo{} · {pages} page{}": "選択した写真 {n} 枚 · {pages} ページ{:.0}{:.0}", "{sel_n} selected · {counted}": "{sel_n}枚選択・{counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", "{what} merge added": "{what}合成を追加しました", @@ -135,6 +138,7 @@ "Label Set: {name}": "ラベルセット:{name}", "Quick Develop: {name}": "クイック現像: {name}", "Reset {name}": "{name}をリセット", + "{name} value": "{name}の値", "Updated “{name}”": "「{name}」を更新しました", "{month}": "{month}月", "{month} {year}": "{year}年{month}月", @@ -156,7 +160,7 @@ "Auto Import: added {} photo{}": "自動読み込み:{}枚の写真を追加しました{:.0}", "Building previews for {} photos…": "{}枚のプレビューを作成中…", "Couldn't open the editor: {e}": "エディターを開けませんでした:{e}", - "Creates {} stacks from {} of {scope}": "{scope}の{1}枚から{0}個のスタックを作成します", + "Creates {stacks} stack{} from {photos} of {scope}": "{scope}の{photos}枚から{stacks}個のスタックを作成します{:.0}", "Done ({what}): {done} photo{plural}": "完了({what}):{done}枚{plural:.0}", "Focus {:.0}": "ピント {:.0}", "Folder “{}” (and its subfolders)": "フォルダ「{}」(サブフォルダを含む)", @@ -231,6 +235,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "「{parent}」にはすでに「{name}」があります。統合しますか?", "There is a “{name}” at the top level already. Merge the two?": "最上位にはすでに「{name}」があります。統合しますか?", "Added “{keyword}” to {n} photo{}": "写真{n}枚に「{keyword}」を追加しました{:.0}", + "Add Keyword “{keywords}”": "キーワード「{keywords}」を追加", "On {have} of {of} selected photos": "選択した写真{of}枚のうち{have}枚", "Remove “{name}”": "「{name}」を削除", "There is a keyword set “{name}” already": "キーワードセット「{name}」はすでにあります", @@ -252,6 +257,7 @@ "{what} merge cancelled": "{what}合成をキャンセルしました", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "ローカル写真{n}枚をスキップしました{0:.0}:アルバムに入れられるのはライブラリの写真です(先にマイフォトに追加してください)", "New Folder in “{name}”": "「{name}」に新規フォルダ", + "Created folder “{name}” in “{parent}”": "「{parent}」にフォルダ「{name}」を作成しました", "Moved {} photo(s)": "{} 枚の写真を移動しました", "not added to Apple Photos: {e}": "Appleの写真に追加されませんでした:{e}", "{n} added to Apple Photos album “{album}”": "{n}件をAppleの写真のアルバム「{album}」に追加しました", @@ -273,6 +279,7 @@ "{n} originals opened in the other editor": "{n}個の元ファイルを別のエディタで開きました", "· {in_source} identical copies": "・同一のコピー {in_source} 件", "{count} more warnings.": "ほかに{count}件の警告があります。", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "カタログの写真 {in_trash} 枚は、このライブラリの「最近削除した写真」にあり、そのまま残ります。表示するには「最近削除した写真」から復元してください。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "カタログ内のレコードが不完全なため、{skipped}件の画像を読み込めませんでした。", "{photos} catalog records processed; {collections} collections.": "カタログの{photos}件のレコードを処理しました。コレクションは{collections}件です。", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing}件のオリジナルが見つかりません。カタログのレコードは利用できます。「見つからない写真を検索」で再リンクしてください。", @@ -285,7 +292,7 @@ "Skipped {problem}": "スキップ: {problem}", "…and {more} more": "…ほか {more} 件", "Template preview: {name}": "テンプレートのプレビュー: {name}", - "{n} photos in view · {slides} slides · {time}": "表示中の写真 {n} 枚 · スライド {slides} 枚 · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "表示中の写真 {n} 枚 · スライド {slides} 枚 · {time}{:.0}{:.0}", "{n} pages": "{n} ページ", "{n} JPEG files": "JPEG ファイル {n} 個", "{s} s of AV1 video": "AV1 ビデオ {s} 秒", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "{name} を読み取れませんでした: {e}", "Added {n} photo{}": "{n}枚を追加しました{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", - "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}", + "Photo: {name}": "写真: {name}", + "Panel layout could not be restored: {error}": "パネル配置を復元できませんでした:{error}", + "Panel move was not applied: {error}": "パネルの移動は適用されませんでした:{error}", + "{name} is installed": "{name} をインストールしました", + "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd..5f80d7896b 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -43,6 +43,7 @@ "Add to Local": "ローカルに追加", "Add to My Photos": "マイフォトに追加", "Can't be moved here": "ここには移動できません", + "Import photos with File → Import Photos…, or drop them here": "「ファイル → 写真を読み込む…」から読み込むか、ここに写真をドロップしてください", "This row covers more than one disk: drop on a folder inside it": "この行は複数のディスクにまたがっています。中のフォルダにドロップしてください", "Local photos aren't in the library yet: Add to My Photos first, then move them": "ローカルの写真はまだライブラリにありません。先に「マイフォトに追加」してから移動してください", "Add to Selected Photos": "選択した写真に追加", @@ -120,6 +121,7 @@ "Auto-Tag Photos from Tracklog": "GPS軌跡から写真に位置情報を自動で付ける", "Auto-Tag from Tracklog": "GPS軌跡から位置情報を付ける", "Auto-Tag from Tracklog…": "GPS軌跡から位置情報を付ける…", + "Add Locations": "位置情報を追加", "Automatic": "自動", "Automatically Write Changes into XMP": "変更をXMPに自動保存", "Automatically write changes into XMP sidecars": "変更をXMPサイドカーファイルに自動保存", @@ -324,6 +326,9 @@ "Crop, Rotate, Geometry": "切り抜き・回転・ジオメトリ", "Cross Process": "クロスプロセス", "Culling": "写真の選別", + "Cull": "選別", + "Create Stacks": "スタックを作成", + "Change Time": "時刻を変更", "Curve": "カーブ", "Custom": "カスタム", "Custom template…": "カスタムテンプレート…", @@ -436,6 +441,7 @@ "Effects": "効果", "Empty Recently Deleted": "最近削除した写真を空にする", "Enable Lens Corrections": "レンズ補正を有効にする", + "Enable Painting": "キーワード付けを有効にする", "Enable Profile Corrections": "プロファイル補正を使用", "End Interaction": "操作を終了", "English": "English", @@ -472,6 +478,7 @@ "Faded Matte": "フェードマット", "Faded Slide": "フェードスライド", "Faded Urban": "フェードアーバン", + "Favorite": "お気に入り", "Favorite Preset": "プリセットをお気に入りに追加", "Favorite Profile": "プロファイルをお気に入りに追加", "Favorites": "お気に入り", @@ -835,7 +842,6 @@ "Import Profiles & Presets…": "プロファイルとプリセットを読み込む…", "Import from Device": "デバイスから読み込む", "Import from Folder…": "フォルダから読み込む…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "「ファイル → 写真を読み込む…」(⌘⇧I)から読み込むか、ここに写真をドロップしてください", "Imported Photos": "写真を読み込み", "Importing": "読み込み中", "Importing scans the source for photos; it doesn't add the folder to Local (use Local → Browse Folder… to work in a folder without importing).": "読み込みでは写真を検索しますが、フォルダはローカルに追加されません。読み込まずに作業する場合は「ローカル → フォルダを参照…」を使ってください", @@ -863,6 +869,7 @@ "Keyword Sets": "キーワードセット", "Keyword Suggestions": "キーワード候補", "Keyword to paint": "写真に付けるキーワード", + "Type a keyword to paint in the Keywords panel": "キーワードパネルで写真に付けるキーワードを入力してください", "Keywords": "キーワード", "Keywords you add appear here; ⌥1–⌥9 apply them.": "追加したキーワードはここに表示されます(⌥1〜⌥9で適用)", "Landscape": "風景", @@ -1397,6 +1404,7 @@ "Table": "表", "Tags": "タグ", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "テンプレート横の「タグ」を参照してください。ファイルとXMPの名前を変更し、同名の場合は-1、-2…を付けます", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "「タグ」ボタンで、{date} や {seq} などテンプレートに使えるタグの一覧を表示します。各ファイルは XMP ファイルとともにディスク上で名前が変更され、同名のものには -1、-2… が付きます", "Targeted Adjustment": "ターゲット調整", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "写真の上を上下にドラッグして、その部分の色を調整", "Targeted adjustment: drag up/down on the photo to adjust the curve there": "写真の上を上下にドラッグして、その部分のカーブを調整", @@ -1634,6 +1642,9 @@ "Your library couldn't be opened": "ライブラリを開けませんでした", "LightCraft couldn't find where to keep your library.": "ライブラリの保存場所が見つかりませんでした。", "LightCraft couldn't open the library at": "次の場所にあるライブラリを開けませんでした:", + "There is no LightCraft library in this folder any more.": "このフォルダーには LightCraft ライブラリがもうありません。", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "ライブラリが見つかりません。移動されたか名前が変更されたか、ドライブまたはネットワーク共有が接続されていません。", + "This folder can't be read:": "このフォルダーを読み取れません:", "Try Again": "再試行", "Choose Another Library…": "別のライブラリを選択…", "Continue Without Saving": "保存せずに続行", @@ -1659,7 +1670,6 @@ "Moves the photos imported from this folder to Recently Deleted; no file is touched": "このフォルダから読み込んだ写真を「最近削除した写真」に移動します。ファイルには手を加えません", "Remove Disk from Library…": "ディスクをライブラリから除去…", "Moves every photo imported from this disk to Recently Deleted; no file is touched": "このディスクから読み込んだすべての写真を「最近削除した写真」に移動します。ファイルには手を加えません", - "Collapse": "折りたたむ", "Expand": "展開", "Remove Disk from Library": "ディスクをライブラリから除去", "All the photos imported from this disk are included.": "このディスクから読み込んだすべての写真が対象です", @@ -1717,6 +1727,7 @@ "Denoise Settings": "ノイズ除去の設定", "Denoise all photos with an Amount": "適用量のあるすべての写真のノイズを除去", "Downloaded and checked. Installing…": "ダウンロードして確認しました。インストール中…", + "The download failed": "ダウンロードに失敗しました。", "Failed its last test": "前回のテストに失敗", "Graphics card": "グラフィックカード", "I have read these terms and accept them for my own use": "この条件を読み、自分の使用のために同意します", @@ -1882,6 +1893,12 @@ "No photo has it; the keywords below it go too.": "このキーワードを持つ写真はありません。下位のキーワードも削除されます。", "Edit Keyword Tag…": "キーワードタグを編集…", "Put New Keywords Inside This Keyword": "新しいキーワードをこのキーワードの中に入れる", + "Use This as Keyword Shortcut": "キーワードショートカットとして使用", + "Set Keyword Shortcut": "キーワードショートカットを設定", + "Set Keyword Shortcut…": "キーワードショートカットを設定…", + "Add or Remove Keyword Shortcut": "キーワードショートカットを付け外し", + "Keyword Shortcut": "キーワードショートカット", + "Part of the keyword shortcut": "キーワードショートカットに含まれています", "Purge Unused Keywords": "使用されていないキーワードを削除", "Delete Keyword…": "キーワードを削除…", "Drop here for the top level": "ここにドロップすると最上位に移動", @@ -1893,6 +1910,7 @@ "& Containing": "と親キーワード", "Edit Set…": "セットを編集…", "Edit Keyword Set": "キーワードセットを編集", + "Edit Keywords": "キーワードを編集", "Keywords (⌥1–⌥9)": "キーワード (⌥1–⌥9)", "A keyword set needs a name": "キーワードセットには名前が必要です", "Save as a new set": "新しいセットとして保存", @@ -2355,6 +2373,20 @@ "Dropped Files": "ドロップしたファイル", "Import dropped files without review": "ドロップしたファイルを確認せずに読み込む", "An import is running": "読み込み中です", + "The photos are imported once it ends": "終わりしだい写真を読み込みます", "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", - "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください" + "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", + "Thumbnail size": "サムネイルのサイズ", + "Import Thumbnail Size": "読み込みサムネイルのサイズ", + "Face recognition is on": "顔認識をオンにしました", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "顔認識はオフです。オンにすると、名前の候補が表示され、似た顔をまとめて見られます。", + "Turn on": "オンにする", + "Set up face recognition": "顔認識を設定", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "顔認識で名前の候補を表示するにはモデルが必要です。設定から一度だけダウンロードします。", + "Turn on name suggestions": "名前の候補をオンにする", + "Set up name suggestions…": "名前の候補を設定…", + "Top bar": "上部バー", + "Tool strip": "ツールバー", + "Bottom bar": "下部バー", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 4603682618..329662ac1b 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -33,6 +33,7 @@ "Added {n} photo{} to “{}”": "„{1}“-ს დაემატა ფოტო: {n}{0:.0}", "Added {what} to {name}": "{what}: დაემატა {name}-ს", "Added “{keyword}” to {n} photo{}": "„{keyword}“ დაემატა ფოტოს: {n}{:.0}", + "Add Keyword “{keywords}”": "საკვანძო სიტყვის „{keywords}“ დამატება", "Adding photos… {} of {}": "ფოტოების დამატება… {} / {}", "All {n} selected photos move by the same amount.": "მონიშნული ფოტოები ({n}) ერთი და იმავე სიდიდით გადაინაცვლებს.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "უკვე ბიბლიოთეკაშია, ახლახან წაშლილებში: მონიშნულია ფოტო: {}{:.0} · მარჯვენა დაწკაპუნება → აღდგენა, ან სამუდამოდ წაშლა თავიდან იმპორტისთვის", @@ -46,10 +47,12 @@ "Build Standard-Sized Previews ({scope})": "სტანდარტული ზომის წინასწარი ხედების შექმნა ({scope})", "Building previews for {} photos…": "იქმნება წინასწარი ხედები ფოტოებისთვის: {}…", "Click {}:1": "დაწკაპუნება {}:1", + "Collapse {name}": "ჩაკეცვა: {name}", "Couldn't open the editor: {e}": "რედაქტორი ვერ გაიხსნა: {e}", "Create Keyword Tag Inside “{name}”…": "საკვანძო სიტყვის შექმნა „{name}“-ში…", "Create {n} Virtual Copies": "ვირტუალური ასლების შექმნა: {n}", "Creates {} stacks from {} of {scope}": "შეიქმნება დასტა: {} — {}-დან ({scope})", + "Creates {stacks} stack{} from {photos} of {scope}": "შეიქმნება დასტა: {stacks} — {photos}-დან ({scope}){:.0}", "Decoder: {reason}": "დეკოდერი: {reason}", "Delete \"{label}\"": "„{label}“-ის წაშლა", "Delete \"{label}\" (and the mask)": "„{label}“-ის წაშლა (ნიღაბთან ერთად)", @@ -62,6 +65,7 @@ "Downloads from {host}. Once it has arrived and checked out, LightCraft installs it, {after}.": "ჩამოიტვირთება {host}-დან. მიღებისა და შემოწმების შემდეგ LightCraft მას დააყენებს, {after}.", "Duplicate \"{label}\"": "„{label}“-ის დუბლირება", "Example: {example}": "მაგალითი: {example}", + "Expand {name}": "გაშლა: {name}", "Exported {n} keyword{}": "ექსპორტირებულია საკვანძო სიტყვა: {n}{:.0}", "Exported {n} photo{}": "ექსპორტირებულია ფოტო: {n}{:.0}", "Exported {ok} of {total} photo{}": "ექსპორტირებულია ფოტო: {ok} / {total}{:.0}", @@ -76,6 +80,7 @@ "Healed {n} dust spot{}": "აღდგენილია მტვრის ლაქა: {n}{:.0}", "Import cancelled · {} photo{} added": "იმპორტი გაუქმდა · დაემატა ფოტო: {}{:.0}", "Import failed: {e}": "იმპორტი ვერ მოხერხდა: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "ფოტოების იმპორტისთვის გამოიყენეთ ფაილი → ფოტოების იმპორტი… ({}), ან ჩააგდეთ ისინი აქ", "Import warnings ({n}):\n{warnings}": "იმპორტის გაფრთხილებები ({n}):\n{warnings}", "Imported {n} point curve preset{}": "იმპორტირებულია წერტილოვანი მრუდის პრესეტი: {n}{:.0}", "Imported {n} preset{}": "იმპორტირებულია პრესეტი: {n}{:.0}", @@ -108,6 +113,7 @@ "Moved; {} photo(s) relinked": "გადატანილია; ხელახლა დაკავშირდა ფოტო: {}", "Named ({named_n})": "სახელიანი ({named_n})", "New Folder in “{name}”": "ახალი საქაღალდე „{name}“-ში", + "Created folder “{name}” in “{parent}”": "საქაღალდე „{name}“ შეიქმნა „{parent}“-ში", "On {have} of {of} selected photos": "{of} მონიშნული ფოტოდან {have}-ზე", "Painting “{k}”: click photos to add or remove it · Esc stops": "„{k}“-ის მინიჭება: დაწკაპეთ ფოტოებზე მის დასამატებლად ან მოსახსნელად · Esc ასრულებს", "Paste into {n} photo{} — only settings that were copied are pasted": "ჩასმა ფოტოებში: {n}{:.0} — ჩაისმება მხოლოდ კოპირებული პარამეტრები", @@ -137,6 +143,7 @@ "Rendering on the CPU: {why}": "რენდერი CPU-ზე: {why}", "Replace {} with:": "{}-ის ჩანაცვლება:", "Reset {name}": "ჩამოყრა: {name}", + "{name} value": "{name}: მნიშვნელობა", "Reset {} Channel": "არხის ჩამოყრა: {}", "Restore {}": "აღდგენა: {}", "Restore {} Photo{}": "ფოტოს აღდგენა: {}{:.0}", @@ -248,62 +255,70 @@ "“{parent}” has a “{name}” already. Merge the two?": "„{parent}“-ში „{name}“ უკვე არსებობს. გაერთიანდეს ორივე?", "• {assumption}": "• {assumption}", "… and {more} more": "… და კიდევ {more}", - " in {g} group{}": " in {g} group{}", - " · kept, not applied: {}": " · kept, not applied: {}", - " · {n} skipped (could not be rendered)": " · {n} skipped (could not be rendered)", - " — kept but not applied: {}": " — kept but not applied: {}", - "Applied {name}": "Applied {name}", - "Apply to “{mask}” on Selected Photos": "Apply to “{mask}” on Selected Photos", - "Create the keyword “{name}”": "Create the keyword “{name}”", - "Delete the effect preset “{name}”?": "Delete the effect preset “{name}”?", - "Delete these {n} effect presets?": "Delete these {n} effect presets?", - "Delete {n} effect preset{}? This can't be undone.": "Delete {n} effect preset{}? This can't be undone.", - "Delete “{name}”?": "Delete “{name}”?", - "Effect: {name}": "Effect: {name}", - "Exported to {path}": "Exported to {path}", - "Exported {} effect preset{}": "Exported {} effect preset{}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", - "Imported {name}": "Imported {name}", - "Keywords of {n} selected photos": "Keywords of {n} selected photos", - "LightCraft stopped unexpectedly: {e}": "LightCraft stopped unexpectedly: {e}", - "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + " in {g} group{}": " · ჯგუფი: {g}{:.0}", + " · kept, not applied: {}": " · შენახულია, არ გამოყენებულა: {}", + " · {n} skipped (could not be rendered)": " · გამოტოვებულია: {n} (ვერ დარენდერდა)", + " — kept but not applied: {}": " — შენახულია, მაგრამ არ გამოყენებულა: {}", + "Applied {name}": "გამოყენებულია: {name}", + "Apply to “{mask}” on Selected Photos": "მონიშნულ ფოტოებზე „{mask}“-ზე გამოყენება", + "Create the keyword “{name}”": "საკვანძო სიტყვის „{name}“ შექმნა", + "Delete the effect preset “{name}”?": "წაიშალოს ეფექტის პრესეტი „{name}“?", + "Delete these {n} effect presets?": "წაიშალოს ეს ეფექტის პრესეტები ({n})?", + "Delete {n} effect preset{}? This can't be undone.": "წაიშალოს ეფექტის პრესეტები ({n}){:.0}? ამის დაბრუნება შეუძლებელია.", + "Delete “{name}”?": "წაიშალოს „{name}“?", + "Effect: {name}": "ეფექტი: {name}", + "Exported to {path}": "ექსპორტირებულია: {path}", + "Exported {} effect preset{}": "ექსპორტირებულია ეფექტის პრესეტი: {}{:.0}", + "Imported {e} mask effect{} (Masking ▸ Effect)": "იმპორტირებულია ნიღბის ეფექტი: {e}{:.0} (ნიღბვა → ეფექტი)", + "Imported {name}": "იმპორტირებულია: {name}", + "Keywords of {n} selected photos": "მონიშნული ფოტოების ({n}) საკვანძო სიტყვები", + "LightCraft stopped unexpectedly: {e}": "LightCraft მოულოდნელად შეწყდა: {e}", + "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft მოულოდნელად შეწყდა: {e}\n\nდეტალები ჟურნალის ფაილშია: {path}", + "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "„{name}“ მოშორდა ფოტოებს ({n}). რედაქტირება → დაბრუნება მას უკან აბრუნებს.", "Inside: {names}": "შიგნით: {names}", - "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", - "Saved template {name}": "Saved template {name}", - "Skipped {problem}": "Skipped {problem}", - "Slideshow exported: {what}": "Slideshow exported: {what}", - "Template preview: {name}": "Template preview: {name}", - "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.", - "Update “{name}” with Current Settings": "Update “{name}” with Current Settings", - "Updated {name}": "Updated {name}", - "new, inside {parent}": "new, inside {parent}", - "{count} more warnings.": "{count} more warnings.", + "Renames {n} face{} across the library. The files are not changed.": "სახეებს ({n}){:.0} მთელ ბიბლიოთეკაში ეცვლება სახელი. ფაილები არ იცვლება.", + "Saved template {name}": "შაბლონი შენახულია: {name}", + "Skipped {problem}": "გამოტოვებულია: {problem}", + "Slideshow exported: {what}": "სლაიდშოუ ექსპორტირებულია: {what}", + "Template preview: {name}": "შაბლონის გადახედვა: {name}", + "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "ფოტოების ({n}) XMP თანმხლები ფაილები ვერ ჩაიწერა (მათი საქაღალდე მიუწვდომელია?). LightCraft ცდას აგრძელებს.", + "Update “{name}” with Current Settings": "„{name}“-ის განახლება მიმდინარე პარამეტრებით", + "Updated {name}": "განახლდა: {name}", + "new, inside {parent}": "ახალი, {parent}-ის შიგნით", + "{count} more warnings.": "კიდევ გაფრთხილება: {count}.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "კატალოგის ფოტოები ამ ბიბლიოთეკის ახლახან წაშლილებში: {in_trash}. ისინი იქ რჩება; სანახავად აღადგინეთ ისინი ახლახან წაშლილებიდან.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "კატალოგის {skipped} სურათი არ დაიმპორტდა, რადგან მათი ჩანაწერები კატალოგში არასრულია.", - "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.", - "{n} JPEG files": "{n} JPEG files", - "{n} pages": "{n} pages", - "{n} photos in view · {slides} slides · {time}": "{n} photos in view · {slides} slides · {time}", - "{n} preset{}": "{n} preset{}", - "{n} raws can now be developed from their raw data": "{n} raws can now be developed from their raw data", - "{photos} catalog records processed; {collections} collections.": "{photos} catalog records processed; {collections} collections.", - "{s} s of AV1 video": "{s} s of AV1 video", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})", - "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has", - "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” is already a person. Combining them makes one person; Undo separates them again.", - "…and {more} more": "…and {more} more", - "Color space: Rec. 2020 {curve} (HDR AVIF)": "Color space: Rec. 2020 {curve} (HDR AVIF)", - "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", - "Already in “{}”": "Already in “{}”", - "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", - "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", + "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "დაკარგულია ორიგინალი: {missing}. მათი კატალოგის ჩანაწერები ხელმისაწვდომია; ხელახლა დასაკავშირებლად გამოიყენეთ „დაკარგული ფოტოების მოძებნა“.", + "{n} JPEG files": "JPEG ფაილი: {n}", + "{n} pages": "გვერდი: {n}", + "{n} photos in view · {slides} slides · {time}": "ფოტო ხედში: {n} · სლაიდი: {slides} · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "ფოტო ხედში: {n} · სლაიდი: {slides} · {time}{:.0}{:.0}", + "{n} preset{}": "პრესეტი: {n}{:.0}", + "{n} raws can now be developed from their raw data": "RAW ფაილების ({n}) დამუშავება ახლა მათი RAW მონაცემებიდან შეიძლება", + "{photos} catalog records processed; {collections} collections.": "დამუშავდა კატალოგის ჩანაწერი: {photos}; კოლექცია: {collections}.", + "{s} s of AV1 video": "{s} წმ AV1 ვიდეო", + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}: გაერთიანება დაემატა {mp} ზომით, რაც პანორამის მაქსიმუმია (მისი სრული ზომაა {full})", + "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}: გაერთიანება დაემატა {mp} ზომით: მის სრულ ზომას, {full}, იმაზე მეტი მეხსიერება სჭირდება, ვიდრე ამ კომპიუტერს აქვს", + "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "„{to}“ უკვე ადამიანია. მათი გაერთიანება ერთ ადამიანს ქმნის; დაბრუნება მათ ისევ გაყოფს.", + "…and {more} more": "…და კიდევ {more}", + "Color space: Rec. 2020 {curve} (HDR AVIF)": "ფერთა სივრცე: Rec. 2020 {curve} (HDR AVIF)", + "{n} selected photos · {pages} pages": "მონიშნული ფოტო: {n} · გვერდი: {pages}", + "{n} selected photo{} · {pages} page{}": "არჩეული ფოტო: {n} · გვერდი: {pages}{:.0}{:.0}", + "Already in “{}”": "უკვე „{}“-შია", + "Move {n} photo{} to “{}”": "ფოტოს გადატანა „{1}“-ში: {n}{0:.0}", + "Move {n} photo{} to “{}”?": "გადავიდეს „{1}“-ში ფოტო: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "„{1}“-ში გადავიდა ფოტო: {n}{0:.0}. რედაქტირება → დაბრუნება მათ უკან აბრუნებს.", "Drop to review {n} item{} for import": "ჩააგდეთ იმპორტამდე გადასახედად (ელემენტები: {n}){:.0}", "Drop to import {n} item{}": "ჩააგდეთ იმპორტისთვის (ელემენტები: {n}){:.0}", "Drop to import {n} preset{}": "ჩააგდეთ პრესეტების იმპორტისთვის: {n}{:.0}", "Could not read {name}: {e}": "ვერ წაიკითხა {name}: {e}", "Added {n} photo{}": "დაემატა ფოტო: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}", + "Photo: {name}": "ფოტო: {name}", + "Panel layout could not be restored: {error}": "პანელების განლაგების აღდგენა ვერ მოხერხდა: {error}", + "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", + "{name} is installed": "{name} დაინსტალირებულია", + "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 32c4077001..0ea7d3d805 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -229,6 +229,7 @@ "Auto-Tag from Tracklog": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან", "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან: GPS მდებარეობები თქვენი ფოტოებისთვის GPX მარშრუტის ჟურნალიდან, გადაღების დროის მიხედვით.", "Auto-Tag from Tracklog…": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან…", + "Add Locations": "მდებარეობების დამატება", "Automatic": "ავტომატური", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "ავტომატური რეჟიმი დეტალურ ხედს ასახავს იმ ზომით, რომლითაც ის ჩანს, ფოტოს საკუთარ პიქსელებამდე. ზღვრისთვის აირჩიეთ ზომა: პატარა უფრო სწრაფია.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "ავტომატური რეჟიმი იყენებს ვიდეობარათს, როცა ის პროცესორზე სწრაფია: ორივეს დრო ამ კომპიუტერზე იზომება, როცა ფოტო პირველად მზადდება.", @@ -262,7 +263,7 @@ "Black & White": "შავ-თეთრი", "Blacks": "შავები", "Bleach Bypass": "გაუთეთრებელი დამუშავება", - "Bleached": "გაუფერულებული", + "Bleached": "გახუნებული", "Blending": "შერევა", "Blown highlights in CR2 files from the Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),": "გადაჭარბებით განათებული ღია ტონები Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),", "Blue": "ლურჯი", @@ -403,7 +404,6 @@ "Closing a library releases its lock explicitly (issue #680). On Linux and macOS the lock used to go with the file": "ბიბლიოთეკის დახურვა მის ბლოკს ცხადად ათავისუფლებს (ხარვეზი #680). Linux-სა და macOS-ზე ბლოკი ადრე ფაილის", "Cloudy": "მოღრუბლული", "Cmd+Shift+R, keeps the photo and clears its edits.)": "Cmd+Shift+R, ფოტოს ინარჩუნებს და მის ცვლილებებს აუქმებს.)", - "Collapse": "ჩაკეცვა", "Collapse All Stacks": "ყველა დასტის ჩაკეცვა", "Collapse Stack": "დასტის ჩაკეცვა", "Color": "ფერი", @@ -507,6 +507,9 @@ "Cropped": "ჩამოჭრილი", "Cross Process": "ჯვარედინი დამუშავება", "Culling": "გადარჩევა", + "Cull": "გადარჩევა", + "Create Stacks": "დასტების შექმნა", + "Change Time": "დროის შეცვლა", "Culling.": "გადარჩევა.", "Curve": "მრუდი", "Custom": "მორგებული", @@ -587,7 +590,7 @@ "Description": "აღწერა", "Deselect": "მონიშვნის მოხსნა", "Deselect All": "ყველა მონიშვნის მოხსნა", - "Desert Heat": "უდაბნოს პაპანაქება", + "Desert Heat": "უდაბნოს ხვატი", "Desert Warmth": "უდაბნოს სითბო", "Desktop": "სამუშაო მაგიდა", "Detail": "დეტალი", @@ -621,6 +624,7 @@ "Download Place Names (GeoNames)": "ადგილების სახელების ჩამოტვირთვა (GeoNames)", "Download the SAM 3 Model?": "ჩამოიტვირთოს SAM 3 მოდელი?", "Downloaded and checked. Installing…": "ჩამოტვირთულია და შემოწმებულია. ინსტალირდება…", + "The download failed": "ჩამოტვირთვა ვერ მოხერხდა", "Downloading model": "მოდელი იტვირთება", "Downloading place names": "ადგილების სახელები იტვირთება", "Downloads": "ჩამოტვირთვები", @@ -656,6 +660,7 @@ "Edit Info": "ინფორმაციის რედაქტირება", "Edit Keyword": "საკვანძო სიტყვის რედაქტირება", "Edit Keyword Set": "საკვანძო სიტყვების ნაკრების რედაქტირება", + "Edit Keywords": "საკვანძო სიტყვების რედაქტირება", "Edit Keyword Tag": "საკვანძო სიტყვის რედაქტირება", "Edit Keyword Tag…": "საკვანძო სიტყვის რედაქტირება…", "Edit Label Names": "იარლიყების სახელების რედაქტირება", @@ -682,6 +687,7 @@ "Effects": "ეფექტები", "Empty Recently Deleted": "ახლახან წაშლილის გასუფთავება", "Enable Lens Corrections": "ობიექტივის კორექციების ჩართვა", + "Enable Painting": "ფუნჯის ჩართვა", "Enable Profile Corrections": "პროფილის კორექციების ჩართვა", "End Interaction": "ურთიერთქმედების დასრულება", "English": "English", @@ -743,7 +749,7 @@ "Faces": "სახეები", "Faces of a Person": "ადამიანის სახეები", "Faded Matte": "გაცრეცილი მატი", - "Faded Slide": "გაცრეცილი სლაიდი", + "Faded Slide": "ძველი სლაიდი", "Faded Urban": "გაცრეცილი ქალაქი", "Failed": "ვერ მოხერხდა", "Failed its last test": "ბოლო შემოწმება ვერ გაიარა", @@ -850,7 +856,7 @@ "GPU Rendering": "GPU რენდერირება", "GPU rendering": "GPU რენდერირება", "General": "ზოგადი", - "Generated demo photo": "გენერირებული სადემონსტრაციო ფოტო", + "Generated demo photo": "სადემონსტრაციო ფოტო", "Geometry": "გეომეტრია", "Get Develop Settings": "დამუშავების პარამეტრების აღება", "Global Hue": "გლობალური ფერის ტონი", @@ -970,7 +976,7 @@ "Import from Device": "იმპორტი მოწყობილობიდან", "Import from Folder…": "იმპორტი საქაღალდიდან…", "Import new photos": "ახალი ფოტოების იმპორტი", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "ფოტოების იმპორტისთვის გამოიყენეთ ფაილი → ფოტოების იმპორტი… (Cmd+Shift+I), ან ჩააგდეთ ისინი აქ", + "Import photos with File → Import Photos…, or drop them here": "ფოტოების იმპორტისთვის გამოიყენეთ ფაილი → ფოტოების იმპორტი…, ან ჩააგდეთ ისინი აქ", "Import presets from other editors: XMP presets, classic `.lrtemplate` files, \"DNG presets\" from mobile apps and `.zip`": "პრესეტების იმპორტი სხვა რედაქტორებიდან: XMP პრესეტები, კლასიკური `.lrtemplate` ფაილები, მობილური აპების „DNG პრესეტები“ და `.zip`", "Import ▸ Copy verifies every copy, like Move (issue #96): each file is written as a new file, synced to disk and": "იმპორტი → კოპირება ყოველ ასლს ამოწმებს, ისევე როგორც გადატანა (ხარვეზი #96): ყოველი ფაილი ახალ ფაილად იწერება, დისკზე სინქრონიზდება და", "Import ▸ Move: photos go into the destination (with the same folders and renaming as Copy, e.g.": "იმპორტი → გადატანა: ფოტოები დანიშნულების ადგილას გადადის (იგივე საქაღალდეებითა და გადარქმევით, რაც კოპირებისას, მაგ.", @@ -1065,7 +1071,8 @@ "Keyword lists": "საკვანძო სიტყვების სიები", "Keyword sets": "საკვანძო სიტყვების ნაკრებები", "Keyword tag options decide what exported files carry: Include on Export, Export Containing Keywords, Export": "საკვანძო სიტყვის პარამეტრები განსაზღვრავს, რას შეიცავს ექსპორტირებული ფაილები: ექსპორტში ჩართვა, მშობელი საკვანძო სიტყვების ექსპორტი,", - "Keyword to paint": "მისანიჭებელი საკვანძო სიტყვა", + "Keyword to paint": "საკვანძო სიტყვა", + "Type a keyword to paint in the Keywords panel": "აკრიფეთ მისანიჭებელი საკვანძო სიტყვა პანელში „საკვანძო სიტყვები“", "Keywording box": "საკვანძო სიტყვების ველი", "Keywords": "საკვანძო სიტყვები", "Keywords & People": "საკვანძო სიტყვები და ადამიანები", @@ -1120,6 +1127,9 @@ "LightCraft could not start": "LightCraft ვერ გაეშვა", "LightCraft couldn't find where to keep your library.": "LightCraft-მა ვერ იპოვა, სად შეინახოს თქვენი ბიბლიოთეკა.", "LightCraft couldn't open the library at": "LightCraft-მა ვერ გახსნა ბიბლიოთეკა მისამართზე", + "There is no LightCraft library in this folder any more.": "ამ საქაღალდეში LightCraft-ის ბიბლიოთეკა აღარ არის.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "ბიბლიოთეკა აქ არ არის: ის გადაიტანეს ან გადაარქვეს სახელი, ან მისი დისკი ან ქსელური საქაღალდე არ არის მიერთებული.", + "This folder can't be read:": "ამ საქაღალდის წაკითხვა ვერ ხერხდება:", "LightCraft does not know this model, so it assumed:": "LightCraft-მა ეს მოდელი არ იცის, ამიტომ ივარაუდა:", "LightCraft no longer crashes at launch on Windows PCs whose Vulkan driver is broken (issue #136, e.g. some Intel UHD": "LightCraft აღარ ითიშება გაშვებისას Windows კომპიუტერებზე, რომელთა Vulkan დრაივერი გაუმართავია (ხარვეზი #136, მაგ. ზოგიერთი Intel UHD", "LightCraft on GitHub": "LightCraft GitHub-ზე", @@ -1235,9 +1245,9 @@ "Monday": "ორშაბათი", "Monitor profile": "მონიტორის პროფილი", "Monitor profiles": "მონიტორის პროფილები", - "Mono Red Filter": "მონოქრომული წითელი ფილტრი", - "Mono Rich": "მდიდარი მონოქრომი", - "Mono Soft": "რბილი მონოქრომი", + "Mono Red Filter": "მონო, წითელი ფილტრი", + "Mono Rich": "მდიდარი მონო", + "Mono Soft": "რბილი მონო", "Monochrome": "მონოქრომული", "Month": "თვე", "Moody": "პირქუში", @@ -1462,7 +1472,7 @@ "Paste Settings from Previous": "წინა ფოტოს პარამეტრების ჩასმა", "Paste from Previous": "წინადან ჩასმა", "Paste pages": "გვერდების ჩასმა", - "Pastel Haze": "პასტელური ბურუსი", + "Pastel Haze": "პასტელის ნისლი", "Pending photo action cancelled": "ფოტოს მოლოდინში მყოფი მოქმედება გაუქმდა", "Pending photo action cancelled because its library or photo changed": "ფოტოს მოლოდინში მყოფი მოქმედება გაუქმდა, რადგან მისი ბიბლიოთეკა ან ფოტო შეიცვალა", "Pentax raws without black borders": "Pentax-ის RAW ფაილები შავი კიდეების გარეშე", @@ -1569,6 +1579,12 @@ "Purple Saturation": "იისფერის გაჯერება", "Put New Keywords Inside": "ახალი საკვანძო სიტყვების შიგნით მოთავსება", "Put New Keywords Inside This Keyword": "ახალი საკვანძო სიტყვების ამ საკვანძო სიტყვაში ჩასმა", + "Use This as Keyword Shortcut": "საკვანძო სიტყვების მალსახმობად გამოყენება", + "Set Keyword Shortcut": "საკვანძო სიტყვების მალსახმობის დაყენება", + "Set Keyword Shortcut…": "საკვანძო სიტყვების მალსახმობის დაყენება…", + "Add or Remove Keyword Shortcut": "საკვანძო სიტყვების მალსახმობის დამატება ან მოხსნა", + "Keyword Shortcut": "საკვანძო სიტყვების მალსახმობი", + "Part of the keyword shortcut": "საკვანძო სიტყვების მალსახმობის ნაწილი", "Put the locations you removed from Local back (no files change)": "ლოკალურიდან მოშორებული მდებარეობების დაბრუნება (ფაილები არ იცვლება)", "Quality": "ხარისხი", "Query Photos": "ფოტოების მოთხოვნა", @@ -1819,7 +1835,7 @@ "Search": "ძიება", "Search Photos": "ფოტოების ძიება", "Search albums": "ალბომების ძიება", - "Search commands or keys": "ბრძანებების ან კლავიშების ძიება", + "Search commands or keys": "ბრძანების ან კლავიშის ძიება", "Search…": "ძიება…", "Seasons": "სეზონები", "Second Window": "მეორე ფანჯარა", @@ -2062,12 +2078,13 @@ "Table": "ცხრილი", "Tags": "ტეგები", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "ტეგები: იხილეთ „ტეგები“ შაბლონის გვერდით. ფაილებს სახელი დისკზე ეცვლება (მათ XMP თანმხლებ ფაილებთან ერთად); არსებულ სახელებს ემატება -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "ღილაკი „ტეგები“ აჩვენებს შაბლონში გამოსაყენებელ ჩანაცვლებებს, მაგალითად {date} ან {seq}. თითოეულ ფაილს სახელი დისკზე ეცვლება მის XMP თანმხლებ ფაილთან ერთად; დაკავებულ სახელს ემატება -1, -2…", "Take a snapshot": "მომენტალური ასლის შექმნა", "Targeted Adjustment": "მიზნობრივი კორექცია", "Targeted adjustment on: drag up or down on the photo · Esc to stop": "მიზნობრივი კორექცია ჩართულია: გადაათრიეთ ფოტოზე ზემოთ ან ქვემოთ · Esc — შეწყვეტა", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "მიზნობრივი კორექცია: გადაათრიეთ ფოტოზე ზემოთ/ქვემოთ, რომ იქ ფერები შეცვალოთ", "Targeted adjustment: drag up/down on the photo to adjust the curve there": "მიზნობრივი კორექცია: გადაათრიეთ ფოტოზე ზემოთ/ქვემოთ, რომ იქ მრუდი შეცვალოთ", - "Teal & Amber": "ზღვისფერი და ქარვისფერი", + "Teal & Amber": "ზღვა და ქარვა", "Teal & Orange": "ზღვისფერი და ნარინჯისფერი", "Temp": "ტემპ.", "Temperature": "ტემპერატურა", @@ -2242,7 +2259,7 @@ "Waiting to start…": "დაწყების მოლოდინში…", "Warm Film": "თბილი ფირი", "Warm Glow": "თბილი ნათება", - "Warm Print": "თბილი ანაბეჭდი", + "Warm Print": "თბილი ფოტო", "Warm Table": "თბილი მაგიდა", "Watched folder": "თვალთვალის ქვეშ მყოფი საქაღალდე", "Watched-folder auto import; Convert to DNG; Duplicate; Build Standard / 1:1 / Smart Previews.": "ავტოიმპორტი თვალთვალის ქვეშ მყოფი საქაღალდიდან; DNG-ად გარდაქმნა; დუბლირება; სტანდარტული / 1:1 / ჭკვიანი წინასწარი ხედების შექმნა.", @@ -2733,6 +2750,914 @@ "Dropped Files": "ჩაგდებული ფაილები", "Import dropped files without review": "ჩაგდებული ფაილების იმპორტი გადახედვის გარეშე", "An import is running": "იმპორტი მიმდინარეობს", + "The photos are imported once it ends": "ფოტოები ამის შემდეგ შემოიტანება", "An import is running. Drop photos when it has finished": "იმპორტი მიმდინარეობს. ფოტოები ჩააგდეთ, როცა დასრულდება", - "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი" + "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი", + "(not in the library)": "(ბიბლიოთეკაში არ არის)", + "1 raw can now be developed from its raw data": "1 RAW ფაილის დამუშავება ახლა მისი RAW მონაცემებიდან შეიძლება", + "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · მიმდინარე ცვლილებები · ჩატევა ჩამოჭრის გარეშე", + "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "16:9 კადრი შავი ზოლებით ზემოთ და ქვემოთ, დასახელება კუთხეში, შავში გადასვლით მიქრობა და დასკვნითი ბარათი.", + "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "მუქი ფიქლისფერი ფონი; თითოეული ფოტოს ქვეშ ექსპოზიცია, ISO და ფოკუსური მანძილი, შემდეგ კამერა და ობიექტივი.", + "A face model uses the GPU only when a check shows it gives the same results faster.": "სახეების მოდელი GPU-ს მხოლოდ მაშინ იყენებს, როცა შემოწმება აჩვენებს, რომ ის იმავე შედეგს უფრო სწრაფად იძლევა.", + "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "ღია ნაცრისფერი კედელი თეთრი პასპარტუთი და რბილი ჩრდილით; ფოტოს ქვეშ წარწერა და შეფასება.", + "A pen's pressure sets the size and flow of the brush": "კალმის დაწოლა ფუნჯის ზომასა და ნაკადს განსაზღვრავს", + "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.": "AV1 ვიდეო: თითოეული სლაიდი თავისი ხანგრძლივობით და მიქრობებით. ხმის გარეშე: მუსიკის ექსპორტი ჯერ არ ხდება.", + "Add a model file…": "მოდელის ფაილის დამატება…", + "Add text overlay": "ტექსტური ზედდების დამატება", + "Already installed. Installing again is harmless.": "უკვე დაინსტალირებულია. ხელახლა დაინსტალირება არაფერს დააზიანებს.", + "Anchored to": "მიმაგრებულია", + "Animal Eye Tracking": "ცხოველის თვალის ტრეკინგი", + "Another library was opened since the photos were dropped: nothing was moved": "ფოტოების ჩაგდების შემდეგ სხვა ბიბლიოთეკა გაიხსნა: არაფერი გადატანილა", + "Aspect preview": "თანაფარდობის გადახედვა", + "Automatically show full screen": "სრულეკრანიან რეჟიმში ავტომატურად ჩვენება", + "Backdrop": "ფონი", + "Background colour": "ფონის ფერი", + "Background image": "ფონის გამოსახულება", + "Before the last template": "ბოლო შაბლონამდე", + "Bottom": "ქვედა", + "Built-in": "ჩაშენებული", + "CPU": "CPU", + "Can't be moved here": "აქ ვერ გადაიტანება", + "Cast shadow": "ჩრდილის დაცემა", + "Center": "ცენტრი", + "Checking raw files": "RAW ფაილები მოწმდება", + "Checking the GPU for faces": "GPU მოწმდება სახეებისთვის", + "Checking the GPU…": "GPU მოწმდება…", + "Choose a PDF destination after confirming. Print the PDF from your viewer.": "დადასტურების შემდეგ აირჩიეთ, სად შეინახოს PDF. PDF დაბეჭდეთ თქვენი სანახავი პროგრამიდან.", + "Cinema Wide": "ფართო კინო", + "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "დაწკაპეთ შაბლონზე მის გამოსაყენებლად; მიიტანეთ მაჩვენებელი მონიშნულ ფოტოზე მის გადასახედად. საკუთარ შაბლონზე მარჯვენა დაწკაპუნებით შეგიძლიათ მისი განახლება, სახელის შეცვლა, ექსპორტი ან წაშლა.", + "Click to name this face": "დაწკაპეთ ამ სახისთვის სახელის დასარქმევად", + "Click to type a value, drag to change it": "დააწკაპუნეთ მნიშვნელობის შესაყვანად, გადაათრიეთ მის შესაცვლელად", + "Color space: Rec. 2020 HLG (HDR AVIF)": "ფერთა სივრცე: Rec. 2020 HLG (HDR AVIF)", + "Color space: Rec. 2020 PQ (HDR AVIF)": "ფერთა სივრცე: Rec. 2020 PQ (HDR AVIF)", + "Color space: Rec. 2020 PQ (HDR JPEG XL)": "ფერთა სივრცე: Rec. 2020 PQ (HDR JPEG XL)", + "Color space: Rec. 2020 PQ, 16-bit (HDR PNG)": "ფერთა სივრცე: Rec. 2020 PQ, 16-ბიტიანი (HDR PNG)", + "Colour": "ფერი", + "Colour only": "მხოლოდ ფერი", + "Colour wash": "ფერადი შეღებვა", + "Confirm before moving photos to another folder on disk": "დისკზე ფოტოების სხვა საქაღალდეში გადატანამდე დადასტურება", + "Contact Sheet PDF": "საკონტაქტო ფურცელი PDF", + "Container": "კონტეინერი", + "Custom AF Area": "მორგებული AF არე", + "Destination library": "სამიზნე ბიბლიოთეკა", + "Detection": "აღმოჩენა", + "Don't ask again": "აღარ მკითხო", + "Duration": "ხანგრძლივობა", + "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "თითოეული ფოტო რაც შეიძლება დიდი, შავ ფონზე, მოკლე გადადნობით. ზემოდან არაფერია დახატული.", + "Edge to Edge": "კიდიდან კიდემდე", + "End": "დასასრული", + "Ending": "დასასრული", + "Ending screen": "დასკვნითი ეკრანი", + "Enter to confirm, Esc to cancel": "Enter — დადასტურება, Esc — გაუქმება", + "Every photo cropped to fill the whole screen, with slow crossfades.": "ყველა ფოტო ჩამოჭრილია მთელი ეკრანის შესავსებად, ნელი გადადნობებით.", + "Expanded Flexible Spot": "გაფართოებული მოქნილი წერტილი", + "Export JPEG…": "JPEG ექსპორტი…", + "Export PDF…": "PDF ექსპორტი…", + "Export Slideshow": "სლაიდშოუს ექსპორტი", + "Export Slideshow Template": "სლაიდშოუს შაბლონის ექსპორტი", + "Export Slideshow: folder for the JPEG files": "სლაიდშოუს ექსპორტი: საქაღალდე JPEG ფაილებისთვის", + "Export Slideshow…": "სლაიდშოუს ექსპორტი…", + "Export Video…": "ვიდეოს ექსპორტი…", + "Export to": "ექსპორტი ფორმატში", + "Exporting slideshow": "სლაიდშოუ ექსპორტირდება", + "Face Tracking": "სახის ტრეკინგი", + "Face tracking": "სახის ტრეკინგი", + "Filename captions": "ფაილის სახელი წარწერად", + "Flexible Spot": "მოქნილი წერტილი", + "Focus": "ფოკუსი", + "Focus point": "ფოკუსის წერტილი", + "Frame rate": "კადრების სიხშირე", + "Gallery Wall": "გალერეის კედელი", + "Grouped by parent": "ზედა საკვანძო სიტყვით დაჯგუფებული", + "Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened.": "დაჯგუფებული: ერთი და იმავე საკვანძო სიტყვის შიგნით მყოფი საკვანძო სიტყვები ერთ სტრიქონზეა მისი სახელით, გრძელი სიები და შეთავაზებები კი შემოკლებულია.", + "HDR TIFF needs 32-bit float.": "HDR TIFF-ს 32-ბიტიანი მცოცავი წერტილი სჭირდება.", + "HDR for Each Bracket Set": "HDR ექსპოზიციის თითოეული სერიისთვის", + "HDR output": "HDR გამოტანა", + "Hold View Until Refreshed": "ხედის შენარჩუნება განახლებამდე", + "Human Eye Tracking": "ადამიანის თვალის ტრეკინგი", + "Identity plate": "საფირმო ნიშანი", + "Import Slideshow Templates": "სლაიდშოუს შაბლონების იმპორტი", + "Import photos to get started": "დასაწყებად ფოტოების იმპორტი გააკეთეთ", + "Import…": "იმპორტი…", + "Intro": "შესავალი", + "Intro screen": "შესავალი ეკრანი", + "Keywords of the selection": "მონიშნულის საკვანძო სიტყვები", + "Layout": "განლაგება", + "Left": "მარცხენა", + "Letter": "წერილი", + "LightCraft stopped": "LightCraft შეწყდა", + "Lightroom Catalog Import": "Lightroom-ის კატალოგის იმპორტი", + "Lightroom catalogs import into the open library; no separate catalog folder is created.": "Lightroom-ის კატალოგების იმპორტი გახსნილ ბიბლიოთეკაში ხდება; კატალოგის ცალკე საქაღალდე არ იქმნება.", + "Link all margins": "ყველა ველის დაკავშირება", + "Local photos aren't in the library yet: Add to My Photos first, then move them": "ლოკალური ფოტოები ჯერ ბიბლიოთეკაში არ არის: ჯერ დაამატეთ „ჩემს ფოტოებში“, შემდეგ გადაიტანეთ", + "Lock On AF": "Lock On AF", + "Margins": "ველები", + "Margins are a share of the slide's shorter side, so slides look the same on any screen.": "ველები სლაიდის მოკლე გვერდის წილია, ამიტომ სლაიდები ნებისმიერ ეკრანზე ერთნაირად გამოიყურება.", + "Move Photos": "ფოტოების გადატანა", + "Multi": "მრავალწერტილოვანი", + "New template name": "შაბლონის სახელი", + "No lens data embedded in this file.": "ამ ფაილში ობიექტივის მონაცემები ჩაშენებული არ არის.", + "None yet: save the current settings as a template below.": "ჯერ არცერთი: შეინახეთ მიმდინარე პარამეტრები შაბლონად ქვემოთ.", + "Not loaded yet": "ჯერ არ ჩატვირთულა", + "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.": "დანომრილი JPEG ფაილები (name-001.jpg…) ახალ საქაღალდეში, რომლის სახელს შემდეგ ნაბიჯზე მიუთითებთ.", + "Offset": "წანაცვლება", + "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode.": "თითო სლაიდზე ერთი გვერდი (გრძელი გვერდი პიქსელებში = პუნქტებში), სლაიდის ხანგრძლივობით და მიქრობით სანახავი პროგრამის პრეზენტაციის რეჟიმისთვის.", + "Open Settings": "პარამეტრების გახსნა", + "Overlays": "ზედდებები", + "Override colour": "საკუთარი ფერი", + "Own duration (off: the slide duration)": "საკუთარი ხანგრძლივობა (გამორთული: სლაიდის ხანგრძლივობა)", + "Pen Pressure": "კალმის დაწოლა", + "PhotoCraft": "PhotoCraft", + "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "HDR-ში დამუშავებული ფოტოები: JPEG HDR gain map-ით (ყველგან სწორად ჩანს, HDR ეკრანებზე უფრო კაშკაშა ღია ტონებით), AVIF 10-ბიტიანად, PNG და JPEG XL 16-ბიტიან Rec. 2020 PQ-ად; TIFF-ს 32-ბიტიანი მცოცავი წერტილი სჭირდება", + "Photos you import show up here. Nothing is copied or moved unless you choose to.": "იმპორტირებული ფოტოები აქ გამოჩნდება. არაფერი კოპირდება ან გადაიტანება, თუ თქვენ არ აირჩევთ.", + "Plain Black": "უბრალო შავი", + "Playback": "დაკვრა", + "Previous settings": "წინა პარამეტრები", + "Rating stars": "შეფასების ვარსკვლავები", + "Read Focus Points": "ფოკუსის წერტილების წაკითხვა", + "Reading focus points": "ფოკუსის წერტილები იკითხება", + "Recognition": "ამოცნობა", + "Refresh View": "ხედის განახლება", + "Remove Folder Color Label": "საქაღალდის ფერადი იარლიყის მოშორება", + "Render behind image": "გამოსახულების უკან განთავსება", + "Reset all edits": "ყველა ცვლილების ჩამოყრა", + "Reset layout": "განლაგების ჩამოყრა", + "Return creates this keyword and gives it to the selected photos": "Return ქმნის ამ საკვანძო სიტყვას და მონიშნულ ფოტოებს ანიჭებს", + "Right": "მარჯვენა", + "Run face models on the CPU only": "სახეების მოდელების მხოლოდ CPU-ზე გაშვება", + "Same folder as original photo": "ორიგინალი ფოტოს საქაღალდე", + "Save as Template": "შაბლონად შენახვა", + "Select a photo to preview its slide": "მონიშნეთ ფოტო მისი სლაიდის გადასახედად", + "Select a photo, then turn this on to fill the slide behind every photo with it.": "მონიშნეთ ფოტო, შემდეგ ჩართეთ ეს, რომ მან ყველა ფოტოს უკან სლაიდი შეავსოს.", + "Select all": "ყველაფრის მონიშვნა", + "Select none": "მონიშვნის მოხსნა", + "Separate several keywords with commas. Return gives them to the selected photos.": "რამდენიმე საკვანძო სიტყვა მძიმეებით გამოყავით. Return მათ მონიშნულ ფოტოებს ანიჭებს.", + "Settings → Confirm before moving photos to another folder on disk turns it back on": "პარამეტრები → „დისკზე ფოტოების სხვა საქაღალდეში გადატანამდე დადასტურება“ ამას ხელახლა რთავს", + "Shooting Data": "გადაღების მონაცემები", + "Show Focus Point": "ფოკუსის წერტილის ჩვენება", + "Show every keyword of the selected photos": "მონიშნული ფოტოების ყველა საკვანძო სიტყვის ჩვენება", + "Show fewer": "ნაკლების ჩვენება", + "Show guides": "დამხმარე ხაზების ჩვენება", + "Show in Library": "ბიბლიოთეკაში ჩვენება", + "Show photos": "ფოტოების ჩვენება", + "Show the import review when a camera or card is connected": "კამერის ან ბარათის მიერთებისას იმპორტის განხილვის ჩვენება", + "Shows": "ჩვენება", + "Slide": "სლაიდი", + "Slides use the slideshow's layout, overlays and intro and ending screens, in view order.": "სლაიდები სლაიდშოუს განლაგებას, ზედდებებს და შესავალ და დასკვნით ეკრანებს იყენებს, ხედის რიგით.", + "Slideshow Templates": "სლაიდშოუს შაბლონები", + "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "სმარტ-ალბომები ავტომატურად ახლდება: შეცვალეთ მათი წესები ან გამოიყენეთ ფოტო → ფოტოს წაშლა", + "Solo Mode": "სოლო რეჟიმი", + "Specific folder": "კონკრეტული საქაღალდე", + "Spot": "წერტილოვანი", + "Stroke border": "კონტურის ჩარჩო", + "Templates": "შაბლონები", + "Text overlays": "ტექსტური ზედდებები", + "The ending screen, after the last photo.": "დასკვნითი ეკრანი, ბოლო ფოტოს შემდეგ.", + "The export watermark, drawn on the photo and sized relative to it.": "ექსპორტის ჭვირნიშანი, ფოტოზე დახატული და მის მიმართ ზომაშერჩეული.", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "შესავალი ერთხელ ეშვება პირველ ფოტომდე; დასასრული — ბოლო ფოტოს შემდეგ, როცა გამეორება გამორთულია. საფირმო ნიშანი ის არის, რაც „ზედდებებში“ არის მითითებული. ტიტრები სლაიდებივით მიქრება და შემთხვევითი რიგი მათ არასოდეს გადაადგილებს.", + "The intro screen, before the first photo.": "შესავალი ეკრანი, პირველ ფოტომდე.", + "The photos in view as slides, with the settings above. Progress shows in the activity stack.": "ხედში მყოფი ფოტოები სლაიდებად, ზემოთ მოცემული პარამეტრებით. პროგრესი აქტივობების დასტაში ჩანს.", + "The selected photo as a slide. Playback fills the screen; the aspect preview only changes this preview.": "მონიშნული ფოტო სლაიდად. დაკვრა ეკრანს ავსებს; თანაფარდობის გადახედვა მხოლოდ ამ გადახედვას ცვლის.", + "Their files and XMP sidecars move on disk. Edit → Undo moves them back.": "მათი ფაილები და XMP თანმხლები ფაილები დისკზე გადაიტანება. რედაქტირება → დაბრუნება მათ უკან აბრუნებს.", + "Their photos in the grid": "მათი ფოტოები ბადეში", + "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "ეს ფოტოები მხოლოდ მეხსიერებაშია. მათ შესანახად გახსენით ბიბლიოთეკა დისკზე და კატალოგის იმპორტი ხელახლა გააკეთეთ.", + "This raw is now developed from its raw data": "ეს RAW ფაილი ახლა მისი RAW მონაცემებიდან მუშავდება", + "This raw variant still can't be decoded": "RAW-ის ეს ვარიანტი ჯერ კიდევ ვერ დეკოდირდება", + "This row covers more than one disk: drop on a folder inside it": "ეს სტრიქონი ერთზე მეტ დისკს მოიცავს: ჩააგდეთ მის შიგნით მყოფ საქაღალდეზე", + "This screen is off: turn it on under Titles to play it.": "ეს ეკრანი გამორთულია: დასაკრავად ჩართეთ „ტიტრებში“.", + "Tidying the thumbnail cache": "ესკიზების ქეში სუფთავდება", + "Title text": "ტიტრის ტექსტი", + "Titles": "ტიტრები", + "Tokens: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. Other text shows as typed.": "ტეგები: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. სხვა ტექსტი ისე ჩანს, როგორც აკრიფეთ.", + "Top": "ზედა", + "Tracking": "ტრეკინგი", + "Use export watermark": "ექსპორტის ჭვირნიშნის გამოყენება", + "Use selected photo": "მონიშნული ფოტოს გამოყენება", + "Viewers that don't read the PNG cICP chunk show PQ values as sRGB: flat and washed out. For a picture that looks right everywhere, use JPEG (gain map).": "სანახავი პროგრამები, რომლებიც PNG-ის cICP ბლოკს ვერ კითხულობს, PQ მნიშვნელობებს sRGB-ად აჩვენებს: ბრტყლად და გაცრეცილად. სურათისთვის, რომელიც ყველგან სწორად ჩანს, გამოიყენეთ JPEG (gain map).", + "Whole names": "სრული სახელები", + "Wide": "ფართო", + "Wrote the XMP sidecars that were waiting": "მომლოდინე XMP თანმხლები ფაილები ჩაიწერა", + "Your library is empty": "თქვენი ბიბლიოთეკა ცარიელია", + "Your name or studio": "თქვენი სახელი ან სტუდია", + "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "საკუთარ შაბლონებს პარამეტრების საქაღალდე სჭირდება, რომელიც ამ ვერსიას არ აქვს; ჩაშენებული შაბლონები მუშაობს.", + "Your templates": "თქვენი შაბლონები", + "Zone": "ზონა", + "Zoom to Focus Point": "ფოკუსის წერტილამდე გადიდება", + "Zoom to fill frame": "კადრის შესავსებად გადიდება", + "new keyword": "ახალი საკვანძო სიტყვა", + "or drop a .onnx file on the window": "ან ჩააგდეთ .onnx ფაილი ფანჯარაზე", + "or drop photos and folders into this window": "ან ჩააგდეთ ფოტოები და საქაღალდეები ამ ფანჯარაში", + "or drop photos into this window": "ან ჩააგდეთ ფოტოები ამ ფანჯარაში", + "Cycle Flag": "დროშის მონაცვლეობა", + "Increase Flag Status": "დროშის სტატუსის აწევა", + "Decrease Flag Status": "დროშის სტატუსის დაწევა", + "Mask Effect Presets": "ნიღბის ეფექტის პრესეტები", + "Apply Mask Effect": "ნიღბის ეფექტის გამოყენება", + "Save Mask Effect": "ნიღბის ეფექტის შენახვა", + "Update Mask Effect": "ნიღბის ეფექტის განახლება", + "Rename Mask Effect": "ნიღბის ეფექტის სახელის შეცვლა", + "Duplicate Mask Effect": "ნიღბის ეფექტის დუბლირება", + "Delete Mask Effect": "ნიღბის ეფექტის წაშლა", + "Favorite Mask Effect": "ნიღბის ეფექტის რჩეულებში დამატება", + "Move Mask Effect to Group": "ნიღბის ეფექტის ჯგუფში გადატანა", + "Rename Mask Effect Group": "ნიღბის ეფექტების ჯგუფის სახელის შეცვლა", + "Set Effect for New Masks": "ახალი ნიღბების ეფექტის დაყენება", + "Import Mask Effects": "ნიღბის ეფექტების იმპორტი", + "Export Mask Effects": "ნიღბის ეფექტების ექსპორტი", + "Write Waiting XMP Sidecars": "მომლოდინე XMP თანმხლები ფაილების ჩაწერა", + "Slideshow Playback Settings": "სლაიდშოუს დაკვრის პარამეტრები", + "Slideshow Layout Settings": "სლაიდშოუს განლაგების პარამეტრები", + "Slideshow Overlay Settings": "სლაიდშოუს ზედდების პარამეტრები", + "Slideshow Title Settings": "სლაიდშოუს ტიტრების პარამეტრები", + "Apply Slideshow Template": "სლაიდშოუს შაბლონის გამოყენება", + "Save Slideshow Template": "სლაიდშოუს შაბლონის შენახვა", + "Update Slideshow Template": "სლაიდშოუს შაბლონის განახლება", + "Rename Slideshow Template": "სლაიდშოუს შაბლონის სახელის შეცვლა", + "Delete Slideshow Template": "სლაიდშოუს შაბლონის წაშლა", + "Import Slideshow Template": "სლაიდშოუს შაბლონის იმპორტი", + "Slideshow Slide Preview": "სლაიდშოუს სლაიდის გადახედვა", + "Slideshow Export Status": "სლაიდშოუს ექსპორტის მდგომარეობა", + "Print Settings": "ბეჭდვის პარამეტრები", + "Set Print Settings": "ბეჭდვის პარამეტრების დაყენება", + "Reset Print Settings": "ბეჭდვის პარამეტრების ჩამოყრა", + "Add Print Cell": "ბეჭდვის უჯრის დამატება", + "Move Print Cell": "ბეჭდვის უჯრის გადატანა", + "Resize Print Cell": "ბეჭდვის უჯრის ზომის შეცვლა", + "Delete Print Cell": "ბეჭდვის უჯრის წაშლა", + "Arrange Print Cell": "ბეჭდვის უჯრის დალაგება", + "Set Print Cell Photo": "ბეჭდვის უჯრის ფოტოს დაყენება", + "Move Print Cell to Page": "ბეჭდვის უჯრის გვერდზე გადატანა", + "Auto Layout": "ავტომატური განლაგება", + "New Print Page": "ახალი საბეჭდი გვერდი", + "Clear Print Layout": "ბეჭდვის განლაგების გასუფთავება", + "Print to PDF": "PDF-ად დაბეჭდვა", + "Print Templates": "ბეჭდვის შაბლონები", + "Save Print Template": "ბეჭდვის შაბლონის შენახვა", + "Apply Print Template": "ბეჭდვის შაბლონის გამოყენება", + "Delete Print Template": "ბეჭდვის შაბლონის წაშლა", + "Recheck Preview-Only Raws": "მხოლოდ წინასწარი ხედის მქონე RAW ფაილების ხელახლა შემოწმება", + "Face Models on the GPU": "სახეების მოდელები GPU-ზე", + "Rename Person": "ადამიანის სახელის შეცვლა", + "Read Focus Points in the Background": "ფოკუსის წერტილების ფონურად წაკითხვა", + "Increase Grid Thumbnail Size": "ბადის ესკიზების ზომის გაზრდა", + "Decrease Grid Thumbnail Size": "ბადის ესკიზების ზომის შემცირება", + "Cycle Tool Overlay": "ხელსაწყოს ზედდების მონაცვლეობა", + "Choose Layout Image…": "განლაგების გამოსახულების არჩევა…", + "Show Layout Image": "განლაგების გამოსახულების ჩვენება", + "Layout Image Opacity": "განლაგების გამოსახულების გაუმჭვირვალობა", + "Layout Image Matte": "განლაგების გამოსახულების მატი", + "Slideshow Options…": "სლაიდშოუს პარამეტრები…", + "Pause / Resume Slideshow": "სლაიდშოუს შეჩერება / გაგრძელება", + "Next Slide": "შემდეგი სლაიდი", + "Previous Slide": "წინა სლაიდი", + "End Slideshow": "სლაიდშოუს დასრულება", + "Save Current Settings as New Effect Preset…": "მიმდინარე პარამეტრების ახალ ეფექტის პრესეტად შენახვა…", + "Manage Effect Presets…": "ეფექტის პრესეტების მართვა…", + "Export Effect Presets…": "ეფექტის პრესეტების ექსპორტი…", + "Dimensions": "ზომები", + "Width & Height": "სიგანე და სიმაღლე", + "Previous page": "წინა გვერდი", + "Next page": "შემდეგი გვერდი", + "No Matte": "მატის გარეშე", + "Tool Overlay: Auto": "ხელსაწყოს ზედდება: ავტომატური", + "Tool Overlay: Always": "ხელსაწყოს ზედდება: ყოველთვის", + "Tool Overlay: Selected": "ხელსაწყოს ზედდება: მონიშნული", + "Tool Overlay: Never": "ხელსაწყოს ზედდება: არასოდეს", + "Copy Settings…": "პარამეტრების კოპირება…", + "Thumbnail size": "მინიატურების ზომა", + "Import Thumbnail Size": "იმპორტის მინიატურების ზომა", + "It is not a denoise model LightCraft understands": "ეს არ არის ხმაურის მოცილების მოდელი, რომელიც LightCraft-ს ესმის", + "Resize region": "რეგიონის ზომის შეცვლა", + "Remove region": "რეგიონის მოშორება", + "Filters": "ფილტრები", + "Mask": "ნიღაბი", + "New spot (Return adds it here)": "ახალი ლაქა (Return აქ ამატებს)", + "Combine with the existing person": "არსებულ ადამიანთან გაერთიანება", + "Masks keep their sliders. Export presets first to keep a copy.": "ნიღბები თავიანთ სლაიდერებს ინარჩუნებენ. ასლის შესანარჩუნებლად ჯერ პრესეტების ექსპორტი გააკეთეთ.", + "Click to hide clipping warnings for shadows and highlights.": "დაწკაპეთ ჩრდილებისა და ღია ტონების მოკვეთის გაფრთხილებების დასამალად.", + "Click to show clipping warnings for shadows and highlights.": "დაწკაპეთ ჩრდილებისა და ღია ტონების მოკვეთის გაფრთხილებების საჩვენებლად.", + "Curve channel": "მრუდის არხი", + "Color wheel": "ფერთა წრე", + "Show / hide": "ჩვენება / დამალვა", + "Hide this wheel's effect": "ამ ბორბლის ეფექტის დამალვა", + "The layout image can't be shown": "განლაგების გამოსახულების ჩვენება შეუძლებელია", + "No change": "ცვლილების გარეშე", + "Search effects": "ეფექტების ძიება", + "No effect presets yet": "ეფექტის პრესეტები ჯერ არ არის", + "No effect matches": "შესაბამისი ეფექტი არ არის", + "★ Favorites": "★ რჩეულები", + "Reset Sliders": "სლაიდერების ჩამოყრა", + "Save Current Settings as New Preset…": "მიმდინარე პარამეტრების ახალ პრესეტად შენახვა…", + "Manage Presets…": "პრესეტების მართვა…", + "Apply to All Masks": "ყველა ნიღბზე გამოყენება", + "Also the masks of the same name on the other selected photos": "აგრეთვე იმავე სახელის ნიღბები სხვა მონიშნულ ფოტოებზე", + "Delete…": "წაშლა…", + "Group (optional)": "ჯგუფი (არასავალდებულო)", + "Choose a group": "ჯგუფის არჩევა", + "Highlighted: sliders this mask changes. Sliders left out stay as they are when the preset is applied.": "გამოკვეთილია: სლაიდერები, რომლებსაც ეს ნიღაბი ცვლის. გამოტოვებული სლაიდერები პრესეტის გამოყენებისას უცვლელი რჩება.", + "Include Amount": "სიძლიერის ჩართვა", + "Include brush size, feather and flow": "ფუნჯის ზომის, კიდეების შერბილებისა და ნაკადის ჩართვა", + "Name the preset": "პრესეტის დასახელება", + "Choose at least one setting to include": "აირჩიეთ ჩასართავად ერთი პარამეტრი მაინც", + "Ungrouped": "დაუჯგუფებელი", + "Favorite": "რჩეული", + "Move to Group…": "ჯგუფში გადატანა…", + "New group — Return": "ახალი ჯგუფი — Return", + "Select a mask to apply or update presets.": "პრესეტების გამოსაყენებლად ან გასაახლებლად მონიშნეთ ნიღაბი.", + "Show mask": "ნიღბის ჩვენება", + "Overlay color": "ზედდების ფერი", + "Rename Person…": "ადამიანის სახელის შეცვლა…", + "Tool Overlay": "ხელსაწყოს ზედდება", + "When pins show on the photo (Shift+H cycles)": "როდის ჩანს მარკერები ფოტოზე (Shift+H ცვლის)", + "Slide duration": "სლაიდის ხანგრძლივობა", + "Fade duration": "მიქრობის ხანგრძლივობა", + "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "სლაიდი ეკრანზე რჩება თავისი ხანგრძლივობის განმავლობაში, გამოჩენის მიქრობის ჩათვლით. 0-ის ტოლი მიქრობა პირდაპირ ცვლის სლაიდს.", + "Fade": "მიქრობა", + "Renders the next slides while the current one is up, so fades never wait. Off: each slide renders when it is due (less memory and work).": "შემდეგ სლაიდებს არენდერებს, სანამ მიმდინარე ჩანს, ასე რომ მიქრობა არასოდეს აყოვნებს. გამორთული: ყოველი სლაიდი თავის დროზე რენდერდება (ნაკლები მეხსიერება და სამუშაო).", + "Slideshow in the View menu plays the photos in view from the selected one. These settings are saved with the library.": "„ხედი“ მენიუს „სლაიდშოუ“ ხილულ ფოტოებს მონიშნულიდან უკრავს. ეს პარამეტრები ბიბლიოთეკასთან ერთად ინახება.", + "Title bar": "სათაურის ზოლი", + "Unnamed face": "უსახელო სახე", + "Template name": "შაბლონის სახელი", + "One photo fills each page inside the margins.": "თითო ფოტო ავსებს თითოეულ გვერდს ველებს შიგნით.", + "Add a cell": "უჯრის დამატება", + "Managed by Printer (sRGB)": "პრინტერის მართვით (sRGB)", + "Managed by Printer (Adobe RGB)": "პრინტერის მართვით (Adobe RGB)", + "current edits": "მიმდინარე ცვლილებები", + "This page setup is not valid": "გვერდის ეს პარამეტრები არასწორია", + "Page": "გვერდი", + "cells": "უჯრა", + "cells overlap": "უჯრები ერთმანეთს ფარავს", + "Delete Cell": "უჯრის წაშლა", + "Click a cell to move, resize or arrange it": "დაწკაპეთ უჯრაზე მის გადასაადგილებლად, ზომის შესაცვლელად ან დასალაგებლად", + "Loupe Overlay": "ლუპის ზედდება", + "2026-10-21": "2026-10-21", + "Sharper resampling in HDR and panorama merges": "უფრო მკვეთრი ხელახალი დისკრეტიზაცია HDR-ისა და პანორამის გაერთიანებებში", + "Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a": "გაერთიანებული ფოტოები (HDR და პანორამა) ხელახლა დისკრეტიზდება უფრო მკვეთრი ფილტრით (Lanczos-3 ბიწრფივის ნაცვლად). ფოტოს", + "photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around": "ნახევარი პიქსელით გადაადგილებისას ადრე იკარგებოდა მისი ყველაზე წვრილი დეტალების მესამედი; ახლა მათი უმეტესობა რჩება, შარავანდის გარეშე", + "hard edges such as clipped highlights.": "მკვეთრი კიდეების გარშემო, როგორიცაა მოკვეთილი ღია ტონები.", + "Scrolling past editing sliders": "გადახვევა რედაქტირების სლაიდერებზე", + "Leaving a selected slider disarms its vertical mouse-wheel adjustment (issue #1355), even when the pointer leaves": "მონიშნული სლაიდერიდან გასვლა თიშავს მის რეგულირებას მაუსის ვერტიკალური ბორბლით (ხარვეზი #1355), მაშინაც კი, როცა მაჩვენებელი გადის", + "and comes back between two screen updates. Scrolling back over it now scrolls the panel instead of unexpectedly": "და ბრუნდება ეკრანის ორ განახლებას შორის. მასზე უკან გადახვევისას ახლა პანელი გადაიხვევა, ნაცვლად იმისა, რომ მოულოდნელად", + "changing the photo. Click or drag the slider again to adjust it with the vertical wheel; keyboard arrow": "ფოტო შეიცვალოს. სლაიდერის ვერტიკალური ბორბლით სარეგულირებლად ხელახლა დაწკაპეთ ან გადაათრიეთ; კლავიატურის ისრებით", + "adjustments and an ongoing drag still work. A slider reached with Tab takes the arrow keys but not the wheel:": "რეგულირება და მიმდინარე გადათრევა ისევ მუშაობს. Tab-ით მიღწეული სლაიდერი იღებს ისრიან კლავიშებს, ბორბალს კი არა:", + "click it to scroll-adjust it. Sideways scrolling still adjusts the slider under the pointer without selecting it": "გადახვევით სარეგულირებლად დაწკაპეთ. გვერდითი გადახვევა ისევ არეგულირებს მაჩვენებლის ქვეშ მყოფ სლაიდერს, მისი", + "first.": "წინასწარ მონიშვნის გარეშე.", + "A pinch no longer re-renders the photo at every zoom step": "თითებით მასშტაბირება ფოტოს აღარ არენდერებს მასშტაბის ყოველ ნაბიჯზე", + "Pinching the loupe now keeps the size the fit view is rendered at until the gesture is quiet, as it already did for": "ლუპაზე თითებით მასშტაბირებისას ახლა ეკრანში ჩატეული ხედის რენდერის ზომა უცვლელი რჩება ჟესტის დასრულებამდე, როგორც უკვე ხდებოდა", + "the render sizes and windows. Before, each frame of a pinch asked for a new full-frame render at a new size.": "რენდერის ზომებისა და ფანჯრებისთვის. ადრე ჟესტის ყოველი კადრი ახალ სრულკადრიან რენდერს ითხოვდა ახალ ზომაზე.", + "Fujifilm lens corrections that match the camera": "Fujifilm-ის ობიექტივის კორექციები, რომლებიც კამერას ემთხვევა", + "X-T4 raws now read the lens's own distortion and vignetting tables the way the camera does. Many photos from zoom": "X-T4-ის RAW ფაილები ახლა ობიექტივის საკუთარ დეფორმაციისა და ვინიეტირების ცხრილებს ისე კითხულობს, როგორც კამერა. ზუმ-ობიექტივებით", + "lenses got no distortion correction at all (more than half of those checked from the XF16-55 and XF70-300), and": "გადაღებული ბევრი ფოტო დეფორმაციის კორექციას საერთოდ არ იღებდა (XF16-55-ითა და XF70-300-ით შემოწმებულთა ნახევარზე მეტი), ხოლო", + "corners came out up to 6.5 % brighter than in the camera's JPEG. The corrected photo now lines up with the camera's": "კუთხეები კამერის JPEG-თან შედარებით 6.5 %-მდე უფრო ნათელი გამოდიოდა. კორექტირებული ფოტო ახლა ემთხვევა კამერის", + "framing. Other recent Fujifilm bodies whose tables have nine knots are read the same way, but only the X-T4 was": "კადრირებას. Fujifilm-ის სხვა ახალი კორპუსები, რომელთა ცხრილებსაც ცხრა კვანძი აქვს, იმავე გზით იკითხება, მაგრამ მხოლოდ X-T4", + "measured. Thumbnails are redrawn when the library next shows them.": "გაიზომა. ესკიზები ხელახლა დაიხატება, როცა ბიბლიოთეკა მათ შემდეგ ჯერზე აჩვენებს.", + "Reference view reliability": "ეტალონური ხედის საიმედოობა", + "Escape now leaves Reference for Detail without changing the active photo or its edits; the next": "Escape ახლა ეტალონიდან დეტალურ ხედზე გადადის აქტიური ფოტოსა და მისი ცვლილებების შეუცვლელად; შემდეგი", + "Escape returns to the grid. A dialog, tool or Lights Out still handles Escape first.": "Escape ბადეს უბრუნდება. დიალოგი, ხელსაწყო ან სინათლის ჩაქრობა Escape-ს ისევ პირველი ამუშავებს.", + "Opening or creating a different library clears the pinned reference. Photo IDs belong to one": "სხვა ბიბლიოთეკის გახსნა ან შექმნა მიმაგრებულ ეტალონს ასუფთავებს. ფოტოების ID-ები ერთ", + "catalog; a pin no longer silently becomes another library's photo with the same numeric ID.": "კატალოგს ეკუთვნის; მიმაგრება აღარ იქცევა შეუმჩნევლად სხვა ბიბლიოთეკის ფოტოდ იმავე რიცხვითი ID-ით.", + "Missing or Recently Deleted photos cannot be pinned. Deleting the pinned reference stops drawing": "დაკარგული ან ახლახან წაშლილი ფოტოების მიმაგრება შეუძლებელია. მიმაგრებული ეტალონის წაშლის შემდეგ ის", + "it; re-entering Reference chooses a live photo, and restoring the deleted photo makes it pinnable again.": "აღარ იხატება; ეტალონში ხელახლა შესვლა ხელმისაწვდომ ფოტოს ირჩევს, წაშლილი ფოტოს აღდგენა კი მას ისევ მიმაგრებადს ხდის.", + "In Recently Deleted, Set as Reference Photo is greyed out, and a refusal says to restore the photo.": "ახლახან წაშლილში „ეტალონურ ფოტოდ დაყენება“ მიუწვდომელია, უარის შეტყობინება კი ფოტოს აღდგენას გირჩევთ.", + "Switching library from Reference view goes to the grid instead of an empty Reference canvas. A refused": "ეტალონური ხედიდან ბიბლიოთეკის გადართვა ბადეზე გადადის, ნაცვლად ეტალონის ცარიელი ტილოსი. უარყოფილი", + "or failed switch keeps both the reference and the Compare pair.": "ან ჩაშლილი გადართვა ინარჩუნებს როგორც ეტალონს, ისე შედარების წყვილს.", + "`photo.setReference` refuses an `id` that is not a photo id (a string, a negative or fractional": "`photo.setReference` უარყოფს `id`-ს, რომელიც ფოტოს id არ არის (სტრიქონი, უარყოფითი ან წილადი", + "number) instead of pinning the active photo; only an absent or null `id` means the active photo.": "რიცხვი), ნაცვლად აქტიური ფოტოს მიმაგრებისა; აქტიურ ფოტოს მხოლოდ გამოტოვებული ან null `id` ნიშნავს.", + "2026-10-20": "2026-10-20", + "Smart albums check File Path rules faster": "სმარტ-ალბომები ფაილის მისამართის წესებს უფრო სწრაფად ამოწმებს", + "A smart album rule on File Path (contains, doesn't contain, is, isn't, starts with, ends with, is empty, isn't": "სმარტ-ალბომის წესი ფაილის მისამართზე (შეიცავს, არ შეიცავს, არის, არ არის, იწყება, მთავრდება, ცარიელია, არ არის", + "empty) no longer builds new text for every photo. On a synthetic library of 312,000 photos, a File Path \"contains\"": "ცარიელი) აღარ ქმნის ახალ ტექსტს ყოველი ფოტოსთვის. 312,000 ფოტოს სინთეზურ ბიბლიოთეკაში ფაილის მისამართის „შეიცავს“", + "or \"doesn't contain\" rule took about 17 ms per pass instead of about 62 ms, around 3.5 times faster, with the same": "ან „არ შეიცავს“ წესს ერთ გავლაზე დაახლოებით 17 ms სჭირდებოდა დაახლოებით 62 ms-ის ნაცვლად, დაახლოებით 3.5-ჯერ უფრო სწრაფად, იმავე", + "photos matched; about 6 ms of that is only reading the paths. Paths and rule text with letters beyond A–Z are": "შესაბამისი ფოტოებით; აქედან დაახლოებით 6 ms მხოლოდ მისამართების წაკითხვაა. მისამართები და წესის ტექსტი A–Z-ის მიღმა ასოებით", + "compared as before.": "ისევე შედარდება, როგორც ადრე.", + "2026-10-19": "2026-10-19", + "AI Denoise on DirectX 12 with NVIDIA GTX 10-series cards": "AI ხმაურის მოცილება DirectX 12-ზე NVIDIA GTX 10-სერიის ბარათებით", + "AI Denoise on the GPU under DirectX 12 (the Windows default) gives the same result as on the CPU again on an NVIDIA": "AI ხმაურის მოცილება GPU-ზე DirectX 12-ით (Windows-ის ნაგულისხმევი) NVIDIA GeForce GTX 1070-ზე ისევ იმავე შედეგს იძლევა, რასაც", + "GeForce GTX 1070. The driver ran the denoise network's output stores wrong, so every second pixel's colour": "CPU-ზე. დრაივერი ხმაურის მოცილების ქსელის გამოსავალ ჩაწერებს არასწორად ასრულებდა, ამიტომ ყოველი მეორე პიქსელის ფერის", + "channels came out shifted and the denoised photo was wrong without any error. Vulkan was not affected.": "არხები წანაცვლებული გამოდიოდა და ხმაურმოცილებული ფოტო არასწორი იყო ყოველგვარი შეცდომის გარეშე. Vulkan ამას არ შეხებია.", + "The Before label stays in view when zoomed in": "„მანამდე“-ს წარწერა გადიდებისას ხედში რჩება", + "Zoomed in, the \"Before\" label (\\ key or the Before view) now sits at the canvas' corner instead of leaving the": "გადიდებისას „მანამდე“-ს წარწერა (\\ კლავიში ან „მანამდე“-ს ხედი) ახლა ტილოს კუთხეში დგას, ნაცვლად იმისა, რომ", + "screen with the photo's corner (issue #2267).": "ფოტოს კუთხესთან ერთად ეკრანიდან გავიდეს (ხარვეზი #2267).", + "Synchronize Folder on a folder that is up to date": "საქაღალდის სინქრონიზაცია განახლებულ საქაღალდეზე", + "When the scan finds nothing to import, relink, remove or read, the Synchronize Folder dialog says the library is up": "როცა სკანირება იმპორტის, ხელახლა დაკავშირების, მოშორების ან წასაკითხს ვერაფერს პოულობს, საქაღალდის სინქრონიზაციის დიალოგი ამბობს, რომ ბიბლიოთეკა", + "to date with the folder and has one Close button. It used to show four greyed choices, two of them still ticked,": "საქაღალდესთან სინქრონშია, და მას ერთი „დახურვა“ ღილაკი აქვს. ადრე ის ოთხ მიუწვდომელ არჩევანს აჩვენებდა, აქედან ორს ისევ მონიშნულს,", + "and a Synchronize button that started a job with nothing to do. Files it skipped (already in the library elsewhere,": "და „სინქრონიზაციის“ ღილაკს, რომელიც უსაქმო დავალებას იწყებდა. ფაილები, რომლებიც გამოტოვა (უკვე ბიბლიოთეკაში სხვაგან,", + "or unreadable) are still listed.": "ან წაუკითხავი), ისევ ჩამოთვლილია.", + "Hidden Local locations come back one at a time": "დამალული ლოკალური მდებარეობები სათითაოდ ბრუნდება", + "With several locations removed from Local, \"Show N hidden locations\" now lists them, so each comes back on its own": "როცა ლოკალურიდან რამდენიმე მდებარეობაა მოშორებული, „დამალული მდებარეობების ჩვენება: N“ ახლა მათ ჩამოთვლის, ასე რომ თითოეული ცალკე ბრუნდება", + "(Restore All is there too). The row used to bring every hidden location back at once (issue #2114).": "(„ყველას აღდგენაც“ იქვეა). ადრე ეს სტრიქონი ყველა დამალულ მდებარეობას ერთბაშად აბრუნებდა (ხარვეზი #2114).", + "2026-10-18": "2026-10-18", + "Thumbnails of Lightroom HDR and panorama merges in a second": "Lightroom-ის HDR-ისა და პანორამის გაერთიანებების ესკიზები წამში", + "Grid and filmstrip thumbnails of DNGs that Lightroom merged (HDR, Panorama, HDR Panorama) now develop from the": "Lightroom-ის მიერ გაერთიანებული DNG-ების (HDR, Panorama, HDR Panorama) ბადისა და კადრების ზოლის ესკიზები ახლა მუშავდება", + "small copies of the raw image Lightroom keeps inside the file (256 to 2048 px), not from the whole merge. A 23836 ×": "RAW გამოსახულების პატარა ასლებიდან, რომლებსაც Lightroom ფაილის შიგნით ინახავს (256-დან 2048 px-მდე), და არა მთელი გაერთიანებიდან. 23836 ×", + "7078 drone panorama's 512 px thumbnail took 38 s and now takes about a second, with the same look; your edits still": "7078 დრონის პანორამის 512 px ესკიზს 38 s სჭირდებოდა, ახლა კი დაახლოებით წამი, იგივე იერით; თქვენი ცვლილებები ისევ", + "apply. Loupe previews larger than the biggest copy, 1:1 views and exports still read the full image.": "გამოიყენება. ლუპის წინასწარი ხედები, რომლებიც უდიდეს ასლზე დიდია, 1:1 ხედები და ექსპორტები ისევ სრულ გამოსახულებას კითხულობს.", + "Fewer false \"not imported\" warnings for Lightroom raws": "ნაკლები ცრუ გაფრთხილება „არ არის იმპორტირებული“ Lightroom-ის RAW ფაილებისთვის", + "Importing raws with Lightroom XMP sidecars no longer lists settings Lightroom writes only for itself as adjustments": "Lightroom-ის XMP თანმხლები ფაილების მქონე RAW-ების იმპორტი აღარ ჩამოთვლის პარამეტრებს, რომლებსაც Lightroom მხოლოდ თავისთვის წერს, როგორც", + "that weren't imported: `CompatibleVersion`, the camera and lens profile checksums, the lens profile's name, file and": "იმპორტირებულ კორექციებს, რომლებიც ვერ შემოვიდა: `CompatibleVersion`, კამერისა და ობიექტივის პროფილების საკონტროლო ჯამები, ობიექტივის პროფილის სახელი, ფაილი და", + "setup, the crop's \"constrain to image\" option, and the lens profile's strength when it is at its default of 100 %.": "გამართვა, ჩამოჭრის „გამოსახულებით შეზღუდვის“ ვარიანტი და ობიექტივის პროფილის სიძლიერე, როცა ის ნაგულისხმევ 100 %-ზეა.", + "A raw sidecar used to name all of them for every photo. Settings LightCraft really doesn't apply, such as `Look`,": "RAW-ის თანმხლები ფაილი ადრე ყველა მათგანს ასახელებდა ყოველი ფოტოსთვის. პარამეტრები, რომლებსაც LightCraft მართლაც არ იყენებს, მაგალითად `Look`,", + "are still reported.": "ისევ ჩამოთვლილია.", + "Fill Location from GPS: no more neighbouring town in City": "მდებარეობის შევსება GPS-ით: ქალაქის ველში აღარ ხვდება მეზობელი ქალაქი", + "The offline place names list towns of 15,000 people or more, so a photo taken in a smaller one got the nearest larger": "ადგილების ოფლაინ სახელების სია შეიცავს 15,000 ან მეტი მცხოვრების მქონე ქალაქებს, ამიტომ პატარა დასახლებაში გადაღებული ფოტო უახლოეს დიდ", + "town in City, sometimes another municipality (issue #2242). The Fill Location tooltip and the command help now say so,": "ქალაქს იღებდა ქალაქის ველში, ზოგჯერ სხვა მუნიციპალიტეტს (ხარვეზი #2242). მდებარეობის შევსების მინიშნება და ბრძანების დახმარება ახლა ამას ამბობს,", + "and `metadata.reverseGeocode` takes `maxDistance` (metres): past it, City stays empty (State and Country still fill)": "და `metadata.reverseGeocode` იღებს `maxDistance`-ს (მეტრებში): მის მიღმა ქალაქი ცარიელი რჩება (რეგიონი და ქვეყანა ისევ ივსება)", + "and the reply names the town it found as `nearestCity`.": "და პასუხი ნაპოვნ ქალაქს ასახელებს როგორც `nearestCity`.", + "A preset that couldn't be saved is no longer lost silently": "პრესეტი, რომლის შენახვაც ვერ მოხერხდა, აღარ იკარგება შეუმჩნევლად", + "When presets.json can't be written (a full disk, or the browser's storage quota), the new or changed preset now": "როცა presets.json-ის ჩაწერა შეუძლებელია (სავსე დისკი ან ბრაუზერის მეხსიერების კვოტა), ახალი ან შეცვლილი პრესეტი ახლა", + "counts as unsaved, like other changes: the top bar warns, saving is retried, and quitting asks first (issue #2266).": "შეუნახავად ითვლება, როგორც სხვა ცვლილებები: ზედა ზოლი გაფრთხილებას აჩვენებს, შენახვა მეორდება, გასვლისას კი ჯერ შეგეკითხებათ (ხარვეზი #2266).", + "Before, the failure was only logged, and the preset could be lost without any warning.": "ადრე შეცდომა მხოლოდ ჟურნალში იწერებოდა და პრესეტი შეიძლებოდა დაკარგულიყო ყოველგვარი გაფრთხილების გარეშე.", + "Portrait crop ratios stay portrait": "პორტრეტული ჩამოჭრის თანაფარდობები პორტრეტულად რჩება", + "A crop ratio no longer flips to the photo's orientation (issue #2253): after X turns the crop portrait, picking": "ჩამოჭრის თანაფარდობა აღარ გადაბრუნდება ფოტოს ორიენტაციაზე (ხარვეზი #2253): მას შემდეგ, რაც X ჩამოჭრას პორტრეტულად აქცევს,", + "another ratio (4 × 5, 2 × 3…) keeps it portrait, as in Lightroom, and a Custom ratio taller than wide gives a": "სხვა თანაფარდობის არჩევა (4 × 5, 2 × 3…) მას პორტრეტულად ტოვებს, როგორც Lightroom-ში, ხოლო მორგებული თანაფარდობა, რომელიც სიგანეზე მაღალია,", + "portrait crop.": "პორტრეტულ ჩამოჭრას იძლევა.", + "2026-10-16": "2026-10-16", + "Synchronize Folder shows that it is listing the folder": "საქაღალდის სინქრონიზაცია აჩვენებს, რომ საქაღალდის ჩამონათვალს ადგენს", + "A folder with tens of thousands of photos, above all on a network share, can take minutes to list before": "ათიათასობით ფოტოს მქონე საქაღალდის ჩამონათვალის შედგენას, განსაკუთრებით ქსელურ საქაღალდეზე, შეიძლება წუთები დასჭირდეს, სანამ", + "Synchronize Folder checks a single photo. Its row in the activity stack used to sit at \"0 of 64085\" with an empty": "საქაღალდის სინქრონიზაცია ერთ ფოტოსაც შეამოწმებს. მისი სტრიქონი აქტივობების დასტაში მთელი ეს დრო „0 of 64085“-ზე იდგა ცარიელი", + "bar all that time, as if it had stopped. It now says how many folders and files it has listed so far, with a bar": "ზოლით, თითქოს გაჩერებულიყო. ახლა ის ამბობს, რამდენი საქაღალდე და ფაილი ჩამოთვალა აქამდე, ზოლით,", + "that moves on its own, and then counts the photos it checks. The dialog says the same.": "რომელიც თავისით მოძრაობს, შემდეგ კი ითვლის ფოტოებს, რომლებსაც ამოწმებს. დიალოგიც იმავეს ამბობს.", + "✕ on the row stops the listing too, not only the checks after it.": "სტრიქონზე × ჩამონათვალის შედგენასაც აჩერებს და არა მხოლოდ მის შემდგომ შემოწმებებს.", + "The photo grid keeps up with imports into a large library": "ფოტოების ბადე დიდ ბიბლიოთეკაში იმპორტს ფეხს უწყობს", + "While photos are imported into a large library, the grid takes in each batch as it arrives instead of reading": "დიდ ბიბლიოთეკაში ფოტოების იმპორტისას ბადე ყოველ პარტიას მოსვლისთანავე იღებს, ნაცვლად იმისა, რომ ხედის ყველა ფოტო", + "every photo of the view again: at about 180,000 photos a batch cost the window a tenth of a second, over and over": "ხელახლა წაიკითხოს: დაახლოებით 180,000 ფოტოზე ყოველი პარტია ფანჯარას წამის მეათედი უჯდებოდა, ისევ და ისევ,", + "for as long as the import ran. Changing one photo's capture time or crop is quicker too.": "სანამ იმპორტი მიმდინარეობდა. ერთი ფოტოს გადაღების დროის ან ჩამოჭრის შეცვლაც უფრო სწრაფია.", + "2026-10-15": "2026-10-15", + "Photo Merge takes each photo once": "ფოტოების გაერთიანება ყოველ ფოტოს ერთხელ იღებს", + "A merge that names the same photo more than once (through `ids` on the control channel, MCP or the CLI) now merges": "გაერთიანება, რომელიც ერთსა და იმავე ფოტოს ერთზე მეტჯერ ასახელებს (`ids`-ით მართვის არხზე, MCP-ში ან CLI-ში), ახლა მას", + "it once (issue #1947). Naming one photo three times no longer \"merges\" it with itself, and a long repeated list no": "ერთხელ აერთიანებს (ხარვეზი #1947). ერთი ფოტოს სამჯერ დასახელება მას აღარ „აერთიანებს“ საკუთარ თავთან, ხოლო გრძელი განმეორებითი სია", + "longer decodes the photo again for every entry.": "აღარ დეკოდირებს ფოტოს ხელახლა ყოველი ჩანაწერისთვის.", + "Constrain Crop tightens the crop you see": "ჩამოჭრის შეზღუდვა თქვენთვის ხილულ ჩამოჭრას ავიწროებს", + "Geometry ▸ Constrain Crop now changes the crop itself, as in Lightroom (issue #1927). Ticking it, or moving a": "გეომეტრია → ჩამოჭრის შეზღუდვა ახლა თავად ჩამოჭრას ცვლის, როგორც Lightroom-ში (ხარვეზი #1927). მისი მონიშვნა, ან, მონიშნულ მდგომარეობაში,", + "Geometry slider, Upright or a lens correction while it is ticked, shrinks the crop about its centre until the blank": "გეომეტრიის სლაიდერის, Upright-ის ან ობიექტივის კორექციის შეცვლა ჩამოჭრას ცენტრის გარშემო ამცირებს, სანამ არ გაქრება ცარიელი", + "corners left by the correction are gone, and the Crop tool shows the tighter crop. Before, it only applied when the": "კუთხეები, რომლებსაც კორექცია ტოვებს, და ჩამოჭრის ხელსაწყო ვიწრო ჩამოჭრას აჩვენებს. ადრე ის მხოლოდ მაშინ მოქმედებდა, როცა", + "photo was shown outside the Crop tool, so in the Crop panel, where the checkbox is, nothing seemed to change. A crop": "ფოტო ჩამოჭრის ხელსაწყოს გარეთ ჩანდა, ამიტომ ჩამოჭრის პანელში, სადაც მოსანიშნი ველია, თითქოს არაფერი იცვლებოდა. ჩამოჭრა,", + "you draw by hand is kept as drawn, and unticking keeps the tighter crop.": "რომელსაც ხელით ხაზავთ, ისე რჩება, როგორც დახაზეთ, ხოლო მონიშვნის მოხსნა ვიწრო ჩამოჭრას ინარჩუნებს.", + "Web: no backup that misses unsaved changes": "ვები: სარეზერვო ასლი, რომელსაც შეუნახავი ცვლილებები აკლია, აღარ იქმნება", + "In the browser version, File ▸ Back Up Library… no longer reports success while a save is failing (storage full or": "ბრაუზერის ვერსიაში ფაილი → ბიბლიოთეკის სარეზერვო ასლი… აღარ იუწყება წარმატებას, როცა შენახვა ვერ ხერხდება (მეხსიერება სავსეა ან", + "cleared): the backup copies the stored library, so it left out the changes that couldn't be saved (issue #1508). It": "გასუფთავებულია): სარეზერვო ასლი შენახულ ბიბლიოთეკას აკოპირებს, ამიტომ მასში არ ხვდებოდა ცვლილებები, რომელთა შენახვაც ვერ მოხერხდა (ხარვეზი #1508). ის", + "now refuses to start and says how many changes are unsaved and why. LightCraft retries the save with every change;": "ახლა არ იწყება და ამბობს, რამდენი ცვლილებაა შეუნახავი და რატომ. LightCraft შენახვას ყოველ ცვლილებაზე ხელახლა ცდის;", + "back up once nothing is left unsaved.": "სარეზერვო ასლი შექმენით, როცა შეუნახავი აღარაფერი დარჩება.", + "Web: an unreadable library is not opened": "ვები: წაუკითხავი ბიბლიოთეკა აღარ იხსნება", + "In the browser version, a library file that exists but can't be read at start-up is no longer taken for a missing": "ბრაუზერის ვერსიაში ბიბლიოთეკის ფაილი, რომელიც არსებობს, მაგრამ გაშვებისას ვერ იკითხება, აღარ ითვლება დაკარგულად", + "one (issue #1507). LightCraft used to open the library without it, showing an incomplete catalog that the next save": "(ხარვეზი #1507). LightCraft ადრე ბიბლიოთეკას მის გარეშე ხსნიდა და არასრულ კატალოგს აჩვენებდა, რომელსაც შემდეგი შენახვა", + "would write over the stored copy. It now leaves the library unopened, saves nothing and says which file couldn't be": "შენახულ ასლს გადააწერდა. ახლა ის ბიბლიოთეკას გაუხსნელს ტოვებს, არაფერს ინახავს და ასახელებს ფაილს, რომლის წაკითხვაც ვერ", + "read; reload the page to try again.": "მოხერხდა; ხელახლა საცდელად განაახლეთ გვერდი.", + "2026-10-14": "2026-10-14", + "Model downloads time out on a name that doesn't resolve": "მოდელების ჩამოტვირთვა წყდება, თუ სერვერის სახელი ვერ იხსნება", + "Model downloads (AI denoise, faces, SAM) give up on a server name that doesn't resolve within the connect timeout,": "მოდელების ჩამოტვირთვა (AI ხმაურის მოცილება, სახეები, SAM) წყდება, თუ სერვერის სახელი დაკავშირების ლოდინის დროში ვერ იხსნება,", + "and Cancel stops a download that is still looking the name up (issue #1532). The lookup used to block with no time": "და „გაუქმება“ აჩერებს ჩამოტვირთვას, რომელიც ჯერ კიდევ სახელს ეძებს (ხარვეზი #1532). ძიება ადრე უვადოდ ბლოკავდა", + "limit, and each of a server's addresses then got the whole connect timeout of its own.": "და შემდეგ სერვერის თითოეული მისამართი დაკავშირების ლოდინის მთელ დროს ცალკე იღებდა.", + "Sony A7CR distortion correction": "Sony A7CR-ის დეფორმაციის კორექცია", + "Full-frame 3:2 Bayer A7CR raws with distortion Auto or forced Auto now use their embedded distortion table. The corrected render is closer to the camera JPEG geometry. Off files keep their original geometry. APS-C, aspect crops and lossless M/S remain excluded.": "სრულკადრიანი 3:2 Bayer A7CR RAW ფაილები, რომელთა დეფორმაცია ავტომატურზე ან იძულებით ავტომატურზეა, ახლა თავიანთ ჩაშენებულ დეფორმაციის ცხრილს იყენებს. კორექტირებული რენდერი კამერის JPEG-ის გეომეტრიას უფრო უახლოვდება. გამორთული ფაილები თავდაპირველ გეომეტრიას ინარჩუნებს. APS-C, თანაფარდობით ჩამოჭრილი და უდანაკარგო M/S ფაილები ისევ გამორიცხულია.", + "The warp also supplies the geometry needed by the lens-aligned camera-look fit in PR #1586. The pairing code is a separate change. Details and numeric validation are in `docs/sony-lens-corrections.md`.": "დეფორმაციის გასწორება ასევე იძლევა გეომეტრიას, რომელიც სჭირდება ობიექტივთან გასწორებულ კამერის იერის მორგებას PR #1586-ში. დაწყვილების კოდი ცალკე ცვლილებაა. დეტალები და რიცხვითი ვალიდაცია `docs/sony-lens-corrections.md`-შია.", + "Lightroom radial masks on the right side": "Lightroom-ის რადიალური ნიღბები სწორ მხარეს", + "Radial masks brought over from Lightroom Classic (catalog import, XMP sidecars, edits inside DNGs and presets) now": "Lightroom Classic-იდან გადმოტანილი რადიალური ნიღბები (კატალოგის იმპორტი, XMP თანმხლები ფაილები, ცვლილებები DNG-ებსა და პრესეტებში) ახლა", + "apply their effect inside the circle, as Lightroom does, instead of outside it (issue #1815). A mask inverted in": "ეფექტს წრის შიგნით იყენებს, როგორც Lightroom, და არა მის გარეთ (ხარვეზი #1815). Lightroom-ში ინვერტირებული ნიღაბი", + "Lightroom stays inverted, and older Radial Filters keep their Effect Outside / Invert Mask setting. Photos imported": "ინვერტირებული რჩება, ძველი რადიალური ფილტრები კი ინარჩუნებს Effect Outside / „ნიღბის ინვერსია“ პარამეტრს. ფოტოები, რომლებიც დაიმპორტდა", + "before this keep the masks they got: Photo ▸ Read Metadata from File reads a sidecar's again.": "ამაზე ადრე, მიღებულ ნიღბებს ინარჩუნებს: ფოტო → მეტამონაცემების წაკითხვა ფაილიდან თანმხლებ ფაილს ხელახლა წაიკითხავს.", + "Delete in an album removes from the album only": "ალბომში წაშლა მხოლოდ ალბომიდან ამოშლის", + "In an album, the Delete key now takes the selected photos out of the album, as in Lightroom. It used to move them": "ალბომში Delete კლავიში ახლა მონიშნულ ფოტოებს ალბომიდან ამოიღებს, როგორც Lightroom-ში. ადრე ის მათ", + "to Recently Deleted, so they also left their folder's view (issue #1805). They stay in the library and in their": "ახლახან წაშლილში გადაიტანდა, ამიტომ ისინი საქაღალდის ხედიდანაც ქრებოდა (ხარვეზი #1805). ისინი რჩება ბიბლიოთეკასა და თავიანთ", + "folder; Edit ▸ Undo puts them back in the album. Photo ▸ Remove from Album does the same and now shows the key.": "საქაღალდეში; რედაქტირება → დაბრუნება მათ ალბომში აბრუნებს. ფოტო → ალბომიდან ამოშლა იმავეს აკეთებს და ახლა კლავიშსაც აჩვენებს.", + "To delete photos from the library from an album, use Photo ▸ Delete Photo or right-click ▸ Delete Photo. In a smart": "ალბომიდან ფოტოების ბიბლიოთეკიდან წასაშლელად გამოიყენეთ ფოტო → ფოტოს წაშლა ან მარჯვენა დაწკაპება → ფოტოს წაშლა. სმარტ-", + "album, Delete changes nothing: its rules decide what it shows.": "ალბომში Delete არაფერს ცვლის: რას აჩვენებს, მისი წესები წყვეტს.", + "Local folders select a photo": "ლოკალური საქაღალდეები ფოტოს ირჩევს", + "Showing a Local folder now makes its first photo the active one, as albums and the other sources do (issue": "ლოკალური საქაღალდის ჩვენება ახლა მის პირველ ფოტოს აქტიურს ხდის, როგორც ალბომები და სხვა წყაროები (ხარვეზი", + "#1447), or keeps the photo you had when the folder holds it. Before, the photo from the previous view stayed active:": "#1447), ან ტოვებს თქვენს ფოტოს, თუ ის საქაღალდეშია. ადრე წინა ხედის ფოტო აქტიური რჩებოდა:", + "Photo Grid marked nothing, and Detail, the histogram and the photo info showed a photo that isn't in the folder.": "ფოტოების ბადე არაფერს მონიშნავდა, დეტალური ხედი, ჰისტოგრამა და ფოტოს ინფორმაცია კი აჩვენებდა ფოტოს, რომელიც საქაღალდეში არ არის.", + "Nikon Z 6II, Z 8 and D5300 colour profiles": "Nikon Z 6II-ის, Z 8-ისა და D5300-ის ფერის პროფილები", + "Raws from the Nikon Z 6II, Z 8 and D5300 now start from a colour profile built from a few hundred photos from each camera, the same way the": "Nikon Z 6II, Z 8 და D5300 კამერების RAW ფაილები ახლა იწყება ფერის პროფილიდან, რომელიც თითოეული კამერის რამდენიმე ასეული ფოტოთია აგებული, ისევე,", + "Sony and Fujifilm profiles were made, instead of fitting each photo's colour on its own. Colours that one photo": "როგორც Sony-სა და Fujifilm-ის პროფილები შეიქმნა, ნაცვლად იმისა, რომ თითოეული ფოტოს ფერი ცალკე მოერგოს. ფერები, რომლებიც ერთ ფოტოში", + "shows only a little of come out closer to the camera's JPEG.": "მხოლოდ ცოტაა, კამერის JPEG-თან უფრო ახლოს გამოდის.", + "Closer camera colour for lens-corrected raws": "უფრო ზუსტი კამერის ფერი ობიექტივით კორექტირებული RAW ფაილებისთვის", + "Raws from cameras that correct their own JPEG for lens distortion (Panasonic and Fujifilm with that setting on, the": "იმ კამერების RAW ფაილები, რომლებიც საკუთარ JPEG-ში ობიექტივის დეფორმაციას ასწორებს (Panasonic და Fujifilm ამ პარამეტრის ჩართვისას,", + "Sony A7R IVA) now start from colours closer to the camera's. The starting look was being fitted against a JPEG that": "Sony A7R IVA), ახლა კამერისაზე უფრო ახლო ფერებით იწყება. საწყისი იერი ერგებოდა JPEG-ს, რომელიც კიდეებთან RAW-ს", + "didn't line up with the raw near the edges. Photos you already imported pick this up when their previews are rebuilt.": "არ ემთხვეოდა. უკვე იმპორტირებული ფოტოები ამას მიიღებს, როცა მათი წინასწარი ხედები ხელახლა შეიქმნება.", + "HDR merges of moving lights, and many brackets at once": "მოძრავი სინათლეების HDR გაერთიანება და ბევრი ექსპოზიციის სერია ერთად", + "A star, the moon or a light that moves between the photos of a bracket (a night bracket on a tripod) no longer": "ვარსკვლავი, მთვარე ან სინათლე, რომელიც სერიის ფოტოებს შორის მოძრაობს (ღამის სერია შტატივზე), აღარ", + "leaves a black hole where the middle photo had it clipped. With Deghost, the brightest photo's copy of it in a": "ტოვებს შავ ხვრელს იქ, სადაც შუა ფოტოში ის მოკვეთილი იყო. აჩრდილების მოცილებისას მისი ასლი ყველაზე ნათელი ფოტოდან", + "dark sky is now removed too.": "ბნელ ცაზე ახლა ასევე მოცილდება.", + "Photo ▸ Photo Merge ▸ HDR for Each Bracket Set merges every bracket among the selected photos with the last HDR": "ფოტო → ფოტოების გაერთიანება → HDR ექსპოზიციის თითოეული სერიისთვის მონიშნულ ფოტოებში ყველა სერიას აერთიანებს ბოლო HDR", + "settings, one after the other: each stack, and photos taken less than a second apart at different exposures.": "პარამეტრებით, ერთმანეთის მიყოლებით: თითოეულ დასტას და სხვადასხვა ექსპოზიციით ერთ წამზე ნაკლები ინტერვალით გადაღებულ ფოტოებს.", + "From the command line: `lightcraft-cli merge hdr-batch FOLDER`.": "ბრძანების სტრიქონიდან: `lightcraft-cli merge hdr-batch FOLDER`.", + "Merging uses about a quarter less memory: three 67 MP raws need 3.8 GB instead of 4.8 GB.": "გაერთიანება დაახლოებით მეოთხედით ნაკლებ მეხსიერებას იყენებს: სამ 67 MP RAW ფაილს 4.8 GB-ის ნაცვლად 3.8 GB სჭირდება.", + "XMP sidecars catch up after a network share comes back": "XMP თანმხლები ფაილები ქსელური საქაღალდის დაბრუნების შემდეგ ახლდება", + "With automatic XMP writing on, an edit to a photo whose folder can't be written (a network share that dropped": "XMP-ის ავტომატური ჩაწერის ჩართვისას ფოტოს რედაქტირება, რომლის საქაღალდეშიც ჩაწერა შეუძლებელია (გათიშული", + "out, a folder that went read-only) used to be written only to the library, with a line in the log, so the sidecar": "ქსელური საქაღალდე, მხოლოდ წაკითხვადი გამხდარი საქაღალდე), ადრე მხოლოდ ბიბლიოთეკაში იწერებოდა, ჟურნალში ერთი სტრიქონით, ამიტომ თანმხლები ფაილი", + "stayed behind the edit. LightCraft now says once that the sidecars are waiting, tries again every few seconds once": "რედაქტირებას ჩამორჩებოდა. ახლა LightCraft ერთხელ გატყობინებთ, რომ თანმხლები ფაილები ელოდება, ფაილების ხელმისაწვდომობისთანავე ყოველ რამდენიმე წამში", + "the files are reachable, and says when they're written. `library.retrySidecars` does it on request.": "ხელახლა ცდილობს და გატყობინებთ, როცა ისინი ჩაიწერება. `library.retrySidecars` ამას მოთხოვნისას აკეთებს.", + "A damaged or crafted raw can no longer make LightCraft set aside gigabytes of memory before finding out the file is": "დაზიანებულ ან სპეციალურად შექმნილ RAW ფაილს აღარ შეუძლია LightCraft-ს გიგაბაიტობით მეხსიერება დააჯავშნინოს, სანამ ის ფაილის გაუმართაობას", + "bad (issue #1512): a compressed PEF whose data is too short for the size it declares, an uncompressed TIFF-based": "აღმოაჩენს (ხარვეზი #1512): შეკუმშული PEF, რომლის მონაცემები გამოცხადებული ზომისთვის მეტისმეტად მოკლეა, შეუკუმშავი TIFF-ზე დაფუძნებული", + "raw whose tile claims far more samples than it holds, and an ARW6 with a broken tile are refused first. All 74": "RAW, რომლის ფილა ბევრად მეტ ნიმუშს აცხადებს, ვიდრე შეიცავს, და ARW6 დაზიანებული ფილით, წინასწარ უარყოფილია. სატესტო კორპუსის", + "files in the test corpus still decode.": "74-ვე ფაილი კვლავ დეკოდირდება.", + "Thumbnails and previews are written to the cache on disk by one background writer instead of a new thread for": "ესკიზებსა და წინასწარ ხედებს დისკზე არსებულ ქეშში ერთი ფონური ჩამწერი წერს, ნაცვლად ყოველი გამოსახულებისთვის ახალი ნაკადისა", + "each image (issue #1522). When renders come in faster than the disk takes them, at most 128 MB of images wait;": "(ხარვეზი #1522). როცა რენდერები უფრო სწრაფად მოდის, ვიდრე დისკი იღებს, მაქსიმუმ 128 MB გამოსახულება ელოდება;", + "past that a write is skipped (the image stays in memory and is written by a later render), so a slow disk can't": "ამის იქით ჩაწერა გამოტოვდება (გამოსახულება მეხსიერებაში რჩება და მას მომდევნო რენდერი ჩაწერს), ამიტომ ნელ დისკს", + "pile up threads and memory.": "აღარ შეუძლია ნაკადებისა და მეხსიერების დაგროვება.", + "Saving the catalog and resuming a model download no longer write through a link left at the temporary file's": "კატალოგის შენახვა და მოდელის ჩამოტვირთვის გაგრძელება აღარ წერს დროებითი ფაილის სახელით დატოვებულ ბმულში", + "name (`catalog.snap.tmp`, `model.onnx.part`): the link is removed and a new file made in its place, so the file it": "(`catalog.snap.tmp`, `model.onnx.part`): ბმული იშლება და მის ადგილას ახალი ფაილი იქმნება, ამიტომ ფაილი, რომელზეც ის", + "pointed to is never changed (issue #1502).": "მიუთითებდა, არასოდეს იცვლება (ხარვეზი #1502).", + "A photo whose file was replaced (Reload Changed Files after an outside edit) no longer keeps the faces recognition": "ფოტო, რომლის ფაილიც შეიცვალა (შეცვლილი ფაილების ხელახლა ჩატვირთვა გარე რედაქტირების შემდეგ), აღარ ინახავს ამოცნობის მიერ", + "made from the old pixels: they are made again from the new file, and a scan still busy with the old file when it": "ძველი პიქსელებიდან შექმნილ სახეებს: ისინი ახალი ფაილიდან ხელახლა იქმნება, ხოლო სკანირება, რომელიც ცვლილებისას ჯერ კიდევ ძველ ფაილს ამუშავებდა,", + "changed doesn't put its faces on the new one (issue #1524).": "თავის სახეებს ახალს აღარ ადებს (ხარვეზი #1524).", + "Settings stays put when you change tabs": "პარამეტრები ადგილზე რჩება ჩანართების გადართვისას", + "The Settings window keeps its top edge and width when you switch tabs, so the tab row no longer jumps around": "პარამეტრების ფანჯარა ჩანართების გადართვისას ზედა კიდესა და სიგანეს ინარჩუნებს, ამიტომ ჩანართების რიგი მაჩვენებლის ქვეშ აღარ ხტის.", + "under the pointer. It used to be centred, so every tab of a different height moved it.": "ადრე ის ცენტრირებული იყო, ამიტომ განსხვავებული სიმაღლის ყოველი ჩანართი მას ამოძრავებდა.", + "Layout image over the loupe": "განლაგების გამოსახულება ლუპაზე", + "View ▸ Loupe Overlay ▸ Choose Layout Image… draws a PNG with transparency over the photo in the loupe, such as": "ხედი → ლუპის ზედდება → განლაგების გამოსახულების არჩევა… ლუპაში ფოტოს ზემოთ გამჭვირვალობიან PNG-ს ხატავს, მაგალითად", + "a magazine cover's masthead and cover lines, so you can frame a shot for the page it is made for. It fits inside": "ჟურნალის ყდის სათაურსა და წარწერებს, რათა კადრი იმ გვერდისთვის დააკომპოზიციოთ, რომლისთვისაც კეთდება. ის ფოტოში ეტევა,", + "the photo, follows zoom and pan, and ⌥⌘O shows or hides it. The same menu sets its opacity and a matte that": "მასშტაბსა და გადაადგილებას მისდევს, ⌥⌘O კი მას აჩენს ან მალავს. იმავე მენიუში ყენდება მისი გაუმჭვირვალობა და მატი, რომელიც", + "darkens the photo outside it. The layout stays chosen across launches.": "ფოტოს მის გარეთ ამუქებს. არჩეული განლაგება გაშვებებს შორის ნარჩუნდება.", + "Smaller JPEG exports": "უფრო მცირე JPEG ექსპორტი", + "JPEG exports are 12–14 % smaller at the same quality, with exactly the same pixels (issue #1373): each file now": "JPEG ექსპორტი იმავე ხარისხით 12–14 %-ით მცირეა, ზუსტად იგივე პიქსელებით (ხარვეზი #1373): ყოველ ფაილს ახლა", + "carries Huffman tables made for its own picture instead of the standard example tables. Every viewer opens them": "საკუთარი გამოსახულებისთვის შექმნილი Huffman-ის ცხრილები აქვს სტანდარტული სანიმუშო ცხრილების ნაცვლად. ნებისმიერი დამთვალიერებელი მათ", + "as before.": "ისე ხსნის, როგორც ადრე.", + "A photo whose Defringe amount was stored far past the sliders' 20 (in a damaged catalog or sidecar) no longer": "ფოტო, რომლის კიდის შარავანდის მოცილების სიძლიერე სლაიდერის 20-ს ბევრად აღემატებოდა (დაზიანებულ კატალოგში ან თანმხლებ ფაილში),", + "crashes LightCraft each time it renders: the amount acts as 20.": "ყოველი რენდერისას LightCraft-ის ავარიულ დახურვას აღარ იწვევს: სიძლიერე 20-ის ტოლად მოქმედებს.", + "Lens names for Nikon DSLR raws": "ობიექტივის სახელები Nikon DSLR-ის RAW ფაილებისთვის", + "Photos from Nikon DSLRs like the D700, D750, D80 or D5300 now show which lens they were taken with, for example": "Nikon DSLR-ების (მაგ. D700, D750, D80 ან D5300) ფოტოები ახლა აჩვენებს, რომელი ობიექტივით არის გადაღებული, მაგალითად „24.0-70.0 mm f/2.8“.", + "\"24.0-70.0 mm f/2.8\". Those cameras don't write a lens name, so the lens field was empty and you couldn't filter or": "ეს კამერები ობიექტივის სახელს არ წერს, ამიტომ ობიექტივის ველი ცარიელი იყო და ობიექტივით ვერც გაფილტრავდით და ვერც მოძებნიდით.", + "search by lens. LightCraft now reads the lens range Nikon keeps in its own maker note, the way Lightroom shows a": "LightCraft ახლა კითხულობს ობიექტივის დიაპაზონს, რომელსაც Nikon საკუთარ მწარმოებლის ჩანაწერში ინახავს, ისე, როგორც Lightroom აჩვენებს", + "lens it doesn't have a name for. Newly imported photos show it.": "ობიექტივს, რომლის სახელიც არ იცის. ამას ახლად იმპორტირებული ფოტოები აჩვენებს.", + "Import when a card is connected": "იმპორტი ბარათის მიერთებისას", + "Settings → Import → Cameras and Cards has an option to open the import review as soon as a camera or memory card": "პარამეტრები → იმპორტი → კამერები და ბარათები გთავაზობთ ვარიანტს, რომ იმპორტის განხილვა გაიხსნას, როგორც კი კამერა ან მეხსიერების ბარათი", + "is connected, the same review File → Import from Device opens. It's off by default. A card that's already in when": "მიერთდება — იმავე განხილვას, რომელსაც ფაილი → იმპორტი მოწყობილობიდან ხსნის. ნაგულისხმევად გამორთულია. ბარათი, რომელიც LightCraft-ის გაშვებისას", + "LightCraft starts doesn't ask, and if a dialog is open or an import is running it waits until that's done.": "უკვე ჩადებულია, არაფერს კითხულობს, ხოლო თუ დიალოგი ღიაა ან იმპორტი მიმდინარეობს, ის მის დასრულებას ელოდება.", + "Photos deleted (or moved) by another app no longer stay in a Local folder, failing to load and logging an error": "სხვა აპის მიერ წაშლილი (ან გადატანილი) ფოტოები აღარ რჩება ლოკალურ საქაღალდეში, სადაც ვერ იტვირთებოდა და", + "each time you look (issue #1392): the next time you browse the folder, in a later session, they're left out. A photo you had rated, flagged or": "ყოველი დათვალიერებისას ჟურნალში შეცდომას წერდა (ხარვეზი #1392): საქაღალდის შემდეგი დათვალიერებისას, მომდევნო სესიაში, ისინი გამოტოვებულია. ფოტო, რომელიც შეაფასეთ, დროშით მონიშნეთ ან", + "edited stays, marked missing, so its changes aren't lost; photos in My Photos are unchanged.": "დაარედაქტირეთ, რჩება, დაკარგულად მონიშნული, ამიტომ მისი ცვლილებები არ იკარგება; ჩემს ფოტოებში არსებული ფოტოები უცვლელია.", + "Full-resolution panoramas": "სრული გარჩევადობის პანორამები", + "Panorama and HDR Panorama merges keep the resolution of their photos instead of stopping at 40 megapixels": "პანორამისა და HDR პანორამის გაერთიანება ფოტოების გარჩევადობას ინარჩუნებს, ნაცვლად 40 მეგაპიქსელზე გაჩერებისა", + "(issue #1455), up to 512 MP and 65,000 pixels on the long edge, as in Lightroom. When the full size needs more": "(ხარვეზი #1455), 512 MP-მდე და გრძელ კიდეზე 65,000 პიქსელამდე, როგორც Lightroom-ში. როცა სრულ ზომას კომპიუტერზე არსებულზე მეტი", + "memory than the computer has, the panorama is made as large as fits (five 51 MP photos: up to 166 MP with": "მეხსიერება სჭირდება, პანორამა იმხელა იქმნება, რამხელაც ეტევა (ხუთი 51 MP ფოტო: 166 MP-მდე 16 GB-ით, 355 MP 32 GB-ით),", + "16 GB, 355 MP with 32 GB) and the message says so. The merge also frees each photo's pixels once they are": "და შეტყობინება ამას აღნიშნავს. გაერთიანება ასევე ათავისუფლებს თითოეული ფოტოს პიქსელებს მათი პროეცირებისთანავე, ამიტომ", + "projected, so it needs less memory than before at any size (an 81 MP stitch: 4.4 GB instead of 6.2 GB).": "ნებისმიერ ზომაზე ადრეზე ნაკლებ მეხსიერებას საჭიროებს (81 MP-იანი გაკერვა: 6.2 GB-ის ნაცვლად 4.4 GB).", + "Nikon D600, D610 and D5000": "Nikon D600, D610 და D5000", + "Raws from the Nikon D600, D610 and D5000 no longer show a bright line down the right edge (issue #1627). Their": "Nikon D600, D610 და D5000 კამერების RAW ფაილები მარჯვენა კიდეზე აღარ აჩვენებს ნათელ ხაზს (ხარვეზი #1627). მათი", + "sensor data runs a few columns of filler past the picture, which stayed in the image; these bodies now develop": "სენსორის მონაცემები კადრის მიღმა შემავსებლის რამდენიმე სვეტს შეიცავს, რომელიც გამოსახულებაში რჩებოდა; ეს კამერები ახლა", + "at the camera JPEG's size (6016 × 4016 for the D600 and D610, 4288 × 2848 for the D5000, as the D90 already": "კამერის JPEG-ის ზომით მუშავდება (6016 × 4016 D600-სა და D610-ისთვის, 4288 × 2848 D5000-ისთვის, როგორც D90 უკვე", + "did). On the D600 and D610 the white level is also measured inside the picture, so the filler can't pass for": "მუშავდებოდა). D600-სა და D610-ზე თეთრის დონე ასევე კადრის შიგნით იზომება, ამიტომ შემავსებელი ვეღარ ჩაითვლება", + "clipped highlights.": "მოკვეთილ ღია ტონებად.", + "More Canon EOS R6 Mark II C-RAW files decode": "Canon EOS R6 Mark II-ის მეტი C-RAW ფაილი დეკოდირდება", + "Some EOS R6 Mark II C-RAW files (about 1 in 50 in one photographer's library) opened as their preview with": "EOS R6 Mark II-ის ზოგიერთი C-RAW ფაილი (ერთი ფოტოგრაფის ბიბლიოთეკაში დაახლოებით 50-დან 1) მხოლოდ წინასწარი ხედით იხსნებოდა შეტყობინებით", + "\"Canon CRX adaptive QP value 172\" or \"175\". They now decode from the sensor data. Photos imported before this": "„Canon CRX adaptive QP value 172“ ან „175“. ახლა ისინი სენსორის მონაცემებიდან დეკოდირდება. ამაზე ადრე იმპორტირებული ფოტოები", + "switch over with Photo ▸ Reload from Disk.": "გადაერთვება ბრძანებით ფოტო → დისკიდან ხელახლა ჩატვირთვა.", + "Nikon raws without coloured edge bars": "Nikon-ის RAW ფაილები ფერადი ზოლების გარეშე კიდეზე", + "Raws from older Nikon bodies no longer show a thin coloured or dark bar along one edge (the right edge, or the top": "ძველი Nikon კამერების RAW ფაილები აღარ აჩვენებს ვიწრო ფერად ან მუქ ზოლს ერთ კიდეზე (მარჯვენა კიდეზე, ან ზედა კიდეზე", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914,": "პორტრეტული ფოტოს შემთხვევაში): სენსორის დაფარული სვეტები სურათის ნაწილად მუშავდებოდა (ხარვეზები #976, #914,", + "#1236). The D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,": "#1236). D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,", + "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s and Nikon 1 V1 now show": "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s და Nikon 1 V1 ახლა აჩვენებს", + "the area the camera itself frames, a few pixels smaller than before.": "იმ არეს, რომელსაც თავად კამერა ჩარჩოში სვამს, ადრინდელზე რამდენიმე პიქსელით პატარას.", + "An empty library leads to Import": "ცარიელი ბიბლიოთეკა იმპორტისკენ მიგიძღვით", + "A library with no photos now opens on the Photo Grid with the sidebar (Square Grid stays as it is), instead of a": "ფოტოების გარეშე ბიბლიოთეკა ახლა ფოტოების ბადეზე იხსნება გვერდითი ზოლით (კვადრატული ბადე უცვლელი რჩება), ნაცვლად", + "Detail view that pointed at an empty grid. The grid and Detail view offer Import Photos… and, in the desktop app,": "დეტალური ხედისა, რომელიც ცარიელ ბადეზე მიუთითებდა. ბადე და დეტალური ხედი გთავაზობს ღილაკებს „ფოტოების იმპორტი…“ და, დესკტოპ აპში,", + "Import Lightroom Catalog… as buttons, and say that photos (and, in the desktop app, folders) can be dropped into": "„Lightroom-ის კატალოგის იმპორტი…“ და გეუბნებათ, რომ ფოტოები (და, დესკტოპ აპში, საქაღალდეები) შეგიძლიათ ჩააგდოთ", + "the window. The shortcut they show is the one Import Photos… has now.": "ფანჯარაში. ნაჩვენები მალსახმობი ის არის, რომელიც ახლა „ფოტოების იმპორტი…“-ს აქვს.", + "The top bar has an Import button, beside Export, in every library.": "ზედა ზოლს ყველა ბიბლიოთეკაში იმპორტის ღილაკი აქვს, ექსპორტის გვერდით.", + "One kind of button": "ერთი სახის ღილაკი", + "Dialogs' buttons and About's Discord link are drawn by one button component: primary (filled with the accent),": "დიალოგების ღილაკებს და „პროგრამის შესახებ“-ის Discord-ის ბმულს ერთი ღილაკის კომპონენტი ხატავს: ძირითადი (აქცენტის ფერით შევსებული),", + "secondary, danger (filled red) and ghost, in three sizes, with an icon or without, and an icon alone (named for": "მეორეხარისხოვანი, საშიში (წითლად შევსებული) და გამჭვირვალე, სამ ზომაში, ხატულით ან მის გარეშე, და მხოლოდ ხატულა (ეკრანის", + "screen readers). Each darkens a little when hovered and more when pressed, shows a ring where the keyboard is, and": "წამკითხველებისთვის სახელდებული). თითოეული ოდნავ მუქდება კურსორის მიტანისას და უფრო მეტად — დაჭერისას, აჩვენებს რგოლს იქ, სადაც კლავიატურის ფოკუსია, და", + "its text reads at 4.5:1 or more on its fill in every theme. Dialog buttons are 30 points tall, like the welcome's.": "მისი ტექსტი ყოველ თემაში შევსებაზე 4.5:1 ან მეტი კონტრასტით იკითხება. დიალოგის ღილაკები 30 წერტილის სიმაღლისაა, როგორც მისასალმებელი ეკრანისა.", + "A dialog's confirm button says it's the next step": "დიალოგის დადასტურების ღილაკი აჩვენებს, რომ ის შემდეგი ნაბიჯია", + "In dialogs, the confirm button is on the right with Cancel to its left, and filled with the accent when it makes or": "დიალოგებში დადასტურების ღილაკი მარჯვნივაა, გაუქმება — მის მარცხნივ, და აქცენტის ფერით ივსება, როცა რაიმეს ქმნის ან", + "brings in something (Import N Photos, Merge, Save, Create, Download…). Delete and Remove stay plain, so a destructive": "შემოაქვს (N ფოტოს იმპორტი, შერწყმა, შენახვა, შექმნა, ჩამოტვირთვა…). წაშლა და მოშორება უბრალო რჩება, ამიტომ დესტრუქციული", + "choice is never the eye-catching default.": "არჩევანი არასოდეს არის თვალშისაცემი ნაგულისხმევი.", + "Straight brush strokes with ⇧-click": "ფუნჯის სწორი შტრიხები ⇧-დაწკაპებით", + "With the brush, click once, then ⇧-click somewhere else: the brush paints a straight line between the two, and": "ფუნჯით ერთხელ დაწკაპეთ, შემდეგ ⇧-ით დაწკაპეთ სხვაგან: ფუნჯი მათ შორის სწორ ხაზს ხატავს, შემდგომი", + "further ⇧-clicks carry on from the last point, as in Lightroom. Change the brush size, feather or flow before the": "⇧-დაწკაპებები კი ბოლო წერტილიდან აგრძელებს, როგორც Lightroom-ში. ⇧-დაწკაპებამდე შეცვალეთ ფუნჯის ზომა, კიდეების შერბილება ან", + "⇧-click and the line tapers from the old values to the new ones. The whole line is one undo step.": "ნაკადი და ხაზი ძველი მნიშვნელობებიდან ახლისკენ გადავა. მთელი ხაზი ერთი დაბრუნების ნაბიჯია.", + "`mask.brushStroke {connect: true}` does the same for agents.": "`mask.brushStroke {connect: true}` იგივეს აკეთებს აგენტებისთვის.", + "Local folders you browse are kept": "ლოკალური საქაღალდეები, რომლებსაც ათვალიერებთ, ინახება", + "Browsing a folder under Local now records it as browsed, so the photos in folders you use aren't forgotten after": "ლოკალურში საქაღალდის დათვალიერება ახლა მას დათვალიერებულად აღრიცხავს, ამიტომ თქვენ მიერ გამოყენებული საქაღალდეების ფოტოები აღარ ივიწყება", + "the number of days set in Settings → Performance. Only the `library.browse` command recorded it before, so a": "„პარამეტრები → წარმადობა“-ში მითითებული დღეების შემდეგ. ადრე ამას მხოლოდ `library.browse` ბრძანება აღრიცხავდა, ამიტომ", + "folder browsed every day from the sidebar was forgotten anyway and read again from scratch on the next visit,": "გვერდითი ზოლიდან ყოველდღე დათვალიერებული საქაღალდე მაინც ივიწყებოდა და მომდევნო ვიზიტისას თავიდან იკითხებოდა,", + "which is slow on a network share.": "რაც ქსელურ საქაღალდეზე ნელია.", + "Hard-edged Heal and Clone spots": "მკვეთრკიდიანი აღდგენისა და კლონირების ლაქები", + "A spot with Feather at 0 no longer draws black pixels exactly on its radius. This also fixes spots at 0% Opacity": "ლაქა, რომლის კიდეების შერბილება 0-ზეა, აღარ ხატავს შავ პიქსელებს ზუსტად თავის რადიუსზე. ეს ასევე ასწორებს 0% გაუმჭვირვალობის", + "changing pixels along their edge. The hard edge now leaves pixels on the radius unchanged.": "ლაქებს, რომლებიც კიდის გასწვრივ პიქსელებს ცვლიდა. მკვეთრი კიდე ახლა რადიუსზე მდებარე პიქსელებს უცვლელს ტოვებს.", + "Search finds people": "ძიება ადამიანებს პოულობს", + "Typing a person's name in Search Photos finds the photos with that named face (issue #1449).": "ფოტოების ძიებაში ადამიანის სახელის აკრეფა პოულობს ფოტოებს ამ სახელით მონიშნული სახით (ხარვეზი #1449).", + "Quotes keep several words together: `person:\"Jane Doe\"` finds exactly that person, `\"jane doe\"` those words side": "ბრჭყალები რამდენიმე სიტყვას ერთად ინახავს: `person:\"Jane Doe\"` პოულობს ზუსტად ამ ადამიანს, `\"jane doe\"` — ამ სიტყვებს გვერდიგვერდ,", + "by side, and `keyword:\"new york\"` a keyword of two words.": "ხოლო `keyword:\"new york\"` — ორსიტყვიან საკვანძო სიტყვას.", + "Where the camera focused": "სად დააფოკუსა კამერამ", + "**View ▸ Show Focus Point** (⌥F) draws the autofocus frame the camera recorded over the photo, in Detail, Compare": "**ხედი → ფოკუსის წერტილის ჩვენება** (⌥F) ფოტოს ზემოთ ხატავს კამერის მიერ ჩაწერილ ავტოფოკუსის ჩარჩოს დეტალურ ხედში, შედარებასა", + "and Survey, following rotation and crops; the Info panel says how it focused (`AF-C · Wide · Animal Eye Tracking`).": "და მიმოხილვაში, მობრუნებისა და ჩამოჭრის გათვალისწინებით; ინფორმაციის პანელი აჩვენებს, როგორ მოხდა ფოკუსირება (`AF-C · Wide · Animal Eye Tracking`).", + "Lightroom has no such view.": "Lightroom-ს ასეთი ხედი არ აქვს.", + "**Z zooms to it**: Toggle Zoom centres on the focus point, so checking that the subject is sharp is one key": "**Z მასზე ადიდებს**: მასშტაბის გადართვა ფოკუსის წერტილზე ცენტრირდება, ამიტომ საგნის სიმკვეთრის შემოწმება ერთი კლავიშია", + "(View ▸ Zoom to Focus Point turns this off). Photos without a point zoom as before.": "(ხედი → ფოკუსის წერტილამდე გადიდება ამას გამორთავს). წერტილის გარეშე ფოტოები ისე დიდდება, როგორც ადრე.", + "Sony α1 (ILCE-1) and A7S III (ILCE-7SM3) raws for now; manual-focus shots and Wide shots that only report the frame": "ჯერჯერობით Sony α1 (ILCE-1) და A7S III (ILCE-7SM3) RAW ფაილები; ხელით ფოკუსირებული კადრები და Wide კადრები, რომლებიც მხოლოდ კადრის ცენტრს", + "centre show nothing. More cameras will follow. Details: [focus-points.md](focus-points.md).": "აცნობებს, არაფერს აჩვენებს. სხვა კამერებიც დაემატება. დეტალები: [focus-points.md](focus-points.md).", + "**Photos already in your library get theirs in the background**: LightCraft reads just the few kilobytes of each": "**ბიბლიოთეკაში უკვე არსებული ფოტოები თავისას ფონურად იღებს**: LightCraft კითხულობს თითოეული ფაილის მხოლოდ იმ რამდენიმე კილობაიტს,", + "file that hold the focus point (about 100 photos a second from a spinning disk), with a *Reading focus points* row": "რომელიც ფოკუსის წერტილს შეიცავს (მბრუნავი დისკიდან დაახლოებით 100 ფოტო წამში), აქტივობების დასტაში *ფოკუსის წერტილები იკითხება* სტრიქონით,", + "in the activity stack you can stop. Photo ▸ Read Focus Points runs it by hand.": "რომლის შეჩერებაც შეგიძლიათ. ფოტო → ფოკუსის წერტილების წაკითხვა მას ხელით უშვებს.", + "Cleaner HDR merges": "უფრო სუფთა HDR გაერთიანება", + "Bright windows in an HDR made with Photo ▸ Photo Merge ▸ HDR no longer take a magenta tinge from the brighter": "ფოტო → ფოტოების გაერთიანება → HDR-ით შექმნილ HDR-ში ნათელი ფანჯრები აღარ იღებს მეწამულ ელფერს უფრო ნათელი ფოტოებიდან", + "photos along the areas they clipped: right next to a clipped area, a photo's colour isn't used. It showed most when": "იმ უბნების გასწვრივ, სადაც ისინი მოკვეთილი იყო: მოკვეთილი უბნის უშუალო სიახლოვეს ფოტოს ფერი არ გამოიყენება. ეს ყველაზე მეტად ჩანდა,", + "the highlights were darkened or saturated.": "როცა ღია ტონები დამუქებული ან გაჯერებული იყო.", + "The same photos give the same HDR whatever order they are selected in; before, a different order could change a": "ერთი და იგივე ფოტოები ერთსა და იმავე HDR-ს იძლევა, რა თანმიმდევრობითაც არ უნდა მოინიშნოს; ადრე სხვა თანმიმდევრობას", + "few pixels.": "რამდენიმე პიქსელის შეცვლა შეეძლო.", + "HDR merges keep the white balance": "HDR გაერთიანება თეთრის ბალანსს ინარჩუნებს", + "An HDR merged from raws that LightCraft colours from the camera's JPEG (CR2, NEF, ARW…) now opens at the same": "RAW ფაილებიდან გაერთიანებული HDR, რომლებსაც LightCraft კამერის JPEG-ის მიხედვით აფერადებს (CR2, NEF, ARW…), ახლა იხსნება", + "As Shot temperature and tint as its photos, and changing the white balance no longer turns it green. Sony ARW": "იმავე „როგორც გადაღებულია“ ტემპერატურითა და ტონირებით, როგორც მისი ფოტოები, და თეთრის ბალანსის შეცვლა მას აღარ ამწვანებს. Sony ARW", + "merges used to open at about 7000 K / +115 where the photos show 4000–5300 K / +8. HDRs merged before this keep": "გაერთიანებები ადრე იხსნებოდა დაახლოებით 7000 K / +115-ზე, მაშინ როცა ფოტოები 4000–5300 K / +8-ს აჩვენებს. ამაზე ადრე გაერთიანებული HDR-ები", + "their old white balance; merge them again.": "ძველ თეთრის ბალანსს ინარჩუნებს; გააერთიანეთ ისინი ხელახლა.", + "Edits keep up in a large library": "რედაქტირება დიდ ბიბლიოთეკაშიც არ ჩამორჩება", + "A small edit (a keyword, a rating, a flag, a slider) no longer has the grid's list worked out again from every": "მცირე რედაქტირება (საკვანძო სიტყვა, შეფასება, დროშა, სლაიდერი) ბადის სიას აღარ ითვლის თავიდან ყველა ფოტოდან: ხელახლა მოწმდება", + "photo: only the photos the edit touched are asked about again and put at their place in the order. In a library of": "მხოლოდ ის ფოტოები, რომლებსაც რედაქტირება შეეხო, და ისინი თანმიმდევრობაში თავის ადგილას დგება. 67,000 ფოტოს ბიბლიოთეკაში", + "67,000 photos that step went from 37 ms to under 1 ms. Still worked out whole: an edit to more than 256 photos, a": "ეს ნაბიჯი 37 ms-დან 1 ms-ზე ნაკლებამდე შემცირდა. კვლავ მთლიანად ითვლება: 256-ზე მეტი ფოტოს რედაქტირება,", + "change to an album, a stack or the keyword list, an album shown in its own order, Recently Added, Missing Photos,": "ალბომის, დასტის ან საკვანძო სიტყვების სიის ცვლილება, საკუთარი თანმიმდევრობით ნაჩვენები ალბომი, ბოლოს დამატებული, დაკარგული ფოტოები", + "and a view that asks about \"the last N days\".": "და ხედი, რომელიც „ბოლო N დღეს“ ეკითხება.", + "With no filter set, the count of the source is taken from the list instead of from a second pass over the library.": "როცა ფილტრი დაყენებული არ არის, წყაროს რაოდენობა სიიდან აიღება ბიბლიოთეკის მეორედ გავლის ნაცვლად.", + "The side panels keep a tally an edit cannot have changed: a rating or a slider changes none of the folders,": "გვერდითი პანელები ინახავს დათვლას, რომელსაც რედაქტირება ვერ შეცვლიდა: შეფასება ან სლაიდერი არ ცვლის საქაღალდეებს,", + "keywords, dates, people and counts; a keyword leaves the folders, the dates and the counts as they are. With both": "საკვანძო სიტყვებს, თარიღებს, ადამიანებსა და რაოდენობებს; საკვანძო სიტყვა საქაღალდეებს, თარიღებსა და რაოდენობებს უცვლელს ტოვებს. ორივე", + "side panels open, the frame after a keyword went from about 156 ms to about 54 ms in that library (2 ms with the": "ღია გვერდითი პანელით საკვანძო სიტყვის შემდგომი კადრი იმ ბიბლიოთეკაში დაახლოებით 156 ms-დან დაახლოებით 54 ms-მდე შემცირდა", + "panels closed, from 71 ms).": "(დახურული პანელებით 2 ms, 71 ms-ის ნაცვლად).", + "The count beside each smart album in the left panel follows an edit the same way: the album asks only the photos": "მარცხენა პანელში ყოველი სმარტ-ალბომის გვერდით რაოდენობა რედაქტირებას ასევე მისდევს: ალბომი ამოწმებს მხოლოდ რედაქტირებით შეხებულ", + "the edit touched, where it asked every photo of the library after each edit (about 25 ms an album in that library).": "ფოტოებს, მაშინ როცა ადრე ყოველი რედაქტირების შემდეგ ბიბლიოთეკის ყველა ფოტოს ამოწმებდა (იმ ბიბლიოთეკაში დაახლოებით 25 ms ალბომზე).", + "With that, the frame after a keyword is at about 29 ms there. New rules, a change to an album or the keyword list,": "ამით საკვანძო სიტყვის შემდგომი კადრი იქ დაახლოებით 29 ms-ია. ახალი წესები, ალბომის ან საკვანძო სიტყვების სიის ცვლილება,", + "an edit to more than 256 photos, and each new minute for an album that asks about \"the last N days\" are still": "256-ზე მეტი ფოტოს რედაქტირება და ყოველი ახალი წუთი ალბომისთვის, რომელიც „ბოლო N დღეს“ ეკითხება, კვლავ", + "counted from every photo.": "ყველა ფოტოდან ითვლება.", + "Still tallied from every photo on each edit: the filter bar's lists of cameras, lenses and keywords.": "ყოველი რედაქტირებისას კვლავ ყველა ფოტოდან ითვლება: ფილტრების ზოლის კამერების, ობიექტივებისა და საკვანძო სიტყვების სიები.", + "A view can hold its photos until you refresh it": "ხედს შეუძლია ფოტოების შენარჩუნება, სანამ მას არ განაახლებთ", + "View ▸ Hold View Until Refreshed (off unless you turn it on; kept with the library). With it on, an edit that makes": "ხედი → ხედის შენარჩუნება განახლებამდე (გამორთულია, სანამ არ ჩართავთ; ინახება ბიბლიოთეკასთან ერთად). ჩართულისას რედაქტირება, რის შემდეგაც", + "a photo stop matching the view keeps it in the view: a keyword given in a smart album of photos without keywords,": "ფოტო ხედს აღარ შეესაბამება, მას ხედში ტოვებს: საკვანძო სიტყვის გარეშე ფოტოების სმარტ-ალბომში მინიჭებული საკვანძო სიტყვა,", + "a flag taken off in Picks, a rating that falls under the filter bar's. With it off, as before, the photo leaves the": "რჩეულებში მოხსნილი დროშა, შეფასება, რომელიც ფილტრების ზოლის შეფასებაზე დაბლა ჩამოვიდა. გამორთულისას, როგორც ადრე, ფოტო", + "grid at once and every photo after it moves up. View ▸ Refresh View (also in the sort menu while the hold is on),": "ბადიდან მაშინვე ქრება და მის შემდეგ ყველა ფოტო ზემოთ ინაცვლებს. ხედი → ხედის განახლება (შენარჩუნების ჩართვისას სორტირების მენიუშიც არის),", + "Reshuffle, another source, filter or sort, or new rules for the smart album shows what matches now.": "ხელახლა არევა, სხვა წყარო, ფილტრი ან სორტირება, ან სმარტ-ალბომის ახალი წესები აჩვენებს, რა შეესაბამება ახლა.", + "Photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder": "ფოტოები, რომლებიც შესაბამისი ხდება, კვლავ მაშინვე ჩნდება, ხოლო ფოტოს წაშლა ან მისი ამოღება ნაჩვენები ალბომიდან ან", + "shown still takes it out of the view.": "საქაღალდიდან მას კვლავ ხედიდანაც აქრობს.", + "The window opens at the size you left it": "ფანჯარა იმ ზომით იხსნება, როგორითაც დატოვეთ", + "LightCraft's window opens at the size it had when you last used it, and zoomed (macOS) / maximized if it was: it": "LightCraft-ის ფანჯარა იხსნება იმ ზომით, რაც ბოლო გამოყენებისას ჰქონდა, და გადიდებული (macOS) / მაქსიმიზებული, თუ ასეთი იყო:", + "used to open at 1600 × 1000 every time. Double-click the top bar to zoom the window, quit, and it is zoomed when": "ადრე ის ყოველთვის 1600 × 1000 ზომით იხსნებოდა. ორჯერ დაწკაპეთ ზედა ზოლზე ფანჯრის გასადიდებლად, გამოდით, და დაბრუნებისას", + "you come back; un-zoom it and it goes back to the size it had before.": "ის გადიდებული იქნება; გააუქმეთ გადიდება და ის წინა ზომას დაუბრუნდება.", + "Full screen is not remembered (the app opens as a window), and neither is where on the desktop the window was:": "სრულეკრანიანი რეჟიმი არ ინახება (პროგრამა ფანჯრად იხსნება), არც ის, სამუშაო მაგიდის რა ადგილას იყო ფანჯარა:", + "the system places it.": "მას სისტემა ათავსებს.", + "On macOS the system does not tell LightCraft when a window is zoomed from the Window menu or resized after a": "macOS-ზე სისტემა LightCraft-ს არ ატყობინებს, როცა ფანჯარა ფანჯრის მენიუდან დიდდება ან გადიდების შემდეგ", + "zoom, so it goes by the window's size, and when in doubt takes the window for a window of the size it has: it": "ზომას იცვლის, ამიტომ ის ფანჯრის ზომით ხელმძღვანელობს და ეჭვის შემთხვევაში მას ამავე ზომის ჩვეულებრივ ფანჯრად თვლის: ის", + "comes back as large as you left it, but not as a zoomed window. That is so after a zoom from the Window menu": "ისეთივე დიდი ბრუნდება, როგორიც დატოვეთ, მაგრამ არა გადიდებული ფანჯრის სახით. ასეა ფანჯრის მენიუდან გადიდების შემდეგ,", + "with the Dock at a side of the screen, or of a window already as wide as the screen. Zoomed by a double-click": "როცა Dock ეკრანის გვერდითაა, ან უკვე ეკრანის სიგანის ფანჯრის შემთხვევაში. ზედა ზოლზე ორმაგი დაწკაპუნებით", + "on the top bar it comes back zoomed. The other way round, a window you drag out until it is as wide as the": "გადიდებული ფანჯარა გადიდებულივე ბრუნდება. პირიქით, ფანჯარა, რომელსაც გაწელავთ, სანამ ის ეკრანის სიგანის", + "screen and nearly as tall counts as zoomed.": "და თითქმის ეკრანის სიმაღლის არ გახდება, გადიდებულად ითვლება.", + "For scripts: a size set with `ui.resize` is remembered like any other, so a script that needs a size sets it.": "სკრიპტებისთვის: `ui.resize`-ით დაყენებული ზომა ისევე ინახება, როგორც ნებისმიერი სხვა, ამიტომ სკრიპტი, რომელსაც კონკრეტული ზომა სჭირდება, თავად აყენებს მას.", + "HDR merges keep the lens correction": "HDR გაერთიანებები ობიექტივის კორექციას ინარჩუნებს", + "An HDR made with Photo ▸ Photo Merge ▸ HDR now keeps the lens correction the photos carry (Sony's, Panasonic's": "ფოტო → ფოტოების გაერთიანება → HDR-ით შექმნილი HDR ახლა ინარჩუნებს ფოტოებში ჩაწერილ ობიექტივის კორექციას (Sony-ის, Panasonic-ის", + "and Leica's, and the one some DNGs carry, e.g. from drones): Optics ▸ Enable Lens Corrections straightens it as it": "და Leica-ს კორექციას, და იმას, რაც ზოგიერთ DNG-შია, მაგ. დრონებიდან): ოპტიკა → ობიექტივის კორექციების ჩართვა მას ისე ასწორებს, როგორც", + "does the photos it was made from. HDRs merged before this don't have it; merge them again.": "ფოტოებს, რომლებიდანაც შეიქმნა. ამაზე ადრე გაერთიანებულ HDR-ებს ეს არ აქვს; გააერთიანეთ ისინი ხელახლა.", + "Portable mode": "პორტატული რეჟიმი", + "A file named `portable.txt` next to the LightCraft program makes it keep its settings, logs and downloaded": "LightCraft-ის პროგრამის გვერდით მდებარე ფაილი `portable.txt` აიძულებს მას, პარამეტრები, ჟურნალები და ჩამოტვირთული", + "models in a `LightCraftData` folder beside it instead of the per-user settings folder (issue #1200), as": "მოდელები გვერდით მდებარე `LightCraftData` საქაღალდეში შეინახოს მომხმარებლის პარამეტრების საქაღალდის ნაცვლად (ხარვეზი #1200), როგორც ამას", + "PhotoCraft does. If that folder can't be written, the usual folder is used and the log says why.": "PhotoCraft აკეთებს. თუ ამ საქაღალდეში ჩაწერა შეუძლებელია, ჩვეული საქაღალდე გამოიყენება და ჟურნალში მიზეზი ჩაიწერება.", + "Importing a preset zip that unpacks to far more than any preset (a \"zip bomb\") is refused with a message naming": "პრესეტების zip-ის იმპორტი, რომელიც გაშლისას ნებისმიერ პრესეტზე ბევრად დიდია („zip-ბომბი“), უარყოფილია შეტყობინებით, რომელიც", + "the file, instead of asking for gigabytes of memory, which could end LightCraft.": "ფაილს ასახელებს, ნაცვლად გიგაბაიტობით მეხსიერების მოთხოვნისა, რასაც LightCraft-ის გათიშვა შეეძლო.", + "A crop of no size (from an agent or a sidecar) no longer gives the Detail view a photo of no size to lay out": "ნულოვანი ზომის ჩამოჭრა (აგენტიდან ან თანმხლები ფაილიდან) დეტალურ ხედს განსალაგებლად აღარ აძლევს ნულოვანი ზომის ფოტოს", + "(its width over its height was 0 / 0, which stopped debug builds); it shows as a single pixel's colour.": "(მისი სიგანე შეფარდებული სიმაღლესთან იყო 0 / 0, რაც გამართვის აწყობებს აჩერებდა); ის ერთი პიქსელის ფერად ჩანს.", + "A crop a hair wide (or of no size), set by an agent or read from a sidecar, no longer crashes or hangs the": "თმის სიგანის (ან ნულოვანი ზომის) ჩამოჭრა, აგენტის მიერ დაყენებული ან თანმხლები ფაილიდან წაკითხული, აღარ თიშავს და აღარ ყინავს", + "render with Clarity, Dehaze, Texture or Highlights / Shadows on: their blurs are held to the picture's size.": "რენდერს, როცა ჩართულია სიცხადე, ბურუსის მოცილება, ტექსტურა ან ღია ტონები / ჩრდილები: მათი გაბუნდოვნება სურათის ზომით შემოიფარგლება.", + "A crop of no size with healing spots or masks no longer crashes the render: samples outside the picture read its": "ნულოვანი ზომის ჩამოჭრა აღდგენის წერტილებით ან ნიღბებით რენდერს აღარ თიშავს: სურათის გარეთ აღებული ნიმუშები მის", + "edge.": "კიდეს კითხულობს.", + "A library whose catalog file was damaged (or edited by hand) in a way that still reads no longer crashes": "ბიბლიოთეკა, რომლის კატალოგის ფაილი ისე დაზიანდა (ან ხელით შეიცვალა), რომ მაინც იკითხება, აღარ თიშავს", + "LightCraft when it shows a stack, or hangs it when a folder is moved: on opening, records are put back under": "LightCraft-ს დასტის ჩვენებისას და აღარ ყინავს მას საქაღალდის გადატანისას: გახსნისას ჩანაწერები საკუთარ", + "their own ids, stacks keep only photos that exist (at least two), folders inside themselves move to the top,": "ID-ებს უბრუნდება, დასტებში მხოლოდ არსებული ფოტოები რჩება (მინიმუმ ორი), საკუთარ თავში მოთავსებული საქაღალდეები ზედა დონეზე გადადის,", + "and new photos never reuse an id in use. What was repaired is written to the log.": "და ახალი ფოტოები არასდროს იყენებს უკვე დაკავებულ ID-ს. რაც შეკეთდა, ჟურნალში იწერება.", + "Nikon lens corrections": "Nikon-ის ობიექტივის კორექციები", + "Raws from the Nikon Z 6II, Z 8 and Z f now open with the camera's own distortion correction, as Lightroom applies a": "Nikon Z 6II, Z 8 და Z f კამერების RAW ფაილები ახლა კამერის საკუთარი დეფორმაციის კორექციით იხსნება, ისე, როგორც Lightroom იყენებს", + "built-in profile: straight lines near the edges stay straight and the framing matches the camera's JPEG. It works": "ჩაშენებულ პროფილს: კიდეებთან სწორი ხაზები სწორი რჩება და კადრირება კამერის JPEG-ს ემთხვევა. ის მუშაობს", + "with Z lenses and with F-mount lenses on the FTZ adapter, follows the in-body stabilisation's shift of the optical": "Z ობიექტივებთან და FTZ ადაპტერზე დამაგრებულ F-mount ობიექტივებთან, ითვალისწინებს კორპუსის სტაბილიზაციით გამოწვეულ ოპტიკური", + "centre, and can be turned off under Lens Corrections. Vignetting correction from the file comes later.": "ცენტრის წანაცვლებას და შეიძლება გამოირთოს ობიექტივის კორექციებში. ფაილიდან ვინიეტირების კორექცია მოგვიანებით დაემატება.", + "Thumbnail cache stays in its folder": "ესკიზების ქეში თავის საქაღალდეში რჩება", + "The thumbnail cache no longer follows a shard folder (`thumbs/ab/`) that is a symlink or junction to somewhere": "ესკიზების ქეში აღარ მიჰყვება ქვესაქაღალდეს (`thumbs/ab/`), რომელიც სიმბოლური ბმული ან junction-ია სხვა", + "else (issue #1504): trimming or clearing the cache can't delete files outside it, and thumbnails are never read": "ადგილას (ხარვეზი #1504): ქეშის შემცირება ან გასუფთავება ვერ წაშლის მის გარეთ არსებულ ფაილებს, ხოლო ესკიზები ასეთი ბმულის", + "from or written through such a link.": "გავლით არასდროს იკითხება და არ იწერება.", + "Synchronize Folder asks a network share less": "საქაღალდის სინქრონიზაცია ქსელურ საქაღალდეს ნაკლებ კითხვას უსვამს", + "A Synchronize Folder scan no longer asks the disk about every photo of the library in the folder (is its file": "საქაღალდის სინქრონიზაციის სკანირება დისკს აღარ ეკითხება საქაღალდეში ბიბლიოთეკის ყოველი ფოტოს შესახებ (არის თუ არა მისი ფაილი", + "there, has it a sidecar): it has just listed the folder, and reads the answers off the listing. On a network share": "ადგილზე, აქვს თუ არა თანმხლები ფაილი): მან ახლახან ჩამოთვალა საქაღალდე და პასუხებს ამ სიიდან კითხულობს. ქსელურ საქაღალდეზე", + "each of those questions is a round trip. Measured on a hard disk over SMB, for folders of 1,600 to 2,400 photos": "თითოეული ასეთი კითხვა ქსელში ცალკე მიმოსვლაა. გაზომილია მყარ დისკზე SMB-ით, 1,600-დან 2,400 ფოტომდე საქაღალდეებზე,", + "that had not changed: 4.6 to 7.1 s of questions after the listing (about 3 ms a photo), now under 0.05 s. The": "რომლებიც არ შეცვლილა: სიის შემდეგ 4.6-დან 7.1 წმ-მდე კითხვები (დაახლოებით 3 მწმ ფოტოზე), ახლა 0.05 წმ-ზე ნაკლები.", + "listing itself took 4 to 5 s and is as it was.": "თავად სიის მიღებას 4-დან 5 წმ-მდე სჭირდებოდა და ასევე რჩება.", + "The disk is still asked wherever a listing can't be sure what a file system would say: about a name that is": "დისკს კვლავ ეკითხება ყველგან, სადაც სია ვერ იქნება დარწმუნებული, რას იტყოდა ფაილური სისტემა: სახელზე, რომელიც", + "there in another case, a link, a name Windows reads another way (`aux.jpg`, a `~`, a `:`, a dot or a space at the": "სხვა რეგისტრით არსებობს, ბმულზე, სახელზე, რომელსაც Windows სხვაგვარად კითხულობს (`aux.jpg`, `~`, `:`, წერტილი ან ჰარი ბოლოში),", + "end), a folder the scan did not walk to its end, and, in a folder that holds any name with a character outside": "საქაღალდეზე, რომელიც სკანირებამ ბოლომდე არ გაიარა, და, საქაღალდეში, სადაც რომელიმე სახელი შეიცავს ASCII-ს გარეთ მყოფ", + "ASCII (an umlaut, a curly apostrophe, a dash), about every name the folder does not list. Names it does list are": "სიმბოლოს (უმლაუტს, ხვეულ აპოსტროფს, ტირეს), ყოველ სახელზე, რომელიც საქაღალდის სიაში არ არის. სიაში არსებულ სახელებზე", + "answered there too. In such a folder the scan saves less, and its checks now start after the listing where they": "პასუხიც იქვე მიიღება. ასეთ საქაღალდეში სკანირება ნაკლებს ზოგავს, და მისი შემოწმებები ახლა სიის შემდეგ იწყება, მაშინ როცა", + "ran beside it.": "ადრე მის პარალელურად მიმდინარეობდა.", + "A photo the folder lists is there for the scan, also where its file could not be opened by its path (a folder": "ფოტო, რომელიც საქაღალდის სიაშია, სკანირებისთვის არსებულად ითვლება, მაშინაც, როცა მისი ფაილის გახსნა მისამართით ვერ მოხერხდა (საქაღალდე,", + "that may be listed but not searched, a path longer than the system takes): such photos used to be listed as": "რომლის ჩამოთვლა შეიძლება, მაგრამ მასში ძებნა არა, ან მისამართი, რომელიც სისტემისთვის ზედმეტად გრძელია): ასეთი ფოტოები ადრე", + "missing. And a share that drops after the scan has listed a folder no longer turns that folder's photos into": "დაკარგულად აღინიშნებოდა. ასევე ქსელური საქაღალდე, რომელიც სკანირების მიერ საქაღალდის ჩამოთვლის შემდეგ ითიშება, ამ საქაღალდის ფოტოებს აღარ აქცევს", + "missing ones.": "დაკარგულად.", + "Large libraries: Synchronize Folder, import and sidecars start sooner": "დიდი ბიბლიოთეკები: საქაღალდის სინქრონიზაცია, იმპორტი და თანმხლები ფაილები უფრო მალე იწყება", + "Opening Synchronize Folder, an import review or an import no longer makes a table of every photo in the library": "საქაღალდის სინქრონიზაციის, იმპორტის გადახედვის ან იმპორტის გახსნა აღარ ადგენს ბიბლიოთეკის ყველა ფოტოს ცხრილს", + "before it looks at the first file. In a library of 3.5 million photos that held the window for about 6 s before": "პირველი ფაილის ნახვამდე. 3.5 მილიონი ფოტოს ბიბლიოთეკაში ეს ფანჯარას დაახლოებით 6 წმ-ით აყოვნებდა", + "a Synchronize scan began (now under 1 s), 2.6 s before an import review (now 0.05 s) and 1.7 s before an import": "სინქრონიზაციის სკანირების დაწყებამდე (ახლა 1 წმ-ზე ნაკლები), 2.6 წმ-ით იმპორტის გადახედვამდე (ახლა 0.05 წმ) და 1.7 წმ-ით იმპორტამდე", + "(now 0.05 s). The scan looks up only the files it finds and the contents it reads, on its own thread.": "(ახლა 0.05 წმ). სკანირება საკუთარ ნაკადში ეძებს მხოლოდ იმ ფაილებს, რომლებსაც პოულობს, და იმ შიგთავსს, რომელსაც კითხულობს.", + "Writing one photo's XMP sidecar (Save Metadata to File, or automatically after an edit) no longer works out who": "ერთი ფოტოს XMP თანმხლები ფაილის ჩაწერა (მეტამონაცემების ფაილში შენახვა, ან ავტომატურად რედაქტირების შემდეგ) აღარ არკვევს, ვის", + "owns every shared sidecar name in the library: 2.4 s a write in that library, now under 1 s.": "ეკუთვნის ბიბლიოთეკაში თანმხლები ფაილის ყოველი საერთო სახელი: იმ ბიბლიოთეკაში 2.4 წმ თითო ჩაწერაზე, ახლა 1 წმ-ზე ნაკლები.", + "Nothing else changes: the same files are found new, already there, moved or missing, and sidecars get the same": "სხვა არაფერი იცვლება: იგივე ფაილები აღმოჩნდება ახალი, უკვე არსებული, გადატანილი ან დაკარგული, და თანმხლები ფაილები იგივე", + "names.": "სახელებს იღებს.", + "Faces load faster in the People view": "სახეები ადამიანების ხედში უფრო სწრაფად იტვირთება", + "Faces on unedited raws are cut from the camera's preview inside the file instead of developing the raw (issue": "დაურედაქტირებელ RAW ფაილებზე სახეები ფაილში შენახული კამერის წინასწარი ხედიდან იჭრება RAW-ის დამუშავების ნაცვლად (ხარვეზი", + "#1440): a Sony α1 face reads 8 MB instead of 70 MB, an A7S III face about 1 MB instead of 24 MB, several times": "#1440): Sony α1-ის სახე 70 MB-ის ნაცვლად 8 MB-ს კითხულობს, A7S III-ის სახე დაახლოებით 1 MB-ს 24 MB-ის ნაცვლად, რამდენჯერმე", + "faster on an external hard disk. A face whose preview is too small, and any edited photo, is still developed from": "უფრო სწრაფად გარე მყარ დისკზე. სახე, რომლის წინასწარი ხედი ძალიან პატარაა, და ნებისმიერი რედაქტირებული ფოტო კვლავ", + "the raw, so it keeps its look.": "RAW-იდან მუშავდება, ამიტომ თავის იერს ინარჩუნებს.", + "Raws whose preview is in Adobe RGB (Sony α1 among others) no longer read the whole file for their grid thumbnail:": "RAW ფაილები, რომელთა წინასწარი ხედი Adobe RGB-შია (მათ შორის Sony α1), ბადის ესკიზისთვის აღარ კითხულობს მთელ ფაილს:", + "only the header and the preview are read, as for other raws.": "იკითხება მხოლოდ სათაური და წინასწარი ხედი, როგორც სხვა RAW ფაილებისთვის.", + "Faces are kept in the thumbnail cache at a few fixed sizes, so moving the thumbnail slider no longer renders them": "სახეები ესკიზების ქეშში რამდენიმე ფიქსირებული ზომით ინახება, ამიტომ ესკიზების სლაიდერის გადაადგილება მათ აღარ არენდერებს", + "all again.": "ყველას ხელახლა.", + "A raw file whose black level is stored as \"not a number\" (or infinity), or a floating-point DNG with such": "RAW ფაილი, რომლის შავის დონე შენახულია როგორც „არა რიცხვი“ (ან უსასრულობა), ან მცურავმძიმიანი DNG ასეთი", + "samples, no longer crashes LightCraft at 1:1 or on export: the bad values read as black.": "ნიმუშებით, LightCraft-ს აღარ თიშავს 1:1-ზე ან ექსპორტისას: არასწორი მნიშვნელობები შავად იკითხება.", + "Exporting a photo more than 65,535 times as long as it is wide (a one-pixel strip), or opening the Export dialog's": "ფოტოს ექსპორტი, რომლის სიგრძე სიგანეზე 65,535-ჯერ მეტია (ერთპიქსელიანი ზოლი), ან მისთვის ექსპორტის დიალოგის", + "watermark preview for it, no longer crashes LightCraft; the export is capped at the encoders' 65,535 pixels.": "ჭვირნიშნის წინასწარი ხედის გახსნა LightCraft-ს აღარ თიშავს; ექსპორტი შემოიფარგლება ენკოდერების 65,535 პიქსელით.", + "Dragging a Tone Curve point that sits very close to its neighbours (two clicks side by side, or a curve from a": "ტონალური მრუდის წერტილის გადათრევა, რომელიც მეზობლებთან ძალიან ახლოსაა (ორი დაწკაპუნება გვერდიგვერდ, ან მრუდი", + "sidecar, a preset or an agent) no longer crashes LightCraft; the point stays between them. Curve points sent to": "თანმხლები ფაილიდან, პრესეტიდან ან აგენტიდან), LightCraft-ს აღარ თიშავს; წერტილი მათ შორის რჩება. `develop.curve`-ისთვის", + "`develop.curve` are kept in order, and a sidecar curve with a \"NaN\" or \"inf\" point is ignored.": "გაგზავნილი მრუდის წერტილები რიგითობას ინარჩუნებს, ხოლო თანმხლები ფაილის მრუდი „NaN“ ან „inf“ წერტილით იგნორირდება.", + "A demo photo whose stored size was damaged (a width of 4294967295) is rendered at its own size instead of": "სადემონსტრაციო ფოტო, რომლის შენახული ზომა დაზიანდა (სიგანე 4294967295), საკუთარი ზომით რენდერდება და არა", + "one that overflows.": "გადავსებული ზომით.", + "DNG camera identity": "კამერის იდენტიფიკაცია DNG-ში", + "DNG export and Convert to DNG no longer duplicate the camera make when the model already": "DNG ექსპორტი და DNG-ად გარდაქმნა აღარ აორმაგებს კამერის მწარმოებელს, როცა მოდელი მას უკვე", + "contains it: `Canon EOS R6` stays `Canon EOS R6`, rather than `Canon Canon EOS R6` (the camera": "შეიცავს: `Canon EOS R6` რჩება `Canon EOS R6`, და არა `Canon Canon EOS R6` (კამერის", + "identity subissue in #840). The separate Make and Model tags keep their original values.": "იდენტიფიკაციის ქვეხარვეზი #840-ში). ცალკეული Make და Model ტეგები თავდაპირველ მნიშვნელობებს ინარჩუნებს.", + "This does not change colour matrices, camera calibration or RAW noise rendering.": "ეს არ ცვლის ფერის მატრიცებს, კამერის კალიბრაციას ან RAW ხმაურის რენდერირებას.", + "Building from source": "აწყობა საწყისი კოდიდან", + "The English and Simplified Chinese build guides now describe command-local job and release": "ინგლისური და გამარტივებული ჩინური აწყობის სახელმძღვანელოები ახლა აღწერს ბრძანების დონეზე ნაკადების რაოდენობისა და release", + "profile overrides for memory-constrained builders (issue #1196), including why packaging": "პროფილის გადაფარვას შეზღუდული მეხსიერების მქონე ამწყობებისთვის (ხარვეზი #1196), მათ შორის იმას, თუ რატომ შეუძლია შეფუთვის", + "recipes can override inherited settings. Default release profiles and application behavior": "რეცეპტებს მემკვიდრეობით მიღებული პარამეტრების გადაფარვა. ნაგულისხმევი release პროფილები და პროგრამის ქცევა", + "are unchanged; the guidance does not guarantee a build will fit every 16 GB machine.": "უცვლელია; ეს რჩევები არ იძლევა გარანტიას, რომ აწყობა 16 GB-იან ნებისმიერ კომპიუტერზე მოთავსდება.", + "Lightroom catalog import": "Lightroom-ის კატალოგის იმპორტი", + "A Lightroom Classic catalog whose changes are all still in its `.lrcat-wal` file (a new catalog Lightroom has": "Lightroom Classic-ის კატალოგი, რომლის ყველა ცვლილება ჯერ კიდევ `.lrcat-wal` ფაილშია (ახალი კატალოგი, რომელიც Lightroom-ს", + "open and hasn't written back yet) imports instead of failing with \"unsupported SQLite schema format\".": "გახსნილი აქვს და ჯერ უკან არ ჩაუწერია), იმპორტირდება, ნაცვლად „unsupported SQLite schema format“ შეცდომისა.", + "An export enlarged far past the photo's size (20000 typed for 2000 with Don't Enlarge off) no longer ends": "ექსპორტი, რომელიც ფოტოს ზომას ბევრად აჭარბებს (2000-ის ნაცვლად აკრეფილი 20000, როცა „გადიდების გარეშე“ გამორთულია), აღარ თიშავს", + "LightCraft: an enlargement stops at 512 megapixels, as in Lightroom, and one that needs more memory than the": "LightCraft-ს: გადიდება 512 მეგაპიქსელზე ჩერდება, როგორც Lightroom-ში, ხოლო ის, რომელსაც კომპიუტერზე არსებულზე მეტი მეხსიერება", + "computer has is refused with the size it would take, before it starts.": "სჭირდება, დაწყებამდე უარყოფილია და შეტყობინება მისთვის საჭირო ზომას ასახელებს.", + "Confirm matching faces together": "შესაბამისი სახეების ერთად დადასტურება", + "On a person's page, the ↑ control on a suggested face confirms it and all shown suggestions with equal or higher": "ადამიანის გვერდზე შემოთავაზებულ სახეზე ↑ მართვის ელემენტი ადასტურებს მას და ყველა ნაჩვენებ შეთავაზებას თანაბარი ან მეტი", + "similarity as one undo step. Hover or focus that face and press A for the same action; hidden suggestions stay hidden.": "მსგავსებით, ერთ დაბრუნების ნაბიჯად. იგივე მოქმედებისთვის მიიტანეთ მაჩვენებელი ამ სახეზე ან მოახდინეთ მასზე ფოკუსირება და დააჭირეთ A-ს; დამალული შეთავაზებები დამალული რჩება.", + "Noise reduction looks the same at every size": "ხმაურის შემცირება ყველა ზომაზე ერთნაირად გამოიყურება", + "Luminance and colour noise reduction no longer look much stronger in grid thumbnails and the filmstrip than in": "სიკაშკაშისა და ფერის ხმაურის შემცირება ბადის ესკიზებში და კადრების ზოლში აღარ გამოიყურება ბევრად ძლიერად, ვიდრე", + "the loupe (issue #960). Their radii are now set in the original photo's pixels, so a thumbnail, the fitted loupe": "ლუპაში (ხარვეზი #960). მათი რადიუსები ახლა ორიგინალი ფოტოს პიქსელებში ყენდება, ამიტომ ესკიზი, ჩატეული ლუპა", + "and a smaller export look like the full-size result scaled down; 1:1 views and full-size exports are unchanged.": "და უფრო პატარა ექსპორტი სრული ზომის შედეგის შემცირებულ ვერსიას ჰგავს; 1:1 ხედები და სრული ზომის ექსპორტი უცვლელია.", + "Like in Lightroom, judge noise reduction at 1:1: at small sizes the noise it removes is mostly averaged away.": "როგორც Lightroom-ში, ხმაურის შემცირება 1:1-ზე შეაფასეთ: მცირე ზომებზე ხმაური, რომელსაც ის აშორებს, ძირითადად ისედაც გასაშუალოებულია.", + "Cached thumbnails are redrawn.": "ქეშირებული ესკიზები ხელახლა იხატება.", + "When the graphics driver resets the GPU while LightCraft is exporting or rendering (issue #1337, seen on Windows": "როცა გრაფიკული დრაივერი GPU-ს გადატვირთავს, სანამ LightCraft ექსპორტს ან რენდერს ასრულებს (ხარვეზი #1337, შენიშნულია Windows-ზე", + "with NVIDIA), LightCraft still stops, because its window can't keep drawing on the lost device, but it now says": "NVIDIA-თი), LightCraft მაინც ჩერდება, რადგან მის ფანჯარას დაკარგულ მოწყობილობაზე ხატვის გაგრძელება არ შეუძლია, მაგრამ ახლა ამბობს", + "\"LightCraft stopped unexpectedly\" and why, instead of \"could not open its window\", and the next start renders": "„LightCraft მოულოდნელად შეწყდა“ და მიზეზს, „ფანჯარა ვერ გახსნა“-ს ნაცვლად, ხოლო შემდეგი გაშვება რენდერს", + "on the CPU and explains how to turn the GPU back on.": "CPU-ზე აკეთებს და ხსნის, როგორ ჩართოთ GPU ისევ.", + "Resetting a slider": "სლაიდერის ჩამოყრა", + "Resting the pointer on a slider's name or its thumb now says that a double-click resets it (\"Exposure — double-click": "სლაიდერის სახელზე ან მის სახელურზე მაჩვენებლის გაჩერებისას ახლა ჩანს, რომ ორმაგი დაწკაპუნება მას ჩამოყრის („ექსპოზიცია — ორმაგი დაწკაპუნებით", + "to reset it\"), in every language (issue #1436).": "ჩამოყრა“), ყველა ენაზე (ხარვეზი #1436).", + "A double-click on the thumb is a single step in History and Undo. Its first click no longer nudges the value to": "ორმაგი დაწკაპუნება სახელურზე ისტორიასა და დაბრუნებაში ერთი ნაბიჯია. მისი პირველი დაწკაპუნება აღარ წევს მნიშვნელობას", + "where the pointer landed, and a single click on the thumb leaves the value alone.": "იქით, სადაც მაჩვენებელი მოხვდა, ხოლო სახელურზე ერთი დაწკაპუნება მნიშვნელობას არ ცვლის.", + "Dehaze while zoomed in": "ბურუსის მოცილება გადიდებისას", + "With Dehaze on, panning a photo zoomed to 1:1 or moving a slider while zoomed no longer samples the whole": "ჩართული ბურუსის მოცილებისას 1:1-ზე გადიდებული ფოტოს გადაადგილება ან სლაიდერის მოძრაობა გადიდებისას აღარ ამოწმებს მთელ", + "original again to find the haze colour. On a 64 MP raw (Sony A7R VI) that took ~0.2 s of CPU per pan and per": "ორიგინალს ხელახლა ბურუსის ფერის საპოვნელად. 64 MP RAW-ზე (Sony A7R VI) ამას ~0.2 წმ CPU-ს დრო სჭირდებოდა თითო გადაადგილებასა და", + "slider step; a slider step now takes ~5 ms on the GPU.": "სლაიდერის ბიჯზე; სლაიდერის ბიჯი ახლა GPU-ზე ~5 მწმ-ს იკავებს.", + "Thumbnails of raw files appear sooner": "RAW ფაილების ესკიზები უფრო მალე ჩნდება", + "Grid thumbnails and the first picture in the loupe of an unedited raw now come from the smallest JPEG the camera": "დაურედაქტირებელი RAW-ის ბადის ესკიზები და პირველი სურათი ლუპაში ახლა კამერის მიერ შენახული უმცირესი საკმარისი ზომის JPEG-იდან", + "stored that is big enough, not always from the largest one. On a Sony A7R VI file a 512 px thumbnail decodes": "მიიღება და არა ყოველთვის უდიდესიდან. Sony A7R VI-ის ფაილზე 512 px ესკიზი 5.6 MB-ის ნაცვლად JPEG-ის", + "0.3 MB of JPEG instead of 5.6 MB and is ready several times sooner; Nikon and Panasonic raws with a mid-sized": "0.3 MB-ს დეკოდირებს და რამდენჯერმე უფრო მალეა მზად; Nikon-ისა და Panasonic-ის RAW ფაილებიც საშუალო ზომის", + "JPEG get faster too.": "JPEG-ით ასევე აჩქარდა.", + "Keywords panel": "საკვანძო სიტყვების პანელი", + "The titles **Keywords** and **Keyword List** in the Keywords panel fold their sections shut and open again, so": "სათაურები **საკვანძო სიტყვები** და **საკვანძო სიტყვების სია** საკვანძო სიტყვების პანელში თავიანთ სექციებს კეცავს და ისევ შლის, ამიტომ", + "the list of every keyword is one click away however many keywords the selected photos have. What is folded is": "ყველა საკვანძო სიტყვის სია ერთ დაწკაპუნებაზეა, რამდენი საკვანძო სიტყვაც არ უნდა ჰქონდეს მონიშნულ ფოტოებს. რაც ჩაკეცილია,", + "remembered.": "ის დამახსოვრებულია.", + "Settings ▸ Interface ▸ Keywords of the selection ▸ **Grouped by parent** lays the selected photos' keywords out by": "პარამეტრები → ინტერფეისი → მონიშნულის საკვანძო სიტყვები → **ზედა საკვანძო სიტყვით დაჯგუფებული** მონიშნული ფოტოების საკვანძო სიტყვებს", + "the keyword they are inside: \"Places › Italy\" once, on a line of its own, with Rome, Venice and the others side by": "იმ საკვანძო სიტყვის მიხედვით ალაგებს, რომელშიც ისინი შედის: „Places › Italy“ ერთხელ, ცალკე ხაზზე, მის ქვეშ კი Rome, Venice და სხვები", + "side under it. A long list stops after eight lines with \"+N more\", and the suggestions say only the keyword's own": "გვერდიგვერდ. გრძელი სია რვა ხაზის შემდეგ წყდება ჩანაწერით „+N კიდევ“, ხოლო შეთავაზებებში მხოლოდ საკვანძო სიტყვის საკუთარი", + "name. Whole names, one chip per keyword, stays the default.": "სახელი ჩანს. ნაგულისხმევად კვლავ სრული სახელები რჩება, თითო ჩიპი თითო საკვანძო სიტყვაზე.", + "A selection without keywords now says \"No keywords yet\" where its chips would be.": "მონიშნული ფოტოები საკვანძო სიტყვების გარეშე ახლა ჩიპების ადგილას აჩვენებს: „საკვანძო სიტყვები ჯერ არ არის“.", + "Typing in **Add keyword** offers the library's matching keywords right under the box. ↓ and Return (or a click)": "**საკვანძო სიტყვის დამატება** ველში აკრეფისას ველის ქვემოთვე ჩნდება ბიბლიოთეკის შესაბამისი საკვანძო სიტყვები. ↓ და Return (ან დაწკაპება)", + "give the offered keyword and keep the cursor in the box for the next one; Return alone still adds what you typed.": "შეთავაზებულ საკვანძო სიტყვას ჩასვამს და კურსორს ველში ტოვებს შემდეგისთვის; მხოლოდ Return კვლავ აკრეფილს ამატებს.", + "A name the library doesn't have is marked as a new keyword before you press Return, so a misspelling no longer": "სახელი, რომელიც ბიბლიოთეკაში არ არის, Return-ის დაჭერამდე ახალ საკვანძო სიტყვად აღინიშნება, ამიტომ შეცდომით აკრეფილი სიტყვა", + "becomes a keyword unnoticed. The suggestions further down stay put while you type.": "შეუმჩნევლად საკვანძო სიტყვად აღარ იქცევა. ქვემოთ მდებარე შეთავაზებები აკრეფისას ადგილზე რჩება.", + "With several photos selected, the Keywords panel says how many photos its keywords belong to. The × on a keyword": "რამდენიმე მონიშნული ფოტოს შემთხვევაში საკვანძო სიტყვების პანელი აჩვენებს, რამდენ ფოტოს ეკუთვნის მისი საკვანძო სიტყვები. საკვანძო სიტყვის ×", + "is a larger target that lights up on its own, and taking a keyword off several photos at once now says which": "უფრო დიდი სამიზნეა და ცალკე ინათება, ხოლო საკვანძო სიტყვის ერთდროულად რამდენიმე ფოტოდან მოხსნისას ახლა ჩანს, რომელი", + "keyword left how many photos, and that Edit ▸ Undo puts it back.": "საკვანძო სიტყვა რამდენ ფოტოს მოეხსნა და რომ რედაქტირება → დაბრუნება მას აღადგენს.", + "Lens corrections": "ობიექტივის კორექციები", + "Sony A7R VI (ILCE-7RM6) raws are corrected for lens distortion from the table the camera records in each file,": "Sony A7R VI (ILCE-7RM6) კამერის RAW ფაილებში ობიექტივის დეფორმაცია სწორდება ცხრილით, რომელსაც კამერა თითოეულ ფაილში იწერს,", + "under Optics ▸ Enable Lens Corrections, on by default for newly imported photos. On 33 photos shot with the camera's": "ოპტიკა → ობიექტივის კორექციების ჩართვა პარამეტრით, რომელიც ახლად იმპორტირებულ ფოტოებზე ნაგულისხმევად ჩართულია. კამერის", + "correction on (24–70 mm, 100 mm macro, 200–600 mm) the render lines up with the camera's JPEG within 0.68 px at": "ჩართული კორექციით გადაღებულ 33 ფოტოზე (24–70 mm, 100 mm მაკრო, 200–600 mm) რენდერი კამერის JPEG-ს 0.68 px სიზუსტით ემთხვევა", + "1440 px at the corners, where it was up to 17 px off before. The camera's lateral chromatic aberration table is read": "1440 px-ზე კუთხეებში, სადაც ადრე 17 px-მდე სცდებოდა. კამერის ლატერალური ქრომატული აბერაციის ცხრილიც იკითხება,", + "too, but not applied by default: our demosaic already hides most of that colour fringing, and the table on top made": "მაგრამ ნაგულისხმევად არ გამოიყენება: ჩვენი დემოზაიკა ამ ფერად შარავანდს უკვე ძირითადად მალავს, ცხრილი კი ზედ", + "it slightly worse. The vignetting table is read but not applied: the camera's own JPEGs don't apply it either. This": "მას ოდნავ აუარესებდა. ვინიეტირების ცხრილი იკითხება, მაგრამ არ გამოიყენება: არც კამერის საკუთარი JPEG-ები იყენებს მას. ეს", + "covers lossless, Compressed and Compressed HQ (ARW 6.0) ARWs alike. The A7R IVA (ILCE-7RM4A) has its own distortion": "ერთნაირად ეხება უდანაკარგო, Compressed და Compressed HQ (ARW 6.0) ARW-ებს. A7R IVA (ILCE-7RM4A) კამერას საკუთარი დეფორმაციის", + "correction, checked against Sony's exports; other Sony bodies record the same tables, but they stay uncorrected until": "კორექცია აქვს, Sony-ის ექსპორტებთან შემოწმებული; სხვა Sony კამერებიც იგივე ცხრილებს იწერს, მაგრამ ისინი შეუსწორებელი რჩება, სანამ", + "they are checked the same way. Photos imported earlier get the correction with Photo ▸ Reload from Disk (when still": "იმავენაირად არ შემოწმდება. ადრე იმპორტირებული ფოტოები კორექციას ფოტო → დისკიდან ხელახლა ჩატვირთვით იღებს (თუ ისინი ჯერ კიდევ", + "at their import settings). See `docs/sony-ilce7rm6-lens-corrections.md`.": "იმპორტის პარამეტრებზეა). იხილეთ `docs/sony-ilce7rm6-lens-corrections.md`.", + "The thumbnail cache is no longer taken for your photos": "ესკიზების ქეში აღარ ითვლება თქვენს ფოტოებად", + "LightCraft's cached thumbnails no longer show up in Windows Photos / Gallery or other photo apps as pictures of": "LightCraft-ის ქეშირებული ესკიზები აღარ ჩანს Windows Photos / Gallery-ში ან სხვა ფოტოპროგრამებში თქვენს", + "yours (issues #610, #1066). They were ordinary `.jpg` files in the library's `thumbs` folder, which is usually": "სურათებად (ხარვეზები #610, #1066). ისინი ჩვეულებრივი `.jpg` ფაილები იყო ბიბლიოთეკის `thumbs` საქაღალდეში, რომელიც, როგორც წესი,", + "inside Pictures, so every thumbnail (one for each photo, size and state of its edits) was listed as a photo.": "Pictures-შია, ამიტომ ყოველი ესკიზი (თითო თითოეული ფოტოს, ზომისა და მისი რედაქტირების მდგომარეობისთვის) ფოტოდ ჩანდა.", + "They are now kept under a name that is no picture's. The ones already there are taken over, not rendered again:": "ახლა ისინი ისეთი სახელით ინახება, რომელიც არცერთ სურათს არ ეკუთვნის. უკვე არსებულები გადმოიტანება და ხელახლა არ რენდერდება:", + "the first time a library opens after this update, \"Tidying the thumbnail cache\" shows in the activity stack": "ამ განახლების შემდეგ ბიბლიოთეკის პირველი გახსნისას აქტივობების დასტაში ჩანს „ესკიზების ქეში სუფთავდება“,", + "while they are renamed (it can be stopped, and goes on at the next open).": "სანამ მათ სახელი ეცვლება (მისი შეჩერება შეიძლება და შემდეგ გახსნაზე გაგრძელდება).", + "Opening a library no longer rewrites the date of every thumbnail it shows, which made them all look new at each": "ბიბლიოთეკის გახსნა აღარ გადაწერს თითოეული ნაჩვენები ესკიზის თარიღს, რის გამოც ყოველი გაშვებისას ყველა მათგანი ახალი", + "launch. Reading a thumbnail writes nothing (but for one that went unused for a week, whose date is brought": "ჩანდა. ესკიზის წაკითხვა არაფერს წერს (გარდა იმისა, რომელიც ერთი კვირა არ გამოყენებულა: მისი თარიღი", + "forward); what was read is remembered for the session, so a full cache still lets go of what is not in use first.": "წინ გადაიწევს); წაკითხული სესიის განმავლობაში ახსოვს, ამიტომ სავსე ქეში კვლავ ჯერ გამოუყენებელს ათავისუფლებს.", + "A `thumbs` folder that holds nothing but the cache says that it is one (`CACHEDIR.TAG`), so backup programs that": "`thumbs` საქაღალდე, რომელშიც მხოლოდ ქეშია, ამას თავადვე აცხადებს (`CACHEDIR.TAG`), ამიტომ სარეზერვო პროგრამებს, რომლებიც ამას", + "go by that can leave it out. It is safe to delete while LightCraft is closed, as before. A `thumbs` folder that": "ითვალისწინებს, შეუძლია ის გამოტოვოს. მისი წაშლა უსაფრთხოა, როცა LightCraft დახურულია, როგორც ადრე. `thumbs` საქაღალდე, რომელიც", + "also holds files of yours (a library opened on a photo folder that had one) is not tagged, and your files in it": "თქვენს ფაილებსაც შეიცავს (ბიბლიოთეკა, გახსნილი ფოტოების საქაღალდეზე, რომელსაც ასეთი ჰქონდა), არ მოინიშნება, ხოლო მასში თქვენი ფაილები", + "are left as they are. Note that files there named exactly like the cache's own (`ab/ab…` with 32 hex digits and": "ხელუხლებელი რჩება. გაითვალისწინეთ, რომ იქ არსებული ფაილები, რომელთა სახელი ზუსტად ქეშის ფაილების სახელს ემთხვევა (`ab/ab…` 32 თექვსმეტობითი ციფრით და", + "`.jpg`) have always been taken for the cache's, and are renamed with it.": "`.jpg`), ყოველთვის ქეშისად ითვლებოდა და მასთან ერთად ეცვლება სახელი.", + "If you go back to an older version, it renders its thumbnails again as `.jpg`. This version then takes those": "თუ ძველ ვერსიაზე დაბრუნდებით, ის ესკიზებს ხელახლა `.jpg`-ად რენდერავს. შემდეგ ეს ვერსია მათ", + "over one by one as they are used; the rest stay until the cache makes room.": "სათითაოდ გადმოიტანს, როგორც კი გამოიყენება; დანარჩენები რჩება, სანამ ქეშს ადგილი არ დასჭირდება.", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914). The": "პორტრეტული ფოტოს შემთხვევაში): სენსორის დაფარული სვეტები სურათის ნაწილად მუშავდებოდა (ხარვეზები #976, #914).", + "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,": "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,", + "D60, D80 and D2Xs now show the area the camera itself frames, a few pixels smaller than before.": "D60, D80 და D2Xs ახლა აჩვენებს იმ არეს, რომელსაც თავად კამერა ჩარჩოში სვამს, ადრინდელზე რამდენიმე პიქსელით პატარას.", + "Export next to the originals": "ექსპორტი ორიგინალების გვერდით", + "The Export dialog has Export to: Specific folder (as before) or Same folder as original photo, like Lightroom": "ექსპორტის დიალოგში ექსპორტის ადგილად შეგიძლიათ აირჩიოთ კონკრეტული საქაღალდე (როგორც ადრე) ან ორიგინალი ფოტოს საქაღალდე, როგორც Lightroom", + "Classic (issue #956). With the second, each photo is exported into the folder its original is in, plus the": "Classic-ში (ხარვეზი #956). მეორე ვარიანტით თითოეული ფოტოს ექსპორტი ხდება იმ საქაღალდეში, სადაც მისი ორიგინალია, დამატებით", + "Subfolder if you give one (say `Exports`), so a batch from several folders lands next to each set of originals.": "ქვესაქაღალდეში, თუ მიუთითებთ (ვთქვათ, `Exports`), ამიტომ რამდენიმე საქაღალდიდან აღებული ჯგუფი ორიგინალების თითოეული ნაკრების გვერდით ხვდება.", + "\"If file exists\" works per folder as usual, and an original is never written over.": "„თუ ფაილი არსებობს“ ჩვეულებისამებრ თითოეულ საქაღალდეზე ცალკე მოქმედებს, ხოლო ორიგინალი არასოდეს გადაიწერება.", + "A photo that has no folder on disk (a demo photo, or one in the web version's browser storage) or whose folder": "ფოტოს, რომელსაც დისკზე საქაღალდე არ აქვს (სადემონსტრაციო ფოტო, ან ვებ-ვერსიის ბრაუზერის საცავში არსებული) ან რომლის საქაღალდე", + "is missing (moved, drive unplugged) is not exported; it gets its own error naming it.": "დაკარგულია (გადატანილია, დისკი გამორთულია), ექსპორტი არ უკეთდება; მისთვის ცალკე შეცდომა ჩნდება, სადაც ის სახელითაა მითითებული.", + "The choice is saved in export presets and Export with Previous. Agents pass": "არჩევანი ინახება ექსპორტის პრესეტებში და „ექსპორტი წინა პარამეტრებით“-ში. აგენტები `app.export`-ს გადასცემენ", + "`destinationMode: \"sameAsOriginal\"` (or `\"specificFolder\"`) to `app.export`; `dir` is then not needed.": "`destinationMode: \"sameAsOriginal\"` (ან `\"specificFolder\"`); ამ დროს `dir` საჭირო აღარ არის.", + "Slideshow export: PDF, JPEG and video": "სლაიდშოუს ექსპორტი: PDF, JPEG და ვიდეო", + "View ▸ Export Slideshow… (or the Export buttons at the end of Settings ▸ Slideshow) writes the slideshow out, like": "ხედი → სლაიდშოუს ექსპორტი… (ან ექსპორტის ღილაკები პარამეტრები → სლაიდშოუს ბოლოში) სლაიდშოუს ფაილად წერს, როგორც", + "Lightroom Classic's Export PDF, Export JPEG and Export Video: the photos in view as their slides, with the layout,": "Lightroom Classic-ის Export PDF, Export JPEG და Export Video: ხედში არსებული ფოტოები სლაიდებად, განლაგებით,", + "overlays and the intro and ending screens, in view order.": "ზედდებებით, შესავალი და დასკვნითი ეკრანებით, ხედის თანმიმდევრობით.", + "**PDF:** one page per slide at 1024, 1920 or 3840 pixels on the long side, at a JPEG quality you choose. Each page": "**PDF:** თითო გვერდი თითო სლაიდზე, გრძელ მხარეზე 1024, 1920 ან 3840 პიქსელით, თქვენ მიერ არჩეული JPEG ხარისხით. ყოველი გვერდი", + "carries the slide duration and fade, so a PDF viewer's presentation mode plays it as a slideshow, and \"Automatically": "სლაიდის ხანგრძლივობასა და მიქრობას ინახავს, ამიტომ PDF-ის სანახავი პროგრამის პრეზენტაციის რეჟიმი მას სლაიდშოუდ უკრავს, ხოლო „სრულეკრანიან", + "show full screen\" asks the viewer to open it that way.": "რეჟიმში ავტომატურად ჩვენება“ პროგრამას სთხოვს, ის ამ სახით გახსნას.", + "**JPEG:** numbered files (`Holiday-001.jpg`, `Holiday-002.jpg`…) in a new folder.": "**JPEG:** დანომრილი ფაილები (`Holiday-001.jpg`, `Holiday-002.jpg`…) ახალ საქაღალდეში.", + "**Video:** AV1 video in an MP4 (or WebM) file at 720p or 1080p, 24 or 30 frames per second: each slide stays up for": "**ვიდეო:** AV1 ვიდეო MP4 (ან WebM) ფაილში, 720p ან 1080p, წამში 24 ან 30 კადრი: თითოეული სლაიდი ჩანს", + "its duration and the fades are rendered frame by frame (crossfades, or fades through the fade colour). The video has": "თავისი ხანგრძლივობით, მიქრობები კი კადრ-კადრ რენდერდება (გადადინება, ან მიქრობა მიქრობის ფერში). ვიდეოს", + "no sound yet. It is AV1 rather than Lightroom's H.264, which has no open encoder we can ship; current browsers,": "ჯერ ხმა არ აქვს. ეს AV1-ია და არა Lightroom-ის H.264, რომლისთვისაც ღია ენკოდერი, რომლის მიწოდებაც შეგვეძლება, არ არსებობს; მას თანამედროვე ბრაუზერები,", + "VLC and recent phones and TVs play it.": "VLC და ახალი ტელეფონები და ტელევიზორები უკრავს.", + "The export runs in the background with its row in the activity stack; ✕ stops it and leaves no half-written file": "ექსპორტი ფონურ რეჟიმში მიმდინარეობს, საკუთარი სტრიქონით აქტივობების დასტაში; × მას აჩერებს და ნახევრად ჩაწერილ ფაილს", + "behind. A photo that can't be read is skipped and named in the message at the end. Agents use `slideshow.export`": "არ ტოვებს. ფოტო, რომლის წაკითხვაც ვერ ხერხდება, გამოიტოვება და ბოლოს შეტყობინებაში სახელით მოიხსენიება. აგენტები იყენებენ `slideshow.export`-ს", + "(`slideshow.exportStatus` for the result).": "(`slideshow.exportStatus`-ს შედეგისთვის).", + "Slideshow templates": "სლაიდშოუს შაბლონები", + "Settings ▸ Slideshow now opens with a template browser, like Lightroom Classic's Template Browser. A template holds": "პარამეტრები → სლაიდშოუ ახლა შაბლონების ბრაუზერით იხსნება, როგორც Lightroom Classic-ის Template Browser. შაბლონი", + "everything about how a slideshow looks and plays: the playback timing and fades, the layout, options and backdrop,": "ინახავს ყველაფერს, თუ როგორ გამოიყურება და იკვრება სლაიდშოუ: დაკვრის დროსა და მიქრობებს, განლაგებას, პარამეტრებსა და ფონს,", + "the overlays and the intro and ending screens. Click one to apply it; point at one to see it on the selected photo in": "ზედდებებს, შესავალ და დასკვნით ეკრანებს. დაწკაპეთ შაბლონზე მის გამოსაყენებლად; მიიტანეთ მაჩვენებელი, რომ ის მონიშნულ ფოტოზე დაინახოთ", + "the preview beside it without changing anything.": "გვერდით მდებარე წინასწარ ხედში, ისე, რომ არაფერი შეიცვალოს.", + "Five built-in templates of our own: Plain Black (the photo on black), Gallery Wall (a light wall, a white mat and a": "ხუთი ჩვენი ჩაშენებული შაბლონი: უბრალო შავი (ფოტო შავზე), გალერეის კედელი (ღია კედელი, თეთრი პასპარტუ და", + "soft shadow, with the caption and rating under the photo), Edge to Edge (photos cropped to fill the screen), Cinema": "რბილი ჩრდილი, წარწერითა და შეფასებით ფოტოს ქვეშ), კიდიდან კიდემდე (ეკრანის შესავსებად ჩამოჭრილი ფოტოები), ფართო", + "Wide (16:9 with black bars, the title in the corner, fades through black and a closing card) and Shooting Data (the": "კინო (16:9 შავი ზოლებით, სათაური კუთხეში, მიქრობა შავის გავლით და დასკვნითი ბარათი) და გადაღების მონაცემები (ექსპოზიცია,", + "exposure, ISO, focal length, camera and lens under each photo on a dark backdrop).": "ISO, ფოკუსური მანძილი, კამერა და ობიექტივი თითოეული ფოტოს ქვეშ, მუქ ფონზე).", + "Save the current settings as a template of your own; right-click it to update it with the current settings, rename,": "შეინახეთ მიმდინარე პარამეტრები საკუთარ შაბლონად; მარჯვენა დაწკაპებით შეგიძლიათ განაახლოთ ის მიმდინარე პარამეტრებით, შეუცვალოთ სახელი,", + "export or delete it, and import templates others share with you. Your templates are `.json` files in the settings": "გაიტანოთ ან წაშალოთ, და შემოიტანოთ სხვების გაზიარებული შაბლონები. თქვენი შაბლონები `.json` ფაილებია პარამეტრების", + "folder's `slideshow-templates` folder, shared by all your libraries.": "საქაღალდის `slideshow-templates` საქაღალდეში, საერთო თქვენი ყველა ბიბლიოთეკისთვის.", + "Applying a template can't be undone with Edit ▸ Undo (slideshow settings are library preferences), so the settings it": "შაბლონის გამოყენების გაუქმება რედაქტირება → დაბრუნებით შეუძლებელია (სლაიდშოუს პარამეტრები ბიბლიოთეკის პარამეტრებია), ამიტომ ჩანაცვლებული", + "replaced are listed as \"Previous settings\" until you quit: click that to go back.": "პარამეტრები გასვლამდე ჩანს როგორც „წინა პარამეტრები“: დაწკაპეთ მასზე დასაბრუნებლად.", + "A template file that can't be used (damaged, from a newer LightCraft, too large) is listed as skipped instead of": "შაბლონის ფაილი, რომლის გამოყენებაც შეუძლებელია (დაზიანებული, უფრო ახალი LightCraft-იდან, ზედმეტად დიდი), გამოტოვებულად ჩამოითვლება და", + "stopping the others, and a template whose identity plate image or background photo isn't there still applies, with a": "დანარჩენებს არ აჩერებს, ხოლო შაბლონი, რომლის საფირმო ნიშნის გამოსახულება ან ფონის ფოტო არ მოიძებნა, მაინც გამოიყენება,", + "note saying what is missing. Agents use `slideshow.templates.*`, and `slideshow.preview {template}` renders a template": "შენიშვნით იმის შესახებ, რა აკლია. აგენტები იყენებენ `slideshow.templates.*`-ს, ხოლო `slideshow.preview {template}` შაბლონს", + "without applying it.": "გამოყენების გარეშე არენდერებს.", + "Slideshow intro and ending screens": "სლაიდშოუს შესავალი და დასკვნითი ეკრანები", + "A slideshow can now open with an intro screen and close with an ending screen, like Lightroom Classic's Titles": "სლაიდშოუ ახლა შეიძლება შესავალი ეკრანით დაიწყოს და დასკვნითი ეკრანით დასრულდეს, როგორც Lightroom Classic-ის Titles", + "panel. Each is switched on on its own and has a background colour and, centred on it, your identity plate (the one": "პანელში. თითოეული ცალკე ირთვება და აქვს ფონის ფერი, მის ცენტრში კი თქვენი საფირმო ნიშანი (ზედდებებში", + "set under Overlays: its text or image) or a line of text of its own, in the plate's colour or one you pick, at a": "დაყენებული: მისი ტექსტი ან გამოსახულება) ან საკუთარი ტექსტის ხაზი, ნიშნის ფერით ან თქვენ მიერ არჩეულით, მითითებული", + "scale. Each stays up for its own duration (by default the slide duration) and fades in and out like a slide.": "მასშტაბით. თითოეული ჩანს საკუთარი ხანგრძლივობით (ნაგულისხმევად სლაიდის ხანგრძლივობით) და სლაიდივით ჩნდება და ქრება.", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off (while repeating": "შესავალი ერთხელ იკვრება პირველი ფოტოს წინ; დასკვნითი ეკრანი ბოლო ფოტოს შემდეგ, როცა გამეორება გამორთულია (გამეორებისას", + "the show runs until you stop it, so the ending doesn't come up). Random order never moves them, ←/→ step across them,": "ჩვენება გრძელდება, სანამ არ შეაჩერებთ, ამიტომ დასკვნითი ეკრანი არ ჩნდება). შემთხვევითი რიგი მათ არასოდეს ანაცვლებს, ←/→ მათზეც გადადის,", + "and the control bar says Intro or End while one is up (the photo count only counts photos).": "ხოლო მართვის ზოლზე წერია „შესავალი“ ან „დასასრული“, სანამ ერთ-ერთი ჩანს (ფოტოების მთვლელი მხოლოდ ფოტოებს ითვლის).", + "Set them in Settings ▸ Slideshow ▸ Titles; the preview there switches between the photo's slide, the intro and the": "დააყენეთ ისინი პარამეტრები → სლაიდშოუ → ტიტრებში; იქ არსებული წინასწარი ხედი გადაირთვება ფოტოს სლაიდს, შესავალსა და", + "ending. They are saved with the library. Agents use `slideshow.titles`, and `slideshow.preview {title: \"intro\"}`": "დასკვნით ეკრანს შორის. ისინი ბიბლიოთეკასთან ერთად ინახება. აგენტები იყენებენ `slideshow.titles`-ს, ხოლო `slideshow.preview {title: \"intro\"}`", + "renders a screen as a PNG.": "ეკრანს PNG-ად არენდერებს.", + "Slideshow overlays": "სლაიდშოუს ზედდებები", + "Slides can now carry Lightroom Classic's Slideshow overlays: an identity plate (a line of text in a colour, or an": "სლაიდებს ახლა შეიძლება ჰქონდეს Lightroom Classic-ის სლაიდშოუს ზედდებები: საფირმო ნიშანი (ტექსტის ხაზი რაიმე ფერით, ან", + "image file such as a PNG logo with transparency, at a size and opacity, optionally drawn behind the photo), the": "გამოსახულების ფაილი, მაგალითად გამჭვირვალობიანი PNG ლოგო, მითითებული ზომითა და გაუმჭვირვალობით, სურვილისამებრ ფოტოს უკან დახატული),", + "photo's rating as stars, and any number of text overlays (up to 16) built from tokens: `{caption}`, `{title}`,": "ფოტოს შეფასება ვარსკვლავებად და ნებისმიერი რაოდენობის ტექსტური ზედდება (16-მდე), აწყობილი ტოკენებისგან: `{caption}`, `{title}`,", + "`{file}`, `{date}`, `{exposure}` (\"1/250 s at f/8\"), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` and the": "`{file}`, `{date}`, `{exposure}` („1/250 s at f/8“), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` და", + "other file-naming tokens, with a size, colour, opacity and an optional soft shadow (opacity, offset, radius, angle).": "ფაილის სახელის სხვა ტოკენები, ზომით, ფერით, გაუმჭვირვალობით და სურვილისამებრ რბილი ჩრდილით (გაუმჭვირვალობა, წანაცვლება, რადიუსი, კუთხე).", + "Each sits at one of nine anchors of the slide or of the photo, moved by an offset, and never leaves the slide.": "თითოეული სლაიდის ან ფოტოს ცხრა მიმაგრების წერტილიდან ერთ-ერთზე დგას, წანაცვლებით გადაადგილებული, და სლაიდს არასოდეს სცდება.", + "The export watermark can be drawn on every slide's photo too (\"Use export watermark\" takes the one you last": "ექსპორტის ჭვირნიშანი შეიძლება თითოეული სლაიდის ფოტოზეც დაიხატოს („ექსპორტის ჭვირნიშნის გამოყენება“ იღებს იმას, რომლითაც ბოლოს", + "exported with).": "გააკეთეთ ექსპორტი).", + "Set them in Settings ▸ Slideshow ▸ Overlays; the slide preview there and View ▸ Slideshow show them. Sizes are a": "დააყენეთ ისინი პარამეტრები → სლაიდშოუ → ზედდებებში; მათ აჩვენებს იქ არსებული სლაიდის წინასწარი ხედი და ხედი → სლაიდშოუ. ზომები", + "share of the slide, so slides look the same on any screen. They are saved with the library. Agents use": "სლაიდის წილია, ამიტომ სლაიდები ნებისმიერ ეკრანზე ერთნაირად გამოიყურება. ისინი ბიბლიოთეკასთან ერთად ინახება. აგენტები იყენებენ", + "`slideshow.overlays`; `slideshow.preview` now also returns where each overlay landed.": "`slideshow.overlays`-ს; `slideshow.preview` ახლა იმასაც აბრუნებს, სად მოხვდა თითოეული ზედდება.", + "Slideshow layout, options and backdrop": "სლაიდშოუს განლაგება, პარამეტრები და ფონი", + "Slides can now be laid out like Lightroom Classic's Slideshow Layout, Options and Backdrop panels: margins (all four": "სლაიდების განლაგება ახლა შეიძლება Lightroom Classic-ის Slideshow-ის Layout, Options და Backdrop პანელების მსგავსად: ველები (ოთხივე", + "linked, or each on its own), Zoom to Fill Frame (crop the photo to fill its cell), a stroke border (colour, width),": "დაკავშირებული, ან თითოეული ცალკე), კადრის შესავსებად გადიდება (ფოტო ჩამოიჭრება, რომ თავისი უჯრა შეავსოს), კონტურის ჩარჩო (ფერი, სისქე),", + "a cast shadow (opacity, offset, radius, angle), and a backdrop colour with an optional colour wash (a gradient from a": "ჩრდილის დაცემა (გაუმჭვირვალობა, წანაცვლება, რადიუსი, კუთხე) და ფონის ფერი სურვილისამებრ ფერადი შეღებვით (გრადიენტი", + "second colour, at an angle and opacity) and a background image (a photo from the library, at an opacity).": "მეორე ფერიდან, მითითებული კუთხითა და გაუმჭვირვალობით) და ფონის გამოსახულებით (ფოტო ბიბლიოთეკიდან, მითითებული გაუმჭვირვალობით).", + "Set them in Settings ▸ Slideshow, which now shows the selected photo as a slide as you change them (with the margin": "დააყენეთ ისინი პარამეტრები → სლაიდშოუში, რომელიც ახლა მონიშნულ ფოტოს სლაიდად აჩვენებს მათი შეცვლისას (ველების", + "guides, at the screen's aspect or 16:9 / 4:3). Sizes are a share of the slide, so a slide looks the same on any": "დამხმარე ხაზებით, ეკრანის თანაფარდობით ან 16:9 / 4:3). ზომები სლაიდის წილია, ამიტომ სლაიდი ნებისმიერ", + "screen. They are saved with the library.": "ეკრანზე ერთნაირად გამოიყურება. ისინი ბიბლიოთეკასთან ერთად ინახება.", + "View ▸ Slideshow plays the composed slides, prepared ahead off the UI thread like before, so fades and the playback": "ხედი → სლაიდშოუ უკრავს აწყობილ სლაიდებს, რომლებიც წინასწარ მზადდება UI ნაკადის გარეთ, როგორც ადრე, ამიტომ მიქრობები და დაკვრის", + "controls work as they did. With the default layout (no margins, border, shadow or backdrop) it plays the photos as": "მართვის ელემენტები ისე მუშაობს, როგორც მუშაობდა. ნაგულისხმევი განლაგებით (ველების, ჩარჩოს, ჩრდილისა და ფონის გარეშე) ის ფოტოებს ისე უკრავს, როგორც", + "before. Agents use `slideshow.layout`, and `slideshow.preview` returns one composed slide as a PNG.": "ადრე. აგენტები იყენებენ `slideshow.layout`-ს, ხოლო `slideshow.preview` ერთ აწყობილ სლაიდს PNG-ად აბრუნებს.", + "Slideshow playback": "სლაიდშოუს დაკვრა", + "View ▸ Slideshow (⌥⌘↩) now plays with Lightroom Classic's Playback settings: how long each slide stays up, a fade": "ხედი → სლაიდშოუ (⌥⌘↩) ახლა Lightroom Classic-ის Playback პარამეტრებით უკრავს: რამდენ ხანს ჩანს თითოეული სლაიდი, მიქრობა", + "between slides (a crossfade, or through black, white or any colour; 0 cuts), random order (every photo once per": "სლაიდებს შორის (გადადინება, ან შავის, თეთრის ან ნებისმიერი ფერის გავლით; 0 — უბრალო გადაჭრა), შემთხვევითი რიგი (ყოველი ფოტო ერთხელ თითო", + "pass, a new order each time round), repeat (off: the slideshow ends after the last photo) and preparing previews in": "გავლაზე, ყოველ ჯერზე ახალი რიგით), გამეორება (გამორთულისას სლაიდშოუ ბოლო ფოტოს შემდეგ მთავრდება) და წინასწარი ხედების", + "advance (the next two slides render while the current one is up, so a fade never waits or flashes).": "წინასწარ მომზადება (შემდეგი ორი სლაიდი რენდერდება, სანამ მიმდინარე ჩანს, ამიტომ მიქრობა არასოდეს ყოვნდება და არ ციმციმებს).", + "Change them in Settings ▸ Slideshow (View ▸ Slideshow Options…); they are saved with the library. Agents use": "შეცვალეთ ისინი პარამეტრები → სლაიდშოუში (ხედი → სლაიდშოუს პარამეტრები…); ისინი ბიბლიოთეკასთან ერთად ინახება. აგენტები იყენებენ", + "`slideshow.playback`; `view.slideshow` takes any of them for one run (`interval` still sets the slide duration).": "`slideshow.playback`-ს; `view.slideshow` ნებისმიერ მათგანს ერთი გაშვებისთვის იღებს (`interval` კვლავ სლაიდის ხანგრძლივობას ადგენს).", + "While it plays, moving the pointer shows a small control bar: previous, play / pause, next, the slide number and": "დაკვრისას მაჩვენებლის მოძრაობა პატარა მართვის ზოლს აჩენს: წინა, დაკვრა / პაუზა, შემდეგი, სლაიდის ნომერი და", + "end. Space pauses, ← / → step (a cut), Esc ends. A slide's time starts once it is shown sharp.": "დასრულება. Space აპაუზებს, ← / → გადადის (გადაჭრით), Esc ასრულებს. სლაიდის დრო მაშინ იწყება, როცა ის მკვეთრად გამოჩნდება.", + "M50, R100, R8 and RP (on the RP also in 1.6× crop mode). CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100, R8 და RP კამერებზე (RP-ზე 1.6× ჩამოჭრის რეჟიმშიც). CR3 ფაილები, რომლებსაც დეკოდერი ჯერ ვერ კითხულობს, კვლავ ჩაშენებული JPEG-იდან იხსნება, როგორც ადრე.", + "Face recognition is on": "სახეების ამოცნობა ჩართულია", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "სახეების ამოცნობა გამორთულია. ჩართეთ, რომ მიიღოთ სახელების შეთავაზებები და ერთად ნახოთ მსგავსი სახეები.", + "Turn on": "ჩართვა", + "Set up face recognition": "სახეების ამოცნობის დაყენება", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "სახეების ამოცნობას სახელების შესათავაზებლად მოდელი სჭირდება: ერთჯერადი ჩამოტვირთვა, პარამეტრებში.", + "Turn on name suggestions": "სახელების შეთავაზებების ჩართვა", + "Set up name suggestions…": "სახელების შეთავაზებების დაყენება…", + "Top bar": "ზედა ზოლი", + "Tool strip": "ხელსაწყოების ზოლი", + "Bottom bar": "ქვედა ზოლი", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6..3f0fd43a22 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -36,9 +36,10 @@ "Build Standard-Sized Previews ({scope})": "Utwórz podglądy o standardowym rozmiarze ({scope})", "Building previews for {} photos…": "Tworzenie podglądów (zdjęcia: {})…", "Click {}:1": "Kliknij {}:1", + "Collapse {name}": "Zwiń {name}", "Couldn't open the editor: {e}": "Nie można otworzyć edytora: {e}", "Create {n} Virtual Copies": "Utwórz {n} kopii wirtualnych", - "Creates {} stacks from {} of {scope}": "Tworzy {} stosów z {} w zakresie: {scope}", + "Creates {stacks} stack{} from {photos} of {scope}": "Tworzy stosy: {stacks} z {photos} w zakresie: {scope}{:.0}", "Decoder: {reason}": "Dekoder: {reason}", "Delete \"{label}\"": "Usuń „{label}”", "Delete \"{label}\" (and the mask)": "Usuń „{label}” (wraz z maską)", @@ -48,6 +49,7 @@ "Done ({what}): {done} photo{plural}": "Gotowe ({what}) — zdjęcia: {done}{plural:.0}", "Duplicate \"{label}\"": "Duplikuj „{label}”", "Example: {example}": "Przykład: {example}", + "Expand {name}": "Rozwiń {name}", "Exported {n} photo{}": "Wyeksportowane zdjęcia: {n}{:.0}", "Exported {ok} of {total} photo{}": "Wyeksportowane zdjęcia: {ok} z {total}{:.0}", "Exported {} point curve preset{}": "Wyeksportowane ustawienia krzywej punktowej: {}{:.0}", @@ -60,6 +62,7 @@ "Healed {n} dust spot{}": "Usunięte plamki kurzu: {n}{:.0}", "Import cancelled · {} photo{} added": "Import anulowany · dodane zdjęcia: {}{:.0}", "Import failed: {e}": "Import nieudany: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importuj zdjęcia przez Plik → Importuj zdjęcia… ({}) lub przeciągnij je tutaj", "Imported {n} point curve preset{}": "Zaimportowane ustawienia krzywej punktowej: {n}{:.0}", "Imported {n} preset{}": "Zaimportowane ustawienia wstępne: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Zaimportowane ustawienia wstępne: {n}{:.0}, nieczytelne pliki: {f}{:.0}", @@ -106,6 +109,7 @@ "Rendering on the CPU: {why}": "Renderowanie na procesorze: {why}", "Replace {} with:": "Zamień {} na:", "Reset {name}": "Wyzeruj {name}", + "{name} value": "{name}: wartość", "Reset {} Channel": "Wyzeruj kanał {}", "Restore {}": "Przywróć {}", "Restore {} Photo{}": "Przywróć zdjęcia: {}{:.0}", @@ -214,6 +218,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "„{parent}” zawiera już „{name}”. Scalić oba?", "There is a “{name}” at the top level already. Merge the two?": "Słowo kluczowe „{name}” istnieje już na najwyższym poziomie. Scalić oba?", "Added “{keyword}” to {n} photo{}": "Dodano „{keyword}” do zdjęć: {n}{:.0}", + "Add Keyword “{keywords}”": "Dodaj słowo kluczowe „{keywords}”", "On {have} of {of} selected photos": "Na {have} z {of} zaznaczonych zdjęć", "Remove “{name}”": "Usuń „{name}”", "There is a keyword set “{name}” already": "Istnieje już zestaw słów kluczowych „{name}”", @@ -236,6 +241,7 @@ "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Geometria z Lightrooma dla {path} nie została zachowana; tryb {mode} zostanie obliczony ponownie.", "Moved {} photo(s)": "Przeniesione zdjęcia: {}", "New Folder in “{name}”": "Nowy folder w „{name}”", + "Created folder “{name}” in “{parent}”": "Utworzono folder „{name}” w „{parent}”", "Restored {} photo{} from Recently Deleted": "Przywrócone z Ostatnio usuniętych zdjęcia: {}{:.0}", "XMP adjustments were not imported for {path}: {fields}.": "Korekty XMP dla {path} nie zostały zaimportowane: {fields}.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Profil XMP „{profile}” nie został zastosowany do {path}; kolory mogą się różnić od Lightrooma.", @@ -261,6 +267,7 @@ "Update “{name}” with Current Settings": "Zaktualizuj „{name}” bieżącymi ustawieniami", "{n} preset{}": "Ustawienia: {n}{:.0}", "{count} more warnings.": "Pozostałe ostrzeżenia: {count}.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "Zdjęcia katalogu w Ostatnio usuniętych tej biblioteki: {in_trash}. Pozostają tam; przywróć je z Ostatnio usuniętych, aby je zobaczyć.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Nie zaimportowano obrazów z katalogu: {skipped}. Ich rekordy w katalogu są niekompletne.", "{photos} catalog records processed; {collections} collections.": "Przetworzone rekordy katalogu: {photos}; kolekcje: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Brakujące oryginały: {missing}. Ich rekordy w katalogu są dostępne; użyj polecenia Znajdź brakujące zdjęcia, aby je ponownie powiązać.", @@ -273,7 +280,7 @@ "Skipped {problem}": "Pominięto: {problem}", "…and {more} more": "…i jeszcze {more}", "Template preview: {name}": "Podgląd szablonu: {name}", - "{n} photos in view · {slides} slides · {time}": "Zdjęcia w widoku: {n} · slajdy: {slides} · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "Zdjęcia w widoku: {n} · slajdy: {slides} · {time}{:.0}{:.0}", "{n} pages": "Strony: {n}", "{n} JPEG files": "Pliki JPEG: {n}", "{s} s of AV1 video": "Wideo AV1: {s} s", @@ -292,7 +299,7 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Dodano scalenie {what} w rozdzielczości {mp}: pełny rozmiar, {full}, wymaga więcej pamięci, niż ma ten komputer", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Dodano scalenie {what} w rozdzielczości {mp}, największej możliwej dla panoramy (pełny rozmiar: {full})", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Przestrzeń kolorów: Rec. 2020 {curve} (HDR AVIF)", - "{n} selected photos · {pages} pages": "Zaznaczone zdjęcia: {n} · strony: {pages}", + "{n} selected photo{} · {pages} page{}": "Wybrane zdjęcia: {n} · stron: {pages}{:.0}{:.0}", "Already in “{}”": "Już w „{}”", "Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?", @@ -305,5 +312,10 @@ "Added {n} photo{}": "Dodano zdjęcia: {n}{:.0}", "Inside: {names}": "Wewnątrz: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}", + "Photo: {name}": "Zdjęcie: {name}", + "Panel layout could not be restored: {error}": "Nie udało się przywrócić układu paneli: {error}", + "Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}", + "{name} is installed": "{name} jest zainstalowany", + "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62a..bb3729a5b6 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -114,6 +114,7 @@ "Auto-Tag from Tracklog": "Automatycznie oznacz na podstawie śladu GPS", "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "Automatyczne tagowanie ze śladu: przypisuje zdjęciom pozycje GPS ze śladu GPX na podstawie czasu wykonania.", "Auto-Tag from Tracklog…": "Automatycznie oznacz na podstawie śladu GPS…", + "Add Locations": "Dodaj lokalizacje", "Automatic": "Automatycznie", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Tryb automatyczny renderuje widok szczegółów w wyświetlanym rozmiarze, nie przekraczając rozdzielczości zdjęcia. Wybierz mniejszy limit, aby przyspieszyć działanie.", "Automatically Write Changes into XMP": "Automatycznie zapisuj zmiany w XMP", @@ -235,7 +236,6 @@ "Close file": "Zamknij plik", "Close panel": "Zamknij panel", "Cloudy": "Pochmurno", - "Collapse": "Zwiń", "Collapse All Stacks": "Zwiń wszystkie stosy", "Collapse Stack": "Zwiń stos", "Color": "Kolor", @@ -322,6 +322,9 @@ "Crop, Rotate, Geometry": "Kadrowanie, obrót, geometria", "Cross Process": "Obróbka krzyżowa", "Culling": "Selekcja zdjęć", + "Cull": "Selekcjonuj", + "Create Stacks": "Utwórz stosy", + "Change Time": "Zmień czas", "Curve": "Krzywa", "Custom": "Niestandardowe", "Custom template…": "Szablon niestandardowy…", @@ -441,6 +444,7 @@ "Effects": "Efekty", "Empty Recently Deleted": "Opróżnij ostatnio usunięte", "Enable Lens Corrections": "Włącz korekcję obiektywu", + "Enable Painting": "Włącz pędzel", "Enable Profile Corrections": "Włącz korekcje profilu", "End Interaction": "Zakończ interakcję", "English": "Angielski", @@ -481,6 +485,7 @@ "Faded Matte": "Wyblakły mat", "Faded Slide": "Wyblakły slajd", "Faded Urban": "Wyblakłe miasto", + "Favorite": "Ulubiony", "Favorite Preset": "Ulubione ustawienie wstępne", "Favorite Profile": "Ulubiony profil", "Favorites": "Ulubione", @@ -657,7 +662,7 @@ "Import as new": "Importuj jako nowe", "Import from Device": "Importuj z urządzenia", "Import from Folder…": "Importuj z folderu…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importuj zdjęcia przez Plik → Importuj zdjęcia… (Cmd+Shift+I) lub przeciągnij je tutaj", + "Import photos with File → Import Photos…, or drop them here": "Importuj zdjęcia przez Plik → Importuj zdjęcia… lub przeciągnij je tutaj", "Imported": "Zaimportowane", "Imported Photos": "Zaimportowane zdjęcia", "Importing": "Importowanie", @@ -707,6 +712,7 @@ "Keyword Sets": "Zestawy słów kluczowych", "Keyword Suggestions": "Sugestie słów kluczowych", "Keyword to paint": "Słowo kluczowe do nanoszenia", + "Type a keyword to paint in the Keywords panel": "Wpisz słowo kluczowe do nanoszenia w panelu Słowa kluczowe", "Keywords": "Słowa kluczowe", "Keywords (K)": "Słowa kluczowe (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "Dodane słowa kluczowe pojawiają się tutaj; skróty ⌥1–⌥9 przypisują je do zdjęć.", @@ -743,6 +749,9 @@ "LightCraft could not start": "Nie można uruchomić LightCraft", "LightCraft couldn't find where to keep your library.": "LightCraft nie znalazł miejsca na przechowywanie biblioteki.", "LightCraft couldn't open the library at": "LightCraft nie mógł otworzyć biblioteki w lokalizacji", + "There is no LightCraft library in this folder any more.": "W tym folderze nie ma już biblioteki LightCraft.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Biblioteki tu nie ma: została przeniesiona lub zmieniono jej nazwę albo jej dysk lub udział sieciowy nie jest podłączony.", + "This folder can't be read:": "Nie można odczytać tego folderu:", "LightCraft on GitHub": "LightCraft w serwisie GitHub", "LightCraft website": "Strona internetowa LightCraft", "LightCraft — Second Window": "LightCraft — drugie okno", @@ -1669,6 +1678,7 @@ "Denoise Settings": "Ustawienia odszumiania", "Denoise all photos with an Amount": "Odszum wszystkie zdjęcia z ustawioną intensywnością", "Downloaded and checked. Installing…": "Pobrano i sprawdzono. Instalowanie…", + "The download failed": "Pobieranie nie powiodło się", "Failed its last test": "Nie przeszedł ostatniego testu", "Graphics card": "Karta graficzna", "I have read these terms and accept them for my own use": "Przeczytałem warunki i akceptuję je na własny użytek", @@ -1822,6 +1832,12 @@ "No photo has it; the keywords below it go too.": "Żadne zdjęcie go nie używa; podrzędne słowa kluczowe również zostaną usunięte.", "Edit Keyword Tag…": "Edytuj słowo kluczowe…", "Put New Keywords Inside This Keyword": "Umieszczaj nowe słowa kluczowe wewnątrz tego", + "Use This as Keyword Shortcut": "Użyj jako skrótu słów kluczowych", + "Set Keyword Shortcut": "Ustaw skrót słów kluczowych", + "Set Keyword Shortcut…": "Ustaw skrót słów kluczowych…", + "Add or Remove Keyword Shortcut": "Dodaj lub usuń skrót słów kluczowych", + "Keyword Shortcut": "Skrót słów kluczowych", + "Part of the keyword shortcut": "Część skrótu słów kluczowych", "Purge Unused Keywords": "Usuń nieużywane słowa kluczowe", "Delete Keyword…": "Usuń słowo kluczowe…", "Drop here for the top level": "Upuść tutaj, aby umieścić na najwyższym poziomie", @@ -1833,6 +1849,7 @@ "& Containing": "i nadrzędne", "Edit Set…": "Edytuj zestaw…", "Edit Keyword Set": "Edytuj zestaw słów kluczowych", + "Edit Keywords": "Edytuj słowa kluczowe", "Keywords (⌥1–⌥9)": "Słowa kluczowe (⌥1–⌥9)", "A keyword set needs a name": "Zestaw słów kluczowych musi mieć nazwę", "Save as a new set": "Zapisz jako nowy zestaw", @@ -1941,6 +1958,7 @@ "Sony ILCE-7M4 downsized lossless ARWs now decode subsampled YCbCr tiles into linear RGB,": "Pomniejszone bezstratne pliki ARW z Sony ILCE-7M4 dekodują teraz próbki YCbCr do liniowej przestrzeni RGB,", "TZ/ZS series, Leica D-Lux, V-Lux and C-Lux, and the GH6, GH7, G9 II, S5 II and S9 generation. They start from a": "serii TZ/ZS, Leica D-Lux, V-Lux i C-Lux oraz generacji GH6, GH7, G9 II, S5 II i S9. Wstępne kolory są dopasowywane do", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Znaczniki: zobacz Znaczniki obok szablonu. Nazwy plików na dysku (wraz z plikami XMP) są zmieniane; kolizje otrzymują przyrostek -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Przycisk Tagi pokazuje symbole, których można użyć w szablonie, np. {date} lub {seq}. Nazwa każdego pliku na dysku jest zmieniana razem z jego plikiem XMP; zajęta nazwa dostaje przyrostek -1, -2…", "The catalog has a format version (issue #102). Opening a library from an older LightCraft upgrades it; a library": "Katalog ma wersję formatu (zgłoszenie #102). Otwarcie biblioteki ze starszego LightCraft aktualizuje ją; biblioteka", "The control port (`--control`) closes a connection as soon as it receives anything that isn't a JSON request": "Port sterujący (`--control`) zamyka połączenie natychmiast po otrzymaniu danych innych niż żądanie JSON", "The thumbnail cache only ever counts and deletes its own files (issue #98): a library opened on a folder that": "Pamięć podręczna miniaturek zlicza i usuwa wyłącznie własne pliki (zgłoszenie #98): otwarcie biblioteki w folderze, który", @@ -2156,6 +2174,7 @@ "Unnamed Faces": "Nienazwane twarze", "Vertical inset (% of short edge)": "Margines pionowy (% krótszego boku)", "not added to Apple Photos (cancelled)": "nie dodano do aplikacji Zdjęcia (anulowano)", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Zapobiegaj migotaniu G-SYNC/FreeSync (po ponownym uruchomieniu)", "Set Folder Color Label": "Ustaw etykietę kolorystyczną folderu", "Refresh View": "Odśwież widok", "Hold View Until Refreshed": "Wstrzymaj widok do odświeżenia", @@ -2282,6 +2301,19 @@ "Dropped Files": "Upuszczone pliki", "Import dropped files without review": "Importuj upuszczone pliki bez przeglądu", "An import is running": "Import jest w toku", + "The photos are imported once it ends": "Zdjęcia zostaną zaimportowane potem", "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", - "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia" + "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", + "Thumbnail size": "Rozmiar miniatur", + "Import Thumbnail Size": "Rozmiar miniatur importu", + "Face recognition is on": "Rozpoznawanie twarzy jest włączone", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Rozpoznawanie twarzy jest wyłączone. Włącz je, aby dostawać propozycje imion i widzieć podobne twarze razem.", + "Turn on": "Włącz", + "Set up face recognition": "Skonfiguruj rozpoznawanie twarzy", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Rozpoznawanie twarzy potrzebuje modelu, aby proponować imiona: jednorazowe pobranie w Ustawieniach.", + "Turn on name suggestions": "Włącz propozycje imion", + "Set up name suggestions…": "Skonfiguruj propozycje imion…", + "Top bar": "Górny pasek", + "Tool strip": "Pasek narzędzi", + "Bottom bar": "Dolny pasek" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4..c26b2e281e 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -25,6 +25,7 @@ "Build Smart Previews ({scope})": "Gerar pré-visualizações inteligentes ({scope})", "Build Standard-Sized Previews ({scope})": "Gerar pré-visualizações em tamanho padrão ({scope})", "Click {}:1": "Clique em {}:1", + "Collapse {name}": "Recolher {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Espaço de cor: Rec. 2020 {curve} (AVIF HDR)", "Create {n} Virtual Copies": "Criar {n} cópias virtuais", "Decoder: {reason}": "Decodificador: {reason}", @@ -35,6 +36,7 @@ "Discard Smart Previews ({scope})": "Descartar pré-visualizações inteligentes ({scope})", "Duplicate \"{label}\"": "Duplicar \"{label}\"", "Example: {example}": "Exemplo: {example}", + "Expand {name}": "Expandir {name}", "Exported {n} photo{}": "{n} foto{0} exportada{0}", "Exported {ok} of {total} photo{}": "Fotos exportadas: {ok} de {total}{:.0}", "Exported {} point curve preset{}": "{} predefinição(ões) de curva de pontos exportada(s){:.0}", @@ -43,6 +45,7 @@ "Filter bar — {active} active filter{}": "Barra de filtros — {active} filtro{0} ativo{0}", "Healed {n} dust spot{}": "{n} mancha{0} de poeira recuperada{0}", "Import cancelled · {} photo{} added": "Importação cancelada · {0} foto{1} adicionada{1}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importe fotos com Arquivo → Importar fotos… ({}) ou solte-as aqui", "Imported {n} point curve preset{}": "{n} predefinição(ões) de curva de pontos importada(s){:.0}", "Imported {n} preset{}": "{n} predefinição(ões) importada(s){:.0}", "Imported {n} preset{}, {f} file{} not readable": "{n} predefinição(ões) importada(s){:.0}, {f} arquivo(s) não legível(is){:.0}", @@ -84,6 +87,7 @@ "Rename “{name}”": "Renomear “{name}”", "Rendering on the CPU: {why}": "Renderizando na CPU: {why}", "Reset {name}": "Redefinir {name}", + "{name} value": "Valor de {name}", "Reset {} Channel": "Redefinir canal {}", "Restore {}": "Restaurar {}", "Restore {} Photo{}": "Restaurar {} foto{}", @@ -123,7 +127,7 @@ "{n} photo{}": "{n} foto{}", "{n} photo{} match · updates automatically as photos change": "{n} foto{0} correspondente{0} · atualiza automaticamente conforme as fotos mudam", "{n} photo{} now · updates automatically as photos change": "{n} foto{} agora · atualiza automaticamente conforme as fotos mudam", - "{n} selected photos · {pages} pages": "{n} fotos selecionadas · {pages} páginas", + "{n} selected photo{} · {pages} page{}": "{n} foto{0} selecionada{0} · {pages} página{1}", "{sel_n} selected · {counted}": "{sel_n} selecionadas · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", "{verb} {n} Photo{}": "{verb} {n} foto{}", @@ -156,7 +160,7 @@ "Auto Import: added {} photo{}": "Importação automática: {} foto{1} adicionada{1}", "Building previews for {} photos…": "Gerando prévias de {} fotos…", "Couldn't open the editor: {e}": "Não foi possível abrir o editor: {e}", - "Creates {} stacks from {} of {scope}": "Cria {} pilhas a partir de {} de {scope}", + "Creates {stacks} stack{} from {photos} of {scope}": "Cria {stacks} pilha{} a partir de {photos} de {scope}", "Done ({what}): {done} photo{plural}": "Concluído ({what}): {done} foto{plural}", "Focus {:.0}": "Foco {:.0}", "Folder “{}” (and its subfolders)": "Pasta “{}” (e suas subpastas)", @@ -231,6 +235,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "“{parent}” já tem “{name}”. Mesclar as duas?", "There is a “{name}” at the top level already. Merge the two?": "Já existe “{name}” no nível superior. Mesclar as duas?", "Added “{keyword}” to {n} photo{}": "“{keyword}” adicionada a {n} foto{}", + "Add Keyword “{keywords}”": "Adicionar palavra-chave “{keywords}”", "On {have} of {of} selected photos": "Em {have} de {of} fotos selecionadas", "Remove “{name}”": "Remover “{name}”", "There is a keyword set “{name}” already": "Já existe um conjunto de palavras-chave “{name}”", @@ -252,6 +257,7 @@ "{what} merge cancelled": "{what} mesclagem cancelada", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Fotos locais ignoradas: {n}{0:.0} — álbuns contêm fotos da biblioteca (adicione-as às Minhas fotos primeiro)", "New Folder in “{name}”": "Nova pasta em “{name}”", + "Created folder “{name}” in “{parent}”": "Pasta “{name}” criada em “{parent}”", "Moved {} photo(s)": "{} foto(s) movida(s)", "not added to Apple Photos: {e}": "não adicionadas ao Fotos da Apple: {e}", "{n} added to Apple Photos album “{album}”": "{n} adicionadas ao álbum “{album}” do Fotos da Apple", @@ -273,6 +279,7 @@ "{n} originals opened in the other editor": "{n} originais abertos no outro editor", "· {in_source} identical copies": "· {in_source} cópias idênticas", "{count} more warnings.": "Mais {count} avisos.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} fotos do catálogo estão em Excluídos recentemente desta biblioteca e continuam lá; restaure-as de Excluídos recentemente para vê-las.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} imagens do catálogo não foram importadas porque seus registros no catálogo estão incompletos.", "{photos} catalog records processed; {collections} collections.": "{photos} registros do catálogo processados; {collections} coleções.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originais estão ausentes. Seus registros no catálogo estão disponíveis; use Encontrar fotos ausentes para vinculá-los novamente.", @@ -285,7 +292,7 @@ "Skipped {problem}": "Ignorado: {problem}", "…and {more} more": "…e mais {more}", "Template preview: {name}": "Prévia do modelo: {name}", - "{n} photos in view · {slides} slides · {time}": "{n} fotos na visualização · {slides} slides · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto{0} na visualização · {slides} slide{1} · {time}", "{n} pages": "{n} páginas", "{n} JPEG files": "{n} arquivos JPEG", "{s} s of AV1 video": "{s} s de vídeo AV1", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "Não foi possível ler {name}: {e}", "Added {n} photo{}": "{n} foto{0} adicionada{0}", "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})", + "Photo: {name}": "Foto: {name}", + "Panel layout could not be restored: {error}": "Não foi possível restaurar a disposição dos painéis: {error}", + "Panel move was not applied: {error}": "A movimentação do painel não foi aplicada: {error}", + "{name} is installed": "{name} está instalado", + "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b..a0884dc56a 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -44,6 +44,7 @@ "Add to Local": "Adicionar a Local", "Add to My Photos": "Adicionar às Minhas fotos", "Can't be moved here": "Não podem ser movidas para cá", + "Import photos with File → Import Photos…, or drop them here": "Importe fotos com Arquivo → Importar fotos… ou solte-as aqui", "This row covers more than one disk: drop on a folder inside it": "Esta linha abrange mais de um disco: solte em uma pasta dentro dela", "Local photos aren't in the library yet: Add to My Photos first, then move them": "As fotos locais ainda não estão na biblioteca: primeiro Adicionar às Minhas fotos, depois mova-as", "Add to Selected Photos": "Adicionar às fotos selecionadas", @@ -123,6 +124,7 @@ "Auto-Tag Photos from Tracklog": "Etiquetar fotos automaticamente pelo tracklog", "Auto-Tag from Tracklog": "Etiquetar automaticamente pelo tracklog", "Auto-Tag from Tracklog…": "Etiquetar automaticamente pelo tracklog…", + "Add Locations": "Adicionar locais", "Automatic": "Automático", "Automatically Write Changes into XMP": "Gravar alterações automaticamente no XMP", "Automatically write changes into XMP sidecars": "Grava automaticamente as alterações nos arquivos XMP auxiliares", @@ -246,7 +248,6 @@ "Close file": "Fechar arquivo", "Close panel": "Fechar painel", "Cloudy": "Nublado", - "Collapse": "Recolher", "Collapse All Stacks": "Recolher todas as pilhas", "Collapse Stack": "Recolher pilha", "Color": "Cor", @@ -341,6 +342,9 @@ "Crop, Rotate, Geometry": "Recorte, rotação, geometria", "Cross Process": "Processamento cruzado", "Culling": "Triagem", + "Cull": "Fazer triagem", + "Create Stacks": "Criar pilhas", + "Change Time": "Alterar hora", "Curve": "Curva", "Custom": "Personalizado", "Custom template…": "Modelo personalizado…", @@ -459,6 +463,7 @@ "Effects": "Efeitos", "Empty Recently Deleted": "Esvaziar Excluídos recentemente", "Enable Lens Corrections": "Ativar correções de lente", + "Enable Painting": "Ativar pincel", "Enable Profile Corrections": "Ativar correções de perfil", "End Interaction": "Encerrar interação", "English": "Inglês", @@ -498,6 +503,7 @@ "Faded Matte": "Fosco desbotado", "Faded Slide": "Slide desbotado", "Faded Urban": "Urbano desbotado", + "Favorite": "Favorito", "Favorite Preset": "Predefinição favorita", "Favorite Profile": "Perfil favorito", "Favorites": "Favoritos", @@ -682,7 +688,6 @@ "Import as new": "Importar como novas", "Import from Device": "Importar de dispositivo", "Import from Folder…": "Importar de pasta…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importe fotos com Arquivo → Importar fotos… (Cmd+Shift+I) ou solte-as aqui", "Imported": "Importados", "Imported Photos": "Fotos importadas", "Importing": "Importando", @@ -733,6 +738,7 @@ "Keyword Sets": "Conjuntos de palavras-chave", "Keyword Suggestions": "Sugestões de palavras-chave", "Keyword to paint": "Palavra-chave a pintar", + "Type a keyword to paint in the Keywords panel": "Digite uma palavra-chave a pintar no painel Palavras-chave", "Keywords": "Palavras-chave", "Keywords (K)": "Palavras-chave (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "As palavras-chave que você adiciona aparecem aqui; ⌥1–⌥9 as aplicam.", @@ -770,6 +776,9 @@ "LightCraft could not start": "Não foi possível iniciar o LightCraft", "LightCraft couldn't find where to keep your library.": "O LightCraft não conseguiu encontrar onde guardar sua biblioteca.", "LightCraft couldn't open the library at": "O LightCraft não conseguiu abrir a biblioteca em", + "There is no LightCraft library in this folder any more.": "Esta pasta não tem mais uma biblioteca do LightCraft.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "A biblioteca não está aqui: foi movida ou renomeada, ou o disco ou compartilhamento de rede dela não está conectado.", + "This folder can't be read:": "Não é possível ler esta pasta:", "LightCraft on GitHub": "LightCraft no GitHub", "LightCraft website": "Site do LightCraft", "LightCraft — Second Window": "LightCraft — segunda janela", @@ -1477,6 +1486,7 @@ "Table": "Tabela", "Tags": "Marcadores", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Marcadores: consulte Marcadores ao lado do modelo. Os arquivos são renomeados no disco (com seus sidecars XMP); nomes existentes recebem -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "O botão Marcadores lista os itens que você pode usar no modelo, como {date} ou {seq}. Cada arquivo é renomeado no disco junto com seu sidecar XMP; um nome já usado recebe -1, -2…", "Take a snapshot": "Tirar um instantâneo", "Targeted Adjustment": "Ajuste direcionado", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Ajuste direcionado: arraste para cima/baixo na foto para ajustar as cores ali", @@ -1717,6 +1727,7 @@ "Denoise Settings": "Configurações de redução de ruído", "Denoise all photos with an Amount": "Reduzir o ruído de todas as fotos com uma Quantidade", "Downloaded and checked. Installing…": "Baixado e verificado. Instalando…", + "The download failed": "Falha ao baixar", "Failed its last test": "Falhou no último teste", "Graphics card": "Placa de vídeo", "I have read these terms and accept them for my own use": "Li estes termos e os aceito para meu uso pessoal", @@ -1880,6 +1891,12 @@ "No photo has it; the keywords below it go too.": "Nenhuma foto a tem; as palavras-chave abaixo dela também são excluídas.", "Edit Keyword Tag…": "Editar palavra-chave…", "Put New Keywords Inside This Keyword": "Colocar novas palavras-chave dentro desta", + "Use This as Keyword Shortcut": "Usar como atalho de palavras-chave", + "Set Keyword Shortcut": "Definir atalho de palavras-chave", + "Set Keyword Shortcut…": "Definir atalho de palavras-chave…", + "Add or Remove Keyword Shortcut": "Adicionar ou remover atalho de palavras-chave", + "Keyword Shortcut": "Atalho de palavras-chave", + "Part of the keyword shortcut": "Faz parte do atalho de palavras-chave", "Purge Unused Keywords": "Excluir palavras-chave não usadas", "Delete Keyword…": "Excluir palavra-chave…", "Drop here for the top level": "Solte aqui para o nível superior", @@ -1891,6 +1908,7 @@ "& Containing": "e as que as contêm", "Edit Set…": "Editar conjunto…", "Edit Keyword Set": "Editar conjunto de palavras-chave", + "Edit Keywords": "Editar palavras-chave", "Keywords (⌥1–⌥9)": "Palavras-chave (⌥1–⌥9)", "A keyword set needs a name": "Um conjunto de palavras-chave precisa de um nome", "Save as a new set": "Salvar como novo conjunto", @@ -2201,6 +2219,20 @@ "Dropped Files": "Arquivos soltos", "Import dropped files without review": "Importar arquivos soltos sem revisão", "An import is running": "Uma importação está em andamento", + "The photos are imported once it ends": "As fotos serão importadas depois", "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", - "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos" + "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", + "Thumbnail size": "Tamanho das miniaturas", + "Import Thumbnail Size": "Tamanho das miniaturas de importação", + "Face recognition is on": "O reconhecimento facial está ativado", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "O reconhecimento facial está desativado. Ative-o para receber sugestões de nomes e ver rostos parecidos juntos.", + "Turn on": "Ativar", + "Set up face recognition": "Configurar o reconhecimento facial", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "O reconhecimento facial precisa de um modelo para sugerir nomes: um download único, em Configurações.", + "Turn on name suggestions": "Ativar sugestões de nomes", + "Set up name suggestions…": "Configurar sugestões de nomes…", + "Top bar": "Barra superior", + "Tool strip": "Barra de ferramentas", + "Bottom bar": "Barra inferior", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af4276..4be240ec5b 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -38,10 +38,11 @@ "Build Standard-Sized Previews ({scope})": "Создать просмотры стандартного размера ({scope})", "Building previews for {} photos…": "Создание просмотров для фото: {}…", "Click {}:1": "Щелчок {}:1", + "Collapse {name}": "Свернуть: {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Цветовое пространство: Rec. 2020 {curve} (HDR AVIF)", "Couldn't open the editor: {e}": "Не удалось открыть редактор: {e}", "Create {n} Virtual Copies": "Создать виртуальные копии: {n}", - "Creates {} stacks from {} of {scope}": "Будет создано стопок: {} из {} фото ({scope})", + "Creates {stacks} stack{} from {photos} of {scope}": "Будет создано стопок: {stacks} из {photos} фото ({scope}){:.0}", "Decoder: {reason}": "Декодер: {reason}", "Delete \"{label}\"": "Удалить «{label}»", "Delete \"{label}\" (and the mask)": "Удалить «{label}» (и маску)", @@ -51,6 +52,7 @@ "Done ({what}): {done} photo{plural}": "Готово ({what}): фото: {done}{plural:.0}", "Duplicate \"{label}\"": "Дублировать «{label}»", "Example: {example}": "Пример: {example}", + "Expand {name}": "Развернуть: {name}", "Exported {n} photo{}": "Экспортировано фото: {n}{:.0}", "Exported {ok} of {total} photo{}": "Экспортировано фото: {ok} из {total}{:.0}", "Exported {} point curve preset{}": "Экспортировано пресетов точечной кривой: {}{:.0}", @@ -64,6 +66,7 @@ "Healed {n} dust spot{}": "Убрано пылинок: {n}{:.0}", "Import cancelled · {} photo{} added": "Импорт отменён · добавлено фото: {}{:.0}", "Import failed: {e}": "Ошибка импорта: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Импортируйте фото через Файл → Импорт фото… ({}) или перетащите их сюда", "Import warnings ({n}):\n{warnings}": "Предупреждения импорта ({n}):\n{warnings}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Не удалось записать XMP-файлы {n} фото (папка недоступна?). LightCraft продолжает попытки.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Профиль XMP \"{profile}\" не применён к {path}; цвета могут отличаться от Lightroom.", @@ -120,6 +123,7 @@ "Rendering on the CPU: {why}": "Рендеринг на CPU: {why}", "Replace {} with:": "Заменить {} на:", "Reset {name}": "Сбросить: {name}", + "{name} value": "{name}: значение", "Reset {} Channel": "Сбросить канал: {}", "Restore {}": "Восстановить {}", "Restore {} Photo{}": "Восстановить фото: {}{:.0}", @@ -168,7 +172,7 @@ "{n} photo{}": "Фото: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "Подходящих фото: {n}{:.0} · обновляется автоматически при изменении фото", "{n} photo{} now · updates automatically as photos change": "Сейчас фото: {n}{:.0} · обновляется автоматически при изменении фото", - "{n} selected photos · {pages} pages": "Выбрано фото: {n} · страниц: {pages}", + "{n} selected photo{} · {pages} page{}": "Выбрано фото: {n} · страниц: {pages}{:.0}{:.0}", "{n} similar photo{} · View ▸ Clear Filters to see all": "Похожих фото: {n}{:.0} · Вид → Сбросить фильтры, чтобы увидеть все", "{pid} (missing)": "{pid} (отсутствует)", "{sel_n} selected · {counted}": "Выбрано: {sel_n} · {counted}", @@ -227,6 +231,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "В «{parent}» уже есть «{name}». Объединить их?", "There is a “{name}” at the top level already. Merge the two?": "На верхнем уровне уже есть «{name}». Объединить их?", "Added “{keyword}” to {n} photo{}": "«{keyword}» добавлено к фото ({n}){:.0}", + "Add Keyword “{keywords}”": "Добавить ключевое слово «{keywords}»", "On {have} of {of} selected photos": "На {have} из {of} выбранных фото", "Remove “{name}”": "Убрать «{name}»", "There is a keyword set “{name}” already": "Набор ключевых слов «{name}» уже есть", @@ -248,6 +253,7 @@ "{what} merge cancelled": "{what}: слияние отменено", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Пропущено локальных фото: {n}{0:.0} — в альбомах только фото из библиотеки (сначала добавьте их в «Мои фото»)", "New Folder in “{name}”": "Новая папка в «{name}»", + "Created folder “{name}” in “{parent}”": "Папка «{name}» создана в «{parent}»", "Moved {} photo(s)": "Перемещено фото: {}", "not added to Apple Photos: {e}": "не добавлено в Apple Фото: {e}", "{n} added to Apple Photos album “{album}”": "Добавлено в альбом «{album}» Apple Фото: {n}", @@ -269,6 +275,7 @@ "{n} originals opened in the other editor": "Открыто оригиналов в другом редакторе: {n}", "· {in_source} identical copies": "· идентичных копий: {in_source}", "{count} more warnings.": "Других предупреждений: {count}.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "Фото каталога в «Недавно удалённых» этой библиотеки: {in_trash}. Они остаются там; чтобы увидеть их, восстановите их из «Недавно удалённых».", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Не импортированы изображения каталога: {skipped}. Их записи в каталоге неполные.", "{photos} catalog records processed; {collections} collections.": "Обработано записей каталога: {photos}; коллекций: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Не найдены оригиналы: {missing}. Их записи каталога доступны; используйте поиск отсутствующих фотографий, чтобы восстановить ссылки.", @@ -281,7 +288,7 @@ "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…и ещё {more}", "Template preview: {name}": "Просмотр шаблона: {name}", - "{n} photos in view · {slides} slides · {time}": "Фото в просмотре: {n} · слайдов: {slides} · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "Фото в просмотре: {n} · слайдов: {slides} · {time}{:.0}{:.0}", "{n} pages": "Страниц: {n}", "{n} JPEG files": "Файлов JPEG: {n}", "{s} s of AV1 video": "{s} с видео AV1", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "Не удалось прочитать {name}: {e}", "Added {n} photo{}": "Добавлено фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}", + "Photo: {name}": "Фото: {name}", + "Panel layout could not be restored: {error}": "Не удалось восстановить расположение панелей: {error}", + "Panel move was not applied: {error}": "Перемещение панели не применено: {error}", + "{name} is installed": "Модель {name} установлена", + "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index f740aaed97..598893c3bc 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -218,6 +218,7 @@ "The layout image can't be shown": "Не удаётся показать изображение макета", "Their photos in the grid": "Их фото в сетке", "This page setup is not valid": "Эти параметры страницы недопустимы", + "Import photos with File → Import Photos…, or drop them here": "Импортируйте фото через Файл → Импорт фото… или перетащите их сюда", "This row covers more than one disk: drop on a folder inside it": "Эта строка охватывает несколько дисков: перетащите на папку внутри неё", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Локальных фото ещё нет в библиотеке: сначала «Добавить в «Мои фото»», затем перемещайте", "Add to Selected Photos": "Добавить к выбранным фото", @@ -288,6 +289,7 @@ "Auto-Tag Photos from Tracklog": "Автопривязка фото по треку", "Auto-Tag from Tracklog": "Автопривязка по треку", "Auto-Tag from Tracklog…": "Автопривязка по треку…", + "Add Locations": "Добавить места", "Automatic": "Автоматически", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Автоматический режим рендерит «Детализацию» в отображаемом размере, вплоть до собственных пикселей фото. Выберите размер, чтобы ограничить: меньше — быстрее.", "Automatically Write Changes into XMP": "Автоматически записывать изменения в XMP", @@ -478,6 +480,9 @@ "Crop Aspect": "Пропорции кадра", "Cross Process": "Кросс-процесс", "Culling": "Отбор", + "Cull": "Отобрать", + "Create Stacks": "Создать стопки", + "Change Time": "Изменить время", "Curve": "Кривая", "Custom": "Свои", "Custom…": "Свои…", @@ -572,6 +577,7 @@ "Effect": "Эффект", "Effects": "Эффекты", "Enable Lens Corrections": "Включить коррекцию объектива", + "Enable Painting": "Включить кисть", "End Interaction": "Завершить взаимодействие", "English": "Английский", "Enter Full Screen": "Полноэкранный режим", @@ -758,7 +764,6 @@ "Import Profiles & Presets…": "Импортировать профили и пресеты…", "Import from Device": "Импорт с устройства", "Import from Folder…": "Импорт из папки…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Импортируйте фото через Файл → Импорт фото… (Cmd+Shift+I) или перетащите их сюда", "Imported Photos": "Импортированные фото", "Importing": "Импорт", "Importing Lightroom Catalog": "Импорт каталога Lightroom", @@ -802,6 +807,7 @@ "Keyword Sets": "Наборы ключевых слов", "Keyword Suggestions": "Подсказки ключевых слов", "Keyword to paint": "Ключевое слово для нанесения", + "Type a keyword to paint in the Keywords panel": "Введите ключевое слово для нанесения на панели «Ключевые слова»", "Keywords": "Ключевые слова", "Keywords (K)": "Ключевые слова (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "Добавленные вами ключевые слова появятся здесь; ⌥1–⌥9 применяют их.", @@ -831,6 +837,9 @@ "LightCraft could not start": "Не удалось запустить LightCraft", "LightCraft couldn't find where to keep your library.": "LightCraft не удалось найти место для хранения вашей библиотеки.", "LightCraft couldn't open the library at": "LightCraft не удалось открыть библиотеку в", + "There is no LightCraft library in this folder any more.": "В этой папке больше нет библиотеки LightCraft.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Библиотеки здесь нет: её переместили или переименовали, либо её диск или сетевая папка не подключены.", + "This folder can't be read:": "Не удаётся прочитать эту папку:", "LightCraft on GitHub": "LightCraft на GitHub", "LightCraft website": "Сайт LightCraft", "LightCraft — Second Window": "LightCraft — второе окно", @@ -1447,6 +1456,7 @@ "System default": "Как в системе", "Tags": "Теги", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Теги: см. «Теги» рядом с шаблоном. Файлы переименовываются на диске (вместе с XMP-файлами); к существующим именам добавляется -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Кнопка «Теги» показывает, что можно вставить в шаблон, например {date} или {seq}. Каждый файл переименовывается на диске вместе с XMP-файлом; к занятому имени добавляется -1, -2…", "Take a snapshot": "Сделать снимок", "Targeted Adjustment": "Целевая коррекция", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Целевая коррекция: перетаскивайте вверх/вниз по фото, чтобы менять цвета в этом месте", @@ -1605,6 +1615,7 @@ "Denoise Settings": "Настройки шумоподавления", "Denoise all photos with an Amount": "Подавить шум на всех фото с заданным количеством", "Downloaded and checked. Installing…": "Загружено и проверено. Установка…", + "The download failed": "Не удалось загрузить", "Failed its last test": "Последняя проверка не пройдена", "Graphics card": "Видеокарта", "I have read these terms and accept them for my own use": "Я прочитал эти условия и принимаю их для собственного использования", @@ -1805,6 +1816,12 @@ "No photo has it; the keywords below it go too.": "Его нет ни на одном фото; вложенные в него ключевые слова тоже исчезнут.", "Edit Keyword Tag…": "Изменить ключевое слово…", "Put New Keywords Inside This Keyword": "Добавлять новые ключевые слова внутрь этого ключевого слова", + "Use This as Keyword Shortcut": "Сделать быстрым ключевым словом", + "Set Keyword Shortcut": "Задать быстрые ключевые слова", + "Set Keyword Shortcut…": "Задать быстрые ключевые слова…", + "Add or Remove Keyword Shortcut": "Добавить или снять быстрые ключевые слова", + "Keyword Shortcut": "Быстрые ключевые слова", + "Part of the keyword shortcut": "Входит в быстрые ключевые слова", "Purge Unused Keywords": "Очистить неиспользуемые ключевые слова", "Delete Keyword…": "Удалить ключевое слово…", "Drop here for the top level": "Перетащите сюда для верхнего уровня", @@ -1817,6 +1834,7 @@ "& Containing": "и родительские", "Edit Set…": "Изменить набор…", "Edit Keyword Set": "Изменить набор ключевых слов", + "Edit Keywords": "Изменить ключевые слова", "Keywords (⌥1–⌥9)": "Ключевые слова (⌥1–⌥9)", "A keyword set needs a name": "Набору ключевых слов нужно название", "Set name": "Название набора", @@ -1999,7 +2017,6 @@ "Click to clear these filters": "Щёлкните, чтобы сбросить эти фильтры", "Click to restore · double-click to rename": "Щёлкните, чтобы восстановить · двойной щелчок переименовывает", "Cmd+Shift+R, keeps the photo and clears its edits.)": "Cmd+Shift+R, сохраняет фото и сбрасывает его правки.)", - "Collapse": "Свернуть", "Collapse Stack": "Свернуть стопку", "Colors": "Цвета", "Colour-label filter with several labels at once; expandable folder tree in Local.": "Фильтр по цветовым меткам с несколькими метками сразу; раскрывающееся дерево папок в «Локальном».", @@ -2564,7 +2581,20 @@ "Dropped Files": "Перетащенные файлы", "Import dropped files without review": "Импортировать перетащенные файлы без проверки", "An import is running": "Импорт уже выполняется", + "The photos are imported once it ends": "Фото будут импортированы после этого", "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", - "★ Favorites": "★ Избранное" + "★ Favorites": "★ Избранное", + "Import Thumbnail Size": "Размер миниатюр при импорте", + "Face recognition is on": "Распознавание лиц включено", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Распознавание лиц выключено. Включите его, чтобы получать подсказки имён и видеть похожие лица вместе.", + "Turn on": "Включить", + "Set up face recognition": "Настроить распознавание лиц", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Для подсказок имён распознаванию лиц нужна модель: однократная загрузка в Настройках.", + "Turn on name suggestions": "Включить подсказки имён", + "Set up name suggestions…": "Настроить подсказки имён…", + "Top bar": "Верхняя панель", + "Tool strip": "Панель инструментов", + "Bottom bar": "Нижняя панель", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c..7d40388d1b 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -37,6 +37,7 @@ "Added {n} photo{} to “{}”": "Lade till {n} foto{} i ”{}”", "Added {what} to {name}": "Lade till {what} i {name}", "Added “{keyword}” to {n} photo{}": "Lade till ”{keyword}” på {n} foto{}", + "Add Keyword “{keywords}”": "Lägg till nyckelordet ”{keywords}”", "Adding photos… {} of {}": "Lägger till foton… {} av {}", "All {n} selected photos move by the same amount.": "Alla {n} markerade foton flyttas lika mycket.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Finns redan i biblioteket, i Nyligen raderade: {} foto{} markerade · högerklicka → Återställ, eller Radera permanent för att importera på nytt", @@ -52,6 +53,7 @@ "Build Standard-Sized Previews ({scope})": "Bygg förhandsgranskningar i standardstorlek ({scope})", "Building previews for {} photos…": "Bygger förhandsgranskningar för {} foton…", "Click {}:1": "Klick {}:1", + "Collapse {name}": "Komprimera {name}", "Couldn't open the editor: {e}": "Kunde inte öppna redigeraren: {e}", "Create Keyword Tag Inside “{name}”…": "Skapa nyckelordstagg i ”{name}”…", "Create the keyword “{name}”": "Skapa nyckelordet ”{name}”", @@ -74,6 +76,7 @@ "Duplicate \"{label}\"": "Duplicera ”{label}”", "Effect: {name}": "Effekt: {name}", "Example: {example}": "Exempel: {example}", + "Expand {name}": "Expandera {name}", "Exported to {path}": "Exporterade till {path}", "Exported {n} keyword{}": "Exporterade {n} nyckelord{}", "Exported {n} photo{}": "Exporterade {n} foto{}", @@ -90,6 +93,7 @@ "Healed {n} dust spot{}": "Retuscherade {n} dammfläck{}", "Import cancelled · {} photo{} added": "Importen avbröts · {} foto{} tillagda", "Import failed: {e}": "Importen misslyckades: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Importera foton med Arkiv → Importera foton… ({}) eller släpp dem här", "Import warnings ({n}):\n{warnings}": "Importvarningar ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", "Imported {name}": "Importerade {name}", @@ -127,6 +131,7 @@ "Moved; {} photo(s) relinked": "Flyttat; {} foto(n) har länkats om", "Named ({named_n})": "Namngivna ({named_n})", "New Folder in “{name}”": "Ny mapp i ”{name}”", + "Created folder “{name}” in “{parent}”": "Mappen ”{name}” skapad i ”{parent}”", "new, inside {parent}": "ny, inuti {parent}", "none (CPU rendering): {why}": "ingen (CPU-rendering): {why}", "not added to Apple Photos: {e}": "inte tillagt i Apple Photos: {e}", @@ -161,6 +166,7 @@ "Rendering on the CPU: {why}": "Renderar på processorn: {why}", "Replace {} with:": "Ersätt {} med:", "Reset {name}": "Återställ {name}", + "{name} value": "{name}: värde", "Reset {} Channel": "Återställ kanalen {}", "Restore {}": "Återställ {}", "Restore {} Photo{}": "Återställ {} foto{}", @@ -296,8 +302,9 @@ "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} katalogfoton finns i Nyligen raderade i det här biblioteket och ligger kvar där; återställ dem från Nyligen raderade för att se dem.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "Listing folders — folders: {folders}, files: {files}": "Listar mappar — mappar: {folders}, filer: {files}", "Added {n} photo{}": "{n} foto tillagda{:.0}", "Could not read {name}: {e}": "Kunde inte läsa {name}: {e}", "Drop to import {n} item{}": "Släpp för att importera {n} objekt{:.0}", @@ -305,5 +312,13 @@ "Drop to review {n} item{} for import": "Släpp för att granska {n} objekt före import{:.0}", "Inside: {names}": "Inuti: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", - "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})", + "Photo: {name}": "Foto: {name}", + "Panel layout could not be restored: {error}": "Panellayouten kunde inte återställas: {error}", + "Panel move was not applied: {error}": "Panelflytten tillämpades inte: {error}", + "{name} is installed": "{name} är installerad", + "{name} is installed and in use: face recognition is on": "{name} är installerad och används: ansiktsigenkänning är på", + "Creates {stacks} stack{} from {photos} of {scope}": "Skapar staplar: {stacks} · foton: {photos} av {scope}{:.0}", + "{n} selected photo{} · {pages} page{}": "Markerade foton: {n} · sidor: {pages}{:.0}{:.0}", + "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 66e69b7ba5..f229b9547c 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -25,6 +25,7 @@ "4 MiB and connections at 16.": "4 MiB och anslutningar till 16.", "630 drivers): on Windows the window and GPU rendering use DirectX 12 only and never load the Vulkan driver unless": "630-drivrutiner): i Windows använder fönstret och GPU-renderingen endast DirectX 12 och läser aldrig in Vulkan-drivrutinen om inte", "= exactly": "= exakt", + "Import photos with File → Import Photos…, or drop them here": "Importera foton med Arkiv → Importera foton… eller släpp dem här", "`img_1-1.JPG`; on case-insensitive volumes the case change still goes through.": "`img_1-1.JPG`; på skiftlägesokänsliga volymer går ändringen av skiftläge ändå igenom.", "`Photos/2026/20260114/20260114_001.jpg`) together with their XMP sidecars; each original leaves the card only after its": "`Photos/2026/20260114/20260114_001.jpg`) tillsammans med sina XMP-sidofiler; varje original lämnar kortet först efter att dess", "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "En 16:9-bild med svarta fält ovanför och nedanför, titeln i hörnet, toningar via svart och ett avslutande kort.", @@ -378,7 +379,6 @@ "Close Window": "Stäng fönster", "Cloudy": "Molnigt", "Cmd+Shift+R, keeps the photo and clears its edits.)": "Cmd+Shift+R, behåller fotot och rensar dess redigeringar.)", - "Collapse": "Komprimera", "Collapse All Stacks": "Komprimera alla staplar", "Collapse Stack": "Komprimera stapel", "Color": "Färg", @@ -606,6 +606,7 @@ "Download Place Names (GeoNames)": "Hämta ortnamn (GeoNames)", "Download the SAM 3 Model?": "Vill du hämta SAM 3-modellen?", "Downloaded and checked. Installing…": "Hämtad och kontrollerad. Installerar…", + "The download failed": "Hämtningen misslyckades", "Downloading model": "Hämtar modell", "Downloading place names": "Hämtar ortnamn", "Downloads": "Hämtade filer", @@ -644,6 +645,7 @@ "Edit Info": "Redigera info", "Edit Keyword": "Redigera nyckelord", "Edit Keyword Set": "Redigera nyckelordsuppsättning", + "Edit Keywords": "Redigera nyckelord", "Edit Keyword Tag": "Redigera nyckelordstagg", "Edit Keyword Tag…": "Redigera nyckelordstagg…", "Edit Label Names": "Redigera etikettnamn", @@ -663,6 +665,7 @@ "Effects": "Effekter", "Empty Recently Deleted": "Töm Nyligen raderade", "Enable Lens Corrections": "Aktivera linskorrigeringar", + "Enable Painting": "Aktivera målning", "Enable Profile Corrections": "Aktivera profilkorrigeringar", "End": "Slut", "End Interaction": "Avsluta interaktion", @@ -961,7 +964,6 @@ "Import Lightroom Catalog…": "Importera Lightroom-katalog…", "Import new photos": "Importera nya foton", "Import Photos": "Importera foton", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Importera foton med Arkiv → Importera foton… (Cmd+Shift+I) eller släpp dem här", "Import Photos…": "Importera foton…", "Import Point Curve Presets": "Importera förinställningar för punktkurva", "Import Point Curve Presets…": "Importera förinställningar för punktkurva…", @@ -1089,6 +1091,7 @@ "Keyword Suggestions": "Nyckelordsförslag", "Keyword Tag Options": "Alternativ för nyckelordstaggar", "Keyword to paint": "Nyckelord att måla", + "Type a keyword to paint in the Keywords panel": "Skriv ett nyckelord att måla i panelen Nyckelord", "Keywords": "Nyckelord", "Keywords & People": "Nyckelord och människor", "Keywords (K)": "Nyckelord (K)", @@ -1137,6 +1140,9 @@ "LightCraft could not start": "LightCraft kunde inte starta", "LightCraft couldn't find where to keep your library.": "LightCraft hittade ingen plats att spara ditt bibliotek på.", "LightCraft couldn't open the library at": "LightCraft kunde inte öppna biblioteket på", + "There is no LightCraft library in this folder any more.": "Det finns inte längre något LightCraft-bibliotek i den här mappen.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Biblioteket finns inte där: det har flyttats eller bytt namn, eller så är dess enhet eller nätverksresurs inte ansluten.", + "This folder can't be read:": "Den här mappen kan inte läsas:", "LightCraft Default": "LightCraft-standard", "LightCraft does not know this model, so it assumed:": "LightCraft känner inte till den här modellen och antog därför:", "LightCraft Help": "LightCraft-hjälp", @@ -1635,6 +1641,12 @@ "Purple Saturation": "Lila mättnad", "Put New Keywords Inside": "Lägg nya nyckelord inuti", "Put New Keywords Inside This Keyword": "Lägg nya nyckelord inuti detta nyckelord", + "Use This as Keyword Shortcut": "Använd som nyckelordsgenväg", + "Set Keyword Shortcut": "Ange nyckelordsgenväg", + "Set Keyword Shortcut…": "Ange nyckelordsgenväg…", + "Add or Remove Keyword Shortcut": "Lägg till eller ta bort nyckelordsgenväg", + "Keyword Shortcut": "Nyckelordsgenväg", + "Part of the keyword shortcut": "Ingår i nyckelordsgenvägen", "Put the locations you removed from Local back (no files change)": "Återställ platserna du tog bort från Lokalt (inga filer ändras)", "Quality": "Kvalitet", "Query Photos": "Sök bland foton", @@ -2422,6 +2434,7 @@ "Mask Pins": "Masknålar", "Photo Counts": "Antal foton", "An import is running": "En import pågår", + "The photos are imported once it ends": "Bilderna importeras efteråt", "An import is running. Drop photos when it has finished": "En import pågår. Släpp fotona när den är klar", "Close the open dialog to drop files here": "Stäng den öppna dialogrutan för att släppa filer här", "Close the open dialog, then drop the files again": "Stäng den öppna dialogrutan och släpp sedan filerna igen", @@ -2429,5 +2442,22 @@ "Drop to open the face model": "Släpp för att öppna ansiktsmodellen", "Dropped Files": "Släppta filer", "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", - "Import dropped files without review": "Importera släppta filer utan granskning" + "Import dropped files without review": "Importera släppta filer utan granskning", + "Import Thumbnail Size": "Miniatyrstorlek vid import", + "Click to type a value, drag to change it": "Klicka för att ange ett värde, dra för att ändra det", + "Face recognition is on": "Ansiktsigenkänning är på", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Ansiktsigenkänning är av. Slå på den för att få namnförslag och se liknande ansikten tillsammans.", + "Turn on": "Slå på", + "Set up face recognition": "Ställ in ansiktsigenkänning", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Ansiktsigenkänning behöver en modell för att föreslå namn: en engångsnedladdning, i Inställningar.", + "Turn on name suggestions": "Slå på namnförslag", + "Set up name suggestions…": "Ställ in namnförslag…", + "Change Time": "Ändra tid", + "Cull": "Gallra", + "Add Locations": "Lägg till platser", + "Create Stacks": "Skapa staplar", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Knappen Taggar visar platshållare för mallen, till exempel {date} eller {seq}. Varje fil byter namn på disken tillsammans med sin XMP-sidofil; ett namn som redan finns får -1, -2…", + "Top bar": "Övre fältet", + "Tool strip": "Verktygsfält", + "Bottom bar": "Nedre fältet" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a2..e87bd03749 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -36,10 +36,11 @@ "Build Standard-Sized Previews ({scope})": "Створити перегляди стандартного розміру ({scope})", "Building previews for {} photos…": "Створення переглядів для фото: {}…", "Click {}:1": "Клацання {}:1", + "Collapse {name}": "Згорнути: {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Колірний простір: Rec. 2020 {curve} (HDR AVIF)", "Couldn't open the editor: {e}": "Не вдалося відкрити редактор: {e}", "Create {n} Virtual Copies": "Створити віртуальні копії: {n}", - "Creates {} stacks from {} of {scope}": "Буде створено стосів: {} із {} ({scope})", + "Creates {stacks} stack{} from {photos} of {scope}": "Буде створено стосів: {stacks} із {photos} ({scope}){:.0}", "Decoder: {reason}": "Декодер: {reason}", "Delete \"{label}\"": "Видалити «{label}»", "Delete \"{label}\" (and the mask)": "Видалити «{label}» (і маску)", @@ -49,6 +50,7 @@ "Done ({what}): {done} photo{plural}": "Готово ({what}): фото: {done}{plural:.0}", "Duplicate \"{label}\"": "Дублювати «{label}»", "Example: {example}": "Приклад: {example}", + "Expand {name}": "Розгорнути: {name}", "Exported {n} photo{}": "Експортовано фото: {n}{:.0}", "Exported {ok} of {total} photo{}": "Експортовано фото: {ok} із {total}{:.0}", "Exported {} point curve preset{}": "Експортовано наборів налаштувань точкової кривої: {}{:.0}", @@ -61,6 +63,7 @@ "Healed {n} dust spot{}": "Усунено пилових плям: {n}{:.0}", "Import cancelled · {} photo{} added": "Імпорт скасовано · додано фото: {}{:.0}", "Import failed: {e}": "Помилка імпорту: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Імпортуйте фото через Файл → Імпортувати фото… ({}) або перетягніть їх сюди", "Import warnings ({n}):\n{warnings}": "Попередження імпорту ({n}):\n{warnings}", "Imported {n} point curve preset{}": "Імпортовано наборів налаштувань точкової кривої: {n}{:.0}", "Imported {n} preset{}": "Імпортовано наборів налаштувань: {n}{:.0}", @@ -115,6 +118,7 @@ "Rendering on the CPU: {why}": "Рендеринг на ЦП: {why}", "Replace {} with:": "Замінити {} на:", "Reset {name}": "Скинути: {name}", + "{name} value": "{name}: значення", "Reset {} Channel": "Скинути канал: {}", "Restore {}": "Відновити {}", "Restore {} Photo{}": "Відновити фото: {}{:.0}", @@ -163,7 +167,7 @@ "{n} photo{}": "Фото: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "Відповідних фото: {n}{:.0} · оновлюється автоматично зі зміною фото", "{n} photo{} now · updates automatically as photos change": "Зараз фото: {n}{:.0} · оновлюється автоматично зі зміною фото", - "{n} selected photos · {pages} pages": "Вибрано фото: {n} · сторінок: {pages}", + "{n} selected photo{} · {pages} page{}": "Вибрано фото: {n} · сторінок: {pages}{:.0}{:.0}", "{pid} (missing)": "{pid} (відсутній)", "{sel_n} selected · {counted}": "Вибрано: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", @@ -227,6 +231,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "«{parent}» уже містить «{name}». Об’єднати їх?", "There is a “{name}” at the top level already. Merge the two?": "На верхньому рівні вже є «{name}». Об’єднати їх?", "Added “{keyword}” to {n} photo{}": "«{keyword}» додано до фото: {n}{:.0}", + "Add Keyword “{keywords}”": "Додати ключове слово «{keywords}»", "On {have} of {of} selected photos": "На {have} з {of} вибраних фото", "Remove “{name}”": "Вилучити «{name}»", "There is a keyword set “{name}” already": "Набір ключових слів «{name}» уже існує", @@ -248,6 +253,7 @@ "{what} merge cancelled": "Об’єднання {what} скасовано", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Пропущено локальних фото: {n}{0:.0} — в альбомах лише фото з бібліотеки (спершу додайте їх до моїх фото)", "New Folder in “{name}”": "Нова тека в «{name}»", + "Created folder “{name}” in “{parent}”": "Теку «{name}» створено в «{parent}»", "Moved {} photo(s)": "Переміщено фото: {}", "not added to Apple Photos: {e}": "не додано до Apple Фото: {e}", "{n} added to Apple Photos album “{album}”": "Додано до альбому Apple Фото «{album}»: {n}", @@ -269,6 +275,7 @@ "{n} originals opened in the other editor": "Відкрито оригіналів в іншому редакторі: {n}", "· {in_source} identical copies": "· ідентичних копій: {in_source}", "{count} more warnings.": "Інших попереджень: {count}.", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "Фото каталогу в нещодавно видалених цієї бібліотеки: {in_trash}. Вони залишаються там; щоб побачити їх, відновіть їх із нещодавно видалених.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Не імпортовано зображення каталогу: {skipped}. Їхні записи в каталозі неповні.", "{photos} catalog records processed; {collections} collections.": "Оброблено записів каталогу: {photos}; колекцій: {collections}.", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "Не знайдено оригінали: {missing}. Їхні записи каталогу доступні; скористайтеся пошуком відсутніх фотографій, щоб відновити посилання.", @@ -281,7 +288,7 @@ "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…і ще {more}", "Template preview: {name}": "Перегляд шаблону: {name}", - "{n} photos in view · {slides} slides · {time}": "Фото в перегляді: {n} · слайдів: {slides} · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "Фото в перегляді: {n} · слайдів: {slides} · {time}{:.0}{:.0}", "{n} pages": "Сторінок: {n}", "{n} JPEG files": "Файлів JPEG: {n}", "{s} s of AV1 video": "{s} с відео AV1", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "Не вдалося прочитати {name}: {e}", "Added {n} photo{}": "Додано фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}", + "Photo: {name}": "Фото: {name}", + "Panel layout could not be restored: {error}": "Не вдалося відновити розташування панелей: {error}", + "Panel move was not applied: {error}": "Переміщення панелі не застосовано: {error}", + "{name} is installed": "{name} установлено", + "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe..a4efe34a60 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -111,6 +111,7 @@ "Home": "Домашня тека", "Horizontal inset (% of short edge)": "Відступ по горизонталі (% короткого краю)", "ISO Speed": "Чутливість ISO", + "Import photos with File → Import Photos…, or drop them here": "Імпортуйте фото через Файл → Імпортувати фото… або перетягніть їх сюди", "Imported": "Імпортовані", "Join the ArtCraft Discord": "Приєднатися до Discord ArtCraft", "Join the ArtCraft Discord…": "Приєднатися до Discord ArtCraft…", @@ -355,7 +356,6 @@ "Revert": "Повернути до збереженого", "Print…": "Друк…", "Find…": "Знайти…", - "Collapse": "Згорнути", "Expand": "Розгорнути", "Speed": "Швидкість", " (library default)": " (типове для бібліотеки)", @@ -463,6 +463,7 @@ "Auto-Tag Photos from Tracklog": "Автоматично позначити фото за журналом маршруту", "Auto-Tag from Tracklog": "Автоматично позначити за журналом маршруту", "Auto-Tag from Tracklog…": "Автоматично позначити за журналом маршруту…", + "Add Locations": "Додати місця", "Automatically Write Changes into XMP": "Автоматично записувати зміни в XMP", "Automatically write changes into XMP sidecars": "Автоматично записувати зміни в супровідні файли XMP", "Autumn Gold": "Осіннє золото", @@ -615,6 +616,9 @@ "Crop Aspect": "Пропорції кадрування", "Crop, Rotate, Geometry": "Кадрування, обертання, геометрія", "Culling": "Відбір", + "Cull": "Відібрати", + "Create Stacks": "Створити стоси", + "Change Time": "Змінити час", "Custom template…": "Власний шаблон…", "Cycle Crop Overlay": "Перемкнути накладання кадрування", "Cycle Crop Overlay Orientation": "Перемкнути орієнтацію накладання кадрування", @@ -703,6 +707,7 @@ "Edited or not": "Відредаговано чи ні", "Empty Recently Deleted": "Очистити нещодавно видалені", "Enable Lens Corrections": "Увімкнути корекцію об’єктива", + "Enable Painting": "Увімкнути призначення", "Enable Profile Corrections": "Увімкнути корекцію профілю", "End Interaction": "Завершити взаємодію", "Enter Full Screen": "Увійти в повноекранний режим", @@ -733,6 +738,7 @@ "Faded Matte": "Вицвіле матове", "Faded Slide": "Вицвілий слайд", "Faded Urban": "Вицвіле місто", + "Favorite": "Улюблений", "Favorite Preset": "Додати набір налаштувань до улюблених", "Favorite Profile": "Додати профіль до улюблених", "File & date": "Файл і дата", @@ -1013,7 +1019,6 @@ "Import Profiles & Presets…": "Імпортувати профілі й набори налаштувань…", "Import from Device": "Імпортувати з пристрою", "Import from Folder…": "Імпортувати з теки…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Імпортуйте фото через Файл → Імпортувати фото… (Cmd+Shift+I) або перетягніть їх сюди", "Imported Photos": "Імпортовані фото", "Importing": "Імпорт", "Importing scans the source for photos; it doesn't add the folder to Local (use Local → Browse Folder… to work in a folder without importing).": "Імпорт сканує джерело фото; він не додає теку до локальних (використовуйте Локальні → Оглянути теку…, щоб працювати в теці без імпорту).", @@ -1034,6 +1039,7 @@ "Keyword Sets": "Набори ключових слів", "Keyword Suggestions": "Пропозиції ключових слів", "Keyword to paint": "Ключове слово для призначення", + "Type a keyword to paint in the Keywords panel": "Введіть ключове слово для призначення на панелі «Ключові слова»", "Keywords you add appear here; ⌥1–⌥9 apply them.": "Додані ключові слова з’являються тут; ⌥1–⌥9 застосовують їх.", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "Автоматичний режим відтворює подання «Деталі» у відображуваному розмірі, до власних пікселів фото. Виберіть розмір для обмеження: менший працює швидше.", "Last view": "Останнє подання", @@ -1449,6 +1455,7 @@ "System default": "Типові системні налаштування", "Tags": "Теги", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "Теги: див. «Теги» біля шаблону. Файли перейменовуються на диску (разом із супровідними XMP); до наявних назв додається -1, -2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Кнопка «Теги» показує, що можна вставити в шаблон, наприклад {date} або {seq}. Кожен файл перейменовується на диску разом із супровідним XMP-файлом; до зайнятої назви додається -1, -2…", "Targeted Adjustment": "Цільова корекція", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "Цільова корекція: тягніть угору/вниз на фото, щоб змінити кольори в цьому місці", "Targeted adjustment: drag up/down on the photo to adjust the curve there": "Цільова корекція: тягніть угору/вниз на фото, щоб змінити криву в цьому місці", @@ -1629,6 +1636,9 @@ "Your library couldn't be opened": "Не вдалося відкрити вашу бібліотеку", "LightCraft couldn't find where to keep your library.": "LightCraft не вдалося знайти місце для бібліотеки.", "LightCraft couldn't open the library at": "LightCraft не вдалося відкрити бібліотеку в", + "There is no LightCraft library in this folder any more.": "У цій папці більше немає бібліотеки LightCraft.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Бібліотеки тут немає: її перемістили чи перейменували, або її диск чи мережеву папку не підключено.", + "This folder can't be read:": "Не вдається прочитати цю папку:", "Try Again": "Спробувати знову", "Choose Another Library…": "Вибрати іншу бібліотеку…", "Continue Without Saving": "Продовжити без збереження", @@ -1708,6 +1718,7 @@ "Denoise Settings": "Налаштування усунення шуму", "Denoise all photos with an Amount": "Обробити всі фото зі значенням усунення шуму", "Downloaded and checked. Installing…": "Завантажено й перевірено. Установлення…", + "The download failed": "Не вдалося завантажити", "Failed its last test": "Останню перевірку не пройдено", "Graphics card": "Відеокарта", "I have read these terms and accept them for my own use": "Я прочитав ці умови й приймаю їх для власного використання", @@ -2064,6 +2075,12 @@ "No photo has it; the keywords below it go too.": "Його не має жодне фото; вкладені в нього ключові слова теж зникнуть.", "Edit Keyword Tag…": "Редагувати ключове слово…", "Put New Keywords Inside This Keyword": "Додавати нові ключові слова в це ключове слово", + "Use This as Keyword Shortcut": "Зробити швидким ключовим словом", + "Set Keyword Shortcut": "Задати швидкі ключові слова", + "Set Keyword Shortcut…": "Задати швидкі ключові слова…", + "Add or Remove Keyword Shortcut": "Додати або зняти швидкі ключові слова", + "Keyword Shortcut": "Швидкі ключові слова", + "Part of the keyword shortcut": "Входить до швидких ключових слів", "Purge Unused Keywords": "Очистити невикористані ключові слова", "Delete Keyword…": "Видалити ключове слово…", "Drop here for the top level": "Перетягніть сюди для верхнього рівня", @@ -2075,6 +2092,7 @@ "& Containing": "і батьківські", "Edit Set…": "Редагувати набір…", "Edit Keyword Set": "Редагувати набір ключових слів", + "Edit Keywords": "Редагувати ключові слова", "Keywords (⌥1–⌥9)": "Ключові слова (⌥1–⌥9)", "A keyword set needs a name": "Набір ключових слів потребує назви", "Save as a new set": "Зберегти як новий набір", @@ -2353,6 +2371,20 @@ "Dropped Files": "Перетягнуті файли", "Import dropped files without review": "Імпортувати перетягнуті файли без перегляду", "An import is running": "Імпорт уже виконується", + "The photos are imported once it ends": "Фото буде імпортовано після цього", "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", - "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото" + "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", + "Thumbnail size": "Розмір мініатюр", + "Import Thumbnail Size": "Розмір мініатюр імпорту", + "Face recognition is on": "Розпізнавання облич увімкнено", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Розпізнавання облич вимкнено. Увімкніть його, щоб отримувати підказки імен і бачити схожі обличчя разом.", + "Turn on": "Увімкнути", + "Set up face recognition": "Налаштувати розпізнавання облич", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Для підказок імен розпізнаванню облич потрібна модель: одноразове завантаження в Налаштуваннях.", + "Turn on name suggestions": "Увімкнути підказки імен", + "Set up name suggestions…": "Налаштувати підказки імен…", + "Top bar": "Верхня панель", + "Tool strip": "Панель інструментів", + "Bottom bar": "Нижня панель", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff06..dbf1d28db5 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -37,6 +37,7 @@ "Added {n} photo{} to “{}”": "Đã thêm {n} ảnh{0:.0} vào «{1}»", "Added {what} to {name}": "Đã thêm {what} vào {name}", "Added “{keyword}” to {n} photo{}": "Đã thêm «{keyword}» vào {n} ảnh{:.0}", + "Add Keyword “{keywords}”": "Thêm từ khóa «{keywords}»", "Adding photos… {} of {}": "Đang thêm ảnh… {} / {}", "All {n} selected photos move by the same amount.": "Tất cả {n} ảnh đã chọn dịch chuyển cùng một lượng.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Đã có trong thư viện, trong Đã xóa gần đây: đã chọn {} ảnh{:.0} · nhấp chuột phải → Khôi phục, hoặc Xóa vĩnh viễn để nhập lại", @@ -53,12 +54,13 @@ "Build Standard-Sized Previews ({scope})": "Tạo xem trước cỡ chuẩn ({scope})", "Building previews for {} photos…": "Đang tạo xem trước cho {} ảnh…", "Click {}:1": "Nhấp {}:1", + "Collapse {name}": "Thu gọn {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Color space: Rec. 2020 {curve} (HDR AVIF)", "Couldn't open the editor: {e}": "Không thể mở trình chỉnh sửa: {e}", "Create Keyword Tag Inside “{name}”…": "Tạo từ khóa trong «{name}»…", "Create the keyword “{name}”": "Create the keyword “{name}”", "Create {n} Virtual Copies": "Tạo {n} bản sao ảo", - "Creates {} stacks from {} of {scope}": "Tạo {} chồng từ {} trong {scope}", + "Creates {stacks} stack{} from {photos} of {scope}": "Tạo {stacks} chồng từ {photos} ảnh ({scope}){:.0}", "Decoder: {reason}": "Bộ giải mã: {reason}", "Delete \"{label}\"": "Xóa «{label}»", "Delete \"{label}\" (and the mask)": "Xóa «{label}» (và mặt nạ)", @@ -76,6 +78,7 @@ "Duplicate \"{label}\"": "Nhân bản «{label}»", "Effect: {name}": "Effect: {name}", "Example: {example}": "Ví dụ: {example}", + "Expand {name}": "Mở rộng {name}", "Exported to {path}": "Exported to {path}", "Exported {n} keyword{}": "Đã xuất {n} từ khóa{:.0}", "Exported {n} photo{}": "Đã xuất {n} ảnh{:.0}", @@ -92,6 +95,7 @@ "Healed {n} dust spot{}": "Đã xử lý {n} vết bụi{:.0}", "Import cancelled · {} photo{} added": "Đã hủy nhập · đã thêm {} ảnh{:.0}", "Import failed: {e}": "Nhập thất bại: {e}", + "Import photos with File → Import Photos… ({}), or drop them here": "Nhập ảnh bằng Tệp → Nhập ảnh… ({}), hoặc thả vào đây", "Import warnings ({n}):\n{warnings}": "Cảnh báo khi nhập ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", @@ -121,7 +125,7 @@ "Lightroom import complete: {imported} photos added; index warning: {warning}": "Nhập Lightroom xong: đã thêm {imported} ảnh; cảnh báo chỉ mục: {warning}", "Lightroom import failed: {e}{warning}": "Nhập Lightroom thất bại: {e}{warning}", "Lightroom inspection failed: {e}{warning}": "Kiểm tra Lightroom thất bại: {e}{warning}", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "Listing folders — folders: {folders}, files: {files}": "Đang liệt kê thư mục — thư mục: {folders}, tệp: {files}", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Phông: {} (OFL). Biểu tượng: tác phẩm gốc.", "Making the denoised picture… {}%": "Đang tạo ảnh đã khử nhiễu… {}%", "Matches: {}": "Khớp: {}", @@ -134,6 +138,7 @@ "Moved; {} photo(s) relinked": "Đã di chuyển; liên kết lại {} ảnh", "Named ({named_n})": "Có tên ({named_n})", "New Folder in “{name}”": "Thư mục mới trong «{name}»", + "Created folder “{name}” in “{parent}”": "Đã tạo thư mục «{name}» trong «{parent}»", "On {have} of {of} selected photos": "Trên {have} / {of} ảnh đã chọn", "Painting “{k}”: click photos to add or remove it · Esc stops": "Gán «{k}»: nhấp ảnh để thêm hoặc gỡ · Esc dừng", "Paste into {n} photo{} — only settings that were copied are pasted": "Dán vào {n} ảnh{:.0} — chỉ dán các thiết lập đã sao chép", @@ -165,6 +170,7 @@ "Rendering on the CPU: {why}": "Đang kết xuất trên CPU: {why}", "Replace {} with:": "Thay {} bằng:", "Reset {name}": "Đặt lại {name}", + "{name} value": "Giá trị {name}", "Reset {} Channel": "Đặt lại kênh {}", "Restore {}": "Khôi phục {}", "Restore {} Photo{}": "Khôi phục {} ảnh{:.0}", @@ -240,15 +246,15 @@ "{n} originals opened in the other editor": "Đã mở {n} bản gốc trong trình chỉnh sửa khác", "{n} pages": "{n} pages", "{n} photos": "{n} ảnh", - "{n} photos in view · {slides} slides · {time}": "{n} photos in view · {slides} slides · {time}", "{n} photos in {} are hidden by the filters above": "{n} ảnh trong «{}» bị ẩn bởi bộ lọc phía trên", "{n} photos opened for editing; each is stacked with its original": "Đã mở {n} ảnh để chỉnh sửa; mỗi ảnh xếp chồng với bản gốc", "{n} photo{}": "{n} ảnh{:.0}", + "{n} photo{} in view · {slides} slide{} · {time}": "{n} ảnh trong chế độ xem · {slides} trang chiếu · {time}{:.0}{:.0}", "{n} photo{} match · updates automatically as photos change": "{n} ảnh{:.0} khớp · tự cập nhật khi ảnh thay đổi", "{n} photo{} now · updates automatically as photos change": "Hiện {n} ảnh{:.0} · tự cập nhật khi ảnh thay đổi", "{n} preset{}": "{n} preset{}", "{n} raws can now be developed from their raw data": "{n} raws can now be developed from their raw data", - "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", + "{n} selected photo{} · {pages} page{}": "{n} ảnh đã chọn · {pages} trang{:.0}{:.0}", "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} ảnh tương tự{:.0} · Xem → Xóa bộ lọc để thấy tất cả", "{n} tasks are still running: {names}. Quitting stops them.": "Còn {n} tác vụ đang chạy: {names}. Thoát sẽ dừng chúng.", "{n} {noun}": "{noun}: {n}", @@ -257,6 +263,7 @@ "{pid} (missing)": "{pid} (thiếu)", "{sel_n} selected · {counted}": "Đã chọn {sel_n} · {counted}", "{size} GB": "{size} GB", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} ảnh của danh mục nằm trong Đã xóa gần đây của thư viện này và vẫn ở đó; hãy khôi phục chúng từ Đã xóa gần đây để xem.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", "{stage}… {:.0}%": "{stage}… {:.0}%", "{s} s of AV1 video": "{s} s of AV1 video", @@ -298,12 +305,17 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” is already a person. Combining them makes one person; Undo separates them again.", "• {assumption}": "• {assumption}", "… and {more} more": "… và {more} nữa", - "…and {more} more": "…and {more} more", + "…and {more} more": "…và {more} nữa", "Added {n} photo{}": "Đã thêm {n} ảnh{:.0}", "Could not read {name}: {e}": "Không thể đọc {name}: {e}", "Drop to import {n} item{}": "Thả để nhập {n} mục{:.0}", "Drop to import {n} preset{}": "Thả để nhập {n} thiết lập sẵn{:.0}", "Drop to review {n} item{} for import": "Thả để xem lại {n} mục trước khi nhập{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Nhập danh mục Lightroom «{catalog}» vào đâu?", - "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})", + "Photo: {name}": "Ảnh: {name}", + "Panel layout could not be restored: {error}": "Không thể khôi phục bố cục bảng: {error}", + "Panel move was not applied: {error}": "Việc di chuyển bảng chưa được áp dụng: {error}", + "{name} is installed": "{name} đã được cài đặt", + "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index e4fb8feb81..c1610e428f 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -50,6 +50,7 @@ "Add Catchlight": "Thêm điểm sáng mắt", "Add Face Model…": "Thêm mô hình khuôn mặt…", "Add Folder to Local": "Thêm thư mục vào Cục bộ", + "Add Locations": "Thêm vị trí", "Add Mask": "Thêm mặt nạ", "Add Object Click": "Thêm cú nhấp đối tượng", "Add Point Color Sample": "Thêm mẫu Point Color", @@ -260,6 +261,7 @@ "Catchlight": "Điểm sáng mắt", "Change": "Đổi", "Change Component Mode": "Đổi chế độ thành phần", + "Change Time": "Đổi thời gian", "Characters not allowed in file names (/ \\ : * ? \" < > |) become -; an existing name gets -1, -2….": "Ký tự không hợp lệ trong tên tệp (/ \\ : * ? \" < > |) thành -; tên đã tồn tại thêm -1, -2….", "Charcoal": "Than", "Check All": "Chọn tất cả", @@ -317,7 +319,6 @@ "Close panel": "Đóng bảng", "Cloudy": "Nhiều mây", "Cmd+Shift+R, keeps the photo and clears its edits.)": "Cmd+Shift+R, giữ ảnh và xóa chỉnh sửa.)", - "Collapse": "Thu gọn", "Collapse All Stacks": "Thu gọn mọi chồng", "Collapse Stack": "Thu gọn chồng", "Color": "Màu", @@ -399,6 +400,7 @@ "Create Smart Album from Filter…": "Tạo album thông minh từ bộ lọc…", "Create Smart Album…": "Tạo album thông minh…", "Create Stack": "Tạo chồng", + "Create Stacks": "Tạo chồng", "Create Version": "Tạo phiên bản", "Create Version from Step": "Tạo phiên bản từ bước", "Create Virtual Copy": "Tạo bản sao ảo", @@ -413,6 +415,7 @@ "Crop, Rotate, Geometry": "Cắt, xoay, hình học", "Cropped": "Đã cắt", "Cross Process": "Cross Process", + "Cull": "Sàng lọc", "Culling": "Sàng lọc", "Curve": "Đường cong", "Custom": "Tùy chỉnh", @@ -518,6 +521,7 @@ "Download Place Names (GeoNames)": "Tải tên địa điểm (GeoNames)", "Download the SAM 3 Model?": "Tải mô hình SAM 3?", "Downloaded and checked. Installing…": "Đã tải và kiểm tra. Đang cài…", + "The download failed": "Tải xuống không thành công", "Downloading model": "Đang tải mô hình", "Downloading place names": "Đang tải tên địa điểm", "Downloads": "Tải xuống", @@ -546,6 +550,7 @@ "Edit Info": "Thông tin chỉnh sửa", "Edit Keyword": "Sửa từ khóa", "Edit Keyword Set": "Sửa bộ từ khóa", + "Edit Keywords": "Sửa từ khóa", "Edit Keyword Tag": "Sửa thẻ từ khóa", "Edit Keyword Tag…": "Sửa thẻ từ khóa…", "Edit Label Names": "Sửa tên nhãn", @@ -571,6 +576,7 @@ "Effects": "Hiệu ứng", "Empty Recently Deleted": "Dọn Đã xóa gần đây", "Enable Lens Corrections": "Bật hiệu chỉnh ống kính", + "Enable Painting": "Bật cọ", "Enable Profile Corrections": "Bật hiệu chỉnh theo hồ sơ", "End Interaction": "Kết thúc tương tác", "English": "English", @@ -831,7 +837,7 @@ "Import from Device": "Nhập từ thiết bị", "Import from Folder…": "Nhập từ thư mục…", "Import new photos": "Nhập ảnh mới", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "Nhập ảnh bằng Tệp → Nhập ảnh… (Cmd+Shift+I), hoặc thả vào đây", + "Import photos with File → Import Photos…, or drop them here": "Nhập ảnh bằng Tệp → Nhập ảnh…, hoặc thả vào đây", "Import presets from other editors: XMP presets, classic `.lrtemplate` files, \"DNG presets\" from mobile apps and `.zip`": "Nhập thiết lập sẵn từ trình soạn khác: preset XMP, tệp `.lrtemplate` cổ điển, \"DNG presets\" từ app di động và `.zip`", "Import ▸ Copy verifies every copy, like Move (issue #96): each file is written as a new file, synced to disk and": "Nhập → Sao chép xác minh mọi bản sao, như Di chuyển (issue #96): mỗi tệp ghi thành tệp mới, đồng bộ ra đĩa và", "Import ▸ Move: photos go into the destination (with the same folders and renaming as Copy, e.g.": "Nhập → Di chuyển: ảnh vào đích (cùng thư mục và đổi tên như Sao chép, ví dụ", @@ -912,6 +918,7 @@ "Keyword Suggestions": "Gợi ý từ khóa", "Keyword Tag Options": "Tùy chọn thẻ từ khóa", "Keyword to paint": "Từ khóa để tô", + "Type a keyword to paint in the Keywords panel": "Nhập từ khóa để tô trong bảng Từ khóa", "Keywords": "Từ khóa", "Keywords & People": "Từ khóa và Người", "Keywords (K)": "Từ khóa (K)", @@ -958,6 +965,8 @@ "LightCraft could not start": "LightCraft không thể khởi động", "LightCraft couldn't find where to keep your library.": "LightCraft không tìm được nơi lưu thư viện của bạn.", "LightCraft couldn't open the library at": "LightCraft không mở được thư viện tại", + "There is no LightCraft library in this folder any more.": "Thư mục này không còn thư viện LightCraft nào.", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "Thư viện không có ở đây: nó đã bị di chuyển hoặc đổi tên, hoặc ổ đĩa hay ổ mạng của nó chưa được kết nối.", "LightCraft does not know this model, so it assumed:": "LightCraft không biết mô hình này, nên đã giả định:", "LightCraft no longer crashes at launch on Windows PCs whose Vulkan driver is broken (issue #136, e.g. some Intel UHD": "LightCraft không còn sự cố khi khởi động trên PC Windows có driver Vulkan lỗi (issue #136, ví dụ một số Intel UHD", "LightCraft on GitHub": "LightCraft trên GitHub", @@ -1371,6 +1380,12 @@ "Purple Saturation": "Độ bão hòa tím", "Put New Keywords Inside": "Đặt từ khóa mới vào trong", "Put New Keywords Inside This Keyword": "Đặt từ khóa mới vào trong từ khóa này", + "Use This as Keyword Shortcut": "Dùng làm phím tắt từ khóa", + "Set Keyword Shortcut": "Đặt phím tắt từ khóa", + "Set Keyword Shortcut…": "Đặt phím tắt từ khóa…", + "Add or Remove Keyword Shortcut": "Thêm hoặc gỡ phím tắt từ khóa", + "Keyword Shortcut": "Phím tắt từ khóa", + "Part of the keyword shortcut": "Thuộc phím tắt từ khóa", "Put the locations you removed from Local back (no files change)": "Đưa các vị trí đã gỡ khỏi Local trở lại (không đổi tệp)", "Quality": "Chất lượng", "Query Photos": "Truy vấn ảnh", @@ -1834,6 +1849,7 @@ "That includes the photos in the folders inside it.": "Bao gồm cả ảnh trong các thư mục bên trong.", "That key can't be used as a shortcut": "Phím đó không thể dùng làm phím tắt", "The SAM 3 model is installed: Object and Describe masks are ready.": "Đã cài mô hình SAM 3: Mặt nạ đối tượng và Mô tả đã sẵn sàng.", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Nút Thẻ liệt kê các phần giữ chỗ cho mẫu, chẳng hạn {date} hoặc {seq}. Mỗi tệp được đổi tên trên đĩa cùng với tệp phụ XMP của nó; tên đã dùng sẽ thêm -1, -2…", "The catalog has a format version (issue #102). Opening a library from an older LightCraft upgrades it; a library": "Catalog có phiên bản định dạng (issue #102). Mở thư viện từ LightCraft cũ hơn sẽ nâng cấp; thư viện", "The control port (`--control`) closes a connection as soon as it receives anything that isn't a JSON request": "Cổng điều khiển (`--control`) đóng kết nối ngay khi nhận bất kỳ thứ gì không phải yêu cầu JSON", "The denoise model is installed and in use: the AI Denoise Amount slider under Detail now works": "Mô hình khử nhiễu đã cài và đang dùng: thanh AI Denoise Amount trong Chi tiết giờ hoạt động", @@ -2228,6 +2244,7 @@ "Mask Pins": "Ghim mặt nạ", "Photo Counts": "Số lượng ảnh", "An import is running": "Đang có một lần nhập chạy", + "The photos are imported once it ends": "Ảnh sẽ được nhập khi việc đó kết thúc", "An import is running. Drop photos when it has finished": "Đang có một lần nhập chạy. Hãy thả ảnh khi nó hoàn tất", "Close the open dialog to drop files here": "Hãy đóng hộp thoại đang mở để thả tệp vào đây", "Close the open dialog, then drop the files again": "Hãy đóng hộp thoại đang mở, rồi thả lại các tệp", @@ -2235,5 +2252,437 @@ "Drop to open the face model": "Thả để mở mô hình khuôn mặt", "Dropped Files": "Tệp đã thả", "Finish Lightroom catalog import before adding photos": "Hoàn tất nhập danh mục Lightroom trước khi thêm ảnh", - "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại" + "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại", + "(not in the library)": "(không có trong thư viện)", + "1 raw can now be developed from its raw data": "Hiện có thể xử lý 1 tệp RAW từ dữ liệu thô", + "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · chỉnh sửa hiện tại · vừa khung không cắt xén", + "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Khung hình 16:9 với dải đen trên và dưới, tiêu đề ở góc, chuyển mờ qua nền đen và thẻ kết thúc.", + "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Phông nền xám đá tối với thông số phơi sáng, ISO và tiêu cự, cùng máy ảnh và ống kính bên dưới mỗi ảnh.", + "A face model uses the GPU only when a check shows it gives the same results faster.": "Mô hình khuôn mặt chỉ dùng GPU khi kiểm tra cho thấy kết quả tương đương nhưng nhanh hơn.", + "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Tường xám nhạt với bo viền trắng và bóng đổ mềm; chú thích và đánh giá nằm dưới ảnh.", + "A pen's pressure sets the size and flow of the brush": "Lực nhấn bút điều chỉnh kích thước và lưu lượng của cọ", + "A slide stays up for its duration, its fade in included. A fade of 0 cuts.": "Mỗi trang trình chiếu hiển thị trong thời lượng đã đặt, tính cả lúc hiện dần. Đặt chuyển mờ bằng 0 để chuyển cảnh ngay.", + "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.": "Video AV1, mỗi trang trình chiếu giữ theo thời lượng cùng hiệu ứng chuyển mờ. Không có âm thanh: chưa hỗ trợ xuất nhạc.", + "Add Print Cell": "Thêm ô in", + "Add a Face Recognition Model": "Thêm mô hình nhận diện khuôn mặt", + "Add a cell": "Thêm ô", + "Add a model file…": "Thêm tệp mô hình…", + "Add text overlay": "Thêm lớp phủ văn bản", + "Already installed. Installing again is harmless.": "Đã được cài đặt. Cài đặt lại cũng không gây ảnh hưởng gì.", + "Also the masks of the same name on the other selected photos": "Áp dụng cả cho các mặt nạ cùng tên trên những ảnh đã chọn khác", + "Anchored to": "Neo vào", + "Animal Eye Tracking": "Theo dõi mắt động vật", + "Another library was opened since the photos were dropped: nothing was moved": "Một thư viện khác đã được mở kể từ khi thả ảnh: chưa di chuyển tệp nào", + "Apply Mask Effect": "Áp dụng hiệu ứng mặt nạ", + "Apply Print Template": "Áp dụng mẫu in", + "Apply Slideshow Template": "Áp dụng mẫu trình chiếu", + "Apply to All Masks": "Áp dụng cho tất cả mặt nạ", + "Arrange Print Cell": "Sắp xếp ô in", + "Aspect preview": "Xem trước tỷ lệ", + "Auto Layout": "Bố cục tự động", + "Automatically show full screen": "Tự động hiển thị toàn màn hình", + "Backdrop": "Phông nền", + "Background colour": "Màu nền", + "Background image": "Ảnh nền", + "Before the last template": "Trước mẫu cuối cùng", + "Bottom": "Dưới", + "Built-in": "Tích hợp sẵn", + "CPU": "CPU", + "Can't be moved here": "Không thể chuyển vào đây", + "Cast shadow": "Đổ bóng", + "Center": "Giữa", + "Checking raw files": "Đang kiểm tra tệp RAW", + "Checking the GPU for faces": "Đang kiểm tra GPU cho nhận diện khuôn mặt", + "Checking the GPU…": "Đang kiểm tra GPU…", + "Choose Layout Image…": "Chọn ảnh bố cục…", + "Choose Monitor Profile": "Chọn hồ sơ màn hình", + "Choose a PDF destination after confirming. Print the PDF from your viewer.": "Chọn nơi lưu PDF sau khi xác nhận. Hãy in tệp PDF từ trình xem của bạn.", + "Choose a group": "Chọn một nhóm", + "Choose at least one setting to include": "Chọn ít nhất một cài đặt để bao gồm", + "Cinema Wide": "Điện ảnh rộng", + "Clear Print Layout": "Xóa bố cục in", + "Click a cell to move, resize or arrange it": "Nhấp vào ô để di chuyển, đổi kích thước hoặc sắp xếp", + "Click a template to apply it; point at one to preview it on the selected photo. Right-click your own to update, rename, export or delete it.": "Nhấp vào mẫu để áp dụng; trỏ vào mẫu để xem trước trên ảnh đã chọn. Nhấp chuột phải vào mẫu của bạn để cập nhật, đổi tên, xuất hoặc xóa.", + "Click to name this face": "Nhấp để đặt tên cho khuôn mặt này", + "Click to type a value, drag to change it": "Nhấp để nhập giá trị, kéo để thay đổi", + "Color Overlay": "Phủ màu", + "Color Overlay on B&W": "Phủ màu trên Đen & Trắng", + "Color space: Rec. 2020 HLG (HDR AVIF)": "Không gian màu: Rec. 2020 HLG (HDR AVIF)", + "Color space: Rec. 2020 PQ (HDR AVIF)": "Không gian màu: Rec. 2020 PQ (HDR AVIF)", + "Color space: Rec. 2020 PQ (HDR JPEG XL)": "Không gian màu: Rec. 2020 PQ (HDR JPEG XL)", + "Color space: Rec. 2020 PQ, 16-bit (HDR PNG)": "Không gian màu: Rec. 2020 PQ, 16-bit (HDR PNG)", + "Color wheel": "Bánh xe màu", + "Colour": "Màu", + "Colour only": "Chỉ màu", + "Colour wash": "Phủ sắc màu", + "Combine with the existing person": "Gộp với người đã có", + "Confirm before moving photos to another folder on disk": "Xác nhận trước khi di chuyển ảnh sang thư mục khác trên ổ đĩa", + "Contact Sheet PDF": "Bảng liên hệ PDF", + "Container": "Vùng chứa", + "Copy Settings…": "Sao chép cài đặt…", + "Curve channel": "Kênh đường cong", + "Custom AF Area": "Vùng AF tùy chỉnh", + "Cycle Flag": "Chuyển đổi cờ", + "Cycle Tool Overlay": "Chuyển đổi lớp phủ công cụ", + "Decrease Flag Status": "Giảm trạng thái cờ", + "Decrease Grid Thumbnail Size": "Giảm kích thước ảnh thu nhỏ trên lưới", + "Delete Cell": "Xóa ô", + "Delete Mask Effect": "Xóa hiệu ứng mặt nạ", + "Delete Print Cell": "Xóa ô in", + "Delete Print Template": "Xóa mẫu in", + "Delete Slideshow Template": "Xóa mẫu trình chiếu", + "Delete…": "Xóa…", + "Destination library": "Thư viện đích", + "Detection": "Phát hiện", + "Don't ask again": "Không hỏi lại", + "Duplicate Mask Effect": "Nhân bản hiệu ứng mặt nạ", + "Duration": "Thời lượng", + "Each photo as large as it fits, on black, with a short crossfade. Nothing drawn over it.": "Mỗi ảnh hiển thị lớn nhất vừa khung trên nền đen, với chuyển mờ ngắn. Không vẽ đè thông tin lên ảnh.", + "Edge to Edge": "Tràn viền", + "End": "Kết thúc", + "End Slideshow": "Kết thúc trình chiếu", + "Ending": "Kết thúc", + "Ending screen": "Màn hình kết thúc", + "Enter to confirm, Esc to cancel": "Enter để xác nhận, Esc để hủy", + "Every photo cropped to fill the whole screen, with slow crossfades.": "Mọi ảnh được cắt vừa kín toàn màn hình, với hiệu ứng chuyển mờ chậm.", + "Expanded Flexible Spot": "Điểm linh hoạt mở rộng", + "Export Effect Presets": "Xuất thiết lập hiệu ứng sẵn", + "Export Effect Presets…": "Xuất thiết lập hiệu ứng sẵn…", + "Export JPEG…": "Xuất JPEG…", + "Export Mask Effects": "Xuất hiệu ứng mặt nạ", + "Export PDF…": "Xuất PDF…", + "Export Slideshow": "Xuất bản trình chiếu", + "Export Slideshow Template": "Xuất mẫu trình chiếu", + "Export Slideshow: folder for the JPEG files": "Xuất bản trình chiếu: thư mục chứa tệp JPEG", + "Export Slideshow…": "Xuất bản trình chiếu…", + "Export Video…": "Xuất video…", + "Export to": "Xuất ra", + "Exporting slideshow": "Đang xuất bản trình chiếu", + "Face Models on the GPU": "Mô hình khuôn mặt trên GPU", + "Face Tracking": "Theo dõi khuôn mặt", + "Face models (ONNX)": "Mô hình khuôn mặt (ONNX)", + "Face tracking": "Theo dõi khuôn mặt", + "Fade": "Giảm dần", + "Fade duration": "Thời lượng chuyển mờ", + "Favorite": "Yêu thích", + "Favorite Mask Effect": "Yêu thích hiệu ứng mặt nạ", + "Filename captions": "Chú thích tên tệp", + "Filters": "Bộ lọc", + "Flexible Spot": "Điểm linh hoạt", + "Focus": "Lấy nét", + "Focus point": "Điểm lấy nét", + "Frame rate": "Tốc độ khung hình", + "Gallery Wall": "Tường trưng bày", + "Group (optional)": "Nhóm (tùy chọn)", + "Grouped by parent": "Nhóm theo mục cha", + "Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened.": "Theo nhóm: các từ khóa con trong cùng một từ khóa cha sẽ chung một dòng có tên mục cha, đồng thời danh sách dài và gợi ý được rút gọn.", + "HDR TIFF needs 32-bit float.": "TIFF HDR cần định dạng dấu phẩy động 32-bit.", + "HDR for Each Bracket Set": "Tạo HDR cho mỗi bộ chụp bù trừ sáng", + "HDR output": "Đầu ra HDR", + "Highlighted: sliders this mask changes. Sliders left out stay as they are when the preset is applied.": "Được tô sáng: các thanh trượt mà mặt nạ này thay đổi. Những thanh trượt không chọn sẽ giữ nguyên khi áp dụng thiết lập sẵn.", + "Hold View Until Refreshed": "Giữ nguyên chế độ xem cho đến khi làm mới", + "Human Eye Tracking": "Theo dõi mắt người", + "ICC Profiles": "Hồ sơ ICC", + "Identity plate": "Biểu trưng định danh", + "Image on Black": "Ảnh trên nền đen", + "Image on White": "Ảnh trên nền trắng", + "Import Mask Effects": "Nhập hiệu ứng mặt nạ", + "Import Slideshow Template": "Nhập mẫu trình chiếu", + "Import Slideshow Templates": "Nhập các mẫu trình chiếu", + "Import photos to get started": "Nhập ảnh để bắt đầu", + "Import…": "Nhập…", + "Include Amount": "Bao gồm Mức tác động", + "Include brush size, feather and flow": "Bao gồm kích thước cọ, độ nhòe biên và lưu lượng", + "Increase Flag Status": "Tăng trạng thái cờ", + "Increase Grid Thumbnail Size": "Tăng kích thước ảnh thu nhỏ trên lưới", + "Intro": "Mở đầu", + "Intro screen": "Màn hình mở đầu", + "Keywords of the selection": "Từ khóa của vùng chọn", + "Layout": "Bố cục", + "Layout Image Matte": "Bo viền ảnh bố cục", + "Layout Image Opacity": "Độ mờ đục ảnh bố cục", + "Left": "Trái", + "Letter": "Thư", + "LightCraft Effect Presets": "Thiết lập hiệu ứng LightCraft", + "LightCraft stopped": "LightCraft đã dừng", + "Lightroom Catalog Import": "Nhập danh mục Lightroom", + "Lightroom catalogs import into the open library; no separate catalog folder is created.": "Danh mục Lightroom được nhập vào thư viện đang mở; không tạo thư mục danh mục riêng.", + "Link all margins": "Liên kết tất cả các lề", + "Local photos aren't in the library yet: Add to My Photos first, then move them": "Ảnh cục bộ chưa có trong thư viện: hãy Thêm vào Ảnh của tôi trước, sau đó mới di chuyển", + "Lock On AF": "AF bám nét khóa mục tiêu", + "Manage Effect Presets…": "Quản lý thiết lập hiệu ứng sẵn…", + "Manage Presets…": "Quản lý thiết lập sẵn…", + "Managed by Printer (Adobe RGB)": "Do máy in quản lý (Adobe RGB)", + "Managed by Printer (sRGB)": "Do máy in quản lý (sRGB)", + "Margins": "Lề", + "Margins are a share of the slide's shorter side, so slides look the same on any screen.": "Lề được tính theo tỷ lệ cạnh ngắn của trang chiếu, giúp trang chiếu hiển thị đồng nhất trên mọi màn hình.", + "Mask": "Mặt nạ", + "Mask Effect Presets": "Thiết lập hiệu ứng mặt nạ sẵn", + "Masks keep their sliders. Export presets first to keep a copy.": "Các mặt nạ vẫn giữ nguyên thanh trượt. Hãy xuất thiết lập sẵn trước để lưu bản sao.", + "Move Mask Effect to Group": "Chuyển hiệu ứng mặt nạ vào nhóm", + "Move Photos": "Di chuyển ảnh", + "Move Print Cell": "Di chuyển ô in", + "Move Print Cell to Page": "Chuyển ô in sang trang", + "Move to Group…": "Di chuyển vào nhóm…", + "Multi": "Đa vùng", + "Name the preset": "Đặt tên thiết lập sẵn", + "New Print Page": "Trang in mới", + "New group — Return": "Nhóm mới — nhấn Return", + "New spot (Return adds it here)": "Điểm mới (nhấn Return để thêm tại đây)", + "New template name": "Tên mẫu mới", + "Next Slide": "Trang chiếu tiếp theo", + "Next page": "Trang tiếp theo", + "No Matte": "Không bo viền", + "No change": "Không thay đổi", + "No effect matches": "Không có hiệu ứng phù hợp", + "No effect presets yet": "Chưa có thiết lập hiệu ứng sẵn", + "No lens data embedded in this file.": "Không có dữ liệu ống kính nhúng trong tệp này.", + "None yet: save the current settings as a template below.": "Chưa có mẫu nào: hãy lưu cài đặt hiện tại thành mẫu ở bên dưới.", + "Not loaded yet": "Chưa tải", + "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.": "Các tệp JPEG đánh số thứ tự (tên-001.jpg…) trong thư mục mới được đặt tên ở bước tiếp theo.", + "Offset": "Dịch lệch", + "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode.": "Mỗi trang trình chiếu là một trang (cạnh dài tính bằng pixel = point), kèm thời lượng và hiệu ứng chuyển mờ cho chế độ thuyết trình của trình xem.", + "One photo fills each page inside the margins.": "Mỗi ảnh lấp đầy một trang bên trong phần lề.", + "Open Settings": "Mở Cài đặt", + "Overlay color": "Màu lớp phủ", + "Overlays": "Lớp phủ", + "Override colour": "Ghi đè màu", + "Own duration (off: the slide duration)": "Thời lượng riêng (tắt: dùng thời lượng trang chiếu)", + "Page": "Trang", + "Page Options": "Tùy chọn trang", + "Pause / Resume Slideshow": "Tạm dừng / Tiếp tục trình chiếu", + "Pen Pressure": "Áp lực bút", + "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Ảnh chỉnh sửa ở chế độ HDR: JPEG kèm bản đồ khuếch đại HDR (hiển thị chuẩn ở mọi nơi và sáng rõ vùng cao quang trên màn hình HDR), AVIF 10-bit, PNG và JPEG XL ở dạng 16-bit Rec. 2020 PQ; TIFF cần định dạng dấu phẩy động 32-bit", + "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Những ảnh bạn nhập sẽ hiển thị tại đây. Không có tệp nào bị sao chép hay di chuyển trừ khi bạn chọn.", + "Plain Black": "Đen tuyền", + "Playback": "Phát trình chiếu", + "Previous Slide": "Trang chiếu trước", + "Previous page": "Trang trước", + "Previous settings": "Cài đặt trước đó", + "Print Settings": "Cài đặt in", + "Print Templates": "Mẫu in", + "Print to PDF": "In thành PDF", + "Rating stars": "Sao đánh giá", + "Read Focus Points": "Đọc điểm lấy nét", + "Read Focus Points in the Background": "Đọc điểm lấy nét trong nền", + "Reading focus points": "Đang đọc điểm lấy nét", + "Recheck Preview-Only Raws": "Kiểm tra lại các tệp RAW chỉ có xem trước", + "Recognition": "Nhận diện", + "Refresh View": "Làm mới chế độ xem", + "Remove Folder Color Label": "Xóa nhãn màu thư mục", + "Remove region": "Xóa vùng", + "Rename Mask Effect": "Đổi tên hiệu ứng mặt nạ", + "Rename Mask Effect Group": "Đổi tên nhóm hiệu ứng mặt nạ", + "Rename Person": "Đổi tên người", + "Rename Person…": "Đổi tên người…", + "Rename Slideshow Template": "Đổi tên mẫu trình chiếu", + "Render behind image": "Kết xuất phía sau ảnh", + "Renders the next slides while the current one is up, so fades never wait. Off: each slide renders when it is due (less memory and work).": "Kết xuất trước các trang chiếu kế tiếp trong khi trang hiện tại đang hiển thị để hiệu ứng chuyển mờ luôn mượt. Tắt: chỉ kết xuất từng trang khi đến lượt (tiết kiệm bộ nhớ và tài nguyên hơn).", + "Reset Print Settings": "Đặt lại cài đặt in", + "Reset Sliders": "Đặt lại thanh trượt", + "Reset all edits": "Đặt lại mọi chỉnh sửa", + "Reset layout": "Đặt lại bố cục", + "Resize Print Cell": "Đổi kích thước ô in", + "Resize region": "Đổi kích thước vùng", + "Return creates this keyword and gives it to the selected photos": "Nhấn Return để tạo từ khóa này và gắn cho các ảnh đã chọn", + "Right": "Phải", + "Run face models on the CPU only": "Chỉ chạy mô hình khuôn mặt trên CPU", + "Same folder as original photo": "Cùng thư mục với ảnh gốc", + "Save Current Settings as New Effect Preset…": "Lưu cài đặt hiện tại thành thiết lập hiệu ứng mới…", + "Save Current Settings as New Preset…": "Lưu cài đặt hiện tại thành thiết lập sẵn mới…", + "Save Mask Effect": "Lưu hiệu ứng mặt nạ", + "Save Print Template": "Lưu mẫu in", + "Save Slideshow Template": "Lưu mẫu trình chiếu", + "Save as Template": "Lưu thành mẫu", + "Search effects": "Tìm hiệu ứng", + "Select Only Active Photo": "Chỉ chọn ảnh đang mở", + "Select a mask to apply or update presets.": "Chọn một mặt nạ để áp dụng hoặc cập nhật thiết lập sẵn.", + "Select a photo to preview its slide": "Chọn một ảnh để xem trước trang trình chiếu", + "Select a photo, then turn this on to fill the slide behind every photo with it.": "Chọn một ảnh, sau đó bật tùy chọn này để dùng ảnh đó làm nền trang chiếu phía sau mọi ảnh.", + "Select all": "Chọn tất cả", + "Select none": "Bỏ chọn tất cả", + "Separate several keywords with commas. Return gives them to the selected photos.": "Ngăn cách nhiều từ khóa bằng dấu phẩy. Nhấn Return để gắn cho các ảnh đã chọn.", + "Set Effect for New Masks": "Đặt hiệu ứng cho mặt nạ mới", + "Set Print Cell Photo": "Đặt ảnh cho ô in", + "Set Print Settings": "Đặt cài đặt in", + "Settings → Confirm before moving photos to another folder on disk turns it back on": "Có thể bật lại trong Cài đặt → Xác nhận trước khi di chuyển ảnh sang thư mục khác trên ổ đĩa", + "Shooting Data": "Thông số chụp", + "Show / hide": "Hiện / ẩn", + "Show Layout Image": "Hiện ảnh bố cục", + "Show every keyword of the selected photos": "Hiện mọi từ khóa của các ảnh đã chọn", + "Show fewer": "Hiện ít hơn", + "Show guides": "Hiện đường gióng", + "Show in Library": "Hiện trong Thư viện", + "Show mask": "Hiện mặt nạ", + "Show photos": "Hiện ảnh", + "Show the import review when a camera or card is connected": "Hiện hộp thoại xem lại nhập ảnh khi kết nối máy ảnh hoặc thẻ nhớ", + "Show this wheel's effect": "Hiện hiệu ứng của bánh xe màu này", + "Shows": "Hiển thị", + "Slide": "Trang chiếu", + "Slide duration": "Thời lượng trang chiếu", + "Slides use the slideshow's layout, overlays and intro and ending screens, in view order.": "Các trang chiếu sử dụng bố cục, lớp phủ cùng màn hình mở đầu và kết thúc của bản trình chiếu, theo thứ tự đang xem.", + "Slideshow Export Status": "Trạng thái xuất bản trình chiếu", + "Slideshow Layout Settings": "Cài đặt bố cục trình chiếu", + "Slideshow Options…": "Tùy chọn trình chiếu…", + "Slideshow Overlay Settings": "Cài đặt lớp phủ trình chiếu", + "Slideshow Playback Settings": "Cài đặt phát trình chiếu", + "Slideshow Slide Preview": "Xem trước trang trình chiếu", + "Slideshow Templates": "Mẫu trình chiếu", + "Slideshow Title Settings": "Cài đặt tiêu đề trình chiếu", + "Slideshow in the View menu plays the photos in view from the selected one. These settings are saved with the library.": "Trình chiếu trong trình đơn Xem sẽ phát các ảnh đang hiển thị bắt đầu từ ảnh đang chọn. Những cài đặt này được lưu cùng thư viện.", + "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Album thông minh tự động cập nhật: hãy thay đổi quy tắc hoặc dùng Ảnh → Xóa ảnh", + "Solo Mode": "Chế độ đơn (Solo)", + "Specific folder": "Thư mục cụ thể", + "Spot": "Chấm", + "Stroke border": "Đường viền nét", + "Template name": "Tên mẫu", + "Templates": "Mẫu", + "Text overlays": "Lớp phủ văn bản", + "The ending screen, after the last photo.": "Màn hình kết thúc, hiển thị sau bức ảnh cuối cùng.", + "The export watermark, drawn on the photo and sized relative to it.": "Hình mờ xuất ảnh, được vẽ lên ảnh và co giãn tỷ lệ theo kích thước ảnh.", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Màn hình mở đầu phát một lần trước ảnh đầu tiên; màn hình kết thúc phát sau ảnh cuối cùng khi tắt Lặp lại. Biểu trưng định danh được lấy từ phần Lớp phủ. Tiêu đề chuyển mờ giống như trang chiếu và không bị đổi vị trí khi bật thứ tự ngẫu nhiên.", + "The intro screen, before the first photo.": "Màn hình mở đầu, hiển thị trước bức ảnh đầu tiên.", + "The layout image can't be shown": "Không thể hiển thị ảnh bố cục", + "The photos in view as slides, with the settings above. Progress shows in the activity stack.": "Xuất các ảnh đang xem thành trang trình chiếu với cài đặt ở trên. Tiến độ sẽ hiển thị trong ngăn hoạt động.", + "The selected photo as a slide. Playback fills the screen; the aspect preview only changes this preview.": "Hiển thị ảnh đang chọn dưới dạng trang trình chiếu. Khi phát sẽ lấp đầy màn hình; xem trước tỷ lệ chỉ thay đổi khung xem trước này.", + "Their files and XMP sidecars move on disk. Edit → Undo moves them back.": "Các tệp ảnh và tệp phụ XMP sẽ được di chuyển trên ổ đĩa. Chọn Chỉnh sửa → Hoàn tác để chuyển về chỗ cũ.", + "Their photos in the grid": "Ảnh của họ trong lưới", + "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "Những ảnh này chỉ đang lưu trong bộ nhớ. Hãy mở một thư viện trên ổ đĩa và nhập lại danh mục để lưu chúng.", + "This page setup is not valid": "Thiết lập trang này không hợp lệ", + "This raw is now developed from its raw data": "Tệp RAW này hiện đã được xử lý từ dữ liệu thô", + "This raw variant still can't be decoded": "Biến thể RAW này hiện vẫn chưa thể giải mã", + "This row covers more than one disk: drop on a folder inside it": "Dòng này bao gồm nhiều ổ đĩa: hãy thả vào một thư mục cụ thể bên trong", + "This screen is off: turn it on under Titles to play it.": "Màn hình này đang tắt: hãy bật trong mục Tiêu đề để phát.", + "Thumbnail size": "Kích thước ảnh thu nhỏ", + "Import Thumbnail Size": "Kích thước ảnh thu nhỏ khi nhập", + "Tidying the thumbnail cache": "Đang dọn dẹp bộ nhớ đệm ảnh thu nhỏ", + "Title bar": "Thanh tiêu đề", + "Title text": "Văn bản tiêu đề", + "Titles": "Tiêu đề", + "Tokens: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. Other text shows as typed.": "Thẻ đại diện: {file}, {name}, {title}, {caption}, {date}, {exposure}, {iso}, {focal}, {camera}, {lens}, {rating}, {creator}, {copyright}. Các văn bản khác sẽ hiển thị đúng như bạn nhập.", + "Tool Overlay": "Lớp phủ công cụ", + "Top": "Trên", + "Tracking": "Giãn ký tự", + "Ungrouped": "Chưa phân nhóm", + "Unknown date": "Không rõ ngày", + "Unnamed face": "Khuôn mặt chưa đặt tên", + "Update Mask Effect": "Cập nhật hiệu ứng mặt nạ", + "Update Slideshow Template": "Cập nhật mẫu trình chiếu", + "Use export watermark": "Dùng hình mờ khi xuất", + "Use selected photo": "Dùng ảnh đang chọn", + "Viewers that don't read the PNG cICP chunk show PQ values as sRGB: flat and washed out. For a picture that looks right everywhere, use JPEG (gain map).": "Các trình xem không đọc khối cICP của PNG sẽ hiển thị giá trị PQ như sRGB: nhợt nhạt và thiếu tương phản. Để ảnh hiển thị chuẩn ở mọi nơi, hãy dùng JPEG (kèm bản đồ khuếch đại).", + "When pins show on the photo (Shift+H cycles)": "Khi ghim hiển thị trên ảnh (nhấn Shift+H để chuyển đổi)", + "White on Black": "Trắng trên nền đen", + "Whole names": "Toàn bộ tên", + "Wide": "Rộng", + "Write Waiting XMP Sidecars": "Ghi các tệp phụ XMP đang chờ", + "Wrote the XMP sidecars that were waiting": "Đã ghi xong các tệp phụ XMP đang chờ", + "Your library is empty": "Thư viện của bạn đang trống", + "Your name or studio": "Tên của bạn hoặc studio", + "Your own templates need a settings folder, which this build doesn't have; the built-in ones work.": "Mẫu riêng của bạn cần có thư mục cài đặt mà bản dựng này không có; các mẫu tích hợp sẵn vẫn hoạt động bình thường.", + "Your templates": "Mẫu của bạn", + "Zone": "Vùng", + "Zoom to Focus Point": "Phóng tới điểm lấy nét", + "Zoom to fill frame": "Phóng lấp đầy khung", + "cells": "ô", + "cells overlap": "các ô bị chồng lấp", + "current edits": "chỉnh sửa hiện tại", + "new keyword": "từ khóa mới", + "or drop a .onnx file on the window": "hoặc kéo thả tệp .onnx vào cửa sổ", + "or drop photos and folders into this window": "hoặc kéo thả ảnh và thư mục vào cửa sổ này", + "or drop photos into this window": "hoặc kéo thả ảnh vào cửa sổ này", + "size": "kích thước", + "source": "nguồn", + "★ Favorites": "★ Yêu thích", + "Always merge into the open library": "Luôn gộp vào thư viện đang mở", + "Another library was opened since this window appeared: nothing was imported": "Một thư viện khác đã được mở kể từ khi cửa sổ này xuất hiện: chưa nhập mục nào", + "Ask me": "Hỏi tôi", + "Ask me lists your recent libraries at launch. Holding Alt (Option on a Mac) as the window appears asks once.": "Tùy chọn Hỏi tôi sẽ liệt kê các thư viện gần đây khi khởi động. Giữ phím Alt (Option trên máy Mac) khi cửa sổ xuất hiện để hỏi một lần.", + "Ask where to import it": "Hỏi nơi nhập danh mục", + "At launch": "Khi khởi động", + "Burst: how alike (loose … strict)": "Chụp liên tiếp: mức độ tương đồng (lỏng … chặt)", + "Burst: shots at most this far apart": "Chụp liên tiếp: khoảng cách tối đa giữa các lần chụp", + "Camera & Lens": "Máy ảnh & Ống kính", + "Checking recent libraries": "Đang kiểm tra các thư viện gần đây", + "Choose the library to open.": "Chọn thư viện cần mở.", + "Click to hide clipping warnings for shadows and highlights.": "Nhấp để ẩn cảnh báo cháy sáng và bết tối.", + "Click to show clipping warnings for shadows and highlights.": "Nhấp để hiện cảnh báo cháy sáng và bết tối.", + "Close a dialog by clicking outside it": "Đóng hộp thoại khi nhấp ra bên ngoài", + "Create Library and Import": "Tạo thư viện và nhập", + "Create a new library": "Tạo thư viện mới", + "Dimensions": "Kích thước", + "Don't ask again (always merge into the open library)": "Không hỏi lại (luôn gộp vào thư viện đang mở)", + "Grid: add the next photo to the selection": "Lưới: thêm ảnh tiếp theo vào vùng chọn", + "Grid: add the previous photo to the selection": "Lưới: thêm ảnh trước đó vào vùng chọn", + "Grid: first photo of the view": "Lưới: ảnh đầu tiên trong khung xem", + "Grid: last photo of the view": "Lưới: ảnh cuối cùng trong khung xem", + "Hide this wheel's effect": "Ẩn hiệu ứng của vòng màu này", + "It is not a denoise model LightCraft understands": "Đây không phải là mô hình khử nhiễu mà LightCraft hỗ trợ", + "Last opened": "Mở lần cuối", + "LightCraft opens the new library, then imports the catalog into it. Its folder must be new or empty.": "LightCraft sẽ mở thư viện mới rồi nhập danh mục vào đó. Thư mục của thư viện phải là thư mục mới hoặc trống.", + "Loupe Info 1": "Thông tin kính lúp 1", + "Loupe Info 2": "Thông tin kính lúp 2", + "Loupe Overlay": "Lớp phủ kính lúp", + "Loupe View": "Chế độ kính lúp", + "Lower it when a panning or moving burst splits into several groups.": "Giảm giá trị này khi loạt chụp lia máy hoặc chuyển động bị tách thành nhiều nhóm.", + "M50, R100 and R8. CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100 và R8. Các tệp CR3 mà bộ giải mã chưa đọc được vẫn mở từ ảnh JPEG nhúng như trước.", + "My Preset": "Thiết lập sẵn của tôi", + "No clipping detected in this preview.": "Không phát hiện vùng cháy sáng hay bết tối trong bản xem trước này.", + "No faces by that name": "Không có khuôn mặt nào mang tên đó", + "No horizon or vertical lines to level by": "Không tìm thấy đường chân trời hoặc đường thẳng đứng để cân chỉnh", + "No named people yet. Name the faces below to start.": "Chưa có người nào được đặt tên. Hãy đặt tên cho các khuôn mặt bên dưới để bắt đầu.", + "No people yet": "Chưa có người nào", + "No person by that name": "Không có người nào mang tên đó", + "No recent libraries. Open one from a folder, or make a new one.": "Không có thư viện gần đây. Hãy mở một thư viện từ thư mục hoặc tạo thư viện mới.", + "No unnamed faces. Faces found in your photos appear here until you name them.": "Không có khuôn mặt chưa đặt tên. Các khuôn mặt tìm thấy trong ảnh sẽ xuất hiện tại đây cho đến khi bạn đặt tên.", + "Not answering yet: the drive may be asleep or offline": "Chưa phản hồi: ổ đĩa có thể đang ở chế độ ngủ hoặc ngoại tuyến", + "Not found: moved, renamed or on a disconnected drive": "Không tìm thấy: đã di chuyển, đổi tên hoặc nằm trên ổ đĩa đã ngắt kết nối", + "Open": "Mở", + "Open Another…": "Mở thư viện khác…", + "Open a Library": "Mở thư viện", + "Open a library first, then drop the presets again": "Hãy mở một thư viện trước, sau đó thả lại các thiết lập sẵn", + "Open now": "Mở ngay", + "Open the last library": "Mở thư viện gần nhất", + "Remove from List": "Xóa khỏi danh sách", + "Show Info Overlay": "Hiện lớp phủ thông tin", + "Show briefly when photo changes": "Hiện thoáng qua khi đổi ảnh", + "Show in Folders": "Hiển thị trong Thư mục", + "Show message when loading or rendering photos": "Hiện thông báo khi đang tải hoặc kết xuất ảnh", + "The catalog's photos, collections and edits join the ones already in this library.": "Ảnh, bộ sưu tập và các chỉnh sửa của danh mục sẽ được gộp vào thư viện hiện tại.", + "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library.": "Quá trình nhập chỉ đọc danh mục mà không làm thay đổi danh mục gốc. Tiếp theo, hãy chọn gộp ảnh, chỉnh sửa, từ khóa và bộ sưu tập vào thư viện đang mở hoặc đưa vào một thư viện mới.", + "The library is empty: the catalog's photos, collections and edits become its first.": "Thư viện đang trống: ảnh, bộ sưu tập và các chỉnh sửa của danh mục sẽ là những mục đầu tiên trong thư viện.", + "The library itself stays where it is.": "Bản thân thư viện vẫn giữ nguyên ở vị trí hiện tại.", + "The library's catalog can't be read:": "Không thể đọc danh mục của thư viện:", + "The photos are imported once a library is open": "Ảnh sẽ được nhập ngay khi mở một thư viện", + "There is no LightCraft library in this folder any more": "Không còn thư viện LightCraft nào trong thư mục này nữa", + "This folder can't be read:": "Không đọc được thư mục này:", + "This is a file, not a library folder": "Đây là một tệp, không phải thư mục thư viện", + "This library couldn't be checked": "Không thể kiểm tra thư viện này", + "This library couldn't be checked:": "Không thể kiểm tra thư viện này:", + "To be asked again: Settings → General → When importing a Lightroom catalog.": "Để được hỏi lại: Cài đặt → Chung → Khi nhập danh mục Lightroom.", + "Tool Overlay: Always": "Lớp phủ công cụ: Luôn hiện", + "Tool Overlay: Auto": "Lớp phủ công cụ: Tự động", + "Tool Overlay: Never": "Lớp phủ công cụ: Không bao giờ", + "Tool Overlay: Selected": "Lớp phủ công cụ: Khi chọn", + "Use Defaults": "Dùng mặc định", + "View Options": "Tùy chọn hiển thị", + "View Options…": "Tùy chọn hiển thị…", + "View → View Options chooses the lines Info 1 and Info 2 show.": "Xem → Tùy chọn hiển thị để chọn các dòng hiển thị trong Thông tin 1 và Thông tin 2.", + "When importing a Lightroom catalog": "Khi nhập danh mục Lightroom", + "Width & Height": "Chiều rộng & Chiều cao", + "Check for Updates…": "Kiểm tra cập nhật…", + "Checking for updates…": "Đang kiểm tra cập nhật…", + "LightCraft {version} is currently the newest version available.": "LightCraft {version} hiện là phiên bản mới nhất.", + "Could not check for updates:\n{error}": "Không thể kiểm tra cập nhật:\n{error}", + "LightCraft Updates": "Cập nhật LightCraft", + "Face recognition is on": "Nhận diện khuôn mặt đã bật", + "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Nhận diện khuôn mặt đang tắt. Hãy bật để nhận gợi ý tên và xem các khuôn mặt giống nhau cùng nhau.", + "Turn on": "Bật", + "Set up face recognition": "Thiết lập nhận diện khuôn mặt", + "Face recognition needs a model to suggest names: a one-time download, in Settings.": "Nhận diện khuôn mặt cần một mô hình để gợi ý tên: tải xuống một lần, trong Cài đặt.", + "Turn on name suggestions": "Bật gợi ý tên", + "Set up name suggestions…": "Thiết lập gợi ý tên…", + "Top bar": "Thanh trên cùng", + "Tool strip": "Thanh công cụ", + "Bottom bar": "Thanh dưới cùng" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b86..0a8b94115f 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -17,6 +17,7 @@ "Auto Sync: edits apply to {n} photos": "自动同步:编辑将应用到 {n} 张照片", "Automatic ({} MB)": "自动({0} MB)", "Click {}:1": "单击 {0}:1", + "Collapse {name}": "折叠 {name}", "Color space: Rec. 2020 {curve} (HDR AVIF)": "色彩空间:Rec. 2020 {curve}(HDR AVIF)", "Create {n} Virtual Copies": "创建 {n} 个虚拟副本", "Decoder: {reason}": "解码器:{reason}", @@ -26,6 +27,7 @@ "Delete “{current}”": "删除“{current}”", "Duplicate \"{label}\"": "复制 \"{label}\"", "Example: {example}": "示例:{example}", + "Expand {name}": "展开 {name}", "Exported {n} photo{}": "已导出 {n} 张照片{0:.0}", "Exported {ok} of {total} photo{}": "已导出 {total} 张中的 {ok} 张照片{0:.0}", "Exported {} point curve preset{}": "已导出 {0} 个点曲线预设{1:.0}", @@ -33,6 +35,7 @@ "Exporting {} of {total}": "正在导出 {total} 张中的第 {0} 张", "Filter bar — {active} active filter{}": "筛选栏 — 已启用 {active} 个筛选{0:.0}", "Healed {n} dust spot{}": "已修复 {n} 处尘点{0:.0}", + "Import photos with File → Import Photos… ({}), or drop them here": "使用“文件 → 导入照片…”({})导入照片,或将照片拖放到此处", "Imported {n} point curve preset{}": "已导入 {n} 个点曲线预设{0:.0}", "Imported {n} preset{}": "已导入 {n} 个预设{0:.0}", "Imported {n} preset{}, {f} file{} not readable": "已导入 {n} 个预设,{f} 个文件无法读取{0:.0}{1:.0}", @@ -99,7 +102,7 @@ "{n} photo{}": "{n} 张照片{0:.0}", "{n} photo{} match · updates automatically as photos change": "{n} 张照片符合 · 随照片变化自动更新{0:.0}", "{n} photo{} now · updates automatically as photos change": "当前 {n} 张照片 · 随照片变化自动更新{0:.0}", - "{n} selected photos · {pages} pages": "已选 {n} 张照片 · {pages} 页", + "{n} selected photo{} · {pages} page{}": "已选 {n} 张照片 · {pages} 页{:.0}{:.0}", "{sel_n} selected · {counted}": "已选择 {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {0:.0}%", "{what} merge added": "已添加 {what} 合并", @@ -135,6 +138,7 @@ "Label Set: {name}": "标签集:{name}", "Quick Develop: {name}": "快速编辑:{name}", "Reset {name}": "重置{name}", + "{name} value": "{name}的值", "Updated “{name}”": "已更新“{name}”", "{verb} {n} Photo{}": "{verb} {n} 张照片{:.0}", "{year}": "{year}年", @@ -156,7 +160,7 @@ "Auto Import: added {} photo{}": "自动导入:已添加 {0} 张照片{1:.0}", "Building previews for {} photos…": "正在为 {0} 张照片生成预览…", "Couldn't open the editor: {e}": "无法打开编辑器:{e}", - "Creates {} stacks from {} of {scope}": "将从{scope}中的 {1} 张照片创建 {0} 个堆叠", + "Creates {stacks} stack{} from {photos} of {scope}": "将从{scope}中的 {photos} 张照片创建 {stacks} 个堆叠{:.0}", "Done ({what}): {done} photo{plural}": "完成({what}):{done} 张照片{plural:.0}", "Focus {:.0}": "对焦 {0:.0}", "Folder “{}” (and its subfolders)": "文件夹“{0}”(含子文件夹)", @@ -231,6 +235,7 @@ "“{parent}” has a “{name}” already. Merge the two?": "“{parent}”中已有“{name}”。要合并两者吗?", "There is a “{name}” at the top level already. Merge the two?": "顶层已有“{name}”。要合并两者吗?", "Added “{keyword}” to {n} photo{}": "已将“{keyword}”添加到 {n} 张照片{:.0}", + "Add Keyword “{keywords}”": "添加关键字“{keywords}”", "On {have} of {of} selected photos": "所选 {of} 张照片中的 {have} 张", "Remove “{name}”": "移除“{name}”", "There is a keyword set “{name}” already": "已有关键字集“{name}”", @@ -252,6 +257,7 @@ "{what} merge cancelled": "已取消 {what} 合并", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "已跳过 {n} 张本地照片{0:.0}:相册只能收录图库中的照片(请先添加到我的照片)", "New Folder in “{name}”": "在“{name}”中新建文件夹", + "Created folder “{name}” in “{parent}”": "已在“{parent}”中创建文件夹“{name}”", "Moved {} photo(s)": "已移动 {} 张照片", "not added to Apple Photos: {e}": "未添加到 Apple 照片:{e}", "{n} added to Apple Photos album “{album}”": "已将 {n} 个添加到 Apple 照片相册“{album}”", @@ -273,6 +279,7 @@ "{n} originals opened in the other editor": "已在其他编辑器中打开 {n} 个原始文件", "· {in_source} identical copies": "· {in_source} 个相同副本", "{count} more warnings.": "另有 {count} 条警告。", + "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "目录中有 {in_trash} 张照片位于此图库的“最近删除”中,并将保留在那里;如需查看,请从“最近删除”中恢复。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "有 {skipped} 张图像未导入,因为它们在目录中的记录不完整。", "{photos} catalog records processed; {collections} collections.": "已处理 {photos} 条目录记录;{collections} 个收藏集。", "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "有 {missing} 个原始文件缺失。其目录记录可用;请使用“查找缺失照片”重新链接文件。", @@ -285,7 +292,7 @@ "Skipped {problem}": "已跳过:{problem}", "…and {more} more": "…还有 {more} 个", "Template preview: {name}": "模板预览:{name}", - "{n} photos in view · {slides} slides · {time}": "视图中 {n} 张照片 · {slides} 张幻灯片 · {time}", + "{n} photo{} in view · {slides} slide{} · {time}": "视图中 {n} 张照片 · {slides} 张幻灯片 · {time}{:.0}{:.0}", "{n} pages": "{n} 页", "{n} JPEG files": "{n} 个 JPEG 文件", "{s} s of AV1 video": "{s} 秒 AV1 视频", @@ -305,5 +312,10 @@ "Could not read {name}: {e}": "无法读取 {name}:{e}", "Added {n} photo{}": "已添加 {n} 张照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", - "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}", + "Photo: {name}": "照片:{name}", + "Panel layout could not be restored: {error}": "无法恢复面板布局:{error}", + "Panel move was not applied: {error}": "面板移动未应用:{error}", + "{name} is installed": "{name} 已安装", + "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a625..ea867f35e6 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -44,6 +44,7 @@ "Add to Local": "添加到本地", "Add to My Photos": "添加到我的照片", "Can't be moved here": "无法移到这里", + "Import photos with File → Import Photos…, or drop them here": "使用“文件 → 导入照片…”导入照片,或将照片拖放到此处", "This row covers more than one disk: drop on a folder inside it": "此行涵盖多个磁盘:请拖放到其中的文件夹", "Local photos aren't in the library yet: Add to My Photos first, then move them": "本地照片尚未在图库中:请先“添加到我的照片”,再移动", "Add to Selected Photos": "添加到所选照片", @@ -122,6 +123,7 @@ "Auto-Tag Photos from Tracklog": "从轨迹日志自动标记照片", "Auto-Tag from Tracklog": "从轨迹日志自动标记", "Auto-Tag from Tracklog…": "从轨迹日志自动标记…", + "Add Locations": "添加位置", "Automatic": "自动", "Automatically Write Changes into XMP": "自动将更改写入 XMP", "Automatically write changes into XMP sidecars": "自动将更改写入 XMP 附属文件", @@ -338,6 +340,9 @@ "Crop, Rotate, Geometry": "裁剪、旋转、几何", "Cross Process": "交叉冲洗", "Culling": "挑片", + "Cull": "筛选", + "Create Stacks": "创建堆叠", + "Change Time": "更改时间", "Curve": "曲线", "Custom": "自定义", "Custom template…": "自定义模板…", @@ -456,6 +461,7 @@ "Effects": "效果", "Empty Recently Deleted": "清空“最近删除”", "Enable Lens Corrections": "启用镜头校正", + "Enable Painting": "启用画笔", "Enable Profile Corrections": "启用配置文件校正", "End Interaction": "结束交互", "English": "English", @@ -494,6 +500,7 @@ "Faded Matte": "褪色哑光", "Faded Slide": "褪色正片", "Faded Urban": "褪色都市", + "Favorite": "收藏", "Favorite Preset": "收藏预设", "Favorite Profile": "收藏配置文件", "Favorites": "收藏夹", @@ -802,7 +809,6 @@ "Import Profiles & Presets…": "导入配置文件与预设…", "Import from Device": "从设备导入", "Import from Folder…": "从文件夹导入…", - "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here": "使用“文件 → 导入照片…”(Cmd+Shift+I)导入照片,或将照片拖放到此处", "Imported Photos": "已导入的照片", "Importing": "正在导入", "Importing scans the source for photos; it doesn't add the folder to Local (use Local → Browse Folder… to work in a folder without importing).": "导入会扫描源中的照片,但不会将该文件夹添加到“本地”(若想在不导入的情况下处理某个文件夹,请使用“本地 → 浏览文件夹…”)。", @@ -839,6 +845,7 @@ "Keyword Sets": "关键字集", "Keyword Suggestions": "关键字建议", "Keyword to paint": "要涂抹的关键字", + "Type a keyword to paint in the Keywords panel": "请在“关键字”面板中输入要涂抹的关键字", "Keywords": "关键字", "Keywords (K)": "关键字 (K)", "Keywords you add appear here; ⌥1–⌥9 apply them.": "您添加的关键字会显示在此处;按 ⌥1–⌥9 即可应用。", @@ -867,6 +874,9 @@ "LightCraft Website": "LightCraft 网站", "LightCraft couldn't find where to keep your library.": "LightCraft 找不到保存图库的位置。", "LightCraft couldn't open the library at": "LightCraft 无法打开以下位置的图库:", + "There is no LightCraft library in this folder any more.": "此文件夹中已经没有 LightCraft 图库。", + "The library isn't there: it was moved or renamed, or its drive or network share isn't connected.": "图库不在这里:它已被移动或重命名,或者它所在的驱动器或网络共享未连接。", + "This folder can't be read:": "无法读取此文件夹:", "LightCraft on GitHub": "GitHub 上的 LightCraft", "LightCraft website": "LightCraft 网站", "LightCraft — Second Window": "LightCraft — 第二窗口", @@ -1456,6 +1466,7 @@ "Table": "表格", "Tags": "标签", "Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…": "标签:请参阅模板旁的“标签”。文件将在磁盘上重命名(连同其 XMP 附属文件);已有同名文件会得到 -1、-2…", + "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "“标签”按钮会列出可用于模板的占位符,例如 {date} 或 {seq}。每个文件会连同其 XMP 附属文件在磁盘上重命名;名称已被占用时会加上 -1、-2…", "Take a snapshot": "创建快照", "Targeted Adjustment": "局部调整", "Targeted adjustment: drag up/down on the photo to adjust the colours there": "局部调整:在照片上上下拖动以调整该处的颜色", @@ -1684,7 +1695,6 @@ "Moves the photos imported from this folder to Recently Deleted; no file is touched": "将从此文件夹导入的照片移到“最近删除”;不会改动任何文件", "Remove Disk from Library…": "从图库中移除磁盘…", "Moves every photo imported from this disk to Recently Deleted; no file is touched": "将从此磁盘导入的所有照片移到“最近删除”;不会改动任何文件", - "Collapse": "折叠", "Expand": "展开", "Remove Disk from Library": "从图库中移除磁盘", "All the photos imported from this disk are included.": "包括从此磁盘导入的所有照片。", @@ -1711,6 +1721,7 @@ "Denoise Settings": "降噪设置", "Denoise all photos with an Amount": "对所有设置了数量的照片进行降噪", "Downloaded and checked. Installing…": "已下载并校验完成。正在安装…", + "The download failed": "下载失败。", "Failed its last test": "上次检测未通过", "Graphics card": "显卡", "I have read these terms and accept them for my own use": "我已阅读这些条款,并为个人使用表示接受", @@ -1874,6 +1885,12 @@ "No photo has it; the keywords below it go too.": "没有照片使用它;其下的关键字也会一并删除。", "Edit Keyword Tag…": "编辑关键字标记…", "Put New Keywords Inside This Keyword": "将新关键字放入此关键字中", + "Use This as Keyword Shortcut": "用作关键字快捷方式", + "Set Keyword Shortcut": "设置关键字快捷方式", + "Set Keyword Shortcut…": "设置关键字快捷方式…", + "Add or Remove Keyword Shortcut": "添加或移除关键字快捷方式", + "Keyword Shortcut": "关键字快捷方式", + "Part of the keyword shortcut": "属于关键字快捷方式", "Purge Unused Keywords": "清除未使用的关键字", "Delete Keyword…": "删除关键字…", "Drop here for the top level": "拖放到此处以移至顶层", @@ -1885,6 +1902,7 @@ "& Containing": "及上级", "Edit Set…": "编辑关键字集…", "Edit Keyword Set": "编辑关键字集", + "Edit Keywords": "编辑关键字", "Keywords (⌥1–⌥9)": "关键字 (⌥1–⌥9)", "A keyword set needs a name": "关键字集需要名称", "Save as a new set": "另存为新关键字集", @@ -2177,6 +2195,7 @@ "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "只有检查表明 GPU 能更快给出相同结果时,人脸模型才会使用 GPU。", "Checking the GPU for faces": "正在检查用于人脸的 GPU", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 闪烁(下次启动时生效)", "Include selected photos": "包含所选照片", "Suggests who is in a photo from the faces you have named. Everything stays on your computer.": "根据你已命名的人脸,推测照片中的人物。所有数据仅保存在本机。", "This build cannot run recognition models: they can be added and chosen, not used.": "此版本无法运行识别模型:可以添加和选择,但无法使用。", @@ -2199,6 +2218,176 @@ "Dropped Files": "拖入的文件", "Import dropped files without review": "不经检查直接导入拖入的文件", "An import is running": "正在导入", + "The photos are imported once it ends": "结束后即导入这些照片", "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", - "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入" + "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", + "Thumbnail size": "缩略图大小", + "Import Thumbnail Size": "导入缩略图大小", + "\"saved in memory but not written to disk\", the top bar shows a warning, and LightCraft keeps retrying until the": "“已保存在内存中但未写入磁盘”,顶栏会显示警告,LightCraft 会持续重试,直到", + "#106): a DNG is checked against the raw data, written to a temp file, synced and read back before it gets its": "#106):DNG 会先与原始数据核对,写入临时文件、同步并读回校验,然后才获得其", + "(`gpuReason`, `gpuFallback`), Help ▸ System Info and Settings ▸ Performance say why the GPU isn't": "(`gpuReason`、`gpuFallback`)——帮助 → 系统信息 和 设置 → 性能 会说明为何未使用 GPU", + "(e.g. D750, D780, D850, D7500, Z 50) no longer render nearly black or with crushed shadows: their black level was": "(如 D750、D780、D850、D7500、Z 50)不再近乎全黑或阴影死黑:其黑电平之前被", + "(issue #94): an HTTP request from a web page can no longer carry a command in its body. Lines are capped at": "(问题 #94):网页发出的 HTTP 请求不再能在请求体中携带命令。每行长度上限为", + "123 on studio-mac)\") instead of letting both write and silently drop each other's edits. A crash never leaves the": "123(位于 studio-mac)\"),而不是让双方同时写入、悄然丢弃彼此的编辑。崩溃绝不会让", + "1620 × 1080 preview, and import with their metadata: capture time, camera, lens, exposure, GPS and XMP. Their raw": "1620 × 1080 预览,并连同其元数据一起导入:拍摄时间、相机、镜头、曝光、GPS 和 XMP。它们的原始数据", + "23 new built-in presets: Portrait, Landscape, Urban, Food, Seasons, Vintage and B&W toners.": "新增 23 款内置预设:人像、风光、城市、美食、四季、复古和黑白调色。", + "4 MiB and connections at 16.": "4 MiB,连接数上限为 16。", + "630 drivers): on Windows the window and GPU rendering use DirectX 12 only and never load the Vulkan driver unless": "630 显卡驱动):在 Windows 上,窗口和 GPU 渲染仅使用 DirectX 12,除非明确要求,否则绝不加载 Vulkan 驱动", + "`img_1-1.JPG`; on case-insensitive volumes the case change still goes through.": "`img_1-1.JPG`;在大小写不敏感的卷上,大小写更改仍会生效。", + "`Photos/2026/20260114/20260114_001.jpg`) together with their XMP sidecars; each original leaves the card only after its": "`Photos/2026/20260114/20260114_001.jpg`)连同其 XMP 附属文件;每张原图只有在其", + "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "无法保存到磁盘的更改(磁盘已满或已拔出)不再无声失败:命令会报告", + "a full drive) no longer counts as built and Build Smart Previews replaces it.": "(磁盘已满)不再被算作已构建,可用“构建智能预览”重新构建。", + "A library is open in one program at a time (issue #99): opening a library that LightCraft or `lightcraft-cli` already": "一个图库同时只能由一个程序打开(问题 #99):打开 LightCraft 或 `lightcraft-cli` 已打开的图库时", + "A save that fails part-way (a full disk, a network share that drops) no longer looks like a damaged catalog": "保存中途失败(磁盘已满、网络共享断开)不再表现为图库损坏", + "A sleeping NAS, a dropped network share or a USB drive spinning up no longer freezes the window (issue #104):": "休眠的 NAS、断开的网络共享或正在启动的 USB 硬盘不再让窗口卡死(问题 #104):", + "afterwards (issue #101): the partial write is cut off before LightCraft retries, so the next launch replays every": "之后(问题 #101):部分写入会在 LightCraft 重试前被截断,因此下次启动会重放所有", + "again. Change the period (or turn it off) in Settings → Performance.": "在 设置 → 性能 中更改周期(或将其关闭)。", + "against the library's originals no longer scans the whole library when nothing is at that path.": "与图库原图核对时,若该路径下没有文件,不再扫描整个图库。", + "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "AI 蒙版使用 SAM 3(蒙版面板中的“对象”和“描述”):点击对象即可选中(⌥-点击会留下一个", + "already has a `thumbs/` folder of other pictures no longer loses them when the cache is trimmed or cleared.": "已包含其他图片 `thumbs/` 文件夹的图库,在缓存清理时不再丢失这些图片。", + "and checks the file before using it. Masks keep their selection, so they render and export without the model.": "并在使用前检查文件。蒙版会保留其选区,因此无需模型即可渲染和导出。", + "and every imported photo as one zip, and File ▸ Restore Library from Backup… brings it back (the current library": "以及每张导入的照片打包为一个 zip,文件 → 从备份恢复图库… 可将其还原(当前图库", + "and never freezes the window. It is optional and not part of LightCraft (Meta's SAM License, about 3.4 GB): the": "并且绝不会让窗口卡死。它是可选的,不属于 LightCraft 的一部分(Meta 的 SAM 许可,约 3.4 GB):", + "as `.corrupt-