diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 51fe5db60e..9ba55da629 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,6 +1,6 @@ # Changes here need a review from one of these people (main's ruleset requires code-owner review). # Workflows, and the scripts and tooling the release jobs hand signing secrets to. -# See docs/releasing.md, "Who can start a release". +# See docs/release-process.md, "Who can start a release". /.github/workflows/ @emmertex @clydecbrown @OneSlips /.github/scripts/ @emmertex @clydecbrown @OneSlips /.github/CODEOWNERS @emmertex @clydecbrown @OneSlips diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 87f3994796..c98a56af9c 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -26,7 +26,7 @@ Fixes # ## How it was checked -- [ ] `cargo xtask ci --fast`, `cargo xtask sil` and `cargo test -p` for the touched crates pass on this branch, up to +- [ ] `cargo xtask ci --quick`, `cargo xtask sil` and `cargo test -p` for the touched crates pass on this branch, up to date with `staging` (merged in, not rebased) - [ ] A test that fails without this change (for a crash fix: a hostile-input check that the bad input gives an error, not a panic) @@ -67,7 +67,7 @@ Fixes # free in `docs/library-shortcuts.md` - [ ] The feature's rows in `docs/parity-checklist.md` and its entry in `docs/gaps.md` are updated, honestly (🟡 when it is partial), in the same commit -- [ ] User-visible change: the manual is updated in the same commit (`docs/manual-site/`, `docs/manual/`; pages: ______), +- [ ] User-visible change: the manual is updated in the same commit (`docs/manual-site/`; pages: ______), and screenshots it made stale are retaken or marked `` — or this changes nothing a user sees - [ ] New code has a caller: no command, module or setting that nothing reaches yet - [ ] Every new image, icon or other asset has its entry in `assets/ATTRIBUTION.md`; no font or media files added diff --git a/.github/PULL_REQUEST_TEMPLATE/licence-conversion.md b/.github/PULL_REQUEST_TEMPLATE/licence-conversion.md new file mode 100644 index 0000000000..50e106ffea --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/licence-conversion.md @@ -0,0 +1,45 @@ + + +## What this converts + + + +## Permission + + + +- [ ] The copyright holder requested this conversion, or is the author of this PR +- [ ] Every converted file is the contributor's own work, not adopted third-party or vendored code +- [ ] Files owned by other copyright holders are untouched, with their notices intact + +## Change + +- [ ] Licence fields and headers now say `GPL-3.0-or-later` (or the crate's existing GPL-compatible expression) +- [ ] `NOTICE`, `assets/ATTRIBUTION.md` and any README or licence statement for the converted work updated +- [ ] `docs/license-status.md` updated in this PR: inventory row, ambiguity cleared, and the "Next" list +- [ ] Adopted third-party licences and notices were not weakened or removed + +## How it was checked + +- [ ] `git grep -n -i 'MIT\|Apache-2.0'` on the converted paths: remaining hits are adopted code and correct +- [ ] `cargo xtask brand check`, `cargo xtask docs --check` and `cargo xtask assets` pass +- [ ] `cargo deny check licenses` passes when a manifest changed (or "no manifest change") + +## Notes + + diff --git a/.github/scripts/sign-checksums.sh b/.github/scripts/sign-checksums.sh index 08cbca9f6d..3d3dafb68f 100755 --- a/.github/scripts/sign-checksums.sh +++ b/.github/scripts/sign-checksums.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Signs a release's SHA256SUMS.txt for the in-app updater, which installs nothing without a valid -# signature (crates/updater/src/signature.rs, docs/releasing.md → Update signing key). +# signature (crates/updater/src/signature.rs, docs/release-process.md → Update signing key). # # UPDATE_SIGNING_KEY= .github/scripts/sign-checksums.sh # diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6a41ef0c3b..8dd3b0f706 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,6 @@ # Release pipeline: every push to `release` builds platform artifacts (signed where credentials # are configured) and creates or updates the draft GitHub Release " v". -# See docs/releasing.md. +# See docs/release-process.md. # # The version job creates (or reuses) the draft; each platform job uploads its own files to it with # `gh release upload` (Actions artifacts crawl from the self-hosted runners), plus a few-byte checksum @@ -12,7 +12,7 @@ # without it. Only the `release` branch drafts a release: elsewhere the version job refuses unless # it is a dry run. # -# Every job runs on the maintainer's self-hosted runners (docs/ci.md, docs/releasing.md): Linux and +# Every job runs on the maintainer's self-hosted runners (docs/ci.md, docs/release-process.md): Linux and # Flatpak in containers on gpu0, Android (arm64 + x86_64, cross-compiled) on gpu0, macOS on mac0, # Windows x64 on win0, Windows ARM64 natively on SNAPDRAGON. A manual dispatch is a dry run by default # (`dry_run`): the signing jobs then run without the `release` environment (unsigned), no draft is @@ -135,7 +135,7 @@ jobs: - id: draft name: Create or reuse the draft release # Platform jobs upload into it as they finish; the release job adds checksums, latest.json and - # notes. It stays a draft: publishing is a separate, manual step (docs/releasing.md). + # notes. It stays a draft: publishing is a separate, manual step (docs/release-process.md). env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} @@ -293,7 +293,7 @@ jobs: permissions: contents: write # Self-hosted: x64 on win0, ARM64 natively on SNAPDRAGON (Windows on ARM with the ARM64 MSVC tools; - # win0 has none). Signing and WiX run the same on both. docs/releasing.md. + # win0 has none). Signing and WiX run the same on both. docs/release-process.md. runs-on: ${{ fromJSON(matrix.runner) }} environment: ${{ (github.event_name == 'workflow_dispatch' && inputs.dry_run) && '' || 'release' }} strategy: @@ -438,7 +438,7 @@ jobs: # Self-hosted gpu0, in an Ubuntu 22.04 container, so the binaries only need glibc >= 2.35 (Ubuntu # 22.04+, Debian 12+, Fedora 36+, RHEL 10). Rust, the cargo registry and the target dir live in # named Docker volumes (incremental between runs; never the runners' own target dirs). See - # docs/releasing.md. + # docs/release-process.md. runs-on: [self-hosted, Linux, X64, lcc] container: image: ubuntu:22.04 @@ -1070,7 +1070,7 @@ jobs: done ` `` `` - `` ``. +- Docs (Markdown) just write the real names: Chromaforge, `chromaforge`, `chromaforge-cli`, `CHROMAFORGE_*`. Templates + (`README.md.in`, `calibrate-lightroom.md.in`) use `{{…}}` fields where a value must be rendered (`{{website}}`, + `{{cli_binary}}`, …), rendered by `cargo xtask docs`. - Crates `lcc-*`; binaries `lcc-app`/`lcc-cli`/`lcc-web`; in `target/` always `app`/`app-cli` (brand names via - `cargo xtask run|package|install`). Env vars `_X` (e.g. `_PROFILE`); legacy prefix still read. + `cargo xtask run|package|install`). Env vars `CHROMAFORGE_X` (e.g. `CHROMAFORGE_PROFILE`); legacy prefix still read. ## Session start 1. [`docs/status.md`](docs/status.md) (tracked: milestone, next task, blockers, metrics) → the local plan it names @@ -44,7 +44,7 @@ This is the one rulebook for agents and humans; `CLAUDE.md` only imports it. Cla `gh pr update-branch N` does). PRs to `staging` run the fast gate only — no tests; the full suite gates the periodic batch PR `staging` → `main`, which lands once green and is what keeps `main` tested (nightly and fuzzing guard it afterwards; [docs/ci.md](docs/ci.md)). Merge agent branches one at a time with -`cargo xtask ci --fast` + targeted tests between (two green branches can still conflict). Resuming after a crash: +`cargo xtask ci --quick` + targeted tests between (two green branches can still conflict). Resuming after a crash: check `git status` on staging, `git worktree list`, `staging..HEAD` per worktree; commit small and often. **Permanent branches:** `staging`, `main` and `release` are never deleted, renamed or force-pushed, and none of @@ -71,7 +71,8 @@ never a panic. Never ship a panic path; fix crashes before building on them. Thi (JNI VM/activity adoption), `crates/winspool` (Win32 print spooler), `crates/winmsi` (`MsiEnumClientsW` + `MsiGetComponentPathW` for the updater), `crates/winjob` (a kill-on-close job object, so the Windows CLI launcher's app ends with it), `crates/firstclick` (macOS: replaces `acceptsFirstMouse:` on winit's window view, - for the background-click setting), `crates/libraw` (FFI into its C shim over LibRaw, opt-in, see Non-negotiables), and `apps/android`'s `#[unsafe(no_mangle)] android_main`. Every other + for the background-click setting), `crates/opendocs` (macOS: adds `application:openURLs:` to winit's application + delegate, so photos opened from Finder, the Dock or Open With reach the app), `crates/libraw` (FFI into its C shim over LibRaw, opt-in, see Non-negotiables), and `apps/android`'s `#[unsafe(no_mangle)] android_main`. Every other production crate root has `#![forbid(unsafe_code)]`. New unsafe need → isolated, well-tested helper crate: `// SAFETY:` everywhere, safe API, safe fallback, and a line here naming it. - Input-derived numbers are hostile: `get()` not `[i]`/`[a..b]`; checked/saturating math; no division by zero, @@ -113,12 +114,12 @@ never a panic. Never ship a panic path; fix crashes before building on them. Thi - **Release notes:** one file per change: `docs/whats-new/-.md` (one `### Title` + bullets) and, if the changelog should mention it, `docs/changelog/unreleased/-.md` (one `## Section` + bullets); READMEs there say how. Never touch `docs/whats-new.md` (frozen) or released `docs/changelog/.md`; - `cargo xtask notes --check` (in `ci`) fails if `docs/whats-new.md` changes outside an upstream merge. + `cargo xtask notes --check` (in `ci`) fails if `docs/whats-new.md` changes. - **The manual moves with the product:** any change a user can notice (new/changed/removed feature, command, menu item, panel, slider, setting, shortcut, default, file format, platform or install step, or a screenshot that no longer - matches) updates the manual **in the same commit**. The manual has two parts: the page-per-feature site in + matches) updates the manual **in the same commit**. The manual is the page-per-feature site in `docs/manual-site/src/content/docs/` (picture-first; rules and screenshot runner in - [`docs/manual-site/AUTHORING.md`](docs/manual-site/AUTHORING.md)) and the markdown guide in `docs/manual/`. Edit the + [`docs/manual-site/AUTHORING.md`](docs/manual-site/AUTHORING.md)). Edit the page that names the feature, or add one; fix every sentence the change makes false; retake affected shots (`scripts/shots.d/.json`) or mark them ``; add a row to `reference/` when it adds a menu item or shortcut. Removing a feature removes its manual text. Mention "Manual: " (or "Manual: none, no user-visible @@ -136,12 +137,15 @@ never a panic. Never ship a panic path; fix crashes before building on them. Thi ## Third-party sources: licence and derivation policy One rule (2026-11-10): **use only material you may legally derive from.** -- **In:** licences allowing derivatives + sharing + commercial use — permissive (MIT, BSD, Apache-2.0, ISC, Zlib, …) - and share-alike (GPL, LGPL, AGPL, CC BY, CC BY-SA, CC0/public domain), open source or not. Read, port, bundle, ship. +- **In, external dependencies:** licences allowing derivatives + sharing + commercial use — GPL, LGPL, AGPL, + Apache-2.0, MIT, BSD, ISC, Zlib, CC BY, CC BY-SA, CC0/public domain. Dependencies are complete modules/libraries. +- **In, code copied into this repository:** adopted code must be GPL-3.0-compatible GPL or Apache-2.0. MIT is + allowed only as a complete, isolated module/library or a plugin; never merged into core. Core code is + `GPL-3.0-or-later` only. - **Out:** CC BY-NC, CC BY-ND, "research only"/"non-commercial", no licence, Adobe's own files (DCP/LCP, presets, assets — proprietary). -- Share-alike code in a distributed binary puts the binary under those terms; our dual licence already offers - GPL-3.0-or-later; `NOTICE` says what shipped. +- Share-alike code in a distributed binary puts the binary under those terms; our GPL-3.0-or-later licence and + `NOTICE` say what shipped. - **Provenance:** every port names its source — commit **Sources:** line, module docs saying "translated from"/"read as a reference" (never "no code copied" when structure follows a source), `NOTICE` credit + licence text next to the material. @@ -157,19 +161,29 @@ One rule (2026-11-10): **use only material you may legally derive from.** synthetic charts or on photos whose owner agrees, fit our own models to it, and ship the fitted parameters or tables as data (e.g. Capture One midtone tables in `crates/develop/src/levels_table.rs`; Lightroom tone-slider fits for #1120/#1124). Name the source app, method and sample set in module docs and `NOTICE`. Only the numbers ship: no - copied files, assets or rendered photos. Camera calibrations still go through ` calibrate-lightroom add`. + copied files, assets or rendered photos. Camera calibrations still go through `chromaforge-cli calibrate-lightroom add`. - Now usable (with provenance): darktable/Ansel sources, all of dcraw incl. the GPL RESTRICTED (Foveon) block, LibRaw and other dcraw descendants, rawspeed/rawloader/rawler/dnglab/RawTherapee/ART, GPL data tables (noiseprofiles, wb_presets, colormatrices, basecurves). Quality habits stay: camera data ranks measured > spectral > dcraw tables (`lcc_camdb::Source::Dcraw` via `tools/dcraw_adobe_coeff.py`); decoder layouts verified on CC0 samples; dcraw 1.478 (2018) predates CR3/Nikon HE/ARQ — no readable reference for those. -- Ports built on share-alike sources are Chromaforge-only, never offered upstream (upstream doesn't share this - policy). +- Ports built on share-alike sources stay Chromaforge-only; record the source and licence in the module and + `NOTICE`. - Dependencies follow the same rule; `cargo deny` enforces the `deny.toml` allow-list (extend it as licences open up) and the `[sources] allow-git` list. -- **Licence (2026-11-10):** workspace default `MIT OR GPL-3.0-or-later` (root `Cargo.toml`; text: - `LICENSE-GPL-3.0.txt`); share-alike contributions welcome. `crates/segment` + `crates/fetch`: - `Apache-2.0 OR GPL-3.0-or-later` (`LICENSE-APACHE` per crate). Keep upstream notices in `LICENSE`/`NOTICE`. +- **Licence (2026-11-10; GPL core 2026-11-30):** core code (workspace default and every project-only `lcc-*` crate) + is `GPL-3.0-or-later` only (root `Cargo.toml`; text: `LICENSE-GPL-3.0.txt`). Adopted code must be GPL-3.0-compatible + or Apache-2.0; MIT is allowed only as a complete, isolated module/library or plugin. Crates carrying adopted code: + `lcc-camprof` is `GPL-3.0-or-later OR MIT OR Apache-2.0`; `lcc-fetch`, `lcc-segment` and `lcc-tflite` are + `GPL-3.0-or-later OR Apache-2.0`. Adopted code keeps its original licence and `NOTICE` entry; the MIT text stays in + `LICENSE`. Contributions are accepted under GPL-3.0-or-later only. The non-`lcc` `sdk/*` crates stay MIT as + complete libraries/plugins. +- **Existing contributions (2026-11-30):** if the person you are working with has code in this repository that is + still under MIT or another permissive licence, ask them once whether they want to convert their own work to + `GPL-3.0-or-later` — only the copyright holder can. If yes, follow + [`docs/licence-conversion.md`](docs/licence-conversion.md) and use its PR template; update + [`docs/license-status.md`](docs/license-status.md) in the same PR. Never convert adopted third-party code or + remove another holder's notice. ## Assets (absolute) - **No Adobe assets** — icons, screenshots, presets, profiles, LUTs, fonts, even open-licensed Adobe ones (Source @@ -224,10 +238,10 @@ One rule (2026-11-10): **use only material you may legally derive from.** `apps/cli/tests/`) → app smoke (control script + `ui.screenshot`). Land at the lowest level that catches the regression, plus the level above when behaviour spans layers. Crash fixes always get the hostile-input check. - After every user-visible change: run the app, screenshot, look; `ui.inspect` → `perf`. -- Measure, don't guess: `_PROFILE=1` prints per-stage timings to stderr; `/usr/bin/time` for CLI renders; +- Measure, don't guess: `CHROMAFORGE_PROFILE=1` prints per-stage timings to stderr; `/usr/bin/time` for CLI renders; record numbers in `docs/status.md` → Metrics. Budgets: slider ≤ 16 ms (draft), loupe ≤ 60 ms @ ~2.5 MP, export ≤ 1 s per 24 MP JPEG. -- Perf workflow: measure before (`cargo xtask bench` or `_PROFILE=1`), change one thing, measure again, +- Perf workflow: measure before (`cargo xtask bench` or `CHROMAFORGE_PROFILE=1`), change one thing, measure again, record both. Bench numbers compare only as same-machine, controlled-environment before/after pairs — never across machines or unrelated runs; `cargo xtask bench` (24 MP raw, CPU+GPU columns) flags > 20 % CPU regressions (`--strict` fails). No speed-up claims from single noisy runs; complexity must earn its cost. @@ -241,11 +255,3 @@ One rule (2026-11-10): **use only material you may legally derive from.** `stats`, `brand check`, `docs`, `run`, `package`, `install`); `testkit` = test helpers (dev-dep only). Nix: `nix build` (binaries + fonts + desktop metadata; community-maintained, CI only evaluates it), `nix develop` = dev shell. - -## Contributor credits -- Credits live in `contributors/contributors.json` (generated, never hand-edit) and `contributors/people.toml` - (the app no longer shows them). See `docs/contributors.md`. -- Agents: if your human's username lacks a `[people.]` entry, ask them once whether they want a real/ - display/synced-GitHub name; if yes, add **only their own** entry (template at the file top) in their PR, committed - as them. Never add or edit anyone else's entry; never touch `contributors.json`. -- Maintainers refresh stats with `python3 contributors/fork-contributors.py` (`gh` signed in, `upstream` fetched). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 13dd38a3d9..bdf8b2db85 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,9 +8,10 @@ Questions/ideas: [the Discord](https://discord.gg/c3dfYATzsQ), [project channel] - [`docs/gaps.md`](docs/gaps.md) (impact-ranked; `B` = beta blocker), [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature/menu item/shortcut), or a GitHub issue. - **Check nobody has it:** claims live in issue comments; search open PRs for the issue number and checklist id. -- **Check upstream:** upstream is no longer merged — each round is reviewed and ported by hand - ([`docs/upstream-pr-intake.md`](docs/upstream-pr-intake.md)), landing as one fork PR. Search the log and open PRs - for the upstream issue/PR number before starting; the fix may be ported already or due to be. +- **Upstream:** no code is taken, ever — no PRs, commits, patches or merges, whatever the licence. Use it for ideas + and observed behaviour, then rewrite; do not copy code or open intake PRs. Adopted code from other sources must + be GPL-3.0-compatible or Apache-2.0; MIT only as a complete, isolated module/library or plugin + ([`docs/upstream-pr-intake.md`](docs/upstream-pr-intake.md)). ## Claim it @@ -23,7 +24,8 @@ issue. A checklist row with no issue is named in the PR title instead. target `main` directly — batches of `staging` land there together, see [`docs/ci.md`](docs/ci.md); `staging`, `main` and `release` are permanent and never a PR's head). GitHub merges only up-to-date branches: when `staging` moves, merge it in, re-run the checks, push. -- **Template** ([`.github/PULL_REQUEST_TEMPLATE.md`](.github/PULL_REQUEST_TEMPLATE.md)); one change per PR. +- **Template** ([`.github/PULL_REQUEST_TEMPLATE.md`](.github/PULL_REQUEST_TEMPLATE.md)); a licence conversion uses + [`licence-conversion.md`](.github/PULL_REQUEST_TEMPLATE/licence-conversion.md). One change per PR. - **Title:** task/checklist id first, as commits do (`LR-IMP-FORMATS: …`), or `Issue #123: …`. - **Description:** `Fixes #123` (or `Part of #123`); what you changed and how you checked it (tests, app, screenshots for UI). @@ -35,7 +37,7 @@ issue. A checklist row with no issue is named in the PR title instead. - **One task id per commit**, with the docs it moves (parity-checklist rows, gaps entry, ROADMAP/target-app-parity numbers) in the same commit. - **Manual:** a user-visible change (feature, menu item, setting, shortcut, default, platform, screenshot) updates the - matching page in `docs/manual-site/src/content/docs/` and/or `docs/manual/` in the same commit; see + matching page in `docs/manual-site/src/content/docs/` in the same commit; see [`docs/manual-site/AUTHORING.md`](docs/manual-site/AUTHORING.md). The PR says which pages, or "none". - **Release notes:** user-visible changes add `docs/whats-new/-.md` (+ `docs/changelog/unreleased/…`); the READMEs there say how. @@ -43,16 +45,13 @@ issue. A checklist row with no issue is named in the PR title instead. What may be read: [`AGENTS.md`](AGENTS.md) → third-party policy. - **Assets:** every image/icon/font gets an [`assets/ATTRIBUTION.md`](assets/ATTRIBUTION.md) entry in the same commit. New fonts go to [craft-fonts](https://github.com/storytold/craft-fonts), not here. -- **Licence:** contributions are offered under the licence of the code you change — `MIT OR GPL-3.0-or-later` - (default; GPL-3.0-or-later share-alike welcome, [`LICENSE-GPL-3.0.txt`](LICENSE-GPL-3.0.txt)); `crates/segment` + - `crates/fetch` also offer Apache-2.0. +- **Licence:** core contributions are offered under `GPL-3.0-or-later` only + ([`LICENSE-GPL-3.0.txt`](LICENSE-GPL-3.0.txt)). Adopted code must be GPL-3.0-compatible or Apache-2.0; MIT only as + a complete, isolated module/library or plugin. Adopted code keeps its original licence and `NOTICE` entry. + If you contributed your own code before 2026-11-30, you can convert it to `GPL-3.0-or-later`: see + [`docs/licence-conversion.md`](docs/licence-conversion.md). - CI is maintainer-run; a fork PR's result can come back hours after push. -## Credits - -The About window credits everyone by GitHub username; add a real/display name via **your own** entry in -`contributors/people.toml` ([`docs/contributors.md`](docs/contributors.md)). Only ever change your own entry. - ## Working with an agent Your agent follows [`AGENTS.md`](AGENTS.md) and this page; you are the author of what it submits — read its PR diff --git a/Cargo.lock b/Cargo.lock index 7aaf25fc87..60aff04684 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1486,16 +1486,38 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4dc543cb449cc232e4c3d58f78a05c1ab169db9e#4dc543cb449cc232e4c3d58f78a05c1ab169db9e" +source = "git+https://github.com/storytold/craft-libs?rev=27c2cbf821ccf3842f789484f0234460cfcd07a6#27c2cbf821ccf3842f789484f0234460cfcd07a6" +dependencies = [ + "serde", +] [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=a4db799563c9ccd7217e1731ec34c58f6ba57248#a4db799563c9ccd7217e1731ec34c58f6ba57248" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a4db799563c9ccd7217e1731ec34c58f6ba57248#a4db799563c9ccd7217e1731ec34c58f6ba57248" dependencies = [ + "serde", "thiserror 2.0.21", ] +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a4db799563c9ccd7217e1731ec34c58f6ba57248#a4db799563c9ccd7217e1731ec34c58f6ba57248" +dependencies = [ + "craft-time", + "serde", + "web-time", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -2525,8 +2547,8 @@ checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" [[package]] name = "filmcraft-aac" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "thiserror 2.0.21", @@ -2534,16 +2556,16 @@ dependencies = [ [[package]] name = "filmcraft-ac3" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "thiserror 2.0.21", ] [[package]] name = "filmcraft-apv" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2552,8 +2574,8 @@ dependencies = [ [[package]] name = "filmcraft-av1" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2562,24 +2584,24 @@ dependencies = [ [[package]] name = "filmcraft-bitstream" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "craft-media", ] [[package]] name = "filmcraft-color" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "serde", ] [[package]] name = "filmcraft-dnx" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2588,8 +2610,8 @@ dependencies = [ [[package]] name = "filmcraft-frame" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-color", "filmcraft-time", @@ -2599,8 +2621,8 @@ dependencies = [ [[package]] name = "filmcraft-h264" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2609,8 +2631,8 @@ dependencies = [ [[package]] name = "filmcraft-h264enc" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2619,8 +2641,8 @@ dependencies = [ [[package]] name = "filmcraft-hevc" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2629,24 +2651,24 @@ dependencies = [ [[package]] name = "filmcraft-isobmff" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "craft-media", ] [[package]] name = "filmcraft-matroska" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "craft-media", ] [[package]] name = "filmcraft-mpeg2v" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2654,29 +2676,29 @@ dependencies = [ [[package]] name = "filmcraft-mpegts" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "thiserror 2.0.21", ] [[package]] name = "filmcraft-mxf" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "chrono", ] [[package]] name = "filmcraft-opus" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" [[package]] name = "filmcraft-prores" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -2685,16 +2707,17 @@ dependencies = [ [[package]] name = "filmcraft-time" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ - "serde", + "craft-time", + "craft-timeline", ] [[package]] name = "filmcraft-vp9" -version = "0.17.0" -source = "git+https://github.com/emmertex/filmcraft?rev=3f0cb5f2a906087e5fdc1cd0bb685527da717ba4#3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" +version = "0.21.0" +source = "git+https://github.com/emmertex/filmcraft?rev=4b82c5a1337dfad846a4a50e868c57ae4502f06c#4b82c5a1337dfad846a4a50e868c57ae4502f06c" dependencies = [ "filmcraft-bitstream", "rayon", @@ -4581,6 +4604,7 @@ dependencies = [ "lcc-gpu", "lcc-gpumem", "lcc-hdrmeta", + "lcc-opendocs", "lcc-pipeline", "lcc-preview", "lcc-raster", @@ -5325,6 +5349,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "lcc-opendocs" +version = "26.49.0" +dependencies = [ + "block2 0.6.2", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "lcc-pdf" version = "26.49.0" diff --git a/Cargo.toml b/Cargo.toml index 86aa1a22b8..1af6b171cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,12 +8,12 @@ exclude = ["vendor", "sdk"] [workspace.package] version = "26.49.0" edition = "2024" -license = "MIT OR GPL-3.0-or-later" +license = "GPL-3.0-or-later" rust-version = "1.95" [workspace.dependencies] craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "4dc543cb449cc232e4c3d58f78a05c1ab169db9e", features = ["serde"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4dc543cb449cc232e4c3d58f78a05c1ab169db9e" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "27c2cbf821ccf3842f789484f0234460cfcd07a6" } # internal lcc-brand = { path = "crates/brand" } lcc-notes = { path = "crates/notes" } @@ -31,6 +31,7 @@ lcc-winspool = { path = "crates/winspool" } lcc-winmsi = { path = "crates/winmsi" } lcc-winjob = { path = "crates/winjob" } lcc-firstclick = { path = "crates/firstclick" } +lcc-opendocs = { path = "crates/opendocs" } lcc-android-host = { path = "crates/android-host" } lcc-peer = { path = "crates/peer" } lcc-sync = { path = "crates/sync" } diff --git a/LICENSE b/LICENSE index 03125091b9..f288702d2f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,23 +1,674 @@ -MIT License - -Copyright (c) the LightCraft contributors -Copyright (c) the PhotoCraft contributors -Copyright (c) the project contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/LICENSE-APACHE2 b/LICENSE-APACHE2 new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/LICENSE-APACHE2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-GPL-3.0.txt b/LICENSE-GPL-3.0.txt deleted file mode 100644 index f288702d2f..0000000000 --- a/LICENSE-GPL-3.0.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000000..03125091b9 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) the LightCraft contributors +Copyright (c) the PhotoCraft contributors +Copyright (c) the project contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NOTICE b/NOTICE index a8defc83f0..55a0f96f7e 100644 --- a/NOTICE +++ b/NOTICE @@ -1,7 +1,9 @@ -This software is dual-licensed (maintainer decision 2026-11-10): you may use it under the MIT -License (LICENSE) or, at your option, the GNU General Public License version 3 or later -(LICENSE-GPL-3.0.txt). crates/segment and crates/fetch additionally remain available under the -Apache License 2.0 inherited from upstream (see LICENSE-APACHE in each of those crate folders). +The lcc crates and this application are licensed under the GNU General Public License version 3 or +later (LICENSE-GPL-3.0.txt) (maintainer decisions 2026-11-10 and 2026-11-30). Core code is GPL-only. +Adopted code must be GPL-3.0-compatible or Apache-2.0; MIT is allowed only as a complete, isolated module/library +or plugin. Adopted code keeps its original licence, as stated below (the MIT text is in LICENSE, Apache texts sit +beside the relevant crates). Those crates also carry the original option: lcc-camprof is +GPL-3.0-or-later OR MIT OR Apache-2.0; lcc-fetch, lcc-segment and lcc-tflite are GPL-3.0-or-later OR Apache-2.0. Upstream attribution @@ -139,8 +141,8 @@ crates/segment (lightcraft-segment) ports the SAM 3 model code of Hugging Face T Copyright The HuggingFace Team and Meta Platforms, Inc., licensed under the Apache License 2.0. The port was modified by the upstream contributors (2026): translated from Python/PyTorch to Rust on candle and restructured; each ported file says so. Because of this, crates/segment is -licensed under the Apache License 2.0 only (crates/segment/LICENSE-APACHE), not under MIT. -crates/fetch is likewise licensed under the Apache License 2.0 only (crates/fetch/LICENSE-APACHE). +licensed under GPL-3.0-or-later OR Apache-2.0 (crates/segment/LICENSE-APACHE), not under MIT. +crates/fetch is likewise licensed under GPL-3.0-or-later OR Apache-2.0 (crates/fetch/LICENSE-APACHE). The SAM 3 weights are not part of this software and are never distributed with it. A user downloads the facebook/sam3 checkpoint only when they choose to (in the app, or by hand), under Meta's SAM @@ -296,7 +298,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -crates/tflite (lcc-tflite, Apache License 2.0) — a TensorFlow Lite interpreter written by OneSlips +crates/tflite (lcc-tflite; its TensorFlow-derived portions are Apache License 2.0) — a TensorFlow Lite interpreter written by OneSlips in 2026 from the TensorFlow Lite model schema (schema.fbs: field order, enum values, option defaults; Copyright The TensorFlow Authors, Apache License 2.0) and the documented behaviour of its builtin operators; no TensorFlow code was copied. Its MediaPipe landmark index lists are data @@ -306,7 +308,8 @@ from MediaPipe's face_landmarks_connections (Copyright 2023 The MediaPipe Author crates/camprof (lcc-camprof) ports the camera-profiling engine of RADcamProfiles (https://github.com/OneSlips/RADcamProfiles, commit dd8003f, crates/engine), Copyright (c) 2026 RAD Films - Roman Alurkoff (@OneSlips), licensed under the MIT License and relicensed under the MIT License or the -Apache License 2.0 by its author. It is clean-room, own work, confirmed by the author 2026-11-03: no DCamProf +Apache License 2.0 by its author. It is distributed as part of the GPL-3.0-or-later work; those ported files +remain available under MIT or Apache-2.0. It is clean-room, own work, confirmed by the author 2026-11-03: no DCamProf or other GPL code was used, and its data is public or the author's own. The port was modified by the Chromaforge contributors (2026); each ported file says so. It carries the CIE 1931 2-degree colour-matching functions and the CIE standard illuminants A, D50, D55, D65, D75 and E (CIE 015:2018 / ISO/CIE 11664 diff --git a/PRIVACY.md b/PRIVACY.md index 4be0247e8f..2006a5ec96 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -13,7 +13,7 @@ catalog, edits, keywords, faces and settings stay on your device. The developers The app works offline. It only connects to the network for the features below. None of these requests carries personal data beyond what any web request reveals to the server it goes to: your IP address, the time, and a -User-Agent of the form `/`. No identifier for you or your device is sent. +User-Agent of the form `chromaforge/`. No identifier for you or your device is sent. | Feature | Server | What is sent | When | How to avoid it | |---|---|---|---|---| diff --git a/README.md b/README.md index 1c73b9f657..b881e440c0 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@

- Licence: MIT + Licence: GPL-3.0-or-later Rust Platforms: macOS, Windows, Linux, web, Android

@@ -19,7 +19,7 @@ Download · Features · Install · - Manual · + Manual · Roadmap · Licence

@@ -41,7 +41,7 @@ UI, the CLI, a control channel and an MCP server all share. - **Local-first:** no account, no cloud, no telemetry, no subscription. The network is used only for things you turn on. - **Non-destructive:** originals are never touched; edits live in the catalog and, if you like, in XMP sidecars. - **Drivable end to end by AI agents** over MCP, with undo for everything they do. -- **Open source** (MIT). Chromaforge is a fork of an open-source project; its copyright notices are kept in [NOTICE](NOTICE) +- **Open source** (GPL-3.0-or-later). Chromaforge is a fork of an open-source project; its copyright notices are kept in [NOTICE](NOTICE) and [LICENSE](LICENSE). ## Contents @@ -49,8 +49,7 @@ UI, the CLI, a control channel and an MCP server all share. - [Features](#features): [modules](#seven-modules-one-catalog) · [editing](#editing) · [masking](#masking) · [library & culling](#library-and-culling) · [video](#video) · [beyond the darkroom](#beyond-the-darkroom) - [Install](#install) · [Keyboard](#keyboard) · [Licence and credits](#licence-and-credits) -- [Manual](docs/manual/README.md): [building from source and contributing](docs/manual/build-and-contribute.md) · - [agents, MCP, performance and feature status](docs/manual/agents-and-status.md) · +- [Manual](https://emmertex.github.io/chromaforge/): [contributing](CONTRIBUTING.md) · [roadmap](ROADMAP.md) # Features @@ -147,7 +146,7 @@ Clips live in the same library as your photos. MP4, MOV, MKV, WebM, MPEG-TS and ProRes, DNxHR, APV or MPEG-2 decode in pure Rust. Play a clip in the loupe (Space, ← / → for single frames), drag the trim handles, pick the poster frame the grid shows, and capture any frame as a photo. The Light and Color controls (and presets that use only them) grade every frame. Export writes H.264 MP4 or -ProRes MOV with the trim, the grade and the sound (graded on the GPU for H.264); ` render clip.mov -o out.mp4 --trim 2,8` does the same from +ProRes MOV with the trim, the grade and the sound (graded on the GPU for H.264); `chromaforge-cli render clip.mov -o out.mp4 --trim 2,8` does the same from the command line. Interlaced H.264 (AVCHD 1080i) is deinterlaced. Masks, spot removal, lens corrections and crop don't apply to video. See [docs/video.md](docs/video.md). @@ -171,19 +170,19 @@ See [docs/video.md](docs/video.md). Not sure which file you need? The [Download page](https://emmertex.github.io/chromaforge/download/) picks the right one for your computer. Release builds are listed on the project's releases page. `` in the file names is the version number, -``/`` are the brand binary names, and `SHA256SUMS.txt` lists a checksum for every file. Build them yourself +`chromaforge`/`chromaforge-cli` are the brand binary names, and `SHA256SUMS.txt` lists a checksum for every file. Build them yourself with `cargo xtask package`. ### Windows | Build | Installer | Portable | |---|---|---| -| x64 (64-bit Intel/AMD) | `--windows-x64.msi` | `--windows-x64-portable.zip` | -| arm64 (Snapdragon and other ARM PCs) | `--windows-arm64.msi` | `--windows-arm64-portable.zip` | +| x64 (64-bit Intel/AMD) | `chromaforge--windows-x64.msi` | `chromaforge--windows-x64-portable.zip` | +| arm64 (Snapdragon and other ARM PCs) | `chromaforge--windows-arm64.msi` | `chromaforge--windows-arm64-portable.zip` | -The installers and executables are not code-signed, so Windows SmartScreen may warn the first time you run them (More info ▸ Run anyway). The installer asks where to install (`C:\Program Files\` by +The installers and executables are not code-signed, so Windows SmartScreen may warn the first time you run them (More info ▸ Run anyway). The installer asks where to install (`C:\Program Files\Chromaforge` by default; upgrades stay in the folder you chose) and ends on a page confirming the app was installed, with an -option to start it. For unattended installs: `msiexec /i --windows-x64.msi /qn INSTALLFOLDER="D:\Apps\\"`. +option to start it. For unattended installs: `msiexec /i chromaforge--windows-x64.msi /qn INSTALLFOLDER="D:\Apps\Chromaforge\"`. **Update or uninstall asks for an old `.msi`, or stops with error 1612 or 1714?** Windows removes the installed version with its own cached copy of that version's installer; if the copy is gone, it asks for the original file and stops @@ -197,19 +196,19 @@ message. | Build | File | Notes | |---|---|---| -| App, Apple silicon | `--macos-arm64.dmg` | Not signed or notarized: macOS asks you to allow it on first open ([how](docs/manual/getting-started.md#install)) | -| App, Intel | `--macos-x64.dmg` | As above | -| Command-line tool | inside the app: `.app/Contents/MacOS/` | Updates with the app; to run it from Terminal, link it onto `PATH` ([how](docs/manual/getting-started.md#install)) | +| App, Apple silicon | `chromaforge--macos-arm64.dmg` | Not signed or notarized: macOS asks you to allow it on first open ([how](https://emmertex.github.io/chromaforge/start/install/)) | +| App, Intel | `chromaforge--macos-x64.dmg` | As above | +| Command-line tool | inside the app: `Chromaforge.app/Contents/MacOS/chromaforge-cli` | Updates with the app; to run it from Terminal, link it onto `PATH` ([how](https://emmertex.github.io/chromaforge/start/install/)) | ### Linux | Format | x86_64 | Notes | |---|---|---| -| AppImage | `--linux-x86_64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) | -| Flatpak | `--linux-x86_64.flatpak` | Sandboxed; `flatpak install --user ` | -| Debian/Ubuntu | `--linux-x86_64.deb` | | -| Fedora/RHEL/openSUSE | `--linux-x86_64.rpm` | | -| Tarball | `--linux-x86_64.tar.gz` | Unpack anywhere | +| AppImage | `chromaforge--linux-x86_64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) | +| Flatpak | `chromaforge--linux-x86_64.flatpak` | Sandboxed; `flatpak install --user ` | +| Debian/Ubuntu | `chromaforge--linux-x86_64.deb` | | +| Fedora/RHEL/openSUSE | `chromaforge--linux-x86_64.rpm` | | +| Tarball | `chromaforge--linux-x86_64.tar.gz` | Unpack anywhere | Linux ARM64 (aarch64) builds are paused; `packaging/linux/package.sh aarch64` still builds one locally. @@ -246,9 +245,9 @@ Install from the release's APKs: | Build | File | Notes | |---|---|---| -| Phones and tablets (arm64) | `--android-arm64-v8a.apk` | Sideload: allow installs from your browser or file manager, then open the file | -| Emulator and Chromebooks (x86_64) | `--android-x86_64.apk` | | -| Play Store bundle | `--android-arm64-v8a-x86_64.aab` | For Play Console uploads, not for installing | +| Phones and tablets (arm64) | `chromaforge--android-arm64-v8a.apk` | Sideload: allow installs from your browser or file manager, then open the file | +| Emulator and Chromebooks (x86_64) | `chromaforge--android-x86_64.apk` | | +| Play Store bundle | `chromaforge--android-arm64-v8a-x86_64.aab` | For Play Console uploads, not for installing | Android 9 or newer. Until a release signing key is set up, the APKs carry a test signature: they install, but a build signed with the release key later will need the test build uninstalled first. @@ -257,7 +256,7 @@ build signed with the release key later will need the test build uninstalled fir | Build | File | Notes | |---|---|---| -| Static site | `-web-.zip` | Runs in a modern browser; host it on any static server | +| Static site | `chromaforge-web-.zip` | Runs in a modern browser; host it on any static server | ## Keyboard @@ -280,9 +279,12 @@ Settings → Shortcuts → Keymap switches to the *Alternative* set. ## Licence and credits -The app is licensed under the [MIT License](LICENSE), except `crates/segment` and `crates/fetch`, which are -Apache-2.0 only. It is a fork of an open-source project; that project's copyright notices and required -third-party notices are in [LICENSE](LICENSE) and [NOTICE](NOTICE). +The app and every `lcc-*` crate are licensed under the [GNU GPL v3 or later](LICENSE-GPL-3.0.txt). +Code adopted from other sources must be GPL-3.0-compatible or Apache-2.0; MIT is allowed only as a complete, +isolated module/library or plugin. Adopted code keeps its original licence (see [NOTICE](NOTICE)); the combined +work is distributed under GPL-3.0-or-later. It is a fork of an +open-source project; that project's copyright notices and required third-party notices are in +[LICENSE](LICENSE) and [NOTICE](NOTICE). Privacy: the app collects no data; see [PRIVACY.md](PRIVACY.md). diff --git a/README.md.in b/README.md.in index a28fdf2df8..225c0a4ed4 100644 --- a/README.md.in +++ b/README.md.in @@ -10,7 +10,7 @@

- Licence: MIT + Licence: GPL-3.0-or-later Rust Platforms: macOS, Windows, Linux, web, Android

@@ -19,7 +19,7 @@ Download · Features · Install · - Manual · + Manual · Roadmap · Licence

@@ -41,7 +41,7 @@ UI, the CLI, a control channel and an MCP server all share. - **Local-first:** no account, no cloud, no telemetry, no subscription. The network is used only for things you turn on. - **Non-destructive:** originals are never touched; edits live in the catalog and, if you like, in XMP sidecars. - **Drivable end to end by AI agents** over MCP, with undo for everything they do. -- **Open source** (MIT). Chromaforge is a fork of an open-source project; its copyright notices are kept in [NOTICE](NOTICE) +- **Open source** (GPL-3.0-or-later). Chromaforge is a fork of an open-source project; its copyright notices are kept in [NOTICE](NOTICE) and [LICENSE](LICENSE). ## Contents @@ -49,8 +49,7 @@ UI, the CLI, a control channel and an MCP server all share. - [Features](#features): [modules](#seven-modules-one-catalog) · [editing](#editing) · [masking](#masking) · [library & culling](#library-and-culling) · [video](#video) · [beyond the darkroom](#beyond-the-darkroom) - [Install](#install) · [Keyboard](#keyboard) · [Licence and credits](#licence-and-credits) -- [Manual](docs/manual/README.md): [building from source and contributing](docs/manual/build-and-contribute.md) · - [agents, MCP, performance and feature status](docs/manual/agents-and-status.md) · +- [Manual]({{website}}): [contributing](CONTRIBUTING.md) · [roadmap](ROADMAP.md) # Features @@ -147,7 +146,7 @@ Clips live in the same library as your photos. MP4, MOV, MKV, WebM, MPEG-TS and ProRes, DNxHR, APV or MPEG-2 decode in pure Rust. Play a clip in the loupe (Space, ← / → for single frames), drag the trim handles, pick the poster frame the grid shows, and capture any frame as a photo. The Light and Color controls (and presets that use only them) grade every frame. Export writes H.264 MP4 or -ProRes MOV with the trim, the grade and the sound (graded on the GPU for H.264); ` render clip.mov -o out.mp4 --trim 2,8` does the same from +ProRes MOV with the trim, the grade and the sound (graded on the GPU for H.264); `chromaforge-cli render clip.mov -o out.mp4 --trim 2,8` does the same from the command line. Interlaced H.264 (AVCHD 1080i) is deinterlaced. Masks, spot removal, lens corrections and crop don't apply to video. See [docs/video.md](docs/video.md). @@ -171,19 +170,19 @@ See [docs/video.md](docs/video.md). Not sure which file you need? The [Download page]({{website}}download/) picks the right one for your computer. Release builds are listed on the project's releases page. `` in the file names is the version number, -``/`` are the brand binary names, and `SHA256SUMS.txt` lists a checksum for every file. Build them yourself +`chromaforge`/`chromaforge-cli` are the brand binary names, and `SHA256SUMS.txt` lists a checksum for every file. Build them yourself with `cargo xtask package`. ### Windows | Build | Installer | Portable | |---|---|---| -| x64 (64-bit Intel/AMD) | `--windows-x64.msi` | `--windows-x64-portable.zip` | -| arm64 (Snapdragon and other ARM PCs) | `--windows-arm64.msi` | `--windows-arm64-portable.zip` | +| x64 (64-bit Intel/AMD) | `chromaforge--windows-x64.msi` | `chromaforge--windows-x64-portable.zip` | +| arm64 (Snapdragon and other ARM PCs) | `chromaforge--windows-arm64.msi` | `chromaforge--windows-arm64-portable.zip` | -The installers and executables are not code-signed, so Windows SmartScreen may warn the first time you run them (More info ▸ Run anyway). The installer asks where to install (`C:\Program Files\` by +The installers and executables are not code-signed, so Windows SmartScreen may warn the first time you run them (More info ▸ Run anyway). The installer asks where to install (`C:\Program Files\Chromaforge` by default; upgrades stay in the folder you chose) and ends on a page confirming the app was installed, with an -option to start it. For unattended installs: `msiexec /i --windows-x64.msi /qn INSTALLFOLDER="D:\Apps\\"`. +option to start it. For unattended installs: `msiexec /i chromaforge--windows-x64.msi /qn INSTALLFOLDER="D:\Apps\Chromaforge\"`. **Update or uninstall asks for an old `.msi`, or stops with error 1612 or 1714?** Windows removes the installed version with its own cached copy of that version's installer; if the copy is gone, it asks for the original file and stops @@ -197,19 +196,19 @@ message. | Build | File | Notes | |---|---|---| -| App, Apple silicon | `--macos-arm64.dmg` | Not signed or notarized: macOS asks you to allow it on first open ([how](docs/manual/getting-started.md#install)) | -| App, Intel | `--macos-x64.dmg` | As above | -| Command-line tool | inside the app: `.app/Contents/MacOS/` | Updates with the app; to run it from Terminal, link it onto `PATH` ([how](docs/manual/getting-started.md#install)) | +| App, Apple silicon | `chromaforge--macos-arm64.dmg` | Not signed or notarized: macOS asks you to allow it on first open ([how]({{website}}start/install/)) | +| App, Intel | `chromaforge--macos-x64.dmg` | As above | +| Command-line tool | inside the app: `Chromaforge.app/Contents/MacOS/chromaforge-cli` | Updates with the app; to run it from Terminal, link it onto `PATH` ([how]({{website}}start/install/)) | ### Linux | Format | x86_64 | Notes | |---|---|---| -| AppImage | `--linux-x86_64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) | -| Flatpak | `--linux-x86_64.flatpak` | Sandboxed; `flatpak install --user ` | -| Debian/Ubuntu | `--linux-x86_64.deb` | | -| Fedora/RHEL/openSUSE | `--linux-x86_64.rpm` | | -| Tarball | `--linux-x86_64.tar.gz` | Unpack anywhere | +| AppImage | `chromaforge--linux-x86_64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) | +| Flatpak | `chromaforge--linux-x86_64.flatpak` | Sandboxed; `flatpak install --user ` | +| Debian/Ubuntu | `chromaforge--linux-x86_64.deb` | | +| Fedora/RHEL/openSUSE | `chromaforge--linux-x86_64.rpm` | | +| Tarball | `chromaforge--linux-x86_64.tar.gz` | Unpack anywhere | Linux ARM64 (aarch64) builds are paused; `packaging/linux/package.sh aarch64` still builds one locally. @@ -246,9 +245,9 @@ Install from the release's APKs: | Build | File | Notes | |---|---|---| -| Phones and tablets (arm64) | `--android-arm64-v8a.apk` | Sideload: allow installs from your browser or file manager, then open the file | -| Emulator and Chromebooks (x86_64) | `--android-x86_64.apk` | | -| Play Store bundle | `--android-arm64-v8a-x86_64.aab` | For Play Console uploads, not for installing | +| Phones and tablets (arm64) | `chromaforge--android-arm64-v8a.apk` | Sideload: allow installs from your browser or file manager, then open the file | +| Emulator and Chromebooks (x86_64) | `chromaforge--android-x86_64.apk` | | +| Play Store bundle | `chromaforge--android-arm64-v8a-x86_64.aab` | For Play Console uploads, not for installing | Android 9 or newer. Until a release signing key is set up, the APKs carry a test signature: they install, but a build signed with the release key later will need the test build uninstalled first. @@ -257,7 +256,7 @@ build signed with the release key later will need the test build uninstalled fir | Build | File | Notes | |---|---|---| -| Static site | `-web-.zip` | Runs in a modern browser; host it on any static server | +| Static site | `chromaforge-web-.zip` | Runs in a modern browser; host it on any static server | ## Keyboard @@ -280,9 +279,12 @@ Settings → Shortcuts → Keymap switches to the *Alternative* set. ## Licence and credits -The app is licensed under the [MIT License](LICENSE), except `crates/segment` and `crates/fetch`, which are -Apache-2.0 only. It is a fork of an open-source project; that project's copyright notices and required -third-party notices are in [LICENSE](LICENSE) and [NOTICE](NOTICE). +The app and every `lcc-*` crate are licensed under the [GNU GPL v3 or later](LICENSE-GPL-3.0.txt). +Code adopted from other sources must be GPL-3.0-compatible or Apache-2.0; MIT is allowed only as a complete, +isolated module/library or plugin. Adopted code keeps its original licence (see [NOTICE](NOTICE)); the combined +work is distributed under GPL-3.0-or-later. It is a fork of an +open-source project; that project's copyright notices and required third-party notices are in +[LICENSE](LICENSE) and [NOTICE](NOTICE). Privacy: the app collects no data; see [PRIVACY.md](PRIVACY.md). diff --git a/ROADMAP.md b/ROADMAP.md index 67179f0d0f..41b68777c4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # Roadmap -*Last updated 2026-11-28 (version 0.8.2). Revision history: [Log](#log).* +*Last updated 2026-11-30 (version 0.8.2). Revision history: [Log](#log).* Milestones toward full Adobe Lightroom Classic parity, with the Classic shell and output modules (Map, Book, Slideshow, Print, Web, publish) and Immich integration as Chromaforge's own focus on top of the upstream engine. Estimates are for @@ -213,13 +213,15 @@ X-Trans, 14/16-bit real-file verification), RW2 / Leica RWL / Panasonic RAW in e packed formats 2, 5 and 7, the 16-bit words of the 2005–2007 bodies; all recovered by black-box analysis of 178 CC0 files from 118 bodies, `crates/raw/src/vendor/rw2.rs`), PEF (uncompressed and Huffman), ORF uncompressed (16-bit and 12-bit packed) and compressed (every Olympus / OM body since ~2008). Supported containers yield their embedded JPEG preview when present (including CR3). The engine uses it for RAW variants it cannot decode yet; HEVC-only CR3 previews are not decoded. +FITS (astrophotography; beyond Lightroom's formats, issue #1604): `.fits`, `.fit` and `.fts` files from astro cameras and stacking software open as raw photos: 8-, 16- and 32-bit integer and 32- and 64-bit floating-point samples, a monochrome frame or a colour filter array (`BAYERPAT`, with `XBAYOFF` / `YBAYOFF`), or red, green and blue planes (`crates/raw/src/vendor/fits.rs`, headers by `crates/meta/src/fits.rs`). A FITS file states no white balance and no colour matrix: As Shot is D65 and colour is the neutral model, and white is the top of the sample type's range. Checked on synthetic files only (no CC0 sample on raw.pixls.us); 64-bit integers, data cubes, `ZIMAGE` tile compression and random-groups records are refused, saying why. + Not decoded yet — preview only (no permissively licensed description; black-box analysis incomplete): - **Canon CR3 unverified CRX variants** (M11.1), **Canon sRAW/mRAW**. **Camera colour matrices:** ARW, NEF, RW2, RAF, CR3, CR2, PEF, Samsung SRW and Olympus ORF files can use guarded, separate chromaticity and tone estimates from their own embedded JPEG (see `docs/camera-preview-colour.md`); this is a per-file camera-look estimate with relative WB, not measured calibration or absolute-Kelvin WB. 52 models whose fit is rejected (or that have no usable JPEG) start from matrices fitted to their measured spectral sensitivities instead (rawtoaces-data, Apache-2.0; `crates/raw/src/spectral.rs`). Other non-DNG raws and rejected fits use the documented neutral fallback (camera RGB ≈ linear sRGB, flagged `matrix_is_fallback`) with the file's as-shot white-balance multipliers. Clean sources to evaluate next: manufacturer matrices stored in the files themselves (Olympus ImageProcessing `ColorMatrix`, Pentax equivalents; Panasonic RW2 files carry none) and our -own calibration (M11.4): ` calibrate-lightroom` fits a camera's colour model and looks black-box to Lightroom's exports of a contributor's own photos (maintainer decision 2026-10-25; [docs/calibrate-lightroom.md](docs/calibrate-lightroom.md)); no camera is calibrated yet. Adobe DCP/LCP files and matrices from Adobe-converted DNGs are never used. +own calibration (M11.4): `chromaforge-cli calibrate-lightroom` fits a camera's colour model and looks black-box to Lightroom's exports of a contributor's own photos (maintainer decision 2026-10-25; [docs/calibrate-lightroom.md](docs/calibrate-lightroom.md)); no camera is calibrated yet. Adobe DCP/LCP files and matrices from Adobe-converted DNGs are never used. ## Lightroom Classic catalog migration @@ -234,6 +236,8 @@ history/snapshots remain source data, and smart collections import current membe database is read-only; the app owns subsequent edits. See `docs/lightroom-catalog-import.md`. ## Log +- 2026-11-30: FITS, the format of astrophotography cameras and software, decodes (#1604; beyond the Lightroom target: no + row moves, the numbers are unchanged). - 2026-11-25: adaptive presets (plan 7.8; LR-PRE-ADAPTIVE, LR-MASK-ADAPTIVE): 90.6% of 630 rows, P2 81.2%. - 2026-11-25: plan 7.5 OpenEXR scene-linear export (gap 42 narrows; beyond the Lightroom target, numbers unchanged): half / float, linear Rec. 2020 or ACEScg, primaries in the `chromaticities` attribute (`exr` crate, BSD-3-Clause). @@ -261,7 +265,7 @@ database is read-only; the app owns subsequent edits. See `docs/lightroom-catalo - 2026-11-24: M10: the Export screen previews the first photo to be exported as its file will be (the export's own rendering), with an SDR / HDR choice: the HDR rendition on an HDR display, else the SDR rendition and the reason (`export.previewMode`, LR-EXP-HDR). -- 2026-10-25: M11.4: ` calibrate-lightroom` (preset, fit, add, list): camera calibrations matched to Lightroom +- 2026-10-25: M11.4: `chromaforge-cli calibrate-lightroom` (preset, fit, add, list): camera calibrations matched to Lightroom by black-box fits to its exports of contributors' own photos; data rules amended (gaps 1 and 3; 0 cameras so far). - 2026-10-22 (upstream): Print page setup and PDF output gain the Japanese photo and postcard papers (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) at their exact metric sizes, by their customary names in the Print dialog diff --git a/apps/app/Cargo.toml b/apps/app/Cargo.toml index 93a96481b9..3c36b5f3be 100644 --- a/apps/app/Cargo.toml +++ b/apps/app/Cargo.toml @@ -38,6 +38,8 @@ libraw = ["lcc-engine/libraw", "lcc-cli/libraw"] # the command-line tool, run when the program is started as `` (`main`); its features follow # the app's, so a build without HEIF leaves it out of the CLI too lcc-cli = { path = "../cli", default-features = false } +# photos macOS hands the app from Finder, the Dock or Open With (a no-op elsewhere) +lcc-opendocs = { workspace = true } # reading the Logi plugin package's version (`logi_plugin`) and the control-surface e2e test lcc-surface = { workspace = true } lcc-brand = { workspace = true } diff --git a/apps/app/src/editors.rs b/apps/app/src/editors.rs index 1438755d21..e12ab3568c 100644 --- a/apps/app/src/editors.rs +++ b/apps/app/src/editors.rs @@ -28,6 +28,19 @@ pub fn check(app: &str) -> Result<(), String> { launcher(app).map(|_| ()) } +/// The program `app` names, as a plain command line the engine's launcher can start (issue +/// #1315): PhotoCraft found where its installer put it, a named program as it is, a macOS +/// application name kept for `open -a` (which takes the arguments with it). `None` = not a plain +/// program for this host: the system default, the Flatpak (the host opener forwards its files) or +/// PhotoCraft, which isn't there — [`open_with`] reports that. +pub fn resolve(app: &str) -> Option { + match launcher(app) { + Ok(Launcher::Program(p)) => Some(p.to_string_lossy().to_string()), + Ok(Launcher::MacApp(n)) => Some(n), + _ => None, + } +} + /// Open `path` in `app` (see [`check`]). Spawned, never waited for: the editor runs alongside. pub fn open_with(path: &str, app: &str) -> Result<(), String> { let mut c = match launcher(app)? { @@ -332,6 +345,169 @@ fn mdfind_app(output: &str) -> Option { output.lines().map(str::trim).find(|l| l.ends_with(".app")).map(PathBuf::from) } +// --------------------------------------------------------------------------------------------- detected editors + +/// How an application's name says it edits photos. A hint only: the combo's Browse… picks any +/// program, and a program the list misses still works once it is named. +const EDITOR_WORDS: &[&str] = &[ + "photoshop", + "affinity", + "gimp", + "darktable", + "rawtherapee", + "ansel", + "photoflare", + "pinta", + "krita", + "digikam", + "pixelmator", + "acorn", + "corel", + "paintshop", + "paint", + "aftershot", + "dxo", + "photolab", + "pureraw", + "capture one", + "captureone", + "lightroom", + "luminar", + "topaz", + "photoline", + "zoner", + "helicon", + "luminance", + "ramka", + "foto", + "image", + "picture", + "photo", +]; + +/// Whether an application's name (or its desktop entry's types) says it edits photos. +fn name_says_editor(name: &str, mime_types: &str) -> bool { + let lower = name.to_lowercase(); + if mime_types.split([';', ',']).any(|m| m.trim().to_lowercase().starts_with("image/")) { + return true; + } + EDITOR_WORDS.iter().any(|w| lower.contains(w)) +} + +/// The photo editors installed on this machine, for Settings ▸ External Editing's Application +/// combo: the desktop entries that open images (Linux), the registry's App Paths entries and the +/// usual names on the PATH (Windows), the application folders by name (macOS). Sorted by name, +/// one entry per application, deduplicated by how the app would start. +pub fn detect_editors() -> Vec { + let mut out = detect_for_this_os(); + out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then(a.app.cmp(&b.app))); + out.dedup_by(|a, b| a.app == b.app); + out +} + +#[cfg(target_os = "macos")] +fn detect_for_this_os() -> Vec { + let mut out = Vec::new(); + for dir in ["/Applications", &format!("{}/Applications", std::env::var("HOME").unwrap_or_default())] { + let Ok(rd) = std::fs::read_dir(dir) else { continue }; + for e in rd.flatten() { + let path = e.path(); + let Some(stem) = path.file_stem() else { continue }; + let name = stem.to_string_lossy().to_string(); + if path.extension().is_some_and(|x| x == "app") && name_says_editor(&name, "") { + out.push(lcc_ui_egui::DetectedEditor { name: name.clone(), app: name }); + } + } + } + out +} + +#[cfg(windows)] +fn detect_for_this_os() -> Vec { + let mut out = Vec::new(); + for hive in [r"HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths", r"HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths"] { + for key in reg_subkeys(hive) { + let Some(name) = key.rsplit(['\\']).next().map(|n| n.trim_end_matches(".exe").to_string()) else { continue }; + if !name_says_editor(&name, "") { + continue; + } + if let Some(path) = reg_query(&key, None) { + out.push(lcc_ui_egui::DetectedEditor { name, app: path }); + } + } + } + let path_dirs: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); + for name in ["gimp", "darktable", "RawTherapee", "ansel", "photoflare", "krita"] { + if let Some(p) = resolve_program(Path::new(name), &path_dirs) { + out.push(lcc_ui_egui::DetectedEditor { name: capitalize(name), app: p.to_string_lossy().to_string() }); + } + } + out +} + +#[cfg(not(any(target_os = "macos", windows)))] +fn detect_for_this_os() -> Vec { + let mut out = Vec::new(); + let env = |k: &str| std::env::var_os(k).map(|v| v.to_string_lossy().to_string()); + let path_dirs: Vec = env("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); + let mut seen = std::collections::HashSet::new(); + for dir in desktop_entry_dirs(env) { + let Ok(rd) = std::fs::read_dir(dir) else { continue }; + for e in rd.flatten().take(2048) { + let Some((name, program, mime)) = desktop_entry_info(&e.path()) else { continue }; + if !name_says_editor(&name, &mime) { + continue; + } + // a wrapper (`Exec=env VAR=1 /opt/ed/ed %F`) can't be started with the photo alone + let Some(app) = resolve_program(&program, &path_dirs) else { continue }; + if seen.insert(app.to_string_lossy().to_string()) { + out.push(lcc_ui_egui::DetectedEditor { name, app: app.to_string_lossy().to_string() }); + } + } + } + out +} + +/// A desktop entry's `Name=`, the program its `Exec=` starts, and its `MimeType=` types. +#[cfg(not(any(target_os = "macos", windows)))] +fn desktop_entry_info(path: &Path) -> Option<(String, PathBuf, String)> { + let text = std::fs::read_to_string(path).ok()?; + if !text.lines().any(|l| l.trim() == "[Desktop Entry]" || l.trim() == "[Desktop Action]") { + return None; + } + let field = |prefix: &str| text.lines().find_map(|l| l.strip_prefix(prefix).map(|v| v.trim().to_string())); + let name = field("Name=")?; + let exec = field("Exec=")?; + let mime = field("MimeType=").unwrap_or_default(); + let program = desktop_exec(&exec)?; + Some((name, program, mime)) +} + +/// A Windows registry key's subkeys (`reg query ` lists them one per line). +#[cfg(windows)] +fn reg_subkeys(key: &str) -> Vec { + let mut c = Command::new("reg"); + c.args(["query", key]); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + c.creation_flags(CREATE_NO_WINDOW); + } + let Some(out) = c.output().ok().filter(|o| o.status.success()) else { return Vec::new() }; + String::from_utf8_lossy(&out.stdout).lines().map(str::trim).filter(|l| l.starts_with("HKEY_")).map(str::to_string).collect() +} + +/// `Gimp` from `gimp` (the PATH fallbacks' display name). +#[cfg(windows)] +fn capitalize(name: &str) -> String { + let mut c = name.chars(); + match c.next() { + Some(f) => f.to_uppercase().collect::() + c.as_str(), + None => String::new(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -494,4 +670,23 @@ mod tests { assert_eq!(named, Launcher::Program("/usr/bin/gimp".into())); } } + + /// A named program resolves to what a plain command line starts (issue #1315): the program + /// itself, a macOS application name for `open -a`; the system default and the Flatpak are + /// None (the host opener starts those), and PhotoCraft resolves only when it is installed. + #[test] + fn resolve_names_a_startable_command() { + assert_eq!(resolve(""), None); + let gimp = resolve("/usr/bin/gimp"); + if cfg!(target_os = "macos") { + assert_eq!(gimp.as_deref(), Some("/usr/bin/gimp"), "open -a takes the path"); + } else { + assert_eq!(gimp.as_deref(), Some("/usr/bin/gimp")); + } + // PhotoCraft is found where its installer put it, or not at all; either way it never + // resolves to the bare name that a PATH-less start would need to find itself + if let Some(found) = resolve("photocraft") { + assert!(found != "photocraft", "{found}"); + } + } } diff --git a/apps/app/src/main.rs b/apps/app/src/main.rs index 40f908aafd..6c4e9778b2 100644 --- a/apps/app/src/main.rs +++ b/apps/app/src/main.rs @@ -42,6 +42,7 @@ mod midi; mod native_dialog; #[cfg(target_os = "macos")] mod native_menu; +mod reveal; #[cfg(any(target_os = "linux", windows))] mod screen_icc; #[cfg(target_os = "macos")] @@ -169,6 +170,8 @@ impl eframe::App for App { } fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { self.0.raw_input_hook(raw); + // after the hook, which replaces `dropped_files` with the control channel's drops + raw.dropped_files.extend(opened_as_dropped(lcc_opendocs::take())); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0); @@ -798,6 +801,15 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> open_all_with: Some(Box::new(editors::open_all_with)), open_preset: Some(Box::new(editors::open_preset)), check_editor: Some(Box::new(editors::check)), + pick_executable: picker!(|| { + file_dialog() + .set_title(lcc_ui_egui::i18n::tr("Choose the Editor's Program")) + .pick_file() + .map(|p| vec![p.to_string_lossy().to_string()]) + .unwrap_or_default() + }), + detect_editors: Some(Box::new(editors::detect_editors)), + resolve_editor: Some(Box::new(editors::resolve)), storage_access: None, camera_roll: None, save_to_gallery: None, @@ -807,6 +819,10 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> launch(open_url_command(url)) })), reveal: Some(Box::new(|path: &str| { + // Linux/BSD: select the file in the file manager, never waiting for it (upstream #4653) + if cfg!(any(target_os = "linux", target_os = "freebsd")) { + return reveal::reveal_one(path); + } let status = if cfg!(target_os = "macos") { std::process::Command::new("open").args(["-R", path]).status() } else if cfg!(target_os = "windows") { @@ -819,6 +835,11 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> .map_err(|e| e.to_string()) .and_then(|s| if s.success() || cfg!(target_os = "windows") { Ok(()) } else { Err(format!("reveal failed: {s}")) }) })), + reveal_many: if cfg!(any(target_os = "linux", target_os = "freebsd")) { + Some(Box::new(|paths: &[String]| reveal::reveal_files(paths))) + } else { + None + }, pick_files: picker!(|| { file_dialog() .add_filter_nocase(lcc_ui_egui::i18n::tr("Photos"), lcc_engine::import::EXTENSIONS) @@ -1247,6 +1268,25 @@ fn launch_imports(args: &[String]) -> LaunchArgs { launch_imports_in(args, cwd.as_deref(), home.as_deref()) } +/// A file the system asked the app to open (`lcc_opendocs`; macOS: Finder, the Dock, Open With), +/// handed to the UI as a file dropped on the window: imported like a drop, or held while no library +/// is open yet (`library_problem::hold_dropped`). Adapted from upstream #1204. +#[derive(Debug)] +struct OpenedFile(std::path::PathBuf); + +impl egui::DroppedFile for OpenedFile { + fn path(&self) -> &std::path::Path { + &self.0 + } + fn bytes(&self) -> Result, String> { + std::fs::read(&self.0).map_err(|e| e.to_string()) + } +} + +fn opened_as_dropped(paths: Vec) -> impl Iterator { + paths.into_iter().map(|p| std::sync::Arc::new(OpenedFile(p.into())) as egui::DroppedFileHandle) +} + /// 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. @@ -1341,8 +1381,9 @@ fn panic_log_path(args: impl IntoIterator) -> Option< /// skipped, as the parser takes them. /// Whether the window looks for a newer release at start: only a session that keeps its settings, and not when /// `--no-update-check` was given (Settings > General still decides within that). +/// `_DISABLE_UPDATES` (a distro package) turns it off too (adapted from upstream #4663). fn startup_update_check(keeps_settings: bool, no_update_check: bool) -> bool { - keeps_settings && !no_update_check + keeps_settings && !no_update_check && !lcc_engine::update::disabled_by_env() } fn in_memory_session(args: impl IntoIterator) -> bool { @@ -1646,11 +1687,17 @@ fn run() -> eframe::Result { b.with_x11(); })); } + // macOS hands photos opened from Finder, the Dock or Open With to the running app, not as + // arguments; installed before the event loop exists, so the ones it was launched with arrive too + lcc_opendocs::install(); let started = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { eframe::run_native( lcc_brand::DISPLAY_NAME, options, Box::new(move |cc| { + // opened files that arrive from now on wake the window, which takes them as drops + let opened_ctx = cc.egui_ctx.clone(); + lcc_opendocs::set_waker(move || opened_ctx.request_repaint()); // the window's renderer is up (eframe calls this after creating it) win_files_app.started(window_renderer); came_up_app.store(true, std::sync::atomic::Ordering::Relaxed); @@ -1867,7 +1914,7 @@ fn run() -> eframe::Result { let started = started.unwrap_or_else(|_| Err(eframe::Error::AppCreation("the window's renderer panicked while starting".into()))); if let Err(e) = &started { // the renderer never came up: start again, which tries the next one in the chain - if window_gpu::relaunch_after_failure(&win_files) { + if window_gpu::relaunch_after_failure(&win_files, lcc_opendocs::take()) { log::error!("{} could not open its window with {}: {e}; trying the next renderer", lcc_brand::DISPLAY_NAME, window_renderer.name()); return Ok(()); } @@ -1927,6 +1974,16 @@ fn startup_failed(error: &str, log_file: Option<&std::path::Path>) { mod tests { use super::*; + /// Files the system asks the app to open (macOS, `lcc_opendocs`) reach the UI as dropped files, + /// path for path and in order. + #[test] + fn opened_files_are_handed_over_as_drops() { + let dropped: Vec<_> = opened_as_dropped(vec!["/tmp/a b.arw".into(), "/tmp/c.heic".into()]).collect(); + let paths: Vec<_> = dropped.iter().map(|f| f.path().to_path_buf()).collect(); + assert_eq!(paths, [std::path::PathBuf::from("/tmp/a b.arw"), std::path::PathBuf::from("/tmp/c.heic")]); + assert_eq!(opened_as_dropped(Vec::new()).count(), 0); + } + fn os(args: &[&str]) -> Vec { args.iter().map(std::ffi::OsString::from).collect() } @@ -2694,7 +2751,7 @@ mod config_path_tests { /// that keeps its settings looks. #[test] fn no_update_check_flag_disables_the_startup_check() { - assert!(startup_update_check(true, false)); + assert_eq!(startup_update_check(true, false), !lcc_engine::update::disabled_by_env()); assert!(!startup_update_check(true, true)); assert!(!startup_update_check(false, false)); } diff --git a/apps/app/src/reveal.rs b/apps/app/src/reveal.rs new file mode 100644 index 0000000000..b9246f14b2 --- /dev/null +++ b/apps/app/src/reveal.rs @@ -0,0 +1,100 @@ +//! Revealing photos in the Linux/BSD file manager. Adapted from upstream #4653 (issues #4652, +//! #4658 there): a file is selected through `org.freedesktop.FileManager1.ShowItems` over D-Bus +//! (several files in one window), and only where that service is missing does the parent folder +//! open with `xdg-open`, which is spawned without waiting so the app never freezes until the file +//! manager window closes. + +/// `file://` URI for `ShowItems`: every byte outside the unreserved set (and `/`) is +/// percent-encoded, so spaces and non-ASCII names survive the D-Bus call. +pub(crate) fn file_uri(path: &str) -> String { + const HEX: &[u8; 16] = b"0123456789ABCDEF"; + let mut out = String::with_capacity(path.len().saturating_add(7)); + out.push_str("file://"); + for &byte in path.as_bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(char::from(byte)), + _ => { + out.push('%'); + out.push(HEX.get(usize::from(byte >> 4)).map_or('0', |&c| char::from(c))); + out.push(HEX.get(usize::from(byte & 0xF)).map_or('0', |&c| char::from(c))); + } + } + } + out +} + +/// `ShowItems` on the running file manager (Linux: `zbus` is a Linux dependency). Managers +/// without `FileManager1` answer with an error and the caller falls back to `xdg-open`. +#[cfg(target_os = "linux")] +fn show_items(uris: &[String]) -> Result<(), String> { + let connection = zbus::blocking::connection::Builder::session() + .map_err(|e| e.to_string())? + .method_timeout(std::time::Duration::from_secs(2)) + .build() + .map_err(|e| e.to_string())?; + let proxy = + zbus::blocking::Proxy::new(&connection, "org.freedesktop.FileManager1", "/org/freedesktop/FileManager1", "org.freedesktop.FileManager1") + .map_err(|e| e.to_string())?; + let startup_id = ""; + proxy.call::<_, _, ()>("ShowItems", &(uris, startup_id)).map_err(|e| e.to_string()) +} + +#[cfg(not(target_os = "linux"))] +fn show_items(_: &[String]) -> Result<(), String> { + Err("no FileManager1 on this system".into()) +} + +/// Opens `dir` with `xdg-open` without waiting for it; the child is reaped on a thread so no +/// zombie is left behind. +fn xdg_open_dir(dir: &str) -> Result<(), String> { + let mut child = std::process::Command::new("xdg-open").arg(dir).spawn().map_err(|e| format!("xdg-open: {e}"))?; + std::thread::spawn(move || { + let _ = child.wait(); + }); + Ok(()) +} + +/// Reveals one path: a folder opens, a file is selected in its folder, falling back to opening +/// the folder. +pub(crate) fn reveal_one(path: &str) -> Result<(), String> { + let p = std::path::Path::new(path); + if p.is_dir() { + return xdg_open_dir(path); + } + if show_items(std::slice::from_ref(&file_uri(path))).is_ok() { + return Ok(()); + } + let dir = p.parent().map(|d| d.to_string_lossy().to_string()).filter(|d| !d.is_empty()).unwrap_or_else(|| ".".into()); + xdg_open_dir(&dir) +} + +/// Reveals several files: one `ShowItems` call selects them all in one window; without the +/// service, the first file's folder opens, as a single reveal does. +pub(crate) fn reveal_files(paths: &[String]) -> Result<(), String> { + let Some(first) = paths.first() else { return Err("no photo selected".into()) }; + if paths.len() > 1 { + let uris: Vec = paths.iter().map(|path| file_uri(path)).collect(); + if show_items(&uris).is_ok() { + return Ok(()); + } + } + reveal_one(first) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_uris_encode_for_show_items() { + assert_eq!(file_uri("/photos/IMG_0001.CR3"), "file:///photos/IMG_0001.CR3"); + assert_eq!(file_uri("/home/Me/My Photos/IMG 1.jpg"), "file:///home/Me/My%20Photos/IMG%201.jpg"); + assert_eq!(file_uri("/photos/café-étude.jpg"), "file:///photos/caf%C3%A9-%C3%A9tude.jpg"); + assert_eq!(file_uri("/photos/a#b%c.jpg"), "file:///photos/a%23b%25c.jpg"); + } + + #[test] + fn revealing_nothing_is_an_error() { + assert!(reveal_files(&[]).is_err()); + } +} diff --git a/apps/app/src/window_gpu.rs b/apps/app/src/window_gpu.rs index f7039a4a0e..b4637eb19f 100644 --- a/apps/app/src/window_gpu.rs +++ b/apps/app/src/window_gpu.rs @@ -464,7 +464,7 @@ pub fn check_pipeline(device: &wgpu::Device, build: impl FnOnce(&wgpu::Device)) /// The start failed (error or panic) before the window's renderer came up: start the app again, /// which then tries the next renderer. `false`: not relaunched (it came up, nothing written to /// disk, or the retries are used up). -pub fn relaunch_after_failure(files: &Files) -> bool { +pub fn relaunch_after_failure(files: &Files, opened: Vec) -> bool { if !files.armed() { return false; } @@ -479,6 +479,8 @@ pub fn relaunch_after_failure(files: &Files) -> bool { log::warn!("window: the renderer failed to start; starting again with the next one"); std::process::Command::new(exe) .args(std::env::args_os().skip(1)) + // files the system handed this launch (macOS: opened from Finder), so the next one imports them + .args(opened) .env(lcc_brand::env_var(RETRY_VAR), (tries + 1).to_string()) .spawn() .map_err(|e| log::error!("window: could not start again: {e}")) @@ -543,7 +545,7 @@ mod tests { // nothing written without a settings folder let none = Files::new(None); none.arm(dx); - assert!(!none.armed() && !relaunch_after_failure(&none)); + assert!(!none.armed() && !relaunch_after_failure(&none, Vec::new())); let _ = std::fs::remove_dir_all(&d); } @@ -633,7 +635,7 @@ mod tests { let f = Files::new(Some(d.clone())); assert_eq!(f.take_failed(), None); f.arm(WindowRenderer::Glow); - assert!(!f.armed() && !relaunch_after_failure(&f)); + assert!(!f.armed() && !relaunch_after_failure(&f, Vec::new())); let _ = std::fs::remove_dir_all(&d); } diff --git a/apps/cli/src/calibrate_lightroom.rs b/apps/cli/src/calibrate_lightroom.rs index 41abb6967d..6a0a6ede54 100644 --- a/apps/cli/src/calibrate_lightroom.rs +++ b/apps/cli/src/calibrate_lightroom.rs @@ -180,6 +180,9 @@ fn probe_check_cmd(args: &[String]) -> Result<(), String> { let (Some(probes), Some(exports)) = (probes, exports) else { return Err("probe-check needs --probes DIR (from `probe`) and --exports DIR (Lightroom's exports of them)".into()); }; + // the app's side of the comparison is its default render, so the camera's calibration and the + // installed profiles apply as they do in a render (they are installed by a session, and none is made here) + lcc_engine::camera_profiles::install_dcps(); let report = lcc_colourfit::probe::check(&probes, &exports).map_err(|e| e.to_string())?; if let Some(path) = &out { let text = serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?; diff --git a/apps/cli/src/lib.rs b/apps/cli/src/lib.rs index 848f1d6c02..6ac35db23c 100644 --- a/apps/cli/src/lib.rs +++ b/apps/cli/src/lib.rs @@ -644,8 +644,15 @@ fn mcp(args: &[String]) -> Result<(), String> { }; if !files.is_empty() { let paths = expand_paths(&files); - let r = h.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?; - eprintln!("{CLI} mcp: imported {} photo(s)", r.get("imported").and_then(Value::as_array).map_or(0, Vec::len)); + // A folder with no photos yet still serves (photos come later through `import`); + // `library.import` refuses an empty list, which would end the server before it starts + // (adapted from upstream #4538). + if paths.is_empty() { + eprintln!("{CLI} mcp: no photos found in {}; nothing imported", files.join(", ")); + } else { + let r = h.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?; + eprintln!("{CLI} mcp: imported {} photo(s)", r.get("imported").and_then(Value::as_array).map_or(0, Vec::len)); + } } Box::new(h) } diff --git a/apps/cli/tests/mcp_empty_folder.rs b/apps/cli/tests/mcp_empty_folder.rs new file mode 100644 index 0000000000..ebfe31c9db --- /dev/null +++ b/apps/cli/tests/mcp_empty_folder.rs @@ -0,0 +1,29 @@ +//! ` mcp FOLDER` serves even when the folder holds no photos yet (adapted from upstream #4538). + +use std::io::Write; +use std::process::{Command, Stdio}; + +#[test] +fn empty_folder_still_serves() { + let dir = std::env::temp_dir().join(format!("lcc-cli-test-{}", std::process::id())).join("mcp-empty-folder"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_app-cli")) + .arg("mcp") + .arg(&dir) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + input.write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"test\",\"version\":\"1\"}}}\n").unwrap(); + drop(input); + let out = child.wait_with_output().unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + let _ = std::fs::remove_dir_all(&dir); + assert!(out.status.success(), "an empty folder must not stop the server: {stderr}"); + assert!(stderr.contains("serving MCP on stdio"), "CLI must reach the MCP transport: {stderr}"); + assert!(stdout.contains("\"id\":1") && stdout.contains("\"result\""), "initialize must be answered: {stdout}"); +} diff --git a/apps/web/src/web.rs b/apps/web/src/web.rs index 334937eff7..9c222dc33d 100644 --- a/apps/web/src/web.rs +++ b/apps/web/src/web.rs @@ -243,11 +243,15 @@ fn services(originals: Originals, backend: Option, files: Files, frozen lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(img), &lcc_codecs::EncodeMeta::default()).unwrap_or_default() })), reveal: None, + reveal_many: None, log_file: None, open_with: None, open_all_with: None, open_preset: None, check_editor: None, + pick_executable: None, + detect_editors: None, + resolve_editor: None, storage_access: None, camera_roll: None, save_to_gallery: None, diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index 25da4c19b9..f074444b6b 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -14,42 +14,42 @@ covers a whole directory), or if a licence file referenced in the Licence column | `assets/camera-profiles/*.json` | Camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | ILCE-7M4: Harald Hoyer | original work: fitted by `lightcraft-cli calibrate` to the contributor's own raw photos and their in-camera JPEGs (597 ILCE-7M4 photos, 2026); aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-07 | none | | `packaging/macos/dmg/` (`background.svg`, the `background.tiff` rendered from it by `generate.py`, and the `dmg-layout.DS_Store` layout file) | macOS DMG window background | @XusBadia | original work for this repository; embeds the app icon (`brand/icon.svg`, referenced via ``, not copied); text is outlined Inter / JetBrains Mono glyph paths | MIT OR Apache-2.0 | 2026-10-08 | none (original); used for the Finder window of the macOS DMG, `packaging/macos/dmg/generate.py` renders it to `background.tiff` | | `assets/camera-profiles/ILCA-99M2.json` | Sony ILCA-99M2 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by @PiMinusMax | original work: fitted by `lightcraft-cli calibrate` to 144 usable ILCA-99M2 ARWs (of 150, seven shooting days, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-11 | none | -| `assets/camera-profiles/ILCE-7CR.json` | Sony ILCE-7CR camera colour profile (matrix + hue/saturation/value table), built into the app | upstream contributors; source photographs supplied by @AlexChambers | original work: fitted by ` calibrate` to 125 usable ILCE-7CR ARWs (of 131, September 2025 to September 2026, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-09 | none | +| `assets/camera-profiles/ILCE-7CR.json` | Sony ILCE-7CR camera colour profile (matrix + hue/saturation/value table), built into the app | upstream contributors; source photographs supplied by @AlexChambers | original work: fitted by `chromaforge-cli calibrate` to 125 usable ILCE-7CR ARWs (of 131, September 2025 to September 2026, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-09 | none | | `assets/camera-profiles/X-H2S.json`, `assets/camera-profiles/X-T4.json` | Fujifilm camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by Sebastian Pfluegelmeier | original work: fitted by `lightcraft-cli calibrate` to 201 X-H2S and 545 X-T4 RAFs and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-08 | none | | `assets/camera-profiles/NIKON_Z_6_2.json` | Nikon Z 6II camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 296 usable Z 6II NEFs of my own (of 299, 2024 to 2026, Standard and Auto picture controls; NIKKOR Z 20mm f/1.8 S, Z 24-70mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | | `assets/camera-profiles/NIKON_Z_8.json` | Nikon Z 8 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 261 usable Z 8 NEFs of my own (of 278, 2023 and 2026, nearly all Standard picture control, lossless 14-bit; NIKKOR Z 24-120mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | | `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | -| `assets/camera-profiles/Canon_EOS_R5_C.json` | Canon EOS R5 C camera colour profile (matrix + hue/saturation/value table), built into Chromaforge | Chromaforge contributors; source photographs supplied by Roman Alurkoff (RAD Films) | original work: fitted by ` calibrate` to 398 usable EOS R5 C CR3s of his own (of 400, two bodies, four wedding and portrait shoots, September and October 2026) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | -| `assets/camera-profiles/NIKON_D780.json` | Nikon D780 camera colour profile (matrix + hue/saturation/value table + tone curve), built into the app | Rob Dunn (@robmdunn) | original work: fitted by ` calibrate` to 255 usable D780 NEFs of my own (300 sampled evenly from 1,093) and their in-camera JPEGs; aggregate colour and tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | -| `assets/camera-profiles/NIKON_D750.json` | Nikon D750 camera colour profile (matrix + hue/saturation/value table + tone curve), built into the app | Rob Dunn (@robmdunn) | original work: fitted by ` calibrate` to 276 usable D750 NEFs of my own (300 sampled evenly from 12,630) and their in-camera JPEGs; aggregate colour and tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | -| `assets/camera-profiles/NIKON_D90.json` | Nikon D90 camera colour profile (matrix + hue/saturation/value table + tone curve), built into the app | Rob Dunn (@robmdunn) | original work: fitted by ` calibrate` to 289 usable D90 NEFs of my own (300 sampled evenly from 3,557) and their in-camera JPEGs; aggregate colour and tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | -| `assets/camera-profiles/NIKON_D70.json` | Nikon D70 camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by ` calibrate` to 379 usable D70 NEFs sampled evenly from 3,650 of the contributor's own photos (1,313,897 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | -| `assets/camera-profiles/NIKON_D700.json` | Nikon D700 camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by ` calibrate` to 394 usable D700 NEFs sampled evenly from 8,487 of the contributor's own photos (1,386,109 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | -| `assets/camera-profiles/X20.json` | Fujifilm X20 (PROVIA film simulation) camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by ` calibrate` to 396 usable X20 RAFs shot with PROVIA, sampled from 2,011 (1,414,745 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | -| `assets/camera-profiles/X100T.json` | Fujifilm X100T (PROVIA film simulation) camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by ` calibrate` to 32 usable X100T RAFs shot with PROVIA, of 37 (105,558 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | -| `assets/camera-profiles/X-T1.json` | Fujifilm X-T1 (PROVIA film simulation) camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by ` calibrate` to 217 usable X-T1 RAFs shot with PROVIA (625,876 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | -| `crates/camdb/data/calibrations/CANON_Canon_EOS_R6.json` | Canon Canon EOS R6 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 4 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-26 | none | -| `crates/camdb/data/calibrations/PANASONIC_DMC-GM1.json` | Panasonic DMC-GM1 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 205 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-26 | none | -| `crates/camdb/data/calibrations/OLYMPUS_E-M1MarkII.json` | OLYMPUS CORPORATION E-M1MarkII camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 33 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | -| `crates/camdb/data/calibrations/OM_OM-1.json` | OM Digital Solutions OM-1 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 40 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | -| `crates/camdb/data/calibrations/OM_OM-3.json` | OM Digital Solutions OM-3 camera calibration matched to Lightroom (colour model + looks: Adobe Standard, Adobe Landscape, Adobe Portrait, Adobe Vivid), built into the app | Matthew Takemoto | original work: black-box fit by ` calibrate-lightroom` to 32 photos and their Lightroom exports by Matthew Takemoto; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | -| `crates/camdb/data/calibrations/RICOH_RICOH_GR_III.json` | RICOH IMAGING COMPANY, LTD. RICOH GR III camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 45 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | -| `crates/camdb/data/calibrations/RICOH_RICOH_GR_IV.json` | RICOH IMAGING COMPANY, LTD. RICOH GR IV camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Portrait, Adobe Vivid), built into the app | Matthew Takemoto | original work: black-box fit by ` calibrate-lightroom` to 32 photos and their Lightroom exports by Matthew Takemoto; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | -| `crates/camdb/data/calibrations/SONY_ILCE-1.json` | SONY ILCE-1 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 124 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | -| `crates/camdb/data/calibrations/XIAOMI_Xiaomi_17_Ultra_2512BPNDAG.json` | Xiaomi Xiaomi 17 Ultra/2512BPNDAG camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 32 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | -| `crates/camdb/data/calibrations/NIKON_NIKON_Z6_3.json` | NIKON CORPORATION NIKON Z6_3 camera calibration matched to Lightroom (colour model + looks: Adobe Standard), built into the app | deunderscorepaul | original work: black-box fit by ` calibrate-lightroom` to 16 photos and their Lightroom exports by deunderscorepaul; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-01 | overfitted hue_sat_map removed (caused severe purple/magenta discoloration in blue and dark tones) | -| `crates/camdb/data/calibrations/PANASONIC_DC-G9.json` | Panasonic DC-G9 camera calibration matched to Lightroom (colour model + looks: Adobe Standard), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 5 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-08 | none | -| `crates/camdb/data/calibrations/CANON_Canon_EOS_R5_C.json` | Canon Canon EOS R5 C camera calibration matched to Lightroom (colour model + looks: Adobe Standard), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 143 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-08 | none | -| `crates/camdb/data/calibrations/RICOH_PENTAX_K-3.json` | RICOH IMAGING COMPANY, LTD. PENTAX K-3 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive Color, Adaptive B&W, Adobe Vivid, Adobe Landscape, Adobe Monochrome, Adobe Portrait), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 63 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-10 | none | -| `crates/camdb/data/calibrations/SONY_ILCE-7M5.json` | SONY ILCE-7M5 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 75 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-10 | none | -| `crates/camdb/data/calibrations/SONY_ILCE-7M3.json` | SONY ILCE-7M3 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Camera Standard), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 195 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-29 | none | -| `crates/camdb/data/calibrations/CANON_Canon_EOS_R5m2.json` | Canon Canon EOS R5m2 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard), built into the app | contributors | original work: black-box fit by ` calibrate-lightroom` to 96 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-29 | none | +| `assets/camera-profiles/Canon_EOS_R5_C.json` | Canon EOS R5 C camera colour profile (matrix + hue/saturation/value table), built into Chromaforge | Chromaforge contributors; source photographs supplied by Roman Alurkoff (RAD Films) | original work: fitted by `chromaforge-cli calibrate` to 398 usable EOS R5 C CR3s of his own (of 400, two bodies, four wedding and portrait shoots, September and October 2026) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | +| `assets/camera-profiles/NIKON_D780.json` | Nikon D780 camera colour profile (matrix + hue/saturation/value table + tone curve), built into the app | Rob Dunn (@robmdunn) | original work: fitted by `chromaforge-cli calibrate` to 255 usable D780 NEFs of my own (300 sampled evenly from 1,093) and their in-camera JPEGs; aggregate colour and tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | +| `assets/camera-profiles/NIKON_D750.json` | Nikon D750 camera colour profile (matrix + hue/saturation/value table + tone curve), built into the app | Rob Dunn (@robmdunn) | original work: fitted by `chromaforge-cli calibrate` to 276 usable D750 NEFs of my own (300 sampled evenly from 12,630) and their in-camera JPEGs; aggregate colour and tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | +| `assets/camera-profiles/NIKON_D90.json` | Nikon D90 camera colour profile (matrix + hue/saturation/value table + tone curve), built into the app | Rob Dunn (@robmdunn) | original work: fitted by `chromaforge-cli calibrate` to 289 usable D90 NEFs of my own (300 sampled evenly from 3,557) and their in-camera JPEGs; aggregate colour and tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-16 | none | +| `assets/camera-profiles/NIKON_D70.json` | Nikon D70 camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by `chromaforge-cli calibrate` to 379 usable D70 NEFs sampled evenly from 3,650 of the contributor's own photos (1,313,897 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | +| `assets/camera-profiles/NIKON_D700.json` | Nikon D700 camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by `chromaforge-cli calibrate` to 394 usable D700 NEFs sampled evenly from 8,487 of the contributor's own photos (1,386,109 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | +| `assets/camera-profiles/X20.json` | Fujifilm X20 (PROVIA film simulation) camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by `chromaforge-cli calibrate` to 396 usable X20 RAFs shot with PROVIA, sampled from 2,011 (1,414,745 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | +| `assets/camera-profiles/X100T.json` | Fujifilm X100T (PROVIA film simulation) camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by `chromaforge-cli calibrate` to 32 usable X100T RAFs shot with PROVIA, of 37 (105,558 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | +| `assets/camera-profiles/X-T1.json` | Fujifilm X-T1 (PROVIA film simulation) camera colour profile (matrix + hue/saturation/value table), built into the app | David Coen (@theDavidCoen) | original work: fitted by `chromaforge-cli calibrate` to 217 usable X-T1 RAFs shot with PROVIA (625,876 colour pairs) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data (upstream #2160) | MIT OR Apache-2.0 | 2026-10-26 | none | +| `crates/camdb/data/calibrations/CANON_Canon_EOS_R6.json` | Canon Canon EOS R6 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 4 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-26 | none | +| `crates/camdb/data/calibrations/PANASONIC_DMC-GM1.json` | Panasonic DMC-GM1 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 205 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-26 | none | +| `crates/camdb/data/calibrations/OLYMPUS_E-M1MarkII.json` | OLYMPUS CORPORATION E-M1MarkII camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 33 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | +| `crates/camdb/data/calibrations/OM_OM-1.json` | OM Digital Solutions OM-1 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 40 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | +| `crates/camdb/data/calibrations/OM_OM-3.json` | OM Digital Solutions OM-3 camera calibration matched to Lightroom (colour model + looks: Adobe Standard, Adobe Landscape, Adobe Portrait, Adobe Vivid), built into the app | Matthew Takemoto | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 32 photos and their Lightroom exports by Matthew Takemoto; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | +| `crates/camdb/data/calibrations/RICOH_RICOH_GR_III.json` | RICOH IMAGING COMPANY, LTD. RICOH GR III camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 45 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | +| `crates/camdb/data/calibrations/RICOH_RICOH_GR_IV.json` | RICOH IMAGING COMPANY, LTD. RICOH GR IV camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adobe Landscape, Adobe Portrait, Adobe Vivid), built into the app | Matthew Takemoto | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 32 photos and their Lightroom exports by Matthew Takemoto; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | +| `crates/camdb/data/calibrations/SONY_ILCE-1.json` | SONY ILCE-1 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 124 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | +| `crates/camdb/data/calibrations/XIAOMI_Xiaomi_17_Ultra_2512BPNDAG.json` | Xiaomi Xiaomi 17 Ultra/2512BPNDAG camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive B&W, Adaptive Color, Adobe Landscape, Adobe Monochrome, Adobe Portrait, Adobe Vivid), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 32 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-10-31 | none | +| `crates/camdb/data/calibrations/NIKON_NIKON_Z6_3.json` | NIKON CORPORATION NIKON Z6_3 camera calibration matched to Lightroom (colour model + looks: Adobe Standard), built into the app | deunderscorepaul | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 16 photos and their Lightroom exports by deunderscorepaul; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-01 | overfitted hue_sat_map removed (caused severe purple/magenta discoloration in blue and dark tones) | +| `crates/camdb/data/calibrations/PANASONIC_DC-G9.json` | Panasonic DC-G9 camera calibration matched to Lightroom (colour model + looks: Adobe Standard), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 5 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-08 | none | +| `crates/camdb/data/calibrations/CANON_Canon_EOS_R5_C.json` | Canon Canon EOS R5 C camera calibration matched to Lightroom (colour model + looks: Adobe Standard), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 143 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-08 | none | +| `crates/camdb/data/calibrations/RICOH_PENTAX_K-3.json` | RICOH IMAGING COMPANY, LTD. PENTAX K-3 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Adaptive Color, Adaptive B&W, Adobe Vivid, Adobe Landscape, Adobe Monochrome, Adobe Portrait), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 63 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-10 | none | +| `crates/camdb/data/calibrations/SONY_ILCE-7M5.json` | SONY ILCE-7M5 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 75 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-10 | none | +| `crates/camdb/data/calibrations/SONY_ILCE-7M3.json` | SONY ILCE-7M3 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard, Camera Standard), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 195 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-29 | none | +| `crates/camdb/data/calibrations/CANON_Canon_EOS_R5m2.json` | Canon Canon EOS R5m2 camera calibration matched to Lightroom (colour model + looks: Adobe Color, Adobe Standard), built into the app | contributors | original work: black-box fit by `chromaforge-cli calibrate-lightroom` to 96 photos and their Lightroom exports; aggregate statistics only, no image content; no profile data of the editor's | MIT OR Apache-2.0 | 2026-11-29 | none | | `crates/camprof/src/data/cmf.rs`, `crates/camprof/src/data/illuminants.rs` | CIE 1931 2° colour-matching functions (360–830 nm, 5 nm) and the relative spectral power distributions of CIE standard illuminants A, D50, D55, D65, D75 and E | CIE (Commission Internationale de l'Éclairage); transcribed by RAD Films - Roman Alurkoff for RADcamProfiles | CIE 015:2018 / ISO/CIE 11664-1 and -2 published tables (https://cie.co.at/data-tables); via RADcamProfiles commit dd8003f | Published standard data; the CIE distributes these data tables under a Creative Commons licence (public standard data); the transcription MIT OR Apache-2.0 | 2026-10-13 | 1964 10°, 2006 and Judd–Vos observer tables of the source left out | | `crates/camprof/src/reference.rs` (`COLORCHECKER_CLASSIC`) | Reference values (CIELAB, D50, 2°) of the 24 patches of the ColorChecker Classic / Mini / Passport, as made before November 2014 | X-Rite (formerly GretagMacbeth): published measurement averages; transcribed by RAD Films - Roman Alurkoff for RADcamProfiles | X-Rite's published ColorChecker values (the same numbers are reproduced widely, e.g. ArgyllCMS `ColorChecker.cie`, BabelColor); via RADcamProfiles commit dd8003f | Factual measurement data published by the chart's maker without a stated licence; public factual data; clean-room, own work, confirmed by the author 2026-11-03. No X-Rite software, spectra or file is included | 2026-10-13 | none; the 2014 and Digital SG values of the source (computed from spectra shipped with X-Rite software) are left out | | `crates/colourfit/src/chart.rs` | ColorChecker Classic reference colours (24 patches, CIE L*a*b* under ICC D50, for charts made before and after November 2014), in the `LAB_2014` and `LAB_2005` tables | X-Rite (published 2016); collected by Colour Developers in colour-science | https://github.com/colour-science/colour, tag v0.4.6, `colour/characterisation/datasets/colour_checkers/chromaticity_coordinates.py` | measurement data (facts) as published by X-Rite; colour-science's collection BSD-3-Clause | 2026-10-26 | values copied as published; nothing else from colour-science is used | | `crates/camdb/data/cameras/dcraw.toml` | Camera colour matrices (one XYZ D65 → camera matrix per model, about 550 models) | Dave Coffin, dcraw.c `adobe_coeff` table: most rows read from Adobe DNG Converter, rows marked DJC measured by Dave Coffin | dcraw.c 9.28, Revision 1.478 (Debian `dcraw_9.28.orig.tar.gz`, dcraw.c sha256 d18d9e43a096eea04eee2148e53068f8fa45ce95395d97128b1aa37b477eab43) | dcraw.c: "No license is required to download and use dcraw.c"; only its Foveon functions are restricted, "all other code remains free for all uses" | 2026-10-26 | generated by `tools/dcraw_adobe_coeff.py`: 3×3 rows only (four-colour and level-only rows skipped), divided by 10000, dcraw's levels dropped, extra rows under the Exif makes Ricoh (Pentax), Konica Minolta and Eastman Kodak | -| `assets/camera-profiles/ILCE-7RM5.json` | Sony ILCE-7RM5 camera colour profile (matrix + hue/saturation/value table), built into the app | Yule (Brian) Wang (@peaperfish) | original work: fitted by ` calibrate` to 220 usable ILCE-7RM5 ARWs of my own (of 241, 2025 to 2026, Standard creative style; Sigma 24-70mm F2.8 DG DN II Art and Sony FE 200-600mm F5.6-6.3 G OSS) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-26 | none | -| `assets/camera-profiles/DMC-GM5.json` | Panasonic DMC-GM5 camera colour profile (matrix + hue/saturation/value table), built into the app | upstream contributors; source photographs supplied by @djlieu | original work: fitted by ` calibrate` to 1,520 usable DMC-GM5 RW2s (of 1,562, 2016 to 2025) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data; taken unchanged from upstream #4064 | MIT OR Apache-2.0 | 2026-11-10 | none | +| `assets/camera-profiles/ILCE-7RM5.json` | Sony ILCE-7RM5 camera colour profile (matrix + hue/saturation/value table), built into the app | Yule (Brian) Wang (@peaperfish) | original work: fitted by `chromaforge-cli calibrate` to 220 usable ILCE-7RM5 ARWs of my own (of 241, 2025 to 2026, Standard creative style; Sigma 24-70mm F2.8 DG DN II Art and Sony FE 200-600mm F5.6-6.3 G OSS) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-26 | none | +| `assets/camera-profiles/DMC-GM5.json` | Panasonic DMC-GM5 camera colour profile (matrix + hue/saturation/value table), built into the app | upstream contributors; source photographs supplied by @djlieu | original work: fitted by `chromaforge-cli calibrate` to 1,520 usable DMC-GM5 RW2s (of 1,562, 2016 to 2025) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data; taken unchanged from upstream #4064 | MIT OR Apache-2.0 | 2026-11-10 | none | | `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix | | `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none | | `crates/camprof/src/data/cmf.rs`, `crates/camprof/src/data/illuminants.rs` | CIE 1931 2° colour-matching functions (360–830 nm, 5 nm) and the relative spectral power distributions of CIE standard illuminants A, D50, D55, D65, D75 and E | CIE (Commission Internationale de l'Éclairage); transcribed by RAD Films - Roman Alurkoff for RADcamProfiles | CIE 015:2018 / ISO/CIE 11664-1 and -2 published tables (https://cie.co.at/data-tables); via RADcamProfiles commit dd8003f | Published standard data; the CIE distributes these data tables under a Creative Commons licence (see the open question in the camera-profiling PR notes on the exact variant); the transcription MIT OR Apache-2.0 | 2026-10-13 | 1964 10°, 2006 and Judd–Vos observer tables of the source left out | @@ -59,16 +59,16 @@ covers a whole directory), or if a licence file referenced in the Licence column | `assets/surface-icons/{mask-invert,brush-erase,brush-new,mask-previous,mask-next,mask-visible,zoom-fit-view,zoom-actual-size,select-all-photos,select-no-photos,rotate-photo-left,rotate-photo-right,reset-develop,preset-apply,preset-apply-ai}.svg` (15 icons) | Surface icons for functions that shared one generic pack icon (the two preset icons, 2026-10-22: a key that applies a preset, with an "AI" mark for AI-mask presets) | drawn by an AI agent (Claude) for LightCraft in the TactileBridge pack's style | original work | MIT, part of the pack (`assets/surface-icons/LICENSE.txt`) | 2026-10-16 | none; new files beside the pack's originals, which are unchanged | | `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code, except the Lucide-derived arms in the next row; GuidedUpright (2026-11-24, issue #1274) is original | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a | -| `crates/ui-egui/src/icons.rs` (`Target`, the reticle, and `Bucket`, the paint bucket) | Targeted Adjustment and mask Color icons drawn as vector paths in code (issues #1301, #1305) | Chromaforge contributors | original work | MIT OR GPL-3.0-or-later | 2026-11-24 | n/a; `Target` replaces the earlier picker-and-arrow drawing | +| `crates/ui-egui/src/icons.rs` (`Target`, the reticle, and `Bucket`, the paint bucket) | Targeted Adjustment and mask Color icons drawn as vector paths in code (issues #1301, #1305) | Chromaforge contributors | original work | GPL-3.0-or-later | 2026-11-24 | n/a; `Target` replaces the earlier picker-and-arrow drawing | | `crates/ui-egui/src/eyedropper.rs` | Eyedropper pointer of the colour pickers, drawn as vector shapes in code | OneSlips, ported by Chromaforge contributors | original work | MIT | 2026-11-03 | none | | `crates/ui-egui/src/icons.rs` (the arms that call `lucide!`, each commented with its Lucide name: Activity, Auto, Bell, Brush, Burn, Cloud, Crop, Depth, Describe, Eraser, Eye, EyeOff, Filmstrip, FlagPick, FlagReject, FlipH, FlipV, Gear, Landscape, Link, MapPin, MaskAdd, MaskIntersect, MaskSubtract, Object, Palette, Pause, People, Picker, Play, Presets, RedEye, Reset, RotateLeft, RotateRight, Sky, Sliders, StepBack, StepForward, Straighten, Unlink, Versions) | UI icons adapted from Lucide | Lucide Contributors (portions Cole Bemis, Feather) | https://lucide.dev (`lucide-static` 0.460.0) | ISC (`assets/licenses/ISC-Lucide.txt`) | 2026-10-11 | SVG path data embedded as strings, scaled from Lucide's 24-unit grid to ours and stroked at 1.5 units; RedEye adds a solid pupil to `eye`; the Crop panel's icons (2026-10-12: `link-2`, `link-2-off`, `rotate-ccw`, `rotate-cw`, `flip-horizontal-2`, `flip-vertical-2`, `undo-2`, `ruler`, `wand-sparkles`) and mask actions (`squares-unite`, `squares-subtract`, `squares-intersect`) are unmodified; the video controls (2026-10-12: `play`, `skip-forward`, `skip-back` unmodified; `pause` with its rounded rects drawn square); Sliders (2026-10-17, issue #208: `sliders-horizontal`, its lines written as path data, otherwise unmodified); Burn (2026-10-24: `flame`, unmodified); MapPin (2026-11-27, PR #1539: `map-pin`, its circle written as path data, otherwise unmodified); the notice is also in `NOTICE`, which ships with every release | -| `crates/ui-egui/src/quick_bar.rs` (`paint_glyph`: the clipping glyph) and `crates/ui-egui/src/eye_strip.rs` (`controls`: the ✕ drawn as two strokes) | Quick settings bar and eye focus strip controls drawn in code | Chromaforge contributors | original work | MIT OR GPL-3.0-or-later | 2026-11-15 | n/a; the bar's other glyphs are `icons.rs` icons | -| `crates/ui-egui/src/help_link.rs` (`draw`: the help link's ring and question mark) | Help link icon drawn in code | Chromaforge contributors | original work | MIT OR GPL-3.0-or-later | 2026-11-15 | n/a | +| `crates/ui-egui/src/quick_bar.rs` (`paint_glyph`: the clipping glyph) and `crates/ui-egui/src/eye_strip.rs` (`controls`: the ✕ drawn as two strokes) | Quick settings bar and eye focus strip controls drawn in code | Chromaforge contributors | original work | GPL-3.0-or-later | 2026-11-15 | n/a; the bar's other glyphs are `icons.rs` icons | +| `crates/ui-egui/src/help_link.rs` (`draw`: the help link's ring and question mark) | Help link icon drawn in code | Chromaforge contributors | original work | GPL-3.0-or-later | 2026-11-15 | n/a | | `crates/ui-egui/src/panels/person.rs` | Up arrow on the People page bulk-confirm control, drawn in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-10-13 | n/a | -| `docs/images/classic/*.jpg` | Application screenshots of the Classic UI: the seven modules, masking, the histogram scopes, Compare and Survey (procedural demo library) | the app's contributors | original work (captured with ` snapshot --demo --script docs/showcase/classic.jsonl`) | MIT | 2026-10-11 | refreshed 2026-10-20 (0.9.5) | -| `docs/images/touch/*.jpg` | Application screenshots of the touch layout: tablet Develop, adjust mode, Export sheet, Settings, phone Library (procedural demo library) | the app's contributors | original work (captured with ` snapshot --demo --script docs/showcase/touch.jsonl`) | MIT | 2026-10-23 | tablet-export: the export folder line painted over | +| `docs/images/classic/*.jpg` | Application screenshots of the Classic UI: the seven modules, masking, the histogram scopes, Compare and Survey (procedural demo library) | the app's contributors | original work (captured with `chromaforge-cli snapshot --demo --script docs/showcase/classic.jsonl`) | MIT | 2026-10-11 | refreshed 2026-10-20 (0.9.5) | +| `docs/images/touch/*.jpg` | Application screenshots of the touch layout: tablet Develop, adjust mode, Export sheet, Settings, phone Library (procedural demo library) | the app's contributors | original work (captured with `chromaforge-cli snapshot --demo --script docs/showcase/touch.jsonl`) | MIT | 2026-10-23 | tablet-export: the export folder line painted over | | `docs/manual-site/src/assets/shots/*/*.jpg` | Manual screenshots in the Classic, Modern and Compact layouts (procedural demo library) | the app's contributors | original work (captured with `docs/manual-site/scripts/shots.mjs`) | MIT | 2026-11-09 | resized and compressed | -| `docs/manual-site/src/assets/shots/classic/getting-started-*.png` | Manual screenshots of the Getting Started guide's pages in the Classic layout (procedural demo library) | the app's contributors | original work (captured headless by `tests_onboarding::every_page_fits_a_desktop_window_and_a_phone` with `_TEST_SHOTS`) | MIT | 2026-11-23 | none | +| `docs/manual-site/src/assets/shots/classic/getting-started-*.png` | Manual screenshots of the Getting Started guide's pages in the Classic layout (procedural demo library) | the app's contributors | original work (captured headless by `tests_onboarding::every_page_fits_a_desktop_window_and_a_phone` with `CHROMAFORGE_TEST_SHOTS`) | MIT | 2026-11-23 | none | | `docs/manual-site/scripts/fixtures/capture-one/Originals/*.jpg` | Placeholder photos (64 × 48, one flat colour each) of the synthetic Capture One catalog the manual's import-result shot imports | the app's contributors | original work (generated by `manual_shot_fixture` in `crates/engine/src/capture_one_catalog.rs`) | MIT | 2026-11-14 | none | | `docs/manual-site/public/favicon.svg` | The manual site's tab icon, a copy of `brand/icon.svg` | the project contributors | original work for this repository | MIT (`LICENSE`) | 2026-11-10 | none | | craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular, Noto Sans Georgian Regular, Noto Sans Hebrew Regular, NanumGothic Regular, Noto Sans Symbols / Symbols 2 Regular | The Noto Project Authors (Arabic, Thai, Georgian, Hebrew, Symbols); NHN Corporation (NanumGothic); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the manifest fonts (all official releases); the web build embeds BIZ UDPGothic Regular, Noto Sans Thai, Noto Sans Georgian and Noto Sans Hebrew Regular and ships Noto Sans CJK SC Regular as a separate font file | diff --git a/brand.toml b/brand.toml index 62713c3e48..f6b8171130 100644 --- a/brand.toml +++ b/brand.toml @@ -47,7 +47,7 @@ catalog_magic = "PHOTO-CATALOG" # file-format magic; neutral on purp # The key the in-app updater checks a release's SHA256SUMS.txt.sig against (ed25519 public key, base64; # `cargo xtask update-key new` prints it); two while the key is being rotated. Empty: this build checks for # updates and links to the release, but never downloads or installs one. A fork sets its own. -# Changing it: docs/releasing.md → Update signing key. +# Changing it: docs/release-process.md → Update signing key. [updates] public_keys = ["PtE/NoJCHCje8yQ9XftBT1GN6aT/5TSu6URW9Vp1aaI="] diff --git a/contributors/contributors.json b/contributors/contributors.json deleted file mode 100644 index 575d85296f..0000000000 --- a/contributors/contributors.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "schema": 1, - "repo": "emmertex/lightcraft-classic", - "branch": "main", - "head": "b0d928d5d611edb7866657d8ddddc2c9461c20b0", - "head_date": "2026-10-18T09:37:46+11:00", - "commits": 789, - "unattributed_commits": 0, - "contributors": [ - { - "login": "emmertex", - "people_entry": false, - "github_name": null, - "prs": 114, - "commits": 1398, - "lines_added": 165335, - "lines_deleted": 13057, - "binary_added": 0, - "binary_deleted": 0, - "first_commit": "2026-10-12T21:57:44Z", - "last_commit": "2026-10-17T22:37:46Z" - }, - { - "login": "deunderscorepaul", - "people_entry": false, - "github_name": null, - "prs": 19, - "commits": 65, - "lines_added": 10665, - "lines_deleted": 541, - "binary_added": 0, - "binary_deleted": 0, - "first_commit": "2026-10-12T19:30:47Z", - "last_commit": "2026-10-17T21:26:16Z" - }, - { - "login": "endthestart", - "people_entry": false, - "github_name": null, - "prs": 17, - "commits": 31, - "lines_added": 2704, - "lines_deleted": 288, - "binary_added": 0, - "binary_deleted": 0, - "first_commit": "2026-10-15T04:01:23Z", - "last_commit": "2026-10-17T21:26:16Z" - }, - { - "login": "clydecbrown", - "people_entry": false, - "github_name": null, - "prs": 8, - "commits": 41, - "lines_added": 5679, - "lines_deleted": 642, - "binary_added": 0, - "binary_deleted": 0, - "first_commit": "2026-10-16T02:16:49Z", - "last_commit": "2026-10-17T21:53:13Z" - }, - { - "login": "Kaan88", - "people_entry": false, - "github_name": null, - "prs": 2, - "commits": 3, - "lines_added": 147, - "lines_deleted": 3, - "binary_added": 0, - "binary_deleted": 0, - "first_commit": "2026-10-16T20:59:17Z", - "last_commit": "2026-10-17T10:52:59Z" - } - ], - "models": [ - { - "id": "anthropic/claude-opus/5.5", - "company": "Anthropic", - "model": "Claude Opus", - "version": "5.5", - "commits": 700, - "lines_added": 0, - "lines_deleted": 0 - }, - { - "id": "anthropic/claude-haiku/5.5", - "company": "Anthropic", - "model": "Claude Haiku", - "version": "5.5", - "commits": 1, - "lines_added": 0, - "lines_deleted": 0 - } - ] -} diff --git a/contributors/fork-contributors.py b/contributors/fork-contributors.py deleted file mode 100644 index 02c786c651..0000000000 --- a/contributors/fork-contributors.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python3 -"""Writes contributors/contributors.json from the pull requests opened on this repository only. - -Upstream's contributors are not listed one by one; the About window credits them in one line. -A person is listed when a pull request of theirs here was merged, or was landed for them by a -maintainer's `land/` or `bundle/-` pull request (whose body names it as `#n`). The -landing pull request itself counts for nobody, so the work is credited once, to its author. -Model credits come from the `Co-Authored-By:` lines of this repository's own commits (not -upstream's). - -Usage: python3 contributors/fork-contributors.py (needs `gh` signed in, and the `upstream` -remote fetched, run from the repository root) -""" -import json -import pathlib -import re -import subprocess -import tomllib - -REPO = "emmertex/lightcraft-classic" -BOTS = {"dependabot", "github-actions", "renovate"} -FIELDS = "number,author,state,headRefName,body,additions,deletions,createdAt,mergedAt,closedAt" - - -def gh(*args): - return json.loads(subprocess.run(["gh", *args], check=True, capture_output=True, text=True, encoding="utf-8").stdout) - - -def git(*args): - return subprocess.run(["git", *args], check=True, capture_output=True, text=True, encoding="utf-8").stdout - - -def main(): - root = pathlib.Path(__file__).resolve().parent.parent - prs = gh("pr", "list", "--repo", REPO, "--state", "all", "--limit", "5000", "--json", FIELDS) - landing = [p for p in prs if p["state"] == "MERGED" and re.match(r"(land|bundle)/", p["headRefName"])] - landed = {int(n) for p in landing for n in re.findall(r"#(\d+)", p["body"] or "")} - landing_numbers = {p["number"] for p in landing} - - people = {} - for p in prs: - login = (p.get("author") or {}).get("login") or "" - if not login or login.removesuffix("[bot]") in BOTS or p["number"] in landing_numbers: - continue - if not (p["state"] == "MERGED" or (p["state"] == "CLOSED" and p["number"] in landed)): - continue - c = people.setdefault(login, {"login": login, "prs": 0, "commits": 0, "lines_added": 0, "lines_deleted": 0, "dates": []}) - c["prs"] += 1 - # (the commit count per pull request: the list query can't carry it, GitHub's node limit) - c["commits"] += int(subprocess.run(["gh", "api", f"repos/{REPO}/pulls/{p['number']}", "--jq", ".commits"], check=True, capture_output=True, text=True).stdout.strip() or 0) - c["lines_added"] += p["additions"] - c["lines_deleted"] += p["deletions"] - c["dates"] += [d for d in (p["createdAt"], p["mergedAt"] or p["closedAt"]) if d] - - with open(root / "contributors" / "people.toml", "rb") as f: - entries = tomllib.load(f).get("people", {}) - rows = [] - for c in sorted(people.values(), key=lambda c: (-c["prs"], c["login"].lower())): - dates = sorted(c.pop("dates")) - rows.append({ - "login": c["login"], - "people_entry": c["login"] in entries, - "github_name": None, - "prs": c["prs"], - "commits": c["commits"], - "lines_added": c["lines_added"], - "lines_deleted": c["lines_deleted"], - "binary_added": 0, - "binary_deleted": 0, - "first_commit": dates[0] if dates else "", - "last_commit": dates[-1] if dates else "", - }) - - # model credits: this repository's own commits (on main, not reachable from upstream) - log = git("-C", str(root), "log", "--no-merges", "--format=%H%x00%B%x01", "upstream/main..origin/main") - models = {} - for entry in log.split("\x01"): - body = entry.partition("\x00")[2] - seen = set() - for name in re.findall(r"(?im)^co-authored-by:\s*(Claude[^<]*?)\s*<[^>]*anthropic\.com>", body): - m = re.match(r"Claude(?:\s+(\w+))?(?:\s+([\d.]+))?", name.strip()) - family, version = (m.group(1) or "", m.group(2) or "") if m else ("", "") - key = (f"Claude {family}".strip(), version) - if key not in seen: - seen.add(key) - models[key] = models.get(key, 0) + 1 - commits = sum(1 for e in log.split("\x01") if e.strip()) - model_rows = [ - {"id": f"anthropic/{m.lower().replace(' ', '-')}/{v}".rstrip("/"), "company": "Anthropic", "model": m, "version": v, - "commits": n, "lines_added": 0, "lines_deleted": 0} - for (m, v), n in sorted(models.items(), key=lambda kv: -kv[1]) - ] - - head = git("-C", str(root), "rev-parse", "origin/main").strip() - out = { - "schema": 1, - "repo": REPO, - "branch": "main", - "head": head, - "head_date": git("-C", str(root), "show", "-s", "--format=%cI", head).strip(), - "commits": commits, - "unattributed_commits": 0, - "contributors": rows, - "models": model_rows, - } - (root / "contributors" / "contributors.json").write_text(json.dumps(out, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n") - print(f"{len(rows)} contributors, {len(model_rows)} models, {commits} fork commits") - - -if __name__ == "__main__": - main() diff --git a/contributors/people.toml b/contributors/people.toml deleted file mode 100644 index 6460e7def0..0000000000 --- a/contributors/people.toml +++ /dev/null @@ -1,87 +0,0 @@ -# Contributor names for the About window (docs/contributors.md; rules in AGENTS.md). -# -# 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. -# -# -# Or 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" -# display_name = "Nickname" # shown when the viewer picks "Display name" -# sync_github_name = true # or: use the name on your public GitHub profile as display name -# -# To remove your names, delete your entry (or set fields empty) in a PR. The next -# contributors.py run, and the next build, drop them. - -[people.echelon] -real_name = "Brandon Thomas" -display_name = "Brandon Thomas" -sync_github_name = false - -[people.rock-meister] -sync_github_name = true - -[people.Th4nat0s] -display_name = "Thanat0s" - -[people.sanyamsingh001] -display_name = "sanyamsingh001" - -[people.ArekatlaNishanthchowdary] -real_name = "Arekatla Nishanth Chowdary" -sync_github_name = true - -[people.Losminek] -sync_github_name = true - -[people.nicolasfalesy] -sync_github_name = true - -[people.FooVoo] -real_name = "Aleksandr Batyrev" -sync_github_name = true - -[people.Silvertree2010] -display_name = "Netter" -sync_github_name = false - -[people.nledford] -real_name = "Nathaniel Ledford" - -[people.marcoarnulfo] -real_name = "Marco Arnulfo" -display_name = "Marco Arnulfo" -sync_github_name = false - -[people.egegl] -real_name = "Ege Gursel" -sync_github_name = true - -[people.valenfys] -sync_github_name = true - -[people.mahmatias] -display_name = "Márcio Matias de Andrade" -sync_github_name = true - -[people.ronibalthazar] -sync_github_name = true - -[people.Kaan88] -sync_github_name = true - - -[people.esli1283] -real_name = "Aaron Lopez" -sync_github_name = false - -[people.dotCooCoo] -real_name = "Robert Lee" - -[people.samuelili] -real_name = "Samuel Li" - -[people.hayone1] -sync_github_name = true diff --git a/crates/camdb/data/calibrations/README.md b/crates/camdb/data/calibrations/README.md index 7778f50cce..bff35b96fc 100644 --- a/crates/camdb/data/calibrations/README.md +++ b/crates/camdb/data/calibrations/README.md @@ -3,13 +3,13 @@ One JSON file per camera model, lens and editor (`_.json` for Lightroom, `__.json` for Capture One, darktable, RawTherapee or DxO PhotoLab; `__[_].json` for a fit made for one lens, `--lens`), embedded into the crate at build time by `build.rs`. Each holds -the camera's colour model and named looks, fitted black-box by ` calibrate-lightroom fit [--editor ID]` to that +the camera's colour model and named looks, fitted black-box by `chromaforge-cli calibrate-lightroom fit [--editor ID]` to that editor's exports of a contributor's own photos (aggregate statistics only: no image content, file names, dates, serial numbers or locations; a lens-specific fit records the lens model identifier only). A photo uses its lens's calibration when there is one, else the lens-less one, never another lens's. The format and its checks are in `src/calibration.rs`; how contributors make one is in [`docs/calibrate-lightroom.md`](../../../../docs/calibrate-lightroom.md). -Files are added only with ` calibrate-lightroom add FILE`, which validates the contribution, writes it here in +Files are added only with `chromaforge-cli calibrate-lightroom add FILE`, which validates the contribution, writes it here in the canonical form and adds its row to `assets/ATTRIBUTION.md`; it refuses to overwrite a file for the same camera, lens and editor unless `--replace`. diff --git a/crates/camdb/data/cameras/README.md b/crates/camdb/data/cameras/README.md index 15741549fe..285ec54387 100644 --- a/crates/camdb/data/cameras/README.md +++ b/crates/camdb/data/cameras/README.md @@ -1,7 +1,7 @@ # Camera data One TOML file per maker (`.toml`), embedded into the crate at build time by `build.rs`. The format and the -provenance rules are in the crate documentation (`src/lib.rs`); ` camdb extract` prints entries from DNGs the +provenance rules are in the crate documentation (`src/lib.rs`); `chromaforge-cli camdb extract` prints entries from DNGs the camera itself wrote. This folder stays in the repository even while it holds no camera file: the build script watches it, and a watched diff --git a/crates/camprof/Cargo.toml b/crates/camprof/Cargo.toml index 4868c97af7..ac56ceeba4 100644 --- a/crates/camprof/Cargo.toml +++ b/crates/camprof/Cargo.toml @@ -2,7 +2,9 @@ name = "lcc-camprof" version.workspace = true edition.workspace = true -license = "MIT OR Apache-2.0 OR GPL-3.0-or-later" +# Project distribution is GPL-3.0-or-later; the ported RADcamProfiles files keep their MIT/Apache +# notices (NOTICE), so the crate also carries those original options. +license = "GPL-3.0-or-later OR MIT OR Apache-2.0" description = "Camera profiling from a ColorChecker photograph (L1; the RADcamProfiles engine)" authors = ["RAD Films - Roman Alurkoff"] diff --git a/crates/catalog/src/dates.rs b/crates/catalog/src/dates.rs index 3e4dfff73b..f4a9ca3edf 100644 --- a/crates/catalog/src/dates.rs +++ b/crates/catalog/src/dates.rs @@ -172,6 +172,26 @@ pub fn capture_start(c: &str) -> std::borrow::Cow<'_, str> { } } +/// Whether `s` is a valid calendar prefix (`YYYY`, `YYYY-MM` or `YYYY-MM-DD`). +pub fn valid_date_prefix(s: &str) -> bool { + let part = |range: std::ops::Range| -> Option { + let sub = s.get(range)?; + sub.bytes().all(|c| c.is_ascii_digit()).then(|| sub.parse().ok()).flatten() + }; + match s.len() { + 4 => part(0..4).is_some(), + 7 if s.as_bytes().get(4) == Some(&b'-') => { + let (Some(y), Some(m)) = (part(0..4), part(5..7)) else { return false }; + chrono::NaiveDate::from_ymd_opt(y as i32, m, 1).is_some() + } + 10 if s.as_bytes().get(4) == Some(&b'-') && s.as_bytes().get(7) == Some(&b'-') => { + let (Some(y), Some(m), Some(d)) = (part(0..4), part(5..7), part(8..10)) else { return false }; + chrono::NaiveDate::from_ymd_opt(y as i32, m, d).is_some() + } + _ => false, + } +} + /// Whether the library can hold `c` as a capture time: a time [`iso_seconds`] reads, or a /// [`partial_capture`]. (`Op::SetCaptured` refuses anything else.) pub fn is_capture_time(c: &str) -> bool { @@ -849,4 +869,15 @@ mod tests { } assert!(c.auto_stack_groups(&ids, 60.0).is_empty()); } + + #[test] + fn valid_date_prefix_checks_calendar_and_shape() { + for ok in ["2026", "0000", "2026-01", "2026-12", "2026-11-30", "2024-02-29"] { + assert!(valid_date_prefix(ok), "{ok}"); + } + for bad in ["", "202", "20265", "20x6", "é202", "2026-00", "2026-13", "2026/05", "2025-02-29", "2026-02-30", "2026-1-1", "2026-11-30T10:00"] + { + assert!(!valid_date_prefix(bad), "{bad}"); + } + } } diff --git a/crates/catalog/src/db.rs b/crates/catalog/src/db.rs index c879fcead3..d0dd233f72 100644 --- a/crates/catalog/src/db.rs +++ b/crates/catalog/src/db.rs @@ -11,7 +11,7 @@ //! //! | table | key → value | //! |---|---| -//! | `meta` | `format`, `version`, `seq`, `head` (ids counters, label names, browse times) | +//! | `meta` | `format`, `version`, `seq`, `head` (ids counters, label names, browse times, the folders' records: colour labels and Custom Orders) | //! | `photos` | photo id → photo JSON, develop settings as references ([`crate::settings_ref`]) | //! | `develop_settings` | settings hash → settings JSON (develop, History steps, Versions; shared) | //! | `collections` | album id → album JSON (albums, smart albums, folders of albums) | @@ -84,7 +84,8 @@ struct Head { /// Keywords listed on their own or given attributes (format version 5). #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] keyword_list: BTreeMap, - /// What the library keeps about its folders (format version 5). + /// What the library keeps about its folders (format version 5): colour labels, and from + /// format version 23 the Custom Order of each folder's photos, which can run to many ids. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] folder_records: BTreeMap, /// The Map module's saved locations (format version 6). diff --git a/crates/catalog/src/facets.rs b/crates/catalog/src/facets.rs index d99ae52f1b..cffccc9c0c 100644 --- a/crates/catalog/src/facets.rs +++ b/crates/catalog/src/facets.rs @@ -69,11 +69,31 @@ impl FacetPick { if self.is_empty() { return true; } - let have = values(p, cat, &self.field); + let have = pick_tokens(p, cat, &self.field); (self.none && have.is_empty()) || have.iter().any(|h| self.values.iter().any(|v| v.eq_ignore_ascii_case(h))) } } +/// What a column pick on `field` is matched against: [`values`], except that a Date pick matches by prefix at any +/// level (the capture time as `YYYY`, `YYYY-MM` and `YYYY-MM-DD`) and a File Type pick also matches the photo's +/// merged kind (`hdr`, `panorama`, `hdrPanorama`, `focusStack`, as the Type menu lists them). `values` itself is +/// what `library.facets` counts, so it stays as it is. +fn pick_tokens(p: &Photo, cat: &Catalog, field: &str) -> Vec { + match field { + "year" => { + let Some(c) = p.captured.as_deref().filter(|c| !c.trim().is_empty()) else { return Vec::new() }; + let start = crate::dates::capture_start(c); + [4, 7, 10].into_iter().filter_map(|n| start.get(..n)).map(str::to_string).collect() + } + "kind" => { + let mut v = values(p, cat, field); + v.extend(crate::query::merged_kind(&p.file_name).map(str::to_string)); + v + } + _ => values(p, cat, field), + } +} + pub fn flag_name(f: Flag) -> &'static str { match f { Flag::Pick => "pick", @@ -147,6 +167,11 @@ pub fn shutter_label(secs: f64) -> Option { lcc_meta::format_exposure_time(secs).map(|text| format!("{text} s")) } +/// Whether `field`'s values list by their number rather than by their text. +pub fn is_numeric(field: &str) -> bool { + matches!(field, "rating" | "year" | "iso" | "focal" | "aperture" | "shutter" | "faces") +} + /// The number a numeric Metadata column's value sorts by: the value itself, an aperture's f-number, a /// shutter speed's seconds. `None` when it isn't one. pub fn sort_key(field: &str, value: &str) -> Option { diff --git a/crates/catalog/src/folders.rs b/crates/catalog/src/folders.rs index 0aa51bdf2d..b5118e52b1 100644 --- a/crates/catalog/src/folders.rs +++ b/crates/catalog/src/folders.rs @@ -24,11 +24,11 @@ //! two rows. Each row is still consistent: choosing it shows exactly the photos it counts. //! //! A folder is otherwise only where photos are, but the library can also keep a -//! [`FolderRecord`] about it (its colour label), stored under the folder's identity -//! ([`crate::query::folder_key`]). A record follows its folder when the folder is renamed or moved -//! here ([`Catalog::folder_records_follow`]), or found again somewhere else on disk -//! ([`Catalog::folder_records_relocate`]); one about a folder that no longer holds a photo is -//! kept (undo can bring the photos back) and shows again when the folder does. +//! [`FolderRecord`] about it (its colour label, and the Custom Order of its photos), stored under +//! the folder's identity ([`crate::query::folder_key`]). A record follows its folder when the +//! folder is renamed or moved here ([`Catalog::folder_records_follow`]), or found again somewhere +//! else on disk ([`Catalog::folder_records_relocate`]); one about a folder that no longer holds a +//! photo is kept (undo can bring the photos back) and shows again when the folder does. //! //! This is the library's own view of its photos; browsing any folder on disk without importing //! is Local's job (see [`crate::local`]). @@ -38,7 +38,7 @@ use std::collections::{BTreeMap, HashMap}; use serde::{Deserialize, Serialize}; use crate::query::{folder_key, folder_rest, folder_within, key_within, photo_in_root, split_path}; -use crate::{Catalog, ColorLabel, Op, Source}; +use crate::{Catalog, ColorLabel, Op, PhotoId, Source}; /// Folder levels kept per photo. No real path comes near it; a deeper one is counted at its /// ancestor this many levels down, which bounds the tree's depth (and so every walk of it) @@ -78,15 +78,29 @@ pub struct FolderRecord { /// A colour label, as a photo has one. #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, + /// The folder's Custom Order (issue #1583): its photos in the order the user set by hand + /// ([`crate::SortKey::Custom`], format version 23). Only the photos directly in the folder + /// count; the ones the order doesn't list follow. A photo taken out of the folder is left out + /// while it is away and finds its place again when it comes back, until the order is saved + /// anew without it. Read it through [`Catalog::folder_photo_order`], which leaves out what the + /// folder no longer holds. Empty: no custom order yet. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub photo_order: Vec, } impl FolderRecord { /// Whether the record says nothing (and so is not kept). pub fn is_empty(&self) -> bool { - self.label.is_none() + self.label.is_none() && self.photo_order.is_empty() } } +/// Whether `path` names a folder whose photos can be put in Custom Order: any absolute folder, +/// however it is spelled; not `.`, a relative path or nothing. +pub fn folder_has_custom_order(path: &str) -> bool { + record_key(path).is_some() +} + /// The identity a folder's record is kept under: its [`folder_key`]; `None` for a path that /// names no folder (empty, relative, `.`). pub(crate) fn record_key(path: &str) -> Option { @@ -512,6 +526,24 @@ impl Catalog { Op::SetFolderRecord { folder: path.to_string(), record: Some(record) } } + /// The op that puts the photos of folder `path` in the Custom Order `order` (see + /// [`FolderRecord::photo_order`]; empty clears it), keeping the rest of its record. Applying + /// it checks the path. + pub fn folder_photo_order_op(&self, path: &str, order: Vec) -> Op { + let mut record = self.folder_record(path).cloned().unwrap_or_default(); + record.photo_order = order; + Op::SetFolderRecord { folder: path.to_string(), record: Some(record) } + } + + /// Whether a view of the library folder `path` is sorted by the folder's Custom Order + /// ([`crate::SortKey::Custom`]): one shown without the photos of the folders inside it + /// (`subfolders` false), or one holding no photo below it — the view is the folder's own photos + /// either way. With the photos of the folders inside it shown as well there is no one order to + /// go by. `false` for a path that names no folder. + pub fn folder_view_has_custom_order(&self, path: &str, subfolders: bool) -> bool { + record_key(path).is_some_and(|root| !subfolders || !self.holds_photos_below(&root)) + } + /// The ops that carry the records of folder `from` and the folders inside it over to `to` /// (the same place below it), for a folder renamed or moved on disk: commit them with the /// photos' relinks so undo puts both back. Records already at or below `to` are left from a diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index d94b4125ce..ce072c7090 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -14,6 +14,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; +use crate::query::{photo_directly_in, photo_in_root}; use crate::{AlbumId, Catalog, Op, Photo, PhotoId, Source, StackId}; #[derive(Default)] @@ -366,6 +367,24 @@ impl Catalog { sorted(self.index.folders.get_or_init(|| self.file_index(photo_folder_index_key)).get(folder_key)) } + /// Whether the library holds a photo in a folder inside the folder whose identity + /// ([`crate::query::folder_key`]) is `root`, not directly in it. Read from the folder index: a + /// look at each folder the catalog knows, then at the photos in the ones inside `root` until one + /// counts. Photos in Recently Deleted or only browsed in Local don't (a folder is never shown + /// with them), and each candidate is asked about its own path: the index groups folders without + /// regard to letter case. + pub(crate) fn holds_photos_below(&self, root: &str) -> bool { + let lower = root.to_lowercase(); + let own = lower.trim_end_matches('/'); + self.index + .folders + .get_or_init(|| self.file_index(photo_folder_index_key)) + .iter() + .filter(|(k, _)| crate::query::key_within(k, &lower) && k.trim_end_matches('/') != own) + .flat_map(|(_, ids)| ids) + .any(|id| self.photos.get(id).is_some_and(|p| p.in_library() && photo_in_root(p, root) && !photo_directly_in(p, root))) + } + /// The photos whose file is named `name_lower` (lower-cased, as [`file_name_index_key`] gives), /// whatever their state, sorted by id. Callers compare exact names themselves. pub fn photos_named_any_case(&self, name_lower: &str) -> Vec { diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 56a57c0ea6..3e87738dd2 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -69,6 +69,8 @@ //! | 20 | Image Quality Scanner scores (issue #1313) | `Analysis.quality` (`QualityScan`: sharpness, noise, exposure, compression, score, verdict, the flag a scan wrote) | //! | 21 | the Image Quality Scanner assigns star ratings (issue #1362) | `QualityScan.rating_written` | //! | 22 | Pixel Shift merges remember how they were made (registered or plain, the hold-out verdict, why plain) | `MergeSources.registration` (`MergeRegistration`) | +//! | 23 | Custom Order in folders (issue #1583): the order set by hand for the photos of one folder of the library | `FolderRecord.photo_order` | +//! | 24 | Raw + JPEG companions: a JPEG beside its raw imports as the raw's companion, not a photo of its own (issue #1692) | `Op::SetCompanion`, `Photo.companion_jpeg` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -101,7 +103,7 @@ pub(crate) const FORMAT: &str = "lcc-catalog"; pub(crate) const V4_FORMAT: &str = "lcc-catalog-db"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 22; +pub const VERSION: u32 = 24; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 4428a30d1e..59c07b2315 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -66,7 +66,7 @@ use lcc_develop::DevelopSettings; pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of}; pub use lock::{LibraryLock, LockError, LockOwner}; pub use model::*; -pub use query::{DateGroup, Filter, MatchOp, Person, RatingOp, Sort, SortKey, Tally, mix64}; +pub use query::{DateGroup, Filter, MatchOp, Person, RatingOp, Sort, SortKey, Tally, date_groups_from, mix64}; pub use remote::{PreviewEntry, RemoteIdentity, RemoteKey, RemoteTable, SyncState}; pub use rules::{Match, Rule, RuleSet}; use serde::{Deserialize, Serialize}; @@ -183,6 +183,14 @@ pub enum Op { #[serde(default)] sources: Option>, }, + /// Which JPEG file is the raw's companion (see [`Photo::companion_jpeg`]; `None`: none, or + /// cleared). Set by an import that found the pair, and by a rename that took the companion + /// along. Format version 23. + SetCompanion { + id: PhotoId, + #[serde(default)] + companion: Option, + }, /// Move the History cursor (see [`Photo::history_cursor`]) without changing the steps. SetHistoryCursor { id: PhotoId, @@ -977,9 +985,12 @@ impl Catalog { Op::SetLabel { .. } => self.changes.now = Aspects::LABEL, Op::SetMeta { .. } | Op::SetXmpStamp { .. } => self.changes.now = Aspects::META, Op::SetCaptured { .. } => self.changes.now = Aspects::CAPTURED, - Op::SetFile { .. } | Op::Relink { .. } | Op::SetSha1 { .. } | Op::SetExported { .. } | Op::SetMergeSources { .. } => { - self.changes.now = Aspects::FILE - } + Op::SetFile { .. } + | Op::Relink { .. } + | Op::SetSha1 { .. } + | Op::SetExported { .. } + | Op::SetMergeSources { .. } + | Op::SetCompanion { .. } => self.changes.now = Aspects::FILE, Op::SetAnalysis { .. } => self.changes.now = Aspects::ANALYSIS, Op::SetDevelop { .. } | Op::SetVersions { .. } @@ -1156,6 +1167,10 @@ impl Catalog { let p = self.photo_mut(id)?; Op::SetMergeSources { id, sources: std::mem::replace(&mut p.merge_sources, sources) } } + Op::SetCompanion { id, companion } => { + let p = self.photo_mut(id)?; + Op::SetCompanion { id, companion: std::mem::replace(&mut p.companion_jpeg, companion) } + } Op::SetHistoryCursor { id, cursor } => { let p = self.photo_mut(id)?; Op::SetHistoryCursor { id, cursor: std::mem::replace(&mut p.history_cursor, cursor) } @@ -1769,6 +1784,7 @@ fn changes_what_albums_test(op: &Op) -> bool { | Op::SetCaptured { .. } | Op::SetFile { .. } | Op::Relink { .. } + | Op::SetCompanion { .. } | Op::SetAnalysis { .. } | Op::SetDevelop { .. } | Op::SetVersions { .. } diff --git a/crates/catalog/src/library.rs b/crates/catalog/src/library.rs index 323b89b736..75702f9732 100644 --- a/crates/catalog/src/library.rs +++ b/crates/catalog/src/library.rs @@ -672,7 +672,7 @@ impl BackupSchedule { } /// The catalog's own settings (`catalog-settings.json`). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct CatalogSettings { pub backup: BackupSchedule, @@ -690,6 +690,11 @@ pub struct CatalogSettings { pub test_integrity: bool, /// Optimise after a backup. pub optimize: bool, + /// Treat JPEGs next to raw files as companions of the raw (issue #1692): at import, a JPEG + /// with a raw's name beside it is not a photo of its own but the raw's companion (one + /// thumbnail, one face scan, one set of metadata). Unchecked, JPEGs import as separate + /// photos. As Lightroom Classic's default (its option is phrased the other way round). + pub raw_jpeg_companions: bool, /// The preview store's settings (standard size, 1:1 discard, previews at import). Owned by /// the engine (`library.previewSettings`); kept opaque here so the catalog needn't know them. #[serde(skip_serializing_if = "Option::is_none")] @@ -700,7 +705,32 @@ pub struct CatalogSettings { pub library_id: Option, } +impl Default for CatalogSettings { + /// The defaults a library without a settings file (or without a field in it, via the serde + /// `default` on the container) stands in with. `raw_jpeg_companions` is on: JPEGs beside + /// raws are companions of the raw (issue #1692), as Lightroom Classic defaults to. + fn default() -> Self { + CatalogSettings { raw_jpeg_companions: true, ..CatalogSettings::empty() } + } +} + impl CatalogSettings { + /// Every setting off/absent ([`Default`] turns the ones on that should be). + fn empty() -> Self { + CatalogSettings { + backup: BackupSchedule::default(), + backup_dir: None, + keep_backups: 0, + last_backup: None, + backup_mark: None, + test_integrity: false, + optimize: false, + previews: None, + library_id: None, + raw_jpeg_companions: false, + } + } + /// The settings in `dir`; [`CatalogSettings::new_library`] when there are none or the file /// can't be used (logged). Changes nothing on disk: opening the library /// ([`CatalogSettings::load_checked`]) is what moves a damaged file aside and tells the user, @@ -717,7 +747,7 @@ impl CatalogSettings { /// The settings a new library starts with: backups kept (10) and tested. pub fn new_library() -> CatalogSettings { - CatalogSettings { keep_backups: 10, test_integrity: true, ..CatalogSettings::default() } + CatalogSettings { keep_backups: 10, test_integrity: true, raw_jpeg_companions: true, ..CatalogSettings::default() } } /// The settings in `dir`, and what was wrong with its file, to tell the user. A missing file diff --git a/crates/catalog/src/local.rs b/crates/catalog/src/local.rs index ee840cb713..87d83c2b4b 100644 --- a/crates/catalog/src/local.rs +++ b/crates/catalog/src/local.rs @@ -346,6 +346,7 @@ impl Op { | Op::SetBefore { id, .. } | Op::SetExported { id, .. } | Op::SetMergeSources { id, .. } + | Op::SetCompanion { id, .. } | Op::SetCaptured { id, .. } | Op::SetAnalysis { id, .. } | Op::SetFile { id, .. } diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index ad018ea85b..8853c90ca6 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -377,6 +377,13 @@ pub struct Photo { /// Hash of the file's bytes (hex), for duplicate detection and preview-cache keys. #[serde(default, skip_serializing_if = "Option::is_none")] pub content_hash: Option, + /// A raw imported with "treat JPEGs next to raw files as companions" (issue #1692): the JPEG + /// twin the import found beside it (same name, same folder). The companion is not a photo of + /// its own — no separate thumbnail, no second face scan, one set of metadata (this photo's) — + /// and travels with the raw through Copy / Move and Rename. `None` for every other photo. + /// Catalog format 24. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub companion_jpeg: Option, /// Lens corrections embedded in the file (DNG `WarpRectilinear` / `FixVignetteRadial`), applied when /// "Enable Profile Corrections" is on. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -746,6 +753,7 @@ impl Photo { duration: None, as_shot_wb: None, content_hash: None, + companion_jpeg: None, embedded_lens: None, copy_of: None, copy_name: None, diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index 43afc53505..a1c624b637 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -159,8 +159,10 @@ pub enum SortKey { /// A shuffle fixed by [`Sort::seed`]: the same seed always gives the same order, and photos /// added or edited later never reshuffle the others. Pick a new seed to reshuffle. Random, - /// Custom Order: the order set by hand in a regular album ([`Catalog::album_photo_order`]). - /// Anywhere else (no album, a smart album) it sorts by capture date. + /// Custom Order: the order set by hand in a regular album ([`Catalog::album_photo_order`]) or + /// in one folder of the library shown as its own photos ([`Catalog::folder_photo_order`]; + /// [`Catalog::folder_view_has_custom_order`]). Anywhere else (no album, a smart album, a + /// folder shown with the photos of the folders inside it) it sorts by capture date. Custom, /// The Image Quality Scanner's score (issue #1313): photos it has not scored go first in /// ascending order (and last descending), as they carry no number to sort by. @@ -190,8 +192,8 @@ impl Sort { /// Which of two photos comes first in this order: the order [`Catalog::query`] gives (never `Equal` for two /// photos: the id decides last). Photos that tie on the key (one import batch, a burst within a second, /// equal ratings) go by file name, the order cameras number frames, so the order doesn't depend on how ids - /// were given out. [`SortKey::Custom`] orders as the capture date here, as it does where there is no album's - /// own order; an album's Custom Order is the album's, not the photos'. + /// were given out. [`SortKey::Custom`] orders as the capture date here, as it does where there is no album's or + /// folder's own order; a Custom Order is the album's or the folder's, not the photos'. pub fn order(&self, a: &Photo, b: &Photo) -> std::cmp::Ordering { let o = match self.key { SortKey::CaptureDate | SortKey::Custom => a.captured.as_deref().cmp(&b.captured.as_deref()).then_with(|| a.imported.cmp(&b.imported)), @@ -927,6 +929,8 @@ impl Filter { label: None, labels: Vec::new(), labels_none: false, + // a Rating column choice of several ratings is a quick filter too + facets: self.facets.iter().filter(|p| p.field != "rating").cloned().collect(), ..self.clone() } } @@ -1297,6 +1301,40 @@ pub fn cmp_name(a: &str, b: &str) -> std::cmp::Ordering { a.chars().flat_map(char::to_lowercase).cmp(b.chars().flat_map(char::to_lowercase)) } +/// Year → month → day counts for `photos` (newest first). +pub fn date_groups_from<'a>(photos: impl IntoIterator) -> Vec { + use std::borrow::Cow; + use std::collections::BTreeMap; + let mut years: BTreeMap, (BTreeMap, usize>, BTreeMap, usize>)> = BTreeMap::new(); + for p in photos { + let Some(d) = p.captured.as_deref().map(crate::dates::capture_start) else { continue }; + // `get`, not `[..]`: a corrupt or foreign `captured` (a Lightroom catalog's + // captureTime is copied verbatim) may not be ASCII, and slicing it on a byte index + // would panic. A partial time (`1983-04`) counts at the start of its period, so only + // it owns its keys. + let part = |n: usize| match &d { + Cow::Borrowed(d) => d.get(..n).map(Cow::Borrowed), + Cow::Owned(d) => d.get(..n).map(|k| Cow::Owned(k.to_string())), + }; + if let (Some(year), Some(month), Some(day)) = (part(4), part(7), part(10)) { + let (months, days) = years.entry(year).or_default(); + *months.entry(month).or_default() += 1; + *days.entry(day).or_default() += 1; + } + } + let newest_first = |m: BTreeMap, usize>| m.into_iter().rev().map(|(k, n)| (k.to_string(), n)).collect::>(); + years + .into_iter() + .rev() + .map(|(year, (months, days))| DateGroup { + year: year.to_string(), + count: months.values().sum(), + months: newest_first(months), + days: newest_first(days), + }) + .collect() +} + impl Catalog { /// Photos matching `filter`, in `sort` order (ties broken by file name, then id). pub fn query(&self, filter: &Filter, sort: &Sort) -> Vec { @@ -1317,8 +1355,8 @@ impl Catalog { /// touched photo that was in the list and still matches `within` stays, as `query_keeping` would keep it. What /// the query would give, without asking every photo again. pub fn follow(&self, was: &[PhotoId], touched: &[PhotoId], filter: &Filter, sort: &Sort, within: Option<&Filter>) -> Vec { - if sort.key == SortKey::Custom && filter.album.is_some_and(|a| self.has_custom_order(a)) { - // an album's own order is the album's, not the photos': asked whole, keeping what the list held (the + if sort.key == SortKey::Custom && (filter.album.is_some_and(|a| self.has_custom_order(a)) || self.custom_order_folder(filter).is_some()) { + // an album's or a folder's own order is not the photos': asked whole, keeping what the list held (the // untouched photos still match what they matched, or the ops would not have been followed) let keep: std::collections::HashSet = was.iter().copied().collect(); return self.query_keeping(filter, sort, &keep, within.unwrap_or(filter)); @@ -1421,7 +1459,29 @@ impl Catalog { } return v.into_iter().map(|(_, id)| id).collect(); } - // no regular album: by capture date + if let Some(root) = self.custom_order_folder(filter) { + // the folder's own order ranks its photos; the rest (new imports, a photo back in the folder) + // follow in the default order, in one pass with the filter + let saved = self.folder_saved_order(&root); + let rank: std::collections::HashMap = saved.iter().enumerate().map(|(i, p)| (*p, i)).collect(); + let mut v: Vec<(usize, PhotoId)> = Vec::new(); + let mut rest: Vec<&Photo> = Vec::new(); + for p in self.photos().map(|p| p.as_ref()).filter(keep) { + match rank.get(&p.id) { + Some(r) => v.push((*r, p.id)), + None => rest.push(p), + } + } + let after = saved.len(); + rest.sort_unstable_by(|a, b| Sort::default().order(a, b)); + v.extend(rest.iter().enumerate().map(|(i, p)| (after + i, p.id))); + v.sort_unstable(); + if !sort.ascending { + v.reverse(); + } + return v.into_iter().map(|(_, id)| id).collect(); + } + // no regular album, no folder of its own: by capture date return self.query_inner(filter, &Sort { key: SortKey::CaptureDate, ..*sort }, cached, keeping); } let all: Vec<&Photo> = self.photos().map(|p| p.as_ref()).collect(); @@ -1457,6 +1517,14 @@ impl Catalog { self.album(id).is_some_and(|a| !a.folder && a.smart.is_none()) } + /// The folder whose Custom Order sorts `filter`'s photos, if any: a library folder whose view + /// is its own photos only ([`Catalog::folder_view_has_custom_order`]), as its identity. A path + /// that names no folder, and a view with the photos of the folders inside it, have none. + pub(crate) fn custom_order_folder(&self, filter: &Filter) -> Option { + let root = filter.library_folder.as_deref().and_then(crate::folders::record_key)?; + self.folder_view_has_custom_order(&root, !filter.library_folder_only).then_some(root) + } + /// The album's photos in Custom Order: [`crate::Album::photo_order`] (members only), then the /// photos it doesn't list in the order they were added. Empty for smart albums and folders. pub fn album_photo_order(&self, id: AlbumId) -> Vec { @@ -1468,40 +1536,40 @@ impl Catalog { out } - /// Year → month → day counts for the "By Date" section (newest first). - pub fn date_groups(&self) -> Vec { - use std::borrow::Cow; - use std::collections::BTreeMap; - let mut years: BTreeMap, (BTreeMap, usize>, BTreeMap, usize>)> = BTreeMap::new(); - for p in self.photos().filter(|p| p.in_library()) { - let Some(d) = p.captured.as_deref().map(crate::dates::capture_start) else { continue }; - // `get`, not `[..]`: a corrupt or foreign `captured` (a Lightroom catalog's - // captureTime is copied verbatim) may not be ASCII, and slicing it on a byte index - // would panic. A partial time (`1983-04`) counts at the start of its period, so only - // it owns its keys. - let part = |n: usize| match &d { - Cow::Borrowed(d) => d.get(..n).map(Cow::Borrowed), - Cow::Owned(d) => d.get(..n).map(|k| Cow::Owned(k.to_string())), - }; - if let (Some(year), Some(month), Some(day)) = (part(4), part(7), part(10)) { - let (months, days) = years.entry(year).or_default(); - *months.entry(month).or_default() += 1; - *days.entry(day).or_default() += 1; - } - } - let newest_first = |m: BTreeMap, usize>| m.into_iter().rev().map(|(k, n)| (k.to_string(), n)).collect::>(); - years + /// [`crate::FolderRecord::photo_order`] of the folder whose identity ([`folder_key`]) is + /// `root`, as far as it still goes: the photos the catalog has that are directly in the folder, + /// each once. Ones only browsed in Local are not the folder's; deleted ones still are (back + /// from Recently Deleted, a photo finds its place again). + pub(crate) fn folder_saved_order(&self, root: &str) -> Vec { + let mut seen = std::collections::HashSet::new(); + self.folder_records + .get(root) .into_iter() - .rev() - .map(|(year, (months, days))| DateGroup { - year: year.to_string(), - count: months.values().sum(), - months: newest_first(months), - days: newest_first(days), - }) + .flat_map(|r| r.photo_order.iter().copied()) + .filter(|id| self.photo(*id).is_some_and(|p| !p.local && photo_directly_in(p, root)) && seen.insert(*id)) .collect() } + /// The folder's photos in Custom Order (issue #1583): [`Self::folder_saved_order`] (the order + /// set by hand), then the photos directly in the folder it doesn't list, in [`Sort::default`] + /// order (capture date), so a photo imported later follows the others. Empty for a path that + /// names no folder. + pub fn folder_photo_order(&self, path: &str) -> Vec { + let Some(root) = crate::folders::record_key(path) else { return Vec::new() }; + let mut out = self.folder_saved_order(&root); + let seen: std::collections::HashSet = out.iter().copied().collect(); + let mut rest: Vec<&Photo> = + self.photos().map(|p| p.as_ref()).filter(|p| !p.local && photo_directly_in(p, &root) && !seen.contains(&p.id)).collect(); + rest.sort_unstable_by(|a, b| Sort::default().order(a, b)); + out.extend(rest.into_iter().map(|p| p.id)); + out + } + + /// Year → month → day counts for the "By Date" section (newest first). + pub fn date_groups(&self) -> Vec { + date_groups_from(self.photos().filter(|p| p.in_library()).map(|p| &**p)) + } + /// All keywords with usage counts, sorted by name. pub fn keywords(&self) -> Vec<(String, usize)> { let mut m: std::collections::BTreeMap = Default::default(); @@ -1655,6 +1723,13 @@ pub fn folder_rest(path: &str, root: &str) -> Option> { Some(split_path(path, false).parts.into_iter().skip(depth).collect()) } +/// A plain POSIX path: absolute, no `\`, `//`, `.` or `..` component and no trailing separator, so +/// it is its own [`folder_key`] as it stands (on a platform that doesn't fold case) and can be +/// matched without building one. +fn plain_posix(path: &str) -> bool { + path.starts_with('/') && !path.starts_with("//") && !path.ends_with('/') && !path.contains('\\') && !path.contains("//") && !path.contains("/.") +} + /// Whether a library photo (not one only browsed in Local) lies in the folder whose /// [`folder_key`] is `root`. A plain POSIX path (no `\`, `.`, `..`, repeated or trailing /// separators) is its own identity, so it is read without building a key for it: the check runs @@ -1664,13 +1739,7 @@ pub(crate) fn photo_in_root(p: &Photo, root: &str) -> bool { return false; } let crate::Source::File { path } = &p.source else { return false }; - let plain = path.starts_with('/') - && !path.starts_with("//") - && !path.ends_with('/') - && !path.contains(['\\']) - && !path.contains("//") - && !path.contains("/."); - if !cfg!(windows) && plain && root.starts_with('/') && !root.starts_with("//") { + if !cfg!(windows) && plain_posix(path) && root.starts_with('/') && !root.starts_with("//") { let r = root.trim_end_matches('/'); return path.strip_prefix(r).is_some_and(|rest| rest.starts_with('/')); } @@ -1678,7 +1747,19 @@ pub(crate) fn photo_in_root(p: &Photo, root: &str) -> bool { } /// Whether `p` lies in the folder `root` itself (a [`folder_key`]), not in a folder inside it. +/// Read without building a key for a plain POSIX path in a POSIX folder, as [`photo_in_root`] is: +/// a folder's Custom Order asks it of every photo. pub(crate) fn photo_directly_in(p: &Photo, root: &str) -> bool { + if let crate::Source::File { path } = &p.source + && !cfg!(windows) + && plain_posix(path) + && root.starts_with('/') + && !root.starts_with("//") + { + // the folder, a separator, then the file's name alone (a disk's key ends in `/`: nothing before it) + let r = root.trim_end_matches('/'); + return path.strip_prefix(r).is_some_and(|rest| rest.strip_prefix('/').is_some_and(|name| !name.contains('/'))); + } crate::local::folder_of(p).is_some_and(|f| f.trim_end_matches('/') == root.trim_end_matches('/')) } diff --git a/crates/catalog/src/tests_custom_order.rs b/crates/catalog/src/tests_custom_order.rs index 3b5eddbb91..5c25f35b9f 100644 --- a/crates/catalog/src/tests_custom_order.rs +++ b/crates/catalog/src/tests_custom_order.rs @@ -1,5 +1,6 @@ //! Custom Order: a regular album's photos in an order set by hand (`Album.photo_order`, -//! `Op::SetAlbumPhotoOrder`, `SortKey::Custom`). +//! `Op::SetAlbumPhotoOrder`, `SortKey::Custom`), and the same for the photos of one folder of the +//! library (`FolderRecord.photo_order`, issue #1583). use crate::*; @@ -77,3 +78,235 @@ fn custom_order_survives_a_snapshot_and_journal_round_trip() { // an album without one doesn't write the field (older builds read it unchanged) assert!(!Catalog::new().to_snapshot().contains("photo_order")); } + +/// A photo of the library at `path`, captured at `captured`. +fn photo_at(c: &mut Catalog, path: &str, captured: &str) -> PhotoId { + let id = c.alloc_photo_id(); + let name = path.rsplit(['/', '\\']).next().unwrap_or("x.jpg"); + let mut p = Photo::new(id, Source::File { path: path.into() }, name, "JPEG", 4, 3, "2026-01-01"); + p.captured = Some(captured.into()); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +/// `/p/a` holds four photos (one spelled with a doubled separator), `/p/b` one, a folder inside +/// `/p/a` one, and one photo of `/p/a` is only browsed in Local: the first four, and `/p/b`'s. +fn folder_setup() -> (Catalog, Vec, PhotoId) { + let mut c = Catalog::new(); + let ids: Vec = ["/p/a/a.jpg", "/p/a//b.jpg", "/p/a/c.jpg", "/p/a/d.jpg"] + .iter() + .enumerate() + .map(|(i, path)| photo_at(&mut c, path, &format!("2026-01-0{}T10:00:00", i + 1))) + .collect(); + let other = photo_at(&mut c, "/p/b/e.jpg", "2025-01-01T10:00:00"); + photo_at(&mut c, "/p/a/sub/f.jpg", "2024-01-01T10:00:00"); + let local = photo_at(&mut c, "/p/a/g.jpg", "2023-01-01T10:00:00"); + c.apply(Op::SetLocal { id: local, local: true }).unwrap(); + (c, ids, other) +} + +/// The photos the library imported from `path`, on their own or with those of the folders inside. +fn folder(path: &str, only: bool) -> Filter { + Filter { library_folder: Some(path.into()), library_folder_only: only, ..Default::default() } +} + +fn relink(id: PhotoId, path: &str) -> Op { + Op::Relink { id, file_name: "x.jpg".into(), source: Source::File { path: path.into() }, format: None } +} + +#[test] +fn a_folder_in_custom_order_sorts_its_own_photos_and_undoes_as_one_step() { + let (mut c, ids, _) = folder_setup(); + let f = folder("/p/a", true); + assert_eq!(c.query(&f, &custom()), ids, "no order yet: capture date, the folder's own photos only"); + // the order is kept as given and read through folder_photo_order: a repeat and a stranger are left out + let inv = c.apply(c.folder_photo_order_op("/p/a", vec![ids[2], ids[0], PhotoId(999), ids[2]])).unwrap(); + assert_eq!(c.folder_record("/p/a").unwrap().photo_order, vec![ids[2], ids[0], PhotoId(999), ids[2]]); + assert_eq!(c.folder_photo_order("/p/a"), vec![ids[2], ids[0], ids[1], ids[3]], "the photos it lists, then the rest"); + assert_eq!(c.query(&f, &custom()), vec![ids[2], ids[0], ids[1], ids[3]]); + assert_eq!(c.query(&f, &Sort { ascending: false, ..custom() }), vec![ids[3], ids[1], ids[0], ids[2]]); + // a filter narrows the view; the order holds among the photos left + let two = Filter { only: vec![ids[3], ids[0]], ..f.clone() }; + assert_eq!(c.query(&two, &custom()), vec![ids[0], ids[3]]); + // a small edit is followed by asking the view whole, as it is for an album + let was = c.query(&f, &custom()); + assert_eq!(c.follow(&was, &[ids[0]], &f, &custom(), None), was); + c.apply(inv).unwrap(); + assert!(c.folder_record("/p/a").is_none(), "one undo step, back to no record"); + assert_eq!(c.query(&f, &custom()), ids); +} + +#[test] +fn a_folder_order_is_about_where_the_photos_are_now() { + let (mut c, ids, other) = folder_setup(); + c.apply(c.folder_photo_order_op("/p/a", vec![ids[3], ids[2], ids[1], ids[0]])).unwrap(); + let f = folder("/p/a", true); + // moved to another folder: out of the order here, a newcomer there (after that folder's own photo) + c.apply(relink(ids[1], "/p/b/b.jpg")).unwrap(); + assert_eq!(c.query(&f, &custom()), vec![ids[3], ids[2], ids[0]]); + assert_eq!(c.folder_photo_order("/p/b"), vec![other, ids[1]]); + // back again: where it was + c.apply(relink(ids[1], "/p/a/b.jpg")).unwrap(); + assert_eq!(c.query(&f, &custom()), vec![ids[3], ids[2], ids[1], ids[0]]); + // into a folder inside: not the folder's own photo any more + c.apply(relink(ids[0], "/p/a/sub/a.jpg")).unwrap(); + assert_eq!(c.query(&f, &custom()), vec![ids[3], ids[2], ids[1]]); + // deleted: out of the view, its place kept for when it comes back + c.apply(Op::SetDeleted { id: ids[2], deleted: true }).unwrap(); + assert_eq!(c.query(&f, &custom()), vec![ids[3], ids[1]]); + c.apply(Op::SetDeleted { id: ids[2], deleted: false }).unwrap(); + assert_eq!(c.query(&f, &custom()), vec![ids[3], ids[2], ids[1]]); + // removed for good: gone + c.apply(Op::RemovePhoto { id: ids[3] }).unwrap(); + assert_eq!(c.query(&f, &custom()), vec![ids[2], ids[1]]); + // photos imported later follow, by capture date among themselves + let newer = photo_at(&mut c, "/p/a/new1.jpg", "2027-01-01T10:00:00"); + let middle = photo_at(&mut c, "/p/a/new2.jpg", "2026-06-01T10:00:00"); + assert_eq!(c.query(&f, &custom()), vec![ids[2], ids[1], middle, newer]); +} + +#[test] +fn a_folder_shown_with_the_folders_inside_it_has_no_custom_order() { + let (mut c, ids, _) = folder_setup(); + c.apply(c.folder_photo_order_op("/p/a", vec![ids[3], ids[2], ids[1], ids[0]])).unwrap(); + let with_subfolders = folder("/p/a", false); + let by_date = c.query(&with_subfolders, &Sort::default()); + assert_eq!(by_date.len(), 5, "the folder's four and the one in the folder inside it"); + assert_eq!(c.query(&with_subfolders, &custom()), by_date, "no one order for photos of several folders: by capture date"); + assert_eq!(c.query(&folder("/p/a", true), &custom()), vec![ids[3], ids[2], ids[1], ids[0]], "on its own, it has one"); + // a path that names no folder shows nothing, in Custom Order as in any other + assert!(c.query(&folder(".", true), &custom()).is_empty()); + assert!(c.query(&folder("relative", true), &custom()).is_empty()); +} + +#[test] +fn a_folder_with_nothing_below_it_has_a_custom_order_however_it_is_shown() { + let (mut c, _, other) = folder_setup(); + // `/p/a` holds a photo in the folder inside it, `/p/b` nothing below it + assert!(!c.folder_view_has_custom_order("/p/a", true), "shown with what is below it: two folders' photos"); + assert!(c.folder_view_has_custom_order("/p/a", false), "on its own"); + assert!(c.folder_view_has_custom_order("/p/b", true) && c.folder_view_has_custom_order("/p/b", false)); + assert!(!c.folder_view_has_custom_order(".", true) && !c.folder_view_has_custom_order("", false), "not a folder"); + let x = photo_at(&mut c, "/p/b/x.jpg", "2026-01-01T10:00:00"); + let y = photo_at(&mut c, "/p/b/y.jpg", "2026-01-02T10:00:00"); + c.apply(c.folder_photo_order_op("/p/b", vec![y, x])).unwrap(); + // (`folder(path, false)` shows the photos of the folders inside it too, `folder(path, true)` the folder alone) + // shown with the folders inside it, there is nothing to take in: the folder's own order all the same + // (the photo the order doesn't list follows) + assert_eq!(c.query(&folder("/p/b", false), &custom()), vec![y, x, other]); + assert_eq!(c.query(&folder("/p/b", true), &custom()), vec![y, x, other]); + assert_eq!(c.query(&folder("/p/a", false), &custom()), c.query(&folder("/p/a", false), &Sort::default()), "/p/a takes in the photo below it"); + // a photo below it that the view wouldn't show doesn't count: one in Recently Deleted, one only browsed + let below = photo_at(&mut c, "/p/b/sub/z.jpg", "2026-01-03T10:00:00"); + assert!(!c.folder_view_has_custom_order("/p/b", true)); + assert_eq!(c.query(&folder("/p/b", false), &custom()), c.query(&folder("/p/b", false), &Sort::default()), "taken in: no one order"); + assert_eq!(c.query(&folder("/p/b", true), &custom()), vec![y, x, other], "the folder alone keeps its order"); + c.apply(Op::SetDeleted { id: below, deleted: true }).unwrap(); + assert!(c.folder_view_has_custom_order("/p/b", true), "in Recently Deleted: not shown with the folder"); + c.apply(Op::SetDeleted { id: below, deleted: false }).unwrap(); + assert!(!c.folder_view_has_custom_order("/p/b", true)); + c.apply(Op::SetLocal { id: below, local: true }).unwrap(); + assert!(c.folder_view_has_custom_order("/p/b", true), "only browsed in Local: not shown with the folder"); + c.apply(Op::RemovePhoto { id: below }).unwrap(); + assert!(c.folder_view_has_custom_order("/p/b", true), "gone for good"); + assert_eq!(c.query(&folder("/p/b", false), &custom()), vec![y, x, other], "the order, then the photo it doesn't list"); +} + +#[test] +fn a_folder_takes_its_order_along_when_it_is_moved() { + let (mut c, ids, _) = folder_setup(); + c.apply(c.folder_photo_order_op("/p/a", vec![ids[3], ids[1], ids[0], ids[2]])).unwrap(); + c.apply(c.folder_label_op("/p/a", Some(ColorLabel::Red))).unwrap(); + // the folder moves to /p/moved: its photos relink, then its record follows them + for (i, id) in ids.iter().enumerate() { + c.apply(relink(*id, &format!("/p/moved/{i}.jpg"))).unwrap(); + } + for op in c.folder_records_follow("/p/a", "/p/moved") { + c.apply(op).unwrap(); + } + let want = vec![ids[3], ids[1], ids[0], ids[2]]; + assert_eq!(c.query(&folder("/p/moved", true), &custom()), want); + assert_eq!((c.folder_color_label("/p/moved"), c.folder_record("/p/a")), (Some(ColorLabel::Red), None)); + // however the new place is spelled, it is the same folder + assert_eq!(c.folder_photo_order("/p/./moved/"), want); +} + +#[test] +fn a_folder_keeps_its_label_and_its_order_in_one_record() { + let (mut c, ids, _) = folder_setup(); + c.apply(c.folder_label_op("/p/a", Some(ColorLabel::Red))).unwrap(); + let inv = c.apply(c.folder_photo_order_op("/p/a", vec![ids[1], ids[0]])).unwrap(); + assert_eq!(c.folder_record("/p/a").unwrap().clone(), FolderRecord { label: Some(ColorLabel::Red), photo_order: vec![ids[1], ids[0]] }); + // a label change leaves the order alone + c.apply(c.folder_label_op("/p/a", Some(ColorLabel::Blue))).unwrap(); + assert_eq!(c.folder_record("/p/a").unwrap().photo_order, vec![ids[1], ids[0]]); + c.apply(c.folder_label_op("/p/a", None)).unwrap(); + assert_eq!(c.folder_record("/p/a").unwrap().label, None, "the record stays for the order"); + // no order and no label: no record + c.apply(c.folder_photo_order_op("/p/a", vec![])).unwrap(); + assert!(c.folder_record("/p/a").is_none()); + // undoing the order gives back the record there was before it + c.apply(inv).unwrap(); + assert_eq!(c.folder_record("/p/a").unwrap().clone(), FolderRecord { label: Some(ColorLabel::Red), photo_order: vec![] }); +} + +#[test] +fn a_folder_order_needs_a_folder_and_reads_past_strangers() { + let (mut c, ids, _) = folder_setup(); + for not_a_folder in ["", ".", "relative/x", "a/..", " "] { + assert!(c.folder_photo_order(not_a_folder).is_empty(), "{not_a_folder:?}"); + assert!(!folders::folder_has_custom_order(not_a_folder), "{not_a_folder:?}"); + let before = c.to_snapshot(); + assert!(c.apply(c.folder_photo_order_op(not_a_folder, vec![ids[0]])).is_err(), "{not_a_folder:?} names no folder"); + assert_eq!(c.to_snapshot(), before, "nothing changed"); + } + for a_folder in ["/pics", "C:\\pics", "//nas/share/pics", "/"] { + assert!(folders::folder_has_custom_order(a_folder), "{a_folder:?}"); + } + // a record written by hand, with repeats and ids of photos the folder doesn't hold: read, only + // what is the folder's own counts, and nothing is repeated + let record = FolderRecord { label: None, photo_order: vec![ids[3], PhotoId(999_999), ids[0], ids[3]] }; + c.apply(Op::SetFolderRecord { folder: "/p/a".into(), record: Some(record) }).unwrap(); + assert_eq!(c.folder_photo_order("/p/a"), vec![ids[3], ids[0], ids[1], ids[2]]); + assert_eq!(c.query(&folder("/p/a", true), &custom()), vec![ids[3], ids[0], ids[1], ids[2]]); +} + +#[test] +fn a_folder_order_survives_a_snapshot_and_an_older_record_has_none() { + let (mut c, ids, _) = folder_setup(); + c.apply(c.folder_photo_order_op("/p/a", vec![ids[1], ids[0]])).unwrap(); + let back = Catalog::from_snapshot(&c.to_snapshot()).unwrap(); + let want = vec![ids[1], ids[0], ids[2], ids[3]]; + assert_eq!(back.folder_photo_order("/p/a"), want); + assert_eq!(back.query(&folder("/p/a", true), &custom()), want); + // a record from before format 23 (a label, no order) opens with no order + let older = serde_json::to_string(&FolderRecord { label: Some(ColorLabel::Red), ..Default::default() }).unwrap(); + assert!(!older.contains("photo_order"), "{older}"); + assert!(serde_json::from_str::(&older).unwrap().photo_order.is_empty()); + // a folder without one doesn't write the field either + let mut c = Catalog::new(); + c.apply(c.folder_label_op("/pics", Some(ColorLabel::Red))).unwrap(); + assert!(!c.to_snapshot().contains("photo_order")); +} + +#[test] +fn a_folder_order_goes_across_catalogs_under_the_importing_librarys_ids() { + use crate::transfer::{self, ConflictRule, ExportOptions}; + let (mut c, ids, _) = folder_setup(); + c.apply(c.folder_photo_order_op("/p/a", vec![ids[2], ids[0], ids[1]])).unwrap(); + // the exported catalog keeps the ids, with the order + let all: Vec = c.photos().map(|p| p.id).collect(); + let sub = transfer::subset(&c, &ExportOptions { photos: all, ..Default::default() }); + assert_eq!(sub.folder_photo_order("/p/a"), vec![ids[2], ids[0], ids[1], ids[3]]); + // a library that numbers its own photos differently imports it: the order names its ids for the photos + let mut here = Catalog::new(); + for i in 0..10 { + photo_at(&mut here, &format!("/mine/{i}.jpg"), "2026-01-01T10:00:00"); + } + let op = transfer::plan_import(&here, &sub).ops(&mut here, &sub, ConflictRule::Keep); + here.apply(op).unwrap(); + let id_of = |name: &str| here.photos().find(|p| p.file_name == name).unwrap().id; + let (a, b, d) = (id_of("a.jpg"), id_of("b.jpg"), id_of("d.jpg")); + assert!(a.0 > 10 && b.0 > 10 && d.0 > 10, "the imported photos were given ids of their own"); + assert_eq!(here.folder_photo_order("/p/a"), vec![id_of("c.jpg"), a, b, d], "the folder's order, under this library's ids"); +} diff --git a/crates/catalog/src/tests_folder_records.rs b/crates/catalog/src/tests_folder_records.rs index 3198438ceb..9d165350c5 100644 --- a/crates/catalog/src/tests_folder_records.rs +++ b/crates/catalog/src/tests_folder_records.rs @@ -91,7 +91,7 @@ fn a_path_that_names_no_folder_is_refused() { let mut c = library(); let before = c.to_snapshot(); for bad in ["", "relative/trip", ".", "a/.."] { - let op = Op::SetFolderRecord { folder: bad.into(), record: Some(FolderRecord { label: Some(ColorLabel::Red) }) }; + let op = Op::SetFolderRecord { folder: bad.into(), record: Some(FolderRecord { label: Some(ColorLabel::Red), ..Default::default() }) }; assert!(c.apply(op).is_err(), "{bad:?} names no folder"); } assert_eq!(c.to_snapshot(), before); diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 263874c53f..f4b5b58ce8 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -238,18 +238,20 @@ fn op_variants_are_versioned() { Op::SetExported { .. } => 17, Op::AddVignettingMap { .. } | Op::SetVignettingMapState { .. } => 18, Op::SetMergeSources { .. } => 19, + Op::SetCompanion { .. } => 24, } } /// v20: `Analysis.quality` (the Image Quality Scanner's scores); v21: `QualityScan.rating_written`; v22: - /// `MergeSources.registration`. - const NEWEST_FIELDS: u32 = 22; + /// `MergeSources.registration`; v23: `FolderRecord.photo_order` (a folder's Custom Order); v24: + /// `Photo.companion_jpeg` (the raw's companion JPEG, issue #1692). + const NEWEST_FIELDS: u32 = 24; let map = lcc_develop::EmbeddedVignettingMap::from_ev([4, 4], [2, 2], None, Default::default(), &[0.0; 4]).unwrap(); let id = lcc_develop::VignettingMapId::of(&map); let _vignetting = since(&Op::AddVignettingMap { id, record: Box::new(crate::VignettingMapRecord { map, photo: None, added: String::new(), withdrawn: false }), }); - let newest = since(&Op::SetMergeSources { id: crate::PhotoId(1), sources: None }); + let newest = since(&Op::SetCompanion { id: crate::PhotoId(1), companion: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } diff --git a/crates/catalog/src/transfer.rs b/crates/catalog/src/transfer.rs index 3efdff98db..0c480a07df 100644 --- a/crates/catalog/src/transfer.rs +++ b/crates/catalog/src/transfer.rs @@ -458,7 +458,11 @@ impl ImportPlan { } for (folder, r) in &other.folder_records { if cat.folder_record(folder).is_none() { - ops.push(Op::SetFolderRecord { folder: folder.clone(), record: Some(r.clone()) }); + let mut r = r.clone(); + // the folder's Custom Order names the other catalog's photos: this library's ids for + // them (the photos it doesn't take are left out of the order) + r.photo_order = r.photo_order.iter().filter_map(|p| map.get(p).copied()).collect(); + ops.push(Op::SetFolderRecord { folder: folder.clone(), record: Some(r) }); } } // stacks made only of new photos diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 76b76c0092..46983098ef 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -35,7 +35,7 @@ lcc-meta = { workspace = true } # AVIF decode: clean-room pure-Rust AV1 decoder (no unsafe), the same pin as lcc-video. Native # only: it indexes its buffers directly, and on wasm32 (panic = abort) a malformed file could # take the page down instead of becoming an error, so the web build refuses AVIF. -filmcraft-av1 = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-av1 = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } ravif = { workspace = true, optional = true } rav1e = { workspace = true, optional = true } avif-serialize = { workspace = true, optional = true } diff --git a/crates/codecs/src/exr_decode.rs b/crates/codecs/src/exr_decode.rs new file mode 100644 index 0000000000..a2132713ba --- /dev/null +++ b/crates/codecs/src/exr_decode.rs @@ -0,0 +1,183 @@ +//! OpenEXR import: the files our export writes and other apps' flat RGB(A) EXRs — scene-linear +//! half or float samples kept linear ([`crate::Decoded::image`] is linear light in the file's +//! chromaticities, matched to a known space where it is one, the OpenEXR specification's default +//! otherwise). Deep data is not used, and of a mipmap the largest level: the first valid layer's +//! largest resolution level is all our export writes. Read with the pure-Rust `exr` crate +//! (BSD-3-Clause, no unsafe code), as the encoder is. + +use std::io::Cursor; + +use exr::meta::MetaData; +use exr::meta::attribute::{Chromaticities, SampleType}; +use exr::prelude::traits::*; +use lcc_raster::{Plane, Rgb32f}; + +use crate::convert::check_size; +use crate::{DecodeOptions, Decoded, Error, Format, NamedSpace, Result, SourceSpace, SpaceOrigin, Trc}; + +const F: Format = Format::Exr; + +/// The malformed-input error for this format. +fn malformed(e: impl std::fmt::Display) -> Error { + Error::Malformed(F, e.to_string()) +} + +/// (width, height, sample bits) of the first layer, from the header alone. +pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { + let meta = MetaData::read_from_buffered(&mut Cursor::new(bytes), true).map_err(malformed)?; + let h = meta.headers.first().ok_or_else(|| malformed("the file has no layer"))?; + let (w, h) = dims(h.layer_size.0, h.layer_size.1)?; + Ok((w, h, sample_bits(&meta))) +} + +/// Decode a flat RGB(A) EXR: the first valid layer's largest resolution level, its samples +/// linear. The `exr` crate reads the header again before the pixels, so a hostile size is +/// refused before the storage is made. +pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { + let meta = MetaData::read_from_buffered(&mut Cursor::new(bytes), true).map_err(malformed)?; + let hdr = meta.headers.first().ok_or_else(|| malformed("the file has no layer"))?; + let (w, h) = dims(hdr.layer_size.0, hdr.layer_size.1)?; + check_size(F, u64::from(w), u64::from(h), opts)?; + let bits = sample_bits(&meta); + let has_alpha = hdr.channels.list.iter().any(|c| c.name.to_string().eq_ignore_ascii_case("a")); + let space = space_of(hdr.shared_attributes.chromaticities); + + let total = (w as usize).saturating_mul(h as usize); + let stride = w as usize; + let image = exr::prelude::read() + .no_deep_data() + .largest_resolution_level() + .rgba_channels( + move |_, _| vec![0.0f32; total.saturating_mul(4)], + move |px: &mut Vec, at: exr::math::Vec2, c: (f32, f32, f32, f32)| { + if let Some(slot) = px.get_mut((at.1 * stride + at.0) * 4..(at.1 * stride + at.0) * 4 + 4) { + slot.copy_from_slice(&[c.0, c.1, c.2, c.3]); + } + }, + ) + .first_valid_layer() + .all_attributes() + .from_buffered(Cursor::new(bytes)) + .map_err(malformed)?; + let px = image.layer_data.channel_data.pixels; + if px.len() < total.saturating_mul(4) { + return Err(malformed("the image data is short")); + } + + // the reader hands straight (unassociated) alpha in the fourth sample + let alpha = has_alpha.then(|| Plane { width: w as usize, height: h as usize, data: px.as_chunks::<4>().0.iter().map(|c| c[3]).collect() }); + let rgb = px.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2]]).collect(); + Ok(Decoded { + format: F, + image: Rgb32f { width: w as usize, height: h as usize, data: rgb }, + alpha, + infrared: None, + space, + bit_depth: bits as u8, + float: true, + has_alpha, + grayscale: false, + cmyk: false, + orientation: 1, + exif: None, + xmp: None, + icc: None, + width: w, + height: h, + source_width: w, + source_height: h, + }) +} + +/// The data window's size, sane. +fn dims(w: usize, h: usize) -> Result<(u32, u32)> { + u32::try_from(w).ok().zip(u32::try_from(h).ok()).ok_or_else(|| malformed("the image is too large")) +} + +/// The file's sample format (half or float; a u32 channel is read as float either way). +fn sample_bits(meta: &MetaData) -> u16 { + let half = meta.headers.iter().any(|h| h.channels.list.iter().any(|c| c.sample_type == SampleType::F16)); + if half { 16 } else { 32 } +} + +/// The space the file's chromaticities name: a known one where they match one, else the matrix +/// they describe. Without the attribute, the specification's default (linear Rec. 709). +fn space_of(ch: Option) -> SourceSpace { + let Some(ch) = ch else { + return linear(NamedSpace::Srgb, SpaceOrigin::Untagged); + }; + let to_xy = |v: exr::math::Vec2| lcc_color::Xy::new(f64::from(v.0), f64::from(v.1)); + let space = lcc_color::RgbSpace { name: "EXR", r: to_xy(ch.red), g: to_xy(ch.green), b: to_xy(ch.blue), white: to_xy(ch.white) }; + let m50 = crate::space::rgb_to_xyz_d50(&space); + match NamedSpace::recognize(&m50) { + Some(n) => linear(n, SpaceOrigin::Container), + None => SourceSpace { named: None, to_xyz_d50: m50, trc: Some([Trc::Linear, Trc::Linear, Trc::Linear]), origin: SpaceOrigin::Container }, + } +} + +/// A space with no encoding curve (EXR samples are linear light). +fn linear(n: NamedSpace, origin: SpaceOrigin) -> SourceSpace { + let mut s = SourceSpace::named(n, origin); + s.trc = Some([Trc::Linear, Trc::Linear, Trc::Linear]); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Our own export reads back: the same pixels, linear, and the space is named again. + #[test] + fn our_export_round_trips() { + let mut px: Vec<[f32; 3]> = Vec::new(); + for y in 0..3u32 { + for x in 0..4u32 { + px.push([x as f32 / 4.0, y as f32 / 3.0, 0.25]); + } + } + let options = crate::ExrOptions { half: false, primaries: lcc_color::REC2020 }; + let bytes = crate::encode_exr(4, 3, 3, bytemuck::cast_slice(&px), &options).unwrap(); + let d = decode(&bytes, &DecodeOptions::fit(64, 64)).unwrap(); + assert_eq!((d.width, d.height, d.bit_depth, d.float), (4, 3, 32, true)); + assert!(d.space.named.is_some_and(|n| n == NamedSpace::Rec2020), "{:?}", d.space.named); + let a = &d.image.data[4]; + assert!((a[0] - 0.0).abs() < 1e-5 && (a[1] - 1.0 / 3.0).abs() < 1e-5 && (a[2] - 0.25).abs() < 1e-5, "{a:?}"); + assert!(!d.has_alpha, "no A channel was written"); + } + + /// Half floats decode as 16 bits; an alpha channel comes back as a plane. + #[test] + fn half_and_alpha() { + let px: Vec<[f32; 4]> = (0..12).map(|i| [i as f32 / 12.0, 0.5, 0.5, 0.75]).collect(); + let options = crate::ExrOptions { half: true, primaries: lcc_color::REC2020 }; + let bytes = crate::encode_exr(4, 3, 4, bytemuck::cast_slice(&px), &options).unwrap(); + let d = decode(&bytes, &DecodeOptions::fit(64, 64)).unwrap(); + assert_eq!((d.bit_depth, d.has_alpha), (16, true)); + let alpha = d.alpha.as_ref().unwrap(); + assert!((alpha.data[5] - 0.75).abs() < 1e-3, "half precision"); + } + + /// Hostile input: truncated and garbage files are errors, never a panic. + #[test] + fn hostile_bytes_are_errors() { + let px: Vec<[f32; 3]> = vec![[0.1, 0.2, 0.3]; 9]; + let options = crate::ExrOptions { half: false, primaries: lcc_color::REC2020 }; + let good = crate::encode_exr(3, 3, 3, bytemuck::cast_slice(&px), &options).unwrap(); + for cut in [0, 4, 40, good.len() / 2, good.len() - 1] { + assert!(decode(&good[..cut.min(good.len())], &DecodeOptions::fit(64, 64)).is_err(), "cut at {cut}"); + let _ = header(&good[..cut.min(good.len())]); + } + for garbage in [vec![0u8; 64], vec![0x76, 0x2f, 0x31, 0x01], { + let mut v = vec![0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]; + v.extend(std::iter::repeat_n(0xffu8, 512)); + v + }] { + let _ = decode(&garbage, &DecodeOptions::fit(64, 64)); + let _ = header(&garbage); + } + // a file larger than the decode budget allows is refused before the storage is made + let over = DecodeOptions { max_pixels: 4, ..Default::default() }; + assert!(decode(&good, &over).is_err(), "over budget"); + let _ = header(&good); + } +} diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index a212d4e26d..f40b8fe3e3 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -28,6 +28,7 @@ mod convert; pub mod display; pub mod encode; pub mod exif; +mod exr_decode; mod exr_encode; pub mod gainmap; mod heif; @@ -280,6 +281,7 @@ pub fn read_header_unguarded(bytes: &[u8], format: Format) -> Result
{ Format::Tiff => tiff_codec::header(bytes)?, Format::WebP => webp::header(bytes)?, Format::Psd => psd::header(bytes)?, + Format::Exr => exr_decode::header(bytes)?, Format::Heif => heif::header(bytes)?, #[cfg(not(target_arch = "wasm32"))] Format::Avif => avif::header(bytes)?, @@ -320,6 +322,7 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R Format::WebP => webp::decode(bytes, &opts), Format::Gif | Format::Bmp => other::decode(bytes, format, &opts), Format::Psd => psd::decode(bytes, &opts), + Format::Exr => exr_decode::decode(bytes, &opts), #[cfg(feature = "jxl")] Format::Jxl => jxl::decode(bytes, &opts), #[cfg(not(feature = "jxl"))] diff --git a/crates/codecs/src/sniff.rs b/crates/codecs/src/sniff.rs index 7452728304..80cc0c8412 100644 --- a/crates/codecs/src/sniff.rs +++ b/crates/codecs/src/sniff.rs @@ -20,6 +20,8 @@ pub enum Format { Bmp, /// Photoshop PSD / PSB (merged composite). Psd, + /// OpenEXR (scene-linear RGB(A), half or float). + Exr, /// TIFF-structured camera raw (DNG, CR2, NEF, ARW, PEF, ORF, RW2, SRW, 3FR, IIQ, ERF, …): /// route to `lcc-raw`. RawTiffLike, @@ -41,6 +43,7 @@ impl Format { Format::Gif => "gif", Format::Bmp => "bmp", Format::Psd => "psd", + Format::Exr => "exr", Format::RawTiffLike => "dng", Format::RawOther => "raw", } @@ -58,6 +61,7 @@ impl Format { Format::Gif => "image/gif", Format::Bmp => "image/bmp", Format::Psd => "image/vnd.adobe.photoshop", + Format::Exr => "image/x-exr", Format::RawTiffLike | Format::RawOther => "image/x-raw", } } @@ -100,6 +104,9 @@ pub fn sniff(b: &[u8]) -> Option { if b.starts_with(b"\x89PNG\r\n\x1a\n") { return Some(Format::Png); } + if b.starts_with(&[0x76, 0x2f, 0x31, 0x01]) { + return Some(Format::Exr); + } if b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a") { return Some(Format::Gif); } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a5bf936542..acb61b253f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -168,8 +168,8 @@ lcc-video = { workspace = true, features = ["test-util"] } # M14.4: the GPU playback LUT benchmark (bench_playback) wgpu = { workspace = true } pollster = { workspace = true } -filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } [target.'cfg(windows)'.dependencies] # free space on Windows (the Folders panel); its own unsafe FFI stays inside the crate diff --git a/crates/engine/src/base_curves.rs b/crates/engine/src/base_curves.rs index c17b086a5e..1717d6c43e 100644 --- a/crates/engine/src/base_curves.rs +++ b/crates/engine/src/base_curves.rs @@ -175,6 +175,10 @@ pub fn list_for(camera: &str) -> Vec { first } +/// Tests that install curves into the shared library take this, one at a time. +#[cfg(test)] +pub(crate) static LIBRARY_LOCK: Mutex<()> = Mutex::new(()); + #[cfg(test)] mod tests { use super::*; @@ -254,6 +258,7 @@ mod tests { #[test] fn a_curve_matches_the_camera_it_names_and_the_selector_lists_those_first() { + let _library = LIBRARY_LOCK.lock().unwrap_or_else(PoisonError::into_inner); assert!(matches_camera("Nikon Z 8", "NIKON Z 8")); assert!(matches_camera("NikonZ8", "Nikon Z 8")); assert!(matches_camera("Nikon Z 8", "NIKON CORPORATION NIKON Z 8")); diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index e49122418e..fc1fabfc93 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -4020,6 +4020,8 @@ mod tests { assert!(!file_local_look(RawFormat::Dng)); // Mamiya MEF has no camera JPEG to measure a look from (its previews are uncompressed RGB) assert!(!file_local_look(RawFormat::Mef)); + // FITS keeps no camera JPEG (no embedded preview at all) to measure a look from + assert!(!file_local_look(RawFormat::Fits)); } #[test] diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 6037b9e336..29a698e6fd 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -340,6 +340,46 @@ pub(crate) fn test_library_lock() -> std::sync::MutexGuard<'static, ()> { LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } +/// The decoder's profile registries emptied for a test: no active `.dcp`, imported or calibrated profiles (not even +/// the bundled calibrations) until it drops, when what was installed comes back. A test whose camera must develop +/// from its own matrices or its fitted look holds this; the registries are per process, so otherwise the answer +/// would depend on whether some other test in the process had installed the bundled calibrations +/// ([`install_dcps`]) or a profile of its own. Holds the [`test_library_lock`] for its life. +#[cfg(test)] +pub(crate) struct NoInstalledProfiles { + _lock: std::sync::MutexGuard<'static, ()>, + active: Vec, + library: Vec<(String, lcc_raw::dcp::Dcp)>, + calibrated: Vec, +} + +#[cfg(test)] +impl NoInstalledProfiles { + pub(crate) fn hold() -> NoInstalledProfiles { + // (the lock runs `install_dcps` first, so its one-time install never lands inside the empty window) + let lock = test_library_lock(); + let saved = NoInstalledProfiles { + _lock: lock, + active: lcc_raw::dcp::installed().iter().map(|d| (**d).clone()).collect(), + library: lcc_raw::dcp::library().into_iter().map(|(id, d)| (id, (*d).clone())).collect(), + calibrated: lcc_raw::dcp::calibrated().iter().map(|c| (**c).clone()).collect(), + }; + lcc_raw::dcp::install(Vec::new()); + lcc_raw::dcp::install_library(Vec::new()); + lcc_raw::dcp::install_calibrated(Vec::new()); + saved + } +} + +#[cfg(test)] +impl Drop for NoInstalledProfiles { + fn drop(&mut self) { + lcc_raw::dcp::install(std::mem::take(&mut self.active)); + lcc_raw::dcp::install_library(std::mem::take(&mut self.library)); + lcc_raw::dcp::install_calibrated(std::mem::take(&mut self.calibrated)); + } +} + /// Folder of calibration files under development (debug and test builds only): `{ENV_PREFIX}_CAMERA_CALIBRATIONS`. fn dev_calibrations_dir() -> Option { if cfg!(debug_assertions) { lcc_brand::env_os("CAMERA_CALIBRATIONS").map(PathBuf::from) } else { None } diff --git a/crates/engine/src/capture_one_catalog.rs b/crates/engine/src/capture_one_catalog.rs index 1dd566e450..52362b2fac 100644 --- a/crates/engine/src/capture_one_catalog.rs +++ b/crates/engine/src/capture_one_catalog.rs @@ -310,6 +310,9 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, let layers = crate::capture_one_develop::read_layers(&reader, &entities, cancel).map_err(|e| e.replace("Lightroom", "Capture One"))?; done.fetch_add(1, Ordering::Relaxed); let mut not_imported: BTreeMap = BTreeMap::new(); + let mut levels_too_close = 0usize; + let mut levels_unreadable = 0usize; + let mut film_curve_unreadable = 0usize; let mut keyword_names: HashMap> = HashMap::new(); for (pk, k) in &keyword_tree { keyword_names.entry(text(k, "ZNAME").trim().to_lowercase()).or_default().push(*pk); @@ -421,11 +424,20 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, let develop = layers .get(&variant_pk) .map(|l| crate::capture_one_develop::develop_of(l, [width as f64, height as f64], (camera_make, camera_model))) - .filter(|d| !d.is_empty() || !d.not_imported.is_empty()); + .filter(|d| !d.is_empty() || !d.not_imported.is_empty() || d.levels_unreadable || d.film_curve_unreadable); for tool in develop.iter().flat_map(|d| &d.not_imported) { let count = not_imported.entry(tool.clone()).or_default(); *count = count.saturating_add(1); } + if develop.as_ref().is_some_and(|d| d.levels_too_close) { + levels_too_close = levels_too_close.saturating_add(1); + } + if develop.as_ref().is_some_and(|d| d.film_curve_unreadable) { + film_curve_unreadable = film_curve_unreadable.saturating_add(1); + } + if develop.as_ref().is_some_and(|d| d.levels_unreadable) { + levels_unreadable = levels_unreadable.saturating_add(1); + } photos.push(CatalogPhoto { source_id: variant_pk, uuid: if uuid.is_empty() { String::new() } else { format!("c1:{uuid}") }, @@ -464,6 +476,19 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, for (tool, count) in not_imported { warnings.push(format!("Capture One {tool}: used on {count} photo(s), not imported yet (the photos keep the rest of their settings)")); } + if film_curve_unreadable > 0 { + warnings + .push(format!("Capture One base curve: values could not be read on {film_curve_unreadable} photo(s); no curve was set for these photos")); + } + if levels_unreadable > 0 { + warnings.push(format!("Capture One Levels: values could not be read on {levels_unreadable} photo(s); Levels skipped for these photos")); + } + if levels_too_close > 0 { + warnings.push(format!( + "Capture One Levels: black and white points closer than {} levels on {levels_too_close} photo(s); they were moved apart", + lcc_develop::LEVELS_MIN_GAP + )); + } // ---- albums, with the projects and groups that hold them let kinds: HashMap = collections @@ -597,6 +622,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, #[cfg(test)] mod tests { use super::*; + use lcc_develop::base_curve; /// A SQLite file with these tables, one leaf page each; a table's columns are its rows' keys. fn sqlite(tables: &[(&str, Vec)]) -> Vec { @@ -813,15 +839,17 @@ mod tests { let read = read_with_progress(&db, &cancel, &AtomicUsize::new(0), &AtomicUsize::new(0)).unwrap(); let c1 = read.photos[0].capture_one.as_deref().expect("variant 7 has settings"); assert_eq!(c1.not_imported, vec!["LCC", "Local adjustment layers"], "Brightness is imported"); + assert_eq!(c1.sliders.get("light.brightness"), Some(&25.0), "Capture One's 12.5 doubled"); assert!(read.photos[1].capture_one.is_none(), "an untouched variant has nothing to import"); let warnings = read.warnings.join("\n"); assert!(warnings.contains("Capture One LCC: used on 1 photo(s), not imported yet"), "{warnings}"); + assert!(!warnings.contains("Capture One Brightness"), "Brightness is imported now: {warnings}"); let mut s = crate::Session::new(); let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); let a = photo("a.NEF"); assert_eq!(a.develop.light.exposure, 0.75); - assert_eq!(a.develop.light.brightness, 25.0, "Capture One's Brightness doubled onto the app's scale"); + assert_eq!(a.develop.light.brightness, 25.0, "Capture One's Brightness doubled onto the app's scale, unrounded"); assert_eq!(a.develop.orientation, lcc_geom::Orientation::from_parts(false, 1)); let g = a.develop.crop.geometry.rect; // the centre (3000, 2000) of the 6000 × 4000 stored image is the centre shown; 2000 × 3000 of 4000 × 6000 @@ -842,6 +870,100 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Brightness and the global Levels land in the photo's settings; Levels on a local adjustment layer are named + /// next to the generic local-layers line, and points the Levels tool would have to move apart are said so. + #[test] + fn brightness_and_global_levels_import_and_local_levels_are_named() { + let dir = std::env::temp_dir().join(format!("c1-levels-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let defaults = json!({"ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", + "ZMIDTONE": "0.000;0.000;0.000;0.000", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.000", + "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZLEVELSTARGETENABLE": 1}); + std::fs::write( + &db, + develop_catalog(vec![ + layer(1, 18, 7, defaults.clone()), + layer( + 2, + 17, + 7, + json!({"ZBRIGHTNESS": 20.5, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.750", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.250", + "ZMIDTONE": "0.000;0.000;0.000;0.500", "ZLEVELSTARGETENABLE": 1}), + ), + // a local layer with Levels of its own, and one without + layer(3, 23, 7, json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.600", "ZLEVELSTARGETENABLE": 1})), + layer(4, 23, 7, json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZLEVELSTARGETENABLE": 1})), + layer(5, 18, 8, defaults), + layer(6, 17, 8, json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.500", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.502"})), + ]), + ) + .unwrap(); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); + let a = photo("a.NEF"); + assert_eq!(a.develop.light.brightness, 41.0); + let m = a.develop.levels.master; + assert_eq!((m.black, m.white, m.midtone), (191.25, 63.75, 0.5), "inverted, as stored"); + assert!(a.develop.levels.red.is_default() && a.develop.levels.green.is_default() && a.develop.levels.blue.is_default()); + // black 127.5 and white 128.01: the tool keeps them at least 2 levels apart + let b = photo("b.NEF").develop.levels.master; + assert!((b.white - b.black).abs() >= lcc_develop::LEVELS_MIN_GAP, "{b:?}"); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for line in [ + "Capture One Levels (local adjustments): used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + "Capture One Local adjustment layers: used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + "Capture One Levels: black and white points closer than 2 levels on 1 photo(s); they were moved apart", + ] { + assert!(warnings.contains(&line), "{line}: {warnings:?}"); + } + assert!(!warnings.iter().any(|w| w.starts_with("Capture One Brightness")), "{warnings:?}"); + let unmapped = + |id: &str| report["unmapped"].get(id).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect::>()); + assert_eq!(unmapped("7"), Some(vec!["Levels (local adjustments)", "Local adjustment layers"])); + assert_eq!(unmapped("8"), None, "the second variant's Levels are all imported"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Capture One can save Exposure, Brightness and Levels as the camera's defaults: a variant that keeps them has + /// them imported, even with no adjustment layer of its own; a neutral default alone imports nothing. + #[test] + fn a_default_layer_with_exposure_brightness_and_levels_is_imported_without_edits() { + let dir = std::env::temp_dir().join(format!("c1-defaults-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let neutral = + json!({"ZEXPOSURE": 0, "ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000"}); + let saved = json!({"ZEXPOSURE": 0.5, "ZBRIGHTNESS": 10, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.100", + "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}); + std::fs::write( + &db, + develop_catalog(vec![ + // variant 7: a saved default and no layer of the user's; variant 8: a neutral default, nothing else + layer(1, 18, 7, saved), + layer(2, 18, 8, neutral), + ]), + ) + .unwrap(); + let read = read_with_progress(&db, &AtomicBool::new(false), &AtomicUsize::new(0), &AtomicUsize::new(0)).unwrap(); + assert!(read.photos[0].capture_one.is_some(), "the saved default is imported"); + assert!(read.photos[1].capture_one.is_none(), "a neutral default has nothing to import"); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); + let a = photo("a.NEF"); + assert_eq!((a.develop.light.exposure, a.develop.light.brightness), (0.5, 20.0)); + assert_eq!((a.develop.levels.master.black, a.develop.levels.master.white), (25.5, 204.0)); + let b = photo("b.NEF"); + assert_eq!((b.develop.light.exposure, b.develop.light.brightness), (0.0, 0.0)); + assert!(b.develop.levels.master.is_default()); + assert!(report["unmapped"].get("7").is_none() && report["unmapped"].get("8").is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_format_named_in_place_of_a_camera_is_no_camera() { let row = |make: &str, model: &str, format: &str| -> Row { @@ -1186,8 +1308,15 @@ mod tests { if v <= 5 { own["ZBRIGHTNESS"] = json!(12); } - if v >= 6 { - own["ZHIGHLIGHTRECOVERY"] = json!(40); + match v { + 4 => own["ZSATURATION"] = json!(30), + 5 => { + own["ZSHADOWRECOVERY"] = json!(20); + own["ZCONTRAST"] = json!(15); + } + 7 => own["ZHIGHLIGHTRECOVERY"] = json!(-50), + _ if v >= 6 => own["ZHIGHLIGHTRECOVERY"] = json!(40), + _ => {} } add(17, v, own); } @@ -1224,8 +1353,9 @@ mod tests { } /// The manual's screenshot fixture is what [`manual_shot_fixture`] makes, and its import shows what the shot is - /// for: the settings not imported yet with their photo counts, and the white balance marked approximate. When the - /// generator changes, the test writes the new files to the temp folder and says where, to copy over. + /// for: the settings not imported yet with their photo counts, and the lines for the approximate Highlight, Shadow, + /// Saturation and white balance. When the generator changes, the test writes the new files to the temp folder and + /// says where, to copy over. #[test] fn the_manual_shot_fixture_is_synthetic_and_current() { let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/manual-site/scripts/fixtures/capture-one"); @@ -1252,11 +1382,684 @@ mod tests { // all of them fit the result window's eight warnings assert!(warnings.len() <= 8, "{warnings:?}"); for line in [ + "Capture One Highlight (positive values): used on 2 photo(s)", "Capture One LCC: used on 2 photo(s)", + "Capture One Contrast: used on 1 photo(s)", "Capture One Local adjustment layers: used on 1 photo(s)", + "Capture One Highlight: approximate on 1 photo(s)", + "Capture One Shadow: approximate on 1 photo(s)", + "Capture One Saturation: positive values on 1 photo(s)", "Capture One White Balance: approximate on 5 photo(s)", ] { assert!(warnings.iter().any(|w| w.starts_with(line)), "{line}: {warnings:?}"); } + // Brightness and Levels are imported now: the shot's list of what is not imported lost two lines + assert!(!warnings.iter().any(|w| w.starts_with("Capture One Brightness") || w.starts_with("Capture One Levels")), "{warnings:?}"); + } + + /// A catalog of photos shot on one (synthetic) camera, in `location`, with the layers given. The photo at index `i` + /// (from 0) is image `i + 1`; its variant is `7 + i`. + fn curve_catalog(layers: Vec, names: &[&str], location: Value) -> Vec { + let photo = |pk: i64, name: &str| { + json!({"Z_PK": pk, "ZIMAGEFILENAME": name, "ZIMAGELOCATION": 1, "ZWIDTH": 6000, "ZHEIGHT": 4000, + "ZCAMERA_MAKE": "EXAMPLE CORP", "ZCAMERA_MODEL": "EXAMPLE X1"}) + }; + let n = names.len() as i64; + sqlite(&[ + ("ZPATHLOCATION", vec![location]), + ("ZIMAGE", names.iter().enumerate().map(|(i, name)| photo(i as i64 + 1, name)).collect()), + ("ZVARIANT", (1..=n).map(|i| json!({"Z_PK": 6 + i, "ZIMAGE": i, "ZVARIANTUUID": format!("v{i}")})).collect()), + ( + "ZENTITIES", + vec![ + json!({"Z_ENT": 17, "ZNAME": "VariantAdjustmentLayer"}), + json!({"Z_ENT": 18, "ZNAME": "VariantDefaultLayer"}), + json!({"Z_ENT": 19, "ZNAME": "VariantStyleLayer"}), + json!({"Z_ENT": 23, "ZNAME": "LocalAdjustmentsLayer"}), + ], + ), + ("ZVARIANTLAYER", layers), + ]) + } + + /// A synthetic base curve file (the same as the base curve folder's tests use). + fn synthetic_curve() -> (base_curve::BaseCurve, u64) { + let bytes = json!({ + "format": "base-curve", "version": 1, "name": "synthetic", + "curves": { "a": { "interpolation": "linear", "points": [[0, 0], [0.5, 0.6], [1, 1]] } }, + "apply": [ { "op": "curve", "curve": "a", "on": "luminance" } ] + }) + .to_string() + .into_bytes(); + (base_curve::parse(&bytes).expect("valid"), base_curve::hash_bytes(&bytes)) + } + + /// A raw's film curve becomes the base curve of the same name, with the app's own colour; one whose file isn't + /// installed keeps the default base tone and is reported once, and importing again after the file is added gives + /// it to the photos nothing else was imported for. The camera's own curve is the photo's baseline, not an edit; a + /// curve of the variant's own choosing, or any other imported setting, is. + #[test] + fn a_raws_film_curve_becomes_its_base_curve_and_a_missing_file_is_reported() { + let _library = crate::base_curves::LIBRARY_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + crate::base_curves::install_once(); + let (curve, hash) = synthetic_curve(); + base_curve::install_library(vec![("base:Example-Auto".to_string(), curve.clone(), hash)]); + let dir = std::env::temp_dir().join(format!("c1-film-curve-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let defaults = |curve: &str| json!({"ZBRIGHTNESS": 0, "ZFILMCURVE": curve}); + let offline = json!({"Z_PK": 1, "ZWINROOT": "Q:\\", "ZMACROOT": "/Volumes/Gone", "ZRELATIVEPATH": "Photos"}); + std::fs::write( + &db, + curve_catalog( + vec![ + // a: the installed curve as the camera's default, nothing edited + layer(1, 18, 7, defaults("Example-Auto.fcrv")), + // b: a curve that isn't installed, and a Brightness edit + layer(2, 18, 8, defaults("Example-Missing.fcrv")), + layer(3, 17, 8, json!({"ZBRIGHTNESS": 10})), + // c: the default is installed, the user's own choice is not + layer(4, 18, 9, defaults("Example-Auto.fcrv")), + layer(5, 17, 9, json!({"ZFILMCURVE": "Example-Other.fcrv"})), + // d: a value that is not a file name + layer(6, 18, 10, json!({"ZBRIGHTNESS": 0, "ZFILMCURVE": 12})), + // e: the installed default curve and a Brightness edit + layer(7, 18, 11, defaults("Example-Auto.fcrv")), + layer(8, 17, 11, json!({"ZBRIGHTNESS": 5})), + // f: the camera's own curve isn't installed, the user's own choice is + layer(9, 18, 12, defaults("Example-Gone.fcrv")), + layer(10, 17, 12, json!({"ZFILMCURVE": "Example-Auto.fcrv"})), + // g: an offline raw with an extension nothing lists, its default curve installed + layer(11, 18, 13, defaults("Example-Auto.fcrv")), + // h: a JPEG with a camera model, whose curve is a rendered format's + layer(12, 18, 14, defaults("FileSystemJpeg-Auto.fcrv")), + ], + &["a.NEF", "b.NEF", "c.NEF", "d.NEF", "e.NEF", "f.NEF", "g.X3F", "h.JPG"], + offline, + ), + ) + .unwrap(); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + let photo = |s: &crate::Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); + let a = photo(&s, "a.NEF"); + assert_eq!((a.develop.profile.camera.as_str(), a.develop.profile.base_curve.as_str()), ("lc", "base:Example-Auto")); + // the camera's own curve, with the app's colour, is what an unedited raw has: no edit, and Reset returns to it + assert!(!a.is_edited() && a.edited.is_none(), "a photo with nothing but its default curve is not edited"); + assert_eq!(a.import_look.as_deref(), Some(&*a.develop)); + assert!(photo(&s, "b.NEF").is_edited(), "a real edit still counts"); + let e = photo(&s, "e.NEF"); + assert!( + e.is_edited() && e.develop.profile.base_curve == "base:Example-Auto" && e.develop.light.brightness == 10.0, + "the curve and a real edit" + ); + for name in ["b.NEF", "c.NEF", "d.NEF"] { + let p = photo(&s, name); + assert_eq!((p.develop.profile.camera.as_str(), p.develop.profile.base_curve.as_str()), ("", ""), "{name}"); + } + assert_eq!(photo(&s, "b.NEF").develop.light.brightness, 20.0, "the rest of its settings still come across"); + // f: the own curve is installed, the camera's isn't: the baseline has the colour only, the own curve is an edit + let f = photo(&s, "f.NEF"); + assert_eq!((f.develop.profile.camera.as_str(), f.develop.profile.base_curve.as_str()), ("lc", "base:Example-Auto")); + let look = f.import_look.as_deref().expect("a baseline"); + assert_eq!((look.profile.camera.as_str(), look.profile.base_curve.as_str()), ("lc", "")); + assert!(f.is_edited()); + // g and h: a raw of a kind nothing lists is one when Capture One gives it a camera's curve; a JPEG is not + let g = photo(&s, "g.X3F"); + assert_eq!(g.kind, lcc_catalog::MediaKind::Raw); + assert_eq!(g.develop.profile.base_curve, "base:Example-Auto"); + assert!(!g.is_edited()); + let h = photo(&s, "h.JPG"); + assert_ne!(h.kind, lcc_catalog::MediaKind::Raw); + assert_eq!((h.develop.profile.camera.as_str(), h.develop.profile.base_curve.as_str()), ("", "")); + assert!(!warnings.iter().any(|w| w.contains("not set up as raws")), "{warnings:?}"); + let missing = "Capture One base curve: 2 photo(s) use a curve file that isn't installed (2 curves, e.g. Example-Missing, Example-Other); \ + they use the default base tone. After adding the file, import the catalog again: photos with nothing else imported pick \ + the curve up; photos that got other Capture One settings keep theirs. To give them the curve, import into a new library \ + with the file in place"; + assert!(warnings.contains(&missing), "{warnings:?}"); + assert!( + warnings.contains(&"Capture One base curve: values could not be read on 1 photo(s); no curve was set for these photos"), + "{warnings:?}" + ); + assert!(!warnings.iter().any(|w| w.starts_with("Capture One Base Characteristics curve")), "{warnings:?}"); + + // what the user did with c in the library since the first import: a rating, a flag, a colour label, a keyword, + // an album and a stack with another photo + let (c0, a0) = (photo(&s, "c.NEF"), photo(&s, "a.NEF")); + let mut meta = c0.meta.clone(); + meta.keywords.push("my keyword".into()); + // (b, which the import does not replace, gets the same, to see what the import itself keeps) + let b0 = photo(&s, "b.NEF"); + let mut b_meta = b0.meta.clone(); + b_meta.keywords.push("my keyword".into()); + let (album, stack) = (s.catalog.alloc_album_id(), s.catalog.alloc_stack_id()); + let mut mine = lcc_catalog::Album::new(album, "Mine"); + mine.photos = vec![c0.id, a0.id]; + s.commit( + "Organise", + lcc_catalog::Op::Batch { + ops: vec![ + lcc_catalog::Op::SetRating { id: c0.id, rating: 4 }, + lcc_catalog::Op::SetRating { id: b0.id, rating: 4 }, + lcc_catalog::Op::SetFlag { id: b0.id, flag: lcc_catalog::Flag::Pick }, + lcc_catalog::Op::SetLabel { id: b0.id, label: Some(lcc_catalog::ColorLabel::Green) }, + lcc_catalog::Op::SetMeta { id: b0.id, meta: Box::new(b_meta) }, + lcc_catalog::Op::SetFlag { id: c0.id, flag: lcc_catalog::Flag::Pick }, + lcc_catalog::Op::SetLabel { id: c0.id, label: Some(lcc_catalog::ColorLabel::Green) }, + lcc_catalog::Op::SetMeta { id: c0.id, meta: Box::new(meta) }, + lcc_catalog::Op::AddAlbum { album: mine }, + lcc_catalog::Op::AddStack { stack: lcc_catalog::Stack { id: stack, photos: vec![a0.id, c0.id], collapsed: false } }, + ], + }, + ) + .unwrap(); + let c0 = photo(&s, "c.NEF"); + + // the missing files are added: importing again gives the curve to c (nothing else was imported for it), not to b + // (its Brightness made it an edited photo here) + base_curve::install_library(vec![ + ("base:Example-Auto".to_string(), curve.clone(), hash), + ("base:Example-Missing".to_string(), curve.clone(), hash), + ("base:Example-Other".to_string(), curve, hash), + ]); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(!warnings.iter().any(|w| w.contains("isn't installed")), "{warnings:?}"); + // c: Reset returns to the camera's base look (its own curve and colour), the own curve is the edit on top + let c = photo(&s, "c.NEF"); + assert_eq!(c.develop.profile.base_curve, "base:Example-Other"); + assert!(c.is_edited(), "a curve of the variant's own choosing is an edit"); + let look = c.import_look.as_deref().expect("a baseline"); + assert_eq!((look.profile.camera.as_str(), look.profile.base_curve.as_str()), ("lc", "base:Example-Auto")); + // the photo was replaced to carry its new import look, and kept everything else that belongs to it: its id and + // dates, rating, flag, label, keywords, album and stack, and the other photo's + assert_eq!((c.id, &c.imported, &c.captured, &c.file_name), (c0.id, &c0.imported, &c0.captured, &c0.file_name)); + // (the import itself writes the catalog's rating, flag and label, so b, which is not replaced, is the yardstick) + let b = photo(&s, "b.NEF"); + assert_eq!((c.rating, c.flag, c.label), (b.rating, b.flag, b.label), "the replacement loses nothing the import keeps"); + assert!(c.meta.keywords.contains(&"my keyword".to_string()), "{:?}", c.meta.keywords); + assert_eq!(c.meta.keywords, b.meta.keywords); + assert_eq!(s.catalog.album(album).unwrap().photos, vec![c0.id, a0.id]); + assert_eq!(s.catalog.stack_of(c0.id).map(|st| st.photos.clone()), Some(vec![a0.id, c0.id])); + assert!(!photo(&s, "a.NEF").is_edited()); + assert_eq!(photo(&s, "b.NEF").develop.profile.base_curve, "", "an edited photo keeps its settings"); + base_curve::install_library(vec![]); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A film curve on a file the app doesn't develop as a raw (here: a raw it can't decode, and a file that reads as an + /// image) sets no curve and no colour, and is reported on its own line. + #[test] + fn a_film_curve_on_a_file_that_is_not_developed_as_a_raw_is_reported() { + let _library = crate::base_curves::LIBRARY_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + crate::base_curves::install_once(); + let (curve, hash) = synthetic_curve(); + base_curve::install_library(vec![("base:Example-Auto".to_string(), curve, hash)]); + let dir = std::env::temp_dir().join(format!("c1-film-curve-not-raw-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Originals")).unwrap(); + for name in ["a.NEF", "b.NEF", "c.NEF"] { + std::fs::write(dir.join("Originals").join(name), b"original").unwrap(); + } + let db = dir.join("Test.cocatalogdb"); + let defaults = json!({"ZBRIGHTNESS": 0, "ZFILMCURVE": "Example-Auto.fcrv"}); + std::fs::write( + &db, + curve_catalog( + vec![layer(1, 18, 7, defaults.clone()), layer(2, 18, 8, defaults.clone()), layer(3, 18, 9, defaults)], + &["a.NEF", "b.NEF", "c.NEF"], + json!({"Z_PK": 1, "ZISRELATIVE": 1, "ZRELATIVEPATH": "./Originals"}), + ), + ) + .unwrap(); + let mut s = crate::Session::new(); + // the originals are read: a is an image to the app, b a raw it can't decode yet, c a raw + s.media.file_probe = Some(std::sync::Arc::new(|path: &str| { + let name = Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let (kind, preview_only) = match name.as_str() { + "a.NEF" => (lcc_catalog::MediaKind::Image, None), + "b.NEF" => (lcc_catalog::MediaKind::Raw, Some("unsupported".to_string())), + _ => (lcc_catalog::MediaKind::Raw, None), + }; + Ok(crate::media::ProbeInfo { + format: "NEF".into(), + width: 20, + height: 10, + file_size: 8, + content_hash: Some(format!("hash-{name}")), + kind, + preview_only, + ..Default::default() + }) + })); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + let photo = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().clone(); + for name in ["a.NEF", "b.NEF"] { + let p = photo(name); + assert_eq!((p.develop.profile.camera.as_str(), p.develop.profile.base_curve.as_str()), ("", ""), "{name}"); + } + assert_eq!(photo("c.NEF").develop.profile.base_curve, "base:Example-Auto"); + let line = "Capture One base curve: 2 photo(s) have a film curve but were not set up as raws (a file the app can't develop yet, or one that \ + couldn't be read); no curve or colour was set for them"; + assert!(warnings.contains(&line), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w.contains("isn't installed")), "{warnings:?}"); + base_curve::install_library(vec![]); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A rendered file's exposure is converted (1.17 times Capture One's), a raw's is taken as it is, and an exposure above + /// half a stop is reported as approximate whatever the file. + #[test] + fn a_rendered_files_exposure_is_converted_and_big_exposures_are_reported() { + let dir = std::env::temp_dir().join(format!("c1-exposure-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let offline = json!({"Z_PK": 1, "ZWINROOT": "Q:\\", "ZMACROOT": "/Volumes/Gone", "ZRELATIVEPATH": "Photos"}); + let ev = |variant: i64, pk: i64, ev: f64| { + vec![layer(pk * 2 - 1, 18, variant, json!({"ZEXPOSURE": 0})), layer(pk * 2, 17, variant, json!({"ZEXPOSURE": ev}))] + }; + let layers: Vec = + [(7, 1, 1.0), (8, 2, 1.0), (9, 3, 0.4), (10, 4, -2.0), (11, 5, 4.5)].iter().flat_map(|(v, pk, e)| ev(*v, *pk, *e)).collect(); + std::fs::write(&db, curve_catalog(layers, &["a.NEF", "b.TIF", "c.TIF", "d.JPG", "e.TIF"], offline)).unwrap(); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + let exposure = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().develop.light.exposure; + assert_eq!(exposure("a.NEF"), 1.0, "a raw's exposure is taken as it is"); + assert!((exposure("b.TIF") - 1.17).abs() < 1e-9); + assert!((exposure("c.TIF") - 0.468).abs() < 1e-9); + assert!((exposure("d.JPG") + 2.34).abs() < 1e-9); + assert_eq!(exposure("e.TIF"), 5.0, "held to the app's range"); + // two of the rendered files are above half a stop (the raw above it is not counted) + let line = "Capture One Exposure: approximate on 2 photo(s); on a rendered file the exposure is converted, and above +0.5 EV Capture One's \ + highlight shoulder isn't reproduced"; + assert!(warnings.contains(&line), "{warnings:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Highlight, Shadow and Saturation come across by their mappings: a negative Highlight one to one (approximate), a + /// negative Shadow 1.2 times and a positive one twice (approximate, held to the range), a positive Highlight not at + /// all; Saturation one to one when negative, as Vibrance on a raw (approximate) and not at all on a rendered file + /// when positive. Contrast, White and Black are reported. The result window says what is approximate and what isn't + /// imported, with the photo counts. + #[test] + fn highlight_shadow_and_saturation_are_imported_by_their_mappings_and_counted() { + let dir = std::env::temp_dir().join(format!("c1-tone-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let offline = json!({"Z_PK": 1, "ZWINROOT": "Q:\\", "ZMACROOT": "/Volumes/Gone", "ZRELATIVEPATH": "Photos"}); + let zero = json!({"ZHIGHLIGHTRECOVERY": 0, "ZSHADOWRECOVERY": 0, "ZSATURATION": 0, "ZCONTRAST": 0, "ZWHITERECOVERY": 0, "ZBLACKRECOVERY": 0}); + let own = |variant: i64, set: Value| vec![layer(variant * 2 - 1, 18, variant, zero.clone()), layer(variant * 2, 17, variant, set)]; + let layers: Vec = [ + // a: a raw: strong Highlight, a negative Shadow, a positive Saturation (-> Vibrance 80) + (7, json!({"ZHIGHLIGHTRECOVERY": -50, "ZSHADOWRECOVERY": -25, "ZSATURATION": 50})), + // b: a rendered file: Highlight at its limit, a negative Saturation + (8, json!({"ZHIGHLIGHTRECOVERY": -100, "ZSATURATION": -40})), + // c: a rendered file: a positive Saturation (not imported) and a positive Shadow (twice, held to the range) + (9, json!({"ZSATURATION": 50, "ZSHADOWRECOVERY": 60})), + // d: a raw: Contrast, White and Black, none imported + (10, json!({"ZCONTRAST": 20, "ZWHITERECOVERY": -10, "ZBLACKRECOVERY": 5})), + // e: a raw: a negative Saturation, nothing approximate + (11, json!({"ZSATURATION": -60})), + // f: a raw: a Shadow that goes past the range once scaled + (12, json!({"ZSHADOWRECOVERY": -90})), + // g: a raw: a positive Highlight, not imported + (13, json!({"ZHIGHLIGHTRECOVERY": 30})), + // h, i: raws: a positive Shadow below and at the top of the range + (14, json!({"ZSHADOWRECOVERY": 20})), + (15, json!({"ZSHADOWRECOVERY": 100})), + ] + .iter() + .flat_map(|(v, set)| own(*v, set.clone())) + .collect(); + std::fs::write(&db, curve_catalog(layers, &["a.NEF", "b.TIF", "c.JPG", "d.NEF", "e.NEF", "f.NEF", "g.NEF", "h.NEF", "i.NEF"], offline)) + .unwrap(); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + let develop = |name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().develop.clone(); + let [a, b, c, d, e, f, g, h, i] = ["a.NEF", "b.TIF", "c.JPG", "d.NEF", "e.NEF", "f.NEF", "g.NEF", "h.NEF", "i.NEF"].map(develop); + assert_eq!((h.light.shadows, i.light.shadows), (40.0, 100.0), "a positive Shadow twice, held to the range"); + assert_eq!((a.light.highlights, a.light.shadows, a.color.vibrance, a.color.saturation), (-50.0, -30.0, 80.0, 0.0)); + assert_eq!((b.light.highlights, b.color.saturation, b.color.vibrance), (-100.0, -40.0, 0.0)); + assert_eq!((c.color.saturation, c.color.vibrance), (0.0, 0.0), "a positive Saturation on a rendered file is not imported"); + assert_eq!(c.light.shadows, 100.0, "a positive Shadow is imported on a rendered file too"); + assert_eq!((d.light.contrast, d.light.whites, d.light.blacks), (0.0, 0.0, 0.0)); + assert_eq!((e.color.saturation, e.color.vibrance), (-60.0, 0.0)); + assert_eq!(f.light.shadows, -100.0, "held to the app's range"); + assert_eq!(g.light.highlights, 0.0, "a positive Highlight is not imported"); + for line in [ + "Capture One Highlight: approximate on 2 photo(s); strong negative values stay lighter than in Capture One in very bright areas", + "Capture One Saturation: positive values on 1 photo(s) are imported as Vibrance, which is approximate; skin tones stay less saturated \ + than in Capture One, and strongly saturated colours are boosted a little less", + "Capture One Saturation: approximate on 1 rendered file(s); negative values are imported one to one, and the most saturated colours \ + don't darken as much as in Capture One", + "Capture One Saturation (positive values): used on 1 rendered file(s), not imported yet (the photos keep the rest of their settings)", + "Capture One Shadow: approximate on 3 photo(s); positive values are imported at twice their value, held to the app's 100, and strong \ + lifts stay darker than in Capture One", + "Capture One Highlight (positive values): used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + "Capture One Contrast: used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + "Capture One White: used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + "Capture One Black: used on 1 photo(s), not imported yet (the photos keep the rest of their settings)", + ] { + assert!(warnings.contains(&line), "{line}: {warnings:#?}"); + } + // the two Saturation lines are the Vibrance one and the rendered one (a negative Saturation on a raw says nothing), and a + // positive Shadow is no longer reported as not imported + assert!(!warnings.iter().any(|w| w.starts_with("Capture One Shadow (positive values)")), "{warnings:?}"); + assert_eq!(warnings.iter().filter(|w| w.starts_with("Capture One Saturation: ")).count(), 2, "{warnings:#?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A raw that gets a base curve has its Capture One white balance converted through the camera database alone: the + /// as-shot white the app may have read from the file (under a camera profile of the user's, say) is not the reference. + #[test] + fn a_curve_photos_white_balance_does_not_depend_on_the_as_shot_white_the_app_read() { + let _library = crate::base_curves::LIBRARY_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + crate::base_curves::install_once(); + let (curve, hash) = synthetic_curve(); + base_curve::install_library(vec![("base:Example-Auto".to_string(), curve, hash)]); + // a camera with matrices: its raws are developed in Kelvin + let camera = lcc_camdb::entries().into_iter().find(|e| lcc_raw::color::has_matrix(&e.color_data())).expect("a camera with matrices"); + let dir = std::env::temp_dir().join(format!("c1-asshot-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let offline = json!({"Z_PK": 1, "ZWINROOT": "Q:\\", "ZMACROOT": "/Volumes/Gone", "ZRELATIVEPATH": "Photos"}); + let catalog = |white: Option<&str>| { + let mut layers = + vec![layer(1, 18, 7, json!({"ZBRIGHTNESS": 0, "ZFILMCURVE": "Example-Auto.fcrv", "ZWHITEBALANCE": "2.000;1.000;1.400"}))]; + if let Some(w) = white { + layers.push(layer(2, 17, 7, json!({"ZWHITEBALANCE": w}))); + } + sqlite(&[ + ("ZPATHLOCATION", vec![offline.clone()]), + ( + "ZIMAGE", + vec![json!({"Z_PK": 1, "ZIMAGEFILENAME": "a.NEF", "ZIMAGELOCATION": 1, "ZWIDTH": 6000, "ZHEIGHT": 4000, + "ZCAMERA_MAKE": camera.make, "ZCAMERA_MODEL": camera.model})], + ), + ("ZVARIANT", vec![json!({"Z_PK": 7, "ZIMAGE": 1, "ZVARIANTUUID": "v1"})]), + ( + "ZENTITIES", + vec![ + json!({"Z_ENT": 17, "ZNAME": "VariantAdjustmentLayer"}), + json!({"Z_ENT": 18, "ZNAME": "VariantDefaultLayer"}), + json!({"Z_ENT": 19, "ZNAME": "VariantStyleLayer"}), + json!({"Z_ENT": 23, "ZNAME": "LocalAdjustmentsLayer"}), + ], + ), + ("ZVARIANTLAYER", layers), + ]) + }; + // the photo first, with nothing but its camera's curve: unedited + std::fs::write(&db, catalog(None)).unwrap(); + let mut s = crate::Session::new(); + crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + use crate::capture_one_develop::kelvin; + assert!(!s.catalog.photo(id).unwrap().is_edited()); + // the app then reads the file's white balance under another reference (a profile of the user's gives another Kelvin) + s.apply_system(lcc_catalog::Op::SetAsShotWb { id, wb: Some((3100.0, -20.0)) }).unwrap(); + // Capture One's white balance is set, and the catalog imported again + std::fs::write(&db, catalog(Some("2.200;1.000;1.200"))).unwrap(); + crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let wb = s.catalog.photo(id).unwrap().develop.wb; + let make = Some(camera.make.as_str()).filter(|m| !m.is_empty()); + let entry = lcc_camdb::find(make, &camera.model).unwrap(); + let (temp, tint) = kelvin(Some(&entry), [2.2, 1.0, 1.2]).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().develop.profile.camera, "lc"); + assert!((wb.temp - temp).abs() < 1e-6 && (wb.tint - tint).abs() < 1e-9, "{wb:?} against {temp} {tint}"); + base_curve::install_library(vec![]); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A Capture One catalog has no edit time for its images (the column is empty in catalogs written by Capture One): the + /// import dates a photo with settings at the import and says nothing about it, where a Lightroom import names the + /// images whose time it can't read. A date the column does hold is used. + #[test] + fn a_capture_one_import_makes_no_edit_time_line() { + let dir = std::env::temp_dir().join(format!("c1-edit-time-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let offline = json!({"Z_PK": 1, "ZWINROOT": "Q:\\", "ZMACROOT": "/Volumes/Gone", "ZRELATIVEPATH": "Photos"}); + let zero = json!({"ZBRIGHTNESS": 0}); + let layers: Vec = + (7..=9).flat_map(|v| vec![layer(v * 2 - 1, 18, v, zero.clone()), layer(v * 2, 17, v, json!({"ZBRIGHTNESS": 10}))]).collect(); + std::fs::write(&db, curve_catalog(layers, &["a.NEF", "b.NEF", "c.NEF"], offline)).unwrap(); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(!warnings.iter().any(|w| w.contains("edit time") || w.contains("Lightroom")), "{warnings:?}"); + assert!(s.catalog.photos().all(|p| p.edited.is_some() && p.develop.light.brightness == 20.0), "dated at the import, with its settings"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A Capture One catalog is the only source of its photos: a sidecar next to an original (another editor's rating, + /// title and develop settings) reaches nothing, however the catalog is imported, and no line about sidecars that + /// differ from the catalog is made. + #[test] + fn a_capture_one_import_reads_no_xmp_sidecar() { + let dir = std::env::temp_dir().join(format!("c1-sidecar-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Originals")).unwrap(); + std::fs::write(dir.join("Originals").join("a.NEF"), b"original").unwrap(); + // what another editor wrote: a rating, a title and a creator, and develop settings + std::fs::write( + dir.join("Originals").join("a.xmp"), + r#"Sidecar title + Sidecar creator"#, + ) + .unwrap(); + let db = dir.join("Test.cocatalogdb"); + std::fs::write( + &db, + sqlite(&[ + ("ZPATHLOCATION", vec![json!({"Z_PK": 1, "ZISRELATIVE": 1, "ZRELATIVEPATH": "./Originals"})]), + ( + "ZIMAGE", + vec![json!({"Z_PK": 1, "ZIMAGEFILENAME": "a.NEF", "ZIMAGELOCATION": 1, "ZWIDTH": 6000, "ZHEIGHT": 4000, + "ZCAMERA_MAKE": "EXAMPLE CORP", "ZCAMERA_MODEL": "EXAMPLE X1"})], + ), + ("ZVARIANT", vec![json!({"Z_PK": 7, "ZIMAGE": 1, "ZVARIANTUUID": "a", "ZADJUSTMENTLAYER": 101})]), + ("ZVARIANTMETADATA", vec![json!({"Z_PK": 1, "ZLAYER": 101, "ZBASIC_RATING": 2})]), + ( + "ZENTITIES", + vec![ + json!({"Z_ENT": 17, "ZNAME": "VariantAdjustmentLayer"}), + json!({"Z_ENT": 18, "ZNAME": "VariantDefaultLayer"}), + json!({"Z_ENT": 19, "ZNAME": "VariantStyleLayer"}), + json!({"Z_ENT": 23, "ZNAME": "LocalAdjustmentsLayer"}), + ], + ), + ("ZVARIANTLAYER", vec![layer(1, 18, 7, json!({"ZBRIGHTNESS": 0})), layer(2, 17, 7, json!({"ZBRIGHTNESS": 10}))]), + ]), + ) + .unwrap(); + let mut s = crate::Session::new(); + s.media.file_probe = Some(std::sync::Arc::new(|_: &str| { + Ok(crate::media::ProbeInfo { + format: "NEF".into(), + width: 20, + height: 10, + file_size: 8, + content_hash: Some("hash".into()), + kind: lcc_catalog::MediaKind::Raw, + ..Default::default() + }) + })); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 2, "the catalog's rating, not the sidecar's"); + assert_eq!((p.develop.light.exposure, p.develop.light.brightness), (0.0, 20.0), "the catalog's settings only"); + let meta = serde_json::to_string(&p.meta).unwrap(); + assert!(!meta.contains("Sidecar title") && !meta.contains("Sidecar creator"), "{meta}"); + assert_eq!(report["sidecarsDisagree"], 0, "{report}"); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(!warnings.iter().any(|w| w.contains("sidecar") || w.contains("edit time")), "{warnings:?}"); + assert!(p.edited.is_some(), "a photo with settings is dated at the import"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A catalog of one image `a.NEF` (a raw on a drive that isn't there) with the variants, their metadata and layers + /// given. A variant row names its metadata layer in `ZADJUSTMENTLAYER`. + fn variants_catalog(variants: Vec, metadata: Vec, layers: Vec) -> Vec { + sqlite(&[ + ("ZPATHLOCATION", vec![json!({"Z_PK": 1, "ZWINROOT": "Q:\\", "ZMACROOT": "/Volumes/Gone", "ZRELATIVEPATH": "Photos"})]), + ( + "ZIMAGE", + vec![json!({"Z_PK": 1, "ZIMAGEFILENAME": "a.NEF", "ZIMAGELOCATION": 1, "ZWIDTH": 6000, "ZHEIGHT": 4000, + "ZCAMERA_MAKE": "EXAMPLE CORP", "ZCAMERA_MODEL": "EXAMPLE X1"})], + ), + ("ZVARIANT", variants), + ("ZVARIANTMETADATA", metadata), + ( + "ZENTITIES", + vec![ + json!({"Z_ENT": 17, "ZNAME": "VariantAdjustmentLayer"}), + json!({"Z_ENT": 18, "ZNAME": "VariantDefaultLayer"}), + json!({"Z_ENT": 19, "ZNAME": "VariantStyleLayer"}), + json!({"Z_ENT": 23, "ZNAME": "LocalAdjustmentsLayer"}), + ], + ), + ("ZVARIANTLAYER", layers), + ]) + } + + /// A further variant of an image is a photo of its own: it starts from the camera's defaults and its own variant's + /// settings, not from its master's edits, edit date, rating, label or keywords. + #[test] + fn a_further_variant_does_not_inherit_its_masters_settings() { + let _library = crate::base_curves::LIBRARY_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + crate::base_curves::install_once(); + let (curve, hash) = synthetic_curve(); + base_curve::install_library(vec![("base:Example-Auto".to_string(), curve, hash)]); + let dir = std::env::temp_dir().join(format!("c1-variants-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("Test.cocatalogdb"); + let default = |pk: i64, variant: i64| layer(pk, 18, variant, json!({"ZEXPOSURE": 0, "ZBRIGHTNESS": 0, "ZFILMCURVE": "Example-Auto.fcrv"})); + let variant = + |pk: i64, metadata_layer: i64| json!({"Z_PK": pk, "ZIMAGE": 1, "ZVARIANTUUID": format!("v{pk}"), "ZADJUSTMENTLAYER": metadata_layer}); + std::fs::write( + &db, + variants_catalog( + // 7 is the master, 8 a variant with nothing of its own, 9 one with a Brightness edit of its own + vec![variant(7, 101), variant(8, 102), variant(9, 103)], + vec![ + json!({"Z_PK": 1, "ZLAYER": 101, "ZBASIC_RATING": 5, "ZCOLOR_TAG_INDEX": 1, "ZCONTENT_KEYWORDS": "Master|Keyword"}), + json!({"Z_PK": 2, "ZLAYER": 102, "ZBASIC_RATING": 2, "ZCOLOR_TAG_INDEX": 4}), + json!({"Z_PK": 3, "ZLAYER": 103, "ZBASIC_RATING": 0, "ZCONTENT_KEYWORDS": "Own"}), + ], + vec![ + default(1, 7), + layer(2, 17, 7, json!({"ZEXPOSURE": 2.0, "ZBRIGHTNESS": 10})), + default(3, 8), + default(4, 9), + layer(5, 17, 9, json!({"ZBRIGHTNESS": 5})), + ], + ), + ) + .unwrap(); + let mut s = crate::Session::new(); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let by_id = |id: i64| { + let pk = report["mapping"][id.to_string()].as_u64().unwrap(); + s.catalog.photo(lcc_catalog::PhotoId(pk)).unwrap().clone() + }; + let (master, plain, edited) = (by_id(7), by_id(8), by_id(9)); + assert!(master.copy_of.is_none() && plain.copy_of == Some(master.id) && edited.copy_of == Some(master.id)); + // the master: its own edits and metadata + assert_eq!((master.develop.light.exposure, master.develop.light.brightness), (2.0, 20.0)); + assert!(master.is_edited() && master.edited.is_some()); + assert_eq!((master.rating, master.label), (5, Some(lcc_catalog::ColorLabel::Red))); + assert_eq!(master.meta.keywords, ["Master|Keyword"]); + // a variant with nothing of its own: the camera's own curve and colour as its baseline, no edit, no exposure + assert_eq!((plain.develop.light.exposure, plain.develop.light.brightness), (0.0, 0.0), "the master's edits stay with the master"); + assert_eq!((plain.develop.profile.camera.as_str(), plain.develop.profile.base_curve.as_str()), ("lc", "base:Example-Auto")); + assert!(!plain.is_edited(), "a curve-only copy is unedited, like a curve-only master"); + assert_eq!(plain.import_look.as_deref(), Some(&*plain.develop)); + assert!(plain.history.is_empty() && plain.versions.is_empty()); + assert_eq!((plain.rating, plain.label), (2, Some(lcc_catalog::ColorLabel::Green)), "its own rating and label"); + assert!(plain.meta.keywords.is_empty(), "the master's keywords are the master's: {:?}", plain.meta.keywords); + // a variant with an edit of its own: only that edit, on the same baseline + assert_eq!((edited.develop.light.exposure, edited.develop.light.brightness), (0.0, 10.0)); + assert!(edited.is_edited()); + assert_eq!(edited.develop.profile.base_curve, "base:Example-Auto"); + assert_eq!((edited.rating, edited.label), (0, None)); + assert_eq!(edited.meta.keywords, ["Own"]); + base_curve::install_library(vec![]); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Two catalog images that point to the same original share one record: the line says so, and the record keeps + /// the settings of the last of them. + #[test] + fn images_that_share_an_original_are_reported() { + let dir = std::env::temp_dir().join(format!("c1-shared-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Originals")).unwrap(); + std::fs::write(dir.join("Originals").join("a.NEF"), b"original").unwrap(); + let db = dir.join("Test.cocatalogdb"); + let photo = |pk: i64| { + json!({"Z_PK": pk, "ZIMAGEFILENAME": "a.NEF", "ZIMAGELOCATION": 1, "ZWIDTH": 6000, "ZHEIGHT": 4000, + "ZCAMERA_MAKE": "EXAMPLE CORP", "ZCAMERA_MODEL": "EXAMPLE X1"}) + }; + std::fs::write( + &db, + sqlite(&[ + ("ZPATHLOCATION", vec![json!({"Z_PK": 1, "ZISRELATIVE": 1, "ZRELATIVEPATH": "./Originals"})]), + ("ZIMAGE", vec![photo(1), photo(2)]), + ("ZVARIANT", vec![json!({"Z_PK": 7, "ZIMAGE": 1, "ZVARIANTUUID": "a"}), json!({"Z_PK": 8, "ZIMAGE": 2, "ZVARIANTUUID": "b"})]), + ( + "ZENTITIES", + vec![ + json!({"Z_ENT": 17, "ZNAME": "VariantAdjustmentLayer"}), + json!({"Z_ENT": 18, "ZNAME": "VariantDefaultLayer"}), + json!({"Z_ENT": 19, "ZNAME": "VariantStyleLayer"}), + json!({"Z_ENT": 23, "ZNAME": "LocalAdjustmentsLayer"}), + ], + ), + ( + "ZVARIANTLAYER", + vec![ + layer(1, 18, 7, json!({"ZBRIGHTNESS": 0})), + layer(2, 17, 7, json!({"ZBRIGHTNESS": 10})), + layer(3, 18, 8, json!({"ZBRIGHTNESS": 0})), + layer(4, 17, 8, json!({"ZBRIGHTNESS": 20})), + ], + ), + ]), + ) + .unwrap(); + let mut s = crate::Session::new(); + s.media.file_probe = Some(std::sync::Arc::new(|_: &str| { + Ok(crate::media::ProbeInfo { + format: "NEF".into(), + width: 20, + height: 10, + file_size: 8, + content_hash: Some("hash".into()), + kind: lcc_catalog::MediaKind::Raw, + ..Default::default() + }) + })); + let report = crate::lightroom_catalog::import(&mut s, &db, false).unwrap(); + let warnings: Vec<&str> = report["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(s.catalog.photos().count(), 1, "one original, one record"); + assert_eq!(s.catalog.photos().next().unwrap().develop.light.brightness, 40.0, "the last image's settings"); + let line = "Capture One: 1 catalog image(s) point to the same original as an earlier image and were put on its record; the record keeps the \ + settings of the last image that points to it"; + assert!(warnings.contains(&line), "{warnings:?}"); + let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/engine/src/capture_one_develop.rs b/crates/engine/src/capture_one_develop.rs index 240a9cce83..c2742a1837 100644 --- a/crates/engine/src/capture_one_develop.rs +++ b/crates/engine/src/capture_one_develop.rs @@ -3,14 +3,22 @@ //! Capture One keeps a variant's develop settings in `ZVARIANTLAYER`, one row per layer, told apart by the //! Core Data entity in `Z_ENT` (named in `ZENTITIES`): the *adjustment* layer holds what the user set (a column //! the user never touched is NULL), *style* layers what applied styles set, and the *default* layer the camera's -//! defaults (every column filled). A setting counts as the variant's when the adjustment layer (else a style) -//! sets it to something other than the default. +//! defaults (every column filled). Exposure, Brightness and the Levels are the variant's *effective* value: the +//! adjustment layer's, else a style's, else the default layer's (Capture One can save them as the camera's defaults), +//! imported when it differs from neutral by more than a tolerance (float noise left by a reset isn't an edit). The +//! other settings count as the variant's when the adjustment layer (else a style) sets them to something other than +//! the default. //! -//! Imported so far: exposure, contrast, brightness, saturation, High Dynamic Range (highlight, shadow, white and -//! black recovery), clarity and structure, levels (per channel, input and target), the curves (RGB, red, green, -//! blue), the orientation and straighten angle, the crop and its aspect, flips and white balance. Every other setting -//! a variant uses, and any of those whose stored value can't be read, is named in the import report as not imported. The ICC profile -//! choice is left out on purpose: photos get the app's standard camera colour. +//! Imported so far: exposure, brightness, levels (per channel, input and output), the curves (RGB, red, green, +//! blue), negative Highlight, Shadow (a positive one at twice its value, held to the app's range), Saturation +//! (see [`vibrance_for_saturation`]), the orientation and straighten angle, the crop and its aspect, flips and white +//! balance. Every other setting a variant uses, and any of those whose stored value can't be read, is named in the +//! import report as not imported (Contrast, White, Black, Clarity and Structure, positive Highlight, and +//! positive Saturation on a rendered file: their scales differ from the app's by more than a factor can bridge). Local +//! adjustment layers are not imported. A raw's film curve (`ZFILMCURVE`, the +//! effective value) is kept as the stem of its file name: the import turns it into the base curve of that name when +//! the file is installed (see `crate::lightroom_catalog`). The ICC profile choice is left out on purpose: photos get +//! the app's standard camera colour, except that a raw given a base curve gets the app's own (Built-in) colour. //! //! How Capture One writes the values (observed in catalogs written by Capture One 16.x, own design; no Capture One //! code or documentation was used): @@ -21,18 +29,19 @@ //! - `ZFLIP` 0 none, 1 horizontal, 2 vertical. //! - `ZWHITEBALANCE` `r;g;b`: the gains on the camera's raw channels (green 1). //! - `ZEXPOSURE` EV. -//! - `ZCONTRAST`, `ZBRIGHTNESS`, `ZSATURATION` −50..50 (the app's sliders run −100..100: doubled). -//! - `ZHIGHLIGHTRECOVERY`, `ZSHADOWRECOVERY`, `ZWHITERECOVERY`, `ZBLACKRECOVERY`: recovery amounts (positive pulls -//! highlights and whites down, lifts shadows and blacks), on the app's −100..100 scale. -//! - `ZCLARITY`, `ZCLARITYSTRUCTURE` −100..100 (structure is the app's Texture); `ZCLARITYMETHOD` has no equivalent. +//! - `ZBRIGHTNESS` −50..50 (fractions are common; the app's slider runs −100..100 with the same effect: doubled). +//! - `ZHIGHLIGHTRECOVERY`, `ZSHADOWRECOVERY`, `ZSATURATION` −100..100, stored as the slider shows them (Highlight and +//! Shadow are the High Dynamic Range tool's, with `ZWHITERECOVERY` and `ZBLACKRECOVERY`). //! - `ZGRADATIONCURVE[RED|GREEN|BLUE]` `x,y;x,y;…`: curve points, 0..1 (0..255 accepted); `…Y` (the luma curve) has //! no equivalent. -//! - `ZLEVELSSHADOW`, `ZLEVELSHIGHLIGHT`, `ZLEVELSTARGETSHADOW`, `ZLEVELSTARGETHIGHLIGHT`, `ZMIDTONE`: one value for -//! all channels or four (`rgb;r;g;b`), 0..1 (0..255 accepted); the midtone is where its marker sits between the -//! black and white points (0.5 neutral). +//! - Levels, one text per column with four slots `red;green;blue;master`: `ZLEVELSSHADOW` and `ZLEVELSHIGHLIGHT` +//! (the input black and white points) and `ZLEVELSTARGETSHADOW` and `ZLEVELSTARGETHIGHLIGHT` (the output levels), +//! all 0..1 of the 0..255 scale, and `ZMIDTONE`, the signed midtone (−1..1, 0 neutral, as the tool shows it). The +//! values are stored to three decimals, and Capture One itself renders a reopened catalog from them, so they are +//! read exactly, not snapped to whole levels. A black point above the white point is stored as it is (the channel +//! is inverted); nothing is swapped. Output levels count only while `ZLEVELSTARGETENABLE` isn't 0. //! -//! The tool formats below the exposure line follow Capture One's own sidecar (`.cos`) keys of the same names; values -//! that don't read as described are reported, never guessed. +//! Values that don't read as described are reported, never guessed. use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::atomic::AtomicBool; @@ -73,16 +82,42 @@ pub struct CaptureOneDevelop { /// White balance through the camera's matrices, when the variant's differs from as shot. #[serde(skip_serializing_if = "Option::is_none")] pub white: Option, - /// Sliders brought across one to one, by the app's name (`light.contrast`, `effects.clarity`, …), on the app's - /// scale. + /// Sliders brought across by a factor, by the app's name (`light.brightness`, `light.highlights`, …), on the + /// app's scale. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub sliders: BTreeMap, + /// Saturation as Capture One stores it (−100..100), when set: the app's Saturation or Vibrance, or nothing, + /// depending on the sign and the file ([`partial_for`]). + #[serde(skip_serializing_if = "Option::is_none")] + pub saturation: Option, /// Point curves (0..1, `[in, out]`) by the app's channel name (`master`, `red`, `green`, `blue`). #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub curves: BTreeMap>, /// Levels by the app's channel name: black, midtone (−1..1), white, output black, output white (0..255). #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub levels: BTreeMap, + /// Whether an imported channel has its black and white points closer together than the Levels tool allows + /// (it moves them apart on import). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub levels_too_close: bool, + /// Whether a Levels column holds something other than four numbers: the variant's Levels are skipped. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub levels_unreadable: bool, + /// The raw's film curve (`ZFILMCURVE`, the effective value) as the stem of its curve file: `-Auto.fcrv` is + /// `-Auto`, the base curve `base:-Auto` once such a file is installed. Not set for a rendered file. + #[serde(skip_serializing_if = "Option::is_none")] + pub film_curve: Option, + /// Whether the film curve column holds something that isn't a file name: no curve is set. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub film_curve_unreadable: bool, + /// Whether the curve is the variant's own choice (an adjustment or style sets a curve other than the camera's + /// default): an edit. The camera's default curve is what an unedited raw has. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub film_curve_own: bool, + /// The camera's default curve (the default layer's, as a file stem) when the variant chose another one: what the + /// photo's baseline has, with the own choice on top as an edit. + #[serde(skip_serializing_if = "Option::is_none")] + pub film_curve_default: Option, /// The settings the variant uses that this import doesn't bring across (names as Capture One shows them). #[serde(skip_serializing_if = "Vec::is_empty")] pub not_imported: Vec, @@ -105,11 +140,15 @@ const TOOLS: &[(&str, &[&str])] = &[ ("Brightness", &["ZBRIGHTNESS"]), ("Contrast", &["ZCONTRAST"]), ("Saturation", &["ZSATURATION"]), - ("High Dynamic Range", &["ZHIGHLIGHTRECOVERY", "ZSHADOWRECOVERY", "ZWHITERECOVERY", "ZBLACKRECOVERY"]), + ("Highlight", &["ZHIGHLIGHTRECOVERY"]), + ("Shadow", &["ZSHADOWRECOVERY"]), + ("White", &["ZWHITERECOVERY"]), + ("Black", &["ZBLACKRECOVERY"]), ("Levels", &["ZLEVELSHIGHLIGHT", "ZLEVELSSHADOW", "ZMIDTONE", "ZLEVELSTARGETHIGHLIGHT", "ZLEVELSTARGETSHADOW"]), ("Curve", &["ZGRADATIONCURVE"]), ("Base Characteristics curve", &["ZFILMCURVE"]), ("Clarity", &["ZCLARITY"]), + ("Structure", &["ZCLARITYSTRUCTURE"]), ("Clarity method", &["ZCLARITYMETHOD"]), ("Luma curve", &["ZGRADATIONCURVEY"]), ("Dehaze", &["ZDEHAZEAMOUNT", "ZDEHAZECOLOR"]), @@ -160,28 +199,101 @@ const TOOLS: &[(&str, &[&str])] = &[ ]; /// Columns this import reads for itself. -const IMPORTED: &[&str] = &["ZEXPOSURE", "ZROTATION", "ZFLIP", "ZCROP", "ZCROPASPECTRATIONAME", "ZWHITEBALANCE"]; - -/// Sliders read one to one: column, the app's group and name, factor onto the app's scale. -const SLIDERS: &[(&str, &str, &str, f64)] = &[ - ("ZCONTRAST", "light", "contrast", 2.0), - ("ZBRIGHTNESS", "light", "brightness", 2.0), - ("ZSATURATION", "color", "saturation", 2.0), - ("ZHIGHLIGHTRECOVERY", "light", "highlights", -1.0), - ("ZSHADOWRECOVERY", "light", "shadows", 1.0), - ("ZWHITERECOVERY", "light", "whites", -1.0), - ("ZBLACKRECOVERY", "light", "blacks", 1.0), - ("ZCLARITY", "effects", "clarity", 1.0), - ("ZCLARITYSTRUCTURE", "effects", "texture", 1.0), +const IMPORTED: &[&str] = &["ZEXPOSURE", "ZROTATION", "ZFLIP", "ZCROP", "ZCROPASPECTRATIONAME", "ZWHITEBALANCE", "ZLEVELSTARGETENABLE"]; + +/// A slider read from one column, with a factor onto the app's scale for each sign. +struct Slider { + column: &'static str, + /// The app's group and name. + group: &'static str, + name: &'static str, + negative: f64, + /// `None`: positive values aren't imported (the report names them as `positive_name`). + positive: Option, + positive_name: &'static str, +} + +/// Sliders imported with a factor, each measured against Capture One's own exports: Brightness has the same effect on +/// twice the range (to 0.2 of an 8-bit level); a negative Highlight is close to the app's own (strong values stay +/// lighter in very bright areas); a negative Shadow needs a little more than the app's (1.2 times), a positive Shadow +/// twice as much (held to the app's 100: Capture One's +100 reaches about twice as far as the app's slider can, and +/// strong lifts stay darker than in Capture One), and Capture One's positive Highlight reaches further than the app's +/// slider can, so it isn't imported. Saturation depends on the file ([`partial_for`]). Contrast, White, Black, Clarity +/// and Structure stay in the report; no guessed factor is applied. +const SLIDERS: &[Slider] = &[ + Slider { column: "ZBRIGHTNESS", group: "light", name: "brightness", negative: 2.0, positive: Some(2.0), positive_name: "" }, + Slider { + column: "ZHIGHLIGHTRECOVERY", + group: "light", + name: "highlights", + negative: 1.0, + positive: None, + positive_name: "Highlight (positive values)", + }, + Slider { column: "ZSHADOWRECOVERY", group: "light", name: "shadows", negative: 1.2, positive: Some(2.0), positive_name: "" }, +]; + +/// What Capture One's Saturation is worth in the app. Negative values go one to one: they desaturate evenly in both +/// (the app doesn't darken the most saturated colours as Capture One does). Capture One's positive Saturation leaves +/// strongly saturated colours alone and lifts the rest, like the app's Vibrance and unlike its Saturation, so on a raw +/// it becomes Vibrance by this table (Capture One's value, the app's Vibrance), linear between the points and from 0 +/// at 0: it comes from the fits of one scene with large near-neutral areas, one with strong colours and a colour chart. +const VIBRANCE_FOR_SATURATION: [(f64, f64); 3] = [(25.0, 45.0), (50.0, 80.0), (100.0, 100.0)]; + +/// The app's Vibrance for a positive Capture One Saturation on a raw ([`VIBRANCE_FOR_SATURATION`]). +pub fn vibrance_for_saturation(saturation: f64) -> f64 { + let s = saturation.clamp(0.0, 100.0); + let mut from = (0.0, 0.0); + for point in VIBRANCE_FOR_SATURATION { + if s <= point.0 { + return from.1 + (point.1 - from.1) * (s - from.0) / (point.0 - from.0); + } + from = point; + } + from.1 +} + +/// An exposure this close to 0 EV (a thousandth, finer than the slider's 0.01 step) is none: Capture One's catalogs +/// hold float noise such as 1e-8 where an exposure was set back to 0. +const EXPOSURE_NEUTRAL: f64 = 1e-3; + +/// A slider this close to 0 (in Capture One's units, where the sliders' step is 1) is none, for the same reason. +const SLIDER_NEUTRAL: f64 = 1e-3; + +/// A Levels value within this of neutral (in Capture One's 0..1 units, finer than the three decimals it stores) is +/// neutral. +const LEVELS_NEUTRAL: f64 = 1e-4; + +/// The columns of the default layer that are always kept: Exposure, Brightness and Levels apply from the camera's +/// defaults too. +const TONE_DEFAULTS: &[&str] = &[ + "ZFILMCURVE", + "ZEXPOSURE", + "ZBRIGHTNESS", + "ZHIGHLIGHTRECOVERY", + "ZSHADOWRECOVERY", + "ZSATURATION", + "ZLEVELSSHADOW", + "ZLEVELSHIGHLIGHT", + "ZMIDTONE", + "ZLEVELSTARGETSHADOW", + "ZLEVELSTARGETHIGHLIGHT", + "ZLEVELSTARGETENABLE", ]; /// Curve columns and the app's channel they become. const CURVES: &[(&str, &str)] = &[("ZGRADATIONCURVE", "master"), ("ZGRADATIONCURVERED", "red"), ("ZGRADATIONCURVEGREEN", "green"), ("ZGRADATIONCURVEBLUE", "blue")]; -/// Levels columns, in the order [`levels_of`] reads them. +/// Levels columns, in the order [`levels_of`] reads them: black, midtone, white, output black, output white. const LEVELS: [&str; 5] = ["ZLEVELSSHADOW", "ZMIDTONE", "ZLEVELSHIGHLIGHT", "ZLEVELSTARGETSHADOW", "ZLEVELSTARGETHIGHLIGHT"]; +/// The value of each [`LEVELS`] column that changes nothing, in Capture One's units (0..1; the midtone signed). +const LEVELS_AT_REST: [f64; 5] = [0.0, 0.0, 1.0, 0.0, 1.0]; + +/// The app's channel of each slot of a Levels value, in the order Capture One stores them. +const LEVELS_SLOTS: [&str; 4] = ["red", "green", "blue", "master"]; + /// A column's tool in the report, or `None` for a column that is never reported. A longer prefix wins /// (`ZLENSLCC…` is LCC, other `ZLENS…` columns lens correction). fn tool_of(column: &str) -> Option<&'static str> { @@ -234,6 +346,8 @@ pub(crate) struct Layers { styles: Vec<(i64, Row)>, default: Row, local: usize, + /// How many of the local adjustment layers have Levels set to something other than neutral. + local_levels: usize, } impl Layers { @@ -251,8 +365,10 @@ impl Layers { self.own(column).filter(|v| self.default(column).is_none_or(|d| !same(v, d))) } - fn number(&self, column: &str) -> Option { - self.changed(column).and_then(Value::as_f64).filter(|v| v.is_finite()) + /// What applies to the variant: the adjustment layer's value, else a style's, else the default layer's (Capture + /// One can save settings as the camera's defaults, so this isn't necessarily neutral). + fn effective(&self, column: &str) -> Option<&Value> { + self.own(column).or_else(|| self.default(column)) } } @@ -282,27 +398,63 @@ pub(crate) fn read_layers(reader: &Reader, entities: &HashMap, canc } else if local.contains(&ent) && row.get("ZENABLED").and_then(Value::as_i64) != Some(0) { let layers = out.entry(variant).or_default(); layers.local = layers.local.saturating_add(1); + if uses_levels(&row) { + layers.local_levels = layers.local_levels.saturating_add(1); + } } Ok(()) })?; for layers in out.values_mut() { layers.styles.sort_by_key(|(index, _)| *index); } - // the default layer: its rotation always (the camera's orientation), the rest where the variant sets something + // the default layer: its rotation always (the camera's orientation), the tone columns that apply from the camera's + // defaults (see [`TONE_DEFAULTS`]), the rest where the variant sets something reader.each_row("ZVARIANTLAYER", false, false, cancel, |row, _| { let (Some(ent), Some(variant)) = (key(&row, "Z_ENT"), key(&row, "ZVARIANT")) else { return Ok(()) }; if !default.contains(&ent) { return Ok(()); } - // (a variant with no adjustment or style layer has nothing to import) - let Some(layers) = out.get_mut(&variant) else { return Ok(()) }; + // (a variant with no adjustment or style layer has nothing to import, unless its camera default sets + // Exposure, Brightness or Levels: Capture One can save those as defaults) + if !out.contains_key(&variant) && !(variant > 0 && default_applies(&row)) { + return Ok(()); + } + let layers = out.entry(variant).or_default(); let used: HashSet = layers.adjustment.keys().chain(layers.styles.iter().flat_map(|(_, s)| s.keys())).cloned().collect(); - layers.default = row.into_iter().filter(|(k, v)| !v.is_null() && (k == "ZROTATION" || used.contains(k))).collect(); + layers.default = + row.into_iter().filter(|(k, v)| !v.is_null() && (k == "ZROTATION" || used.contains(k) || TONE_DEFAULTS.contains(&k.as_str()))).collect(); Ok(()) })?; Ok(out) } +/// Whether an exposure is a setting: finite and more than [`EXPOSURE_NEUTRAL`] from 0. +fn exposure_is_set(e: f64) -> bool { + e.is_finite() && e.abs() > EXPOSURE_NEUTRAL +} + +/// Whether a slider value is a setting: finite and not under [`SLIDER_NEUTRAL`] from 0. +fn slider_is_set(v: f64) -> bool { + v.is_finite() && v.abs() >= SLIDER_NEUTRAL +} + +/// Whether a camera default layer sets an exposure, a slider or Levels that apply to every photo that keeps them. +fn default_applies(row: &Row) -> bool { + let number = |column: &str| row.get(column).and_then(number_of); + row.get("ZFILMCURVE").is_some_and(|v| !v.is_null() && v.as_str().is_none_or(|s| !s.trim().is_empty())) + || number("ZEXPOSURE").is_some_and(exposure_is_set) + || SLIDERS.iter().any(|s| number(s.column).is_some_and(slider_is_set)) + || number("ZSATURATION").is_some_and(slider_is_set) + || uses_levels(row) +} + +/// Whether a layer row has any Levels column set to something other than neutral (read as [`slots_of`] reads it). +fn uses_levels(row: &Row) -> bool { + LEVELS.iter().zip(LEVELS_AT_REST).any(|(column, rest)| { + row.get(*column).and_then(Value::as_str).and_then(numbers).is_some_and(|n| n.iter().any(|v| (v - rest).abs() > LEVELS_NEUTRAL)) + }) +} + /// A crop rectangle that is a crop: finite, positive size. fn crop_of(v: &Value) -> Option<[f64; 4]> { let n = numbers(v.as_str()?)?; @@ -322,7 +474,7 @@ fn gains(v: &Value) -> Option<[f32; 3]> { /// camera database's), else through the white a raw without colour tags has (`lcc_raw::color::as_shot_white_of`). /// Only the change from as shot is applied ([`partial`]), so a raw whose own file carries matrices still gets /// Capture One's change. -fn kelvin(camera: Option<&lcc_camdb::Entry>, gains: [f32; 3]) -> Option<(f64, f64)> { +pub(crate) fn kelvin(camera: Option<&lcc_camdb::Entry>, gains: [f32; 3]) -> Option<(f64, f64)> { let none = lcc_raw::ColorData::default(); let xy = match camera { Some(c) => c.as_shot_white_through(&none, Some(gains))?, @@ -367,60 +519,67 @@ fn curve_of(v: &Value) -> Option> { Some(if points.iter().all(|p| (p[0] - p[1]).abs() < 1e-9) { Vec::new() } else { points }) } -/// One levels value: the same for every channel, or four (`rgb;r;g;b`). -fn channels_of(v: &Value) -> Option<[f64; 4]> { - let n = match v { - Value::String(s) => numbers(s)?, - _ => vec![number_of(v)?], - }; - match n.as_slice() { - [a] => Some([*a; 4]), - [a, b, c, d] => Some([*a, *b, *c, *d]), - _ => None, - } +/// A Levels column's four slots (`red;green;blue;master`), each within `lo..=hi`; `None` when the value isn't four such +/// numbers (a single number, another count, text, NaN, out of range). +fn slots_of(v: &Value, lo: f64, hi: f64) -> Option<[f64; 4]> { + let n = <[f64; 4]>::try_from(numbers(v.as_str()?)?).ok()?; + n.iter().all(|x| (lo..=hi).contains(x)).then_some(n) } -/// The variant's levels by the app's channel; `None` when a set value can't be read. Points given as fractions -/// (all within 0..1) are scaled to 0..255. +/// The variant's Levels by the app's channel, from the effective value of each column ([`Layers::effective`]; a +/// column no layer sets is neutral): `red`, `green`, `blue` and `master`, each as black, midtone, white, output black +/// and output white on the app's scale (0..255, the midtone signed), for the channels that aren't neutral. Output +/// levels count only while `ZLEVELSTARGETENABLE` isn't 0. `None` when a Levels column holds something that isn't four +/// numbers in range (0..1, the midtone −1..1): reported, never guessed. fn levels_of(layers: &Layers) -> Option> { - let mut out = BTreeMap::new(); - if LEVELS.iter().all(|c| layers.changed(c).is_none()) { - return Some(out); - } - // (a column the variant leaves alone is the default layer's, else neutral) - let neutral = [0.0, 0.5, 1.0, 0.0, 1.0]; - let mut v = [[0.0; 4]; 5]; + let outputs = layers.effective("ZLEVELSTARGETENABLE").and_then(Value::as_f64) != Some(0.0); + let mut columns = [[0.0; 4]; 5]; for (i, column) in LEVELS.iter().enumerate() { - let raw = match layers.own(column).or_else(|| layers.default(column)) { - Some(value) => channels_of(value)?, - None => [neutral[i]; 4], - }; - v[i] = if i == 1 { - // the midtone marker: strictly between the points - raw.iter().all(|m| *m > 0.0 && *m < 1.0).then_some(raw)? - } else if raw.iter().all(|x| (0.0..=1.0).contains(x)) { - raw.map(|x| x * 255.0) - } else if raw.iter().all(|x| (0.0..=255.0).contains(x)) { - raw - } else { - return None; + columns[i] = match layers.effective(column) { + Some(v) => slots_of(v, if i == 1 { -1.0 } else { 0.0 }, 1.0)?, + None => [LEVELS_AT_REST[i]; 4], }; } - for (c, name) in ["master", "red", "green", "blue"].iter().enumerate() { - let mut l = lcc_develop::ChannelLevels { black: v[0][c], midtone: 0.0, white: v[2][c], out_black: v[3][c], out_white: v[4][c] }.sanitized(); - l.set_midtone_position(l.black + (l.white - l.black) * v[1][c]); - if !l.is_default() { - out.insert((*name).to_string(), [l.black, l.midtone, l.white, l.out_black, l.out_white]); + let mut out = BTreeMap::new(); + for (slot, name) in LEVELS_SLOTS.iter().enumerate() { + let mut v: [f64; 5] = std::array::from_fn(|i| columns[i][slot]); + if !outputs { + (v[3], v[4]) = (LEVELS_AT_REST[3], LEVELS_AT_REST[4]); + } + if v.iter().zip(LEVELS_AT_REST).any(|(x, rest)| (x - rest).abs() > LEVELS_NEUTRAL) { + // 0..1 of the 0..255 scale (the midtone is the tool's own signed value) + out.insert((*name).to_string(), [v[0] * 255.0, v[1], v[2] * 255.0, v[3] * 255.0, v[4] * 255.0]); } } Some(out) } +/// The stem of the curve file a `ZFILMCURVE` value names: `-Auto.fcrv` is `-Auto`. `Ok(None)` for an +/// empty value or the curve of a rendered file's format (`FileSystemTiff-Auto`: no tone of its own); `Err` for +/// anything that can't name a base curve (not text, control characters, path separators, too long). +fn film_curve_stem(v: &Value) -> Result, ()> { + let Some(text) = v.as_str() else { return Err(()) }; + let name = text.trim(); + if name.is_empty() { + return Ok(None); + } + let stem = match name.len().checked_sub(5).and_then(|at| name.get(at..)) { + Some(ext) if ext.eq_ignore_ascii_case(".fcrv") => &name[..name.len() - 5], + _ => name, + }; + if !lcc_develop::base_curve::is_valid_id(&lcc_develop::base_curve::id_for(stem)) { + return Err(()); + } + Ok((!stem.starts_with("FileSystem")).then(|| stem.to_string())) +} + /// One variant's develop settings, for an image of `size` pixels shot on `camera` (Exif make and model). pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) -> CaptureOneDevelop { let mut d = CaptureOneDevelop { size, ..Default::default() }; let mut not_imported: BTreeMap<&'static str, ()> = BTreeMap::new(); - d.exposure = layers.number("ZEXPOSURE"); + // Exposure, the sliders and the Levels are the effective values, not the change from the default layer: Capture One + // can save them as the camera's defaults + d.exposure = layers.effective("ZEXPOSURE").and_then(number_of).filter(|e| exposure_is_set(*e)); d.camera_rotation = layers.default("ZROTATION").and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); d.rotation = layers.own("ZROTATION").and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e6).unwrap_or(d.camera_rotation); d.flip = layers.changed("ZFLIP").and_then(Value::as_i64).filter(|f| *f != 0); @@ -448,11 +607,45 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) } // the columns brought across: never reported let mut handled: HashSet<&str> = HashSet::new(); - for (column, group, name, factor) in SLIDERS { - if let Some(v) = layers.changed(column).and_then(number_of) { - d.sliders.insert(format!("{group}.{name}"), (v * factor).clamp(-100.0, 100.0)); - handled.insert(column); + for s in SLIDERS { + if let Some(v) = layers.effective(s.column).and_then(number_of) { + if slider_is_set(v) { + match (v < 0.0, s.positive) { + (true, _) => { + d.sliders.insert(format!("{}.{}", s.group, s.name), (v * s.negative).clamp(-100.0, 100.0)); + } + (false, Some(factor)) => { + d.sliders.insert(format!("{}.{}", s.group, s.name), (v * factor).clamp(-100.0, 100.0)); + } + (false, None) => { + not_imported.insert(s.positive_name, ()); + } + } + } + handled.insert(s.column); + } + } + // Saturation: what it becomes depends on the file ([`partial_for`]), so the value is kept as stored + if let Some(v) = layers.effective("ZSATURATION").and_then(number_of) { + d.saturation = Some(v.clamp(-100.0, 100.0)).filter(|v| slider_is_set(*v)); + handled.insert("ZSATURATION"); + } + // the film curve of a raw (its file name is the stem of the base curve file); a rendered file has none, and its + // column stays in the report when the variant changes it + if !camera.1.is_empty() + && let Some(v) = layers.effective("ZFILMCURVE") + { + match film_curve_stem(v) { + Ok(stem) => { + d.film_curve_own = stem.is_some() && layers.changed("ZFILMCURVE").is_some(); + if d.film_curve_own { + d.film_curve_default = layers.default("ZFILMCURVE").and_then(|v| film_curve_stem(v).ok().flatten()); + } + d.film_curve = stem; + } + Err(()) => d.film_curve_unreadable = true, } + handled.insert("ZFILMCURVE"); } for (column, channel) in CURVES { if let Some(points) = layers.changed(column).and_then(curve_of) { @@ -462,10 +655,14 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) handled.insert(column); } } - if let Some(levels) = levels_of(layers) { - d.levels = levels; - handled.extend(LEVELS); + // the Levels columns have lines of their own in the report (values that can't be read, points too close, local + // layers), never a tool's + match levels_of(layers) { + Some(levels) => d.levels = levels, + None => d.levels_unreadable = true, } + handled.extend(LEVELS); + d.levels_too_close = d.levels.values().any(|[black, _, white, ..]| (white - black).abs() < lcc_develop::LEVELS_MIN_GAP); let columns: HashSet<&String> = layers.adjustment.keys().chain(layers.styles.iter().flat_map(|(_, s)| s.keys())).collect(); for column in columns { if let Some(tool) = tool_of(column) @@ -478,6 +675,9 @@ pub(crate) fn develop_of(layers: &Layers, size: [f64; 2], camera: (&str, &str)) if layers.local > 0 { not_imported.insert("Local adjustment layers", ()); } + if layers.local_levels > 0 { + not_imported.insert("Levels (local adjustments)", ()); + } d.not_imported = not_imported.into_keys().map(str::to_string).collect(); d } @@ -488,21 +688,72 @@ impl CaptureOneDevelop { pub fn is_empty(&self) -> bool { self.exposure.is_none() && self.sliders.is_empty() + && self.saturation.is_none() && self.curves.is_empty() && self.levels.is_empty() && self.flip.is_none() && self.crop.is_none() && self.white.is_none() + && self.film_curve.is_none() && (self.rotation - self.camera_rotation).abs() < 1e-9 } } +/// What an exposure of Capture One's counts as on a rendered file (TIFF, JPEG, …): measured against Capture One's own +/// exports, the app's Exposure matches Capture One's when Capture One's value is multiplied by 1.17 (the best factor +/// was 1.14 to 1.21 over the range). A raw's exposure is taken as it is. +pub const RENDERED_EXPOSURE_FACTOR: f64 = 1.17; +/// A rendered file's exposure above this many EV (Capture One's value) is only approximated: Capture One's highlight +/// shoulder isn't reproduced, so the result brightens highlights more than Capture One does. (On a raw the remaining +/// difference is small and isn't reported.) +/// reproduced, so the result brightens highlights more than Capture One does. +pub const EXPOSURE_SHOULDER_EV: f64 = 0.5; + +/// Whether an exposure of Capture One's is above [`EXPOSURE_SHOULDER_EV`]. +pub fn exposure_is_approximate(ev: f64) -> bool { + ev.is_finite() && ev > EXPOSURE_SHOULDER_EV +} + +/// What the report names for a positive Saturation that isn't imported (on a rendered file). +pub const SATURATION_POSITIVE_RENDERED: &str = "Saturation (positive values)"; + +/// Which of a variant's imported settings are only approximate, for the import report's counts. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Approximate { + /// A negative Highlight: close to the app's own, but strong values stay lighter in very bright areas. + pub highlight: bool, + /// A positive Shadow, imported at twice its value (held to the app's range): strong lifts stay darker than in + /// Capture One. + pub shadow: bool, + /// A positive Saturation on a raw, imported as Vibrance. + pub saturation_as_vibrance: bool, + /// A negative Saturation on a rendered file: the most saturated colours don't darken as they do in Capture One. + pub saturation_rendered: bool, +} + +/// What of `d` is approximate on a file that is (`rendered`) or isn't a rendered file ([`partial_for`]). +pub fn approximate(d: &CaptureOneDevelop, rendered: bool) -> Approximate { + Approximate { + highlight: d.sliders.contains_key("light.highlights"), + shadow: d.sliders.get("light.shadows").is_some_and(|v| *v > 0.0), + saturation_as_vibrance: !rendered && d.saturation.is_some_and(|v| v > 0.0), + saturation_rendered: rendered && d.saturation.is_some_and(|v| v < 0.0), + } +} + /// The partial develop settings (the app's names) for `d` on a photo developed for `target`, whose as-shot white /// balance the app read from the file (`as_shot`, Kelvin and tint, when known), with what couldn't be applied. pub fn partial(d: &CaptureOneDevelop, target: crate::crs::Target, as_shot: Option<(f64, f64)>) -> (Value, Vec) { + partial_for(d, target, as_shot, false) +} + +/// [`partial`] for a photo that may be a rendered file (`rendered`: not a raw, so its exposure is converted by +/// [`RENDERED_EXPOSURE_FACTOR`]). +pub fn partial_for(d: &CaptureOneDevelop, target: crate::crs::Target, as_shot: Option<(f64, f64)>, rendered: bool) -> (Value, Vec) { let mut out = serde_json::Map::new(); let mut skipped = d.not_imported.clone(); if let Some(ev) = d.exposure { + let ev = if rendered { ev * RENDERED_EXPOSURE_FACTOR } else { ev }; out.insert("light".into(), json!({"exposure": ev.clamp(-5.0, 5.0)})); } for (key, v) in &d.sliders { @@ -512,6 +763,22 @@ pub fn partial(d: &CaptureOneDevelop, target: crate::crs::Target, as_shot: Optio m.insert(name.to_string(), json!(v)); } } + // Saturation: negative one to one; positive as Vibrance on a raw, and not imported on a rendered file + if let Some(v) = d.saturation.filter(|v| v.is_finite()) { + let mapped = match (v < 0.0, rendered) { + (true, _) => Some(("saturation", v.max(-100.0))), + (false, false) => Some(("vibrance", vibrance_for_saturation(v))), + (false, true) => None, + }; + match mapped { + Some((name, value)) => { + if let Some(m) = group(&mut out, "color") { + m.insert(name.to_string(), json!(value)); + } + } + None => skipped.push(SATURATION_POSITIVE_RENDERED.into()), + } + } for (channel, points) in &d.curves { if !lcc_develop::PointCurves::CHANNELS.contains(&channel.as_str()) || points.len() > lcc_develop::MAX_CURVE_POINTS { continue; diff --git a/crates/engine/src/capture_one_develop_tests.rs b/crates/engine/src/capture_one_develop_tests.rs index 1e776d2c34..00b3f1232b 100644 --- a/crates/engine/src/capture_one_develop_tests.rs +++ b/crates/engine/src/capture_one_develop_tests.rs @@ -24,7 +24,12 @@ fn columns_belong_to_the_tool_with_the_longest_prefix() { assert_eq!(tool_of("ZGRADATIONCURVEY"), Some("Luma curve")); assert_eq!(tool_of("ZGRADATIONCURVERED"), Some("Curve")); assert_eq!(tool_of("ZBWLIGHTTONEHUE"), Some("Black & White")); - assert_eq!(tool_of("ZCLARITYSTRUCTURE"), Some("Clarity")); + assert_eq!(tool_of("ZCLARITYSTRUCTURE"), Some("Structure")); + assert_eq!((tool_of("ZCLARITY"), tool_of("ZCLARITYMETHOD")), (Some("Clarity"), Some("Clarity method"))); + assert_eq!( + ["ZHIGHLIGHTRECOVERY", "ZSHADOWRECOVERY", "ZWHITERECOVERY", "ZBLACKRECOVERY"].map(tool_of), + [Some("Highlight"), Some("Shadow"), Some("White"), Some("Black")] + ); // imported, computed by Capture One, bookkeeping, the ICC profile: never reported for column in ["ZEXPOSURE", "ZCROP", "ZCALCULATEDDEHAZECOLOR", "ZLENSDEFAULTCHROMABR", "ZNAME", "ZICCPROFILE", "ZBRUSHSIZE"] { assert_eq!(tool_of(column), None, "{column}"); @@ -226,23 +231,136 @@ fn applied(d: &CaptureOneDevelop) -> (lcc_develop::DevelopSettings, Vec) (lcc_develop::apply_partial(&lcc_develop::DevelopSettings::default(), &p, 1.0), skipped) } +fn tone_defaults() -> Value { + json!({"ZCONTRAST": 0, "ZBRIGHTNESS": 0, "ZSATURATION": 0, "ZHIGHLIGHTRECOVERY": 0, "ZSHADOWRECOVERY": 0, + "ZWHITERECOVERY": 0, "ZBLACKRECOVERY": 0, "ZCLARITY": 0, "ZCLARITYSTRUCTURE": 0, "ZCLARITYMETHOD": 1}) +} + +/// Brightness, a negative Highlight, Shadow and Saturation have measured scales; the others are reported (no guessed +/// factor): Contrast, White, Black, Clarity, Structure and the positive Highlight. #[test] -fn tone_sliders_and_clarity_come_across_on_the_apps_scale() { +fn measured_sliders_come_across_on_the_apps_scale_and_the_others_are_reported() { let l = layers( - json!({"ZCONTRAST": 20, "ZBRIGHTNESS": "-10", "ZSATURATION": 15, "ZHIGHLIGHTRECOVERY": 60, "ZSHADOWRECOVERY": 40, - "ZCLARITY": 30, "ZCLARITYSTRUCTURE": -25, "ZCLARITYMETHOD": 2}), - json!({"ZCONTRAST": 0, "ZBRIGHTNESS": 0, "ZSATURATION": 0, "ZHIGHLIGHTRECOVERY": 0, "ZSHADOWRECOVERY": 0, - "ZCLARITY": 0, "ZCLARITYSTRUCTURE": 0, "ZCLARITYMETHOD": 1}), + json!({"ZCONTRAST": 20, "ZBRIGHTNESS": "-10", "ZSATURATION": 15, "ZHIGHLIGHTRECOVERY": -60, "ZSHADOWRECOVERY": -40, + "ZWHITERECOVERY": -10, "ZBLACKRECOVERY": 10, "ZCLARITY": 30, "ZCLARITYSTRUCTURE": -25, "ZCLARITYMETHOD": 2}), + tone_defaults(), ); let d = develop_of(&l, [6000.0, 4000.0], ("", "")); - assert_eq!(d.not_imported, vec!["Clarity method"], "only the method has no equivalent"); + assert_eq!(d.not_imported, vec!["Black", "Clarity", "Clarity method", "Contrast", "Structure", "White"]); + assert_eq!(d.sliders.keys().collect::>(), ["light.brightness", "light.highlights", "light.shadows"]); + assert_eq!(d.saturation, Some(15.0)); assert!(!d.is_empty()); let (s, skipped) = applied(&d); - assert_eq!(skipped, vec!["Clarity method"]); - assert_eq!((s.light.contrast, s.light.brightness), (40.0, -20.0), "Capture One's ±50 doubled"); - assert_eq!(s.color.saturation, 30.0); - assert!(s.light.highlights < 0.0 && s.light.shadows > 0.0, "recovery pulls highlights down and lifts shadows"); - assert_eq!((s.effects.clarity, s.effects.texture), (30.0, -25.0)); + assert_eq!(skipped, d.not_imported); + assert_eq!(s.light.brightness, -20.0, "Capture One's ±50 doubled; a number written as text is read"); + assert_eq!(s.light.highlights, -60.0, "a negative Highlight is taken as it is"); + assert_eq!(s.light.shadows, -48.0, "a negative Shadow needs a fifth more"); + assert_eq!((s.color.saturation, s.color.vibrance), (0.0, 27.0), "a positive Saturation on a raw becomes Vibrance by the table"); + // nothing else moved: the unmeasured sliders have no factor + let others = (s.light.contrast, s.light.whites, s.light.blacks, s.effects.clarity, s.effects.texture); + assert_eq!(others, (0.0, 0.0, 0.0, 0.0, 0.0)); +} + +/// A negative Highlight is imported one to one, a negative Shadow 1.2 times and a positive Shadow twice (held to the +/// range: at 50 and up); a positive Highlight reaches further in Capture One than the app's slider can and is +/// reported, whatever the file. +#[test] +fn highlight_and_shadow_are_imported_by_sign() { + let cases = [ + // (Highlight, Shadow) -> (app Highlights, app Shadows) + ((-100.0, -100.0), (Some(-100.0), Some(-100.0))), + ((-50.0, -25.0), (Some(-50.0), Some(-30.0))), + ((-1.0, -90.0), (Some(-1.0), Some(-100.0))), + ((60.0, 10.0), (None, Some(20.0))), + ((87.0, 25.0), (None, Some(50.0))), + ((30.0, 49.0), (None, Some(98.0))), + ((30.0, 50.0), (None, Some(100.0))), + ((30.0, 51.0), (None, Some(100.0))), + ((30.0, 100.0), (None, Some(100.0))), + ]; + for ((highlight, shadow), (want_h, want_s)) in cases { + let l = layers(json!({"ZHIGHLIGHTRECOVERY": highlight, "ZSHADOWRECOVERY": shadow}), tone_defaults()); + let d = develop_of(&l, [6000.0, 4000.0], ("EXAMPLE CORP", "EXAMPLE X1")); + for rendered in [false, true] { + let (p, skipped) = partial_for(&d, crate::crs::Target::RawAbsolute, None, rendered); + let got = |name: &str| p["light"].get(name).and_then(Value::as_f64); + assert_eq!((got("highlights"), got("shadows")), (want_h, want_s), "{highlight}/{shadow} rendered {rendered}"); + let mut expected = Vec::new(); + if want_h.is_none() { + expected.push("Highlight (positive values)"); + } + if want_s.is_none() { + expected.push("Shadow (positive values)"); + } + assert_eq!(skipped, expected, "{highlight}/{shadow}"); + } + assert_eq!((approximate(&d, false).highlight, approximate(&d, true).highlight), (want_h.is_some(), want_h.is_some())); + assert_eq!(approximate(&d, false).shadow, shadow > 0.0, "{shadow}"); + } + // a sign change at zero: a tiny value is no setting + let l = layers(json!({"ZHIGHLIGHTRECOVERY": 0.0005, "ZSHADOWRECOVERY": -0.0005}), tone_defaults()); + assert!(develop_of(&l, [6000.0, 4000.0], ("", "")).is_empty()); +} + +/// Capture One's positive Saturation is the app's Vibrance on a raw (a table through the fits, linear between its +/// points and from 0 at 0) and nothing on a rendered file; its negative Saturation is the app's, one to one. +#[test] +fn saturation_is_imported_by_sign_and_file() { + // the table: its points, between them, at the ends + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + for (saturation, vibrance) in [(0.0, 0.0), (12.5, 22.5), (25.0, 45.0), (37.5, 62.5), (50.0, 80.0), (75.0, 90.0), (100.0, 100.0), (150.0, 100.0)] { + assert!(near(vibrance_for_saturation(saturation), vibrance), "{saturation}"); + } + let table: Vec = (0..=100).map(|s| vibrance_for_saturation(f64::from(s))).collect(); + assert!(table.windows(2).all(|w| w[1] > w[0] || (w[1] == 100.0 && w[0] == 100.0)), "monotone"); + for (stored, raw, rendered) in [ + (-100.0, (Some(("saturation", -100.0)), vec![]), (Some(("saturation", -100.0)), vec![])), + (-50.0, (Some(("saturation", -50.0)), vec![]), (Some(("saturation", -50.0)), vec![])), + (25.0, (Some(("vibrance", 45.0)), vec![]), (None, vec!["Saturation (positive values)"])), + (50.0, (Some(("vibrance", 80.0)), vec![]), (None, vec!["Saturation (positive values)"])), + (100.0, (Some(("vibrance", 100.0)), vec![]), (None, vec!["Saturation (positive values)"])), + ] { + let l = layers(json!({"ZSATURATION": stored}), tone_defaults()); + let d = develop_of(&l, [6000.0, 4000.0], ("", "")); + assert_eq!(d.saturation, Some(stored)); + assert!(d.not_imported.is_empty(), "the file decides, not the reader: {d:?}"); + for (rendered_file, (want, want_skipped)) in [(false, &raw), (true, &rendered)] { + let (p, skipped) = partial_for(&d, crate::crs::Target::RawAbsolute, None, rendered_file); + let color = p.get("color").and_then(Value::as_object); + match want { + Some((name, value)) => { + let m = color.expect("a colour group"); + assert_eq!(m.len(), 1, "only the one slider: {p}"); + assert!(near(m[*name].as_f64().unwrap(), *value), "{stored} rendered {rendered_file}: {p}"); + } + None => assert!(color.is_none(), "nothing for a positive Saturation on a rendered file: {p}"), + } + assert_eq!(skipped, *want_skipped, "{stored} rendered {rendered_file}"); + } + } + // what is approximate: positive on a raw (as Vibrance), negative on a rendered file + let at = |v: f64, rendered: bool| { + let d = develop_of(&layers(json!({"ZSATURATION": v}), tone_defaults()), [6000.0, 4000.0], ("", "")); + let a = approximate(&d, rendered); + (a.saturation_as_vibrance, a.saturation_rendered) + }; + assert_eq!((at(30.0, false), at(30.0, true)), ((true, false), (false, false))); + assert_eq!((at(-30.0, false), at(-30.0, true)), ((false, false), (false, true))); +} + +/// Capture One can save these sliders as the camera's defaults: the effective value applies, as for Brightness. +#[test] +fn highlight_shadow_and_saturation_defaults_of_the_camera_apply() { + let l = layers(json!({}), json!({"ZHIGHLIGHTRECOVERY": -30, "ZSHADOWRECOVERY": -20, "ZSATURATION": -10})); + let d = develop_of(&l, [6000.0, 4000.0], ("", "")); + let (p, _) = partial_for(&d, crate::crs::Target::RawAbsolute, None, false); + assert_eq!( + (p["light"]["highlights"].as_f64(), p["light"]["shadows"].as_f64(), p["color"]["saturation"].as_f64()), + (Some(-30.0), Some(-24.0), Some(-10.0)) + ); + assert!(default_applies(&row(json!({"ZHIGHLIGHTRECOVERY": -30}))) && default_applies(&row(json!({"ZSHADOWRECOVERY": 5})))); + assert!(default_applies(&row(json!({"ZSATURATION": 7})))); + assert!(!default_applies(&row(json!({"ZHIGHLIGHTRECOVERY": 0, "ZSHADOWRECOVERY": 0, "ZSATURATION": 0, "ZCONTRAST": 20})))); } #[test] @@ -262,20 +380,22 @@ fn curves_become_point_curves() { assert!(lcc_develop::ToneCurve::point_curve_is_identity(&s.curve.blue), "a straight line changes nothing"); } +/// Capture One writes four slots, `red;green;blue;master` (the master edit of a catalog is `0.000;0.000;0.000;0.078`), +/// and the midtone as the tool's own signed value (0 neutral; the default layer holds `0.000;0.000;0.000;0.000`). #[test] -fn levels_per_channel() { +fn levels_per_channel_in_the_stored_slot_order() { let l = layers( - json!({"ZLEVELSSHADOW": "0.1;0;0.2;0", "ZLEVELSHIGHLIGHT": "0.9", "ZMIDTONE": "0.4;0.5;0.5;0.5", "ZLEVELSTARGETHIGHLIGHT": 250}), - json!({"ZLEVELSSHADOW": "0;0;0;0", "ZLEVELSHIGHLIGHT": "1;1;1;1", "ZMIDTONE": "0.5;0.5;0.5;0.5", "ZLEVELSTARGETSHADOW": "0", "ZLEVELSTARGETHIGHLIGHT": 255}), + json!({"ZLEVELSSHADOW": "0.1;0;0.2;0", "ZLEVELSHIGHLIGHT": "1;0.9;1;0.8", "ZMIDTONE": "0;0;0;0.4", "ZLEVELSTARGETHIGHLIGHT": "1;1;1;0.98"}), + levels_neutral(), ); let d = develop_of(&l, [6000.0, 4000.0], ("", "")); - assert!(d.not_imported.is_empty(), "{:?}", d.not_imported); + assert!(d.not_imported.is_empty() && !d.levels_unreadable && !d.levels_too_close, "{d:?}"); let (s, _) = applied(&d); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + assert!(near(s.levels.red.black, 25.5) && near(s.levels.blue.black, 51.0) && s.levels.green.black == 0.0); + assert!(near(s.levels.green.white, 229.5) && s.levels.red.white == 255.0); let m = s.levels.master; - assert!((m.black - 25.5).abs() < 1e-6 && (m.white - 229.5).abs() < 1e-6 && (m.out_white - 250.0).abs() < 1e-6, "{m:?}"); - assert!(m.midtone > 0.0, "a marker nearer black brightens the midtones"); - assert!((s.levels.green.black - 51.0).abs() < 1e-6); - assert_eq!(s.levels.red.black, 0.0); + assert!(m.black == 0.0 && near(m.white, 204.0) && m.midtone == 0.4 && near(m.out_white, 249.9), "{m:?}"); assert_eq!(s.levels.red.midtone, 0.0); } @@ -290,13 +410,8 @@ fn unreadable_tool_values_are_reported() { ("ZGRADATIONCURVE", json!("nan,0;1,1"), "Curve"), ("ZGRADATIONCURVE", json!(format!("0,0;{}1,1", "0.5,0.5;".repeat(400))), "Curve"), ("ZGRADATIONCURVE", json!(12), "Curve"), - ("ZLEVELSSHADOW", json!("0.1;0.2"), "Levels"), - ("ZLEVELSSHADOW", json!("300"), "Levels"), - ("ZLEVELSSHADOW", json!("-0.5"), "Levels"), - ("ZMIDTONE", json!("1.5"), "Levels"), - ("ZMIDTONE", json!("0"), "Levels"), - ("ZLEVELSHIGHLIGHT", json!({"a": 1}), "Levels"), ("ZCONTRAST", json!("lots"), "Contrast"), + ("ZBRIGHTNESS", json!("lots"), "Brightness"), ("ZCLARITY", json!("1e999"), "Clarity"), ]; for (column, value, tool) in cases { @@ -306,6 +421,33 @@ fn unreadable_tool_values_are_reported() { assert!(d.curves.is_empty() && d.levels.is_empty() && d.sliders.is_empty(), "{column} = {value}"); let _ = applied(&d); } + // Levels: four numbers in range (0..1, the midtone -1..1), or the variant's Levels have a line of their own in the + // report ("values could not be read") and nothing is set + let levels: &[(&str, Value)] = &[ + ("ZLEVELSSHADOW", json!("0.1;0.2")), + ("ZLEVELSSHADOW", json!("0.1;0.2;0.3")), + ("ZLEVELSSHADOW", json!("0;0;0;0;0")), + ("ZLEVELSSHADOW", json!("300")), + ("ZLEVELSSHADOW", json!("-0.5")), + ("ZLEVELSSHADOW", json!("0;0;0;1.5")), + ("ZLEVELSSHADOW", json!("0;0;0;-0.1")), + ("ZMIDTONE", json!("1.5")), + ("ZMIDTONE", json!("0")), + ("ZMIDTONE", json!("0;0;0;1.5")), + ("ZMIDTONE", json!("0;0;0;-1.5")), + ("ZLEVELSHIGHLIGHT", json!({"a": 1})), + ("ZLEVELSHIGHLIGHT", json!("0;0;0;nan")), + ("ZLEVELSHIGHLIGHT", json!(0.5)), + ]; + for (column, value) in levels { + let d = develop_of(&layers(json!({ *column: value }), levels_neutral()), [6000.0, 4000.0], ("", "")); + assert!(d.levels_unreadable && d.levels.is_empty() && d.not_imported.is_empty(), "{column} = {value}: {d:?}"); + let _ = applied(&d); + } + // an unreadable camera default is the same + let mut bad = levels_neutral(); + bad["ZMIDTONE"] = json!("0;0;0"); + assert!(develop_of(&layers(json!({"ZEXPOSURE": 0.5}), bad), [6000.0, 4000.0], ("", "")).levels_unreadable); // an archive with values out of range still applies within range let d = CaptureOneDevelop { sliders: [("light.contrast".to_string(), 1e9), ("nogroup".to_string(), 1.0)].into_iter().collect(), @@ -317,3 +459,419 @@ fn unreadable_tool_values_are_reported() { assert_eq!(s.light.contrast, 100.0); assert!(s.levels.master.white <= 255.0 && s.levels.master.midtone <= 1.0); } + +/// What the camera's default layer holds for Exposure, Brightness and Levels when nothing is saved there: neutral. +fn levels_neutral() -> Value { + json!({"ZEXPOSURE": 0, "ZBRIGHTNESS": 0, "ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", + "ZMIDTONE": "0.000;0.000;0.000;0.000", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.000", + "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZLEVELSTARGETENABLE": 1}) +} + +fn develop(adjustment: Value) -> CaptureOneDevelop { + develop_of(&layers(adjustment, levels_neutral()), [6000.0, 4000.0], ("", "")) +} + +fn develop_over(adjustment: Value, default: Value) -> CaptureOneDevelop { + develop_of(&layers(adjustment, default), [6000.0, 4000.0], ("", "")) +} + +fn brightness_of(d: &CaptureOneDevelop) -> Option { + d.sliders.get("light.brightness").copied() +} + +fn channel(d: &CaptureOneDevelop, name: &str) -> Option<[f64; 5]> { + d.levels.get(name).copied() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +/// A camera default that isn't neutral (Capture One can save Brightness and Levels as defaults). +fn saved_default() -> Value { + let mut d = levels_neutral(); + d["ZBRIGHTNESS"] = json!(10); + d["ZLEVELSHIGHLIGHT"] = json!("1.000;1.000;1.000;0.800"); + d["ZMIDTONE"] = json!("0.000;0.000;0.000;0.250"); + d +} + +#[test] +fn brightness_doubles_without_rounding() { + // fractions are common in the catalog: no rounding on the way + let b = |v: Value| brightness_of(&develop(json!({"ZBRIGHTNESS": v}))); + assert_eq!(b(json!(12.345)).map(|x| (x * 1e9).round() / 1e9), Some(24.69)); + assert_eq!(b(json!(23)), Some(46.0)); + assert_eq!(b(json!(-0.25)), Some(-0.5)); + // the ends of Capture One's range are the ends of the app's; beyond them (hostile or damaged) it is held there + assert_eq!((b(json!(50)), b(json!(-50))), (Some(100.0), Some(-100.0))); + assert_eq!((b(json!(75)), b(json!(-1.0e12))), (Some(100.0), Some(-100.0))); + // it lands in the settings + let (p, _) = partial(&develop(json!({"ZBRIGHTNESS": 10})), crate::crs::Target::RawAbsolute, None); + assert_eq!(p["light"], json!({"brightness": 20.0})); +} + +#[test] +fn brightness_at_its_default_or_within_noise_of_it_is_nothing() { + for own in [json!(0), json!(0.0), json!(null)] { + let d = develop(json!({"ZBRIGHTNESS": own})); + assert!(d.sliders.is_empty() && d.is_empty() && d.not_imported.is_empty()); + } + // float noise left by a reset, as the photo's own value and as a camera default; from a thousandth on it is a setting + for tiny in [9.0e-9, -2.0e-8, 0.0005, -0.00099] { + let d = develop(json!({"ZBRIGHTNESS": tiny})); + assert!(d.sliders.is_empty() && d.is_empty(), "{tiny}"); + let kept = develop_over(json!({}), json!({"ZBRIGHTNESS": tiny})); + assert!(kept.sliders.is_empty() && kept.is_empty(), "{tiny} as a default"); + } + assert_eq!(brightness_of(&develop(json!({"ZBRIGHTNESS": 0.001}))), Some(0.002)); + // a value that isn't a number is reported, not guessed + let bad = develop(json!({"ZBRIGHTNESS": "not a number"})); + assert!(bad.sliders.is_empty() && bad.not_imported == ["Brightness"]); +} + +#[test] +fn the_master_slot_scales_to_the_0_to_255_scale() { + let d = develop( + json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.200", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800", "ZMIDTONE": "0.000;0.000;0.000;0.250"}), + ); + assert!(d.not_imported.is_empty() && !d.is_empty() && !d.levels_too_close && !d.levels_unreadable); + // the colour channels are untouched, and not written + assert_eq!(d.levels.keys().collect::>(), ["master"]); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 51.0) && near(m[1], 0.25) && near(m[2], 204.0) && near(m[3], 0.0) && near(m[4], 255.0), "{m:?}"); + let (p, _) = partial(&d, crate::crs::Target::RawAbsolute, None); + assert_eq!(p["levels"].as_object().unwrap().keys().collect::>(), ["master"]); +} + +#[test] +fn output_levels_scale_like_the_input_points() { + let d = develop(json!({"ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.100", "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;0.900"})); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 0.0) && near(m[2], 255.0) && near(m[3], 25.5) && near(m[4], 229.5), "{m:?}"); +} + +#[test] +fn inverted_points_and_output_levels_are_kept_as_they_are() { + // black above white, and output black above output white: nothing is swapped, clamped or refused + let d = develop(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.750", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.250", + "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.800", "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;0.200"})); + assert!(!d.levels_too_close); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 191.25) && near(m[2], 63.75) && near(m[3], 204.0) && near(m[4], 51.0), "{m:?}"); + // through the app's own settings too + let (s, _) = applied(&d); + assert!(s.levels.master.black > s.levels.master.white && s.levels.master.out_black > s.levels.master.out_white); +} + +#[test] +fn the_midtone_goes_across_signed_and_unchanged() { + for m in [-1.0, -0.5, -0.125, 0.0625, 0.5, 1.0] { + let d = develop(json!({"ZMIDTONE": format!("0.000;0.000;0.000;{m:.4}")})); + assert_eq!(channel(&d, "master").unwrap()[1], m, "{m}"); + } +} + +/// Inverted points, a midtone and enabled output levels in one master edit, as the Levels tool stores them: nothing is +/// dropped, swapped or rounded, in the stored slot order. +#[test] +fn inverted_points_a_midtone_and_output_levels_are_all_kept_together() { + let d = develop(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.843", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.157", + "ZMIDTONE": "0.000;0.000;0.000;0.300", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.118", + "ZLEVELSTARGETHIGHLIGHT": "1.000;1.000;1.000;0.863", "ZLEVELSTARGETENABLE": 1})); + assert_eq!(d.levels.keys().collect::>(), ["master"]); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 214.965) && near(m[1], 0.3) && near(m[2], 40.035) && near(m[3], 30.09) && near(m[4], 220.065), "{m:?}"); + let (s, _) = applied(&d); + let l = s.levels.master; + assert!(l.black > l.white && l.out_black < l.out_white && (l.midtone - 0.3).abs() < 1e-9, "{l:?}"); +} +#[test] +fn a_column_the_variant_does_not_set_keeps_the_defaults() { + // only the white point is set: black, midtone and the outputs stay neutral + let m = channel(&develop(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.500"})), "master").unwrap(); + assert!(near(m[0], 0.0) && near(m[1], 0.0) && near(m[2], 127.5) && near(m[3], 0.0) && near(m[4], 255.0), "{m:?}"); + // a column set to its default value is no change + let none = develop(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZMIDTONE": "0.0;0.0;0.0;0.0", "ZLEVELSTARGETENABLE": 1})); + assert!(none.levels.is_empty() && none.is_empty()); +} + +#[test] +fn the_adjustment_layer_wins_over_a_style_and_a_style_counts_alone() { + let mut l = layers(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}), levels_neutral()); + l.styles = vec![(1, row(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.900", "ZLEVELSSHADOW": "0.000;0.000;0.000;0.100"})))]; + let m = channel(&develop_of(&l, [6000.0, 4000.0], ("", "")), "master").unwrap(); + assert!(near(m[2], 204.0) && near(m[0], 25.5), "the white point is the adjustment layer's, the black point the style's: {m:?}"); + let style_only = Layers { styles: l.styles.clone(), default: row(levels_neutral()), ..Default::default() }; + assert!(near(channel(&develop_of(&style_only, [6000.0, 4000.0], ("", "")), "master").unwrap()[2], 229.5)); +} + +#[test] +fn output_levels_count_only_while_they_are_enabled() { + let own = json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.100", "ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.500", "ZLEVELSTARGETENABLE": 0}); + let m = channel(&develop(own), "master").unwrap(); + assert!(near(m[0], 25.5) && near(m[3], 0.0) && near(m[4], 255.0), "{m:?}"); + // disabled outputs alone are no change + assert!(develop(json!({"ZLEVELSTARGETSHADOW": "0.000;0.000;0.000;0.500", "ZLEVELSTARGETENABLE": 0})).is_empty()); +} + +#[test] +fn points_closer_than_the_levels_tool_allows_are_flagged() { + let gap = |black: f64, white: f64| { + develop(json!({"ZLEVELSSHADOW": format!("0;0;0;{black}"), "ZLEVELSHIGHLIGHT": format!("1;1;1;{white}")})).levels_too_close + }; + assert!(gap(0.5, 0.5), "equal points"); + assert!(gap(0.5, 0.504), "1 level apart"); + assert!(gap(0.504, 0.5), "1 level apart, inverted"); + assert!(!gap(0.5, 0.51), "2.55 levels apart"); + assert!(!gap(0.75, 0.25), "inverted but wide"); + assert!(!gap(0.0, 1.0)); + // and the Levels settings keep the distance they need + let (s, _) = applied(&develop(json!({"ZLEVELSSHADOW": "0;0;0;0.5", "ZLEVELSHIGHLIGHT": "1;1;1;0.5"}))); + assert!((s.levels.master.white - s.levels.master.black).abs() >= lcc_develop::LEVELS_MIN_GAP); +} + +#[test] +fn local_levels_are_found_by_comparing_with_neutral() { + assert!(!uses_levels(&row(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.000", "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000"})))); + assert!(!uses_levels(&row(json!({"ZLEVELSSHADOW": null, "ZMIDTONE": null}))), "NULL is not a setting"); + assert!(!uses_levels(&row(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.99995"}))), "within a ten-thousandth"); + assert!(!uses_levels(&row(json!({"ZEXPOSURE": 1.0, "ZBRIGHTNESS": 25}))), "other settings are not Levels"); + assert!(uses_levels(&row(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.9998"}))), "beyond a ten-thousandth"); + assert!(uses_levels(&row(json!({"ZLEVELSSHADOW": "0.1;0;0;0"}))), "a colour channel counts"); + assert!(uses_levels(&row(json!({"ZMIDTONE": "0;0;0;-0.25"})))); + assert!(uses_levels(&row(json!({"ZLEVELSTARGETHIGHLIGHT": "1;1;1;0.5"}))), "output levels count"); + // the variant is told: the specific line next to the generic one, and its global Levels still go across + let mut l = layers(json!({"ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;0.800"}), levels_neutral()); + l.local = 2; + l.local_levels = 1; + let d = develop_of(&l, [6000.0, 4000.0], ("", "")); + assert_eq!(d.not_imported, vec!["Levels (local adjustments)", "Local adjustment layers"]); + assert!(near(channel(&d, "master").unwrap()[2], 204.0)); + // local layers without Levels: only the generic line + l.local_levels = 0; + assert_eq!(develop_of(&l, [6000.0, 4000.0], ("", "")).not_imported, vec!["Local adjustment layers"]); +} + +#[test] +fn levels_within_a_ten_thousandth_of_neutral_are_none() { + // every column a little off neutral by float noise: no channel is written, as own values and as defaults + let noise = |scale: f64| { + json!({"ZLEVELSSHADOW": format!("{0};{0};{0};{0}", 0.00005 * scale), "ZLEVELSHIGHLIGHT": format!("{0};{0};{0};{0}", 1.0 - 0.00005 * scale), + "ZMIDTONE": format!("{0};{0};{0};{0}", -0.00005 * scale), "ZLEVELSTARGETSHADOW": format!("{0};{0};{0};{0}", 0.00005 * scale), + "ZLEVELSTARGETHIGHLIGHT": format!("{0};{0};{0};{0}", 1.0 - 0.00005 * scale)}) + }; + let own = develop_over(noise(1.0), levels_neutral()); + assert!(own.levels.is_empty() && own.is_empty() && !own.levels_too_close); + assert!(develop_over(json!({"ZEXPOSURE": 0.5}), noise(1.0)).levels.is_empty()); + // beyond it (0.0002 on every value) each channel is written + assert_eq!(develop_over(noise(4.0), levels_neutral()).levels.len(), 4); + // one value beyond it is enough, and only its channel is written + let one = develop(json!({"ZMIDTONE": "0;0;0.0002;0"})); + assert_eq!(one.levels.keys().collect::>(), ["blue"]); + // the closeness check is unaffected: points 1 level apart are flagged however the other values look + assert!(develop(json!({"ZLEVELSSHADOW": "0;0;0;0.5", "ZLEVELSHIGHLIGHT": "1;1;1;0.504"})).levels_too_close); +} + +#[test] +fn a_default_that_is_not_neutral_applies_to_a_photo_that_keeps_it() { + // no adjustment layer values of its own: the default is what the photo has + let d = develop_over(json!({"ZEXPOSURE": 0.5}), saved_default()); + assert_eq!(brightness_of(&d), Some(20.0)); + let m = channel(&d, "master").unwrap(); + assert!(near(m[0], 0.0) && near(m[1], 0.25) && near(m[2], 204.0), "{m:?}"); + // a style that sets one column leaves the others to the default; so does an adjustment + let mut l = layers(json!({}), saved_default()); + l.styles = vec![(1, row(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.100"})))]; + let m = channel(&develop_of(&l, [6000.0, 4000.0], ("", "")), "master").unwrap(); + assert!(near(m[0], 25.5) && near(m[1], 0.25) && near(m[2], 204.0), "{m:?}"); + let m = channel(&develop_over(json!({"ZLEVELSSHADOW": "0.000;0.000;0.000;0.100"}), saved_default()), "master").unwrap(); + assert!(near(m[0], 25.5) && near(m[1], 0.25) && near(m[2], 204.0), "{m:?}"); +} + +#[test] +fn an_adjustment_that_resets_to_neutral_over_a_non_neutral_default_writes_nothing() { + let d = develop_over( + json!({"ZBRIGHTNESS": 0, "ZLEVELSHIGHLIGHT": "1.000;1.000;1.000;1.000", "ZMIDTONE": "0.000;0.000;0.000;0.000"}), + saved_default(), + ); + assert!(d.sliders.is_empty() && d.levels.is_empty() && d.is_empty() && d.not_imported.is_empty()); + let (p, _) = partial(&d, crate::crs::Target::RawAbsolute, None); + assert!(p.get("light").is_none() && p.get("levels").is_none(), "{p}"); +} + +#[test] +fn the_closeness_check_runs_on_the_effective_points() { + // a default whose points are 1 level apart, kept by the photo + let mut close = levels_neutral(); + close["ZLEVELSSHADOW"] = json!("0;0;0;0.5"); + close["ZLEVELSHIGHLIGHT"] = json!("1;1;1;0.504"); + assert!(develop_over(json!({"ZEXPOSURE": 0.5}), close.clone()).levels_too_close); + // the photo moves them apart: the default's no longer counts + assert!(!develop_over(json!({"ZLEVELSHIGHLIGHT": "1;1;1;0.9"}), close.clone()).levels_too_close); + // or resets them to neutral + let reset = develop_over(json!({"ZLEVELSSHADOW": "0;0;0;0", "ZLEVELSHIGHLIGHT": "1;1;1;1"}), close); + assert!(!reset.levels_too_close && reset.levels.is_empty()); +} + +#[test] +fn a_camera_default_layer_applies_when_it_sets_something() { + assert!(default_applies(&row(json!({"ZEXPOSURE": 0.5})))); + assert!(default_applies(&row(json!({"ZBRIGHTNESS": "-3"})))); + assert!(default_applies(&row(json!({"ZLEVELSHIGHLIGHT": "1;1;1;0.9"})))); + assert!(!default_applies(&row(levels_neutral()))); + assert!(!default_applies(&row(json!({"ZEXPOSURE": 1e-8, "ZBRIGHTNESS": 0.0004, "ZLEVELSSHADOW": "0;0;0;0.00005"}))), "noise is not a setting"); +} + +#[test] +fn an_archive_from_before_the_levels_flags_still_reads() { + let old = json!({"exposure": 0.5, "rotation": 0.0, "camera_rotation": 0.0, "size": [6000.0, 4000.0]}); + let d: CaptureOneDevelop = serde_json::from_value(old).unwrap(); + assert!(!d.levels_too_close && !d.levels_unreadable && d.levels.is_empty()); + // and the new fields survive the archive + let new = develop(json!({"ZLEVELSHIGHLIGHT": "1;1;1;0.8", "ZLEVELSSHADOW": "0;0;0;0.5", "ZBRIGHTNESS": 5})); + let back: CaptureOneDevelop = serde_json::from_value(serde_json::to_value(&new).unwrap()).unwrap(); + assert_eq!(back, new); + let unreadable = develop(json!({"ZLEVELSSHADOW": "1;2"})); + assert!(unreadable.levels_unreadable); + let back: CaptureOneDevelop = serde_json::from_value(serde_json::to_value(&unreadable).unwrap()).unwrap(); + assert!(back.levels_unreadable); +} + +#[test] +fn a_default_exposure_applies_to_a_photo_that_keeps_it() { + // Capture One can save an exposure as the camera's default: a photo with no exposure of its own has it + let d = develop_over(json!({"ZBRIGHTNESS": 5}), json!({"ZEXPOSURE": 0.5, "ZBRIGHTNESS": 0})); + assert_eq!(d.exposure, Some(0.5)); + assert_eq!(partial(&d, crate::crs::Target::RawAbsolute, None).0["light"]["exposure"], json!(0.5)); + // a style supplies it where the adjustment layer doesn't + let mut l = layers(json!({}), json!({"ZEXPOSURE": 0.5})); + l.styles = vec![(1, row(json!({"ZEXPOSURE": -1.0})))]; + assert_eq!(develop_of(&l, [6000.0, 4000.0], ("", "")).exposure, Some(-1.0)); + // and the photo's own value wins over the default + assert_eq!(develop_over(json!({"ZEXPOSURE": 1.25}), json!({"ZEXPOSURE": 0.5})).exposure, Some(1.25)); + // a default alone is a variant with something to import + let alone = develop_over(json!({}), json!({"ZEXPOSURE": 0.75})); + assert!(!alone.is_empty() && alone.exposure == Some(0.75)); +} + +#[test] +fn an_exposure_reset_to_zero_over_a_non_zero_default_writes_nothing() { + let d = develop_over(json!({"ZEXPOSURE": 0}), json!({"ZEXPOSURE": 0.5})); + assert_eq!(d.exposure, None); + assert!(d.is_empty() && d.not_imported.is_empty()); + let (p, _) = partial(&d, crate::crs::Target::RawAbsolute, None); + assert!(p.get("light").is_none(), "{p}"); + assert_eq!(develop_over(json!({"ZEXPOSURE": 0.0}), json!({"ZEXPOSURE": 0})).exposure, None); +} + +#[test] +fn exposure_values_are_held_to_the_apps_range_and_unreadable_ones_are_nothing() { + let ev = |v: Value| { + partial(&develop_over(json!({"ZEXPOSURE": v}), json!({"ZEXPOSURE": 0})), crate::crs::Target::RawAbsolute, None).0["light"]["exposure"] + .as_f64() + }; + assert_eq!((ev(json!(0.125)), ev(json!(-5))), (Some(0.125), Some(-5.0))); + assert_eq!((ev(json!(1.0e9)), ev(json!(-1.0e9))), (Some(5.0), Some(-5.0))); + for bad in [json!("x"), json!("1;2"), json!(null)] { + assert_eq!(develop_over(json!({"ZEXPOSURE": bad.clone()}), json!({"ZEXPOSURE": 0})).exposure, None, "{bad}"); + } +} + +#[test] +fn an_exposure_within_a_thousandth_of_zero_is_none() { + // float noise where an exposure was set back to 0, as a default and as a value of the photo's own + for tiny in [9.0e-9, -2.0e-8, 0.0005, -0.001] { + let d = develop_over(json!({"ZEXPOSURE": tiny}), json!({"ZEXPOSURE": 0})); + assert!(d.exposure.is_none() && d.is_empty(), "{tiny}"); + assert_eq!(develop_over(json!({}), json!({"ZEXPOSURE": tiny})).exposure, None, "{tiny} as a default"); + } + assert_eq!(develop_over(json!({"ZEXPOSURE": 0.002}), json!({"ZEXPOSURE": 0})).exposure, Some(0.002)); + assert_eq!(develop_over(json!({"ZEXPOSURE": -0.01}), json!({"ZEXPOSURE": 0})).exposure, Some(-0.01)); +} + +#[test] +fn a_film_curve_names_the_stem_of_its_base_curve_file() { + let stem = |v: Value| film_curve_stem(&v); + assert_eq!(stem(json!("Example-Auto.fcrv")), Ok(Some("Example-Auto".into()))); + assert_eq!(stem(json!("Example Low Contrast.FCRV")), Ok(Some("Example Low Contrast".into())), "any case, spaces kept"); + assert_eq!(stem(json!(" Example-Auto ")), Ok(Some("Example-Auto".into())), "no extension needed"); + assert_eq!(stem(json!("")), Ok(None)); + assert_eq!(stem(json!("FileSystemTiff-Auto.fcrv")), Ok(None), "a rendered file's format has no tone of its own"); + for bad in [json!(12), json!(null), json!(["a"]), json!("a/b.fcrv"), json!("a\\b.fcrv"), json!("a:b.fcrv"), json!(".fcrv"), json!("x\u{7}y.fcrv")] + { + assert_eq!(stem(bad.clone()), Err(()), "{bad}"); + } + assert_eq!(stem(json!("é.fcrv")), Ok(Some("é".into())), "not only ASCII"); +} + +#[test] +fn the_film_curve_is_the_effective_value_of_a_raw() { + let raw = ("EXAMPLE CORP", "EXAMPLE X1"); + let curve = |adjustment: Value, default: Value, camera| develop_of(&layers(adjustment, default), [6000.0, 4000.0], camera); + // the camera's default alone, and the user's own choice over it + let d = curve(json!({}), json!({"ZFILMCURVE": "Example-Auto.fcrv"}), raw); + assert_eq!(d.film_curve.as_deref(), Some("Example-Auto")); + assert!(!d.film_curve_own && d.film_curve_default.is_none()); + assert!(!d.is_empty() && d.not_imported.is_empty(), "the column is imported, not reported"); + let d = curve(json!({"ZFILMCURVE": "Example-Other.fcrv"}), json!({"ZFILMCURVE": "Example-Auto.fcrv"}), raw); + assert_eq!(d.film_curve.as_deref(), Some("Example-Other")); + assert!(d.film_curve_own && d.film_curve_default.as_deref() == Some("Example-Auto"), "the camera's own curve is kept for the baseline"); + // a style supplies it where the adjustment layer doesn't + let mut l = layers(json!({}), json!({"ZFILMCURVE": "Example-Auto.fcrv"})); + l.styles = vec![(1, row(json!({"ZFILMCURVE": "Example-Style.fcrv"})))]; + assert_eq!(develop_of(&l, [6000.0, 4000.0], raw).film_curve.as_deref(), Some("Example-Style")); + // a rendered file (Capture One names its format in place of a camera) has none, and a change of it stays reported + let d = curve(json!({"ZFILMCURVE": "Example-Other.fcrv"}), json!({"ZFILMCURVE": "Example-Auto.fcrv"}), ("", "")); + assert!(d.film_curve.is_none() && !d.film_curve_unreadable); + assert_eq!(d.not_imported, vec!["Base Characteristics curve"]); + let d = curve(json!({}), json!({"ZFILMCURVE": "FileSystemTiff-Auto.fcrv"}), ("", "")); + assert!(d.is_empty() && d.not_imported.is_empty()); + // a value that isn't a file name sets no curve and is flagged + let d = curve(json!({"ZFILMCURVE": 5}), json!({"ZFILMCURVE": "Example-Auto.fcrv"}), raw); + assert!(d.film_curve.is_none() && d.film_curve_unreadable); +} + +#[test] +fn a_camera_default_film_curve_makes_a_variant_with_no_edits_readable() { + assert!(default_applies(&row(json!({"ZFILMCURVE": "Example-Auto.fcrv"})))); + assert!(!default_applies(&row(json!({"ZFILMCURVE": ""})))); + assert!(!default_applies(&row(json!({"ZFILMCURVE": null})))); + assert!(default_applies(&row(json!({"ZFILMCURVE": 12}))), "a value that is not a name is read, to be reported"); +} + +#[test] +fn an_archive_from_before_the_film_curve_still_reads() { + let old = json!({"rotation": 0.0, "camera_rotation": 0.0, "size": [6000.0, 4000.0]}); + let d: CaptureOneDevelop = serde_json::from_value(old).unwrap(); + assert!(d.film_curve.is_none() && !d.film_curve_unreadable); + let with = CaptureOneDevelop { film_curve: Some("Example-Auto".into()), ..Default::default() }; + assert_eq!(serde_json::from_value::(serde_json::to_value(&with).unwrap()).unwrap(), with); + assert!(serde_json::to_value(CaptureOneDevelop::default()).unwrap().get("film_curve").is_none()); +} + +#[test] +fn a_rendered_files_exposure_is_converted_and_a_raws_is_not() { + let d = develop_over(json!({"ZEXPOSURE": 1.0}), json!({"ZEXPOSURE": 0})); + let ev = + |rendered: bool, d: &CaptureOneDevelop| partial_for(d, crate::crs::Target::Rendered, None, rendered).0["light"]["exposure"].as_f64().unwrap(); + assert_eq!(ev(false, &d), 1.0, "a raw's exposure is taken as it is"); + assert!((ev(true, &d) - 1.17).abs() < 1e-12, "a rendered file's is converted"); + assert_eq!(partial(&d, crate::crs::Target::RawAbsolute, None).0["light"]["exposure"], json!(1.0)); + let low = develop_over(json!({"ZEXPOSURE": -2.0}), json!({"ZEXPOSURE": 0})); + assert!((ev(true, &low) + 2.34).abs() < 1e-12); + // the app's range holds after the conversion + let high = develop_over(json!({"ZEXPOSURE": 4.5}), json!({"ZEXPOSURE": 0})); + assert_eq!(ev(true, &high), 5.0); + assert_eq!(ev(false, &high), 4.5); + // no exposure, nothing to convert + let none = develop_over(json!({"ZBRIGHTNESS": 5}), json!({"ZEXPOSURE": 0, "ZBRIGHTNESS": 0})); + assert!(partial_for(&none, crate::crs::Target::Rendered, None, true).0["light"].get("exposure").is_none()); +} + +#[test] +fn an_exposure_is_approximate_above_half_a_stop() { + for (ev, approximate) in [(0.5, false), (0.0, false), (-3.0, false), (0.51, true), (1.0, true), (5.0, true), (f64::NAN, false)] { + assert_eq!(exposure_is_approximate(ev), approximate, "{ev}"); + } +} diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 514a43f3d8..e66dd2ae4a 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -17,7 +17,7 @@ use lcc_catalog::{Op, PhotoId, Source}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, bool_or, cmd, str_param}; -use crate::import::{ImportMode, ImportOptions, import_with, is_supported}; +use crate::import::{ImportMode, ImportOptions, browse_folder_string, import_with, is_supported}; use crate::{Browse, LibrarySource, Result, Session}; fn browse(s: &mut Session, p: &Value) -> Result { @@ -27,7 +27,7 @@ fn browse(s: &mut Session, p: &Value) -> Result { if !dir.is_dir() { return Err(bad(C, format!("{path}: not a folder"))); } - let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string(); + let dir_s = browse_folder_string(&dir); // subfolders: given, it wins; left out, a re-browse of the same folder keeps the choice and a // new folder starts with subfolders in (the Import tab's browse applies the same rule) let subfolders = bool_or(p, "subfolders", s.browse.as_ref().is_none_or(|b| b.path != dir_s || b.subfolders)); @@ -143,8 +143,7 @@ const RESTAMP_SECS: i64 = 3600; fn stamp_browsed(s: &mut Session, root: &str, files: &[String]) { let now = (s.clock)(); let now_s = lcc_catalog::stacks::iso_seconds(&now); - let mut folders: std::collections::BTreeSet = - files.iter().filter_map(|f| Path::new(f).parent().map(|d| d.to_string_lossy().trim_end_matches(['/', '\\']).to_string())).collect(); + let mut folders: std::collections::BTreeSet = files.iter().filter_map(|f| Path::new(f).parent().map(browse_folder_string)).collect(); folders.insert(root.to_string()); let ops: Vec = folders .into_iter() @@ -512,7 +511,27 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result { continue; } let name = ph.file_name.clone(); - plans.push(crate::rename::RenamePlan { id: id.0, from: name.clone(), to: name, from_path: Some(path.clone()), to_path: Some(to_s) }); + // the raw's companion JPEG (issue #1692) moves with it, keeping its own name + let companion = match ph.companion_jpeg.as_deref() { + Some(from) => { + let Some(c_file) = Path::new(from).file_name().map(|n| n.to_string_lossy().to_string()) else { continue }; + let c_to = dir.join(&c_file).to_string_lossy().to_string(); + if Path::new(from) != Path::new(&c_to) && (Path::new(&c_to).exists() || !taken.insert(c_to.to_lowercase())) { + clashes.push(format!("{c_file} (the companion JPEG of {})", file.to_string_lossy())); + continue; + } + Some((from.to_string(), c_to)) + } + None => None, + }; + plans.push(crate::rename::RenamePlan { + id: id.0, + from: name.clone(), + to: name, + from_path: Some(path.clone()), + to_path: Some(to_s), + companion, + }); } if !clashes.is_empty() { let s_ = if clashes.len() == 1 { "" } else { "s" }; diff --git a/crates/engine/src/cmd/catalog.rs b/crates/engine/src/cmd/catalog.rs index a24fdf0310..e36272f76e 100644 --- a/crates/engine/src/cmd/catalog.rs +++ b/crates/engine/src/cmd/catalog.rs @@ -46,6 +46,7 @@ fn settings_json(s: &Session, c: &CatalogSettings) -> Value { "lastBackup": c.last_backup, "testIntegrity": c.test_integrity, "optimize": c.optimize, + "rawJpegCompanions": c.raw_jpeg_companions, "previews": s.preview_prefs.json(), "backupDue": c.backup_due(lcc_catalog::library::now_secs()), }) @@ -83,6 +84,9 @@ fn settings(s: &mut Session, p: &Value) -> Result { if let Some(b) = p.get("optimize").and_then(Value::as_bool) { c.optimize = b; } + if let Some(b) = p.get("rawJpegCompanions").and_then(Value::as_bool) { + c.raw_jpeg_companions = b; + } if c != before { s.set_catalog_settings(&c)?; } @@ -191,7 +195,7 @@ pub fn specs() -> Vec { "Catalog Settings", [], None, - "{backup?: never|everyExit|daily|weekly|monthly, backupDir?: path (\"\" = backups/ in the catalog), keepBackups?: n (0 = all), testIntegrity?: bool, optimize?: bool, previews?: library.previewSettings params} → the settings (saved in the catalog's catalog-settings.json)", + "{backup?: never|everyExit|daily|weekly|monthly, backupDir?: path (\"\" = backups/ in the catalog), keepBackups?: n (0 = all), testIntegrity?: bool, optimize?: bool, rawJpegCompanions?: bool (treat JPEGs next to raw files as companions of the raw: one photo per pair; issue #1692), previews?: library.previewSettings params} → the settings (saved in the catalog's catalog-settings.json)", on_disk, settings ), diff --git a/crates/engine/src/cmd/edit_in.rs b/crates/engine/src/cmd/edit_in.rs index 20258b0f9d..8bcf18f47d 100644 --- a/crates/engine/src/cmd/edit_in.rs +++ b/crates/engine/src/cmd/edit_in.rs @@ -6,7 +6,8 @@ //! dialog offers on top: //! //! - **presets** (`editIn.presets` / `editIn.savePreset` / `editIn.deletePreset`): application, -//! arguments, file format (TIFF or layered PSD), colour space, bit depth, mode, naming, stacking; +//! arguments, file format (TIFF, layered PSD, PNG, scene-linear OpenEXR, or a raw's DNG), colour +//! space, bit depth, mode, naming, stacking, an XMP sidecar for a copy-of/original hand-over; //! kept in `editors.json` in the settings folder. Built in: the system's TIFF editor and //! PhotoCraft (layered PSD). A preset's `menu` says what Photo ▸ Edit In shows for it: one //! *Edit in * (`single`), Lightroom's choices (`choices`), or its own items with their @@ -126,6 +127,44 @@ pub enum Format { Tiff, /// Layered Photoshop document (lcc-psd). Psd, + /// 8- or 16-bit PNG, the linked XMP packet embedded. + Png, + /// Scene-linear OpenEXR (Rec. 2020 primaries): 16-bit half or 32-bit float; the colour space + /// and tone curve choices don't apply. The linked XMP goes to a `.xmp` sidecar (EXR carries + /// no metadata packets). + Exr, + /// The raw data as a DNG, the edits in its XMP (a raw only: a rendered photo has no raw data + /// to keep). Bit depth and colour space don't apply. + Dng, +} + +impl Format { + /// The format's value (case as saved; anything else is `None`). + pub fn parse(s: &str) -> Option { + serde_json::from_value::(serde_json::Value::String(s.into())).ok() + } + + /// The bit depths `format` offers (as the export dialog's `ExportFormat::bit_depths`): PNG + /// takes 8/16, TIFF 8/16/32, a layered PSD 8/16 (its writer has no float), EXR 16/32, and a + /// DNG keeps the raw data's own (no choice). `None` = no choice. + pub fn bit_depths(self) -> &'static [u8] { + match self { + Format::Tiff => &[16, 8, 32], + Format::Psd => &[16, 8], + Format::Png => &[8, 16], + Format::Exr => &[16, 32], + Format::Dng => &[], + } + } + + /// Whether `bit_depth` is one `format` takes (a DNG takes none: any depth is accepted and + /// ignored, so an older `editors.json` with a depth next to a DNG still reads). + fn takes_depth(self, bit_depth: u8) -> bool { + match self { + Format::Dng => true, + _ => self.bit_depths().contains(&bit_depth), + } + } } /// A running PhotoCraft to send files to over its control channel. @@ -149,15 +188,20 @@ pub struct EditorPreset { /// Arguments before the file; one containing `{file}` takes the path instead of it going last. pub args: Vec, pub format: Format, - /// `srgb`, `adobeRgb`, `displayP3` or `proPhoto`. + /// `srgb`, `adobeRgb`, `displayP3`, `proPhoto` or `rec2020`. Not used by an EXR or DNG copy. pub color_space: String, - /// 8 or 16. + /// 8, 16 or 32 as the format takes ([`Format::bit_depths`]). pub bit_depth: u8, pub mode: Mode, /// File name template (`{name}` = the original's name without extension). pub naming: String, /// Stack the new file on the original. pub stack: bool, + /// Hand an Edit a Copy / Edit Original file an XMP sidecar too (metadata and edits, merged + /// into one that is already there): a raw developer that reads Lightroom-style sidecars. A + /// rendered copy carries its XMP in the file. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub xmp: bool, /// What its menu shows: `choices`, `single` or `actions` ([`Menu`]). pub menu: String, /// The items of an `actions` menu. @@ -178,6 +222,7 @@ impl Default for EditorPreset { mode: Mode::CopyWithAdjustments, naming: "{name}-Edit".into(), stack: true, + xmp: false, menu: Menu::Choices.as_str().into(), actions: Vec::new(), control: None, @@ -189,8 +234,9 @@ impl EditorPreset { fn validate(&self) -> std::result::Result<(), String> { lcc_actions::validate_name(&self.name)?; space(&self.color_space)?; - if !matches!(self.bit_depth, 8 | 16) { - return Err(format!("bit depth {} (8 or 16)", self.bit_depth)); + if !self.format.takes_depth(self.bit_depth) { + let depths: Vec = self.format.bit_depths().iter().map(|d| d.to_string()).collect(); + return Err(format!("bit depth {} for {} (one of {})", self.bit_depth, format_name(self.format), depths.join(", "))); } if self.naming.trim().is_empty() || self.naming.contains(['/', '\\']) || self.naming.len() > 200 { return Err("the file name template must be a plain name".into()); @@ -237,10 +283,22 @@ pub(crate) fn space(s: &str) -> std::result::Result lcc_pipeline::OutputSpace::AdobeRgb, "displayP3" => lcc_pipeline::OutputSpace::DisplayP3, "proPhoto" | "prophoto" => lcc_pipeline::OutputSpace::ProPhoto, - other => return Err(format!("unknown colour space `{other}` (srgb, adobeRgb, displayP3, proPhoto)")), + "rec2020" | "rec.2020" | "bt2020" => lcc_pipeline::OutputSpace::Rec2020, + other => return Err(format!("unknown colour space `{other}` (srgb, adobeRgb, displayP3, proPhoto, rec2020)")), }) } +/// The format's name as errors and the commands show it. +pub(crate) fn format_name(f: Format) -> &'static str { + match f { + Format::Tiff => "TIFF", + Format::Psd => "PSD", + Format::Png => "PNG", + Format::Exr => "OpenEXR", + Format::Dng => "DNG", + } +} + /// The user's presets (read from `editors.json` on first use; a damaged file is an error and is /// not written over). /// The user's saved presets, read without changing the session (the menu lists them): those read @@ -388,7 +446,7 @@ fn resolve(s: &mut Session, p: &Value, cmd: &str) -> Result { None => builtin_presets().into_iter().next().unwrap_or_default(), }; let mut v = serde_json::to_value(&base).map_err(|e| bad(cmd, e.to_string()))?; - for k in ["app", "args", "format", "colorSpace", "bitDepth", "mode", "naming", "stack", "control", "menu", "actions"] { + for k in ["app", "args", "format", "colorSpace", "bitDepth", "mode", "naming", "stack", "xmp", "control", "menu", "actions"] { if let (Some(x), Some(o)) = (p.get(k), v.as_object_mut()) { o.insert(k.into(), x.clone()); } @@ -585,6 +643,50 @@ fn decode_tiff16(bytes: &[u8]) -> std::result::Result { Ok(Rendered16 { width: w, height: h, rgb, icc }) } +/// A photo rendered with its edits as linear float samples in `space` (a 32-bit float copy's +/// pixels): rendered through the float export, decoded back. +struct RenderedF32 { + width: u32, + height: u32, + rgb: Vec, + icc: Option>, +} + +fn render32(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, cmd: &str) -> Result { + let opts = crate::export::ExportOptions { + format: crate::export::ExportFormat::Tiff, + bit_depth: Some(32), + color_space: space, + tiff_compression: crate::export::TiffCompression::None, + metadata: crate::export::MetadataPolicy::None, + ..Default::default() + }; + let e = crate::export::export_photo(s, id, &opts, 1).map_err(|e| bad(cmd, e))?; + decode_tiff_f32(&e.bytes).map_err(|e| bad(cmd, format!("photo {}: {e}", id.0))) +} + +/// Our own 32-bit float RGB(A) TIFF back to samples (alpha dropped). +fn decode_tiff_f32(bytes: &[u8]) -> std::result::Result { + use tiff::decoder::{Decoder, DecodingResult, Limits}; + let mut d = Decoder::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?.with_limits(Limits::unlimited()); + let (w, h) = d.dimensions().map_err(|e| e.to_string())?; + let spp = match d.colortype().map_err(|e| e.to_string())? { + tiff::ColorType::RGB(32) => 3, + tiff::ColorType::RGBA(32) => 4, + other => return Err(format!("unexpected render layout {other:?}")), + }; + let icc = d.get_tag_u8_vec(tiff::tags::Tag::Unknown(34675)).ok(); + let DecodingResult::F32(v) = d.read_image().map_err(|e| e.to_string())? else { + return Err("unexpected render sample format".into()); + }; + let n = (w as usize).saturating_mul(h as usize); + if v.len() < n.saturating_mul(spp) { + return Err("render is short".into()); + } + let rgb = if spp == 3 { v } else { v.as_chunks::<4>().0.iter().flat_map(|p| p.iter().take(3).copied()).collect() }; + Ok(RenderedF32 { width: w, height: h, rgb, icc }) +} + /// A layered PSD (PSB when a side passes 30 000 px): `layers` bottom to top, each centred on a /// canvas as large as the largest, and the composite (layers are opaque: the topmost covering a /// pixel shows; uncovered pixels are transparent). @@ -650,9 +752,38 @@ fn linked_xmp(s: &Session, id: PhotoId, seed: &str) -> Option { Some(link::add_link(&packet, &link::new_document_id(seed), &from, &ph.file_name)) } -/// A TIFF of `id` rendered with its edits (8 or 16 bits in `space`), with the export metadata -/// (EXIF) and the linked XMP packet. +/// A TIFF of `id` rendered with its edits (8 or 16 bits in `space`, or 32-bit float linear), with +/// the export metadata (EXIF) and the linked XMP packet. fn linked_tiff(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, depth: u8, seed: &str, cmd: &str) -> Result> { + let ph = s.catalog.photo(id).cloned().ok_or_else(|| bad(cmd, "no photo"))?; + let meta = crate::export::export_metadata(&ph, &s.catalog, &crate::export::ExportOptions::default()); + let exif = meta.as_ref().map(lcc_meta::write_exif); + let xmp = linked_xmp(s, id, seed); + if depth == 32 { + // 32-bit float TIFF is linear light (as an editor's float files are): rendered through + // the float export and encoded with the metadata + let r = render32(s, id, space, cmd)?; + let profile = r.icc.clone().unwrap_or_else(|| lcc_codecs::icc::write_named(crate::export::named_space(space))); + let img = lcc_codecs::EncodeImage::new(r.width, r.height, 3, lcc_codecs::Samples::F32(&r.rgb)); + let em = lcc_codecs::EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: None }; + return lcc_codecs::encode_tiff(&img, lcc_codecs::TiffCompression::Deflate, &em).map_err(|e| bad(cmd, e.to_string())); + } + let r = render16(s, id, space, cmd)?; + let profile = r.icc.clone().unwrap_or_else(|| lcc_codecs::icc::write_named(crate::export::named_space(space))); + let eight: Vec; + let img = if depth == 8 { + eight = r.rgb.iter().map(|x| ((u32::from(*x) * 255 + 32_767) / 65_535) as u8).collect(); + lcc_codecs::EncodeImage::new(r.width, r.height, 3, lcc_codecs::Samples::U8(&eight)) + } else { + lcc_codecs::EncodeImage::new(r.width, r.height, 3, lcc_codecs::Samples::U16(&r.rgb)) + }; + let em = lcc_codecs::EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: None }; + lcc_codecs::encode_tiff(&img, lcc_codecs::TiffCompression::Deflate, &em).map_err(|e| bad(cmd, e.to_string())) +} + +/// A PNG of `id` rendered with its edits (8 or 16 bits in `space`), with the export metadata +/// (EXIF) and the linked XMP packet embedded. +fn linked_png(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, depth: u8, seed: &str, cmd: &str) -> Result> { let r = render16(s, id, space, cmd)?; let ph = s.catalog.photo(id).cloned().ok_or_else(|| bad(cmd, "no photo"))?; let meta = crate::export::export_metadata(&ph, &s.catalog, &crate::export::ExportOptions::default()); @@ -667,7 +798,31 @@ fn linked_tiff(s: &mut Session, id: PhotoId, space: lcc_pipeline::OutputSpace, d } else { lcc_codecs::EncodeImage::new(r.width, r.height, 3, lcc_codecs::Samples::U16(&r.rgb)) }; - lcc_codecs::encode_tiff(&img, lcc_codecs::TiffCompression::Deflate, &em).map_err(|e| bad(cmd, e.to_string())) + lcc_codecs::encode_png(&img, &em).map_err(|e| bad(cmd, e.to_string())) +} + +/// A scene-linear OpenEXR of `id` with its edits: Rec. 2020 primaries (the pipeline's working +/// space), 16-bit half or 32-bit float. The colour space choice doesn't apply (a float render is +/// linear). +fn exr_copy(s: &mut Session, id: PhotoId, depth: u8, cmd: &str) -> Result> { + let opts = crate::export::ExportOptions { + format: crate::export::ExportFormat::Exr, + bit_depth: Some(depth), + color_space: lcc_pipeline::OutputSpace::Rec2020, + exr_primaries: crate::export::ExrPrimaries::Rec2020, + metadata: crate::export::MetadataPolicy::None, + ..Default::default() + }; + let e = crate::export::export_photo(s, id, &opts, 1).map_err(|e| bad(cmd, e))?; + Ok(e.bytes) +} + +/// The raw data as a DNG, the edits in its XMP (the export's DNG path). A raw only: a rendered +/// photo has no raw data to keep. +fn dng_copy(s: &mut Session, id: PhotoId, cmd: &str) -> Result> { + let opts = crate::export::ExportOptions { format: crate::export::ExportFormat::Dng, ..Default::default() }; + let e = crate::export::export_photo(s, id, &opts, 1).map_err(|e| bad(cmd, e))?; + Ok(e.bytes) } /// The mode Lightroom suggests for a photo: Edit Original for a PSD or TIFF (most likely an @@ -714,6 +869,34 @@ fn edit_in(s: &mut Session, p: &Value) -> Result { write_durable(&dest, &bytes, C)?; dest } + Format::Png => { + let dest = unique_path(&dir, &stem, "png")?; + let bytes = linked_png(s, id, space, pr.bit_depth, &dest.to_string_lossy(), C)?; + write_durable(&dest, &bytes, C)?; + dest + } + Format::Exr => { + let dest = unique_path(&dir, &stem, "exr")?; + let bytes = exr_copy(s, id, pr.bit_depth, C)?; + write_durable(&dest, &bytes, C)?; + // EXR carries no metadata packet: the linked XMP goes to a sidecar beside it + if let Some(x) = linked_xmp(s, id, &dest.to_string_lossy()) + && !x.is_empty() + { + let side = unique_path(&dir, &stem, "xmp")?; + write_durable(&side, x.as_bytes(), C)?; + } + dest + } + Format::Dng => { + if ph.kind != lcc_catalog::MediaKind::Raw { + return Err(bad(C, "a DNG copy keeps the raw data: give a raw photo, or choose TIFF, PSD, PNG or OpenEXR")); + } + let dest = unique_path(&dir, &stem, "dng")?; + let bytes = dng_copy(s, id, C)?; + write_durable(&dest, &bytes, C)?; + dest + } Format::Psd => { let r = render16(s, id, space, C)?; let icc = r.icc.clone(); @@ -729,15 +912,55 @@ fn edit_in(s: &mut Session, p: &Value) -> Result { } }; let edited = new.unwrap_or(id.0); + // (+XMP): the file the editor gets also gets the photo's metadata and edits as a sidecar, + // merged into one that is already there. A rendered copy carries its XMP in the file (the + // EXR's is beside it), so only a copy of, or the, original file takes the sidecar. + let mut xmp_error = None; + if pr.xmp && matches!(pr.mode, Mode::Copy | Mode::Original) { + match write_edit_sidecar(s, PhotoId(edited), id) { + Ok(()) => (), + Err(e) => xmp_error = Some(e), + } + } let opened = hand_over(s, &pr, &path, edited, p, C)?; - Ok(json!({ + let mut out = json!({ "path": path.to_string_lossy(), "id": edited, "original": id.0, "mode": pr.mode, "openWith": {"path": path.to_string_lossy(), "app": pr.app, "args": pr.args, "reload": [edited], "preset": pr.name, "control": pr.control}, "opened": opened, - })) + }); + if let Some(e) = xmp_error { + out["xmpError"] = json!(e); + } + Ok(out) +} + +/// `photo.saveMetadataToFile` for the file the editor gets: its XMP sidecar (metadata and edits), +/// merged into one that is already there (an unreadable one is backed up first). A copy's sidecar +/// also names what it was made from (`xmpMM:DerivedFrom`), so a re-import of the file stacks it. +fn write_edit_sidecar(s: &mut Session, id: PhotoId, original: PhotoId) -> std::result::Result<(), String> { + s.settle_sidecar_writes().map_err(|e| e.to_string())?; + let owners = crate::sidecar::StemOwners::among(&s.catalog, &[id]); + let saved = s.save_sidecar_with(id, &owners).map_err(|e| e.to_string())?; + if id != original + && let Some(packet) = (|| { + let bytes = std::fs::read(&saved.path).ok()?; + if bytes.len() > (1 << 20) { + return None; + } + let text = String::from_utf8(bytes).ok()?; + let ph = s.catalog.photo(original)?; + let from = link::source_document_id(ph); + Some(link::add_link(&text, &link::new_document_id(&saved.path.to_string_lossy()), &from, &ph.file_name)) + })() + && lcc_catalog::safe_file::write_atomic(&saved.path, packet.as_bytes()).is_ok() + { + s.note_sidecar_write(&saved.path, packet.as_bytes()); + } + s.record_xmp_stamps(&[id], false); + Ok(()) } fn open_as_layers(s: &mut Session, p: &Value) -> Result { @@ -919,13 +1142,13 @@ pub fn control_open(_: &Control, _: &Path) -> std::result::Result pub(super) fn specs() -> Vec { vec![ - cmd!(query "editIn.presets", "Edit In Presets", [], None, "{}: external editor presets → {builtin: [preset], user: [preset]}; a preset is {name, app, args, format: tiff|psd, colorSpace, bitDepth: 8|16, mode: copyWithAdjustments|copy|original|sourceFile, naming, stack, control?: {port, tokenFile, root}}", always, presets), + cmd!(query "editIn.presets", "Edit In Presets", [], None, "{}: external editor presets → {builtin: [preset], user: [preset]}; a preset is {name, app, args, format: tiff|psd|png|exr|dng, colorSpace, bitDepth: 8|16|32, mode: copyWithAdjustments|copy|original|sourceFile, naming, stack, xmp?, control?: {port, tokenFile, root}}", always, presets), cmd!( "editIn.savePreset", "Save Edit In Preset", [], None, - "{name, app?, args?: [..., \"{file}\"?], format?: tiff|psd, colorSpace?: srgb|adobeRgb|displayP3|proPhoto, bitDepth?: 8|16, mode?: copyWithAdjustments|copy|original|sourceFile, naming?: \"{name}-Edit\", stack?: true, menu?: choices|single|actions, actions?: [{label, args?: [...]}], control?: {port, tokenFile, root}}: add or replace an external editor preset (kept in editors.json in the settings folder); app, args and control choose a program, so over MCP, the control channel or in an action they can't be set or changed → the preset", + "{name, app?, args?: [..., \"{file}\"?], format?: tiff|psd|png|exr|dng, colorSpace?: srgb|adobeRgb|displayP3|proPhoto|rec2020, bitDepth?: 8|16|32 (as the format takes), mode?: copyWithAdjustments|copy|original|sourceFile, naming?: \"{name}-Edit\", stack?: true, xmp?: false, menu?: choices|single|actions, actions?: [{label, args?: [...]}], control?: {port, tokenFile, root}}: add or replace an external editor preset (kept in editors.json in the settings folder); app, args and control choose a program, so over MCP, the control channel or in an action they can't be set or changed → the preset", always, save_preset ), @@ -945,7 +1168,7 @@ pub(super) fn specs() -> Vec { "Edit In…", ["Photo", "Edit In"], None, - "{id?, preset?: name (default \"External Editor\"), mode?, format?, colorSpace?, bitDepth?, app?, args?, naming?, stack?, dir?, launch?: false, wait?: false}: Edit In with Lightroom's options: copyWithAdjustments renders the photo with its edits (TIFF, or a layered PSD), copy copies the original file, original edits the file itself (copy/original: JPEG, TIFF, PNG, PSD, WebP only), sourceFile opens the photo's own file, a raw included. A new file is added to the library, stacked directly above the photo it was made from (inside that photo's stack when it has one) and selected; TIFF and PSD copies carry an xmpMM:DerivedFrom link to it, so a re-import stacks them again. launch opens it in the preset's application (or over PhotoCraft's control channel); app and args (and a preset's control) choose a program, so they're for the command line and the Edit In Presets dialog only: over MCP, the control channel or in an action, name a saved preset instead; wait (with launch) starts the application with --wait, returns when it exits and reloads the photo → {path, id, original, mode, openWith: {path, app, args, reload, preset, control}, opened}", + "{id?, preset?: name (default \"External Editor\"), mode?, format?: tiff|psd|png|exr|dng, colorSpace?: srgb|adobeRgb|displayP3|proPhoto|rec2020, bitDepth?: 8|16|32 (as the format takes), app?, args?, naming?, stack?, xmp?: false, dir?, launch?: false, wait?: false}: Edit In with Lightroom's options: copyWithAdjustments renders the photo with its edits (TIFF, a layered PSD, PNG, scene-linear OpenEXR in Rec. 2020, or a raw's DNG with the edits in its XMP), copy copies the original file, original edits the file itself (copy/original: JPEG, TIFF, PNG, PSD, WebP only), sourceFile opens the photo's own file, a raw included. xmp (copy/original) writes an XMP sidecar beside the file the editor gets, merged into one that is there. A new file is added to the library, stacked directly above the photo it was made from (inside that photo's stack when it has one) and selected; TIFF, PSD and PNG copies carry an xmpMM:DerivedFrom link to it (OpenEXR's beside the file), so a re-import stacks them again. launch opens it in the preset's application (or over PhotoCraft's control channel); app and args (and a preset's control) choose a program, so they're for the command line and the Edit In Presets dialog only: over MCP, the control channel or in an action, name a saved preset instead; wait (with launch) starts the application with --wait, returns when it exits and reloads the photo → {path, id, original, mode, openWith: {path, app, args, reload, preset, control}, opened, xmpError?}", has_active, edit_in ) @@ -1045,7 +1268,7 @@ mod tests { // parse or is checked like a preset saved through `editIn.savePreset`. { let values = [r#""""#, r#""../x""#, r#""{file}{file}""#, r#""\u0000""#, "1e308", "-1", "null", "[]", "{}", r#""a\nb""#, "255", "65536"]; - let keys = ["name", "app", "args", "format", "colorSpace", "bitDepth", "mode", "naming", "stack", "control", "menu", "actions"]; + let keys = ["name", "app", "args", "format", "colorSpace", "bitDepth", "mode", "naming", "stack", "xmp", "control", "menu", "actions"]; let extras = ["", r#","args":["{file}","-x"]"#, r#","control":{"port":99999,"tokenFile":"","root":"/"}"#]; let mut n = 0; for (i, k) in keys.iter().enumerate() { diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index eb191795d4..a5b119ef61 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -706,6 +706,96 @@ fn rect_json(r: &lcc_geom::Rect) -> Value { /// Most confirmed faces `faces.person` lists. const MAX_CONFIRMED: usize = 5000; +/// How a person's confirmed faces are ordered (`faces.person`'s `sort`, issue #1691): the order the +/// photos came into the library (the default, what the page showed before), their capture time +/// oldest or newest first (to see someone grow up or age), by folder and file name, or the largest +/// face first (to pick a good portrait). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum PersonSort { + #[default] + Photo, + Oldest, + Newest, + Folder, + FaceSize, +} + +/// The `sort` a `faces.person` call asks for. +fn person_sort_of(cmd: &str, p: &Value) -> Result { + match p.get("sort") { + None | Some(Value::Null) => Ok(PersonSort::default()), + Some(Value::String(v)) => match v.as_str() { + "photo" => Ok(PersonSort::Photo), + "oldest" => Ok(PersonSort::Oldest), + "newest" => Ok(PersonSort::Newest), + "folder" => Ok(PersonSort::Folder), + "faceSize" => Ok(PersonSort::FaceSize), + other => Err(bad(cmd, format!("`sort` must be \"photo\", \"oldest\", \"newest\", \"folder\" or \"faceSize\", not \"{other}\""))), + }, + Some(_) => Err(bad(cmd, "`sort` must be a string")), + } +} + +/// One of a person's confirmed faces, with what its order depends on. The photo is borrowed from the +/// catalog (its capture time reads off it); the folder and file name keys are made once, lower-cased, +/// so the sort itself does not allocate. +struct FaceRow<'a> { + photo: u64, + index: usize, + rect: lcc_geom::Rect, + view: lcc_geom::Rect, + captured: Option<&'a str>, + folder: String, + file: String, + /// The face's size in pixels of the photo; never NaN or infinite (a broken box sorts last). + area: f64, +} + +/// The photo's folder (everything before the last separator; `""` when the path has none, or for a +/// demo photo, which has no folder at all). +fn folder_of(ph: &lcc_catalog::Photo) -> &str { + match &ph.source { + lcc_catalog::Source::File { path } => path.rsplit_once(['/', '\\']).map_or(path.as_str(), |(dir, _)| dir), + lcc_catalog::Source::Demo { .. } => "", + } +} + +/// How two faces compare by capture time (ISO 8601 texts compare as dates, as the grid's capture-date +/// sort does): oldest first, or newest. A photo with no capture time has no place on the timeline: +/// it comes last, whichever way. +fn by_captured(a: Option<&str>, b: Option<&str>, newest: bool) -> std::cmp::Ordering { + match (a, b) { + (Some(x), Some(y)) => { + if newest { + y.cmp(x) + } else { + x.cmp(y) + } + } + (Some(_), None) => std::cmp::Ordering::Less, + (None, Some(_)) => std::cmp::Ordering::Greater, + (None, None) => std::cmp::Ordering::Equal, + } +} + +/// `sort`'s order for two of a person's faces; every way ends in the photo, then the region, so the +/// order never depends on how the list was walked. +fn face_order(sort: PersonSort, a: &FaceRow, b: &FaceRow) -> std::cmp::Ordering { + match sort { + // as imported: the photo ids, then the regions on the photo + PersonSort::Photo => a.photo.cmp(&b.photo).then(a.index.cmp(&b.index)), + PersonSort::Oldest => by_captured(a.captured, b.captured, false), + PersonSort::Newest => by_captured(a.captured, b.captured, true), + // the folders in the library's path order (lower-cased, so a case difference does not + // separate two folders a file system counts the same), then the file names + PersonSort::Folder => a.folder.cmp(&b.folder).then(a.file.cmp(&b.file)), + // the largest face first (a broken box's area was made -inf, so it comes last) + PersonSort::FaceSize => b.area.total_cmp(&a.area), + } + .then(a.photo.cmp(&b.photo)) + .then(a.index.cmp(&b.index)) +} + /// `faces.person {name, more?}`: the faces named `name` (case-insensitively) across the library, and, when a recognition /// model is chosen, the unnamed faces that look most like them, to be confirmed one by one. fn person(s: &mut Session, p: &Value) -> Result { @@ -714,7 +804,9 @@ fn person(s: &mut Session, p: &Value) -> Result { let key = name.to_lowercase(); let limit = p.get("more").and_then(Value::as_u64).map_or(120, |n| usize::try_from(n).unwrap_or(120)).min(1000); let scope = scope_of(s, C, p)?; - let (mut shown, mut total, mut confirmed) = (name.to_string(), 0usize, Vec::new()); + let sort = person_sort_of(C, p)?; + let (mut shown, mut total) = (name.to_string(), 0usize); + let mut confirmed: Vec = Vec::new(); for ph in s.catalog.photos().filter(|ph| ph.in_library()) { for (index, r) in ph.meta.regions.iter().enumerate() { let Some(n) = r.name.as_deref().filter(|n| r.kind == lcc_meta::RegionKind::Face && n.trim().to_lowercase() == key) else { @@ -724,12 +816,29 @@ fn person(s: &mut Session, p: &Value) -> Result { shown = n.trim().to_string(); } total += 1; - // the count is the whole library's; the faces shown follow the scope - if confirmed.len() < MAX_CONFIRMED && in_scope(&scope, ph.id.0) { - confirmed.push(json!({"photo": ph.id.0, "index": index, "rect": rect_json(&r.rect), "view": rect_json(&s.face_view(ph.id, r.rect))})); + // the count is the whole library's; the faces shown follow the scope, in `sort`'s order + if in_scope(&scope, ph.id.0) { + let w = f64::from(ph.width.max(1)); + let h = f64::from(ph.height.max(1)); + // `.max` puts a negative or NaN box's measures at 0 (so the face sorts last, not first) + let area = (r.rect.x1 - r.rect.x0).max(0.0) * (r.rect.y1 - r.rect.y0).max(0.0) * w * h; + confirmed.push(FaceRow { + photo: ph.id.0, + index, + rect: r.rect, + view: s.face_view(ph.id, r.rect), + captured: ph.captured.as_deref(), + folder: folder_of(ph).to_lowercase(), + file: ph.file_name.to_lowercase(), + area: if area.is_finite() { area } else { f64::NEG_INFINITY }, + }); } } } + confirmed.sort_by(|a, b| face_order(sort, a, b)); + confirmed.truncate(MAX_CONFIRMED); + let confirmed: Vec = + confirmed.iter().map(|f| json!({"photo": f.photo, "index": f.index, "rect": rect_json(&f.rect), "view": rect_json(&f.view)})).collect(); let similar = if total > 0 { imp::similar(s, &key, limit, &scope) } else { Similar { items: Vec::new(), ready: false, pending: 0 } }; Ok( json!({"name": shown, "total": total, "confirmed": confirmed, "more": similar.items, "ready": similar.ready, "pendingPhotos": similar.pending}), @@ -887,8 +996,12 @@ mod imp { }) .map(|r| r.rect) .collect(); - // Finding faces needs the detector the user may not have downloaded: without it a photo is left unsearched. - let detector = (search || redetect).then(|| crate::cmd::face_detect::detector(s).ok()).flatten(); + // The detector has two jobs here. It finds the faces of photos that have none, which is what `search` and + // `redetect` ask for, and it lends its landmarks to every face that is embedded, so each is cut out aligned: + // a recognition model matches a face cut by its box far less well (issue #1616: the scans that only embed did + // exactly that for a while). It is also what the user may not have downloaded: without it a photo is left + // unsearched, and its faces are cut by their boxes. + let detector = crate::cmd::face_detect::detector(s).ok(); let detect = detector.is_some() && (redetect || (search && needs_search(s, &photo))); if todo.is_empty() && !detect { return None; @@ -2543,6 +2656,58 @@ mod imp { } } + /// Issue #1616: the scans that only embed (Recognize Existing Faces, Rebuild All Embeddings, `faces.index`) cut + /// every face by its box for a while, because the detector was only attached when a scan searched. With the face + /// model installed they cut it by the detector's landmarks, as the background scan does, and still find no faces + /// of their own. Needs the MediaPipe face model and a photo with a face (`LC_AI_MODELS_TEST_DIR`, + /// `LC_RETOUCH_TEST_PHOTO`), as the Retouch test does; skipped without them. + #[cfg(feature = "sam")] + #[test] + fn a_scan_that_only_embeds_cuts_the_face_by_the_detectors_landmarks() { + let (Some(_), Some(photo)) = (std::env::var_os("LC_AI_MODELS_TEST_DIR"), std::env::var_os("LC_RETOUCH_TEST_PHOTO")) else { + lcc_testkit::skip!(Model, "set LC_AI_MODELS_TEST_DIR and LC_RETOUCH_TEST_PHOTO"); + return; + }; + let d = temp("aligned"); + let mut s = Session::new().with_fs(); + s.face_models_dir = Some(d.join("models")); + let model = d.join("tiny64.onnx"); + std::fs::write(&model, lcc_faces::synthetic::tiny_embedder_model(64)).unwrap(); + let p = json!({"path": model.to_string_lossy(), "acknowledged": true, "enable": true}); + s.execute("faces.models.install", &p).unwrap(); + if !install_face_model(&mut s) { + lcc_testkit::skip!(Model, "the face model in LC_AI_MODELS_TEST_DIR could not be loaded"); + return; + } + let r = s.execute("library.import", &json!({"paths": [photo.to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().unwrap()); + // where the face is, by the detector's own box, drawn a tenth larger: the photo's one face region + let r = s.execute("faces.detect", &json!({"ids": [id.0], "wait": true, "apply": false})).unwrap(); + let faces = r["photos"][0]["faces"].as_array().cloned().unwrap_or_default(); + assert!(!faces.is_empty(), "the detector finds the face: {r}"); + let f = &faces[0]["rect"]; + let (x0, y0, x1, y1) = (f["x0"].as_f64().unwrap(), f["y0"].as_f64().unwrap(), f["x1"].as_f64().unwrap(), f["y1"].as_f64().unwrap()); + let grow = |c: f64, half: f64| (c - half * 1.1, c + half * 1.1); + let ((rx0, rx1), (ry0, ry1)) = (grow((x0 + x1) / 2.0, (x1 - x0) / 2.0), grow((y0 + y1) / 2.0, (y1 - y0) / 2.0)); + let rect = Rect { x0: rx0, y0: ry0, x1: rx1, y1: ry1 }; + set_regions(&mut s, id, vec![Region { rect, ..region(0.0, None) }]); + let embedder = current(&mut s, "faces.index").unwrap(); + // the background scan's job (it searches, so the detector was always attached): the face, aligned + let scan = prepare(&mut s, id, true, false, false, crate::faces_worker::REGION_SCORE, false).unwrap(); + assert!(scan.detector.is_some() && !scan.detect && scan.todo == vec![rect]); + let scan = process(scan, &embedder).results.remove(0); + assert!(scan.2 != rect, "the detector found the face and lends its landmarks"); + // the job of a scan that only embeds + let job = prepare(&mut s, id, false, false, false, crate::faces_worker::REGION_SCORE, false).expect("the face still needs embedding"); + assert!(job.detector.is_some(), "the detector is there to align the face"); + assert!(!job.detect && job.todo == vec![rect], "it is not asked to find faces"); + let done = process(job, &embedder); + assert!(done.found.is_none(), "nothing was searched for"); + assert_eq!(done.results[0].2, scan.2, "cut by the detector's landmarks, as the background scan does"); + assert_eq!(done.results[0].1, scan.1, "and so the same face"); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn faces_from_another_library_or_a_replaced_file_are_dropped() { // opening another library forgets the old ones faces @@ -2941,6 +3106,15 @@ pub fn specs() -> Vec { super::always, imp::maintain ), + cmd!( + "faces.buildThumbnails", + "Build Face Thumbnails", + [], + None, + "{edge?: 256, lanes?: 1..8 (2 in the background, with wait an eighth of the threads up to 4), wait?: bool, status?: bool, cancel?: bool}: render a tile of every face in the library (the ignored ones aside) at one tile edge into the thumbnail cache, memory and disk, so the People view shows them without rendering while it scrolls; `edge` is the size the frontend's tiles are now, else 256, and tiles cached already cost a lookup. Runs in the background (an activity row, cancellable); `wait` runs it now; `status` reports the last run; `cancel` stops it → {active, done, total, built, failed, cancelled, edge, ms?, lanes?}", + super::always, + crate::face_thumbs::build + ), cmd!( query "faces.scanStatus", "Face Maintenance Status", @@ -3090,7 +3264,7 @@ pub fn specs() -> Vec { "Faces of a Person", [], None, - "{name, more?: 120, scope?: \"filter\"} → {name, total, confirmed: [{photo, index, rect}], more: [{photo, index, rect, score}], ready, pendingPhotos}: the faces named `name` across the library, and the unnamed faces that look most like them (best first, already embedded ones only, once a recognition model is chosen); confirm one with `faces.setName`. `scope: \"filter\"` shows only the faces in the photos the library shows (the sidebar's source and the filter, any person filter aside); `total` still counts the whole library", + "{name, more?: 120, scope?: \"filter\", sort?: photo | oldest | newest | folder | faceSize} → {name, total, confirmed: [{photo, index, rect}], more: [{photo, index, rect, score}], ready, pendingPhotos}: the faces named `name` across the library, and the unnamed faces that look most like them (best first, already embedded ones only, once a recognition model is chosen); confirm one with `faces.setName`. `scope: \"filter\"` shows only the faces in the photos the library shows (the sidebar's source and the filter, any person filter aside); `total` still counts the whole library. `sort` orders the confirmed faces: `photo` (the import order, the default), `oldest`/`newest` (capture time; photos without a capture time last either way), `folder` (path, then file name) or `faceSize` (largest face first, to pick a portrait)", super::always, person ), diff --git a/crates/engine/src/cmd/facets.rs b/crates/engine/src/cmd/facets.rs index 9bdb62e73a..0a4af3f4e3 100644 --- a/crates/engine/src/cmd/facets.rs +++ b/crates/engine/src/cmd/facets.rs @@ -49,8 +49,11 @@ fn without(field: &str, f: &Filter) -> Filter { f.flag = None; f.flags.clear(); } - "rating" => f.rating = 0, - "kind" => f.kind = None, + "rating" => { + f.rating = 0; + f.rating_op = Default::default(); + } + "kind" => (f.kind, f.merged) = (None, None), "year" => { f.date = None; f.date_from = None; @@ -96,11 +99,16 @@ pub fn chosen(s: &Session, field: &str) -> Vec { v.extend(f.label.filter(|l| !f.labels.contains(l))); v.into_iter().map(|l| s.catalog.label_name(l)).collect() } - "flag" => f.flag.map(flag_name).map(str::to_string).into_iter().collect(), + "flag" => f.flag.into_iter().chain(f.flags.iter().copied()).map(flag_name).map(str::to_string).fold(Vec::new(), |mut v, n| { + if !v.contains(&n) { + v.push(n); + } + v + }), "rating" if f.rating_op == RatingOp::Exactly && f.rating > 0 => vec![f.rating.to_string()], - "kind" => f.kind.map(kind_name).map(str::to_string).into_iter().collect(), + "kind" => f.kind.map(kind_name).map(str::to_string).into_iter().chain(f.merged.clone()).collect(), "rating" if f.rating_op == RatingOp::Exactly && f.rating == 0 => vec!["0".to_string()], - "year" => f.date.iter().filter(|d| d.len() == 4).cloned().collect(), + "year" => f.date.iter().filter(|d| lcc_catalog::dates::valid_date_prefix(d)).cloned().collect(), _ => facet(f, field).map(|p| p.values.clone()).unwrap_or_default(), }; if let Some(pk) = facet(f, field) { @@ -113,144 +121,214 @@ pub fn chosen(s: &Session, field: &str) -> Vec { out } -/// `library.facetPick`: a click on a Metadata column's value. Fields that take several values (camera, lens, -/// keyword, person, label) toggle it among the chosen ones, any of which matches; the others hold one value, which -/// a second click clears. No value clears the field. `none: true` toggles the photos without a value instead -/// (the column's "no value" row), which combine with the chosen values (any matches). +/// `library.facetPick`: a click on a Metadata column's value. `values` with a `mode` sets the choice: `replace` +/// chooses exactly those values, `toggle` adds each one or removes it when it is chosen (⌘-click); a ⇧-click's run +/// is the explicit list the caller worked out. Any of the chosen values matches. The older `value` form toggles a +/// value of the fields that take several (camera, lens, keyword, person, label and the facet fields) and sets or +/// clears the one value of flag, rating, kind and year; no value clears the field. `none: true` toggles the photos +/// without a value instead (the column's "no value" row), which combine with the chosen values (any matches). fn pick(s: &mut Session, p: &Value) -> Result { const C: &str = "library.facetPick"; let Some(field) = p.get("field").and_then(Value::as_str).filter(|f| lcc_catalog::facets::is_field(f)) else { return Err(bad(C, format!("field is one of {}", fields().join(", ")))); }; - match p.get("none") { - None | Some(Value::Null) | Some(Value::Bool(false)) => {} - Some(Value::Bool(true)) => { - if matches!(field, "flag" | "rating" | "kind" | "faces") { - return Err(bad(C, format!("every photo has a {field}: pick its value (flag none, rating 0, faces 0) instead"))); - } - let on = !none_chosen(s, field); - // turning the no-value row on unites it with values picked before: they move from the - // dedicated fields into the `Filter::facets` entry (the union), the dedicated fields - // would AND with it and the column would come out empty - if on && matches!(field, "camera" | "lens" | "keyword" | "person" | "label") { - let mut values = chosen(s, field); - match field { - "camera" => (s.filter.camera, s.filter.cameras) = (None, Vec::new()), - "lens" => (s.filter.lens, s.filter.lenses) = (None, Vec::new()), - "keyword" => (s.filter.keyword, s.filter.keywords) = (None, Vec::new()), - "person" => (s.filter.person, s.filter.people) = (None, Vec::new()), - _ => (s.filter.label, s.filter.labels) = (None, Vec::new()), - } - match s.filter.facets.iter_mut().find(|p| p.field == field) { - Some(pk) => { - pk.values.clear(); - pk.values.append(&mut values); - pk.none = true; + let none_arg = match p.get("none") { + None | Some(Value::Null) => None, + Some(Value::Bool(b)) => Some(*b), + Some(_) => return Err(bad(C, "none is true or false")), + }; + let done = |s: &mut Session| Ok(json!({"field": field, "chosen": chosen(s, field), "none": none_chosen(s, field), "count": s.visible().len()})); + if let Some(list) = p.get("values") { + let Some(list) = list.as_array() else { return Err(bad(C, "values is a list of strings")) }; + let mut given = Vec::new(); + for v in list { + given.push(v.as_str().ok_or_else(|| bad(C, "values is a list of strings"))?.to_string()); + } + let (before, none_before) = (chosen(s, field), none_chosen(s, field)); + let (next, none) = match p.get("mode").and_then(Value::as_str) { + Some("replace") => (given, none_arg.unwrap_or(false)), + Some("toggle") => { + let mut next = before; + for v in given { + match next.iter().position(|b| b.eq_ignore_ascii_case(&v)) { + Some(i) => { + next.remove(i); + } + None => next.push(v), } - None => s.filter.facets.push(FacetPick { field: field.to_string(), values, none: true }), } - s.filter.facets.retain(|p| !p.is_empty()); - return Ok(json!({"field": field, "chosen": chosen(s, field), "none": none_chosen(s, field), "count": s.visible().len()})); + (next, if none_arg == Some(true) { !none_before } else { none_before }) } - match s.filter.facets.iter_mut().find(|p| p.field == field) { - Some(pk) => pk.none = on, - None => s.filter.facets.push(FacetPick { field: field.to_string(), values: Vec::new(), none: on }), - } - s.filter.facets.retain(|p| !p.is_empty()); - return Ok(json!({"field": field, "chosen": chosen(s, field), "none": none_chosen(s, field), "count": s.visible().len()})); - } - Some(_) => return Err(bad(C, "none is true or false")), + _ => return Err(bad(C, "mode is replace or toggle")), + }; + set_choice(s, field, next, none)?; + return done(s); + } + if none_arg == Some(true) { + let (before, none_before) = (chosen(s, field), none_chosen(s, field)); + set_choice(s, field, before, !none_before)?; + return done(s); } let value = match p.get("value") { None | Some(Value::Null) => None, Some(Value::String(v)) if !v.trim().is_empty() => Some(v.trim().to_string()), Some(_) => return Err(bad(C, "value is a non-empty string (or null to clear the field)")), }; + let Some(value) = value else { + set_choice(s, field, Vec::new(), false)?; + return done(s); + }; let before = chosen(s, field); - let on = value.as_ref().is_some_and(|v| before.iter().any(|b| b.eq_ignore_ascii_case(v))); - // the chosen values once the click is done - let next: Vec = match &value { - None => Vec::new(), - Some(v) if on => before.iter().filter(|b| !b.eq_ignore_ascii_case(v)).cloned().collect(), - Some(v) => before.iter().cloned().chain([v.clone()]).collect(), + let on = before.iter().any(|b| b.eq_ignore_ascii_case(&value)); + let (next, none) = if matches!(field, "flag" | "rating" | "kind" | "year") { + // one value: a second click clears it + (if on { Vec::new() } else { vec![value] }, false) + } else if on { + (before.into_iter().filter(|b| !b.eq_ignore_ascii_case(&value)).collect(), none_chosen(s, field)) + } else { + (before.into_iter().chain([value]).collect(), none_chosen(s, field)) }; - // a single-valued field keeps only the last value clicked; clicking it again clears it - let single = if on { None } else { value.clone() }; - if value.is_none() { - s.filter.facets.retain(|p| p.field != field); + set_choice(s, field, next, none)?; + done(s) +} + +/// Writes the choice on `field`: no value and no `none` clears it; one value goes in the dedicated field (`flag`, +/// `rating` exactly, `kind` or `merged`, `date`, the single list of camera, lens…), as the filter bar's other +/// controls read it; several go in `Filter::flags` (flag) or a `Filter::facets` entry (rating, kind, year, the facet +/// fields), with every other form cleared: the dedicated field would AND with the list. A camera, lens, keyword, +/// person or label pick with the no-value row keeps its values in the `Filter::facets` entry (the union). +fn set_choice(s: &mut Session, field: &str, values: Vec, none: bool) -> Result<()> { + const C: &str = "library.facetPick"; + let mut vals: Vec = Vec::new(); + for v in values { + let v = v.trim().to_string(); + if !v.is_empty() && !vals.iter().any(|o| o.eq_ignore_ascii_case(&v)) { + vals.push(v); + } } - match field { - // with the column's no-value row picked, the values go into the `Filter::facets` entry - // (which unites them with the photos without a value): the dedicated fields would AND - // with it and the union would come out empty - "camera" | "lens" | "keyword" | "person" | "label" if none_chosen(s, field) => { - let none = none_chosen(s, field); - s.filter.facets.retain(|p| p.field != field); - let pk = FacetPick { field: field.to_string(), values: next, none }; - if !pk.is_empty() { - s.filter.facets.push(pk); - } + if none && matches!(field, "flag" | "rating" | "kind" | "faces") { + return Err(bad(C, format!("every photo has a {field}: pick its value (flag none, rating 0, faces 0) instead"))); + } + let put = |f: &mut Filter, field: &str, values: Vec, none: bool| { + f.facets.retain(|p| p.field != field); + let pk = FacetPick { field: field.to_string(), values, none }; + if !pk.is_empty() { + f.facets.push(pk); } - "camera" => (s.filter.camera, s.filter.cameras) = (None, next), - "lens" => (s.filter.lens, s.filter.lenses) = (None, next), - "keyword" => (s.filter.keyword, s.filter.keywords) = (None, next), - "person" => (s.filter.person, s.filter.people) = (None, next), - "label" => { + }; + match field { + "camera" | "lens" | "keyword" | "person" | "label" => { let mut labels = Vec::new(); - for name in &next { - let Some(l) = ColorLabel::ALL.into_iter().find(|l| s.catalog.label_name(*l).eq_ignore_ascii_case(name)) else { - return Err(bad(C, format!("no colour label is named `{name}`"))); - }; - labels.push(l); + if field == "label" { + for name in &vals { + let Some(l) = ColorLabel::ALL.into_iter().find(|l| s.catalog.label_name(*l).eq_ignore_ascii_case(name)) else { + return Err(bad(C, format!("no colour label is named `{name}`"))); + }; + labels.push(l); + } + labels.sort(); + labels.dedup(); + } + let f = &mut s.filter; + match field { + "camera" => (f.camera, f.cameras) = (None, Vec::new()), + "lens" => (f.lens, f.lenses) = (None, Vec::new()), + "keyword" => (f.keyword, f.keywords) = (None, Vec::new()), + "person" => (f.person, f.people) = (None, Vec::new()), + _ => (f.label, f.labels) = (None, Vec::new()), + } + if none { + put(f, field, vals, true); + } else { + put(f, field, Vec::new(), false); + match field { + "camera" => f.cameras = vals, + "lens" => f.lenses = vals, + "keyword" => f.keywords = vals, + "person" => f.people = vals, + _ => f.labels = labels, + } } - labels.sort(); - labels.dedup(); - (s.filter.label, s.filter.labels) = (None, labels); } "flag" => { - s.filter.flag = match single.as_deref() { - None => None, - Some("pick") => Some(Flag::Pick), - Some("reject") => Some(Flag::Reject), - Some("none") => Some(Flag::None), - Some(other) => return Err(bad(C, format!("flag `{other}` is pick, reject or none"))), + let mut flags = Vec::new(); + for v in &vals { + flags.push(match v.to_ascii_lowercase().as_str() { + "pick" => Flag::Pick, + "reject" => Flag::Reject, + "none" => Flag::None, + other => return Err(bad(C, format!("flag `{other}` is pick, reject or none"))), + }); } + // the filmstrip's order: Picked, Unflagged, Rejected + flags.sort_by_key(|f| match f { + Flag::Pick => 0, + Flag::None => 1, + Flag::Reject => 2, + }); + let f = &mut s.filter; + (f.flag, f.flags) = if flags.len() == 1 { (flags.first().copied(), Vec::new()) } else { (None, flags) }; } - "rating" => match single { - None => (s.filter.rating, s.filter.rating_op) = (0, RatingOp::AtLeast), - Some(r) => { + "rating" => { + let mut ratings = Vec::new(); + for v in &vals { // 0: exactly unrated - let r: u8 = r.parse().ok().filter(|r| *r <= 5).ok_or_else(|| bad(C, format!("rating `{r}` is 0 (unrated) to 5")))?; - (s.filter.rating, s.filter.rating_op) = (r, RatingOp::Exactly); + ratings.push(v.parse::().ok().filter(|r| *r <= 5).ok_or_else(|| bad(C, format!("rating `{v}` is 0 (unrated) to 5")))?); } - }, + ratings.sort_unstable(); + let f = &mut s.filter; + f.facets.retain(|p| p.field != "rating"); + match ratings.as_slice() { + [] => (f.rating, f.rating_op) = (0, RatingOp::AtLeast), + [r] => (f.rating, f.rating_op) = (*r, RatingOp::Exactly), + _ => { + (f.rating, f.rating_op) = (0, RatingOp::AtLeast); + put(f, "rating", ratings.iter().map(u8::to_string).collect(), false); + } + } + } "kind" => { - s.filter.kind = match single.as_deref() { - None => None, - Some("image") => Some(MediaKind::Image), - Some("raw") => Some(MediaKind::Raw), - Some("video") => Some(MediaKind::Video), - Some(other) => return Err(bad(C, format!("kind `{other}` is image, raw or video"))), + let mut kinds = Vec::new(); + for v in &vals { + let known = ["image", "raw", "video", "hdr", "panorama", "hdrPanorama", "focusStack"]; + let Some(k) = known.into_iter().find(|k| k.eq_ignore_ascii_case(v)) else { + return Err(bad(C, format!("kind `{v}` is image, raw, video, hdr, panorama, hdrPanorama or focusStack"))); + }; + kinds.push(k.to_string()); + } + let f = &mut s.filter; + (f.kind, f.merged) = (None, None); + f.facets.retain(|p| p.field != "kind"); + match kinds.as_slice() { + [] => {} + [k] => match k.as_str() { + "image" => f.kind = Some(MediaKind::Image), + "raw" => f.kind = Some(MediaKind::Raw), + "video" => f.kind = Some(MediaKind::Video), + merged => f.merged = Some(merged.to_string()), + }, + _ => put(f, "kind", kinds, false), } } "year" => { - if single.as_ref().is_some_and(|y| y.len() != 4 || !y.chars().all(|c| c.is_ascii_digit())) { - return Err(bad(C, "year is four digits")); + if let Some(bad_date) = vals.iter().find(|y| !lcc_catalog::dates::valid_date_prefix(y)) { + return Err(bad(C, format!("date `{bad_date}` is YYYY, YYYY-MM or YYYY-MM-DD"))); } - s.filter.date = single; - (s.filter.date_from, s.filter.date_to) = (None, None); - } - // the fields picked through `Filter::facets`: several values, any of which matches - _ => { - let none = none_chosen(s, field); - s.filter.facets.retain(|p| p.field != field); - let pk = FacetPick { field: field.to_string(), values: next, none }; - if !pk.is_empty() { - s.filter.facets.push(pk); + vals.sort(); + let f = &mut s.filter; + f.date = None; + (f.date_from, f.date_to) = (None, None); + f.facets.retain(|p| p.field != "year"); + if none || vals.len() > 1 { + put(f, "year", vals, none); + } else { + f.date = vals.pop(); } } + // the fields picked through `Filter::facets`: several values, any of which matches + _ => put(&mut s.filter, field, vals, none), } - Ok(json!({"field": field, "chosen": chosen(s, field), "none": none_chosen(s, field), "count": s.visible().len()})) + Ok(()) } /// The values `field` takes for photo `p` (several for keywords and people; none when it has no value). @@ -260,7 +338,7 @@ fn values(s: &Session, field: &str, p: &Photo) -> Vec { /// Numeric fields sort by value; the rest by count, most first, then by name. fn numeric(field: &str) -> bool { - matches!(field, "rating" | "year" | "iso" | "focal" | "aperture" | "shutter" | "faces") + lcc_catalog::facets::is_numeric(field) } fn facets(s: &mut Session, p: &Value) -> Result { @@ -315,7 +393,30 @@ fn facets(s: &mut Session, p: &Value) -> Result { rows.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))); } let shown: Vec = rows.into_iter().take(limit).map(|(value, count)| json!({"value": value, "count": count})).collect(); - out.insert(field.clone(), json!({"photos": ids.len(), "none": none, "distinct": distinct, "values": shown, "chosen": chosen(s, field), "noneChosen": none_chosen(s, field)})); + let mut entry = json!({"photos": ids.len(), "none": none, "distinct": distinct, "values": shown, "chosen": chosen(s, field), "noneChosen": none_chosen(s, field)}); + if field == "year" { + let tree: Vec = lcc_catalog::date_groups_from(ids.iter().filter_map(|id| s.catalog.photo(*id).map(|p| &**p))) + .into_iter() + .map(|g| { + let months: Vec = g + .months + .into_iter() + .map(|(month, count)| { + let days: Vec = g + .days + .iter() + .filter(|(day, _)| day.starts_with(month.as_str())) + .map(|(day, count)| json!({"day": day, "count": count})) + .collect(); + json!({"month": month, "count": count, "days": days}) + }) + .collect(); + json!({"year": g.year, "count": g.count, "months": months}) + }) + .collect(); + entry["tree"] = Value::Array(tree); + } + out.insert(field.clone(), entry); } Ok(Value::Object(out)) } @@ -327,7 +428,7 @@ pub fn specs() -> Vec { "Pick Metadata Value", [], None, - "{field: a library.facets field, value?: a value as library.facets lists it (null: clear the field), none?: true (toggle the photos without a value)} → {field, chosen, none, count}: a Metadata filter column's click: flag, rating (exactly; 0 = unrated), kind and year take the one value, and a second click clears it; the other fields toggle the value among the chosen ones (any matches). `none` adds or removes the photos without a value (no camera, keyword, label, capture date, title…), which any chosen value also lets through", + "{field: a library.facets field, values?: [values as library.facets lists them], mode?: \"replace\" (choose exactly these) | \"toggle\" (add each, or remove it when chosen), value?: a value as library.facets lists it (null: clear the field), none?: true (toggle the photos without a value)} → {field, chosen, none, count}: a Metadata filter column's click: flag, rating (exactly; 0 = unrated), kind and year (YYYY, YYYY-MM or YYYY-MM-DD) take the one value, and a second click clears it; the other fields toggle the value among the chosen ones (any matches). `none` adds or removes the photos without a value (no camera, keyword, label, capture date, title…), which any chosen value also lets through", always, pick ), @@ -336,7 +437,7 @@ pub fn specs() -> Vec { "Metadata Facets", [], None, - "{fields?: [camera | lens | keyword | person | faces | label | flag | rating | kind | year | iso | focal | format | title | headline | caption | creator | copyright | location | city | country | aspect | preset | ai] (default: all), limit? (values per field, default 200, at most 2000)} → {: {photos, none, distinct, values: [{value, count}], chosen: [the values the filter picked], noneChosen}}. format: the file format (JPG, CR3, TIFF…); aspect: the developed aspect ratio (3:2, 4:5, 16:9…); preset: develop presets applied (from History); ai: AI tools in use (Denoise, Subject mask…); faces: how many face regions a photo has (0 when none). The values each field takes among the photos in view (the source, and the filter without that field's own constraint), with how many photos have each; `none`: photos without one. Counts by most photos first; rating, year, ISO, focal length and face count by value", + "{fields?: [camera | lens | keyword | person | faces | label | flag | rating | kind | year | iso | focal | format | title | headline | caption | creator | copyright | location | city | country | aspect | preset | ai] (default: all), limit? (values per field, default 200, at most 2000)} → {: {photos, none, distinct, values: [{value, count}], tree? (year only: [{year, count, months: [{month, count, days: [{day, count}]}]}]), chosen: [the values the filter picked], noneChosen}}. format: the file format (JPG, CR3, TIFF…); aspect: the developed aspect ratio (3:2, 4:5, 16:9…); preset: develop presets applied (from History); ai: AI tools in use (Denoise, Subject mask…); faces: how many face regions a photo has (0 when none). The values each field takes among the photos in view (the source, and the filter without that field's own constraint), with how many photos have each; `none`: photos without one. Counts by most photos first; rating, year, ISO, focal length and face count by value", always, facets ), diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 858f3ff4b0..c58f49b59d 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -286,14 +286,21 @@ pub fn specs() -> Vec { ), None => None, }; - // keywords not given: the renamed set's own, else the current nine - let keywords = if p.get("keywords").is_some() { - slots(&strs(p, "keywords")) - } else { - match renames.and_then(|at| s.keyword_sets.get(at)) { + // Validate every supplied slot before replacing or renaming the saved set. + let invalid_keywords = || bad("keyword.saveSet", "`keywords` must be a string, null or an array of strings"); + let keywords = match p.get("keywords") { + Some(Value::String(k)) => slots(std::slice::from_ref(k)), + Some(Value::Array(a)) => { + let typed = a.iter().map(|k| k.as_str().map(str::to_string).ok_or_else(invalid_keywords)).collect::>>()?; + slots(&typed) + } + Some(Value::Null) => Vec::new(), + Some(_) => return Err(invalid_keywords()), + // keywords not given: the renamed set's own, else the current nine + None => match renames.and_then(|at| s.keyword_sets.get(at)) { Some(x) => x.keywords.clone(), None => current_keywords(s), - } + }, }; let set = KeywordSet { name: name.clone(), keywords }; match renames { diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index bb5e0d68f7..14563e8c8a 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -6,7 +6,7 @@ use lcc_develop::DevelopSettings; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, ok, str_param}; -use crate::{LibrarySource, Result, Selection, Session}; +use crate::{CustomOrderSource, LibrarySource, Result, Selection, Session}; /// The selection after photos left the view (deleted, or rated, flagged or labelled out of it). /// Its callers end an open edit (a slider drag) before their own change, as moving to the next @@ -169,8 +169,10 @@ pub fn import_params(s: &Session, p: &Value) -> Result { local: bool_or(p, "local", false), preset_profile: bool_or(p, "presetProfile", false), keep_sidecars: false, + ignore_xmp: false, recipe: super::recipe_param(p, "library.import")?, import_duplicates: bool_or(p, "importDuplicates", false), + companions: p.get("companions").and_then(Value::as_bool), plugin_hooks: bool_or(p, "pluginHooks", true), }; let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); @@ -264,18 +266,42 @@ fn strs(p: &Value, key: &str) -> Vec { } /// The regular album the library shows, if any (the one Custom Order sorts). -fn custom_album(s: &Session) -> Option { - match s.source { - crate::LibrarySource::Album(a) if s.catalog.has_custom_order(a) => Some(a), +fn shown_album(s: &Session) -> Option { + match s.custom_order_source() { + Some(CustomOrderSource::Album(a)) => Some(a), _ => None, } } -/// The album's photos in the order the user sees them: its Custom Order, or — while the album is -/// shown in another sort — the shown photos first, in the grid's order, then the rest. -fn shown_order(s: &mut Session, a: AlbumId) -> Vec { - let saved = s.catalog.album_photo_order(a); - if custom_album(s) != Some(a) || s.sort.key == SortKey::Custom { +/// `t`'s photos in the Custom Order it has now, shown or not: the ones set by hand, then the rest. +fn saved_order(s: &Session, t: &CustomOrderSource) -> Vec { + match t { + CustomOrderSource::Album(a) => s.catalog.album_photo_order(*a), + CustomOrderSource::Folder(path) => s.catalog.folder_photo_order(path), + } +} + +/// Whether `t` has a Custom Order of its own yet: one set by hand. +fn has_own_order(s: &Session, t: &CustomOrderSource) -> bool { + match t { + CustomOrderSource::Album(a) => s.catalog.album(*a).is_some_and(|al| !al.photo_order.is_empty()), + CustomOrderSource::Folder(path) => s.catalog.folder_record(path).is_some_and(|r| !r.photo_order.is_empty()), + } +} + +/// The op that gives `t` the Custom Order `order`. +fn order_op(s: &Session, t: &CustomOrderSource, order: Vec) -> Op { + match t { + CustomOrderSource::Album(a) => Op::SetAlbumPhotoOrder { id: *a, order }, + CustomOrderSource::Folder(path) => s.catalog.folder_photo_order_op(path, order), + } +} + +/// The album's or the folder's photos in the order the user sees them: its Custom Order, or — +/// while it is shown in another sort — the shown photos first, in the grid's order, then the rest. +fn shown_order(s: &mut Session, t: &CustomOrderSource) -> Vec { + let saved = saved_order(s, t); + if s.custom_order_source().as_ref() != Some(t) || s.sort.key == SortKey::Custom { return saved; } let members: std::collections::HashSet = saved.iter().copied().collect(); @@ -285,17 +311,17 @@ fn shown_order(s: &mut Session, a: AlbumId) -> Vec { out } -/// `ids` for an ordering command: album members, repeats dropped; an id not in the album is an error. -fn order_ids(s: &Session, a: AlbumId, p: &Value, c: &str) -> Result> { +/// `ids` for an ordering command: photos of the album or the folder, repeats dropped; any other +/// id is an error. +fn order_ids(s: &Session, t: &CustomOrderSource, p: &Value, c: &str) -> Result> { let Some(raw) = p.get("ids").and_then(Value::as_array) else { return Err(bad(c, "missing `ids` (an array of photo ids)")) }; - let al = s.catalog.album(a).ok_or_else(|| bad(c, "no such collection"))?; - let members: std::collections::HashSet = al.photos.iter().copied().collect(); + let members: std::collections::HashSet = saved_order(s, t).into_iter().collect(); let mut seen = std::collections::HashSet::new(); let mut out = Vec::new(); for v in raw { let id = v.as_u64().map(PhotoId).ok_or_else(|| bad(c, "`ids` must be photo ids"))?; if !members.contains(&id) { - return Err(bad(c, format!("photo {} is not in the collection", id.0))); + return Err(bad(c, format!("photo {} is not in the {}", id.0, t.noun()))); } if seen.insert(id) { out.push(id); @@ -304,17 +330,107 @@ fn order_ids(s: &Session, a: AlbumId, p: &Value, c: &str) -> Result Ok(out) } -/// Saves the album's Custom Order (one undo step) and sorts the view by it when it's shown. -fn set_custom_order(s: &mut Session, a: AlbumId, order: Vec, label: &str) -> Result { - if s.catalog.album(a).is_some_and(|al| al.photo_order != order) { - s.commit(label, Op::SetAlbumPhotoOrder { id: a, order: order.clone() })?; +/// Saves the album's or the folder's Custom Order (one undo step) and sorts the view by it when +/// it's shown. +fn set_custom_order(s: &mut Session, t: &CustomOrderSource, order: Vec, label: &str) -> Result { + // the album's order as it is kept against the new one; a folder's as it stands (what it would + // show), so an id of a photo the folder no longer holds isn't a change of its own + let changed = match t { + CustomOrderSource::Album(a) => s.catalog.album(*a).is_some_and(|al| al.photo_order != order), + CustomOrderSource::Folder(_) => saved_order(s, t) != order, + }; + if changed { + s.commit(label, order_op(s, t, order.clone()))?; } - if custom_album(s) == Some(a) && s.sort.key != SortKey::Custom { + if s.custom_order_source().as_ref() == Some(t) && s.sort.key != SortKey::Custom { s.sort = Sort { key: SortKey::Custom, ascending: true, ..s.sort }; } Ok(json!({"order": order.iter().map(|x| x.0).collect::>()})) } +/// `folder` for a folder's ordering command: the path given, or the folder shown that can have a +/// Custom Order. +fn folder_order_param(s: &Session, p: &Value, c: &str) -> Result { + let path = match p.get("folder") { + Some(Value::String(path)) => path.clone(), + None | Some(Value::Null) => match s.custom_order_source() { + Some(CustomOrderSource::Folder(path)) => path, + Some(CustomOrderSource::Album(_)) => return Err(bad(c, "missing `folder` (a collection is shown, not a folder)")), + None if s.source == LibrarySource::LibraryFolder && s.folder_subfolders => { + return Err(bad( + c, + "missing `folder`: the folder shown takes in the photos of the folders inside it, which have no one order (show it on its own: library.showSubfolderPhotos {on: false})", + )); + } + None => return Err(bad(c, "missing `folder` (no folder is shown)")), + }, + Some(_) => return Err(bad(c, "`folder` must be the path of a folder (as library.folders lists it)")), + }; + // it names a folder, and the library holds photos directly in it + check_folder_order(s, &path, c)?; + Ok(path) +} + +/// The folder `path` can have its photos put in Custom Order: it names a folder, and the library +/// holds photos directly in it (the folders inside it are folders of their own). +fn check_folder_order(s: &Session, path: &str, c: &str) -> Result<()> { + if !lcc_catalog::folders::folder_has_custom_order(path) { + return Err(bad(c, format!("{path:?} is not a folder (give the path of a folder from library.folders)"))); + } + if s.catalog.folder_photo_order(path).is_empty() { + return Err(bad(c, format!("{path}: no photo in the catalog was imported directly from it"))); + } + Ok(()) +} + +/// The body of `album.orderPhotos` and `folder.orderPhotos`: the photos `ids` names, in their +/// order, before `before` (to the end without it) in `t`'s Custom Order. +fn order_photos(s: &mut Session, p: &Value, c: &str, t: &CustomOrderSource) -> Result { + // `before` means "left of it in the grid": a descending Custom Order shows the saved order + // reversed, so the drop is worked out on the shown list and saved back in forward order + let shown = s.custom_order_source().as_ref() == Some(t); + let reversed = shown && s.sort.key == SortKey::Custom && !s.sort.ascending; + let mut base = shown_order(s, t); + if reversed { + base.reverse(); + } + let moved = order_ids(s, t, p, c)?; + if moved.is_empty() { + return Err(bad(c, "missing `ids`")); + } + let before = match p.get("before") { + None | Some(Value::Null) => None, + Some(v) => { + let b = v.as_u64().map(PhotoId).ok_or_else(|| bad(c, "`before` must be a photo id or null"))?; + if !base.contains(&b) { + return Err(bad(c, format!("photo {} is not in the {}", b.0, t.noun()))); + } + Some(b) + } + }; + // the moved photos keep their order among themselves + let moving: std::collections::HashSet = moved.iter().copied().collect(); + let in_order: Vec = base.iter().copied().filter(|x| moving.contains(x)).collect(); + // dropping before one of the moved photos: before the first photo after it that stays + let anchor = before.and_then(|b| base.iter().skip_while(|x| **x != b).find(|x| !moving.contains(x)).copied()); + let mut order: Vec = base.iter().copied().filter(|x| !moving.contains(x)).collect(); + let at = anchor.and_then(|b| order.iter().position(|x| *x == b)).unwrap_or(order.len()); + order.splice(at..at, in_order); + if reversed { + order.reverse(); + } + set_custom_order(s, t, order, "Move in Custom Order") +} + +/// The body of `album.setPhotoOrder` and `folder.setPhotoOrder`: `ids` as the Custom Order, the +/// photos they don't name following in the order they have now. +fn set_photo_order(s: &mut Session, p: &Value, c: &str, t: &CustomOrderSource) -> Result { + let mut order = order_ids(s, t, p, c)?; + let listed: std::collections::HashSet = order.iter().copied().collect(); + order.extend(saved_order(s, t).into_iter().filter(|x| !listed.contains(x))); + set_custom_order(s, t, order, "Set Custom Order") +} + /// 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 @@ -472,6 +588,17 @@ fn step(s: &mut Session, d: isize) -> Result { /// NOTES-1028 note 16): in the view's order, the selection kept, wrapping round; the photos between are skipped. /// ↑ / ↓ and Auto Advance step through the view. fn step_in(s: &mut Session, d: isize, within: bool) -> Result { + step_from(s, d, within, false) +} + +/// ↑ / ↓ (`library.up` / `library.down`): a step with no photo active takes the view's last photo for a downward step +/// and its first for an upward one (F-66C0), whatever the row distance. +fn step_vertical(s: &mut Session, d: isize) -> Result { + step_from(s, d, false, d > 0) +} + +/// [`step_in`]; `from_end` (only with no photo active) lands on the view's last photo rather than its first. +fn step_from(s: &mut Session, d: isize, within: bool, from_end: bool) -> Result { let vis = s.visible_cloned(); if vis.is_empty() { return ok(); @@ -499,6 +626,7 @@ fn step_in(s: &mut Session, d: isize, within: bool) -> Result { } let next = match cur { Some(i) => (i as isize + d).clamp(0, vis.len() as isize - 1) as usize, + None if from_end => vis.len().saturating_sub(1), None => 0, }; s.end_interaction()?; @@ -1123,7 +1251,7 @@ pub fn specs() -> Vec { "Sort", ["View", "Sort"], None, - "{key?: captureDate|importDate|editDate|fileName|rating|fileSize|random|custom (Custom Order: a regular album's order set by hand)|quality (the Image Quality Scanner's score; unscanned photos first ascending, last descending), ascending?: bool, group?: auto|none|day|month|year, seed?: u64 (the shuffle `random` gives)}", + "{key?: captureDate|importDate|editDate|fileName|rating|fileSize|random|custom (Custom Order: the order set by hand in a regular collection, or in one folder of the Folders panel shown as its own photos: nothing below it, or Show Photos in Subfolders off)|quality (the Image Quality Scanner's score; unscanned photos first ascending, last descending), ascending?: bool, group?: auto|none|day|month|year, seed?: u64 (the shuffle `random` gives)}", always, |s, p| { let key: SortKey = match p.get("key") { @@ -1138,13 +1266,20 @@ pub fn specs() -> Vec { let explicit = p.get("seed").is_some_and(|v| !v.is_null()); let mut ascending = bool_or(p, "ascending", s.sort.ascending); if key == SortKey::Custom && s.sort.key != SortKey::Custom { - let Some(a) = custom_album(s) else { - return Err(bad("library.sort", "Custom Order sorts a regular collection: open one first")); + let Some(t) = s.custom_order_source() else { + return Err(bad( + "library.sort", + if s.source == LibrarySource::LibraryFolder && s.folder_subfolders { + "Custom Order sorts a folder's own photos, and the folder shown takes in the photos of the folders inside it: show it on its own (library.showSubfolderPhotos {on: false})" + } else { + "Custom Order sorts a regular collection or one folder of the Folders panel: open one first" + }, + )); }; // no order of its own yet: it starts from what is shown now - if s.catalog.album(a).is_some_and(|al| al.photo_order.is_empty()) { - let order = shown_order(s, a); - s.commit("Custom Order", Op::SetAlbumPhotoOrder { id: a, order })?; + if !has_own_order(s, &t) { + let order = shown_order(s, &t); + s.commit("Custom Order", order_op(s, &t, order))?; } ascending = bool_or(p, "ascending", true); } @@ -1369,8 +1504,12 @@ pub fn specs() -> Vec { select_by ), cmd!("library.selectNone", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", always, |s, _| { - let a = s.selection.active; - s.selection = Selection { ids: a.into_iter().collect(), active: a }; + // nothing selected and no active photo: the arrows then start again from the view's ends (F-66C0) + s.end_interaction()?; + s.selection = Selection::default(); + s.all_selected = None; + s.active_mask = None; + s.active_spot = None; ok() }), cmd!( @@ -1420,15 +1559,17 @@ pub fn specs() -> Vec { "Deselect Unflagged Photos", ["Edit"], None, - "{}: keeps only the flagged (picked) photos of the selection selected; with none flagged it acts as Deselect All (the active photo stays) → {selected}", + "{}: keeps only the flagged (picked) photos of the selection selected; with none flagged it deselects everything, the active photo included → {selected}", always, |s, _| { let keep: Vec = s.selection.ids.iter().copied().filter(|id| s.catalog.photo(*id).is_some_and(|ph| ph.flag == Flag::Pick)).collect(); if keep.is_empty() { - let a = s.selection.active; - s.selection = Selection { ids: a.into_iter().collect(), active: a }; + s.end_interaction()?; + s.selection = Selection::default(); s.all_selected = None; + s.active_mask = None; + s.active_spot = None; return Ok(json!({"selected": s.selection.ids.len()})); } let active = s.selection.active.filter(|a| keep.contains(a)).or(keep.first().copied()); @@ -1481,7 +1622,7 @@ pub fn specs() -> Vec { Some("Down"), "{rows?: n (photos to move forward; default 1, the grid passes the distance to the cell below)}", always, - |s, p| { step(s, row_step(p)) } + |s, p| { step_vertical(s, row_step(p)) } ), cmd!( "library.up", @@ -1490,7 +1631,7 @@ pub fn specs() -> Vec { Some("Up"), "{rows?: n (photos to move back; default 1, the grid passes the distance to the cell above)}", always, - |s, p| { step(s, -row_step(p)) } + |s, p| { step_vertical(s, -row_step(p)) } ), // ---- rating / flags / labels cmd!( @@ -2374,44 +2515,12 @@ pub fn specs() -> Vec { const C: &str = "album.orderPhotos"; let a = match opt_album_param(p, "album", C)? { Some(a) => a, - None => custom_album(s).ok_or_else(|| bad(C, "missing `album` (no album is shown)"))?, + None => shown_album(s).ok_or_else(|| bad(C, "missing `album` (no album is shown)"))?, }; if !s.catalog.has_custom_order(a) { return Err(bad(C, "only regular collections have a custom order")); } - // `before` means "left of it in the grid": a descending Custom Order shows the saved order - // reversed, so the drop is worked out on the shown list and saved back in forward order - let reversed = custom_album(s) == Some(a) && s.sort.key == SortKey::Custom && !s.sort.ascending; - let mut base = shown_order(s, a); - if reversed { - base.reverse(); - } - let moved = order_ids(s, a, p, C)?; - if moved.is_empty() { - return Err(bad(C, "missing `ids`")); - } - let before = match p.get("before") { - None | Some(Value::Null) => None, - Some(v) => { - let b = v.as_u64().map(PhotoId).ok_or_else(|| bad(C, "`before` must be a photo id or null"))?; - if !base.contains(&b) { - return Err(bad(C, format!("photo {} is not in the collection", b.0))); - } - Some(b) - } - }; - // the moved photos keep their order among themselves - let moving: std::collections::HashSet = moved.iter().copied().collect(); - let in_order: Vec = base.iter().copied().filter(|x| moving.contains(x)).collect(); - // dropping before one of the moved photos: before the first photo after it that stays - let anchor = before.and_then(|b| base.iter().skip_while(|x| **x != b).find(|x| !moving.contains(x)).copied()); - let mut order: Vec = base.iter().copied().filter(|x| !moving.contains(x)).collect(); - let at = anchor.and_then(|b| order.iter().position(|x| *x == b)).unwrap_or(order.len()); - order.splice(at..at, in_order); - if reversed { - order.reverse(); - } - set_custom_order(s, a, order, "Move in Custom Order") + order_photos(s, p, C, &CustomOrderSource::Album(a)) } ), cmd!( @@ -2427,10 +2536,37 @@ pub fn specs() -> Vec { if !s.catalog.has_custom_order(a) { return Err(bad(C, "only regular collections have a custom order")); } - let mut order = order_ids(s, a, p, C)?; - let listed: std::collections::HashSet = order.iter().copied().collect(); - order.extend(s.catalog.album_photo_order(a).into_iter().filter(|x| !listed.contains(x))); - set_custom_order(s, a, order, "Set Custom Order") + set_photo_order(s, p, C, &CustomOrderSource::Album(a)) + } + ), + cmd!( + "folder.orderPhotos", + "Move in Custom Order", + [], + None, + "{folder?: path (default: the folder shown), ids: [photoIds], before?: photoId (default: to the end)}: moves the photos, in their current order, before `before` in the Custom Order of the folder's own photos (issue #1583: the photos the library holds directly in it, see library.folders; the order follows the folder when it is renamed or moved); sorts the view by Custom Order when that folder is shown on its own. A folder shown with the photos of the folders inside it has no one order: library.showSubfolderPhotos {on: false} shows it on its own → {order}", + always, + |s, p| { + const C: &str = "folder.orderPhotos"; + let folder = folder_order_param(s, p, C)?; + order_photos(s, p, C, &CustomOrderSource::Folder(folder)) + } + ), + cmd!( + "folder.setPhotoOrder", + "Set Custom Order", + [], + None, + "{folder: path, ids: [photoIds]}: the Custom Order of the folder's own photos (issue #1583; repeats ignored, the photos not listed follow in their current order); one undo step. The order is kept with the folder and follows it when it is renamed or moved → {order}", + always, + |s, p| { + const C: &str = "folder.setPhotoOrder"; + let folder = match p.get("folder") { + Some(Value::String(path)) => path.clone(), + _ => return Err(bad(C, "missing `folder` (the path of a folder from library.folders)")), + }; + check_folder_order(s, &folder, C)?; + set_photo_order(s, p, C, &CustomOrderSource::Folder(folder)) } ), cmd!( @@ -2783,7 +2919,7 @@ pub fn specs() -> Vec { "Review Import", [], None, - "{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned, scanLimited: bool (the folder walk stopped at its scan limit: there may be more photos), skipped: {unreadable (folders that could not be listed), unsupported (files in the folders that are not a supported photo type, XMP sidecars not counted; a file named in paths is always tried)}}: nothing is added", + "{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview, companionOf?: the raw beside it (a JPEG the setting takes as its raw's companion: shown with the raw, not as a photo of its own)}], duplicates, scanned, scanLimited: bool (the folder walk stopped at its scan limit: there may be more photos), skipped: {unreadable (folders that could not be listed), unsupported (files in the folders that are not a supported photo type, XMP sidecars not counted; a file named in paths is always tried)}}: nothing is added", always, |s, p| { let paths = strs(p, "paths"); @@ -2806,7 +2942,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} {caption} {headline} {category} {keywords} {copyright} {job_title} {location} {city} {state} {country} {serial} {alt_text} {extended_description} {description_writer} {shutter} {aperture} {focal} {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, presetProfile?: bool (a preset's camera profile replaces the raw's; default false: each raw keeps its body's camera profile through the presets), presets?: [presetId] (a stack applied in order after `preset`, one History step each; a browsed photo joining the library gets the presets, keywords and metadata preset too, on top of its own culling and edits, and copied or moved its record follows its file), recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has (a duplicate, one restored from Recently Deleted, one joined from a browsed folder) is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], cameraProfile?: auto (default: each body's own camera profile, else the camera's default) | {all: camera profile id} (every raw of that profile's camera) | {perBody: {body (as profiles.bodies lists it): camera profile id}}, for this import only; a raw whose XMP sidecar sets develop settings keeps its own, 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), importDuplicates?: bool (false by default = Lightroom's Don't Import Suspected Duplicates: a file whose content the library already has is skipped; true imports it as a new photo; a path already in the library, or a photo in Recently Deleted, is still handled as above)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, skipped: {unreadable, unsupported} (what the folder walk left out, as library.importPreview counts it; a file named in paths is always tried, so it is never counted here), 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} {caption} {headline} {category} {keywords} {copyright} {job_title} {location} {city} {state} {country} {serial} {alt_text} {extended_description} {description_writer} {shutter} {aperture} {focal} {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, presetProfile?: bool (a preset's camera profile replaces the raw's; default false: each raw keeps its body's camera profile through the presets), presets?: [presetId] (a stack applied in order after `preset`, one History step each; a browsed photo joining the library gets the presets, keywords and metadata preset too, on top of its own culling and edits, and copied or moved its record follows its file), recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has (a duplicate, one restored from Recently Deleted, one joined from a browsed folder) is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], cameraProfile?: auto (default: each body's own camera profile, else the camera's default) | {all: camera profile id} (every raw of that profile's camera) | {perBody: {body (as profiles.bodies lists it): camera profile id}}, for this import only; a raw whose XMP sidecar sets develop settings keeps its own, 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), importDuplicates?: bool (false by default = Lightroom's Don't Import Suspected Duplicates: a file whose content the library already has is skipped; true imports it as a new photo; a path already in the library, or a photo in Recently Deleted, is still handled as above), companions?: bool (treat JPEGs next to raw files as companions of the raw, issue #1692: a JPEG with a raw's name beside it is not a photo of its own but the raw's (one thumbnail, one face scan, one set of metadata), and travels with it through copy / move and rename; a raw the library already has is pointed at the JPEG; default = the library's setting, catalog.settings' rawJpegCompanions, on like Lightroom Classic's; a file with a browsed record always joins as its own photo)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], companions?: [{path, raw?}] (JPEGs taken as their raw's companions), restored?: [photoId], failed, skipped: {unreadable, unsupported} (what the folder walk left out, as library.importPreview counts it; a file named in paths is always tried, so it is never counted here), 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/manage.rs b/crates/engine/src/cmd/manage.rs index b2d07dbf3e..d8ede10b4c 100644 --- a/crates/engine/src/cmd/manage.rs +++ b/crates/engine/src/cmd/manage.rs @@ -294,7 +294,7 @@ pub fn specs() -> Vec { cmd!(query "photo.renameTokens", "Rename Template Tags", [], None, "{} → {tokens: [{tag, aliases, meaning, example}], dateDirectives: [{directive, meaning}], notes: [..], sample}: the file-name template tags shared by photo.rename, library.import (rename) and app.export (naming); examples are for a sample photo", always, |_, _| { Ok(crate::rename::token_help_json()) }), - cmd!(query "photo.renamePreview", "Rename Preview", [], None, "{template: e.g. `{date}_{name}`, `Trip-{seq:3}` (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {caption} {headline} {category} {keywords} {copyright} {job_title} {location} {city} {state} {country} {serial} {alt_text} {extended_description} {description_writer} {shutter} {aperture} {focal} {ext} {text:Label}; photo.renameTokens explains each), start?: first sequence number (1), texts?: {label: text} (what each {text:Label} becomes), ids?}: renames the files on disk (sidecars too, never overwriting: collisions get -1, -2…); undoable", has_selection, |s, p| { + cmd!(query "photo.renamePreview", "Rename Preview", [], None, "{template: e.g. `{date}_{name}`, `Trip-{seq:3}` (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {caption} {headline} {category} {keywords} {copyright} {job_title} {location} {city} {state} {country} {serial} {alt_text} {extended_description} {description_writer} {shutter} {aperture} {focal} {ext} {text:Label}; photo.renameTokens explains each), start?: first sequence number (1), texts?: {label: text} (what each {text:Label} becomes), ids?}: renames the files on disk (sidecars too, and a raw's companion JPEG follows its raw's new name; never overwriting: collisions get -1, -2…); undoable", has_selection, |s, p| { let (ids, template, start) = rename_args(s, p, "photo.renamePreview", false)?; Ok(serde_json::to_value(s.plan_rename(&ids, &template, start)).unwrap_or_default()) }), @@ -303,7 +303,7 @@ pub fn specs() -> Vec { "Rename Photos", [], None, - "{template: e.g. `{date}_{name}`, `Trip-{seq:3}` (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {caption} {headline} {category} {keywords} {copyright} {job_title} {location} {city} {state} {country} {serial} {alt_text} {extended_description} {description_writer} {shutter} {aperture} {focal} {ext} {text:Label}; photo.renameTokens explains each), start?: first sequence number (1), texts?: {label: text} (what each {text:Label} becomes), ids?}: renames the files on disk (sidecars too, never overwriting: collisions get -1, -2…); undoable", + "{template: e.g. `{date}_{name}`, `Trip-{seq:3}` (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {caption} {headline} {category} {keywords} {copyright} {job_title} {location} {city} {state} {country} {serial} {alt_text} {extended_description} {description_writer} {shutter} {aperture} {focal} {ext} {text:Label}; photo.renameTokens explains each), start?: first sequence number (1), texts?: {label: text} (what each {text:Label} becomes), ids?}: renames the files on disk (sidecars too, and a raw's companion JPEG follows its raw's new name; never overwriting: collisions get -1, -2…); undoable", has_selection, |s, p| { let (ids, template, start) = rename_args(s, p, "photo.rename", true)?; diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs index 7bfa3718da..5d3281d66c 100644 --- a/crates/engine/src/cmd/metadata.rs +++ b/crates/engine/src/cmd/metadata.rs @@ -93,9 +93,11 @@ pub fn apply_to(m: &mut Meta, fields: &Value) { m.copyright_status = st; } } else if k == "keywords" { + let mut seen: std::collections::HashSet = m.keywords.iter().map(|k| k.to_lowercase()).collect(); for kw in v.as_array().into_iter().flatten().filter_map(Value::as_str) { - if !m.keywords.iter().any(|x| x.eq_ignore_ascii_case(kw)) { - m.keywords.push(kw.to_string()); + let kw = lcc_catalog::keywords::clean(kw); + if !kw.is_empty() && seen.insert(kw.to_lowercase()) { + m.keywords.push(kw); } } } else if let (Some(f), Some(l)) = (list_field(m, k), text_list(v)) { diff --git a/crates/engine/src/cmd/preset_files.rs b/crates/engine/src/cmd/preset_files.rs index 220bcd134b..3d4d606554 100644 --- a/crates/engine/src/cmd/preset_files.rs +++ b/crates/engine/src/cmd/preset_files.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use super::mask_effect_files as mef; use super::{CommandSpec, always, bad, cmd, str_param}; use crate::preset_import::{group_from_dir, read_presets}; -use crate::presets::{LCPRESET_EXT, expand_preset_paths, to_lcpreset}; +use crate::presets::{LCPRESET_EXT, expand_preset_paths_with_seen, to_lcpreset}; use crate::{Result, Session}; fn strings(p: &Value, key: &str) -> Option> { @@ -28,9 +28,10 @@ fn import(s: &mut Session, p: &Value) -> Result { let mut export_found = Vec::new(); // every file's presets, added in one go below (adding one at a time indexed the library each time) let mut pending: Vec<(lcc_develop::Preset, Value)> = Vec::new(); + let mut seen_dirs = std::collections::HashSet::new(); for top in &paths { let from_dir = std::path::Path::new(top).is_dir(); - for f in expand_preset_paths(std::slice::from_ref(top)) { + for f in expand_preset_paths_with_seen(std::slice::from_ref(top), &mut seen_dirs) { // presets in a folder go to a group named after it (unless the file names its own) // the path from the imported folder (inclusive) to the file's folder let base = std::path::Path::new(top).parent().unwrap_or(std::path::Path::new("")); @@ -136,13 +137,18 @@ fn export(s: &mut Session, p: &Value) -> Result { if path.extension().is_none() { path.set_extension(LCPRESET_EXT); } - let ids = strings(p, "ids"); + let invalid_ids = || bad("preset.export", "`ids` must be an array of preset IDs"); + let ids = match p.get("ids") { + None | Some(Value::Null) => None, + Some(Value::Array(ids)) => Some(ids.iter().map(|id| id.as_str().ok_or_else(invalid_ids)).collect::>>()?), + Some(_) => return Err(invalid_ids()), + }; let group = str_param(p, "group"); let chosen: Vec<_> = s .presets .iter() .filter(|x| match (&ids, group) { - (Some(ids), _) => ids.contains(&x.id), + (Some(ids), _) => ids.contains(&x.id.as_str()), (None, Some(g)) => x.group == g, (None, None) => !x.builtin, }) diff --git a/crates/engine/src/cmd/profile_manager.rs b/crates/engine/src/cmd/profile_manager.rs index e6600da115..3de71ec69b 100644 --- a/crates/engine/src/cmd/profile_manager.rs +++ b/crates/engine/src/cmd/profile_manager.rs @@ -706,6 +706,8 @@ mod tests { fn camera_profiles_can_be_hidden() { let mut s = Session::with_demo(); // a bundled calibration of a camera of its own (the registry is process-wide: add one and take it out again) + // (under the lock: another test's save-and-restore of the registry would otherwise drop or revive this entry) + let _lock = crate::camera_profiles::test_library_lock(); let dcp = std::sync::Arc::new(lcc_raw::dcp::Dcp { model: "PMHIDE ONE".into(), name: "Hide Me".into(), diff --git a/crates/engine/src/cmd/update.rs b/crates/engine/src/cmd/update.rs index 18d005c049..2532ea2e65 100644 --- a/crates/engine/src/cmd/update.rs +++ b/crates/engine/src/cmd/update.rs @@ -23,6 +23,10 @@ fn check(s: &mut Session, p: &Value) -> Result { if p.get("feed").is_some() { return Err(bad(C, "`feed` is not a parameter: the app reads only its own release feed")); } + if crate::update::disabled_by_env() { + let var = lcc_brand::env_var(crate::update::DISABLE_ENV); + return Err(bad(C, format!("updates are disabled ({var} is set); your package manager handles updates"))); + } let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false); if wait && !s.updater.checking() { s.updater.check_now(); diff --git a/crates/engine/src/crs.rs b/crates/engine/src/crs.rs index ff0613711e..b506ded0ec 100644 --- a/crates/engine/src/crs.rs +++ b/crates/engine/src/crs.rs @@ -42,9 +42,14 @@ impl Target { /// `fileFormat` name) shot on `camera` (Exif make and model as the catalog keeps them, or /// empty when unknown); `preview_only` for a raw that can't be decoded yet. pub fn for_file(kind: lcc_catalog::MediaKind, format: &str, preview_only: bool, camera: &str) -> Target { + Target::for_file_as(kind, format, preview_only, camera, "") + } + /// [`Target::for_file`] for a photo whose camera-profile choice (`profile.camera`) is `choice`: the choice decides + /// whether the raw is developed in Kelvin or relative to its as-shot look ([`lcc_catalog::relative_wb_camera_as`]). + pub fn for_file_as(kind: lcc_catalog::MediaKind, format: &str, preview_only: bool, camera: &str, choice: &str) -> Target { if kind != lcc_catalog::MediaKind::Raw || preview_only { Target::Rendered - } else if lcc_catalog::relative_wb_camera(format, camera) { + } else if lcc_catalog::relative_wb_camera_as(format, camera, choice) { Target::RawRelative } else { Target::RawAbsolute @@ -54,6 +59,10 @@ impl Target { pub fn for_photo(p: &lcc_catalog::Photo) -> Target { Target::for_file(p.kind, &p.format, p.preview_only.is_some(), &p.meta.camera) } + /// The target for a photo in the catalog once its camera-profile choice is `choice`. + pub fn for_photo_as(p: &lcc_catalog::Photo, choice: &str) -> Target { + Target::for_file_as(p.kind, &p.format, p.preview_only.is_some(), &p.meta.camera, choice) + } } /// Band names as they appear in `crs:` field names, in our mixer order. @@ -390,9 +399,14 @@ pub fn to_partial(props: &Props, target: Target) -> Value { n(o, "ParametricMidtoneSplit", "curve.split_mid"); n(o, "ParametricHighlightSplit", "curve.split_highlights"); n(o, "CurveRefineSaturation", "curve.refine_saturation"); + // Under the older process versions an untouched photo's curve is the one named "Medium + // Contrast", as Contrast 25, Blacks 5 and Brightness 50 are its sliders' defaults (read + // relative to them above): it is no edit, and our rendering has its own base contrast, so it + // is not applied. A changed curve is named otherwise ("Custom", "Strong Contrast"). + let old_default_curve = first(props, "crs:ToneCurveName").is_some_and(|n| n.eq_ignore_ascii_case("Medium Contrast")); if let Some(c) = curve(props, "crs:ToneCurve").filter(|c| c.as_array().is_some_and(|a| !a.is_empty())) { // the older single curve, used when no 2012 curve is present - if !props.contains_key("crs:ToneCurvePV2012") { + if !props.contains_key("crs:ToneCurvePV2012") && !old_default_curve { put(o, "curve.master", c); } } @@ -430,7 +444,13 @@ pub fn to_partial(props: &Props, target: Target) -> Value { n(o, "SplitToningBalance", "grading.balance"); // ---- Detail - n(o, "Sharpness", "detail.sharpen_amount"); + // An older process version's raw sharpening default (25) is an untouched photo's, like its + // tone sliders' defaults above: the photo keeps our own raw default. (Rendered files defaulted + // to 0 there, and 25 under the 2012 process is a choice: both are read as written.) + let raw = matches!(target, Target::RawAbsolute | Target::RawRelative); + if !(raw && !pv2012 && num(props, "crs:Sharpness") == Some(25.0)) { + n(o, "Sharpness", "detail.sharpen_amount"); + } n(o, "SharpenRadius", "detail.sharpen_radius"); n(o, "SharpenDetail", "detail.sharpen_detail"); n(o, "SharpenEdgeMasking", "detail.sharpen_masking"); @@ -617,12 +637,36 @@ pub fn to_partial_report(props: &Props, values: Option<&crate::crs_masks::Values // Point Color slots that are all empty (-1) let value_is = |k: &str, f: &dyn Fn(&[String]) -> bool| props.get(&format!("crs:{k}")).is_some_and(|v| f(v)); let empty_points = |v: &[String]| v.iter().all(|s| s.split(',').all(|n| n.trim().parse::().is_ok_and(|x| x == -1.0) || n.trim().is_empty())); + // a channel curve that is the identity: ascending points from x = 0 to 255, each with y == x (upstream #4747) + let identity_curve = |v: &[String]| { + let mut previous = None; + for point in v { + let Some((x, y)) = point.split_once(',') else { return false }; + let (Ok(x), Ok(y)) = (x.trim().parse::(), y.trim().parse::()) else { + return false; + }; + let ascending = match previous { + None => x == 0.0, + Some(prior) => x > prior, + }; + if !ascending || !(0.0..=255.0).contains(&x) || x != y { + return false; + } + previous = Some(x); + } + previous == Some(255.0) + }; let quiet = |k: &str| { k.starts_with("Enable") || k.starts_with("ToneCurveName") || k == "AutoTone" || k == "AutoGrayscaleMix" + || k == "AutoWhiteVersion" || (k == "PointColors" && value_is(k, &empty_points)) + // inactive legacy optics fields at zero, and identity channel curves (upstream #4747) + || (matches!(k, "ChromaticAberrationB" | "ChromaticAberrationR" | "Defringe") + && value_is(k, &|v| v.len() == 1 && v.iter().all(|s| s.trim().parse::().is_ok_and(|n| n == 0.0)))) + || (matches!(k, "ToneCurveRed" | "ToneCurveGreen" | "ToneCurveBlue") && value_is(k, &identity_curve)) // Point Color's variance means nothing without a used slot || (k == "ColorVariance" && (!props.contains_key("crs:PointColors") || value_is("PointColors", &empty_points))) // the lens profile's strength, written at its default (100 %) next to every profile @@ -1093,6 +1137,79 @@ mod tests { assert!(["/curve/master", "/curve/red", "/curve/green", "/curve/blue"].iter().all(|p| all.pointer(p).is_some()), "{all}"); } + /// An older-process packet (written for this test, as old DNGs, sidecars and catalogs carry it) of + /// a photo nobody edited: its sliders and raw sharpening at their old defaults and its curve named + /// as the old default one. `extra`: more attributes. + fn old_process_packet(curve_name: &str, sharpness: &str, extra: &str) -> String { + format!( + r#" + + 0, 070, 58180, 190255, 255 + "# + ) + } + + /// An untouched raw from an older process version keeps the look it is imported with (so it isn't + /// taken for an edited one, whose thumbnails need the whole raw decoded); what was changed there + /// still comes in, and so does a sharpening of 25 where it isn't that version's raw default. + #[test] + fn the_older_process_defaults_are_no_edit() { + let raw = DevelopSettings::for_raw(5000.0, 0.0); + let read = |base: &DevelopSettings, packet: String, target| apply_partial(base, &to_partial(&props(&packet), target), 1.0); + let untouched = old_process_packet("Medium Contrast", "25", ""); + assert_eq!(read(&raw, untouched.clone(), Target::RawAbsolute), raw, "an untouched older-process raw is unchanged"); + assert_eq!(read(&raw, untouched, Target::RawRelative), raw); + for changed in ["Custom", "Strong Contrast"] { + assert!(!read(&raw, old_process_packet(changed, "25", ""), Target::RawAbsolute).curve.master.is_empty(), "{changed}: the curve is read"); + } + let sharpening = |packet: String, base: &DevelopSettings, target| read(base, packet, target).detail.sharpen_amount; + assert_eq!(sharpening(old_process_packet("Medium Contrast", "50", ""), &raw, Target::RawAbsolute), 50.0, "a changed amount is read"); + let current = old_process_packet("Medium Contrast", "25", r#"crs:ProcessVersion="11.0" crs:Contrast2012="0""#); + assert_eq!(sharpening(current, &raw, Target::RawAbsolute), 25.0, "25 under the 2012 process is a choice"); + let rendered = DevelopSettings::default(); + assert_eq!( + sharpening(old_process_packet("Medium Contrast", "25", ""), &rendered, Target::Rendered), + 25.0, + "a rendered file's old default was 0" + ); + } + + #[test] + fn legacy_optics_defaults_and_identity_channel_curves_do_not_warn() { + let attrs = r#"crs:AutoWhiteVersion="134348800" crs:ChromaticAberrationR="+0" crs:ChromaticAberrationB="0.0" crs:Defringe="0""#; + let curve = r#"0, 0255, 255"#; + assert!(unmapped(&preset_packet(attrs, curve)).is_empty()); + + let collinear = curve.replace("255, 255", "128, 128255, 255"); + assert!(unmapped(&preset_packet(attrs, &collinear)).is_empty()); + let unordered = collinear.replace("255, 255", "64, 64255, 255"); + assert_eq!(unmapped(&preset_packet(attrs, &unordered)), ["ToneCurveRed"]); + + let attrs = attrs.replace(r#"crs:Defringe="0""#, r#"crs:Defringe="1""#); + let curve = curve.replace("255, 255", "255, 220"); + assert_eq!(unmapped(&preset_packet(&attrs, &curve)), ["Defringe", "ToneCurveRed"]); + } + + #[test] + fn auto_white_version_preserves_an_explicit_crop_reset() { + let packet = r#" + + + "#; + let target = Target::RawAbsolute; + let defaults = DevelopSettings::default(); + let cropped = apply_partial(&defaults, &to_partial(&props(SIDECAR), target), 1.0); + assert_ne!(cropped.crop.geometry, defaults.crop.geometry); + + let sidecar = crate::sidecar::parse_sidecar(packet, target).unwrap(); + assert!(sidecar.warnings.is_empty()); + let Some(crate::sidecar::DevelopPatch::Partial(patch)) = sidecar.develop else { panic!("expected a crop reset") }; + assert_eq!(apply_partial(&cropped, &patch, 1.0).crop.geometry, defaults.crop.geometry); + } + fn unmapped(x: &str) -> Vec { to_partial_report(&props(x), None, Target::Any, 1.5).1 } diff --git a/crates/engine/src/denoise.rs b/crates/engine/src/denoise.rs index e09335f532..90e2d9df75 100644 --- a/crates/engine/src/denoise.rs +++ b/crates/engine/src/denoise.rs @@ -1563,8 +1563,13 @@ fn loaded(spec: &JobSpec) -> Result, MakeError> { Ok(m) } -/// The cell `[(0,0), (1,0), (0,1), (1,1)]` colours of a Bayer mosaic and so its layout. -fn layout_of(cfa: &lcc_raw::Cfa) -> Option { +/// The layout of a Bayer mosaic, from the colours of its cell `[(0,0), (1,0), (0,1), (1,1)]`; `None` for any other +/// pattern. The pattern itself must be the 2 × 2 cell: 16 of X-Trans's 36 phases have a top-left 2 × 2 that reads as a +/// Bayer cell, and one of those packed as Bayer would hand the model a sensor it was not looking at. +pub(crate) fn layout_of(cfa: &lcc_raw::Cfa) -> Option { + if !cfa.is_bayer() { + return None; + } Layout::from_cell([cfa.color_at(0, 0), cfa.color_at(1, 0), cfa.color_at(0, 1), cfa.color_at(1, 1)]) } @@ -1602,20 +1607,35 @@ pub(crate) fn make_product(spec: &JobSpec, progress: Option<&Progress>) -> Resul drop(bytes); // hot, dead and stuck pixels go before the denoiser sees them, as in the plain development crate::files::repair_pixels(&mut raw, &crate::files::RawOptions::for_path(&spec.path, true)); - if raw.cpp != 1 || !raw.cfa.as_ref().is_some_and(lcc_raw::Cfa::is_bayer) { + if raw.cpp != 1 || raw.cfa.is_none() { return Err(MakeError::Unsupported( - "only Bayer raw files can be denoised (this one has another sensor layout or is already demosaiced)".into(), + "only raw files with a colour filter array can be denoised (this one is monochrome or already demosaiced)".into(), )); } let n = raw.normalized().map_err(|e| MakeError::Failed(e.to_string()))?; drop(raw); - let layout = - n.cfa.as_ref().and_then(layout_of).ok_or_else(|| MakeError::Unsupported("the colour filter layout is not a Bayer pattern".into()))?; + let layout = n.cfa.as_ref().and_then(layout_of); (n, layout) }; if cancelled() { return Err(MakeError::Cancelled); } + // X-Trans and the other non-Bayer layouts: the model's contract is four RGGB planes, so the mosaic is interpolated + // and rebuilt as RGGB first. The picture keeps its size and the sites the two patterns share keep their own + // samples; the rest reach the model already interpolated (see docs/denoise.md). This holds the mosaic, its green + // plane and the RGGB copy at once, after the decode's memory has gone back. + let (mosaic, layout) = match layout { + Some(layout) => (mosaic, layout), + None => { + let _held = crate::memory::work_gate().acquire(mosaic.data.len().saturating_mul(12)); + let rggb = lcc_raw::demosaic::remosaic_rggb(&mosaic) + .ok_or_else(|| MakeError::Unsupported("this sensor layout cannot be read as a Bayer mosaic, so it cannot be denoised".into()))?; + (rggb, Layout { dx: 0, dy: 0 }) + } + }; + if cancelled() { + return Err(MakeError::Cancelled); + } let decoded = began.elapsed(); let model = loaded(spec)?; model.prepare(&mosaic.data, mosaic.width, mosaic.height); diff --git a/crates/engine/src/face_thumbs.rs b/crates/engine/src/face_thumbs.rs new file mode 100644 index 0000000000..285f1d630d --- /dev/null +++ b/crates/engine/src/face_thumbs.rs @@ -0,0 +1,248 @@ +//! `faces.buildThumbnails`: render the People view's face tiles ahead of the scrolling that asks +//! for them (issue #1691). +//! +//! A face tile ([`crate::Session::face_job`]) is cut from the photo's preview (or, for an unedited +//! raw, from the camera's embedded JPEG) and kept in the thumbnail cache, memory and the library's +//! disk cache, under the key the People view asks for. The view builds a tile the first time it +//! scrolls past it, which on a big library means a render every few tiles; this builds them all at +//! once — every named and unnamed face of the library (the ignored ones are left out of People, so +//! their tiles are never asked for) at one tile edge — so scrolling is a texture upload from the +//! cache afterwards, also in a later session. `wait: true` runs it there and then (the CLI, tests); +//! otherwise it runs in the background, a cancellable row in the activity stack. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use lcc_catalog::PhotoId; +use serde_json::{Value, json}; + +use crate::{Result, Session}; + +const C: &str = "faces.buildThumbnails"; +/// The activity row's label (translated by the frontend). +pub const LABEL: &str = "Building face thumbnails"; +/// The tile edge built when the caller does not name one (`face_edge` keeps it on the 16 px step +/// the People view's tiles ask for). A frontend passes what its tiles are now, so the run fills the +/// cache keys it will ask for. +const DEFAULT_EDGE: usize = 256; +/// The most lanes a run takes. +const MAX_LANES: usize = 8; +/// How many lanes a background run keeps: face tiles are small, but a lane may decode an edited +/// raw's source, and two leave the photo on screen and the face scan their room. +const BACKGROUND_LANES: usize = 2; + +/// A run in the background, and what it has done so far. The counters are shared with its lanes. +pub struct FaceThumbs { + cancel: Arc, + finished: Arc, + /// The face tiles the run is for, and the edge they are built at (the cache key's step). + total: u64, + edge: usize, + built: Arc, + failed: Arc, +} + +impl FaceThumbs { + fn json(&self) -> Value { + let finished = self.finished.load(Ordering::Relaxed); + let built = self.built.load(Ordering::Relaxed); + json!({ + "active": !finished, + "done": finished, + "total": self.total, + "built": built.min(self.total), + "failed": self.failed.load(Ordering::Relaxed), + "cancelled": self.cancel.load(Ordering::Relaxed), + "edge": self.edge, + }) + } +} + +/// Lanes of a run that waits (a CLI or test run): an eighth of the computer's threads, 1–4 (each +/// lane may hold one decoded source at a time, as the preview build's lanes do). +fn default_lanes() -> usize { + std::thread::available_parallelism().map_or(1, |n| n.get() / 8).clamp(1, 4) +} + +/// `jobs` dealt out to `lanes` lanes in turn, so the first faces are built first. +fn split(jobs: Vec, lanes: usize) -> Vec> { + let lanes = lanes.max(1); + let mut out: Vec> = (0..lanes).map(|_| Vec::new()).collect(); + for (i, j) in jobs.into_iter().enumerate() { + if let Some(lane) = out.get_mut(i % lanes) { + lane.push(j); + } + } + out.retain(|l| !l.is_empty()); + out +} + +/// What the lanes count, shared. +#[derive(Clone)] +struct Counter { + built: Arc, + failed: Arc, + seen: Arc, + total: u64, +} + +impl Counter { + fn add(&self, r: &crate::media::RenderResult) { + match r.rendered { + Ok(_) => { + self.built.fetch_add(1, Ordering::Relaxed); + } + Err(_) => { + self.failed.fetch_add(1, Ordering::Relaxed); + } + } + let n = self.seen.fetch_add(1, Ordering::Relaxed).saturating_add(1); + if n.is_multiple_of(500) { + log::info!("faces.buildThumbnails: {n} of {} face tiles", self.total); + } + } +} + +/// One lane's tiles built: each job's picture, rendered or found in the cache, goes to the thumbnail +/// cache the job carries; a face the People view has shown already costs a lookup. `each` reports +/// every tile to the caller (the activity row's progress); a cancelled lane stops before its next +/// tile, the one being built always finishes. +fn build_lane(lane: Vec, cancel: &AtomicBool, count: &Counter, mut each: impl FnMut(&crate::media::RenderResult)) { + for job in lane { + if cancel.load(Ordering::Relaxed) { + return; + } + let r = job.run(); + count.add(&r); + each(&r); + } +} + +/// `faces.buildThumbnails`. +pub fn build(s: &mut Session, p: &Value) -> Result { + let running = s.face_thumbs.as_ref().filter(|r| !r.finished.load(Ordering::Relaxed)); + if p.get("status").and_then(Value::as_bool).unwrap_or(false) { + return Ok(s.face_thumbs.as_ref().map_or_else(|| json!({"active": false, "done": false}), |r| r.json())); + } + if p.get("cancel").and_then(Value::as_bool).unwrap_or(false) { + if let Some(r) = running { + r.cancel.store(true, Ordering::Relaxed); + } + return Ok(json!({"cancelled": running.is_some()})); + } + if running.is_some() { + return Err(crate::cmd::bad(C, "a run is in progress already (`{\"cancel\": true}` stops it)")); + } + let edge = crate::media::face_edge(p.get("edge").and_then(Value::as_u64).map_or(DEFAULT_EDGE, |n| usize::try_from(n).unwrap_or(DEFAULT_EDGE))); + // every face the People view shows, with the box its tile is shown by (the detector's, once the + // scan has looked at the photo, else the region's own): the same keys the view asks for + let mut faces: Vec<(PhotoId, lcc_geom::Rect)> = Vec::new(); + for ph in s.catalog.photos().filter(|ph| ph.in_library()) { + for r in ph.meta.regions.iter().filter(|r| r.kind == lcc_meta::RegionKind::Face) { + faces.push((ph.id, s.face_view(ph.id, r.rect))); + } + } + let mut jobs: Vec = Vec::with_capacity(faces.len()); + for (id, rect) in &faces { + if let Some(job) = s.face_job(*id, *rect, edge) { + jobs.push(job); + } + } + let run = FaceThumbs { + cancel: Arc::default(), + finished: Arc::default(), + total: jobs.len() as u64, + edge, + built: Arc::default(), + failed: Arc::default(), + }; + let count = Counter { built: run.built.clone(), failed: run.failed.clone(), seen: Arc::default(), total: run.total }; + let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); + let lanes = p + .get("lanes") + .and_then(Value::as_u64) + .map(|n| n.clamp(1, MAX_LANES as u64) as usize) + .unwrap_or(if wait { default_lanes() } else { BACKGROUND_LANES }) + .min(jobs.len().max(1)); + let n_lanes = lanes; + let lanes = split(jobs, lanes); + if wait { + let t0 = web_time::Instant::now(); + std::thread::scope(|sc| { + let mut inline = Vec::new(); + let mut handles = Vec::new(); + for lane in lanes { + let (cancel, count) = (&run.cancel, count.clone()); + let job = { + let lane = lane.clone(); + move || build_lane(lane, cancel, &count, |_| ()) + }; + match std::thread::Builder::new().name("face-thumbs".into()).spawn_scoped(sc, job) { + Ok(h) => handles.push(h), + Err(_) => inline.push(lane), + } + } + for lane in inline { + build_lane(lane, &run.cancel, &count, |_| ()); + } + for h in handles { + if h.join().is_err() { + log::error!("faces.buildThumbnails: a lane stopped unexpectedly"); + } + } + }); + run.finished.store(true, Ordering::Relaxed); + let mut out = run.json(); + out["ms"] = json!(t0.elapsed().as_millis() as u64); + out["lanes"] = json!(n_lanes); + return Ok(out); + } + let task = s.activity.start_batch("faceThumbs", LABEL, crate::activity::Cancel::Flag(run.cancel.clone())); + task.progress(0, run.total); + let (flag, finished) = (run.cancel.clone(), run.finished.clone()); + std::thread::Builder::new() + .name("face-thumbs".into()) + .spawn(move || { + let mut handles = Vec::new(); + let mut inline = Vec::new(); + for lane in lanes { + let (flag, count, row) = (flag.clone(), count.clone(), task.handle()); + let job = { + let lane = lane.clone(); + move || { + build_lane(lane, &flag, &count, |r| { + if r.rendered.is_ok() { + row.item_done(); + } else if let Err(e) = &r.rendered { + row.item_failed(e); + } + }) + } + }; + match std::thread::Builder::new().name("face-thumbs".into()).spawn(job) { + Ok(h) => handles.push(h), + Err(_) => inline.push(lane), + } + } + for lane in inline { + build_lane(lane, &flag, &count, |r| { + if r.rendered.is_ok() { + task.item_done(); + } else if let Err(e) = &r.rendered { + task.item_failed(e); + } + }); + } + for h in handles { + if h.join().is_err() { + log::error!("faces.buildThumbnails: a lane stopped unexpectedly"); + } + } + finished.store(true, Ordering::Relaxed); + drop(task); + }) + .map_err(|e| crate::cmd::bad(C, format!("could not start ({e})")))?; + let out = run.json(); + s.face_thumbs = Some(Arc::new(run)); + Ok(out) +} diff --git a/crates/engine/src/faces_index.rs b/crates/engine/src/faces_index.rs index c80bc15793..3fa0c7aaad 100644 --- a/crates/engine/src/faces_index.rs +++ b/crates/engine/src/faces_index.rs @@ -11,7 +11,7 @@ //! face, so every face is shown equally close however loosely or tightly its own region was drawn (a Lightroom box, an //! older tool's box), else the region's own box. //! -//! Layout (little-endian): `"LCFE"`, version `2`, tag length `u16`, the tag (`@`), dimension `u32`, +//! Layout (little-endian): `"LCFE"`, version `3`, tag length `u16`, the tag (`@`), dimension `u32`, //! then records of `photo u64`, four `i32` (the region's box in ten-thousandths), four `i32` (the view box likewise), and //! `dim` `f32`. @@ -24,7 +24,10 @@ use std::sync::Arc; use lcc_geom::Rect; const MAGIC: &[u8; 4] = b"LCFE"; -const VERSION: u8 = 2; +/// Version 3 holds the same records as 2 and does not read a file written as 2: versions 26.48.1 and 26.48.2 cut faces +/// by their box in the scans that only embed (issue #1616), and nothing in a record says which way its face was cut, so +/// every face is embedded once more rather than leave those among the aligned ones. +const VERSION: u8 = 3; /// Ends the tag of a cache whose faces are each averaged with their mirror image /// ([`lcc_faces::runtime::Embedder::embed_faces`]); a cache made the other way has another tag, so it is not read and /// its faces are embedded again rather than mixed with the new ones. @@ -446,6 +449,33 @@ mod tests { let _ = std::fs::remove_file(path); } + /// Issue #1616: a cache written before every scan aligned the faces it embedded may hold faces cut by their box, + /// so it is not read; the file is written anew, with the new version, at the first save. + #[test] + fn a_cache_from_before_faces_were_always_aligned_is_embedded_again() { + let path = temp("oldversion"); + let _ = std::fs::remove_file(&path); + let mut a = Index::default(); + a.reset("m@abc+mirror", 3, Some(path.clone())); + a.insert(1, &rect(0.1), vec![1.0, 0.0, 0.0]); + a.save().unwrap(); + let mut bytes = std::fs::read(&path).unwrap(); + assert_eq!(&bytes[..4], b"LCFE", "the file starts with its magic"); + bytes[4] = 2; + std::fs::write(&path, &bytes).unwrap(); + let mut b = Index::default(); + b.reset("m@abc+mirror", 3, Some(path.clone())); + assert_eq!(b.len(), 0, "nothing of the old file is used"); + assert!(b.needs(1, &rect(0.1)), "so its one face is to be embedded again"); + b.insert(2, &rect(0.3), vec![0.0, 1.0, 0.0]); + b.save().unwrap(); + let mut again = Index::default(); + again.reset("m@abc+mirror", 3, Some(path.clone())); + assert_eq!(again.len(), 1, "written fresh: the new face only, not appended after the old records"); + assert!(again.contains(2, &rect(0.3)) && again.needs(1, &rect(0.1))); + let _ = std::fs::remove_file(path); + } + #[test] fn another_model_a_damaged_file_or_a_torn_tail_are_handled() { let path = temp("other"); @@ -619,7 +649,8 @@ mod tests { pub(crate) enum FaceScanMode { /// Find faces only in photos without existing boxes, then embed the known boxes. Detect, - /// Embed existing face boxes without running the detector. + /// Embed existing face boxes that have no embedding yet. No faces are looked for; the detector still lends its + /// landmarks, so they are aligned. Recognize, /// Work only on new or unindexed photos within the selected scope. New, diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 190c80d1f1..07eab129e5 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -3654,6 +3654,66 @@ pub(crate) mod tests { assert_eq!((img.width, img.height, src.raw), (64, 48, true)); } + /// FITS (issue #1604): its three extensions are imported, the file is described from its header as a raw photo + /// (the header cards fill the metadata) and it loads from its samples. + #[test] + fn fits_probes_and_loads_as_a_raw_photo() { + for ext in ["fits", "fit", "fts"] { + let name = format!("M 31.{ext}"); + assert!(crate::import::is_supported(std::path::Path::new(&name)), "folder imports find {name}"); + } + let kw = |name: &str, value: i32| format!("{:<80}", format!("{name:<8}= {value:>20}")); + let card = |text: &str| format!("{text:<80}"); + let cards = [ + card("SIMPLE = T"), + kw("BITPIX", 16), + kw("NAXIS", 2), + kw("NAXIS1", 16), + kw("NAXIS2", 8), + kw("BZERO", 32768), + card("BAYERPAT= 'RGGB '"), + card("DATE-OBS= '2026-11-28T12:34:56'"), + card("INSTRUME= 'ZWO ASI260MC'"), + card("EXPTIME = 120.5"), + card("OBJECT = 'M 31 '"), + ]; + // a header unit (whole 2880-byte blocks) and its samples + let file = |cards: &[String], data: &[u8]| -> Vec { + let mut out: Vec = cards.iter().flat_map(|c| c.as_bytes().iter().copied()).collect(); + out.extend_from_slice(b"END"); + out.resize(out.len().div_ceil(2880) * 2880, b' '); + out.extend_from_slice(data); + out + }; + let f = file(&cards, &(0..16 * 8).flat_map(|i| ((i * 997 % 60000 + 500 - 32768) as i16).to_be_bytes()).collect::>()); + for name in ["M31.FITS", "m31.fit", "m31.fts"] { + let p = probe_bytes(name, &f).unwrap(); + assert_eq!((p.kind, p.preview_only.as_ref(), p.width, p.height), (MediaKind::Raw, None, 16, 8), "{name}"); + assert_eq!(p.format, name.rsplit_once('.').map(|(_, e)| e.to_uppercase()).unwrap_or_default(), "its extension, as for any raw"); + assert_eq!((p.meta.camera_model.as_str(), p.meta.camera.as_str()), ("ZWO ASI260MC", "ZWO ASI260MC")); + assert_eq!(p.meta.exposure_time, Some(120.5)); + assert!(p.captured.as_deref().is_some_and(|c| c.starts_with("2026-11-28T12:34:56")), "{:?}", p.captured); + assert_eq!(p.orientation, Some(Orientation::Normal)); + } + // a variant that cannot be read is refused, saying why (a FITS file has no embedded preview to show instead) + let cube = file( + &[ + card("SIMPLE = T"), + kw("BITPIX", 16), + kw("NAXIS", 4), + kw("NAXIS1", 2), + kw("NAXIS2", 2), + kw("NAXIS3", 2), + kw("NAXIS4", 2), + ], + &[0; 16], + ); + let err = probe_bytes("cube.fits", &cube).unwrap_err(); + assert!(err.contains("4 axes") && err.contains("without an embedded preview"), "{err}"); + let (img, src) = load_bytes(&f, 64).unwrap(); + assert_eq!((img.width, img.height, src.raw), (16, 8, true)); + } + /// Any failure of a recognised raw (not only an unsupported variant) can fall back to its preview; /// CR3 keeps its own wording. #[test] diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 992d4177a2..0fc61c55a7 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -43,7 +43,9 @@ pub const EXTENSIONS: &[&str] = &[ // Decoded when built with the codecs' `heif` feature; otherwise the import reports them as // failed with the reason ("HEIC/HEIF support isn't included in this build"). "heic", "heif", "avif", // a HEIC without the `heif` feature is reported as failed - "iiq", "crw", "mrw", "x3f", "kdc", "mos", "erf", "3fr", "fff", "mef", "gpr", // video clips (MediaKind::Video; see VIDEO_EXTENSIONS) + "iiq", "crw", "mrw", "x3f", "kdc", "mos", "erf", "3fr", "fff", "mef", "gpr", + // FITS, the format of astrophotography cameras and software (issue #1604) + "fits", "fit", "fts", // video clips (MediaKind::Video; see VIDEO_EXTENSIONS) "mp4", "m4v", "mov", "mkv", "webm", "mts", "m2ts", "3gp", "mxf", ]; @@ -133,6 +135,10 @@ pub struct ImportOptions { /// Keep what each new photo's sidecar said, as it was merged ([`ImportReport::sidecars_read`]): a Lightroom /// catalog import puts the catalog's values over it and then compares the two (issue #1312). Off by default. pub keep_sidecars: bool, + /// Read neither a sidecar nor the XMP embedded in a file: the import's other source (a Capture One catalog, which + /// holds the photo's settings and metadata itself) is the only one, so nothing a file or a sidecar says reaches the + /// photo. Off by default. + pub ignore_xmp: bool, /// A batch-edit recipe: develop control id / value pairs (e.g. `light.exposure` → 0.5), /// applied to every imported photo *after* its XMP sidecar, camera default and import preset, /// as one more History step (`Import adjustments`). Only the named controls change; the recipe @@ -148,6 +154,12 @@ pub struct ImportOptions { /// Import Suspected Duplicates" unchecked). A file at a path the library already lists, or one /// in Recently Deleted, is still handled as a duplicate. pub import_duplicates: bool, + /// Treat JPEGs next to raw files as companions of the raw (issue #1692): a JPEG with a raw's + /// name beside it (same folder) is not imported as a photo of its own but kept attached to the + /// raw (one thumbnail, one face scan, one set of metadata), and travels with it through Copy / + /// Move. `None` = the library's setting ([`lcc_catalog::CatalogSettings::raw_jpeg_companions`], + /// on by default, as Lightroom Classic's default). + pub companions: Option, /// The plug-ins' `beforeImport` hook is asked about each file (the default). Off for a /// plug-in's own output (`library.add`), so a hook never re-asks about it. pub plugin_hooks: bool, @@ -230,6 +242,10 @@ pub struct ImportCandidate { /// A raw's camera (`Make Model`). #[serde(skip_serializing_if = "String::is_empty")] pub camera: String, + /// A JPEG beside its raw (companions on, issue #1692): the raw beside it (its path), whose + /// companion it is instead of a photo of its own. The review shows it attached to the raw. + #[serde(rename = "companionOf", skip_serializing_if = "Option::is_none")] + pub companion_of: Option, } #[derive(Clone, Debug, Default, Serialize)] @@ -244,6 +260,16 @@ pub struct Duplicate { pub existing_deleted: bool, } +/// A JPEG imported as its raw's companion, not a photo of its own (issue #1692). +#[derive(Clone, Debug, Serialize)] +pub struct CompanionPair { + /// The JPEG's own path (its source; a Move or Copy kept it beside its raw). + pub path: String, + /// The raw that keeps it, when its import succeeded. + #[serde(skip_serializing_if = "Option::is_none")] + pub raw: Option, +} + /// Files an import's folder walk left out ([`Expansion::unreadable`], [`Expansion::unsupported`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] pub struct Skipped { @@ -266,6 +292,10 @@ pub struct ImportReport { #[serde(skip)] pub promoted_changed: Vec, pub duplicates: Vec, + /// JPEGs imported as their raw's companion (issue #1692): each with the raw that keeps it + /// (its photo id; `None` when that raw's own import failed — the JPEG stays unimported). + #[serde(skip_serializing_if = "Vec::is_empty")] + pub companions: Vec, /// [`OnDeleted::Restore`]: photos brought back from Recently Deleted instead of imported. #[serde(skip_serializing_if = "Vec::is_empty")] pub restored: Vec, @@ -745,9 +775,12 @@ fn expand_report_noting( subfolders: bool, ) -> Expansion { let mut out = Expansion::default(); + // canonical folders walked so far: overlapping roots (an alias, a folder inside another) are walked once + let mut seen_dirs = std::collections::HashSet::new(); + let skipped = skip.and_then(|p| std::fs::canonicalize(p).ok()); for p in paths { let p = Path::new(p); - if skip.is_some_and(|s| p == s) { + if skip.is_some_and(|s| p == s) || skipped.as_ref().is_some_and(|s| std::fs::canonicalize(p).as_ref().ok() == Some(s)) { continue; } if p.is_dir() { @@ -761,9 +794,12 @@ fn expand_report_noting( } keep }; + // one root can't overlap another: it is walked without asking for canonical paths let w = match note.as_mut() { - Some(note) => crate::walk::files_in_noting(p, skip, walk_limits, keep, &mut **note), - None => crate::walk::files_in(p, skip, walk_limits, keep), + Some(note) if paths.len() < 2 => crate::walk::files_in_noting(p, skip, walk_limits, keep, &mut **note), + None if paths.len() < 2 => crate::walk::files_in(p, skip, walk_limits, keep), + Some(note) => crate::walk::files_in_with_seen(p, skip, walk_limits, keep, Some(&mut **note), &mut seen_dirs), + None => crate::walk::files_in_with_seen(p, skip, walk_limits, keep, None, &mut seen_dirs), }; let truncated = if subfolders { w.truncated } else { w.entries >= limits.max_entries }; if truncated { @@ -789,6 +825,37 @@ fn expand_report_noting( out } +/// The string used for an absolute folder in Local browse: trailing separators trimmed, except on a +/// filesystem root (`/`, `C:\`, a UNC share), which keeps its own (adapted from upstream #4628). +pub fn browse_folder_string(path: &Path) -> String { + let text = path.to_string_lossy(); + if path.parent().is_none() { text.into_owned() } else { text.trim_end_matches(['/', '\\']).to_string() } +} + +#[cfg(test)] +mod browse_folder_tests { + use super::{Path, browse_folder_string}; + + #[test] + fn browse_folder_string_keeps_filesystem_roots() { + #[cfg(windows)] + { + assert_eq!(browse_folder_string(Path::new(r"C:\")), r"C:\"); + assert_eq!(browse_folder_string(Path::new(r"\\server\share\")), r"\\server\share\"); + } + #[cfg(not(windows))] + assert_eq!(browse_folder_string(Path::new("/")), "/"); + } + + #[test] + fn browse_folder_string_removes_trailing_separators_from_other_folders() { + #[cfg(windows)] + assert_eq!(browse_folder_string(Path::new(r"C:\photos\")), r"C:\photos"); + #[cfg(not(windows))] + assert_eq!(browse_folder_string(Path::new("/photos/")), "/photos"); + } +} + /// What a path given on the command line at launch becomes ([`launch_path`]). #[derive(Clone, Debug, PartialEq, Eq)] pub enum LaunchPath { @@ -1149,6 +1216,9 @@ pub struct ScanInput { /// ([`library_hashes`]), on the scan's thread. library: std::sync::Arc, cache: HashMap, + /// Whether JPEGs beside raws are companions of the raw (issue #1692): the scan marks them + /// ([`ImportCandidate::companion_of`]) so the review shows them attached to their raw. + companions: bool, } /// The library's photos of `files`: path → (photo, its summary as a candidate that is there @@ -1250,7 +1320,13 @@ impl ScanInput { // (no table of the library here: this is the session's thread, and the library may hold // millions of photos. The scan looks up what it finds) let library = std::sync::Arc::new(s.catalog.clone()); - let input = ScanInput { probe: s.media.file_probe.clone(), skip, library, cache: std::mem::take(&mut s.import_probes) }; + let input = ScanInput { + probe: s.media.file_probe.clone(), + skip, + library, + cache: std::mem::take(&mut s.import_probes), + companions: s.raw_jpeg_companions(), + }; (input, paths.to_vec()) } @@ -1444,6 +1520,36 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc } out.push(c); } + // the JPEGs beside raws (companions on, issue #1692): marked with the raw beside them, so the + // review shows them attached to their raw instead of as photos of their own. One the library + // already has stays a duplicate: it is its own photo there. + if input.companions { + let mut raws: HashMap<(String, String), String> = HashMap::new(); + for c in &out { + if (c.kind == MediaKind::Raw || is_raw_pair_name(&c.path)) + && let Some(path) = (c.error.is_none() && c.duplicate.is_none()).then(|| c.path.clone()) + { + raws.insert(companion_key(&path), path); + } + } + if !raws.is_empty() { + for p in input.library.photos().filter(|p| !p.deleted && !p.local && p.copy_of.is_none()) { + let Some(path) = crate::sidecar::file_path(p) else { continue }; + if is_raw_pair_name(path) || p.kind == MediaKind::Raw { + raws.entry(companion_key(path)).or_insert(path.to_string()); + } + } + for c in &mut out { + if c.error.is_none() + && c.duplicate.is_none() + && is_jpeg_pair_name(&c.path) + && let Some(raw) = raws.get(&companion_key(&c.path)) + { + c.companion_of = Some(raw.clone()); + } + } + } + } // (the walks' diagnostics are [`scan_with`]'s: these files were found already) ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 } } @@ -1507,6 +1613,26 @@ pub struct ImportJob { cache: HashMap, naming: crate::sidecar::SidecarNaming, now: String, + /// Whether JPEGs beside raws are companions of the raw (issue #1692): [`ImportOptions::companions`], + /// resolved against the library's setting. + companions: bool, + /// The companion JPEGs a planned raw has claimed (their paths), so two raws sharing a stem + /// don't both attach the same file. + claimed_companions: std::collections::HashSet, + /// The files of this import that carry a Local (browsed) record and follow or join it: they + /// are never companions ([`companion_pairs`], [`ImportJob::claim_companion`]). + following: std::collections::HashSet, + /// The library's file paths ([`normalize_import_path`]): a companion JPEG one of them points + /// at is that record's own photo ([`ImportJob::claim_companion`]). + library_paths: std::collections::HashSet, + /// One listing per folder of the raws planned so far: the JPEG files beside them + /// ([`folder_jpegs`]), for [`ImportJob::claim_companion`]. `None`: not listable. + folder_jpegs: HashMap>>, + /// The companion pairing ([`companion_plan`]) of the whole import, computed once over every + /// file, so a pair split across two batches of a streamed import still comes out as one photo. + companion_plan: HashMap, + /// Whether [`ImportJob::companion_plan`] was computed (the first file list is the whole one). + companion_planned: bool, /// 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. @@ -1555,6 +1681,21 @@ enum PreparedItem { Copying(String), Kept(Kept), Ready(Box), + /// A JPEG beside its raw (companions on, issue #1692): not a photo of its own. The report + /// says so ([`ImportReport::companions`]); a raw already in the library is pointed at it. + Companion { + path: String, + raw: CompanionOf, + }, +} + +/// What a companion JPEG (issue #1692) belongs to, decided when a batch is planned. +#[derive(Clone, Debug)] +pub(crate) enum CompanionOf { + /// A raw this import adds; matched to its record by the raw's own path at commit. + Batch(String), + /// A raw the library already has: its record gets the companion. + Library(PhotoId), } #[derive(Debug)] @@ -1569,6 +1710,12 @@ struct ReadyFile { promote: Option, /// Copy as DNG was asked for and not made: why (one of the `Dng…` codes). dng_not_made: Option, + /// The companion JPEG the record points at (issue #1692): its path as the record holds it — + /// the file itself when added where it is, the copy beside the raw's copy. `None`: none. + companion: Option, + /// A Copy's companion that wasn't copied: (its source, why) — [`ImportReport::kept`]. The + /// raw is imported all the same. + companion_failed: Option<(String, String)>, } impl Prepared { @@ -1612,7 +1759,7 @@ impl Prepared { items.push(item); continue; }; - let ReadyFile { path, stored, info, sidecar, placed, promote, dng_not_made } = *ready; + let ReadyFile { path, stored, info, sidecar, placed, promote, dng_not_made, companion, companion_failed } = *ready; let existing_path = paths.get(&normalize_import_path(&stored)).copied().or_else(|| paths.get(&normalize_import_path(&path)).copied()); let existing_hash = info.content_hash.as_ref().and_then(|hash| hashes.get(crate::sync::base_hash(hash)).map(|(_, id)| *id)); if let Some(existing) = existing_path.or(existing_hash) { @@ -1626,7 +1773,17 @@ impl Prepared { hash: info.content_hash, }); } else { - items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, promote, dng_not_made }))); + items.push(PreparedItem::Ready(Box::new(ReadyFile { + path, + stored, + info, + sidecar, + placed, + promote, + dng_not_made, + companion, + companion_failed, + }))); } } self.items = items; @@ -1664,6 +1821,9 @@ impl ImportJob { return Err(crate::EngineError::Other("copying or moving needs a destination folder or an open catalog".into())); } let fresh = opts.on_deleted == OnDeleted::Fresh; + // browsing a folder shows its files (Local records for every one of them): no companions + // there, the pairing is for what joins the library + let companions = !opts.local && opts.companions.unwrap_or_else(|| s.raw_jpeg_companions()); Ok(ImportJob { seq: Some(opts.rename_start.max(1)), opts, @@ -1678,6 +1838,13 @@ impl ImportJob { cache: std::mem::take(&mut s.import_probes), naming: s.xmp.naming, now: (s.clock)(), + companions, + claimed_companions: Default::default(), + following: Default::default(), + library_paths: Default::default(), + folder_jpegs: Default::default(), + companion_plan: Default::default(), + companion_planned: false, total: Default::default(), done: Default::default(), before_import: None, @@ -1747,6 +1914,11 @@ impl ImportJob { continue; } if let Source::File { path } = &p.source { + // companions on: a file a record already points at is its own photo, never a + // raw's companion ([`ImportJob::claim_companion`]) + if self.companions { + self.library_paths.insert(normalize_import_path(path)); + } self.by_path.insert(path.clone(), (p.id, p.local, p.content_hash.clone())); } // importing suspected duplicates: only a trashed photo's content still matches @@ -1802,6 +1974,13 @@ impl ImportJob { let probed = probe_all_cached(self.probe.as_ref(), &todo, cached, keep_import_probe, &self.read_done, cancel); crate::memory::release(); let stems = import_stems(library.as_ref(), &todo, &probed); + // the JPEGs beside raws (companions on, issue #1692): not photos of their own, skipped + // here. The pairing is the whole import's ([`ImportJob::companion_plan`], computed once by + // the streamed planner, or over this call's files when this call is the whole import) + if !self.companion_planned { + self.companion_plan = if self.companions { companion_plan(library.as_ref(), &todo) } else { Default::default() }; + self.companion_planned = true; + } // 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. @@ -1813,6 +1992,17 @@ impl ImportJob { out.cut_short = true; break; } + // a JPEG beside its raw: the report says so, and the raw already in the library is + // pointed at it (a raw this import adds claims it when it is planned). Not one: a + // file the library has a photo at (a duplicate here), or one with a Local record + if !self.by_path.contains_key(&path) + && !self.following.contains(&path) + && let Some(raw) = self.companion_plan.get(&path) + { + self.done.fetch_add(1, Relaxed); + out.items.push(PreparedItem::Companion { path, raw: raw.clone() }); + continue; + } let info = match info { Ok(i) => i, Err(e) => { @@ -1939,6 +2129,7 @@ impl ImportJob { Known::New => Sorted::Todo(f), Known::Follows { id, hash } => { self.by_path.insert(f.clone(), (id, false, hash)); + self.following.insert(f.clone()); follow.insert(f.clone(), id); Sorted::Todo(f) } @@ -1953,7 +2144,8 @@ impl ImportJob { self.by_hash.insert(h.clone(), Some(id)); } // a file that was only browsed (Local) joins the library when it is imported for real - self.by_path.insert(f, (id, false, hash)); + self.by_path.insert(f.clone(), (id, false, hash)); + self.following.insert(f); self.done.fetch_add(1, Relaxed); Sorted::Item(PreparedItem::Promote(id)) } @@ -2012,8 +2204,13 @@ impl ImportJob { // found keeps precedence even when it can't be read, as on a manual reread // (`sidecar::read_packet`): the embedded values don't apply (upstream #3607). let raw = info.kind == MediaKind::Raw; - let packet = match crate::sidecar::find_sidecar_for_import(stems, self.naming, &path, listing) { + // a raw's companion JPEG (issue #1692): the file beside it with the same name, not becoming + // a photo of this import and not taken by another raw of it. A Copy or Move carries it to + // the raw's copy ([`run_transfer`]); added where it is, the record points at it directly. + let companion = if self.companions && (raw || is_raw_pair_name(&path)) { self.claim_companion(&path) } else { None }; + let packet = match crate::sidecar::find_sidecar_for_import(stems, self.naming, &path, listing).filter(|_| !self.opts.ignore_xmp) { Some(f) => std::fs::read_to_string(&f).inspect_err(|e| log::warn!("import {path}: sidecar {}: {e}", f.display())).ok(), + None if self.opts.ignore_xmp => None, None => info.xmp.clone(), }; let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); @@ -2079,7 +2276,7 @@ impl ImportJob { }; // Copy as DNG: the copied raw becomes a DNG (the copy is ours to replace) let dng = self.opts.convert_dng && mode == ImportMode::Copy && raw && !info.format.eq_ignore_ascii_case("DNG"); - return Planned { kept, next: Next::Transfer(Box::new(Transfer { path, info, sidecar, dir, how, dng, promote, family })) }; + return Planned { kept, next: Next::Transfer(Box::new(Transfer { path, info, sidecar, dir, how, dng, promote, family, companion })) }; } (ImportMode::Move, _) => { let reason = "already inside the destination or the library: added where it is"; @@ -2099,11 +2296,46 @@ impl ImportJob { next: Next::Item(match promote { // (planned for a transfer that turned out not to need one: joins where it is) Some(id) => PreparedItem::Promote(id), - None => PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed: None, promote: None, dng_not_made: None })), + None => PreparedItem::Ready(Box::new(ReadyFile { + path, + stored, + info, + sidecar, + placed: None, + promote: None, + dng_not_made: None, + companion, + companion_failed: None, + })), }), } } + /// The raw's companion JPEG (issue #1692): the file beside it with the same name and a JPEG + /// extension ([`folder_jpegs`], one listing per folder) that is not becoming a photo of this + /// import (a Local record's, or one the library has) and that no other planned raw took. The + /// first raw of a name keeps the file. + fn claim_companion(&mut self, raw: &str) -> Option { + let dir = Path::new(raw).parent()?.to_path_buf(); + let stem = Path::new(raw).file_stem()?.to_string_lossy().to_lowercase(); + let jpegs = self.folder_jpegs.entry(dir.clone()).or_insert_with(|| folder_jpegs(&dir)); + let (Some(jpegs), stem) = (jpegs.as_ref(), stem) else { return None }; + for (s, path) in jpegs { + if *s == stem { + let p = path.clone(); + if self.by_path.contains_key(&p) + || self.following.contains(&p) + || self.library_paths.contains(&normalize_import_path(&p)) + || !self.claimed_companions.insert(p.clone()) + { + continue; + } + return Some(p); + } + } + None + } + /// A transfer's outcome, as it arrives: a copy that is ready makes its content a duplicate for /// the files after it. fn note_transfer(&mut self, item: &PreparedItem) { @@ -2203,6 +2435,120 @@ fn import_stems(library: Option<&lcc_catalog::Catalog>, todo: &[String], prob ) } +/// Whether a file name is a JPEG that can be a raw's companion (issue #1692). Only JPEGs pair, +/// as in Lightroom Classic; a PNG or TIFF beside a raw stays its own photo. +fn is_jpeg_pair_name(name: &str) -> bool { + matches!(Path::new(name).extension().map(|e| e.to_string_lossy().to_lowercase()).as_deref(), Some("jpg" | "jpeg")) +} + +/// Whether a file name is a raw file a companion JPEG can belong to (issue #1692): the raw +/// extensions import discovers. A probe that read the file ([`MediaKind::Raw`]) says it more +/// reliably; this is the name-only answer. +fn is_raw_pair_name(name: &str) -> bool { + matches!( + Path::new(name).extension().map(|e| e.to_string_lossy().to_lowercase()).as_deref(), + Some( + "dng" + | "cr2" + | "cr3" + | "nef" + | "nefx" + | "nrw" + | "arw" + | "sr2" + | "srf" + | "raf" + | "orf" + | "rw2" + | "rwl" + | "raw" + | "pef" + | "srw" + | "iiq" + | "crw" + | "mrw" + | "x3f" + | "kdc" + | "mos" + | "erf" + | "3fr" + | "fff" + | "mef" + | "gpr" + ) + ) +} + +/// The folder and lower-cased name without extension a companion pair is matched by +/// ([`companion_pairs`]): two files of a folder with the same name belong together, whatever +/// their extensions' letter case (as on the case-insensitive volumes most photos come from). +fn companion_key(path: &str) -> (String, String) { + let p = Path::new(path); + let dir = p.parent().map(|d| d.to_string_lossy().to_lowercase()).unwrap_or_default(); + let stem = p.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default(); + (dir, stem) +} + +/// The JPEG files of `dir`, as (name without extension, lower-cased, exact path). `None`: the +/// folder can't be listed. One listing per folder ([`ImportJob::claim_companion`]'s cache). +fn folder_jpegs(dir: &Path) -> Option> { + let rd = std::fs::read_dir(if dir.as_os_str().is_empty() { Path::new(".") } else { dir }).ok()?; + let mut out = Vec::new(); + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().to_string(); + let Some((stem, ext)) = name.rsplit_once('.') else { continue }; + if !matches!(ext.to_lowercase().as_str(), "jpg" | "jpeg") || !e.path().is_file() { + continue; + } + out.push((stem.to_lowercase(), e.path().to_string_lossy().to_string())); + } + Some(out) +} + +/// The companion pairing (issue #1692) of a whole import's files: every JPEG whose folder and +/// name match a raw's — a raw this import adds, or one the library already has at that name +/// beside it — is not a photo of its own. Name-based and computed once over every file, so a pair +/// split across two batches of a streamed import still comes out as one photo; that the library +/// has the JPEG, or that it carries a Local (browsed) record, is asked when the pairing is used +/// ([`ImportJob::by_path`], [`ImportJob::following`]). +fn companion_plan(cat: Option<&lcc_catalog::Catalog>, files: &[String]) -> HashMap { + // the raws of this import, then the library's raws beside its JPEG candidates, by folder and + // name: the first raw of a name keeps its JPEG (two raws of one name in a folder share + // nothing else). A JPEG can pair with a raw that only arrives later in the list (or that the + // library already has), so the pairing is worked out over the whole import's files + let mut raws: HashMap<(String, String), CompanionOf> = HashMap::new(); + let mut jpegs: HashMap<(String, String), ()> = HashMap::new(); + for path in files { + if is_raw_pair_name(path) { + raws.entry(companion_key(path)).or_insert_with(|| CompanionOf::Batch(path.clone())); + } else if is_jpeg_pair_name(path) { + jpegs.insert(companion_key(path), ()); + } + } + if let Some(cat) = cat + && !jpegs.is_empty() + { + for p in cat.photos().filter(|p| !p.deleted && !p.local && p.copy_of.is_none()) { + let Some(path) = crate::sidecar::file_path(p) else { continue }; + if !is_raw_pair_name(path) && p.kind != MediaKind::Raw { + continue; + } + if jpegs.contains_key(&companion_key(path)) { + raws.entry(companion_key(path)).or_insert(CompanionOf::Library(p.id)); + } + } + } + let mut out = HashMap::new(); + for path in files { + if is_jpeg_pair_name(path) + && let Some(raw) = raws.get(&companion_key(path)) + { + out.insert(path.clone(), raw.clone()); + } + } + out +} + /// A batch's items in file order while its transfers are pending ([`ImportJob::run_plan`]). #[derive(Default)] struct Plan { @@ -2230,6 +2576,9 @@ struct Transfer { /// The folder (lowercase) and [`name_family`]: transfers of one family can take each other's /// names, so they never run at the same time. family: (String, String), + /// The raw's companion JPEG (issue #1692) at its source: carried to the copy ([`run_transfer`]), + /// under the raw copy's name with the JPEG's own extension. + companion: Option, } enum How { @@ -2429,7 +2778,7 @@ fn transfer_ok(item: &PreparedItem) -> bool { /// Copy or move one planned file (and Copy as DNG); its item. fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> PreparedItem { - let Transfer { path, mut info, sidecar, dir, how, dng, promote, .. } = t; + let Transfer { path, mut info, sidecar, dir, how, dng, promote, companion, .. } = t; let mut placed = None; let mut stored = match how { How::Place { name } => match crate::import_move::place(Path::new(&path), &dir, &name) { @@ -2469,7 +2818,41 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P } } } - PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, promote, dng_not_made })) + // the raw's companion JPEG (issue #1692) travels to the copy, named after it with the JPEG's + // own extension. A Move carries the pair together: a companion that can't be placed takes the + // raw's placement back, and both stay at the source. A Copy leaves a companion that can't be + // copied at its source, and the report says so — the raw is imported all the same. + let mut companion_stored = None; + let mut companion_failed = None; + if let Some(src) = companion { + let ext = Path::new(&src).extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); + let stem = Path::new(&stored).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + match placed.take() { + Some(mut pl) => { + if let Err(e) = crate::import_move::place_companion(&mut pl, Path::new(&src)) { + crate::import_move::rollback(&pl); + return PreparedItem::Failed(path, format!("{e} (the raw stays with its companion)")); + } + companion_stored = pl.companions.last().map(|c| c.dst.to_string_lossy().to_string()); + placed = Some(pl); + } + None => match crate::import_move::copy_new(Path::new(&src), &dir, &format!("{stem}{ext}"), None) { + Ok(c) => companion_stored = Some(c.to_string_lossy().to_string()), + Err(e) => companion_failed = Some((src, e)), + }, + } + } + PreparedItem::Ready(Box::new(ReadyFile { + path, + stored, + info, + sidecar, + placed, + promote, + dng_not_made, + companion: companion_stored, + companion_failed, + })) } /// The warning for a Copy as DNG the work gate refused. @@ -2518,6 +2901,10 @@ fn commit_prepared_inner(s: &mut Session, opts: &ImportOptions, now: &str, prepa let mut plugin_fields: Vec<(PhotoId, Vec<(String, String, String)>)> = Vec::new(); // photos added by this batch, by content (a duplicate of a file earlier in the import names it) let mut new_hash: HashMap = HashMap::new(); + // this batch's raws by their own path (companions, issue #1692: a skipped JPEG is matched to + // the raw beside it, which may be added before or after it) + let mut stored_of: HashMap = HashMap::new(); + let mut pending_companions: Vec<(String, CompanionOf)> = Vec::new(); // Fresh: trashed photos a new import replaces (by content or by file), each removed once let mut trash_content: HashMap = HashMap::new(); let mut trash_path: HashMap = HashMap::new(); @@ -2608,21 +2995,29 @@ fn commit_prepared_inner(s: &mut Session, opts: &ImportOptions, now: &str, prepa PreparedItem::Ready(r) if r.promote.is_some_and(|id| s.catalog.photo(id).is_some_and(|p| p.local)) => { // a browsed photo copied or moved: its record follows the file into the library, // keeping its culling and edits - let ReadyFile { path, stored, info, placed: pl, promote, dng_not_made, .. } = *r; + let ReadyFile { path, stored, info, placed: pl, promote, dng_not_made, companion_failed, .. } = *r; placed.extend(pl); let Some(id) = promote else { continue }; + if let Some((src, why)) = companion_failed { + report.kept.push(Kept { path: src, reason: format!("its raw was imported: {why}") }); + } report.warnings.extend(dng_warning(&path, id, dng_not_made)); let file_name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| stored.clone()); let format = s.catalog.photo(id).filter(|p| p.format != info.format).map(|_| info.format.clone()); ops.push(Op::Relink { id, file_name, source: Source::File { path: stored.clone() }, format }); ops.push(Op::SetLocal { id, local: false }); promote_ops(s, id, opts, &now, &mut ops); + // the raw this import added: a companion skipped beside it is its (source path) + stored_of.insert(path, id); report.imported.push(id.0); } PreparedItem::Ready(r) => { - let ReadyFile { path, stored, info, sidecar, placed: pl, dng_not_made, .. } = *r; + let ReadyFile { path, stored, info, sidecar, placed: pl, dng_not_made, companion, companion_failed, .. } = *r; placed.extend(pl); let id = s.catalog.alloc_photo_id(); + if let Some((src, why)) = companion_failed { + report.kept.push(Kept { path: src, reason: format!("its raw was imported: {why}") }); + } report.warnings.extend(dng_warning(&path, id, dng_not_made)); if let Some(h) = &info.content_hash { new_hash.insert(h.clone(), id); @@ -2652,6 +3047,8 @@ fn commit_prepared_inner(s: &mut Session, opts: &ImportOptions, now: &str, prepa p.label = info.label_text.as_deref().and_then(|t| s.catalog.label_from_name(t)).or(info.label); p.as_shot_wb = info.as_shot_wb; p.content_hash = info.content_hash; + // a raw imported with companions on: the JPEG beside it is not a photo of its own + p.companion_jpeg = companion; if opts.import_duplicates && let Some(h) = p.content_hash.clone() && !live_hash.insert(h.clone()) @@ -2750,8 +3147,31 @@ fn commit_prepared_inner(s: &mut Session, opts: &ImportOptions, now: &str, prepa p.set_local_baseline(); } ops.push(Op::AddPhoto { photo: Box::new(p) }); + // the raw this import added: a companion skipped beside it is its (source path) + stored_of.insert(path, id); } + PreparedItem::Companion { path, raw } => pending_companions.push((path, raw)), + } + } + // the companions (issue #1692) that were skipped: the raws they belong to are known once the + // batch's records exist (a JPEG and its raw may arrive in either order). A raw this import + // adds carries its companion on its own record ([`ReadyFile::companion`]); only a raw the + // library already has is pointed at the JPEG here. + for (path, raw) in pending_companions { + let id = match raw { + CompanionOf::Library(id) => Some(id), + // the raw of this batch: its own record carries the companion ([`ReadyFile::companion`]); + // one that sorted out as a duplicate was already the library's — the companion is its + CompanionOf::Batch(source) => stored_of.get(&source).copied().or_else(|| { + s.catalog.photos().find(|p| !p.deleted && !p.local && matches!(&p.source, Source::File { path } if *path == source)).map(|p| p.id) + }), + }; + if let Some(id) = id + && s.catalog.photo(id).is_some_and(|p| p.companion_jpeg.as_deref() != Some(path.as_str())) + { + ops.push(Op::SetCompanion { id, companion: Some(path.clone()) }); } + report.companions.push(CompanionPair { path, raw: id.map(|i| i.0) }); } // (built against the catalog as it is: one op list for all of them, ahead of the additions) if !purge.is_empty() { @@ -2803,10 +3223,14 @@ fn apply_settings(s: &Session, p: &mut Photo, opts: &ImportOptions, now: &str) { if let Some(mp) = opts.metadata_preset.as_ref().and_then(|n| s.metadata_presets.iter().find(|m| m.name.eq_ignore_ascii_case(n))) { crate::cmd::metadata::apply_to(&mut p.meta, &mp.fields); } - for k in &opts.keywords { - let k = lcc_catalog::keywords::clean(k); - if !k.is_empty() && !p.meta.keywords.iter().any(|x| x.eq_ignore_ascii_case(&k)) { - p.meta.keywords.push(k); + // Most imports add no keywords: don't index the file's existing keywords then. + if !opts.keywords.is_empty() { + let mut seen: std::collections::HashSet = p.meta.keywords.iter().map(|k| k.to_lowercase()).collect(); + for k in &opts.keywords { + let k = lcc_catalog::keywords::clean(k); + if !k.is_empty() && seen.insert(k.to_lowercase()) { + p.meta.keywords.push(k); + } } } // the camera profile before the presets: a preset doesn't take it away unless the import says so @@ -2877,6 +3301,14 @@ fn finish_moves(s: &mut Session, placed: Vec, log0: Ok(kept) => { let sidecars = p.sidecars.iter().map(|sc| sc.dst.to_string_lossy().to_string()).collect(); report.moved.push(Moved { from, to: p.dst.to_string_lossy().to_string(), sidecars }); + // the raw's companion JPEG went with it (issue #1692): its own entry + for c in &p.companions { + report.moved.push(Moved { + from: c.src.to_string_lossy().to_string(), + to: c.dst.to_string_lossy().to_string(), + sidecars: Vec::new(), + }); + } report.kept.extend(kept.into_iter().map(|(path, reason)| Kept { path, reason })); } Err(reason) => { @@ -3085,6 +3517,8 @@ mod prepared_tests { placed: None, promote: None, dng_not_made: None, + companion: None, + companion_failed: None, }; let mut prepared = Prepared { scanned: 2, @@ -3131,6 +3565,8 @@ mod prepared_tests { placed: None, promote: None, dng_not_made: Some(ImportWarningCode::DngMemoryHeld), + companion: None, + companion_failed: None, })), ], }; diff --git a/crates/engine/src/import/stream.rs b/crates/engine/src/import/stream.rs index bda0bc7884..2b7103911a 100644 --- a/crates/engine/src/import/stream.rs +++ b/crates/engine/src/import/stream.rs @@ -29,7 +29,8 @@ use lcc_catalog::PhotoId; use lcc_catalog::folders::VolumeKey; use super::{ - How, ImportJob, Next, Planned, Prepared, PreparedItem, Sorted, Transfer, import_stems, probe_outcome, transfer_ok, transfer_outcome, workers, + How, ImportJob, Next, Planned, Prepared, PreparedItem, Sorted, Transfer, companion_plan, import_stems, probe_outcome, transfer_ok, + transfer_outcome, workers, }; use crate::io_sched::pool::Stream; use crate::io_sched::{IoContext, JobOutcome}; @@ -277,6 +278,12 @@ impl ImportJob { } // the library as it was, for the first batch's stem sidecars (as prepare_files gives it) let mut library = self.look_up_library(); + // the companion pairing (issue #1692) is the whole import's: computed once over every + // file, so a JPEG and its raw in different batches still come out as one photo + if !self.companion_planned { + self.companion_plan = if self.companions { companion_plan(library.as_ref(), &files) } else { Default::default() }; + self.companion_planned = true; + } let mut run = Run::new(ctx, look.checked(), cancel, files, self.file_bytes.clone()); let chunks = run.files.len().div_ceil(run.look.batch); for k in 0..chunks { @@ -363,6 +370,17 @@ impl ImportJob { out.cut_short = true; break; } + // a JPEG beside its raw (companions on, issue #1692): not a photo of its own; the raw + // already in the library is pointed at it. Not one: a file the library has a photo at + // (a duplicate here), or one with a Local record ([`ImportJob::companion_plan`]) + if !self.by_path.contains_key(&path) + && !self.following.contains(&path) + && let Some(raw) = self.companion_plan.get(&path).cloned() + { + out.items.push(PreparedItem::Companion { path, raw }); + run.release(pos); + continue; + } let info = match info { Ok(i) => i, Err(e) => { diff --git a/crates/engine/src/import/tests_stream.rs b/crates/engine/src/import/tests_stream.rs index f430a096ce..779f710fab 100644 --- a/crates/engine/src/import/tests_stream.rs +++ b/crates/engine/src/import/tests_stream.rs @@ -104,6 +104,7 @@ fn describe(item: &PreparedItem, root: &str) -> String { PreparedItem::Copying(path) => format!("copying {path}"), PreparedItem::Kept(k) => format!("kept {} {}", k.path, k.reason), PreparedItem::Ready(r) => format!("ready {} -> {} {} placed={}", r.path, r.stored, r.info.format, r.placed.is_some()), + PreparedItem::Companion { path, .. } => format!("companion {path}"), }; s.replace(root, "") } diff --git a/crates/engine/src/import/tests_transfers.rs b/crates/engine/src/import/tests_transfers.rs index f32e78c591..76fecde522 100644 --- a/crates/engine/src/import/tests_transfers.rs +++ b/crates/engine/src/import/tests_transfers.rs @@ -70,6 +70,7 @@ fn transfer(src: &Path, dir: &Path, how: How, dng: bool) -> Transfer { dng, promote: None, family: (dir.to_string_lossy().to_lowercase(), name_family(&name)), + companion: None, } } diff --git a/crates/engine/src/import_move.rs b/crates/engine/src/import_move.rs index 4cb73a8c59..ce815c7d1b 100644 --- a/crates/engine/src/import_move.rs +++ b/crates/engine/src/import_move.rs @@ -33,6 +33,15 @@ pub(crate) struct Placed { pub src: PathBuf, pub dst: PathBuf, pub sidecars: Vec, + /// A raw's companion JPEG (issue #1692) placed beside it, sources untouched like the raw's. + pub companions: Vec, +} + +/// A companion JPEG put beside its raw by [`place_companion`]. +#[derive(Clone, Debug)] +pub(crate) struct PlacedCompanion { + pub src: PathBuf, + pub dst: PathBuf, } #[derive(Clone, Debug)] @@ -236,7 +245,7 @@ pub(crate) fn place(src: &Path, dir: &Path, name: &str) -> Result Result<(), String> { + let ext = src.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); + let stem = placed.dst.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + let dir = placed.dst.parent().map(Path::to_path_buf).unwrap_or_default(); + let c = place(src, &dir, &format!("{stem}{ext}"))?; + placed.companions.push(PlacedCompanion { src: c.src, dst: c.dst }); + Ok(()) +} + /// Undo a [`place`]: remove what it created at the destination (the sources were never touched). pub(crate) fn rollback(p: &Placed) { for sc in p.sidecars.iter().filter(|s| s.created) { let _ = fs::remove_file(&sc.dst); } + for c in &p.companions { + let _ = fs::remove_file(&c.dst); + } let _ = fs::remove_file(&p.dst); } - -/// Remove a placed photo's source (its catalog record is committed and saved): only when the /// destination is still there with the same bytes. Then its sidecars, unless another photo still /// uses a shared one. `Err` = the source was kept (why); `Ok` lists sidecars kept (path, why). pub(crate) fn finish(p: &Placed) -> Result, String> { @@ -351,6 +374,18 @@ pub(crate) fn finish(p: &Placed) -> Result, String> { kept.push((path, format!("could not remove the sidecar ({e})"))); } } + // the companions move with their raw: their destinations were verified with its, their + // sources go once its did (a companion whose copy changed stays at the source) + for c in &p.companions { + let path = c.src.to_string_lossy().to_string(); + if !same_bytes(&c.src, &c.dst).unwrap_or(false) { + kept.push((path, format!("{} is missing or changed: the companion is kept", c.dst.display()))); + continue; + } + if let Err(e) = fs::remove_file(&c.src) { + kept.push((path, format!("could not remove the companion ({e})"))); + } + } Ok(kept) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2224a2233..2bf0e60e2e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -68,6 +68,7 @@ pub mod eyes; pub mod face_download; #[cfg(not(target_arch = "wasm32"))] mod face_suggestions; +pub mod face_thumbs; pub mod face_tiles; #[cfg(not(target_arch = "wasm32"))] mod faces_index; @@ -191,7 +192,7 @@ use lcc_develop::DevelopSettings; pub use lcc_filters::analysis_status as plugin_analysis_status; pub use media::{RenderJob, SourceLevel}; use serde_json::Value; -pub use view::{Browse, FilterChip, LibrarySource, Selection, SelectionState, filter_chips}; +pub use view::{Browse, CustomOrderSource, FilterChip, LibrarySource, Selection, SelectionState, filter_chips}; pub use {lcc_catalog as catalog, lcc_develop as develop, lcc_gpu as gpu, lcc_pipeline as pipeline}; /// [`Session::before_step`]: the commit count and the length of the queue of ops not yet written to the library's log. @@ -707,6 +708,8 @@ pub struct Session { pub(crate) face_detect_results: Vec<(PhotoId, std::result::Result, String>)>, /// The last `eyes.analyze` run in the background. pub(crate) eye_prep: Option>, + /// The last `faces.buildThumbnails` run in the background. + pub(crate) face_thumbs: Option>, /// Look-alike signatures by content key (Find Similar). pub signatures: std::collections::HashMap, /// Imported `.cube` LUT profiles. @@ -1048,6 +1051,7 @@ impl Session { face_detect: None, face_detect_results: Vec::new(), eye_prep: None, + face_thumbs: None, signatures: Default::default(), lut_profiles: Vec::new(), target_album: None, @@ -2374,12 +2378,16 @@ impl Session { self.view_filter(self.source, &Filter::default()) } }); - // Views whose order or photos are not the query's alone are worked out whole each time: an album in - // its own order, a semantic search (ordered by similarity rank), Recently Added (how far back it - // reaches moves with every import), Missing Photos. - let own_order = matches!(self.source, LibrarySource::Album(a) if self.sort.key == lcc_catalog::SortKey::Custom + // Views whose order or photos are not the query's alone are worked out whole each time: an album or + // a folder in its own order, a semantic search (ordered by similarity rank), Recently Added (how far + // back it reaches moves with every import), Missing Photos. + let own_order = self.sort.key == lcc_catalog::SortKey::Custom && self.filter == Filter::default() - && self.catalog.album(a).is_some_and(|al| !al.is_smart())); + && match &self.source { + LibrarySource::Album(a) => self.catalog.album(*a).is_some_and(|al| !al.is_smart()), + LibrarySource::LibraryFolder => self.custom_order_source().is_some(), + _ => false, + }; let whole = own_order || self.filter.semantic.is_some() || matches!(self.source, LibrarySource::RecentlyAdded | LibrarySource::Missing); // A view that asks about "the last N days" (itself, or through a smart album it looks into) changes // with the clock as well as with edits: a photo nobody touched can stop matching. It is asked whole. @@ -2579,6 +2587,23 @@ impl Session { f } + /// The album or folder the library shows whose photos can be put in Custom Order + /// ([`CustomOrderSource`]), if any: what `library.sort {key: custom}` sorts by here and what + /// a drag in the grid rearranges. A folder shown with the photos of the folders inside it has + /// no one order (unless nothing is below it: the view is its own photos then), and neither + /// does a folder only browsed in Local. + pub fn custom_order_source(&self) -> Option { + match &self.source { + LibrarySource::Album(a) if self.catalog.has_custom_order(*a) => Some(CustomOrderSource::Album(*a)), + LibrarySource::LibraryFolder => self + .library_folder + .as_deref() + .filter(|p| self.catalog.folder_view_has_custom_order(p, self.folder_subfolders)) + .map(|p| CustomOrderSource::Folder(p.to_string())), + _ => None, + } + } + /// Let go of what a held view kept: the view shows what matches now ([`Session::hold_view`]). pub fn refresh_view(&mut self) { self.base = None; @@ -2978,8 +3003,13 @@ mod tests_face_models; mod tests_face_recognize; #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] +mod tests_face_thumbs; +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] mod tests_face_tiles; #[cfg(test)] +mod tests_facet_multi; +#[cfg(test)] mod tests_facets; #[cfg(test)] mod tests_filesystem_history; @@ -3016,6 +3046,8 @@ mod tests_immich; #[cfg(test)] mod tests_import; #[cfg(test)] +mod tests_import_companions; +#[cfg(test)] mod tests_import_local; #[cfg(test)] mod tests_import_move; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 25d65a717e..89c49e7ba9 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -1692,6 +1692,22 @@ impl Session { } /// Catalog-level operations (native: a catalog is a folder with a v4 store). +impl Session { + /// Whether JPEGs beside raws import as the raw's companions (issue #1692): the open + /// catalog's setting (`CatalogSettings::raw_jpeg_companions`). + #[cfg(not(target_arch = "wasm32"))] + pub fn raw_jpeg_companions(&self) -> bool { + self.catalog_settings().raw_jpeg_companions + } + + /// Whether JPEGs beside raws import as the raw's companions (issue #1692). The browser keeps + /// no catalog settings file, so it is what a library without one has: on. + #[cfg(target_arch = "wasm32")] + pub fn raw_jpeg_companions(&self) -> bool { + true + } +} + #[cfg(not(target_arch = "wasm32"))] impl Session { /// The open catalog's folder, when it is one on disk with a v4 store (backup, integrity diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 7f3313a00c..264c615c1b 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -128,6 +128,8 @@ const NAME_PREFIX: &str = "lightroom-import-"; const NAME_SUFFIX: &str = ".lca"; const MAX_SCAN: usize = 1024; const IO_BUFFER: usize = 16 * 1024; +/// JSON gathered before each compressor call when writing an archive. +const JSON_BUFFER: usize = 1024 * 1024; /// Store compact source data below `directory` and return its managed archive. /// @@ -346,7 +348,14 @@ fn write_archive(path: &Path, data: &CatalogImport, settings: bool, limit: u64) let mut bounded = BoundedWriter { inner: raw, total: 0, limit }; bounded.write_all(HEADER)?; let mut compressor = ZlibWriter::new(&mut bounded, limit.saturating_mul(MAX_JSON_PER_DISK_BYTE)); - serde_json::to_writer(&mut compressor, &ArchiveRef(data, settings)).map_err(json_io)?; + // serde_json writes each token on its own: gather them, so the compressor works on large blocks (as the + // journal's snapshot writer does). + let mut buffered = io::BufWriter::with_capacity(JSON_BUFFER, &mut compressor); + let written = serde_json::to_writer(&mut buffered, &ArchiveRef(data, settings)).map_err(json_io).and_then(|()| buffered.flush()); + // Taken apart rather than dropped: after an error (the archive too big), dropping would flush the rest + // into the compressor that refused it. + let _ = buffered.into_parts(); + written?; compressor.finish()?; Ok(()) }) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 46775e432b..1375a5fe9d 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1560,6 +1560,14 @@ fn read_lightroom(path: &Path, reader: Reader, source_guard: SourceGuard, cancel Ok(out) } +/// A video the catalog lists with the format `VIDEO` and a video extension. It becomes a video record +/// by reference, so the import never runs an image probe on it (adapted from upstream #4741). +pub(crate) 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))) +} + /// How many of the images left out of an import (no file, folder or root record) the warnings name one by one. const LEFT_OUT_NAMED: usize = 20; /// Drop the virtual copies whose master was skipped, adding them to the skipped images: a copy has @@ -1775,6 +1783,26 @@ fn custom_as_shot(reader: &Reader, develops: &HashMap, cancel: &Ato found } +/// The id of the installed base curve whose file stem is `stem` (a Capture One film curve's file name), or `None` +/// when no such curve file is installed. The folder is read when nothing is installed yet, and once more per import +/// when a curve is missing but its file is in the folder (it was added since the last scan). +fn capture_one_curve_installed(stem: &str, rescanned: &mut bool) -> Option { + use lcc_develop::base_curve; + if base_curve::library().is_empty() { + crate::base_curves::install_once(); + } + let id = base_curve::id_for(stem); + if base_curve::get(&id).is_some() { + return Some(id); + } + if !*rescanned && crate::base_curves::dir().is_some_and(|d| d.join(format!("{stem}.json")).is_file()) { + *rescanned = true; + crate::base_curves::refresh(); + return base_curve::get(&id).map(|_| id); + } + None +} + /// Lightroom's `Adobe_images.orientation`: where the stored image's top-left and top-right corners /// land in the displayed photo, naming the displayed corners A, B, C, D clockwise from the top left /// (`AB` upright, `BC` a quarter turn clockwise, `DA` a quarter turn counter-clockwise, `BA` mirrored). @@ -1917,7 +1945,12 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> .collect(); let missing_sources: HashSet = data.photos.iter().filter(|p| number(&p.image, "masterImage") == 0).filter(|p| !p.original_is_file()).map(|p| key(&p.path)).collect(); - let opts = crate::import::ImportOptions { mode: crate::import::ImportMode::Add, keep_sidecars: true, ..Default::default() }; + let opts = crate::import::ImportOptions { + mode: crate::import::ImportMode::Add, + keep_sidecars: true, + ignore_xmp: crate::capture_one_catalog::is_capture_one(Path::new(&data.source)), + ..Default::default() + }; let files = crate::import::import_with(s, &paths, &opts)?; let applied = match apply_prepared( s, @@ -2038,6 +2071,25 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co let mut unmapped = BTreeMap::new(); // Capture One white balances applied on the relative scale (`crate::capture_one_develop`): approximate let mut capture_one_wb_approximate = 0usize; + // Capture One exposures on rendered files above its highlight shoulder's start (`crate::capture_one_develop`): approximate + let mut capture_one_exposure_approximate = 0usize; + // Capture One tone settings that are only approximate (`crate::capture_one_develop::approximate`): a negative + // Highlight, a positive Shadow, a positive Saturation on a raw (as Vibrance), a negative Saturation on a rendered file + let mut capture_one_highlight_approximate = 0usize; + let mut capture_one_shadow_approximate = 0usize; + let mut capture_one_saturation_as_vibrance = 0usize; + let mut capture_one_saturation_rendered = 0usize; + // a positive Saturation on a rendered file, which isn't imported + let mut capture_one_saturation_unimported = 0usize; + // Capture One film curves whose base curve file isn't installed, by file stem, with the photos using each + let mut capture_one_missing_curves: BTreeMap = BTreeMap::new(); + // (the curve folder is scanned again once per import, when a curve is missing but its file is in the folder) + let mut capture_one_rescanned = false; + // Capture One photos with a film curve that weren't developed as raws (a file the app can't develop, or not read) + let mut capture_one_not_raw = 0usize; + // Capture One images that share their original with an earlier image of the import, and so its record + let mut capture_one_shared_originals = 0usize; + let mut records_seen: HashSet = HashSet::new(); let mut preserved = 0; let mut history_imported = 0usize; let mut snapshots_imported = 0usize; @@ -2049,6 +2101,14 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co let copy_masters: HashSet<_> = data.photos.iter().map(|p| number(&p.image, "masterImage")).filter(|id| *id != 0).collect(); let refused: HashSet<_> = data.photos.iter().filter(|p| matches!(p.original, Original::Refused(_))).map(|p| p.source_id).collect(); let mut planned: HashMap = HashMap::new(); + // A Capture One variant is its own photo: a further variant of an image (a virtual copy) starts from its master's + // record as it was before the master's catalog data was applied, and with no develop settings, import look or edit + // date of the master's. (A Lightroom virtual copy's own settings replace its master's, so it keeps starting from + // the master as it is.) + let is_capture_one = crate::capture_one_catalog::is_capture_one(Path::new(&data.source)); + // (for the lines of the result window that name the program the catalog came from) + let source_name = if is_capture_one { "Capture One" } else { "Lightroom" }; + let mut unmerged_masters: HashMap = HashMap::new(); // diagnostics (issue #1363): the per-photo loop as one step, how far it has got, and each photo's time in aggregate // `done` counts the photos finished before the current one (a hang in photo k shows done=k-1); an error passed up // with `?` ends the stage `abandoned`, and the enclosing `lightroom_commit` records the error @@ -2077,19 +2137,39 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co .filter(|id| !created.contains(id)); let existing_id = indexed.or_else(|| if master == 0 { by_path.get(&key(&src.path)).copied() } else { None }).filter(|id| !created.contains(id)); + // (a Capture One image whose original another image of this import already has: the two share one record) + if is_capture_one + && master == 0 + && let Some(id) = existing_id + && !records_seen.insert(id) + { + capture_one_shared_originals = capture_one_shared_originals.saturating_add(1); + } // a record made here from the catalog alone: an original that is missing, or not read yet (issue #1303) let mut catalog_only = false; let mut p = if let Some(id) = existing_id.and_then(|id| s.catalog.photo(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)))?; - let mut p = planned - .get(&master_id) + let from = if is_capture_one { unmerged_masters.get(&master_id) } else { planned.get(&master_id) }; + let mut p = from .cloned() .or_else(|| s.catalog.photo(master_id).map(|p| (**p).clone())) .ok_or_else(|| error("virtual copy master is unavailable"))?; p.id = s.catalog.alloc_photo_id(); p.copy_of = Some(master_id); + if is_capture_one { + // nothing of the master's own edits comes along: the copy has the camera's defaults, and only its own + // variant's settings go on top + p.develop = Arc::new(p.camera_defaults()); + p.import_look = None; + p.import_state = None; + p.before = None; + p.edited = None; + p.history.clear(); + p.history_cursor = None; + p.versions.clear(); + } p } else if let Some(duplicate) = duplicates.get(&key(&src.path)).and_then(|id| s.catalog.photo(*id)) { // Catalogs can contain distinct originals with identical bytes and independent edits. @@ -2108,7 +2188,9 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co let turned = lightroom_orientation(text(&src.image, "orientation")).is_some_and(|o| o.swaps_axes()); let (upright_w, upright_h) = if turned { (h, w) } else { (w, h) }; let mut p = Photo::new(id, Source::File { path: src.path.clone() }, &name, text(&src.image, "fileFormat"), upright_w, upright_h, &now); - if ["RAW", "DNG", "ARW", "CR2", "CR3", "NEF", "NRW", "RAF", "ORF", "RW2", "PEF"].contains(&p.format.to_uppercase().as_str()) { + // (a Capture One variant with a camera model and a film curve of a raw is one, whatever its extension) + let c1_raw = src.capture_one.as_deref().is_some_and(|c| c.film_curve.is_some()); + if c1_raw || ["RAW", "DNG", "ARW", "CR2", "CR3", "NEF", "NRW", "RAF", "ORF", "RW2", "PEF"].contains(&p.format.to_uppercase().as_str()) { p.kind = lcc_catalog::MediaKind::Raw; } catalog_only = true; @@ -2129,9 +2211,15 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co } ids.insert(src.source_id, p.id); index.photos.insert(identity(&data, src), p.id.0); + if is_capture_one && copy_masters.contains(&src.source_id) { + unmerged_masters.insert(p.id, p.clone()); + } // A record this import added, or a Local one untouched since browsing (an offline original // never reaches the add step, so it is judged here), holds no edits of the library's own. - let fresh = catalog_only || existing_id.is_some_and(|id| added.contains(&id) || s.catalog.photo(id).is_some_and(|q| q.untouched_local())); + let new_variant_copy = is_capture_one && master != 0 && existing_id.is_none(); + let fresh = catalog_only + || new_variant_copy + || existing_id.is_some_and(|id| added.contains(&id) || s.catalog.photo(id).is_some_and(|q| q.untouched_local())); // Every photo Lightroom has carries its edit date (below), so a date alone doesn't say the library edited it: // its settings or its History do. let library_edits = existing_id.is_some() && !fresh && p.edited.is_some() && (p.is_edited() || !p.history.is_empty()); @@ -2162,9 +2250,29 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co { p.develop = Arc::new(p.camera_defaults()); } + // a raw's Capture One film curve becomes the base curve of the same name when that file is installed, and the + // raw is then developed with the app's own colour; otherwise it keeps the default base tone and colour, and the + // curve is reported (a photo that isn't developed as a raw is reported on its own line) + let curve = match src.capture_one.as_deref() { + Some(c1) if src.settings.is_empty() && !keep_develop && !p.develops_raw() && c1.film_curve.is_some() => { + capture_one_not_raw = capture_one_not_raw.saturating_add(1); + None + } + Some(c1) if src.settings.is_empty() && !keep_develop && p.develops_raw() => c1.film_curve.as_deref().and_then(|stem| { + let found = capture_one_curve_installed(stem, &mut capture_one_rescanned); + if found.is_none() { + let count = capture_one_missing_curves.entry(stem.to_string()).or_default(); + *count = count.saturating_add(1); + } + found + }), + _ => None, + }; // a Capture One variant's settings (partial: what it uses) start from the camera's defaults too if fresh && src.settings.is_empty() && src.capture_one.as_deref().is_some_and(|c| !c.is_empty()) { - p.develop = Arc::new(p.camera_defaults()); + let relative = + curve.is_none() && p.relative_wb() || curve.is_some() && lcc_catalog::relative_wb_camera_as(p.colour_format(), &p.meta.camera, "lc"); + p.develop = Arc::new(p.camera_defaults_as(relative)); } if !src.xmp.is_empty() { match lcc_meta::parse_xmp(&src.xmp).map(|mut d| { @@ -2259,8 +2367,57 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co && !keep_develop { // what the variant uses that isn't imported is reported for it, settings applied or not - let target = crate::crs::Target::for_photo(&p); - let (partial, unknown) = crate::capture_one_develop::partial(c1, target, p.as_shot_wb); + let target = if curve.is_some() { crate::crs::Target::for_photo_as(&p, "lc") } else { crate::crs::Target::for_photo(&p) }; + // (a rendered file's exposure is converted: Capture One's acts on its encoded values; a raw's, even one shown from + // its preview, is taken as it is) + let rendered = p.kind == lcc_catalog::MediaKind::Image; + // (a photo that gets a curve is developed as the app's own colour, not through a profile of the user's: its + // white balance is converted through the camera database alone, not measured against an as-shot white the + // app may have read under such a profile) + let as_shot = if curve.is_some() { None } else { p.as_shot_wb }; + let (mut partial, unknown) = crate::capture_one_develop::partial_for(c1, target, as_shot, rendered); + if rendered && c1.exposure.is_some_and(crate::capture_one_develop::exposure_is_approximate) { + capture_one_exposure_approximate = capture_one_exposure_approximate.saturating_add(1); + } + let approximate = crate::capture_one_develop::approximate(c1, rendered); + capture_one_highlight_approximate = capture_one_highlight_approximate.saturating_add(usize::from(approximate.highlight)); + capture_one_shadow_approximate = capture_one_shadow_approximate.saturating_add(usize::from(approximate.shadow)); + capture_one_saturation_as_vibrance = capture_one_saturation_as_vibrance.saturating_add(usize::from(approximate.saturation_as_vibrance)); + capture_one_saturation_rendered = capture_one_saturation_rendered.saturating_add(usize::from(approximate.saturation_rendered)); + if unknown.iter().any(|u| u == crate::capture_one_develop::SATURATION_POSITIVE_RENDERED) { + capture_one_saturation_unimported = capture_one_saturation_unimported.saturating_add(1); + } + if let Some(id) = &curve { + let profile = serde_json::json!({"profile": {"camera": "lc", "base_curve": id}}); + if fresh || !p.is_edited() { + // Capture One's base look for a raw, the camera's own curve with the app's colour (and the as-shot + // white balance that goes with it), is the photo's baseline, not an edit: Reset returns to it, and + // a photo with nothing else imported stays unedited. A curve the variant chose itself goes on top + // of it as an edit; when the camera's own curve isn't installed the baseline has the colour only. + let baseline = if c1.film_curve_own { + c1.film_curve_default.as_deref().and_then(|stem| capture_one_curve_installed(stem, &mut capture_one_rescanned)) + } else { + Some(id.clone()) + }; + let mut base_profile = serde_json::json!({"camera": "lc"}); + if let (Some(base), Some(m)) = (&baseline, base_profile.as_object_mut()) { + m.insert("base_curve".into(), base.clone().into()); + } + let relative = lcc_catalog::relative_wb_camera_as(p.colour_format(), &p.meta.camera, "lc"); + let look = + Arc::new(lcc_develop::apply_partial(&p.camera_defaults_as(relative), &serde_json::json!({"profile": base_profile}), 1.0)); + p.import_look = Some(look.clone()); + p.develop = look; + if baseline.as_ref() != Some(id) + && let Some(map) = partial.as_object_mut() + { + map.insert("profile".into(), serde_json::json!({"base_curve": id})); + } + } else if let (Some(map), Some(extra)) = (partial.as_object_mut(), profile.as_object()) { + // a photo edited here that is updated: the curve and colour are applied as edits + map.extend(extra.clone()); + } + } if target == crate::crs::Target::RawRelative && partial.get("wb").is_some() { capture_one_wb_approximate = capture_one_wb_approximate.saturating_add(1); } @@ -2298,13 +2455,15 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co planned.insert(photo_id, p.clone()); } if let Some(old) = s.catalog.photo(p.id) { - if old.kind != p.kind || old.copy_name != p.copy_name { - // Repair older imports, and bring a changed Copy Name across (no op sets one), with existing - // reversible operations. Removing just the record leaves album/stack membership intact; the - // enclosing batch is atomic. The record's cached previews go with it, so they render again. + if old.kind != p.kind || old.copy_name != p.copy_name || old.import_look != p.import_look { + // Repair older imports, bring a changed Copy Name across, and give a photo the import look that is + // Capture One's base look (no op sets these), with existing reversible operations. Removing just the + // record leaves album/stack membership intact; the enclosing batch is atomic. The record's cached + // previews go with it, so they render again. let mut repaired = (**old).clone(); repaired.kind = p.kind; repaired.copy_name = p.copy_name.clone(); + repaired.import_look = p.import_look.clone(); ops.extend([Op::RemovePhoto { id: p.id }, Op::AddPhoto { photo: Box::new(repaired) }]); } if was_local && promoted.insert(p.id) { @@ -2326,7 +2485,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co ops.push(Op::SetCaptured { id: p.id, captured: p.captured.clone() }); } else if let (Some(stored), true) = (&stored, p.captured != stored) { warnings.push(format!( - "image {}: the library's capture time “{stored}” is not a date, so Lightroom's was not applied (undoing the import could not restore it)", + "image {}: the library's capture time “{stored}” is not a date, so {source_name}'s was not applied (undoing the import could not restore it)", src.source_id )); } @@ -2347,13 +2506,72 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co commit_part(s, step, &mut ops, undo0)?; } } + if capture_one_exposure_approximate > 0 { + warnings.push(format!( + "Capture One Exposure: approximate on {capture_one_exposure_approximate} photo(s); on a rendered file the exposure is converted, and above +{} EV Capture One's highlight shoulder isn't reproduced", + crate::capture_one_develop::EXPOSURE_SHOULDER_EV + )); + } + if capture_one_highlight_approximate > 0 { + warnings.push(format!( + "Capture One Highlight: approximate on {capture_one_highlight_approximate} photo(s); strong negative values stay lighter than in Capture One in very bright areas" + )); + } + if capture_one_shadow_approximate > 0 { + warnings.push(format!( + "Capture One Shadow: approximate on {capture_one_shadow_approximate} photo(s); positive values are imported at twice their value, held to the app's 100, and strong lifts stay darker than in Capture One" + )); + } + if capture_one_saturation_as_vibrance > 0 { + warnings.push(format!( + "Capture One Saturation: positive values on {capture_one_saturation_as_vibrance} photo(s) are imported as Vibrance, which is approximate; skin tones stay less saturated than in Capture One, and strongly saturated colours are boosted a little less" + )); + } + if capture_one_saturation_rendered > 0 { + warnings.push(format!( + "Capture One Saturation: approximate on {capture_one_saturation_rendered} rendered file(s); negative values are imported one to one, and the most saturated colours don't darken as much as in Capture One" + )); + } + if capture_one_saturation_unimported > 0 { + warnings.push(format!( + "Capture One Saturation (positive values): used on {capture_one_saturation_unimported} rendered file(s), not imported yet (the photos keep the rest of their settings)" + )); + } if capture_one_wb_approximate > 0 { warnings.push(format!( "Capture One White Balance: approximate on {capture_one_wb_approximate} photo(s); their raws are edited on the \ relative white balance scale, where Capture One's change can only be approximated" )); } - if let Some(first) = untimed.first() { + if !capture_one_missing_curves.is_empty() { + let photos = capture_one_missing_curves.values().fold(0usize, |a, n| a.saturating_add(*n)); + // the most used first + let mut by_use: Vec<(&String, &usize)> = capture_one_missing_curves.iter().collect(); + by_use.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0))); + let named: Vec<&str> = by_use.iter().take(3).map(|(stem, _)| stem.as_str()).collect(); + let n = by_use.len(); + warnings.push(format!( + "Capture One base curve: {photos} photo(s) use a curve file that isn't installed ({n} curve{}, e.g. {}); they use the default \ + base tone. After adding the file, import the catalog again: photos with nothing else imported pick the curve up; photos that got \ + other Capture One settings keep theirs. To give them the curve, import into a new library with the file in place", + if n == 1 { "" } else { "s" }, + named.join(", ") + )); + } + if capture_one_shared_originals > 0 { + warnings.push(format!( + "Capture One: {capture_one_shared_originals} catalog image(s) point to the same original as an earlier image and were put on its record; the record keeps the settings of the last image that points to it" + )); + } + if capture_one_not_raw > 0 { + warnings.push(format!( + "Capture One base curve: {capture_one_not_raw} photo(s) have a film curve but were not set up as raws (a file the app can't develop \ + yet, or one that couldn't be read); no curve or colour was set for them" + )); + } + // (a Capture One catalog has no usable edit time for an image: its photos with settings are dated at the import and the line would + // only repeat that for nearly every photo) + if let Some(first) = untimed.first().filter(|_| !is_capture_one) { let named: Vec = untimed.iter().take(LEFT_OUT_NAMED).map(i64::to_string).collect(); let more = untimed.len() - named.len(); let more = if more > 0 { format!(" and {more} more") } else { String::new() }; @@ -2568,7 +2786,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co { album.parent = None; warnings.push(format!( - "{}: its collection set could not be created first; imported at the top level (Lightroom collection {})", + "{}: its collection set could not be created first; imported at the top level ({source_name} collection {})", album.name, number(collection, "id_local") )); @@ -2591,7 +2809,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co (None, None) => "at the top level".to_string(), }; // the Lightroom id tells apart collections that share a name (#2165) - warnings.push(format!("{}: {why}; imported {to} (Lightroom collection {})", album.name, number(collection, "id_local"))); + warnings.push(format!("{}: {why}; imported {to} ({source_name} collection {})", album.name, number(collection, "id_local"))); } if album.folder { added_folders.insert(id); @@ -2970,11 +3188,11 @@ pub(crate) mod tests { dropped.sort(); let mapped = PUBLIC_CRS_FIELDS.len() - dropped.len(); eprintln!("crs coverage: {mapped} of {} public fields map; dropped: {dropped:?}", PUBLIC_CRS_FIELDS.len()); - // No equivalent in the app: Lightroom's algorithm / tool bookkeeping (auto white version, + // No equivalent in the app: Lightroom's tool bookkeeping (auto white version is quiet since upstream #4747; // Upright's preview, centre mode and focal length: ours computes its own) and the pre-2012 // single Defringe switch. Reported as unmapped and kept in the archive. (Lens profile setup // is bookkeeping the import ignores, `crs::IGNORED`: not reported.) - let expected = ["AutoWhiteVersion", "Defringe", "UprightCenterMode", "UprightFocalLength35mm", "UprightPreview"]; + let expected = ["Defringe", "UprightCenterMode", "UprightFocalLength35mm", "UprightPreview"]; assert_eq!(dropped, expected, "{mapped} mapped"); } @@ -3260,6 +3478,22 @@ pub(crate) mod tests { assert!(s.catalog.photos().all(|p| p.copy_name.as_deref() != Some("Far copy")), "the refused original's copy became a record: {r}"); } + /// A Lightroom virtual copy still starts from its master's record: what its own settings text doesn't say + /// (here the master's Contrast), its edit history and its keywords come from the master, as before Capture One + /// variants were given their own start. + #[test] + fn a_lightroom_virtual_copy_still_starts_from_its_master() { + let mut s = crate::Session::new(); + apply(&mut s, sample(), false).unwrap(); + let master = s.catalog.photos().find(|p| p.copy_of.is_none()).unwrap().clone(); + let copy = s.catalog.photos().find(|p| p.copy_of == Some(master.id)).unwrap().clone(); + assert_eq!((master.develop.light.exposure, master.develop.light.contrast), (1.25, 17.0)); + assert_eq!(copy.develop.light.exposure, -0.5, "its own setting"); + assert_eq!(copy.develop.light.contrast, 17.0, "the master's, which the copy's settings don't mention"); + assert_eq!(copy.meta.keywords, master.meta.keywords); + assert_eq!((master.rating, copy.rating), (5, 2), "each has its own rating"); + } + #[test] fn offline_local_master_and_copy_join_library_with_one_undo_step() { let mut s = crate::Session::new(); @@ -5104,6 +5338,31 @@ pub(crate) mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn native_catalog_links_present_video_without_an_image_probe_failure() { + let dir = std::env::temp_dir().join(format!("app-lrcat-video-link-{}", std::process::id())); + std::fs::create_dir_all(dir.join("Photos")).unwrap(); + let path = dir.join("videos.lrcat"); + let clip = dir.join("Photos").join("clip.MOV"); + std::fs::write(&clip, b"opaque movie bytes").unwrap(); + let mut tables = photo_tables((dir.to_str().unwrap(), "")); + tables[2].2[2] = SqlValue::Text("clip.MOV".into()); + tables[3].2[3] = SqlValue::Text("VIDEO".into()); + std::fs::write(&path, native_catalog(&tables)).unwrap(); + let mut s = crate::Session::new(); + s.media.file_probe = Some(Arc::new(|_| Err("unsupported image format".into()))); + + let imported = s.execute("library.importLightroom", &json!({"path": path})).unwrap(); + + assert_eq!(imported["failed"], json!([])); + assert_eq!(imported["missing"], json!([])); + let id = PhotoId(imported["mapping"]["1"].as_u64().unwrap()); + let photo = s.catalog.photo(id).unwrap(); + assert_eq!(photo.kind, lcc_catalog::MediaKind::Video); + assert_eq!(photo.source, Source::File { path: clip.to_str().unwrap().into() }); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn native_video_reimport_repairs_kind_without_losing_edits_or_memberships() { let dir = std::env::temp_dir().join(format!("app-lrcat-video-reimport-{}", std::process::id())); diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index ed9f2122b5..4c5511a4fb 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -294,7 +294,13 @@ impl LightroomJob { /// Snapshot session state only. This constructor performs no filesystem work. pub fn new(s: &mut crate::Session, path: PathBuf, update_existing: bool) -> crate::Result { // a photo deleted here stays deleted: the catalog's record is matched, not restored - let opts = ImportOptions { mode: ImportMode::Add, on_deleted: crate::import::OnDeleted::Skip, ..ImportOptions::default() }; + let opts = ImportOptions { + mode: ImportMode::Add, + on_deleted: crate::import::OnDeleted::Skip, + // a Capture One catalog holds the settings and metadata itself: no sidecar or embedded XMP reaches its photos + ignore_xmp: crate::capture_one_catalog::is_capture_one(&path), + ..ImportOptions::default() + }; let import = ImportJob::new(s, opts)?; let archive_dir = s.library.as_ref().filter(|library| library.on_disk).map(|library| library.dir.join("Interop")); let progress = LightroomProgress { @@ -407,8 +413,13 @@ fn commit_prepared_inner(s: &mut crate::Session, mut prepared: PreparedLightroom let undo0 = s.undo.len(); prepared.normal.revalidate_add(s); // (each photo's sidecar is kept, to compare with the catalog's values once they are applied) - let options = - ImportOptions { mode: ImportMode::Add, on_deleted: crate::import::OnDeleted::Skip, keep_sidecars: true, ..ImportOptions::default() }; + let options = ImportOptions { + mode: ImportMode::Add, + on_deleted: crate::import::OnDeleted::Skip, + keep_sidecars: true, + ignore_xmp: crate::capture_one_catalog::is_capture_one(Path::new(&prepared.data.source)), + ..ImportOptions::default() + }; let now = prepared.now.clone(); let before = s.before_step(); let files = crate::import::commit_prepared(s, &options, &now, prepared.normal)?; @@ -483,10 +494,12 @@ fn original_paths(data: &CatalogImport, cancel: &AtomicBool) -> crate::Result<(V if !seen.insert(key.clone()) { continue; } - if photo.original_is_file() { - paths.push(photo.path.clone()); - } else { + if !photo.original_is_file() { missing.insert(key); + } else if !lightroom_catalog::is_catalog_video(photo) { + // Catalog videos are references. The image probe reads the entire + // file before rejecting it, even though its catalog entry is added. + paths.push(photo.path.clone()); } } Ok((paths, missing)) diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 9487eaeb3f..34dc856bb0 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -4278,6 +4278,8 @@ mod tests { /// and the panel then reads As Shot in Kelvin while the stored settings keep their look. #[test] fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_as_shot_white() { + // a fitted-look camera with measured matrices: no calibration (#1670 bundles one) or `.dcp` installed + let _profiles = crate::camera_profiles::NoInstalledProfiles::hold(); use lcc_develop::{WbMode, WbScale}; let mut s = crate::Session::new(); let id = s.catalog.alloc_photo_id(); diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 7ca2ea91a9..71ffb59c9c 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -233,6 +233,13 @@ pub fn without_unavailable_masks(preset: &Preset, available: bool) -> (Preset, V /// Expand files/folders (recursively, bounded: see [`crate::walk`]) into preset files /// (`.lcpreset`, `.xmp`). pub fn expand_preset_paths(paths: &[String]) -> Vec { + expand_preset_paths_with_seen(paths, &mut std::collections::HashSet::new()) +} + +/// [`expand_preset_paths`] sharing the canonical folders and files already expanded in `seen`, so +/// overlapping roots of one import (an alias, a folder inside another) yield each preset once, under +/// the first path that reached it (adapted from upstream #1638). +pub(crate) fn expand_preset_paths_with_seen(paths: &[String], seen: &mut std::collections::HashSet) -> Vec { let preset_file = |p: &Path| { let ext = p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); lcc_brand::preset_exts().any(|e| e == ext) @@ -252,12 +259,13 @@ pub fn expand_preset_paths(paths: &[String]) -> Vec { for p in paths { let path = Path::new(p); if path.is_dir() { - let w = crate::walk::files_in(path, None, crate::walk::Limits::default(), preset_file); + let w = crate::walk::files_in_with_seen(path, None, crate::walk::Limits::default(), preset_file, None, seen); out.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string())); } else { out.push(p.clone()); } } + out.retain(|p| std::fs::canonicalize(p).map_or(true, |real| seen.insert(real))); out } diff --git a/crates/engine/src/print/layout.rs b/crates/engine/src/print/layout.rs index afff879ed5..8c783d4e9f 100644 --- a/crates/engine/src/print/layout.rs +++ b/crates/engine/src/print/layout.rs @@ -632,7 +632,7 @@ impl Layout { return Err(format!("duplicate cell id {}", c.id)); } if c.page >= self.pages { - return Err(format!("cell {} is on page {} but the layout has {} pages", c.id, c.page + 1, self.pages)); + return Err(format!("cell {} is on page {} but the layout has {} pages", c.id, u64::from(c.page) + 1, self.pages)); } self.check_rect(&c.rect, area)?; } @@ -1409,3 +1409,23 @@ mod tests { } } } + +#[cfg(test)] +mod page_overflow_tests { + use super::{Layout, Style}; + + #[test] + fn oversized_cell_pages_are_errors_without_changing_the_layout() { + let mut source = Layout { style: Style::PicturePackage, ..Default::default() }; + let id = source.add_cell(2.0, 2.0).unwrap(); + source.validate().unwrap(); + for (page, shown) in [(1, "2"), (u32::MAX, "4294967296")] { + let mut value = serde_json::to_value(&source).unwrap(); + value["cells"][0]["page"] = serde_json::json!(page); + let mut imported: Layout = serde_json::from_value(value).unwrap(); + let before = imported.clone(); + assert_eq!(imported.validate().unwrap_err(), format!("cell {id} is on page {shown} but the layout has 1 pages")); + assert_eq!(imported, before, "a rejected page changed the layout"); + } + } +} diff --git a/crates/engine/src/proof.rs b/crates/engine/src/proof.rs index 046ff0a85b..3584bba3b3 100644 --- a/crates/engine/src/proof.rs +++ b/crates/engine/src/proof.rs @@ -16,7 +16,6 @@ pub struct ProofProfile { /// Load the profile at `path` for proofing with `intent`, simulating paper and ink or not. pub fn load(path: &str, intent: ProofIntent, paper_ink: bool) -> Result { - let path = path.trim(); let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?; if meta.len() > MAX_PROFILE_BYTES as u64 { return Err(format!("{path}: too large for an ICC profile")); @@ -45,6 +44,17 @@ mod tests { use super::*; use lcc_codecs::space::NamedSpace; + #[test] + fn loads_an_icc_path_with_trailing_whitespace() { + let profile = lcc_codecs::icc::write_named(NamedSpace::DisplayP3); + let path = std::env::temp_dir().join(format!("lc-proof-{}.icc\u{00a0}", std::process::id())); + std::fs::write(&path, &profile).unwrap(); + let result = load(path.to_str().unwrap(), ProofIntent::Perceptual, false); + std::fs::remove_file(&path).unwrap(); + let expected = from_bytes(&profile, ProofIntent::Perceptual, false, "x").unwrap(); + assert_eq!(result.unwrap().id, expected.id); + } + #[test] fn profiles_register_by_content_and_options() { let p3 = lcc_codecs::icc::write_named(NamedSpace::DisplayP3); diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index b7476100b4..be33f7069f 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -47,6 +47,10 @@ pub struct RenamePlan { pub from_path: Option, #[serde(skip_serializing_if = "Option::is_none")] pub to_path: Option, + /// The raw's companion JPEG (issue #1692) follows the rename, keeping its own extension: + /// (old path, new path). The record is pointed at the new path in the same step. + #[serde(skip_serializing_if = "Option::is_none")] + pub companion: Option<(String, String)>, } pub fn split_ext(name: &str) -> (&str, &str) { @@ -1357,7 +1361,32 @@ fn plan_rename_core( Source::File { path } => Some(path.clone()), _ => None, }; - out.push(RenamePlan { id: p.id.0, from: p.file_name.clone(), to, from_path, to_path }); + // the companion JPEG (issue #1692) follows the photo's new name, keeping its own + // extension: `Trip-1.CR2` puts `Trip-1.JPG` beside it (a taken name gets -1, -2…, of its + // own, so the pair's names can drift apart only when something else is in the way) + let companion = match (&p.source, p.companion_jpeg.as_deref()) { + (Source::File { path }, Some(from)) if folded_path(from) != folded_path(path) => { + let ext = Path::new(from).extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); + let (to_stem, _) = split_ext(&to); + let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default(); + let mut k = 0; + let c_to = loop { + let name = if k == 0 { format!("{to_stem}{ext}") } else { format!("{to_stem}-{k}{ext}") }; + let cp = dir.join(&name).to_string_lossy().to_string(); + let key = folded_path(&cp); + let same = key == folded_path(from) && exists(Path::new(&cp)) && same_file(Path::new(from), Path::new(&cp)); + // free: not claimed in this batch and not on disk (unless it is this very file) + if !taken.contains(&key) && (same || !exists(Path::new(&cp))) { + taken.insert(key); + break cp; + } + k += 1; + }; + Some((from.to_string(), c_to)) + } + _ => None, + }; + out.push(RenamePlan { id: p.id.0, from: p.file_name.clone(), to, from_path, to_path, companion }); } out } @@ -1464,6 +1493,12 @@ impl Session { if plan.to != p.file_name || source != p.source { ops.push(Op::SetFile { id: p.id, file_name: plan.to.clone(), source }); } + // the companion's record follows its file, in the same undo step + if let Some((from, to)) = &plan.companion + && folded_path(from) != folded_path(to) + { + ops.push(Op::SetCompanion { id: p.id, companion: Some(to.clone()) }); + } } let n = ops.len(); let op = Op::Batch { ops }; @@ -1473,6 +1508,9 @@ impl Session { (Some(a), Some(b)) if Path::new(a) != Path::new(b) => Some((a.clone(), b.clone())), _ => None, }) + .chain( + plans.iter().filter_map(|pl| pl.companion.as_ref().and_then(|(a, b)| (Path::new(a) != Path::new(b)).then(|| (a.clone(), b.clone())))), + ) .collect(); if let Err(e) = move_all(fs, &moves) { return Err(EngineError::Other(self.follow_stuck(&op, e, true).0)); @@ -1545,25 +1583,36 @@ impl Session { let mut pending = vec![op]; let mut order = Vec::new(); let mut targets = HashMap::new(); + // companions (issue #1692): their own moves, in op order after the photos' + let mut companions = Vec::new(); while let Some(op) = pending.pop() { match op { Op::Batch { ops } => pending.extend(ops.iter().rev()), Op::SetFile { id, source, .. } if targets.insert(*id, source).is_none() => { order.push(*id); } + Op::SetCompanion { id, companion: Some(c) } => companions.push((*id, c.clone())), _ => {} } } // Virtual copies share one physical move, keeping the original batch order. let mut seen = HashSet::new(); - order + let mut out: Vec<(String, String)> = order .into_iter() .filter_map(|id| { let Source::File { path: to } = targets.get(&id).copied()? else { return None }; let Source::File { path: from } = &self.catalog.photo(id)?.source else { return None }; (Path::new(from) != Path::new(to) && seen.insert(from)).then(|| (from.clone(), to.clone())) }) - .collect() + .collect(); + for (id, to) in companions { + let Some(p) = self.catalog.photo(id) else { continue }; + let Some(from) = &p.companion_jpeg else { continue }; + if Path::new(from) != Path::new(&to) { + out.push((from.clone(), to)); + } + } + out } } diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 085a4730af..c8fd0ef20d 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -2257,6 +2257,8 @@ mod tests { .any(|w| w.code == crate::import::ImportWarningCode::CameraProfile && w.profile.as_deref() == Some("Adobe Vivid")) }; // add a calibrated camera to whatever is installed (the registry is process-wide), and take it out again + // (under the lock: another test's save-and-restore of the registry would otherwise drop or revive this entry) + let _lock = crate::camera_profiles::test_library_lock(); let dcp = std::sync::Arc::new(lcc_raw::dcp::Dcp { model: "LOOKTEST ONE".into(), name: "Adobe Vivid".into(), diff --git a/crates/engine/src/slideshow_export.rs b/crates/engine/src/slideshow_export.rs index 846bf6b153..9296278041 100644 --- a/crates/engine/src/slideshow_export.rs +++ b/crates/engine/src/slideshow_export.rs @@ -511,10 +511,11 @@ impl Prepared { if pages == 0 { return Err("no slide could be rendered".into()); } - let bytes = pdf.len(); let catalog = if self.request.settings.full_screen { " /PageMode /FullScreen" } else { "" }; let pdf_file = pdf.finish(catalog)?.into_inner().map_err(|e| format!("PDF: {}", e.error()))?; lcc_catalog::safe_file::sync_file(&pdf_file, false).map_err(|e| format!("PDF: {e}"))?; + // the finished file's size: the trailer and cross-reference table come after the pages + let bytes = pdf_file.metadata().map_err(|e| format!("PDF: {e}"))?.len(); // closed before the rename: Windows can't rename a file that is still open drop(pdf_file); part.commit(&self.guard)?; diff --git a/crates/engine/src/tests_color.rs b/crates/engine/src/tests_color.rs index ae9c185611..40f10866e6 100644 --- a/crates/engine/src/tests_color.rs +++ b/crates/engine/src/tests_color.rs @@ -151,6 +151,8 @@ fn targeted_adjustment_on_curve_and_mixer() { /// the Custom Kelvin value that renders the same before applying an edit on top of it. #[test] fn white_balance_commands_write_kelvin_on_raws_whose_camera_has_matrices() { + // the camera develops from its measured matrices, never a calibration another test installed (see the guard) + let _profiles = crate::camera_profiles::NoInstalledProfiles::hold(); use lcc_develop::{DevelopSettings, WbMode, WbScale}; let mut s = Session::new(); let add = add_raw; @@ -254,6 +256,8 @@ fn engine_effective(info: &lcc_pipeline::SourceInfo, d: &lcc_develop::DevelopSet /// partial that says `scale: "kelvin"` is read in Kelvin. #[test] fn one_field_wb_partial_merge_keeps_the_other_field_on_its_scale() { + // the camera develops from its measured matrices, never a calibration another test installed (see the guard) + let _profiles = crate::camera_profiles::NoInstalledProfiles::hold(); use lcc_develop::{DevelopSettings, WbMode, WbScale}; let mut s = Session::new(); let add = add_raw; @@ -415,6 +419,8 @@ fn one_field_wb_partial_merge_keeps_the_other_field_on_its_scale() { /// `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() { + // the camera develops from its measured matrices, never a calibration another test installed (see the guard) + let _profiles = crate::camera_profiles::NoInstalledProfiles::hold(); use lcc_develop::{DevelopSettings, WbMode, WbScale}; let mut s = Session::new(); let add = add_raw; diff --git a/crates/engine/src/tests_custom_order.rs b/crates/engine/src/tests_custom_order.rs index 61499474ff..1cd513a5c6 100644 --- a/crates/engine/src/tests_custom_order.rs +++ b/crates/engine/src/tests_custom_order.rs @@ -1,10 +1,13 @@ //! Custom Order: `album.orderPhotos`, `album.setPhotoOrder` and `library.sort {key: custom}` — -//! one undo step each, kept across reopening the library, and followed by Rename `{seq}`. +//! one undo step each, kept across reopening the library, and followed by Rename `{seq}`. The +//! same for the photos of one folder of the Folders panel (issue #1583): `folder.orderPhotos` +//! and `folder.setPhotoOrder`. -use lcc_catalog::{AlbumId, PhotoId, SortKey}; +use lcc_catalog::{AlbumId, Op, Photo, PhotoId, SortKey, Source}; use serde_json::{Value, json}; +use std::path::Path; -use crate::{Selection, Session}; +use crate::{Browse, CustomOrderSource, LibrarySource, Selection, Session}; /// A demo session showing a new album with the first five demo photos. fn album(s: &mut Session) -> (u64, Vec) { @@ -167,3 +170,216 @@ fn dropping_in_a_descending_custom_order_lands_where_the_grid_shows_it() { assert_eq!(order(&r), want.iter().rev().copied().collect::>(), "saved in forward order"); assert!(!s.sort.ascending, "the view stays descending"); } + +/// A photo of the library at `path`, captured at `captured`: its id. +fn add(s: &mut Session, path: &str, captured: &str) -> u64 { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + p.captured = Some(captured.into()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 +} + +/// [`add`], through the journal: the photo is still there when the library is reopened. +fn import(s: &mut Session, path: &str, captured: &str) -> u64 { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + p.captured = Some(captured.into()); + s.commit("Import", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 +} + +/// A session whose library holds three photos in `/pics/trip` (one per day) and one in +/// `/pics/home`, nothing below either: `/pics/trip`'s ids, and `/pics/home`'s. A folder is chosen +/// with the photos of the folders inside it shown (the default), which for a folder that holds +/// nothing below it is the folder's own photos. +fn folders() -> (Session, Vec, u64) { + let mut s = Session::new(); + assert!(s.folder_subfolders, "shown with the photos of the folders inside it, the default"); + let trip: Vec = (1..=3).map(|day| add(&mut s, &format!("/pics/trip/day{day}.jpg"), &format!("2026-01-0{day}T10:00:00"))).collect(); + let home = add(&mut s, "/pics/home/c.jpg", "2025-01-01T10:00:00"); + (s, trip, home) +} + +/// Show the library folder `path`. +fn show(s: &mut Session, path: &str) { + s.execute("library.source", &json!({"kind": "libraryFolder", "path": path})).unwrap(); +} + +fn show_trip(s: &mut Session) { + show(s, "/pics/trip"); +} + +/// The Custom Order of the photos of folder `path`. +fn order_of(s: &Session, path: &str) -> Vec { + s.catalog.folder_photo_order(path).iter().map(|p| p.0).collect() +} + +#[test] +fn a_folder_shown_on_its_own_sorts_by_custom_order_and_a_move_switches_to_it() { + let (mut s, trip, _) = folders(); + show_trip(&mut s); + assert_eq!(shown(&mut s), trip, "capture date, the folder's own photos"); + assert_eq!(s.custom_order_source(), Some(CustomOrderSource::Folder("/pics/trip".into()))); + s.execute("library.sort", &json!({"key": "custom"})).unwrap(); + assert_eq!((s.sort.key, s.sort.ascending), (SortKey::Custom, true)); + assert_eq!(shown(&mut s), trip, "it starts from the order shown"); + assert_eq!(order_of(&s, "/pics/trip"), trip); + + // the move a drag in the grid makes: the last photo before the second + let r = s.execute("folder.orderPhotos", &json!({"ids": [trip[2]], "before": trip[1]})).unwrap(); + assert_eq!(order(&r), vec![trip[0], trip[2], trip[1]]); + assert_eq!(shown(&mut s), vec![trip[0], trip[2], trip[1]]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(shown(&mut s), trip, "one undo step per move"); + + // moving a photo while another sort is shown switches the folder to Custom Order + s.execute("library.sort", &json!({"key": "fileName", "ascending": false})).unwrap(); + let o = shown(&mut s); + s.execute("folder.orderPhotos", &json!({"folder": "/pics/trip", "ids": [o[0]]})).unwrap(); + assert_eq!(s.sort.key, SortKey::Custom); + assert_eq!(shown(&mut s), vec![o[1], o[2], o[0]]); + // a photo imported later follows, whenever it was captured + let late = add(&mut s, "/pics/trip/day0.jpg", "2020-01-01T10:00:00"); + assert_eq!(shown(&mut s), vec![o[1], o[2], o[0], late]); +} + +#[test] +fn a_folder_photo_order_lists_the_rest_after_and_is_kept_across_reopening() { + let dir = std::env::temp_dir().join(format!("lc-folder-custom-order-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + let trip: Vec = (1..=3).map(|day| import(&mut s, &format!("/pics/trip/day{day}.jpg"), &format!("2026-01-0{day}T10:00:00"))).collect(); + let r = s.execute("folder.setPhotoOrder", &json!({"folder": "/pics/trip", "ids": [trip[2], trip[0], trip[2]]})).unwrap(); + assert_eq!(order(&r), vec![trip[2], trip[0], trip[1]], "repeats ignored, the rest after"); + drop(s); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + show_trip(&mut s); + s.execute("library.sort", &json!({"key": "custom"})).unwrap(); + assert_eq!(shown(&mut s), vec![trip[2], trip[0], trip[1]], "kept across reopening"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn dropping_in_a_descending_folder_order_lands_where_the_grid_shows_it() { + let (mut s, trip, _) = folders(); + show_trip(&mut s); + s.execute("library.sort", &json!({"key": "custom"})).unwrap(); + s.execute("library.sort", &json!({"key": "custom", "ascending": false})).unwrap(); + let grid = shown(&mut s); + assert_eq!(grid, trip.iter().rev().copied().collect::>(), "descending shows the order reversed"); + // the last photo of the grid onto the left side of the first + let r = s.execute("folder.orderPhotos", &json!({"ids": [grid[2]], "before": grid[0]})).unwrap(); + assert_eq!(shown(&mut s), vec![grid[2], grid[0], grid[1]], "where the grid shows it landing"); + assert_eq!(order(&r), vec![grid[1], grid[0], grid[2]], "saved in forward order"); + assert!(!s.sort.ascending, "the view stays descending"); +} + +#[test] +fn a_folder_shown_with_the_photos_of_the_folders_inside_it_has_no_one_order() { + let (mut s, trip, home) = folders(); + assert!(s.execute("library.sort", &json!({"key": "custom"})).is_err(), "All Photos has no custom order"); + assert_eq!(s.sort.key, SortKey::CaptureDate); + // a folder only browsed in Local: its files aren't the library's + s.source = LibrarySource::Folder; + s.browse = Some(Browse { path: "/pics/trip".into(), ..Default::default() }); + assert_eq!(s.custom_order_source(), None); + assert!(s.execute("library.sort", &json!({"key": "custom"})).is_err()); + s.browse = None; + show_trip(&mut s); + // nothing below the folder: its view is its own photos, shown with the folders inside it or without + assert_eq!(s.custom_order_source(), Some(CustomOrderSource::Folder("/pics/trip".into()))); + // a photo in a folder inside it is taken in: the photos of two folders have no one order + let inside = add(&mut s, "/pics/trip/inside/d.jpg", "2024-01-01T10:00:00"); + assert_eq!(shown(&mut s), vec![inside, trip[0], trip[1], trip[2]]); + assert_eq!(s.custom_order_source(), None); + let e = s.execute("library.sort", &json!({"key": "custom"})).unwrap_err().to_string(); + assert!(e.contains("showSubfolderPhotos"), "the refusal says how to show the folder on its own: {e}"); + assert!(s.execute("folder.orderPhotos", &json!({"ids": [trip[0]]})).is_err()); + s.execute("library.showSubfolderPhotos", &json!({"on": false})).unwrap(); + s.execute("library.sort", &json!({"key": "custom"})).unwrap(); + assert_eq!(shown(&mut s), trip, "on its own"); + // with the folders inside it again, Custom Order falls back to capture date, as it does elsewhere + s.execute("library.showSubfolderPhotos", &json!({"on": true})).unwrap(); + assert_eq!((s.sort.key, shown(&mut s)), (SortKey::Custom, vec![inside, trip[0], trip[1], trip[2]])); + s.execute("library.showSubfolderPhotos", &json!({"on": false})).unwrap(); + assert_eq!(shown(&mut s), trip, "and back in the folder's own order"); + assert_eq!(s.custom_order_source(), Some(CustomOrderSource::Folder("/pics/trip".into()))); + // folders that name none, that hold no photo of their own directly, or the wrong type + for bad in [ + json!({"folder": ".", "ids": [trip[0]]}), + json!({"folder": "relative/x", "ids": [trip[0]]}), + json!({"folder": 5, "ids": [trip[0]]}), + json!({"folder": "/pics", "ids": [trip[0]]}), + ] { + assert!(s.execute("folder.orderPhotos", &bad).is_err(), "{bad}"); + } + assert!(s.execute("folder.setPhotoOrder", &json!({"folder": "/pics", "ids": []})).is_err(), "no photo directly in it"); + assert!(s.execute("folder.setPhotoOrder", &json!({"ids": [trip[0]]})).is_err(), "setPhotoOrder names its folder"); + assert!(s.execute("folder.setPhotoOrder", &json!({"folder": 5, "ids": []})).is_err()); + // photos of another folder, of a folder inside, strangers, not ids, none at all; a `before` from elsewhere + let before = shown(&mut s); + for bad in [ + json!({"ids": [home]}), + json!({"ids": [inside]}), + json!({"ids": [999_999]}), + json!({"ids": ["x"]}), + json!({"ids": []}), + json!({"ids": [trip[0]], "before": home}), + json!({"ids": [trip[0]], "before": inside}), + json!({"ids": [trip[0]], "before": "x"}), + json!({"ids": [trip[0], 999_999]}), + ] { + assert!(s.execute("folder.orderPhotos", &bad).is_err(), "{bad}"); + } + for bad in + [json!({"ids": [home]}), json!({"ids": [inside]}), json!({"ids": [999_999]}), json!({"ids": ["x"]}), json!({"ids": [trip[0], 999_999]})] + { + assert!(s.execute("folder.setPhotoOrder", &bad).is_err(), "{bad}"); + } + assert_eq!((shown(&mut s), order_of(&s, "/pics/trip")), (before.clone(), before), "a refused command changes nothing"); + // the collection commands don't take a folder for a collection + assert!(s.execute("album.orderPhotos", &json!({"ids": [trip[0]]})).is_err(), "a folder is shown, no collection"); + assert_eq!(s.custom_order_source(), Some(CustomOrderSource::Folder("/pics/trip".into()))); +} + +#[test] +fn rename_numbers_a_folder_selection_in_custom_order() { + let (mut s, trip, _) = folders(); + show_trip(&mut s); + s.execute("folder.setPhotoOrder", &json!({"folder": "/pics/trip", "ids": [trip[2], trip[0]]})).unwrap(); + // selected out of grid order: numbered in grid order all the same + s.selection = Selection { ids: vec![PhotoId(trip[0]), PhotoId(trip[2])], active: Some(PhotoId(trip[0])) }; + let plans = s.execute("photo.renamePreview", &json!({"template": "Trip-{seq}"})).unwrap(); + let got: Vec<(u64, String)> = + plans.as_array().unwrap().iter().map(|p| (p["id"].as_u64().unwrap(), p["to"].as_str().unwrap().to_string())).collect(); + assert_eq!(got.iter().map(|g| g.0).collect::>(), vec![trip[2], trip[0]]); + assert!(got[0].1.starts_with("Trip-1.") && got[1].1.starts_with("Trip-2."), "{got:?}"); +} + +#[test] +fn a_folder_order_follows_a_renamed_folder_and_undo_brings_it_back() { + let dir = std::env::temp_dir().join(format!("lc-folder-custom-order-rename-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("trip")).unwrap(); + let trip = dir.join("trip").to_string_lossy().to_string(); + let holiday = dir.join("holiday").to_string_lossy().to_string(); + let mut s = Session::new(); + let ids: Vec = + ["a", "b", "c"].iter().enumerate().map(|(i, n)| add(&mut s, &format!("{trip}/{n}.jpg"), &format!("2026-01-0{}T10:00:00", i + 1))).collect(); + show(&mut s, &trip); + s.execute("folder.setPhotoOrder", &json!({"folder": trip, "ids": [ids[2], ids[0], ids[1]]})).unwrap(); + s.execute("folder.rename", &json!({"path": trip, "name": "holiday"})).unwrap(); + assert!(Path::new(&holiday).is_dir()); + assert_eq!(order_of(&s, &holiday), vec![ids[2], ids[0], ids[1]], "the order is the folder's, wherever the folder is"); + assert!(s.catalog.folder_record(&trip).is_none(), "nothing stays behind"); + show(&mut s, &holiday); + s.execute("library.sort", &json!({"key": "custom"})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[2], ids[0], ids[1]]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(order_of(&s, &trip), vec![ids[2], ids[0], ids[1]], "undo moves the order back with the folder"); + assert!(s.catalog.folder_record(&holiday).is_none()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests_denoise.rs b/crates/engine/src/tests_denoise.rs index fbe5ce9cee..439d132d72 100644 --- a/crates/engine/src/tests_denoise.rs +++ b/crates/engine/src/tests_denoise.rs @@ -14,7 +14,7 @@ use serde_json::{Value, json}; use crate::Session; use crate::denoise::{Loader, Model, PhotoState, RunOn}; use crate::export::{ExportOptions, export_photo}; -use crate::tests_xmp::{synthetic_dng_of, temp_dir}; +use crate::tests_xmp::{synthetic_dng_cfa, synthetic_dng_of, temp_dir}; /// A model that makes every output pixel half of its cell's colour: a picture that is plainly not the plain one. struct Dim { @@ -591,6 +591,103 @@ fn files_that_cannot_be_denoised_fail_with_a_reason_and_never_a_panic() { let _ = std::fs::remove_dir_all(&dir); } +/// Only a Bayer pattern has a Bayer layout. 16 of X-Trans's 36 phases start with a 2 × 2 that reads as a Bayer cell +/// (rows 2 and 3 at column 1 are R G / G B), so a file whose active area began at one of them would have had its +/// X-Trans mosaic packed as Bayer. +#[test] +fn an_x_trans_phase_that_starts_like_a_bayer_cell_is_not_taken_for_one() { + use crate::denoise::layout_of; + use lcc_raw::Cfa; + let mut looks_bayer = 0; + for dy in 0..6 { + for dx in 0..6 { + let cfa = Cfa::xtrans().shifted(dx, dy); + let cell = [cfa.color_at(0, 0), cfa.color_at(1, 0), cfa.color_at(0, 1), cfa.color_at(1, 1)]; + looks_bayer += usize::from(lcc_denoise::bayer::Layout::from_cell(cell).is_some()); + assert_eq!(layout_of(&cfa), None, "X-Trans at phase ({dx}, {dy})"); + } + } + assert_eq!(looks_bayer, 16, "the phases this test is about"); + for name in ["RGGB", "GRBG", "GBRG", "BGGR"] { + assert!(layout_of(&Cfa::bayer(name).unwrap()).is_some(), "{name}"); + } +} + +/// X-Trans (and any other non-Bayer colour filter array) reaches the model through the RGGB re-mosaic: +/// the picture comes out whole and the right size, where before the file was refused outright. +#[test] +fn a_non_bayer_sensor_is_denoised_through_the_rggb_remosaic() { + let dir = temp_dir("xtrans"); + let (w, h) = (192usize, 160usize); + let data: Vec = (0..w * h).map(|i| 600 + ((i % w) * 30 + (i / w) * 35) as u16).collect(); + let f = dir.join("xtrans.dng"); + std::fs::write(&f, synthetic_dng_cfa(w, h, lcc_raw::Cfa::xtrans(), data, None, Default::default())).unwrap(); + let runs = Arc::new(AtomicUsize::new(0)); + let spec = crate::denoise::JobSpec { + path: f.to_string_lossy().into_owned(), + read: None, + product: dir.join("xtrans.lcdn"), + key: "k".into(), + manifest: manifest("stand-in"), + onnx: dir.join("model.onnx"), + model: Default::default(), + loader: dim_loader(&runs), + parallel: 2, + run_on: RunOn::Auto, + }; + assert_eq!(crate::denoise::make_product(&spec, None), Ok(true)); + let header = lcc_denoise::product::read_header_at(&spec.product).unwrap(); + assert_eq!((header.width, header.height), (w, h), "the denoised picture keeps the sensor's size"); + let rgb = lcc_denoise::product::read(&spec.product, "k", 1).unwrap(); + assert_eq!((rgb.width, rgb.height), (w, h)); + assert!(rgb.data.iter().flatten().all(|v| v.is_finite()), "no sample is left non-finite"); + assert!(rgb.data.iter().any(|p| p.iter().any(|v| *v > 0.0)), "the picture is not all black"); + assert_eq!(crate::denoise::make_product(&spec, None), Ok(false), "the product is already there"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The denoised picture of an X-Trans file is used where the photo is shown, not only made: in a preview binned 3 × 3 +/// (the only binning X-Trans allows) and at full size, from a default crop whose sides 3 does not divide. Before +/// non-Bayer sensors could be denoised nothing ever read such a product, and a twin that does not match the plain +/// picture's size is silently dropped, so a mismatch here would leave the Amount slider doing nothing in the loupe. +#[test] +fn an_x_trans_photo_shows_its_denoised_picture_binned_and_at_full_size() { + use crate::media::DenoiseSpec; + let dir = temp_dir("xtrans-twin"); + let (w, h) = (384usize, 288usize); + let data: Vec = (0..w * h).map(|i| 900 + ((i % w) * 23 + (i / w) * 31 + (i * 7919) % 401) as u16).collect(); + let mut raw = lcc_raw::decode(&synthetic_dng_cfa(w, h, lcc_raw::Cfa::xtrans(), data, None, Default::default())).unwrap(); + raw.crop = lcc_raw::Rect::new(5, 7, 371, 271); + let bytes = lcc_raw::write_dng(&raw, &Default::default()).unwrap(); + assert_eq!(lcc_raw::decode(&bytes).unwrap().crop, raw.crop, "the crop survives the DNG"); + let f = dir.join("xtrans.dng"); + std::fs::write(&f, &bytes).unwrap(); + let spec = crate::denoise::JobSpec { + path: f.to_string_lossy().into_owned(), + read: None, + product: dir.join("xtrans.lcdn"), + key: "k".into(), + manifest: manifest("stand-in"), + onnx: dir.join("model.onnx"), + model: Default::default(), + loader: dim_loader(&Arc::new(AtomicUsize::new(0))), + parallel: 2, + run_on: RunOn::Auto, + }; + assert_eq!(crate::denoise::make_product(&spec, None), Ok(true)); + let twin = DenoiseSpec { product: spec.product.clone(), key: "k".into(), make: None }; + for (max_edge, binned) in [(128, true), (100_000, false)] { + let (plain, denoised, _) = crate::files::load_vec_pair(bytes.clone(), max_edge, &twin, crate::media::LoadOptions::default()).unwrap(); + assert_eq!(plain.width < 371, binned, "max_edge {max_edge}: {}×{}", plain.width, plain.height); + let denoised = denoised.unwrap_or_else(|| panic!("max_edge {max_edge}: the denoised picture was dropped")); + assert_eq!((denoised.width, denoised.height), (plain.width, plain.height), "max_edge {max_edge}"); + // the stand-in model halves every sample: the picture shown is the denoised one, not the plain one again + let mean = |img: &lcc_raster::Rgb32f| img.data.iter().map(|p| f64::from(p[1])).sum::() / img.data.len() as f64; + assert!(mean(&denoised) < 0.75 * mean(&plain), "max_edge {max_edge}: {} vs {}", mean(&denoised), mean(&plain)); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn two_threads_making_the_same_picture_make_it_once() { let dir = temp_dir("twice"); diff --git a/crates/engine/src/tests_edit_in.rs b/crates/engine/src/tests_edit_in.rs index ad98b1f53b..16f21ae629 100644 --- a/crates/engine/src/tests_edit_in.rs +++ b/crates/engine/src/tests_edit_in.rs @@ -423,3 +423,143 @@ fn an_action_step_that_chooses_a_program_stops_the_action() { assert!(matches!(calls.as_slice(), [crate::desktop::Request::Launch(line)] if line.first().is_some_and(|a| a == "/opt/ed")), "{calls:?} {r}"); let _ = std::fs::remove_dir_all(&dir); } + +/// The copy formats beyond TIFF/PSD: a PNG copy embeds the linked XMP, a 32-bit float TIFF holds +/// linear samples with Rec. 2020 accepted, an OpenEXR copy carries its link in a sidecar, and a +/// DNG copy keeps the raw data (a rendered photo has none and is told so). +#[test] +fn edit_in_copy_formats_png_float_tiff_exr_and_dng() { + let dir = temp_dir("formats"); + let src = dir.join("lake.png"); + write_png(&src, 5, 24, 16); + let mut s = session(&dir); + let orig = import(&mut s, &src); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.0})).unwrap(); + + // PNG, 8-bit sRGB, linked XMP embedded + let r = + s.execute("photo.editIn", &json!({"id": orig.0, "preset": "External Editor", "format": "png", "colorSpace": "srgb", "bitDepth": 8})).unwrap(); + let path = r["path"].as_str().unwrap().to_string(); + assert!(path.ends_with("lake-Edit.png"), "{r}"); + let d = lcc_codecs::decode(&std::fs::read(&path).unwrap(), Default::default()).unwrap(); + assert_eq!((d.width, d.height), (24, 16), "{path}"); + assert!(d.xmp.is_some_and(|x| x.contains("DerivedFrom")), "the linked XMP is embedded"); + + // 32-bit float TIFF in Rec. 2020: linear samples, profile embedded + let r = s + .execute("photo.editIn", &json!({"id": orig.0, "preset": "External Editor", "format": "tiff", "colorSpace": "rec2020", "bitDepth": 32})) + .unwrap(); + let path = r["path"].as_str().unwrap().to_string(); + assert!(path.ends_with("lake-Edit.tif"), "{r}"); + let bytes = std::fs::read(&path).unwrap(); + let mut dec = tiff::decoder::Decoder::new(std::io::Cursor::new(&bytes)).unwrap().with_limits(tiff::decoder::Limits::unlimited()); + assert!(matches!(dec.colortype().unwrap(), tiff::ColorType::RGB(32)), "{path}"); + assert!(matches!(dec.read_image().unwrap(), tiff::decoder::DecodingResult::F32(_)), "{path}"); + assert!(dec.get_tag_u8_vec(tiff::tags::Tag::Unknown(34675)).is_ok(), "the colour profile is embedded"); + + // OpenEXR (16-bit half): scene-linear Rec. 2020, the link in a sidecar + let r = s.execute("photo.editIn", &json!({"id": orig.0, "preset": "External Editor", "format": "exr", "bitDepth": 16})).unwrap(); + let path = r["path"].as_str().unwrap().to_string(); + assert!(path.ends_with("lake-Edit.exr"), "{r}"); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(&bytes[0..4], &[0x76, 0x2f, 0x31, 0x01], "an OpenEXR file"); + let side = std::path::Path::new(&path).with_extension("xmp"); + let side = std::fs::read_to_string(&side).unwrap_or_default(); + assert!(side.contains("DerivedFrom"), "the link rides in a sidecar: {side}"); + + // a DNG copy keeps the raw data: a rendered PNG is told what to choose instead + let e = s.execute("photo.editIn", &json!({"id": orig.0, "preset": "External Editor", "format": "dng"})).unwrap_err().to_string(); + assert!(e.contains("raw"), "{e}"); + + // and for a raw it is the raw data with the edits in its XMP + let raw_bytes = test_dng(); + let raw_path = dir.join("lake.raw.dng"); + std::fs::write(&raw_path, raw_bytes).unwrap(); + let raw = import(&mut s, &raw_path); + s.selection = crate::Selection::single(raw); + s.execute("develop.set", &json!({"id": raw.0, "control": "light.exposure", "value": 1.0})).unwrap(); + let r = s.execute("photo.editIn", &json!({"id": raw.0, "preset": "External Editor", "format": "dng"})).unwrap(); + let path = r["path"].as_str().unwrap().to_string(); + assert!(path.ends_with("lake.raw-Edit.dng"), "{r}"); + // a raw is read with lcc-raw, not the still-image codecs + let bytes = std::fs::read(&path).unwrap(); + assert!(lcc_raw::probe(&bytes).is_some(), "the DNG copy is raw data"); + assert!(bytes.windows(11).any(|w| w == b"lc:settings"), "the edits ride in the DNG's XMP"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A tiny RGGB DNG the library imports as a raw (the DNG copy keeps its data). +fn test_dng() -> Vec { + let (w, h) = (64usize, 48usize); + let raw = lcc_raw::RawImage { + format: lcc_raw::RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: lcc_raw::RawData::U16((0..w * h).map(|i| 1000 + (i % 97) as u16 * 40).collect()), + cfa: lcc_raw::Cfa::bayer("RGGB"), + bits: 14, + black: lcc_raw::BlackLevel::uniform(512.0), + white: vec![16000.0], + active_area: lcc_raw::Rect::new(0, 0, w, h), + crop: lcc_raw::Rect::new(0, 0, w, h), + orientation: lcc_raw::Orientation::Normal, + color: lcc_raw::ColorData { + illuminant: [21, 0], + color_matrix: [Some(lcc_raw::Mat3([[0.8, -0.2, -0.05], [-0.45, 1.3, 0.15], [-0.08, 0.22, 0.62]])), None], + as_shot_neutral: Some([0.5, 1.0, 0.7]), + ..Default::default() + }, + wb_multipliers: None, + linearized: false, + pixel_aspect: 1.0, + opcodes: Default::default(), + metadata: Default::default(), + lens_metadata: Default::default(), + }; + lcc_raw::write_dng(&raw, &Default::default()).unwrap() +} + +/// (+XMP): an Edit a Copy file gets the photo's metadata and edits as a sidecar beside it, and +/// Edit Original merges into the original's own sidecar. Nothing is written without the flag. +#[test] +fn edit_copy_and_original_take_an_xmp_sidecar_when_asked() { + let dir = temp_dir("xmp-sidecar"); + let src = dir.join("lake.png"); + write_png(&src, 7, 16, 16); + let mut s = session(&dir); + let orig = import(&mut s, &src); + s.execute("photo.rate", &json!({"rating": 3})).unwrap(); + + let r = s.execute("photo.editIn", &json!({"id": orig.0, "mode": "copy"})).unwrap(); + let first = r["path"].as_str().unwrap().to_string(); + assert!(!std::path::Path::new(&first).with_extension("xmp").exists(), "no sidecar without the flag"); + + let r = s.execute("photo.editIn", &json!({"id": orig.0, "mode": "copy", "xmp": true})).unwrap(); + let second = r["path"].as_str().unwrap().to_string(); + let side = std::fs::read_to_string(std::path::Path::new(&second).with_extension("xmp")).unwrap(); + assert!(side.contains("xmpMM:DerivedFrom") && side.contains("lake.png"), "the copy's sidecar links to the original: {side}"); + + let r = s.execute("photo.editIn", &json!({"id": orig.0, "mode": "original", "xmp": true})).unwrap(); + assert_eq!(r["path"].as_str().unwrap(), src.to_string_lossy()); + let side = std::fs::read_to_string(dir.join("lake.xmp")).unwrap(); + assert!(side.contains("Rating") || side.contains("rating"), "the original's sidecar carries the metadata: {side}"); + // the sidecar names the photo it was made from, so a re-import of the file stacks it + // (the DerivedFrom round trip: tests_edit_roundtrip) + let _ = std::fs::remove_dir_all(&dir); +} + +/// The depth a format takes is checked when a preset is saved: a PSD has no float, OpenEXR has no +/// 8-bit, TIFF takes all three. +#[test] +fn a_preset_depth_is_checked_against_its_format() { + let dir = temp_dir("depths"); + let mut s = session(&dir); + assert!(s.execute("editIn.savePreset", &json!({"name": "Tiff 32", "format": "tiff", "bitDepth": 32})).is_ok()); + assert!(s.execute("editIn.savePreset", &json!({"name": "Exr", "format": "exr", "bitDepth": 16, "colorSpace": "rec2020"})).is_ok()); + let e = s.execute("editIn.savePreset", &json!({"name": "Psd float", "format": "psd", "bitDepth": 32})).unwrap_err().to_string(); + assert!(e.contains("bit depth 32") && e.contains("PSD"), "{e}"); + let e = s.execute("editIn.savePreset", &json!({"name": "Exr 8", "format": "exr", "bitDepth": 8})).unwrap_err().to_string(); + assert!(e.contains("16, 32"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 4bd895b030..d827c87983 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -2361,3 +2361,26 @@ fn an_original_never_carries_a_position_cleared_or_moved_in_the_library() { assert!(s.catalog.photo(city).unwrap().meta.gps_removed.is_some()); assert!(export_photo(&mut s, city, &original, 1).is_ok(), "the city stays: only the position was cleared"); } + +#[test] +fn preset_export_rejects_malformed_ids_without_replacing_the_output() { + let dir = temp_dir("preset-export-ids"); + let mut s = Session::with_demo(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.6})).unwrap(); + s.execute("preset.create", &json!({"name": "Bright", "group": "Travel"})).unwrap(); + s.execute("develop.set", &json!({"control": "effects.clarity", "value": 30})).unwrap(); + s.execute("preset.create", &json!({"name": "Crisp", "group": "Street"})).unwrap(); + let path = dir.join("selected.lcpreset"); + let prior = b"previous output"; + std::fs::write(&path, prior).unwrap(); + let path_text = path.to_string_lossy(); + + for ids in [json!("lc.warm-glow"), json!(["lc.warm-glow", 7]), json!([])] { + assert!(s.execute("preset.export", &json!({"path": path_text, "ids": ids})).is_err(), "{ids}"); + assert_eq!(std::fs::read(&path).unwrap().as_slice(), prior); + } + assert_eq!(s.execute("preset.export", &json!({"path": path_text})).unwrap()["count"], 2); + assert_eq!(s.execute("preset.export", &json!({"path": path_text, "ids": null, "group": "Travel"})).unwrap()["count"], 1); + assert_eq!(s.execute("preset.export", &json!({"path": path_text, "ids": ["lc.warm-glow"], "group": "Nope"})).unwrap()["count"], 1); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/tests_face_recognize.rs b/crates/engine/src/tests_face_recognize.rs index 5850cdb28c..e77ad1ed7d 100644 --- a/crates/engine/src/tests_face_recognize.rs +++ b/crates/engine/src/tests_face_recognize.rs @@ -489,6 +489,72 @@ fn unit64(parts: &[(usize, f32)]) -> Vec { v.iter().map(|x| x / n).collect() } +#[test] +fn faces_person_sorts_the_confirmed_faces_its_sort_asks_for() { + let d = temp("person-sort"); + let (mut s, _) = setup(&d, 64); + s.execute("faces.index", &json!({"budgetMs": 0})).unwrap(); + // the two lowest ids, then the next two (ids ascend). Ann is on all four; a is the newest photo + // (2024), b the oldest (2020), c in between (2022) and u has no capture time at all. + let (a, b) = two_photos(&s); + let mut rest: Vec<_> = s.catalog.photos().map(|p| p.id).filter(|id| *id != a && *id != b).collect(); + rest.sort(); + let (c, u) = (rest[0], rest[1]); + let big = Region { rect: Rect { x0: 0.05, y0: 0.1, x1: 0.55, y1: 0.7 }, kind: RegionKind::Face, name: Some("Ann".into()), description: None }; + // (0.25 and 0.5 so the two boxes' areas come out equal in floating point too, and the tie is + // decided by the photo and the region) + set_regions(&mut s, a, vec![region(0.25, Some("Ann")), region(0.5, Some("Ann"))]); + set_regions(&mut s, b, vec![region(0.1, Some("Ann"))]); + set_regions(&mut s, c, vec![big]); + set_regions(&mut s, u, vec![region(0.1, Some("Ann"))]); + s.commit("setup", Op::SetCaptured { id: a, captured: Some("2024-05-01T10:00:00".into()) }).unwrap(); + s.commit("setup", Op::SetCaptured { id: b, captured: Some("2020-01-01T09:00:00".into()) }).unwrap(); + s.commit("setup", Op::SetCaptured { id: c, captured: Some("2022-06-01T12:00:00".into()) }).unwrap(); + s.commit("setup", Op::SetCaptured { id: u, captured: None }).unwrap(); + let at = |s: &mut Session, sort: &[&str]| -> Vec<(u64, u64)> { + let mut p = json!({"name": "Ann"}); + if let Some(sort) = sort.first() { + p["sort"] = json!(sort); + } + let r = s.execute("faces.person", &p).unwrap(); + assert_eq!(r["total"], 5, "the count does not follow the sort: {r}"); + r["confirmed"].as_array().unwrap().iter().map(|f| (f["photo"].as_u64().unwrap(), f["index"].as_u64().unwrap())).collect() + }; + // the default and "photo": the library's import order, the regions of a photo in their own order + assert_eq!(at(&mut s, &[]), vec![(a.0, 0), (a.0, 1), (b.0, 0), (c.0, 0), (u.0, 0)]); + assert_eq!(at(&mut s, &["photo"]), vec![(a.0, 0), (a.0, 1), (b.0, 0), (c.0, 0), (u.0, 0)]); + // capture time, oldest first (b 2020, c 2022, a 2024) and newest first (the other way); + // the photo without a capture time comes last either way + assert_eq!(at(&mut s, &["oldest"]), vec![(b.0, 0), (c.0, 0), (a.0, 0), (a.0, 1), (u.0, 0)]); + assert_eq!(at(&mut s, &["newest"]), vec![(a.0, 0), (a.0, 1), (c.0, 0), (b.0, 0), (u.0, 0)]); + // the largest face first (c's is much the bigger), ties by photo + assert_eq!(at(&mut s, &["faceSize"]), vec![(c.0, 0), (a.0, 0), (a.0, 1), (b.0, 0), (u.0, 0)]); + // by folder, then file name: the demo photos share no folder, so the file names decide + let by_name: Vec<(u64, u64)> = { + let mut rows: Vec<(String, u64, u64)> = s + .catalog + .photos() + .filter(|p| p.in_library()) + .flat_map(|p| { + let id = p.id; + p.meta + .regions + .iter() + .enumerate() + .filter(|(_, r)| r.name.as_deref() == Some("Ann")) + .map(move |(i, _)| (p.file_name.to_lowercase(), id.0, i as u64)) + }) + .collect(); + rows.sort(); + rows.into_iter().map(|(_, photo, index)| (photo, index)).collect() + }; + assert_eq!(at(&mut s, &["folder"]), by_name); + // a sort nobody knows is refused + assert!(s.execute("faces.person", &json!({"name": "Ann", "sort": "sharpness"})).is_err()); + assert!(s.execute("faces.person", &json!({"name": "Ann", "sort": 7})).is_err()); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn unnamed_faces_come_with_look_alikes_together_and_the_name_the_named_ones_suggest() { let d = temp("unnamed"); diff --git a/crates/engine/src/tests_face_thumbs.rs b/crates/engine/src/tests_face_thumbs.rs new file mode 100644 index 0000000000..c4d3d065cd --- /dev/null +++ b/crates/engine/src/tests_face_thumbs.rs @@ -0,0 +1,97 @@ +//! `faces.buildThumbnails`: the library's face tiles built ahead of the People view (issue #1691) — +//! one tile per named and unnamed face, none for the ignored ones, the edge kept on the step the +//! People view's tiles ask for, and the tiles found in the cache on a run again. + +use serde_json::json; + +use crate::Session; +use crate::tests_face_recognize::{region, set_regions, temp, two_photos}; + +#[test] +fn building_makes_a_tile_of_every_face_shown_in_people_and_none_of_the_ignored_ones() { + let d = temp("face-thumbs"); + let mut s = Session::with_demo(); + let (a, b) = two_photos(&s); + set_regions(&mut s, a, vec![region(0.1, Some("Ann")), region(0.5, None)]); + // an ignored face is left out of People, so its tile is never asked for + let mut ignored = region(0.6, Some("Ann")); + ignored.kind = lcc_meta::RegionKind::IgnoredFace; + set_regions(&mut s, b, vec![region(0.3, Some("Ann")), ignored]); + // `edge` lands on the 16 px step the tiles are rendered at + let r = s.execute("faces.buildThumbnails", &json!({"wait": true, "edge": 100})).unwrap(); + assert_eq!(r["edge"], 112, "{r}"); + assert_eq!((r["done"].clone(), r["failed"].clone()), (json!(true), json!(0)), "{r}"); + // a's two faces and b's one; the ignored face is not built + assert_eq!((r["total"].clone(), r["built"].clone()), (json!(3), json!(3)), "{r}"); + assert!(r["lanes"].as_u64().is_some_and(|n| n >= 1), "{r}"); + // every tile built is in the cache under the key the People view asks for + for (id, x) in [(a, 0.1), (a, 0.5), (b, 0.3)] { + let job = s.face_job(id, region(x, None).rect, 112).unwrap(); + let (cache, key) = job.cache.expect("a face tile job caches its picture"); + assert!(cache.get(key).is_some(), "photo {}'s tile is cached", id.0); + } + // a run again: the tiles are found in the cache, and nothing fails + let again = s.execute("faces.buildThumbnails", &json!({"wait": true, "edge": 100})).unwrap(); + assert_eq!((again["total"].clone(), again["failed"].clone()), (json!(3), json!(0)), "{again}"); + let _ = std::fs::remove_dir_all(&d); +} + +/// Enough tiles that a background run is in the middle of its work for a moment. +fn many_faces(s: &mut Session) { + let (a, b) = two_photos(s); + for id in [a, b] { + let regions: Vec<_> = (0..48).map(|i| region(0.01 * i as f64, Some("Ann"))).collect(); + set_regions(s, id, regions); + } +} + +#[test] +fn a_run_started_in_the_background_reports_itself_and_finishes() { + let mut s = Session::with_demo(); + many_faces(&mut s); + // nothing is running yet + let st = s.execute("faces.buildThumbnails", &json!({"status": true})).unwrap(); + assert_eq!((st["active"].clone(), st["done"].clone()), (json!(false), json!(false)), "{st}"); + let r = s.execute("faces.buildThumbnails", &json!({"edge": 256, "lanes": 4})).unwrap(); + assert_eq!(r["total"], 96, "{r}"); + // while it works, another start is refused + let st = s.execute("faces.buildThumbnails", &json!({"status": true})).unwrap(); + if st["done"] == false { + assert!(s.execute("faces.buildThumbnails", &json!({})).is_err(), "a run in progress is not started again"); + } + // and it finishes, reporting what it did + for _ in 0..1200 { + let st = s.execute("faces.buildThumbnails", &json!({"status": true})).unwrap(); + if st["done"] == true { + assert_eq!( + (st["total"].clone(), st["failed"].clone(), st["cancelled"].clone(), st["edge"].clone()), + (json!(96), json!(0), json!(false), json!(256)), + "{st}" + ); + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the background run did not finish in six seconds"); +} + +#[test] +fn cancelling_stops_a_run_and_its_status_says_so() { + let mut s = Session::with_demo(); + many_faces(&mut s); + let r = s.execute("faces.buildThumbnails", &json!({"edge": 256, "lanes": 4})).unwrap(); + assert_eq!(r["total"], 96, "{r}"); + // the run may already be finished (it is only tiles); the cancel answers either way, and it is + // over soon, with the run's own answer available afterwards + let _ = s.execute("faces.buildThumbnails", &json!({"cancel": true})).unwrap(); + for _ in 0..1200 { + let st = s.execute("faces.buildThumbnails", &json!({"status": true})).unwrap(); + if st["done"] == true { + assert_eq!(st["cancelled"], true, "{st}"); + assert_eq!(st["total"], 96, "{st}"); + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the cancelled run did not finish in six seconds"); +} diff --git a/crates/engine/src/tests_facet_multi.rs b/crates/engine/src/tests_facet_multi.rs new file mode 100644 index 0000000000..87ebde5004 --- /dev/null +++ b/crates/engine/src/tests_facet_multi.rs @@ -0,0 +1,179 @@ +//! `library.facetPick` with several values of one column (the Date, Flag, Rating and File Type columns, and the +//! bar's Flag icons and Type menu): any of the chosen values matches, ⌘-click is `toggle`, a ⇧-click's run and a plain +//! click are `replace`, and values of different types still combine with AND. + +use lcc_catalog::{Filter, Flag, Op, PhotoId}; +use serde_json::{Value, json}; + +use crate::Session; + +/// The demo library with its photos given capture dates in 1995 to 1997 and flags and ratings of their own. +fn library() -> (Session, Vec) { + let mut s = Session::with_demo(); + let ids: Vec<_> = s.catalog.photos().filter(|p| p.in_library()).take(6).map(|p| p.id).collect(); + for (id, date) in [ + (ids[0], "1995-06-01T10:00:00"), + (ids[1], "1995-06-02T10:00:00"), + (ids[2], "1996-03-10T10:00:00"), + (ids[3], "1996-07-05T10:00:00"), + (ids[4], "1997-01-01T10:00:00"), + (ids[5], "1997-02-02T10:00:00"), + ] { + s.catalog.apply(Op::SetCaptured { id, captured: Some(date.into()) }).unwrap(); + } + for (id, flag, rating) in + [(ids[0], "pick", 3), (ids[1], "reject", 5), (ids[2], "none", 3), (ids[3], "pick", 1), (ids[4], "reject", 0), (ids[5], "none", 5)] + { + s.execute("photo.flag", &json!({"ids": [id.0], "flag": flag})).unwrap(); + s.execute("photo.rate", &json!({"ids": [id.0], "rating": rating})).unwrap(); + } + (s, ids) +} + +fn pick(s: &mut Session, field: &str, mode: &str, values: &[&str]) -> Value { + s.execute("library.facetPick", &json!({"field": field, "mode": mode, "values": values})).unwrap() +} + +/// The photos the view shows that are among `ids`, in `ids` order. +fn shown(s: &mut Session, ids: &[PhotoId]) -> Vec { + let visible = s.visible().to_vec(); + ids.iter().copied().filter(|id| visible.contains(id)).collect() +} + +#[test] +fn a_toggle_adds_and_removes_values_and_any_chosen_value_matches() { + let (mut s, ids) = library(); + pick(&mut s, "year", "toggle", &["1995"]); + assert_eq!(shown(&mut s, &ids), ids[..2], "1995 alone"); + let r = pick(&mut s, "year", "toggle", &["1996"]); + assert_eq!(r["chosen"], json!(["1995", "1996"])); + assert_eq!(shown(&mut s, &ids), ids[..4], "1995 or 1996"); + assert_eq!(s.visible().len(), 4, "no photo of another year"); + pick(&mut s, "year", "toggle", &["1995"]); + assert_eq!(shown(&mut s, &ids), ids[2..4], "1995 taken off again"); + pick(&mut s, "year", "toggle", &["1996"]); + assert_eq!(s.filter, Filter::default(), "taking off the last value clears the type, as All does"); +} + +#[test] +fn a_month_and_a_year_can_be_chosen_together() { + let (mut s, ids) = library(); + pick(&mut s, "year", "replace", &["1996-03", "1997"]); + assert_eq!(shown(&mut s, &ids), [ids[2], ids[4], ids[5]], "March 1996 and the year 1997"); + pick(&mut s, "year", "replace", &["1995-06-02", "1996-07"]); + assert_eq!(shown(&mut s, &ids), [ids[1], ids[3]], "a day and a month"); + assert!(s.execute("library.facetPick", &json!({"field": "year", "mode": "replace", "values": ["1995", "soon"]})).is_err()); +} + +#[test] +fn replace_chooses_exactly_the_values_given_and_one_value_keeps_the_dedicated_field() { + let (mut s, ids) = library(); + pick(&mut s, "year", "replace", &["1995", "1996"]); + assert!(s.filter.date.is_none() && s.filter.facets.len() == 1, "{:?}", s.filter); + pick(&mut s, "year", "replace", &["1997"]); + assert_eq!((s.filter.date.as_deref(), s.filter.facets.len()), (Some("1997"), 0), "{:?}", s.filter); + assert_eq!(shown(&mut s, &ids), ids[4..]); + pick(&mut s, "year", "replace", &[]); + assert_eq!(s.filter, Filter::default()); + for bad in [ + json!({"field": "year", "values": ["1995"]}), + json!({"field": "year", "mode": "add", "values": ["1995"]}), + json!({"field": "year", "mode": "toggle", "values": "1995"}), + ] { + assert!(s.execute("library.facetPick", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn two_flags_two_ratings_and_two_kinds_match_any_of_them() { + let (mut s, ids) = library(); + pick(&mut s, "flag", "toggle", &["reject"]); + pick(&mut s, "flag", "toggle", &["pick"]); + assert_eq!(s.filter.flags_shown(), Some(vec![Flag::Pick, Flag::Reject]), "listed Picked, Unflagged, Rejected"); + assert!(s.filter.flag.is_none(), "the list is the choice, `flag` would AND with it"); + assert_eq!(shown(&mut s, &ids), [ids[0], ids[1], ids[3], ids[4]]); + pick(&mut s, "flag", "replace", &[]); + + pick(&mut s, "rating", "toggle", &["3"]); + pick(&mut s, "rating", "toggle", &["5"]); + assert_eq!(shown(&mut s, &ids), [ids[0], ids[1], ids[2], ids[5]], "rated 3 or 5 exactly"); + assert_eq!((s.filter.rating, s.filter.facets.len()), (0, 1), "the stars take no part"); + pick(&mut s, "rating", "replace", &[]); + + // the demo library holds only photos of one kind, so "any of" shows in a pick that adds a kind it has none of + let all = s.visible().len(); + pick(&mut s, "kind", "replace", &["raw"]); + assert_eq!(s.visible().len(), 0, "the demo has no raws"); + pick(&mut s, "kind", "toggle", &["image"]); + assert_eq!(s.filter.facets[0].values, ["raw", "image"]); + assert_eq!(s.visible().len(), all, "raw or photo: every photo"); + pick(&mut s, "kind", "toggle", &["image"]); + assert_eq!((s.filter.kind, s.filter.facets.len()), (Some(lcc_catalog::MediaKind::Raw), 0), "one value goes back to the dedicated field"); + // the merged kinds join the same choice + pick(&mut s, "kind", "replace", &["raw", "hdr"]); + assert_eq!(s.filter.facets[0].values, ["raw", "hdr"]); + assert!(s.execute("library.facetPick", &json!({"field": "kind", "mode": "replace", "values": ["gif"]})).is_err()); +} + +#[test] +fn values_of_different_types_still_combine_with_and() { + let (mut s, ids) = library(); + pick(&mut s, "year", "replace", &["1995", "1996"]); + pick(&mut s, "flag", "replace", &["none"]); + assert_eq!(shown(&mut s, &ids), [ids[2]], "unflagged, and from 1995 or 1996"); + pick(&mut s, "flag", "toggle", &["pick"]); + assert_eq!(shown(&mut s, &ids), [ids[0], ids[2], ids[3]], "unflagged or picked, and from 1995 or 1996"); + // the other columns count what the choices leave, each without its own + let f = s.execute("library.facets", &json!({"fields": ["year", "flag"]})).unwrap(); + assert_eq!(f["flag"]["chosen"], json!(["pick", "none"])); + assert_eq!(f["year"]["chosen"], json!(["1995", "1996"])); +} + +#[test] +fn one_chip_names_every_value_and_clears_only_its_type() { + let (mut s, _) = library(); + pick(&mut s, "year", "replace", &["1995", "1996-03"]); + pick(&mut s, "rating", "replace", &["3", "5"]); + pick(&mut s, "flag", "replace", &["pick", "none"]); + let chips = crate::filter_chips(&s.filter, &s.catalog); + let labels: Vec<&str> = chips.iter().map(|c| c.label.as_str()).collect(); + assert!(labels.contains(&"Date: 1995 or March 1996"), "{labels:?}"); + assert!(labels.contains(&"Rating = 3★ or 5★"), "{labels:?}"); + assert!(labels.contains(&"Flag: pick or none"), "{labels:?}"); + assert_eq!(chips.len(), 3, "one chip a type: {labels:?}"); + let date = chips.iter().find(|c| c.label.starts_with("Date")).unwrap().clear.clone(); + s.execute("library.filter", &date).unwrap(); + let left: Vec = crate::filter_chips(&s.filter, &s.catalog).into_iter().map(|c| c.label).collect(); + assert_eq!(left, ["Flag: pick or none", "Rating = 3★ or 5★"], "× on Date leaves the other types"); + let rating = crate::filter_chips(&s.filter, &s.catalog).into_iter().find(|c| c.label.starts_with("Rating")).unwrap().clear; + s.execute("library.filter", &rating).unwrap(); + assert!(s.filter.facets.is_empty() && s.filter.flags.len() == 2, "{:?}", s.filter); +} + +#[test] +fn a_saved_filter_keeps_every_chosen_value() { + let (mut s, ids) = library(); + pick(&mut s, "year", "replace", &["1995", "1996"]); + pick(&mut s, "rating", "replace", &["3", "5"]); + pick(&mut s, "flag", "replace", &["pick", "reject"]); + let before = shown(&mut s, &ids); + assert!(!before.is_empty()); + s.execute("filter.savePreset", &json!({"name": "Several"})).unwrap(); + s.execute("library.filter", &json!({"facets": [], "flags": []})).unwrap(); + assert!(shown(&mut s, &ids).len() > before.len()); + s.execute("filter.applyPreset", &json!({"name": "Several"})).unwrap(); + assert_eq!(shown(&mut s, &ids), before); + // and through the JSON the preset is kept as + let json = serde_json::to_string(&s.filter).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), s.filter); +} + +#[test] +fn the_older_value_form_still_toggles_and_sets_a_single_value() { + let (mut s, ids) = library(); + s.execute("library.facetPick", &json!({"field": "year", "value": "1995"})).unwrap(); + s.execute("library.facetPick", &json!({"field": "year", "value": "1996"})).unwrap(); + assert_eq!(shown(&mut s, &ids), ids[2..4], "a single-valued field keeps the last value clicked"); + s.execute("library.facetPick", &json!({"field": "year", "value": "1996"})).unwrap(); + assert_eq!(s.filter, Filter::default(), "a second click clears it"); +} diff --git a/crates/engine/src/tests_facets.rs b/crates/engine/src/tests_facets.rs index db6c18bdb4..fdf3da0f45 100644 --- a/crates/engine/src/tests_facets.rs +++ b/crates/engine/src/tests_facets.rs @@ -80,6 +80,9 @@ fn picks_narrow_cascade_take_unknown_and_single_values_and_refuse_bad_ones() { json!({"field": "kind", "value": "hologram"}), json!({"field": "year", "value": "20x6"}), json!({"field": "year", "value": "é202"}), + json!({"field": "year", "value": "2026-13"}), + json!({"field": "year", "value": "2026-02-30"}), + json!({"field": "year", "value": "2026-1-1"}), json!({"field": "label", "value": "Ultraviolet"}), ] { assert!(s.execute("library.facetPick", &p).is_err(), "{p}"); @@ -202,3 +205,40 @@ fn the_face_count_column_counts_and_picks_by_number_of_faces() { assert_eq!(visible, vec![ids[1], ids[2]]); assert!(s.execute("library.facetPick", &json!({"field": "faces", "none": true})).is_err(), "no photo is without a count"); } + +/// Issue #1708: the Date column ("year" facet) returns a Year -> Month -> Day tree and accepts +/// YYYY, YYYY-MM, and YYYY-MM-DD picks, cascading with other columns and toggling off on re-pick. +#[test] +fn date_facet_returns_year_month_day_tree_and_picks_by_day_or_month() { + let (mut s, ids) = library(); + for (id, date) in [(ids[0], "2025-11-10T10:00:00"), (ids[1], "2025-11-11T12:00:00"), (ids[2], "2025-12-01T09:00:00")] { + s.catalog.apply(Op::SetCaptured { id, captured: Some(date.into()) }).unwrap(); + } + let facets = s.execute("library.facets", &json!({"fields": ["year"]})).unwrap(); + let tree = facets["year"]["tree"].as_array().expect("year.tree array"); + let y2025 = tree.iter().find(|y| y["year"] == "2025").expect("2025 in tree"); + assert_eq!(y2025["count"], 3); + let months = y2025["months"].as_array().unwrap(); + let m11 = months.iter().find(|m| m["month"] == "2025-11").expect("2025-11 in tree"); + assert_eq!(m11["count"], 2); + let days = m11["days"].as_array().unwrap(); + assert!(days.iter().any(|d| d["day"] == "2025-11-10" && d["count"] == 1)); + assert!(days.iter().any(|d| d["day"] == "2025-11-11" && d["count"] == 1)); + + // Pick a single day + s.execute("library.facetPick", &json!({"field": "year", "value": "2025-11-10"})).unwrap(); + assert_eq!(s.visible().to_vec(), vec![ids[0]]); + assert_eq!(s.execute("library.facets", &json!({"fields": ["year"]})).unwrap()["year"]["chosen"], json!(["2025-11-10"])); + + // Pick a month + s.execute("library.facetPick", &json!({"field": "year", "value": "2025-11"})).unwrap(); + let mut vis = s.visible().to_vec(); + vis.sort(); + assert_eq!(vis, vec![ids[0], ids[1]]); + + // Pick the whole year, then click again to clear + s.execute("library.facetPick", &json!({"field": "year", "value": "2025"})).unwrap(); + assert_eq!(s.visible().len(), 3); + s.execute("library.facetPick", &json!({"field": "year", "value": "2025"})).unwrap(); + assert_eq!(s.filter, lcc_catalog::Filter::default()); +} diff --git a/crates/engine/src/tests_import_companions.rs b/crates/engine/src/tests_import_companions.rs new file mode 100644 index 0000000000..96ce82ac13 --- /dev/null +++ b/crates/engine/src/tests_import_companions.rs @@ -0,0 +1,305 @@ +//! Raw + JPEG companions (issue #1692): a JPEG with a raw's name beside it imports as the raw's +//! companion — one photo, one face scan, one set of metadata — instead of a photo of its own. It +//! travels with the raw through Copy / Move and Rename, and a raw the library already has is +//! pointed at the JPEG beside it. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::Session; + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("lc-import-companions-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A tiny real DNG (`/.DNG`) and its JPEG twin (`/.JPG`); `seed` makes +/// every pair's bytes distinct (a second pair is never a content duplicate of the first). +fn write_pair(dir: &Path, stem: &str, seed: u8) -> (PathBuf, PathBuf) { + let dng = crate::tests_xmp::synthetic_dng_with(None, lcc_meta::Metadata { title: Some(format!("pair {seed}")), ..Default::default() }); + let pixels = [100u8.saturating_add(seed); 12]; + let jpeg = lcc_codecs::encode_jpeg( + &lcc_codecs::EncodeImage::new(2, 2, 3, lcc_codecs::Samples::U8(&pixels)), + 90, + Default::default(), + &Default::default(), + ) + .unwrap(); + let (raw, jpg) = (dir.join(format!("{stem}.DNG")), dir.join(format!("{stem}.JPG"))); + std::fs::write(&raw, dng).unwrap(); + std::fs::write(&jpg, jpeg).unwrap(); + (raw, jpg) +} + +/// The JPEG beside its raw is not a photo of its own: one photo, the companion on the record, +/// the report says so, and the scan shows the pair as one. +#[test] +fn a_jpeg_beside_its_raw_imports_as_the_raws_companion() { + let src = temp_dir("add"); + let (raw, jpg) = write_pair(&src, "IMG_0001", 1); + let src_str = src.to_string_lossy().to_string(); + + // the scan marks the JPEG with the raw beside it, not as a photo of its own + let mut s = Session::new().with_fs(); + let scan = s.execute("library.importPreview", &json!({"paths": [src_str]})).unwrap(); + let candidates = scan["candidates"].as_array().unwrap(); + let jpg_c = candidates.iter().find(|c| c["path"].as_str().unwrap().ends_with("IMG_0001.JPG")).unwrap(); + let raw_c = candidates.iter().find(|c| c["path"].as_str().unwrap().ends_with("IMG_0001.DNG")).unwrap(); + assert_eq!(jpg_c["companionOf"].as_str().unwrap().replace('\\', "/"), raw_c["path"].as_str().unwrap().replace('\\', "/"), "{scan}"); + + let r = s.execute("library.import", &json!({"paths": [src_str]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "the raw only: {r}"); + let id = r["imported"][0].as_u64().unwrap(); + let companions = r["companions"].as_array().unwrap(); + assert_eq!(companions.len(), 1, "{r}"); + assert_eq!(companions[0]["path"].as_str().unwrap().replace('\\', "/"), jpg.to_string_lossy().replace('\\', "/")); + assert_eq!(companions[0]["raw"], id, "{r}"); + let p = s.catalog.photo(lcc_catalog::PhotoId(id)).unwrap(); + assert_eq!(p.companion_jpeg.as_deref().map(|c| c.replace('\\', "/")), Some(jpg.to_string_lossy().replace('\\', "/"))); + assert!(!s.catalog.photos().any(|p| p.file_name.eq_ignore_ascii_case("IMG_0001.JPG")), "the JPEG is no photo"); + assert!(raw.is_file() && jpg.is_file(), "added where they are, both files stay"); + + // the pair stays one: importing the folder again adds nothing — the raw is a duplicate by + // path, and the JPEG beside it is reported as that photo's companion again + let r = s.execute("library.import", &json!({"paths": [src_str]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(0), "{r}"); + assert_eq!(r["duplicates"].as_array().map(Vec::len), Some(1), "the raw is a duplicate by path: {r}"); + let companions = r["companions"].as_array().unwrap(); + assert_eq!(companions.len(), 1, "{r}"); + assert_eq!(companions[0]["raw"], id, "{r}"); + assert_eq!(s.catalog.photos().filter(|p| p.companion_jpeg.is_some()).count(), 1, "still one pair"); + let _ = std::fs::remove_dir_all(src); +} + +/// The option unchecked (or the library's setting off) keeps today's behaviour: two photos. +#[test] +fn companions_off_imports_the_jpeg_as_its_own_photo() { + let src = temp_dir("off"); + let (_raw, _jpg) = write_pair(&src, "IMG_0002", 2); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "companions": false})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(2), "{r}"); + assert_eq!(r["companions"], Value::Null, "{r}"); + let p = s.catalog.photo(lcc_catalog::PhotoId(r["imported"][0].as_u64().unwrap())).unwrap(); + assert_eq!(p.companion_jpeg, None); + let _ = std::fs::remove_dir_all(src); +} + +/// A JPEG alone (no raw beside it) imports as its own photo, companion mode or not. +#[test] +fn a_jpeg_without_a_raw_beside_it_is_its_own_photo() { + let src = temp_dir("lone"); + let (_, _jpg) = write_pair(&src, "IMG_0003", 3); + std::fs::remove_file(src.join("IMG_0003.DNG")).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + assert_eq!(r["companions"], Value::Null, "{r}"); + let p = s.catalog.photo(lcc_catalog::PhotoId(r["imported"][0].as_u64().unwrap())).unwrap(); + assert!(p.file_name.eq_ignore_ascii_case("IMG_0003.JPG"), "{}", p.file_name); + let _ = std::fs::remove_dir_all(&src); +} + +/// Copy: the pair travels together — the JPEG copied beside the raw copy under its name, the +/// record pointing there, and the sources left as they were. +#[test] +fn a_copy_takes_the_companion_along() { + let src = temp_dir("copy"); + let (raw, jpg) = write_pair(&src, "IMG_0004", 4); + let lib = src.join("Library"); + std::fs::create_dir_all(&lib).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s + .execute("library.import", &json!({"paths": [src.to_string_lossy()], "mode": "copy", "destination": src.join("Originals").to_string_lossy()})) + .unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + let id = r["imported"][0].as_u64().unwrap(); + let p = s.catalog.photo(lcc_catalog::PhotoId(id)).unwrap(); + let crate::catalog::Source::File { path } = &p.source else { panic!("a file photo") }; + let stored = PathBuf::from(path); + assert!(stored.starts_with(src.join("Originals")), "the copy is under the destination: {path}"); + let companion = PathBuf::from(p.companion_jpeg.as_ref().expect("the companion travelled")); + assert_eq!( + crate::rename::split_ext(&companion.to_string_lossy()).0, + crate::rename::split_ext(&stored.to_string_lossy()).0, + "the same name as the raw copy: {companion:?}" + ); + assert!(companion.is_file() && stored.is_file(), "both at the destination"); + assert!(raw.is_file() && jpg.is_file(), "the sources stay (a Copy)"); + // both copies verified: the JPEG twin's bytes are the original's + assert_eq!(std::fs::read(&companion).unwrap(), std::fs::read(&jpg).unwrap()); + let _ = std::fs::remove_dir_all(src); +} + +/// Move: the pair travels together and the sources go — the raw's and the companion's. +#[test] +fn a_move_takes_the_companion_along_and_both_sources_go() { + let src = temp_dir("move"); + let (raw, jpg) = write_pair(&src, "IMG_0005", 5); + let lib = src.join("Library"); + std::fs::create_dir_all(&lib).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s + .execute("library.import", &json!({"paths": [src.to_string_lossy()], "mode": "move", "destination": src.join("Originals").to_string_lossy()})) + .unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + let id = r["imported"][0].as_u64().unwrap(); + let p = s.catalog.photo(lcc_catalog::PhotoId(id)).unwrap(); + let companion = p.companion_jpeg.as_ref().expect("the companion travelled").replace('\\', "/"); + assert!(!raw.exists() && !jpg.exists(), "both sources removed"); + assert!(Path::new(&companion).is_file(), "the companion at the destination: {companion}"); + let moved = r["moved"].as_array().unwrap(); + assert!(moved.iter().any(|m| m["to"].as_str().unwrap().replace('\\', "/") == companion), "{r}"); + let _ = std::fs::remove_dir_all(src); +} + +/// A raw the library already has is pointed at the JPEG beside it when the JPEG arrives later +/// (a card imported raws first, the JPEGs came with the folder). +#[test] +fn a_late_jpeg_attaches_to_the_librarys_raw() { + let src = temp_dir("late"); + // the raw alone first (no JPEG beside it yet) + let dng = crate::tests_xmp::synthetic_dng_with(None, lcc_meta::Metadata::default()); + let raw = src.join("IMG_0006.DNG"); + std::fs::write(&raw, dng).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + assert_eq!(s.catalog.photo(lcc_catalog::PhotoId(id)).unwrap().companion_jpeg, None); + // the JPEG arrives: the import skips it as the raw's companion and points the raw at it + let jpg = src.join("IMG_0006.JPG"); + let pixels = [106u8; 12]; + let jpeg = lcc_codecs::encode_jpeg( + &lcc_codecs::EncodeImage::new(2, 2, 3, lcc_codecs::Samples::U8(&pixels)), + 90, + Default::default(), + &Default::default(), + ) + .unwrap(); + std::fs::write(&jpg, jpeg).unwrap(); + let r = s.execute("library.import", &json!({"paths": [jpg.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(0), "{r}"); + let companions = r["companions"].as_array().unwrap(); + assert_eq!(companions.len(), 1, "{r}"); + assert_eq!(companions[0]["raw"], id, "{r}"); + let p = s.catalog.photo(lcc_catalog::PhotoId(id)).unwrap(); + assert_eq!(p.companion_jpeg.as_deref().map(|c| c.replace('\\', "/")), Some(jpg.to_string_lossy().replace('\\', "/"))); + let _ = std::fs::remove_dir_all(src); +} + +/// Rename: the companion keeps the pair together — the file takes the raw's new name, the record +/// follows it, and undo puts both back. +#[test] +fn a_rename_takes_the_companion_along_and_undo_puts_both_back() { + let src = temp_dir("rename"); + let (raw, jpg) = write_pair(&src, "IMG_0007", 7); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rename", &json!({"ids": [id], "template": "Trip-{seq:3}"})).unwrap(); + let p = s.catalog.photo(lcc_catalog::PhotoId(id)).unwrap(); + let companion = p.companion_jpeg.as_ref().expect("the companion followed").clone(); + assert!(Path::new(&companion).is_file(), "renamed beside the raw: {companion}"); + assert!(crate::rename::split_ext(&companion).1.eq_ignore_ascii_case("JPG"), "{companion}"); + // the same name as the raw: Trip-001.JPG beside Trip-001.DNG (split_ext on a full path + // keeps the folders, so the names are compared through their file names) + let companion_name = Path::new(&companion).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + assert_eq!(crate::rename::split_ext(&companion_name).0, crate::rename::split_ext(&p.file_name).0, "the same name as the raw"); + assert!(!jpg.exists(), "the old name is gone"); + s.undo_step().unwrap(); + let p = s.catalog.photo(lcc_catalog::PhotoId(id)).unwrap(); + assert!(p.file_name.eq_ignore_ascii_case("IMG_0007.DNG"), "{}", p.file_name); + let companion = p.companion_jpeg.as_ref().expect("the companion back on the record").clone(); + assert!(Path::new(&companion).is_file() && jpg.exists(), "both files back"); + assert!(raw.is_file(), "the raw back too"); + let _ = std::fs::remove_dir_all(src); +} + +/// One photo per pair is what the whole library sees: no second record for the companion — no +/// second thumbnail, and the face scan (which walks the catalog's photos) runs on the raw only. +#[test] +fn the_pair_is_one_photo_everywhere() { + let src = temp_dir("one"); + let (_, jpg) = write_pair(&src, "IMG_0008", 8); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + let library: Vec<_> = s.catalog.photos().filter(|p| p.in_library()).collect(); + assert_eq!(library.len(), 1, "the raw only, never the JPEG"); + assert!(!library.iter().any(|p| p.file_name.eq_ignore_ascii_case("IMG_0008.JPG")), "no record carries the JPEG's name"); + assert!(jpg.is_file(), "the file stays beside its raw"); + let _ = std::fs::remove_dir_all(&src); +} + +/// Two raws sharing one name in a folder: the first keeps the JPEG, the second goes without. +#[test] +fn two_raws_of_one_name_leave_one_companion() { + let src = temp_dir("tworaws"); + let (_raw, _jpg) = write_pair(&src, "IMG_0009", 9); + // a second raw with the same name, different content (and a name the probe reads as a raw too) + let dng2 = crate::tests_xmp::synthetic_dng_with(None, lcc_meta::Metadata { title: Some("second".into()), ..Default::default() }); + let raw2 = src.join("IMG_0009.NEF"); + std::fs::write(&raw2, dng2).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(2), "{r}"); + let with = s.catalog.photos().filter(|p| p.companion_jpeg.is_some()).count(); + assert_eq!(with, 1, "one raw keeps the JPEG: {r}"); + let _ = std::fs::remove_dir_all(&src); +} + +/// The library's setting drives the import (`catalog.settings rawJpegCompanions`): off, the pair +/// comes in as two photos; on, as one. +#[test] +fn the_library_setting_decides() { + let src = temp_dir("setting"); + let (_raw, _jpg) = write_pair(&src, "IMG_0010", 10); + let lib = src.join("Library"); + std::fs::create_dir_all(&lib).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert!(s.catalog_settings().raw_jpeg_companions, "on by default"); + let mut settings = s.catalog_settings(); + settings.raw_jpeg_companions = false; + s.set_catalog_settings(&settings).unwrap(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(2), "the setting off: two photos: {r}"); + // and back on: a later pair is one + let mut settings = s.catalog_settings(); + settings.raw_jpeg_companions = true; + s.set_catalog_settings(&settings).unwrap(); + let src2 = temp_dir("setting2"); + write_pair(&src2, "IMG_0011", 11); + let r = s.execute("library.import", &json!({"paths": [src2.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + let _ = std::fs::remove_dir_all(src); + let _ = std::fs::remove_dir_all(src2); +} + +/// A JPEG the library already has as a photo stays its own photo: not a companion of the raw +/// beside it (a record already points at it), and the import says duplicate. +#[test] +fn a_jpeg_already_in_the_library_is_not_a_companion() { + let src = temp_dir("already"); + let (_raw, jpg) = write_pair(&src, "IMG_0012", 12); + // the JPEG imported on its own first (companions off, say) + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [jpg.to_string_lossy()], "companions": false})).unwrap(); + let jid = r["imported"][0].as_u64().unwrap(); + // then the folder with companions on: the raw imports; the JPEG beside it is a duplicate by + // path (its record stands), never a companion + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + let rid = r["imported"][0].as_u64().unwrap(); + assert_eq!(r["companions"], Value::Null, "the JPEG stays its own photo: {r}"); + assert_eq!(r["duplicates"].as_array().map(Vec::len), Some(1), "{r}"); + let p = s.catalog.photo(lcc_catalog::PhotoId(rid)).unwrap(); + assert_eq!(p.companion_jpeg, None, "the raw is not pointed at a photo of the library"); + assert!(s.catalog.photo(lcc_catalog::PhotoId(jid)).is_some(), "the JPEG's record stands"); + let _ = std::fs::remove_dir_all(src); +} diff --git a/crates/engine/src/tests_move_to_share.rs b/crates/engine/src/tests_move_to_share.rs index 58f706006a..e5ce207287 100644 --- a/crates/engine/src/tests_move_to_share.rs +++ b/crates/engine/src/tests_move_to_share.rs @@ -144,6 +144,7 @@ fn plans(s: &Session, ids: &[PhotoId], into: &str) -> Vec Vec { + let kw = |name: &str, value: i32| format!("{:<80}", format!("{name:<8}= {value:>20}")); + let mut cards = vec![format!("{:<80}", "SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", axes as i32)]; + let lengths = [16usize, 8, 2, 2]; + cards.extend(lengths.iter().enumerate().take(axes).map(|(i, n)| kw(&format!("NAXIS{}", i + 1), *n as i32))); + cards.extend([kw("BZERO", 32768), format!("{:<80}", "BAYERPAT= 'RGGB '")]); + let mut out: Vec = cards.iter().flat_map(|c| c.as_bytes().iter().copied()).collect(); + out.extend_from_slice(b"END"); + out.resize(2880, b' '); + out.extend((0..lengths.iter().take(axes).product::()).flat_map(|i| (((i * 997 % 60000 + 500) as i32 - 32768) as i16).to_be_bytes())); + out +} + +/// FITS is not a format LibRaw reads: Auto never hands it one (lcc-raw decodes the file), and with LibRaw chosen for +/// the camera the file comes back to lcc-raw, as it does where no LibRaw exists (web, Android). +#[test] +fn fits_is_read_by_lcc_raw_whatever_the_choice() { + let bytes = fits(2); + let fake = Fake::new(Err("unsupported file format".into())); + let (raw, used) = decode_as(&bytes, Decoder::Auto, Some(&fake)).unwrap(); + assert_eq!((used, fake.calls()), (Used::Lcc, 0)); + assert_eq!(raw, lcc_raw::decode(&bytes).unwrap()); + let (raw, used) = decode_as(&bytes, Decoder::Libraw, Some(&fake)).unwrap(); + assert_eq!((used, fake.calls()), (Used::Lcc, 1)); + assert_eq!((raw.format, raw.width, raw.height), (lcc_raw::RawFormat::Fits, 16, 8)); + let (raw, used) = decode_as(&bytes, Decoder::Libraw, None).unwrap(); + assert_eq!((used, raw.format), (Used::Lcc, lcc_raw::RawFormat::Fits)); + // a variant lcc-raw refuses is handed to LibRaw, which cannot read FITS either: the refusal names the reason + let err = decode_as(&fits(4), Decoder::Auto, Some(&fake)).unwrap_err(); + assert!(matches!(&err, lcc_raw::RawError::Unsupported(m) if m.contains("4 axes")), "{err}"); + assert_eq!(fake.calls(), 2); +} + #[test] fn a_frame_without_app_headers_takes_libraws_matrix_and_the_whole_image_area() { let raw = frame().into_raw_image(&unsupported()).unwrap(); diff --git a/crates/engine/src/tests_select_menu.rs b/crates/engine/src/tests_select_menu.rs index 8069884d66..ea1cc6ea15 100644 --- a/crates/engine/src/tests_select_menu.rs +++ b/crates/engine/src/tests_select_menu.rs @@ -103,7 +103,7 @@ fn deselect_unflagged_with_no_pick_or_no_selection_does_not_panic() { s.execute("photo.flag", &json!({"ids": [vis[0].0, vis[1].0], "flag": "none"})).unwrap(); s.execute("library.select", &json!({"ids": [vis[0].0, vis[1].0], "active": vis[1].0})).unwrap(); s.execute("library.deselectUnflagged", &json!({})).unwrap(); - assert_eq!(s.selection, Selection::single(vis[1]), "acts as Deselect All"); + assert_eq!(s.selection, Selection::default(), "with none flagged, nothing stays selected, the active photo included"); s.selection = Selection::default(); assert!(s.execute("library.deselectUnflagged", &json!({})).is_ok()); assert_eq!(s.selection, Selection::default()); diff --git a/crates/engine/src/tests_slideshow_export.rs b/crates/engine/src/tests_slideshow_export.rs index ce38c2a9f6..13e5c793c8 100644 --- a/crates/engine/src/tests_slideshow_export.rs +++ b/crates/engine/src/tests_slideshow_export.rs @@ -133,6 +133,7 @@ fn pdf_has_a_page_per_slide_titles_included() { let r = export(&mut s, json!({"format": "pdf", "path": path, "size": 160, "quality": 80, "ids": ids})); assert_eq!((r["pages"].as_u64(), r["slides"].as_u64(), r["width"].as_u64(), r["height"].as_u64()), (Some(5), Some(5), Some(160), Some(90))); let bytes = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64)); assert!(bytes.starts_with(b"%PDF-1.4")); let pages = pdf_pages(&bytes); assert_eq!(pages.len(), 5); @@ -152,7 +153,9 @@ fn pdf_has_a_page_per_slide_titles_included() { s.execute("slideshow.layout", &json!({"aspect": "4:3"})).unwrap(); let r = export(&mut s, json!({"format": "pdf", "path": path, "size": 120, "fullScreen": false, "ids": ids})); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(120), Some(90))); - assert!(!String::from_utf8_lossy(&std::fs::read(&path).unwrap()).contains("/FullScreen")); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64)); + assert!(!String::from_utf8_lossy(&bytes).contains("/FullScreen")); } #[test] diff --git a/crates/engine/src/tests_spots.rs b/crates/engine/src/tests_spots.rs index c0ba4b54d5..8cc39918b4 100644 --- a/crates/engine/src/tests_spots.rs +++ b/crates/engine/src/tests_spots.rs @@ -21,6 +21,36 @@ fn up_and_down_move_by_rows_and_stop_at_the_ends() { assert_eq!(s.selection.active, vis.last().copied(), "hostile counts clamp, never overflow"); } +/// F-66C0: with no photo active (none selected, or the state Cmd+D leaves), ↑ selects the first photo of the view and +/// ↓ the last, each made active; with a photo active they step from it as before. +#[test] +fn with_no_photo_active_up_takes_the_first_and_down_the_last() { + let mut s = Session::with_demo(); + let vis = s.visible_cloned(); + assert!(vis.len() >= 6); + // AC-1: nothing selected, ↑ selects the first photo and makes it active + s.selection = crate::Selection { ids: vec![], active: None }; + s.execute("library.up", &json!({})).unwrap(); + assert_eq!((s.selection.active, s.selection.ids.clone()), (Some(vis[0]), vec![vis[0]])); + // AC-2: nothing selected, ↓ selects the last photo and makes it active + s.selection = crate::Selection { ids: vec![], active: None }; + s.execute("library.down", &json!({})).unwrap(); + assert_eq!((s.selection.active, s.selection.ids.clone()), (vis.last().copied(), vec![*vis.last().unwrap()])); + // AC-4: a selection with no active photo behaves the same, whatever the row distance + s.selection = crate::Selection { ids: vec![vis[2], vis[3]], active: None }; + s.execute("library.down", &json!({"rows": 3})).unwrap(); + assert_eq!(s.selection.active, vis.last().copied()); + s.selection = crate::Selection { ids: vec![vis[2], vis[3]], active: None }; + s.execute("library.up", &json!({"rows": 3})).unwrap(); + assert_eq!(s.selection.active, Some(vis[0])); + // AC-3: with a photo active, ↑ and ↓ still step from it + s.selection = crate::Selection::single(vis[3]); + s.execute("library.down", &json!({})).unwrap(); + assert_eq!(s.selection.active, Some(vis[4])); + s.execute("library.up", &json!({})).unwrap(); + assert_eq!(s.selection.active, Some(vis[3])); +} + fn spots(s: &Session) -> Vec { s.develop_of(s.active().unwrap()).unwrap().spots.clone() } diff --git a/crates/engine/src/tests_xmp.rs b/crates/engine/src/tests_xmp.rs index 409792ea40..ea2241a2e1 100644 --- a/crates/engine/src/tests_xmp.rs +++ b/crates/engine/src/tests_xmp.rs @@ -924,8 +924,12 @@ pub(crate) fn synthetic_dng_with(xmp: Option<&str>, metadata: lcc_meta::Metadata /// A synthetic Bayer DNG for denoise and cache tests. pub(crate) fn synthetic_dng_of(w: usize, h: usize, cfa: &str, data: Vec, xmp: Option<&str>, metadata: lcc_meta::Metadata) -> Vec { + synthetic_dng_cfa(w, h, lcc_raw::Cfa::bayer(cfa).unwrap(), data, xmp, metadata) +} + +/// [`synthetic_dng_of`] for any colour filter array, Bayer or not (X-Trans). +pub(crate) fn synthetic_dng_cfa(w: usize, h: usize, cfa: lcc_raw::Cfa, data: Vec, xmp: Option<&str>, metadata: lcc_meta::Metadata) -> Vec { use lcc_raw::*; - let cfa = Cfa::bayer(cfa).unwrap(); let raw = RawImage { format: RawFormat::Dng, width: w, diff --git a/crates/engine/src/update.rs b/crates/engine/src/update.rs index 2105961de2..23d59c1304 100644 --- a/crates/engine/src/update.rs +++ b/crates/engine/src/update.rs @@ -26,6 +26,22 @@ pub const ACTIVITY_KIND: &str = "update"; /// The row's label (English; the frontend translates it). pub const ACTIVITY_LABEL: &str = "Downloading update"; +/// The variable (after the brand's env prefix) that turns every update check and prompt off. +pub const DISABLE_ENV: &str = "DISABLE_UPDATES"; + +/// Whether `_DISABLE_UPDATES` (or a legacy spelling) turns update checks off for this +/// process. Distro packages (NixOS, deb/rpm, …) set it: the package manager owns the update flow, +/// so the app's own start-up prompt and manual check would only nag. Adapted from upstream #4663. +pub fn disabled_by_env() -> bool { + disabled_by_value(lcc_brand::env(DISABLE_ENV).as_deref()) +} + +/// [`disabled_by_env`] for a known value, without reading the environment: `1`, `on`, `true` or +/// `yes` (case-insensitive, trimmed) turn updates off; anything else, or no variable, leaves them on. +pub fn disabled_by_value(value: Option<&str>) -> bool { + value.is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "on" | "true" | "yes")) +} + /// Settings file in the app's settings folder. const SETTINGS_FILE: &str = "updates.json"; /// Schema version of that file; a file from a newer build is left alone. diff --git a/crates/engine/src/update/tests.rs b/crates/engine/src/update/tests.rs index 2be11af217..f2da7c7774 100644 --- a/crates/engine/src/update/tests.rs +++ b/crates/engine/src/update/tests.rs @@ -911,3 +911,14 @@ fn a_package_install_is_sent_to_its_package_manager() { assert!(activity.list().is_empty(), "nothing started"); let _ = std::fs::remove_dir_all(&dir); } + +// upstream #4663: `_DISABLE_UPDATES` values that turn updates off, and those that don't +#[test] +fn disable_updates_values() { + for on in ["1", "on", "true", "yes", " yes ", "TRUE"] { + assert!(disabled_by_value(Some(on)), "{on:?}"); + } + for off in [None, Some(""), Some(" "), Some("0"), Some("false"), Some("off"), Some("no"), Some("2")] { + assert!(!disabled_by_value(off), "{off:?}"); + } +} diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 7555e55aa3..29186ad1b7 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -116,6 +116,28 @@ pub struct Browse { pub not_imported: bool, } +/// What the library shows whose photos can be put in Custom Order (issue #1583): a regular +/// album, or one folder of the Folders panel shown as its own photos: without the photos of the +/// folders inside it, or holding none below it. With the photos of several folders shown there is +/// no one order to go by. What `library.sort {key: custom}` sorts by and what a drag in the grid +/// rearranges; see [`crate::Session::custom_order_source`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CustomOrderSource { + Album(AlbumId), + /// The folder, spelled as [`crate::Session::library_folder`] spells it. + Folder(String), +} + +impl CustomOrderSource { + /// What a message calls it: "collection" or "folder". + pub(crate) fn noun(&self) -> &'static str { + match self { + CustomOrderSource::Album(_) => "collection", + CustomOrderSource::Folder(_) => "folder", + } + } +} + /// How far back Recently Added reaches from the latest import. pub const RECENT_DAYS: i64 = 30; @@ -302,6 +324,37 @@ pub fn filter_chips(f: &Filter, cat: &Catalog) -> Vec { }; add(format!("Type: {n}"), json!({"merged": Null})); } + // several Rating, Type or Date values chosen in a Metadata column (or the Type menu): one chip, "Date: 1995 or + // March 1996"; its × takes that entry out of `Filter::facets` and keeps the others + for pk in f.facets.iter().filter(|p| matches!(p.field.as_str(), "rating" | "kind" | "year") && !p.is_empty()) { + let mut names: Vec = pk + .values + .iter() + .map(|v| match (pk.field.as_str(), v.as_str()) { + ("rating", "0") => "Unrated".to_string(), + ("rating", n) => format!("{n}★"), + ("kind", "image") => "Photos".to_string(), + ("kind", "raw") => "Raw".to_string(), + ("kind", "video") => "Videos".to_string(), + ("kind", "hdr") => "HDR".to_string(), + ("kind", "panorama") => "Panoramas".to_string(), + ("kind", "hdrPanorama") => "HDR panoramas".to_string(), + ("kind", "focusStack") => "Focus stacks".to_string(), + ("year", d) => date_label(d), + (_, other) => other.to_string(), + }) + .collect(); + if pk.none { + names.push("Unknown".to_string()); + } + let name = match pk.field.as_str() { + "rating" => "Rating =", + "kind" => "Type:", + _ => "Date:", + }; + let rest: Vec<&lcc_catalog::FacetPick> = f.facets.iter().filter(|p| p.field != pk.field).collect(); + add(format!("{name} {}", names.join(" or ")), json!({"facets": rest})); + } if let Some(e) = f.edited { add(if e { "Edited".into() } else { "Unedited".into() }, json!({"edited": Null})); } diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index afffd45be3..e791b2d9d5 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -143,7 +143,7 @@ pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, Entr /// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped and counted /// ([`Walked::unreadable`]), as are the files `keep` refuses ([`Walked::skipped`]). pub fn files_in(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool) -> Walked { - walk(root, skip, limits, keep, |_| true, None) + walk(root, skip, limits, keep, |_| true, None, None) } /// [`files_in`], entering a folder below `root` only when `enter` accepts it: a folder it turns @@ -156,14 +156,30 @@ pub fn files_in_entering( keep: impl FnMut(&Path) -> bool, enter: impl FnMut(&Path) -> bool, ) -> Walked { - walk(root, skip, limits, keep, enter, None) + walk(root, skip, limits, keep, enter, None, None) } /// [`files_in`], handing the listing of every folder it reads to `note`: who walks a folder to /// find its files has, with that, the answer to "is this name there" for everything in it, and /// need not ask the disk again (a round trip for each name on a network share). pub fn files_in_noting(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked { - walk(root, skip, limits, keep, |_| true, Some(note)) + walk(root, skip, limits, keep, |_| true, Some(note), None) +} + +/// [`files_in`] (or [`files_in_noting`] with `note`) sharing canonical folder identities across +/// the roots of one request in `seen`: a folder already walked from an earlier root (named twice, +/// inside another root, or reached through a link) is not walked again, and the first spelling of +/// its path is the one kept. It costs one `canonicalize` per folder (not per entry), which is why +/// only multi-root requests ask for it. Adapted from upstream #1638. +pub(crate) fn files_in_with_seen( + root: &Path, + skip: Option<&Path>, + limits: Limits, + keep: impl FnMut(&Path) -> bool, + note: Option, + seen: &mut HashSet, +) -> Walked { + walk(root, skip, limits, keep, |_| true, note, Some(seen)) } fn walk( @@ -173,6 +189,7 @@ fn walk( mut keep: impl FnMut(&Path) -> bool, mut enter: impl FnMut(&Path) -> bool, mut note: Option, + mut shared: Option<&mut HashSet>, ) -> Walked { let mut out = Walked::default(); // canonical folders reached through a link, so a link loop is walked at most once @@ -200,6 +217,20 @@ fn walk( out.truncated = true; continue; } + // after the depth check: a folder too deep to be read here was not walked, so a later root + // that names it still is + if let Some(seen) = shared.as_deref_mut() { + // a folder whose canonical path can't be had (some network and virtual drives) is + // walked under its own spelling rather than left out + let real = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); + if seen.len() >= MAX_ENTRIES && !seen.contains(&real) { + out.truncated = true; + break; + } + if !seen.insert(real) { + continue; + } + } let Ok(rd) = std::fs::read_dir(&path) else { out.unreadable = out.unreadable.saturating_add(1); continue; @@ -525,4 +556,23 @@ mod tests { assert!(w.files.iter().any(|p| p.ends_with("a/b/p.jpg")), "{w:?}"); let _ = std::fs::remove_dir_all(&d); } + + /// Roots sharing `seen`: a folder is walked once, but one that an earlier root only passed by + /// (too deep for it: an import without subfolders) is still walked when a later root names it. + #[test] + fn shared_roots_walk_a_folder_once_but_not_one_they_only_passed() { + let d = tmp("seen"); + std::fs::create_dir_all(d.join("sub")).unwrap(); + std::fs::write(d.join("top.jpg"), b"x").unwrap(); + std::fs::write(d.join("sub/inner.jpg"), b"x").unwrap(); + let flat = Limits { max_depth: 1, ..Limits::default() }; + let mut seen = HashSet::new(); + let top = files_in_with_seen(&d, None, flat, |_| true, None, &mut seen); + assert_eq!(top.files, [d.join("top.jpg")]); + let sub = files_in_with_seen(&d.join("sub"), None, flat, |_| true, None, &mut seen); + assert_eq!(sub.files, [d.join("sub/inner.jpg")], "the subfolder named as a root of its own"); + let again = files_in_with_seen(&d.join("sub"), None, flat, |_| true, None, &mut seen); + assert!(again.files.is_empty(), "walked once: {again:?}"); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/engine/tests/import_keywords.rs b/crates/engine/tests/import_keywords.rs new file mode 100644 index 0000000000..7a5ea52ee6 --- /dev/null +++ b/crates/engine/tests/import_keywords.rs @@ -0,0 +1,98 @@ +//! Keyword normalization is the same for import presets and import-dialog keywords. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use lcc_engine::Session; +use serde_json::json; + +struct Input(PathBuf); + +impl Input { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let path = std::env::temp_dir().join(format!("import-keywords-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&path).unwrap(); + let image = lcc_raster::Rgba8 { width: 2, height: 1, data: vec![[20, 40, 60, 255], [80, 100, 120, 255]] }; + let bytes = lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&image), &lcc_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(path.join("photo.png"), bytes).unwrap(); + Self(path) + } + + fn photo(&self) -> PathBuf { + self.0.join("photo.png") + } + + fn sidecar(&self) { + std::fs::write( + self.0.join("photo.xmp"), + r#"ÉtéPortraitOriginalÉté|PortraitOriginal"#, + ) + .unwrap(); + } +} + +impl Drop for Input { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn keywords(s: &Session) -> Vec { + assert_eq!(s.catalog.len(), 1); + s.catalog.photos().next().unwrap().meta.keywords.clone() +} + +fn import(s: &mut Session, path: &Path, mut options: serde_json::Value) { + options["paths"] = json!([path.to_string_lossy()]); + let report = s.execute("library.import", &options).unwrap(); + assert_eq!(report["imported"].as_array().unwrap().len(), 1, "{report}"); + assert_eq!(report["failed"], json!([]), "{report}"); +} + +#[test] +fn default_metadata_preset_cleans_keywords_and_ignores_unicode_duplicates() { + let input = Input::new(); + let mut s = Session::new().with_fs(); + s.execute( + "metadata.savePreset", + &json!({"name": "Default", "fields": {"creator": "Studio", "keywords": [ + " || ", " Été | Portrait ", "été|portrait", "Ärger", "ärger", "studio", "STUDIO" + ]}}), + ) + .unwrap(); + s.execute("library.preferences", &json!({"import": {"metadataPreset": "Default"}})).unwrap(); + + import(&mut s, &input.photo(), json!({})); + assert_eq!(keywords(&s), ["Été|Portrait", "Ärger", "studio"]); + assert_eq!(s.catalog.photos().next().unwrap().meta.creator, "Studio"); +} + +#[test] +fn explicit_preset_and_import_keywords_keep_first_sidecar_spellings_and_order() { + let input = Input::new(); + input.sidecar(); + let mut s = Session::new().with_fs(); + s.execute("metadata.savePreset", &json!({"name": "Import", "fields": {"keywords": [" été | portrait ", " | ", "Ärger", "ärger"]}})).unwrap(); + + import( + &mut s, + &input.photo(), + json!({"metadataPreset": "Import", "keywords": ["ÉTÉ|PORTRAIT", " ÄRGER ", " New | Child ", "new|child", " || "]}), + ); + let expected = ["Été|Portrait", "Original", "Ärger", "New|Child"]; + assert_eq!(keywords(&s), expected); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.is_empty(), "the whole import is one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(keywords(&s), expected); +} + +#[test] +fn import_keywords_without_a_preset_use_unicode_keyword_identity() { + let input = Input::new(); + input.sidecar(); + let mut s = Session::new().with_fs(); + import(&mut s, &input.photo(), json!({"keywords": [" été | portrait ", "Ärger", "ärger", " New || Child ", "new|child", " || "]})); + assert_eq!(keywords(&s), ["Été|Portrait", "Original", "Ärger", "New|Child"]); +} diff --git a/crates/engine/tests/keyword_set_inputs.rs b/crates/engine/tests/keyword_set_inputs.rs new file mode 100644 index 0000000000..13116b5b42 --- /dev/null +++ b/crates/engine/tests/keyword_set_inputs.rs @@ -0,0 +1,61 @@ +//! Invalid keyword-set slots must not erase a set or shift its keyboard shortcuts. + +use lcc_engine::Session; +use serde_json::{Value, json}; + +fn sets(s: &mut Session) -> Value { + s.execute("keyword.sets", &json!({})).unwrap() +} + +fn named(s: &mut Session, name: &str) -> Value { + sets(s)["sets"].as_array().unwrap().iter().find(|set| set["name"] == name).unwrap()["keywords"].clone() +} + +#[test] +fn malformed_keyword_slots_leave_saved_sets_and_current_set_unchanged() { + let mut s = Session::new(); + s.execute("keyword.saveSet", &json!({"name": "Saved", "keywords": ["first", "", "third"]})).unwrap(); + s.execute("keyword.saveSet", &json!({"name": "Other", "keywords": ["other"]})).unwrap(); + let before = sets(&mut s); + for keywords in [ + json!(true), + json!(7), + json!(1.5), + json!({"name": "replacement"}), + json!(["first", null, "third"]), + json!(["first", false, "third"]), + json!(["first", 7, "third"]), + json!(["first", {}, "third"]), + json!(["first", [], "third"]), + ] { + for mut params in [json!({"name": "Saved"}), json!({"name": "Renamed", "replace": "Saved"}), json!({"name": "New", "new": true})] { + params["keywords"] = keywords.clone(); + let error = s.execute("keyword.saveSet", ¶ms).unwrap_err().to_string(); + assert!(error.contains("`keywords`"), "{params}: {error}"); + assert_eq!(sets(&mut s), before, "{params}: saved or current sets changed"); + } + } +} + +#[test] +fn valid_keyword_slot_forms_keep_their_existing_meaning() { + let mut s = Session::new(); + s.execute("keyword.saveSet", &json!({"name": "Text", "keywords": " Parent | Child "})).unwrap(); + assert_eq!(named(&mut s, "Text"), json!(["Parent|Child"]), "text stays a single slot"); + s.execute("keyword.saveSet", &json!({"name": "Slots", "keywords": [" Alpha ", "", "Été", "été", "Last", ""]})).unwrap(); + assert_eq!(named(&mut s, "Slots"), json!(["Alpha", "", "Été", "", "Last"])); + + s.execute("keyword.saveSet", &json!({"name": "Inherited"})).unwrap(); + assert_eq!(named(&mut s, "Inherited"), named(&mut s, "Slots"), "omission inherits the current slots"); + s.execute("keyword.saveSet", &json!({"name": "Renamed", "replace": "Text"})).unwrap(); + assert_eq!(named(&mut s, "Renamed"), json!(["Parent|Child"]), "rename without keywords keeps the renamed set's slots"); + + s.execute("keyword.saveSet", &json!({"name": "Slots", "keywords": null})).unwrap(); + assert_eq!(named(&mut s, "Slots"), json!([]), "explicit null still clears"); + s.execute("keyword.saveSet", &json!({"name": "Renamed", "keywords": []})).unwrap(); + assert_eq!(named(&mut s, "Renamed"), json!([]), "an empty list still clears"); + + let many: Vec = (1..=10).map(|n| n.to_string()).collect(); + s.execute("keyword.saveSet", &json!({"name": "Nine", "keywords": many})).unwrap(); + assert_eq!(named(&mut s, "Nine"), json!(many[..9]), "the nine-slot limit is unchanged"); +} diff --git a/crates/engine/tests/overlapping_roots.rs b/crates/engine/tests/overlapping_roots.rs new file mode 100644 index 0000000000..ef161c2850 --- /dev/null +++ b/crates/engine/tests/overlapping_roots.rs @@ -0,0 +1,39 @@ +//! Overlapping import roots (a folder named twice, or inside another root) are walked once and +//! keep the first path spelling; the same holds for preset imports (adapted from upstream #1638). + +use lcc_engine::Session; +use serde_json::json; + +fn temp(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("overlapping-roots-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("real")).unwrap(); + dir +} + +#[test] +fn overlapping_photo_roots_are_walked_once_and_keep_the_first_path() { + let dir = temp("photos"); + let real = dir.join("real"); + std::fs::write(real.join("photo.jpg"), b"not really a jpeg").unwrap(); + let roots = [real.to_string_lossy().to_string(), dir.to_string_lossy().to_string(), real.to_string_lossy().to_string()]; + let (files, truncated) = lcc_engine::import::expand_within(&roots, None, lcc_engine::walk::Limits::default()); + assert!(!truncated); + assert_eq!(files, [real.join("photo.jpg").to_string_lossy().to_string()]); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn overlapping_preset_roots_import_once_and_keep_the_first_path() { + let dir = temp("presets"); + let real = dir.join("real"); + let file = real.join("look.lrtemplate"); + std::fs::write(&file, r#"return { title = "Linked Look", value = { settings = { Exposure2012 = 0.5 } } }"#).unwrap(); + let mut s = Session::new(); + let r = s.execute("preset.import", &json!({"paths": [real, dir, file], "dryRun": true})).unwrap(); + let imported = r["imported"].as_array().unwrap(); + assert_eq!(imported.len(), 1, "{r}"); + assert_eq!(imported[0]["file"], file.to_string_lossy().as_ref()); + assert_eq!(r["failed"], json!([])); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/fetch/Cargo.toml b/crates/fetch/Cargo.toml index 2b9938c37c..05db74521e 100644 --- a/crates/fetch/Cargo.toml +++ b/crates/fetch/Cargo.toml @@ -2,7 +2,8 @@ name = "lcc-fetch" version.workspace = true edition.workspace = true -license = "Apache-2.0 OR GPL-3.0-or-later" +# The project distribution is GPL-3.0-or-later; Apache-2.0 portions keep their notices (NOTICE). +license = "GPL-3.0-or-later OR Apache-2.0" description = "Model downloads: mirrors, resume, pinned SHA-256, over HTTPS in pure Rust (L0)" [lints] diff --git a/crates/fetch/README.md b/crates/fetch/README.md index 84419866c7..2bb32d2da9 100644 --- a/crates/fetch/README.md +++ b/crates/fetch/README.md @@ -1,6 +1,6 @@ # lcc-fetch -Native model downloads in pure Rust (L0, Apache-2.0): HTTP/1.1 over std sockets and rustls with the RustCrypto provider, without ring, aws-lc, C or assembly build dependencies. The wasm32 crate is empty. +Native model downloads in pure Rust (L0, GPL-3.0-or-later OR Apache-2.0): HTTP/1.1 over std sockets and rustls with the RustCrypto provider, without ring, aws-lc, C or assembly build dependencies. The wasm32 crate is empty. Call `download` with bounded file specifications and ordered mirrors, or `download_url` for an exact catalog URL (including its query). Each file has a local filename independent of the URL, a size cap and optional pinned size/SHA-256. Transfers resume pinned `.part` files, verify before renaming, report progress and check cancellation during reads. Run on a worker thread. No proxy support; DNS resolution uses the platform resolver. Tokens are off by default and never forwarded to a different redirect host. A redirect from https to http is refused. diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 4f7f24b024..6c27aacbee 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -1230,17 +1230,24 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let t = sstep(start, start + pf(F_VIG_WIDTH), dist); if (t > 0.0) { let lum = clamp(lum2020(d), 0.0, 1.0); - if (amount < 0.0) { + let style = pu(F_VIG_STYLE); + if (style == 2u) { + // Paint: a flat overlay toward black (negative) or white (positive), as the CPU's + // finish.rs; in HDR it never pulls highlights down to SDR white + let w = abs(amount) * t; + if (amount < 0.0) { + d = d * (1.0 - w); + } else if (hdr) { + d = max(d, d * (1.0 - w) + vec3(w)); + } else { + d = d * (1.0 - w) + vec3(w); + } + } else if (amount < 0.0) { var f = 1.0 + amount * t; - let style = pu(F_VIG_STYLE); if (style == 1u) { f += (1.0 - f) * pf(F_VIG_HL) * sstep(0.4, 1.0, lum); } - if (style == 2u) { - d = d * (1.0 - (-amount) * t) + 0.0; - } else { - d = d * f; - } + d = d * f; } else if (hdr) { // lighten towards SDR white; never pull HDR highlights down to it d = d + max(vec3(1.0) - d, vec3(0.0)) * amount * t * 0.85; diff --git a/crates/gpu/tests/shutdown.rs b/crates/gpu/tests/shutdown.rs index 1fc0ce7bb2..2b61139e49 100644 --- a/crates/gpu/tests/shutdown.rs +++ b/crates/gpu/tests/shutdown.rs @@ -40,7 +40,8 @@ fn nothing_renders_on_the_gpu_once_the_process_is_ending() { }) }; if has_gpu { - while rendered.load(Ordering::SeqCst) == 0 && !refused.load(Ordering::SeqCst) { + let end = std::time::Instant::now() + Duration::from_secs(120); + while rendered.load(Ordering::SeqCst) == 0 && !refused.load(Ordering::SeqCst) && std::time::Instant::now() < end { std::thread::yield_now(); } assert!(rendered.load(Ordering::SeqCst) > 0, "the GPU renders before the shutdown ({:?})", lcc_gpu::last_fallback()); diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index c3a2ba0441..cd38cac712 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -133,6 +133,9 @@ impl Headless { lcc_engine::export::set_video_hooks(&mut items, &lcc_engine::export_video::VideoHooks { cancel, progress: Some(progress) }); row }); + // a batch goes on past a photo that fails (a missing original) and lists it in `files`; + // a single-photo export that fails is an error (upstream #4737) + let stop_on_error = total == 1; let mut hook = self.progress.take(); let mut cancelled = false; let files = run_batch( @@ -141,7 +144,7 @@ impl Headless { &Destination::on_disk(dir.to_string(), exact.map(str::to_string)), write, &|path| Path::new(path).exists(), - true, + stop_on_error, &mut |done, name| { cancelled = hook.as_mut().is_some_and(|h| !h(done, total, name)); !cancelled @@ -154,8 +157,9 @@ impl Headless { return Err("cancelled".into()); } lcc_engine::export::mark_exported(&mut self.session, &files); - // Single-photo exports also report path/width/height at the top level (back-compat). - let mut out = files.first().cloned().unwrap_or_else(|| json!({})); + // Single-photo exports also report path/width/height at the top level (back-compat); a + // per-file error is never promoted to the top level. + let mut out = files.first().filter(|file| file.get("error").is_none()).cloned().unwrap_or_else(|| json!({})); if let Some(photos) = after.run(&files, false) { out["applePhotos"] = photos; } @@ -396,6 +400,38 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Upstream #4737 (issue #4714): a missing original in a headless export is reported per file, and later photos still export. + #[test] + fn a_missing_original_does_not_stop_a_headless_batch_export() { + let base = std::env::temp_dir().join(format!("lc-mcp-missing-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (source, output) = (base.join("source"), base.join("output")); + std::fs::create_dir_all(&source).unwrap(); + + let mut h = Headless::demo(); + let mut ids = Vec::new(); + for (i, name) in ["missing.png", "before.png", "after.png"].into_iter().enumerate() { + let img = lcc_raster::Rgba8 { width: 8, height: 8, data: vec![[20 + i as u8, 3, 9, 255]; 64] }; + let png = lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&img), &lcc_codecs::EncodeMeta::default()).unwrap(); + let path = source.join(name); + std::fs::write(&path, &png).unwrap(); + let r = crate::call_tool(&mut h, "import", &json!({"paths": [path.to_string_lossy()]})); + assert!(!r.is_error, "{r:?}"); + ids.push(h.session.catalog.photos().find(|p| p.file_name == name).unwrap().id.0); + } + std::fs::remove_file(source.join("missing.png")).unwrap(); + + let r = h.call("app.export", json!({"ids": ids, "dir": output.to_string_lossy(), "longEdge": 32, "format": "png"})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 3, "{r}"); + assert!(files[0]["error"].as_str().is_some_and(|e| e.contains("missing.png")), "{r}"); + assert!(r.get("error").is_none(), "{r}"); + assert!(output.join("before.png").is_file(), "{r}"); + assert!(output.join("after.png").is_file(), "{r}"); + + let _ = std::fs::remove_dir_all(&base); + } + /// The export file-name template takes the Rename Photos tokens. #[test] fn export_naming_tokens() { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 90a28370a4..e1f3ee24f0 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -213,6 +213,29 @@ fn export_tool_forwards_its_advertised_options() { let _ = std::fs::remove_dir_all(&base); } +/// JPEG XL options reach the export command in both selection and explicit-photo calls. +#[test] +fn export_tool_forwards_jpeg_xl_options() { + for (lossless, effort, progressive) in [(true, "fast", true), (false, "normal", false)] { + for id in [None, Some(17)] { + let params = json!({"path": "out.jxl", "format": "jxl", "jxlLossless": lossless, "jxlEffort": effort, "jxlProgressive": progressive}); + let mut args = params.clone(); + if let Some(id) = id { + args["id"] = json!(id); + } + let mut b = Recorder(vec![]); + let result = call_tool(&mut b, "export", &args); + assert!(!result.is_error, "{result:?}"); + let mut calls = vec![]; + if let Some(id) = id { + calls.push(("engine.execute".to_string(), json!({"command": "library.select", "params": {"ids": [id], "active": id}}))); + } + calls.push(("engine.execute".to_string(), json!({"command": "app.export", "params": params}))); + assert_eq!(b.0, calls, "{args}"); + } + } +} + /// Issue #236: `app.export {addToPhotos, photosAlbum}` through the headless backend (the MCP /// `export` tool, `lcc-cli run`): the files written go to Photos and the result says how /// it went; where Photos isn't (not macOS), it is refused before anything is written. A fake @@ -843,3 +866,32 @@ fn a_relative_save_path_is_checked_as_the_absolute_path_that_is_written() { assert!(std::path::Path::new(path).is_absolute(), "{path}"); assert!(path.ends_with("x.png")); } + +/// Issue #4496: the Gemini API takes only string `enum`s in a tool's parameters and refuses the whole tool list +/// (400) for one integer enum, so no helper tool declares one. +#[test] +fn every_enum_in_the_helper_tools_is_a_list_of_strings() { + fn check(at: &str, v: &Value, bad: &mut Vec) { + match v { + Value::Object(m) => { + if let Some(e) = m.get("enum") + && !e.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(Value::is_string)) + { + bad.push(format!("{at}: {e}")); + } + for (k, x) in m { + check(&format!("{at}.{k}"), x, bad); + } + } + Value::Array(a) => a.iter().enumerate().for_each(|(i, x)| check(&format!("{at}[{i}]"), x, bad)), + _ => {} + } + } + let mut bad = Vec::new(); + for has_ui in [false, true] { + for t in crate::tools::helper_tools(has_ui) { + check(t["name"].as_str().unwrap_or("?"), &t["inputSchema"], &mut bad); + } + } + assert!(bad.is_empty(), "non-string enums: {bad:?}"); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 02270a81b7..ab97a9d351 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -267,7 +267,8 @@ pub fn helper_tools(has_ui: bool) -> Vec { "removeLocation": {"type": "boolean"}, "removePersonInfo": {"type": "boolean", "description": "Leave out keywords marked as a person (Lightroom's Remove Person Info)"}, "colorSpace": {"type": "string", "enum": ["srgb", "displayP3", "adobeRgb", "proPhoto", "rec2020"], "description": "Output colour space (default sRGB; AVIF is always sRGB; lossy JPEG XL writes adobeRgb/proPhoto as rec2020). adobeRgb = Adobe RGB (1998) compatible; the embedded ICC profile is generated from the published primaries"}, - "bitDepth": {"type": "integer", "enum": [8, 10, 16, 32], "description": "Bits per channel: PNG 8|16 (default 8), TIFF 8|16|32 (default 16; 32 = linear float with a linear profile), PSD 8|16 (default 16), AVIF 8|10, JPEG XL 8|16; JPEG/WebP are 8-bit"}, + // the values in words, not an `enum`: the Gemini API refuses a tool list with a non-string enum (upstream #4496) + "bitDepth": {"type": "integer", "description": "Bits per channel (8, 10, 16 or 32): PNG 8|16 (default 8), TIFF 8|16|32 (default 16; 32 = linear float with a linear profile), PSD 8|16 (default 16), AVIF 8|10, JPEG XL 8|16; JPEG/WebP are 8-bit"}, "hdr": {"type": "boolean", "description": "HDR output for photos edited in HDR (develop.hdr): JPEG as an ISO 21496-1 gain map JPEG, AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ, 32-bit TIFF with highlights above 1; other formats and SDR edits export as usual"}, "hdrTransfer": {"type": "string", "enum": ["pq", "hlg"], "description": "Transfer curve of HDR AVIF output (default pq): pq = SMPTE ST 2084, hlg = ITU-R BT.2100 hybrid log-gamma"}, "pluginDestination": {"type": "object", "description": "Send the exported files on to a plug-in export destination: {plugin, destination, args?} (see plugin.exportDestinations)"}, @@ -853,6 +854,9 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { "dontEnlarge", "ppi", "quality", + "jxlLossless", + "jxlEffort", + "jxlProgressive", "limitKb", "sharpen", "sharpenAmount", diff --git a/crates/meta/src/fits.rs b/crates/meta/src/fits.rs new file mode 100644 index 0000000000..9d4cfc512c --- /dev/null +++ b/crates/meta/src/fits.rs @@ -0,0 +1,518 @@ +#![deny(clippy::indexing_slicing, clippy::arithmetic_side_effects)] +//! FITS (Flexible Image Transport System, the FITS 4.0 standard of NASA / IAU) headers: the format of astrophotography +//! cameras and of the images astrophotography software exports (issue #1604). A FITS header is no Exif block, so the +//! cards that say when a picture was taken and with what are read here; `lcc-raw` (`vendor/fits.rs`) decodes the pixels +//! and finds the image's header through this module too. +//! +//! Sources: the FITS standard, read as a reference (the header cards, the order of the data, `BITPIX`, `PCOUNT`). The +//! `ROWORDER` card is not in the standard: it is a convention of astrophotography software (KStars reads it), read as +//! KStars' reader documents it. No decoder source was copied. +//! +//! - A header is 2880-byte blocks of 80-byte ASCII cards, ending with `END`. A file's first card is +//! `SIMPLE = T` (and it is a standard FITS file only when the value is `T`). +//! - A card is `KEYWORD = value / comment`: a logical (`T`, `F`), an integer, a real (a `D` exponent as the standard +//! writes it) or a string in single quotes (`''` inside it is a quote; trailing blanks are not part of it). +//! - A file is header units one after another, each a header and its data: the primary unit first, then extensions +//! (`XTENSION`: `IMAGE`, `BINTABLE`, …). An image's data is one cell for every point of its axes (`NAXIS1` is the +//! fastest-varying axis: columns), `BITPIX` bits each, in whole blocks. +//! - `DATE-OBS` is the capture time (`YYYY-MM-DD`, `YYYY-MM-DDThh:mm:ss`, with a fraction of a second; UTC unless it +//! states a zone; older files write a space where the standard has `T`), `EXPTIME` the exposure in seconds, +//! `INSTRUME` the instrument (for a camera, its model), `OBJECT` the target (the picture's title), `FOCALLEN` the +//! focal length in millimetres. `ROWORDER = 'BOTTOM-UP'` says the file keeps its bottom row first. +use crate::Metadata; +use lcc_geom::Orientation; + +/// Bytes in a header or data block, and in a card. +pub const BLOCK: usize = 2880; +pub const CARD: usize = 80; +/// Header blocks read looking for `END`. +const MAX_BLOCKS: usize = 4096; +/// Header units walked looking for an image. +pub const MAX_UNITS: usize = 256; + +/// Whether a file is FITS: its first card is `SIMPLE =` (the value is read with the header). +pub fn is_fits(bytes: &[u8]) -> bool { + bytes.starts_with(b"SIMPLE =") +} + +/// A header unit's keyword cards: each keyword with the text of its value. A keyword that appears twice is a +/// malformed header; the first one is kept, as every reader keeps it. +#[derive(Debug, Default)] +pub struct Cards<'a> { + entries: Vec<(&'a str, &'a str)>, +} + +impl<'a> Cards<'a> { + fn push(&mut self, card: &'a str) { + let Some((key, value)) = split_card(card) else { return }; + if !self.entries.iter().any(|(k, _)| *k == key) { + self.entries.push((key, value)); + } + } + + /// The text of a card's value, without its comment. + pub fn get(&self, key: &str) -> Option<&'a str> { + self.entries.iter().find(|(k, _)| *k == key).map(|(_, v)| *v) + } + + /// A logical value. + pub fn flag(&self, key: &str) -> Option { + match self.get(key)?.trim() { + "T" => Some(true), + "F" => Some(false), + _ => None, + } + } + + /// An integer value. + pub fn int(&self, key: &str) -> Option { + self.get(key)?.trim().parse().ok() + } + + /// A real value (a `D` exponent as the standard writes it), when finite. + pub fn real(&self, key: &str) -> Option { + let text = self.get(key)?.trim(); + (!text.is_empty()).then(|| text.replace(['D', 'd'], "E")).and_then(|t| t.parse().ok()).filter(|v: &f64| v.is_finite()) + } + + /// A string value without its quotes (`''` inside it is a quote), trailing blanks dropped. + pub fn text(&self, key: &str) -> Option { + let inner = self.get(key)?.trim_start().strip_prefix('\'')?; + let end = string_end(inner).unwrap_or(inner.len()); + Some(inner.get(..end)?.replace("''", "'").trim_end().to_string()) + } +} + +/// Keyword and value text of a card (`KEYWORD = value / comment`). `None` for `END`, `COMMENT`, `HISTORY`, blank and +/// malformed cards. +fn split_card(card: &str) -> Option<(&str, &str)> { + if !card.is_ascii() { + return None; + } + let key = card.get(..8)?.trim_end(); + let value = card.get(8..)?.strip_prefix("= ")?; + let named = !key.is_empty() && key.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'-' || b == b'_'); + (named && key != "END").then_some((key, value_text(value))) +} + +/// A card's value without its comment: a `/` ends it unless it is inside a string. +fn value_text(value: &str) -> &str { + match value.strip_prefix('\'').and_then(string_end) { + // the string's closing quote (one past the opening one) is part of the value + Some(end) => value.get(..end.checked_add(2).unwrap_or(value.len())).unwrap_or(value), + None => value.split('/').next().unwrap_or(value), + } +} + +/// Where a string that starts right after a `'` ends: the offset of the `'` that closes it (`''` inside it is a +/// quote). `None` when nothing closes it. +fn string_end(s: &str) -> Option { + let mut chars = s.char_indices(); + while let Some((at, c)) = chars.next() { + if c == '\'' { + match chars.clone().next() { + // `''` is a quote inside the string: both are passed over + Some((_, '\'')) => chars.next(), + _ => return Some(at), + }; + } + } + None +} + +/// Why the header of a FITS file's image could not be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Problem { + /// The file does not start with the `SIMPLE` card. + NotFits, + /// The file does not follow the standard (`SIMPLE = F`). + NotStandard, + /// A header ends before its `END` card. + NoEnd, + /// A header of more blocks than are read. + TooLong, + /// A data size that overflows, or is more than this build reads. + TooLarge, + /// A card is missing or malformed: what is wrong with it. + Card(&'static str), + /// No image among the header units walked. + NoImage, +} + +/// The cards of the header unit that starts at byte `at`, and where its data starts. +fn unit_header(bytes: &[u8], at: usize) -> Result<(Cards<'_>, usize), Problem> { + let mut cards = Cards::default(); + let mut pos = at; + for _ in 0..MAX_BLOCKS { + let block = bytes.get(pos..).and_then(|b| b.get(..BLOCK)).ok_or(Problem::NoEnd)?; + for raw in block.as_chunks::().0 { + // a card that is not text (a stray byte in a comment) is skipped; `END` is text + let Ok(card) = std::str::from_utf8(raw) else { continue }; + if card.get(..8).is_some_and(|k| k.trim_end() == "END") { + return Ok((cards, pos.checked_add(BLOCK).ok_or(Problem::TooLarge)?)); + } + cards.push(card); + } + pos = pos.checked_add(BLOCK).ok_or(Problem::TooLarge)?; + } + Err(Problem::TooLong) +} + +/// The bytes a header unit's data takes, in whole blocks: its data array (one cell for every point of its axes) and +/// its `PCOUNT` supplementary cells (a table's heap), `BITPIX` bits each. +fn unit_bytes(axes: &[usize], bitpix: i64, pcount: Option) -> Result { + let bits = match bitpix { + 8 | 16 | 32 | 64 | -32 | -64 => bitpix.unsigned_abs(), + _ => return Err(Problem::Card("BITPIX is not 8, 16, 32, 64, -32 or -64")), + }; + let mut array = 1u64; + for &axis in axes { + array = array.checked_mul(axis as u64).ok_or(Problem::TooLarge)?; + } + // a header with no axes has no data array + let array = if axes.is_empty() { 0 } else { array }; + let pcount = u64::try_from(pcount.unwrap_or(0)).map_err(|_| Problem::Card("PCOUNT is negative"))?; + let cells = array.checked_add(pcount).ok_or(Problem::TooLarge)?; + let block = u64::try_from(BLOCK).unwrap_or(2880); + let bytes = cells.checked_mul(bits.div_ceil(8)).ok_or(Problem::TooLarge)?; + let padded = bytes.checked_add(block.saturating_sub(1)).and_then(|n| n.checked_div(block)).and_then(|n| n.checked_mul(block)); + usize::try_from(padded.ok_or(Problem::TooLarge)?).map_err(|_| Problem::Card("the data is larger than this build reads")) +} + +/// An image's header unit. +#[derive(Debug)] +pub struct Image<'a> { + pub cards: Cards<'a>, + /// `BITPIX`: bits to a sample (negative for IEEE floats). + pub bitpix: i64, + /// The lengths of `NAXIS1`, `NAXIS2`, … (`NAXIS1` is the width). + pub axes: Vec, + /// Offset of the data. + pub data: usize, + /// A tile-compressed image (`ZIMAGE = T`): its data is a table of compressed tiles, not samples. + pub compressed: bool, +} + +/// The header unit of a file's image: the primary unit's, or when that has no data (`NAXIS` 0), the first `IMAGE` +/// extension's. A tile-compressed image (`ZIMAGE`) is found too, and said so. +pub fn image_header(bytes: &[u8]) -> Result, Problem> { + if !is_fits(bytes) { + return Err(Problem::NotFits); + } + let mut at = 0usize; + for index in 0..MAX_UNITS { + let (cards, data) = unit_header(bytes, at)?; + if index == 0 && cards.flag("SIMPLE") != Some(true) { + return Err(Problem::NotStandard); + } + let naxis = cards.int("NAXIS").ok_or(Problem::Card("the header has no NAXIS"))?; + let bitpix = cards.int("BITPIX").ok_or(Problem::Card("the header has no BITPIX"))?; + if !(0..=999).contains(&naxis) { + return Err(Problem::Card("NAXIS is not between 0 and 999")); + } + let mut axes: Vec = Vec::with_capacity(usize::try_from(naxis).unwrap_or(0)); + for i in 1..=naxis { + let axis = cards.int(&format!("NAXIS{i}")).ok_or(Problem::Card("an axis has no length"))?; + axes.push(usize::try_from(axis).map_err(|_| Problem::Card("an axis length is negative or too large"))?); + } + let compressed = cards.flag("ZIMAGE") == Some(true); + let image = index == 0 || cards.text("XTENSION").as_deref() == Some("IMAGE") || compressed; + if image && !axes.is_empty() { + return Ok(Image { cards, bitpix, axes, data, compressed }); + } + at = data.checked_add(unit_bytes(&axes, bitpix, cards.int("PCOUNT"))?).ok_or(Problem::TooLarge)?; + // a well-formed file may end here (a primary header without data and no extensions) + if at >= bytes.len() { + break; + } + } + Err(Problem::NoImage) +} + +/// `DATE-OBS` as the capture time: `YYYY-MM-DD`, `YYYY-MM-DDThh:mm:ss`, with a fraction of a second. With no time +/// zone of its own it is UTC (the standard's). Older files write a space where the standard has `T`. +fn capture_time(card: &str) -> Option { + let iso = match card.as_bytes().get(10) { + Some(&b' ') => format!("{}T{}", card.get(..10)?, card.get(11..)?), + _ => card.to_string(), + }; + let mut at = crate::DateTime::parse_iso(&iso)?; + if at.offset_minutes.is_none() { + at.offset_minutes = Some(0); + } + Some(at) +} + +/// What a FITS file's image header states as photo metadata: pixel size, capture time (`DATE-OBS`), exposure +/// (`EXPTIME`), camera model (`INSTRUME`), title (`OBJECT`), focal length (`FOCALLEN`) and, for a file that keeps its +/// bottom row first (`ROWORDER`), the turn that makes it upright. `None` for any other file and for a FITS file whose +/// image header cannot be read. +pub fn metadata(bytes: &[u8]) -> Option { + if !is_fits(bytes) { + return None; + } + let image = image_header(bytes).ok()?; + let cards = &image.cards; + // (a compressed image's axes count table rows and the bytes in them, not pixels) + let (width, height) = match (image.compressed, image.axes.as_slice()) { + (false, [w, h, ..]) => (Some(u32::try_from(*w).unwrap_or(u32::MAX)), Some(u32::try_from(*h).unwrap_or(u32::MAX))), + _ => (None, None), + }; + Some(Metadata { + width, + height, + capture_time: cards.text("DATE-OBS").as_deref().and_then(capture_time), + exposure_time: cards.real("EXPTIME").filter(|e| e.is_finite() && *e > 0.0), + model: cards.text("INSTRUME").filter(|s| !s.is_empty()), + title: cards.text("OBJECT").filter(|s| !s.is_empty()), + focal_length: cards.real("FOCALLEN").filter(|f| f.is_finite() && *f > 0.0), + orientation: cards.text("ROWORDER").filter(|o| o.eq_ignore_ascii_case("BOTTOM-UP")).map(|_| Orientation::FlipV), + ..Default::default() + }) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::arithmetic_side_effects)] + + use super::*; + + fn card(text: &str) -> String { + format!("{text:<80}") + } + + fn kw(name: &str, value: impl std::fmt::Display) -> String { + card(&format!("{name:<8}= {value:>20}")) + } + + fn text(name: &str, value: &str) -> String { + card(&format!("{name:<8}= '{value:<8}'")) + } + + /// A header unit and its data, in whole blocks. + fn unit(cards: &[String], data: &[u8]) -> Vec { + let mut out: Vec = cards.iter().flat_map(|c| c.as_bytes().iter().copied()).collect(); + out.extend_from_slice(b"END"); + out.resize(out.len().div_ceil(BLOCK) * BLOCK, b' '); + out.extend_from_slice(data); + out.resize(out.len().div_ceil(BLOCK) * BLOCK, 0); + out + } + + fn image(w: u32, h: u32) -> Vec { + vec![card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", 2), kw("NAXIS1", w), kw("NAXIS2", h)] + } + + fn fits(extra: &[String]) -> Vec { + let mut cards = image(4, 2); + cards.extend_from_slice(extra); + unit(&cards, &[0; 16]) + } + + #[test] + fn the_cards_fill_the_metadata() { + assert!(!is_fits(b"II*\0\0\x08\0\0")); + assert!(metadata(b"not a FITS file").is_none()); + let at = |h: u8, m: u8, s: u8, millis: u16| crate::DateTime { + year: 2026, + month: 11, + day: 28, + hour: h, + minute: m, + second: s, + millis, + offset_minutes: Some(0), + ..Default::default() + }; + let m = metadata(&fits(&[ + text("DATE-OBS", "2026-11-28T12:34:56.789"), + kw("EXPTIME", "120.5"), + text("INSTRUME", "ZWO ASI2600MC"), + text("OBJECT", "M 31 / Andromeda"), + kw("FOCALLEN", 530), + text("TELESCOP", "Askol 130/730"), + text("OBSERVER", "Jane Doe"), + kw("GAIN", 120), + card("COMMENT a stretched stack"), + card("HISTORY Siril 1.4"), + ])) + .unwrap(); + assert_eq!((m.width, m.height), (Some(4), Some(2))); + assert_eq!(m.capture_time, Some(at(12, 34, 56, 789))); + assert_eq!(m.exposure_time, Some(120.5)); + assert_eq!(m.model.as_deref(), Some("ZWO ASI2600MC")); + assert_eq!(m.title.as_deref(), Some("M 31 / Andromeda")); + assert_eq!(m.focal_length, Some(530.0)); + assert_eq!(m.orientation, None); + // cards that have no counterpart state nothing + assert!((m.make.is_none() && m.iso.is_none() && m.lens_model.is_none() && m.artist.is_none())); + + // the bare header states the size and nothing else + let m = metadata(&fits(&[])).unwrap(); + assert_eq!((m.width, m.height), (Some(4), Some(2))); + assert!(m.capture_time.is_none() && m.exposure_time.is_none() && m.model.is_none() && m.title.is_none() && m.focal_length.is_none()); + + // the capture time: the standard's forms, an older file's space, the date alone, a zone of its own + let time = |value: &str| metadata(&fits(&[text("DATE-OBS", value)])).unwrap().capture_time; + assert_eq!(time("2026-11-28T12:34:56"), Some(at(12, 34, 56, 0))); + assert_eq!(time("2026-11-28 12:34:56"), Some(at(12, 34, 56, 0))); + assert_eq!(time("2026-11-28"), Some(at(0, 0, 0, 0))); + let t = time("2026-11-28T12:34:56+02:00").unwrap(); + assert_eq!((t.hour, t.offset_minutes), (12, Some(120))); + for bad in ["yesterday", "2026-13-28", "2026-02-30", "2026-11-28T25:00:00", "20261128", "1666-02-30"] { + assert_eq!(time(bad), None, "{bad}"); + } + + // values that are not numbers, or not positive, are ignored + let m = + metadata(&fits(&[kw("EXPTIME", "NaN"), kw("FOCALLEN", -5), kw("EXPTIME", "2.5D1"), text("INSTRUME", " "), text("OBJECT", "")])) + .unwrap(); + // (the first `EXPTIME` is the one read: a NaN is not stated) + assert!(m.exposure_time.is_none() && m.focal_length.is_none() && m.model.is_none() && m.title.is_none()); + assert_eq!(metadata(&fits(&[kw("EXPTIME", "2.5D1")])).unwrap().exposure_time, Some(25.0)); + assert_eq!(metadata(&fits(&[kw("EXPTIME", "INFINITY")])).unwrap().exposure_time, None); + + // strings: a quote written twice, lower case kept, a comment after, blanks dropped + let m = metadata(&fits(&[text("OBJECT", "O''M 1 "), card("INSTRUME= 'ZWO Camera' / who took it")])).unwrap(); + assert_eq!(m.title.as_deref(), Some("O'M 1")); + assert_eq!(m.model.as_deref(), Some("ZWO Camera")); + + // row order + for (order, upright) in + [("BOTTOM-UP", Some(Orientation::FlipV)), ("bottom-up", Some(Orientation::FlipV)), ("TOP-DOWN", None), ("SIDEWAYS", None)] + { + assert_eq!(metadata(&fits(&[text("ROWORDER", order)])).unwrap().orientation, upright, "{order}"); + } + } + + #[test] + fn the_image_is_the_primary_or_the_first_image_extension() { + // where the data starts: after the header's whole blocks + let long = unit(&image(4, 2), &[0; 16]); + let i = image_header(&long).unwrap(); + assert_eq!((i.axes.clone(), i.bitpix, i.data, i.compressed), (vec![4, 2], 16, BLOCK, false)); + // a header of two blocks + let mut two = image(4, 2); + two.extend((0..40).map(|n| card(&format!("COMMENT filler number {n}")))); + assert_eq!(image_header(&unit(&two, &[0; 16])).unwrap().data, 2 * BLOCK); + + // an empty primary, a table with its heap, then the image + let empty = unit(&[card("SIMPLE = T"), kw("BITPIX", 8), kw("NAXIS", 0), kw("EXTEND", "T")], &[]); + let mut f = empty.clone(); + f.extend(unit( + &[ + text("XTENSION", "BINTABLE"), + kw("BITPIX", 8), + kw("NAXIS", 2), + kw("NAXIS1", 8), + kw("NAXIS2", 3), + kw("PCOUNT", 16), + kw("GCOUNT", 1), + kw("TFIELDS", 0), + ], + &[0x5a; 24 + 16], + )); + let mut picture = image(6, 5); + picture.insert(0, text("XTENSION", "IMAGE")); + picture.push(text("OBJECT", "M 31")); + f.extend(unit(&picture, &[0; 60])); + let i = image_header(&f).unwrap(); + assert_eq!((i.axes.clone(), i.data), (vec![6, 5], 4 * BLOCK)); + assert_eq!(metadata(&f).unwrap().title.as_deref(), Some("M 31")); + // the image straight after the primary header + let mut g = empty.clone(); + g.extend(unit(&picture, &[0; 60])); + assert_eq!(image_header(&g).unwrap().axes, vec![6, 5]); + // a table alone, or nothing after the primary: no image (a well-formed file either way) + let mut g = empty.clone(); + g.extend(unit(&[text("XTENSION", "BINTABLE"), kw("BITPIX", 8), kw("NAXIS", 2), kw("NAXIS1", 8), kw("NAXIS2", 3)], &[0; 24])); + assert_eq!(image_header(&g).err(), Some(Problem::NoImage)); + assert!(metadata(&g).is_none()); + assert_eq!(image_header(&empty).err(), Some(Problem::NoImage)); + // a tile-compressed image is found and said so: its axes are not pixels + let mut g = empty; + g.extend(unit( + &[ + text("XTENSION", "BINTABLE"), + kw("BITPIX", 8), + kw("NAXIS", 2), + kw("NAXIS1", 8), + kw("NAXIS2", 10), + kw("ZIMAGE", "T"), + text("ZCMPTYPE", "RICE_1"), + text("OBJECT", "M 31"), + ], + &[0; 80], + )); + let i = image_header(&g).unwrap(); + assert!(i.compressed); + let m = metadata(&g).unwrap(); + assert_eq!((m.width, m.height, m.title.as_deref()), (None, None, Some("M 31"))); + // more units without an image than are walked + let mut g = unit(&[card("SIMPLE = T"), kw("BITPIX", 8), kw("NAXIS", 0), kw("EXTEND", "T")], &[]); + let table = unit(&[text("XTENSION", "BINTABLE"), kw("BITPIX", 8), kw("NAXIS", 0)], &[]); + for _ in 0..MAX_UNITS { + g.extend_from_slice(&table); + } + assert_eq!(image_header(&g).err(), Some(Problem::NoImage)); + } + + #[test] + fn headers_that_cannot_be_read_say_why() { + assert_eq!(image_header(b"SIMPLE = T").err(), Some(Problem::NoEnd)); + assert_eq!( + image_header(&unit(&[card("SIMPLE = F"), kw("BITPIX", 8), kw("NAXIS", 0)], &[])).err(), + Some(Problem::NotStandard) + ); + assert_eq!(image_header(b"Not a FITS file at all").err(), Some(Problem::NotFits)); + let base = image(2, 2); + let card_problem = |cards: &[String]| match image_header(&unit(cards, &[0; 8])) { + Err(Problem::Card(what)) => what, + other => panic!("{other:?}"), + }; + assert_eq!( + card_problem(&[card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS1", 2), kw("NAXIS2", 2)]), + "the header has no NAXIS" + ); + assert_eq!( + card_problem(&[card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", 3), kw("NAXIS1", 2), kw("NAXIS2", 2)]), + "an axis has no length" + ); + let mut bad = base.clone(); + bad[2] = card("NAXIS = 2.0"); + assert_eq!(card_problem(&bad), "the header has no NAXIS"); + let mut bad = base.clone(); + bad[4] = kw("NAXIS2", -2); + assert_eq!(card_problem(&bad), "an axis length is negative or too large"); + // the data of a unit that is passed over must be measured to find the next one + let skipped = |cards: &[String]| match image_header(&unit(cards, &[])) { + Err(Problem::Card(what)) => what, + other => panic!("{other:?}"), + }; + assert_eq!( + skipped(&[card("SIMPLE = T"), kw("BITPIX", 12), kw("NAXIS", 0), kw("EXTEND", "T")]), + "BITPIX is not 8, 16, 32, 64, -32 or -64" + ); + let mut heap = unit(&[card("SIMPLE = T"), kw("BITPIX", 8), kw("NAXIS", 0), kw("EXTEND", "T")], &[]); + heap.extend(unit(&[text("XTENSION", "BINTABLE"), kw("BITPIX", 8), kw("NAXIS", 1), kw("NAXIS1", 2), kw("PCOUNT", -1)], &[])); + assert_eq!(image_header(&heap).err(), Some(Problem::Card("PCOUNT is negative"))); + // huge sizes are a limit, never a wrap + let mut heap = unit(&[card("SIMPLE = T"), kw("BITPIX", 8), kw("NAXIS", 0), kw("EXTEND", "T")], &[]); + heap.extend(unit(&[text("XTENSION", "BINTABLE"), kw("BITPIX", 32), kw("NAXIS", 2), kw("NAXIS1", u32::MAX), kw("NAXIS2", u32::MAX)], &[])); + assert_eq!(image_header(&heap).err(), Some(Problem::TooLarge)); + // a header that never ends, short and long + let comments = card("COMMENT no end in sight"); + let endless = [card("SIMPLE = T"), comments.clone(), comments.clone()].concat(); + assert_eq!(image_header(endless.as_bytes()).err(), Some(Problem::NoEnd)); + let endless = [card("SIMPLE = T"), comments.repeat(BLOCK / CARD * MAX_BLOCKS)].concat(); + assert_eq!(image_header(endless.as_bytes()).err(), Some(Problem::TooLong)); + // every truncation of a good file is an error, never a panic; the bytes before `END` are not enough + let good = fits(&[]); + for cut in 0..good.len() { + let _ = image_header(&good[..cut]); + let _ = metadata(&good[..cut]); + } + assert!(image_header(&good[..BLOCK - CARD]).is_err()); + assert!(image_header(&good[..BLOCK]).is_ok(), "the header alone places the data"); + } +} diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 944d7686c3..dea4141dae 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -8,6 +8,8 @@ //! - [`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, HEIF/HEIC/AVIF). +//! - [`fits`] — FITS headers (astrophotography cameras and software): the cards that state the capture time, +//! exposure, camera and target, and where the image's data is. //! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks). #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -16,6 +18,7 @@ mod container; pub mod cr3; mod datetime; mod exif; +pub mod fits; pub mod focus; mod focus_canon; mod focus_read; @@ -470,7 +473,11 @@ pub fn exposure_display_of(t: f64) -> Option { /// Read everything we understand from a whole file (JPEG, PNG, WebP, TIFF-based incl. DNG/raw). /// Precedence: EXIF, then IPTC fills gaps, then XMP overrides user fields and fills the rest. +/// A FITS file (astrophotography) has no Exif: its header cards are read directly ([`fits::metadata`]). pub fn extract(bytes: &[u8]) -> Metadata { + if let Some(m) = fits::metadata(bytes) { + return m; + } let e = embedded(bytes); let exif = with_cr3_focus(bytes, e.exif.as_deref().map(read_exif).unwrap_or_default()); let xmp = e.xmp.as_deref().and_then(|xmp| parse_xmp(xmp).ok()); @@ -480,6 +487,9 @@ pub fn extract(bytes: &[u8]) -> Metadata { /// Read metadata while reporting malformed PSD/PSB containers, embedded EXIF, or embedded XMP instead of treating /// them as empty. Other container formats retain [`extract`]'s best-effort behavior. pub fn try_extract(bytes: &[u8]) -> Result { + if fits::is_fits(bytes) { + return Ok(fits::metadata(bytes).unwrap_or_default()); + } let e = container::try_embedded(bytes)?; let is_psd = bytes.starts_with(b"8BPS"); let exif = match e.exif.as_deref() { diff --git a/crates/opendocs/Cargo.toml b/crates/opendocs/Cargo.toml new file mode 100644 index 0000000000..542a9fa750 --- /dev/null +++ b/crates/opendocs/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "lcc-opendocs" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Files macOS hands the app (L0): photos opened from Finder, the Dock or another app's Open With. One of the crates allowed `unsafe` (adds one Objective-C method); does nothing elsewhere." + +# Opts out of the workspace lints only to keep `unsafe_code = "deny"` overridable for the single +# `macos` module below, as in crates/firstclick; every other crate root has `#![forbid(unsafe_code)]`. +# See AGENTS.md. +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +dbg_macro = "warn" +todo = "warn" + +[dependencies] +log = { workspace = true } + +[target.'cfg(target_os = "macos")'.dependencies] +# All already in the tree through winit and muda: no new crate, only features. +block2 = "0.6" +objc2 = { workspace = true } +objc2-app-kit = { workspace = true } +objc2-foundation = { workspace = true, features = ["block2", "NSEnumerator", "NSNotification", "NSOperation", "NSString", "NSURL"] } diff --git a/crates/opendocs/src/lib.rs b/crates/opendocs/src/lib.rs new file mode 100644 index 0000000000..2fc7a6b391 --- /dev/null +++ b/crates/opendocs/src/lib.rs @@ -0,0 +1,198 @@ +//! Files the operating system asks the app to open: on macOS, a photo opened from Finder (Open +//! With, a drop on the Dock icon), from another app (Photo Mechanic's "Open with", Files) or with +//! `open -a photo.arw`. +//! +//! macOS doesn't pass these on the command line: AppKit hands them to the application delegate's +//! `application:openURLs:`, and when the delegate has no such method it asks `NSDocumentController`, +//! which fails with " cannot open files in the … format" because the app isn't an +//! `NSDocument` app. winit 0.30's delegate doesn't implement the method, so [`install`] adds it to +//! the delegate's class when the app is about to finish launching: after winit set the delegate and +//! before AppKit delivers the files the app was launched with. The handler queues the paths and +//! calls the waker ([`set_waker`]); the app collects them with [`take`]. +//! +//! Adapted from upstream #1204 (LR-IMP-DRAGDROP, issue #506), which followed VectorCraft's +//! `open_documents.rs`; Apple's AppKit (`application(_:open:)`) and Objective-C runtime +//! (`class_addMethod`) documentation. +//! +//! Adding a method to another crate's Objective-C class has no safe API: this is one of the crates +//! allowed `unsafe` (AGENTS.md), here inside `macos`. Its API +//! is safe, and elsewhere [`install`] does nothing and [`take`] stays empty. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::sync::{Mutex, OnceLock, PoisonError}; + +/// Paths that arrived and haven't been taken yet. +static PENDING: Mutex> = Mutex::new(Vec::new()); +/// Called when paths arrive (unset until the window exists; the app takes them on its first frame). +static WAKER: OnceLock> = OnceLock::new(); + +/// Receive the files the operating system asks the app to open from now on. Call once, before the +/// event loop runs. Does nothing except on macOS, where such files come as arguments elsewhere. +pub fn install() { + #[cfg(target_os = "macos")] + macos::install(); +} + +/// Call `wake` whenever files arrive, e.g. to repaint the window that takes them. Only the first +/// waker set is kept. +pub fn set_waker(wake: impl Fn() + Send + Sync + 'static) { + let _ = WAKER.set(Box::new(wake)); +} + +/// The paths that arrived since the last call, in order. +pub fn take() -> Vec { + std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)) +} + +/// Queue `paths` and wake the app (called by the macOS handler; elsewhere only by the tests). +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +fn arrived(paths: impl IntoIterator) { + let len = { + let mut pending = PENDING.lock().unwrap_or_else(PoisonError::into_inner); + pending.extend(paths); + pending.len() + }; + if len > 0 + && let Some(wake) = WAKER.get() + { + wake(); + } +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod macos { + use std::ptr::NonNull; + + use block2::RcBlock; + use objc2::MainThreadMarker; + use objc2::runtime::{AnyClass, AnyObject, Imp, Sel}; + use objc2::sel; + use objc2_app_kit::{NSApplication, NSApplicationWillFinishLaunchingNotification}; + use objc2_foundation::{NSArray, NSNotification, NSNotificationCenter, NSURL}; + + /// The handler's signature, as the Objective-C runtime calls it. + type OpenUrls = extern "C-unwind" fn(&AnyObject, Sel, &AnyObject, &NSArray); + + pub fn install() { + let block = RcBlock::new(|_: NonNull| add_to_delegate()); + // SAFETY: the name is AppKit's notification constant; no object or queue filter, so the + // block runs on the posting thread (AppKit posts it on the main thread). The notification + // center keeps the registration (and the block) for the life of the app; the returned + // observer token is only needed to unregister, which we never do. + unsafe { + NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock( + Some(NSApplicationWillFinishLaunchingNotification), + None, + None, + &block, + ); + } + } + + /// `application:openURLs:` on the application delegate's class (winit's). + fn add_to_delegate() { + let Some(mtm) = MainThreadMarker::new() else { return }; + let Some(delegate) = NSApplication::sharedApplication(mtm).delegate() else { + log::warn!("no application delegate: photos opened from Finder or other apps won't arrive"); + return; + }; + if !add_open_urls(AsRef::::as_ref(&*delegate).class()) { + log::warn!("the application delegate already handles open-document events"); + } + } + + /// Add [`open_urls`] to `class` as `application:openURLs:`. False when the class already has + /// that method (it is then left as it is). + pub(crate) fn add_open_urls(class: &AnyClass) -> bool { + let handler: OpenUrls = open_urls; + // SAFETY: `Imp` is the untyped form of a method implementation; the Objective-C runtime + // calls it with the arguments the type encoding declares, which match `open_urls`: no + // return value (`v`), the receiver (`@`), the selector (`:`), the application (`@`) and the + // URL array (`@`). `class_addMethod` copies the encoding string and never replaces an + // existing method; the class is a registered class, alive for the life of the process. + let added = unsafe { + let imp = std::mem::transmute::(handler); + objc2::ffi::class_addMethod(std::ptr::from_ref(class).cast_mut(), sel!(application:openURLs:), imp, c"v@:@@".as_ptr()) + }; + added.as_bool() + } + + /// Queue the files among `urls`. Never panics: it runs inside AppKit. + extern "C-unwind" fn open_urls(_delegate: &AnyObject, _cmd: Sel, _app: &AnyObject, urls: &NSArray) { + // Only file URLs: macOS 27 turns an https URL's path into a file path too. + super::arrived(urls.iter().filter(|u| u.isFileURL()).filter_map(|u| u.to_file_path()).map(|p| p.to_string_lossy().into_owned())); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + + /// The queue is global: tests that fill it take turns. + static QUEUE: Mutex<()> = Mutex::new(()); + static WOKEN: AtomicUsize = AtomicUsize::new(0); + + fn turn() -> std::sync::MutexGuard<'static, ()> { + let guard = QUEUE.lock().unwrap_or_else(PoisonError::into_inner); + let _ = take(); + guard + } + + #[test] + fn files_wait_until_taken_and_wake_the_app() { + let _turn = turn(); + set_waker(|| { + WOKEN.fetch_add(1, Ordering::SeqCst); + }); + let before = WOKEN.load(Ordering::SeqCst); + arrived(["/tmp/a.arw".to_string(), "/tmp/b c.jpg".to_string()]); + assert_eq!(WOKEN.load(Ordering::SeqCst), before + 1); + arrived(["/tmp/d.heic".to_string()]); + assert_eq!(take(), ["/tmp/a.arw", "/tmp/b c.jpg", "/tmp/d.heic"]); + assert!(take().is_empty()); + // nothing arrived: nothing to wake the app for + let before = WOKEN.load(Ordering::SeqCst); + arrived(Vec::new()); + assert_eq!(WOKEN.load(Ordering::SeqCst), before); + } + + #[cfg(not(target_os = "macos"))] + #[test] + fn install_elsewhere_queues_nothing() { + let _turn = turn(); + install(); + assert!(take().is_empty()); + } + + /// The method `install` adds, called the way AppKit calls it: only file URLs are queued, and a + /// class that already has the method keeps its own. + #[cfg(target_os = "macos")] + #[test] + #[allow(unsafe_code)] + fn an_open_urls_message_queues_the_files() { + use objc2::rc::Retained; + use objc2::runtime::{AnyObject, ClassBuilder, NSObject}; + use objc2::{ClassType, msg_send, sel}; + use objc2_foundation::{NSArray, NSString, NSURL}; + + let _turn = turn(); + let class = ClassBuilder::new(c"LccOpenDocsTestDelegate", NSObject::class()).unwrap().register(); + assert!(!class.responds_to(sel!(application:openURLs:))); + assert!(macos::add_open_urls(class)); + assert!(!macos::add_open_urls(class), "a second add leaves the method alone"); + + let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.jpg")).unwrap(); + let urls = + NSArray::from_retained_slice(&[NSURL::from_file_path("/tmp/a b.arw").unwrap(), web, NSURL::from_file_path("/tmp/c.heic").unwrap()]); + // SAFETY: `class` is an NSObject subclass (`new` returns a retained instance), and it now + // has `application:openURLs:` with the signature the message is sent with. + let delegate: Retained = unsafe { msg_send![class, new] }; + let app = NSObject::new(); + let () = unsafe { msg_send![&*delegate, application: &*app, openURLs: &*urls] }; + assert_eq!(take(), ["/tmp/a b.arw", "/tmp/c.heic"]); + } +} diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index d5e07b7d49..2212c77c9a 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -1094,16 +1094,25 @@ pub(crate) fn finish_with( let t = smooth(v.start, v.start + v.width, dist); if t > 0.0 { let lum = luminance_2020(d).clamp(0.0, 1.0); - if v.amount < 0.0 { + if v.style == VignetteStyle::PaintOverlay { + // Paint is a flat overlay toward black (negative) or white (positive); Color and + // Highlight Priority stay a multiply or a lift, so the style tabs differ once Amount + // leaves 0. Adapted from upstream #1261. (finish.wgsl does the same.) + let w = v.amount.abs() * t; + if v.amount < 0.0 { + d = d.map(|c| c * (1.0 - w)); + } else if hdr { + // towards SDR white; never pull HDR highlights down to it + d = d.map(|c| c.max(c * (1.0 - w) + w)); + } else { + d = d.map(|c| c * (1.0 - w) + w); + } + } else if v.amount < 0.0 { let mut f = 1.0 + v.amount * t; if v.style == VignetteStyle::HighlightPriority { f += (1.0 - f) * v.highlights * smooth(0.4, 1.0, lum); } - if v.style == VignetteStyle::PaintOverlay { - d = d.map(|c| c * (1.0 - (-v.amount) * t) + 0.0); - } else { - d = d.map(|c| c * f); - } + d = d.map(|c| c * f); } else if hdr { // lighten towards SDR white; never pull HDR highlights down to it d = d.map(|c| c + (1.0 - c).max(0.0) * v.amount * t * 0.85); diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index 822dbe88f4..f9bf7b47b3 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -135,6 +135,23 @@ fn resolution_independence_of_local_contrast() { assert!(err < 9.0, "mean abs error {err}"); } +#[test] +fn paint_overlay_vignette_lifts_a_corner_toward_white() { + use lcc_develop::VignetteStyle; + let src = Rgb32f::filled(48, 48, [0.18, 0.18, 0.18]); + let mut paint = DevelopSettings::default(); + paint.vignette.amount = 100.0; + paint.vignette.midpoint = 0.0; + paint.vignette.feather = 10.0; + paint.vignette.style = VignetteStyle::PaintOverlay; + let mut color = paint.clone(); + color.vignette.style = VignetteStyle::ColorPriority; + let paint_img = render(&src, &SourceInfo::default(), &paint, &RenderRequest::fit(48, 48)).image; + let color_img = render(&src, &SourceInfo::default(), &color, &RenderRequest::fit(48, 48)).image; + let corner = |img: &lcc_raster::Rgba8| img.data[0][0]; + assert!(corner(&paint_img) > corner(&color_img) + 8, "paint {} color {}", corner(&paint_img), corner(&color_img)); +} + #[test] fn crop_and_straighten_output_size() { let mut s = DevelopSettings::default(); diff --git a/crates/preview/src/tests.rs b/crates/preview/src/tests.rs index d6d6a42f98..2c4d59d131 100644 --- a/crates/preview/src/tests.rs +++ b/crates/preview/src/tests.rs @@ -218,17 +218,13 @@ fn pool_priorities_dedupe_and_drop() { 1000, Box::new(move || { let (m, cv) = &*g; - let mut open = m.lock().unwrap(); - while !*open { - open = cv.wait(open).unwrap(); - } + let (_open, waited) = cv.wait_timeout_while(m.lock().unwrap(), std::time::Duration::from_secs(60), |open| !*open).unwrap(); + assert!(!waited.timed_out(), "the test never opened the gate"); 999 }), ); // wait until the worker took the gate job - while p.queued() > 0 { - std::thread::yield_now(); - } + assert!(eventually(30, || p.queued() == 0), "the worker never took the gate job"); p.submit(1, 1, 5, Box::new(|| 1)); // off-screen thumb p.submit(2, 1, 10, Box::new(|| 2)); // visible thumb p.submit(3, 1, 100, Box::new(|| 3)); // loupe @@ -243,13 +239,11 @@ fn pool_priorities_dedupe_and_drop() { cv.notify_all(); } let mut order = Vec::new(); - while order.len() < 4 { - if let Some(d) = p.try_recv() { - order.push((d.slot, d.key, d.result)); - } else { - std::thread::yield_now(); - } - } + let all_done = eventually(30, || { + order.extend(std::iter::from_fn(|| p.try_recv()).map(|d| (d.slot, d.key, d.result))); + order.len() >= 4 + }); + assert!(all_done, "four jobs done: {order:?}"); assert_eq!(order, vec![(999, 0, 999), (3, 1, 3), (2, 2, 22), (1, 1, 1)]); } @@ -279,7 +273,7 @@ fn pool_with_a_running_job() -> (JobPool, std::sync::mpsc::Sender<()>) { let _ = released.recv_timeout(std::time::Duration::from_secs(60)); }), ); - has_started.recv().unwrap(); + has_started.recv_timeout(std::time::Duration::from_secs(30)).expect("the job starts"); (p, release) } @@ -301,7 +295,7 @@ fn pool_drop_waits_for_running_job() { f.store(true, Ordering::SeqCst); }), ); - has_started.recv().unwrap(); + has_started.recv_timeout(std::time::Duration::from_secs(30)).expect("the job starts"); let q = queued_ran.clone(); p.submit(2, 0, 1, Box::new(move || q.store(true, Ordering::SeqCst))); drop(p); @@ -347,9 +341,7 @@ fn pool_stops_after_a_job_panicked_and_when_dropped_by_its_own_job() { // a worker that unwound is not waited for let mut p: JobPool = JobPool::new(1); p.submit(1, 0, 1, Box::new(|| panic!("a job panics (expected in this test)"))); - while p.live_workers() > 0 { - std::thread::yield_now(); - } + assert!(eventually(30, || p.live_workers() == 0), "the worker that panicked is still counted"); assert!(p.shutdown(std::time::Duration::from_secs(30))); // the last owner of a pool is one of its jobs: the worker must not wait for (or join) itself @@ -785,7 +777,7 @@ fn a_slot_runs_one_job_at_a_time() { }) }; p.submit(1, 1, 9, job(1, Some(released))); - assert_eq!(has_started.recv().unwrap(), 1); + assert_eq!(has_started.recv_timeout(std::time::Duration::from_secs(30)).expect("slot 1's first job starts"), 1); // two newer requests for the busy slot: the second replaces the first, neither starts p.submit(1, 2, 9, job(2, None)); p.submit(1, 3, 9, job(3, None)); diff --git a/crates/raw/src/demosaic/mod.rs b/crates/raw/src/demosaic/mod.rs index ee1b00d80d..423e6e66ab 100644 --- a/crates/raw/src/demosaic/mod.rs +++ b/crates/raw/src/demosaic/mod.rs @@ -16,6 +16,8 @@ //! - [`Method::Ppg`] → `xtrans::directional`: our own edge-weighted colour-difference interpolation (faster). //! - [`Method::Bilinear`] → bilinear. //! +//! [`remosaic_rggb`] goes the other way, for callers that need Bayer geometry from a sensor that has none. +//! //! Every method reproduces a constant-colour mosaic exactly. mod ahd; @@ -150,6 +152,40 @@ pub fn demosaic_with(n: &Normalized, method: Method, opts: Options) -> Rgb32f { } } +/// Adapted from upstream #1828; the fork's quality X-Trans path (`xtrans_ri`) is not used here. +/// A non-Bayer mosaic (Fujifilm X-Trans, …) rebuilt as an RGGB mosaic of the same size, so that tools +/// written around Bayer geometry can read a sensor they were not written for: the AI denoiser, whose +/// model contract is four RGGB planes. The mosaic is interpolated as `xtrans::directional` ([`Method::Ppg`]) would and one channel is +/// kept per site, the one RGGB wants there, without building the full RGB picture in between. +/// +/// Where the sensor already carries that colour at that site the interpolation returns the sample +/// itself, so those sites keep their original value and their original noise, while the rest are +/// interpolated and so already a little smoother. Anything reading the result sees noise that varies +/// from site to site, and the interpolation's own errors: this is an approximation of the sensor, not +/// the sensor. +/// +/// `None` when the mosaic is not one this can rebuild: already demosaiced data (`cpp != 1`), no CFA, a +/// CFA that is already Bayer (read that one as it is), a pattern whose size does not match its colours +/// or holding a colour that is not red, green or blue (RGBE, CYGM) or missing one of the three, or a +/// size that does not match the samples. +pub fn remosaic_rggb(n: &Normalized) -> Option { + let cfa = n.cfa.as_ref()?; + if n.cpp != 1 || cfa.is_bayer() { + return None; + } + if cfa.width == 0 || cfa.height == 0 || cfa.width.checked_mul(cfa.height) != Some(cfa.pattern.len()) { + return None; + } + if !(0..=2).all(|c| cfa.pattern.contains(&c)) || cfa.pattern.iter().any(|&c| c > 2) { + return None; + } + if n.width == 0 || n.height == 0 || n.width.checked_mul(n.height) != Some(n.data.len()) { + return None; + } + let data = xtrans::rggb(&Mosaic { w: n.width, h: n.height, data: &n.data, cfa }); + Some(Normalized { width: n.width, height: n.height, cpp: 1, data, cfa: Some(Cfa::bayer_static("RGGB")) }) +} + /// Build a mosaic from an RGB image by sampling each pixel's CFA colour (for tests and synthetic data). pub fn mosaic_from_rgb(img: &Rgb32f, cfa: &Cfa) -> Normalized { let data = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.get(x, y)[cfa.color_at(x, y) as usize]).collect(); @@ -179,6 +215,13 @@ pub fn psnr(a: &Rgb32f, b: &Rgb32f, border: usize) -> f64 { mod tests { use super::*; + fn smooth_scene(w: usize, h: usize) -> Rgb32f { + Rgb32f::from_fn(w, h, |x, y| { + let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32); + [0.2 + 0.6 * fx * fy, 0.3 + 0.4 * (fx * 3.0).sin().abs() * 0.5 + 0.2 * fy, 0.1 + 0.5 * (1.0 - fx) * (0.5 + 0.5 * (fy * 5.0).cos())] + }) + } + /// A photo-like scene: sharp luminance structure (disc, stripes, diagonal edge, fine texture) modulating a /// smoothly varying colour — edges are mostly luminance edges, as in natural images. fn edgy_scene(w: usize, h: usize) -> Rgb32f { @@ -384,4 +427,172 @@ mod tests { assert_eq!(reflect(3, 1), 0); assert_eq!(reflect(-7, 2), 1); } + + /// The single-pass re-mosaic must give exactly what demosaicing and then keeping each site's RGGB + /// colour gives: every phase of the pattern, the borders, and samples with no structure to hide behind. + #[test] + fn remosaic_matches_the_demosaic_sampled_as_rggb() { + let mut seed = 2024u32; + for (dx, dy) in [(0, 0), (1, 2), (5, 3)] { + let cfa = Cfa::xtrans().shifted(dx, dy); + let (w, h) = (37, 29); + let data: Vec = (0..w * h) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }) + .collect(); + let n = Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; + let want = mosaic_from_rgb(&demosaic(&n, Method::Ppg), &Cfa::bayer("RGGB").unwrap()); + let got = remosaic_rggb(&n).unwrap(); + assert_eq!((got.width, got.height, got.cpp), (w, h, 1)); + assert!(got.data.iter().zip(&want.data).all(|(a, b)| a.to_bits() == b.to_bits()), "phase ({dx}, {dy})"); + } + } + + #[test] + fn remosaic_keeps_a_constant_colour_exactly() { + let colour = [0.3f32, 0.55, 0.8]; + let n = mosaic_from_rgb(&Rgb32f::filled(19, 14, colour), &Cfa::xtrans()); + let r = remosaic_rggb(&n).unwrap(); + let cfa = r.cfa.clone().unwrap(); + assert_eq!(cfa.name(), "RGGB"); + for y in 0..r.height { + for x in 0..r.width { + let want = colour[cfa.color_at(x, y) as usize]; + assert!((r.data[y * r.width + x] - want).abs() < 1e-5, "({x}, {y})"); + } + } + } + + /// The sites where X-Trans already carries the colour RGGB wants keep their own sample, untouched. + #[test] + fn remosaic_keeps_the_samples_the_two_patterns_share() { + let img = edgy_scene(40, 32); + let xt = Cfa::xtrans(); + let n = mosaic_from_rgb(&img, &xt); + let r = remosaic_rggb(&n).unwrap(); + let rggb = r.cfa.clone().unwrap(); + let mut shared = 0; + for y in 0..32 { + for x in 0..40 { + let c = rggb.color_at(x, y); + if xt.color_at(x, y) != c { + continue; + } + shared += 1; + assert_eq!(r.data[y * 40 + x].to_bits(), img.get(x, y)[c as usize].to_bits(), "({x}, {y})"); + } + } + // about two sites in five: 20/36 greens against RGGB's half, 8/36 reds and blues against its quarters + assert!(shared > 40 * 32 / 4, "only {shared} shared sites"); + } + + /// Reading the re-mosaic back as Bayer costs a little against demosaicing the X-Trans mosaic directly, + /// but must stay close: it is the picture the denoiser's Bayer contract starts from. + #[test] + fn remosaic_round_trip_stays_close_to_the_direct_demosaic() { + for img in [smooth_scene(96, 80), edgy_scene(96, 80)] { + let n = mosaic_from_rgb(&img, &Cfa::xtrans()); + let direct = psnr(&img, &demosaic(&n, Method::Ppg), 6); // the interpolator the re-mosaic uses + let through = psnr(&img, &demosaic(&remosaic_rggb(&n).unwrap(), Method::Ahd), 6); + eprintln!("direct {direct:.1} dB, through RGGB {through:.1} dB"); + assert!(through > 24.0, "through RGGB {through:.1} dB"); + assert!(through > direct - 2.0, "through RGGB {through:.1} dB against direct {direct:.1} dB"); + } + } + + #[test] + fn remosaic_refuses_what_it_cannot_rebuild() { + let img = smooth_scene(12, 10); + let xtrans = || mosaic_from_rgb(&img, &Cfa::xtrans()); + // already Bayer: the caller reads that mosaic as it is + assert!(remosaic_rggb(&mosaic_from_rgb(&img, &Cfa::bayer("GRBG").unwrap())).is_none()); + // already demosaiced + let mut three = xtrans(); + three.cpp = 3; + assert!(remosaic_rggb(&three).is_none()); + // no colour filter array at all (a monochrome sensor) + let mut mono = xtrans(); + mono.cfa = None; + assert!(remosaic_rggb(&mono).is_none()); + // a fourth colour (RGBE), a pattern missing blue, and patterns whose size does not match their colours + // (a zero side would divide by zero when looking a colour up, a short pattern would read past its end) + for (width, height, pattern) in + [(2, 2, vec![0, 1, 1, 3]), (2, 2, vec![0, 1, 1, 1]), (0, 2, vec![0, 1, 2]), (2, 2, vec![0, 1, 2]), (6, 6, vec![])] + { + let mut odd = xtrans(); + odd.cfa = Some(Cfa { width, height, pattern }); + assert!(remosaic_rggb(&odd).is_none(), "{width}×{height}"); + } + // samples that do not match the size + let mut short = xtrans(); + short.data.pop(); + assert!(remosaic_rggb(&short).is_none()); + let mut empty = xtrans(); + (empty.width, empty.height, empty.data) = (0, 0, Vec::new()); + assert!(remosaic_rggb(&empty).is_none()); + } + + /// The re-mosaic on a real non-Bayer file, which no synthetic pattern stands in for (the active-area crop + /// moves the pattern's phase, and sensor noise is what the denoiser is given the result for): + /// `LC_XTRANS_RAW= cargo test --release -p lcc-raw --lib -- --ignored --nocapture remosaic_a_real_file` + #[test] + #[ignore = "needs LC_XTRANS_RAW pointing at a real non-Bayer raw file"] + fn remosaic_a_real_file() { + let Some(path) = std::env::var_os("LC_XTRANS_RAW") else { + lcc_testkit::skip!(Input, "set LC_XTRANS_RAW="); + return; + }; + let raw = crate::decode(&std::fs::read(&path).unwrap()).unwrap(); + let n = raw.normalized().unwrap(); + let cfa = n.cfa.clone().unwrap(); + assert!(!cfa.is_bayer(), "not a non-Bayer file"); + let t = std::time::Instant::now(); + let r = remosaic_rggb(&n).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3; + assert_eq!((r.width, r.height), (n.width, n.height)); + assert!(r.data.iter().all(|v| v.is_finite())); + let rggb = r.cfa.clone().unwrap(); + let (mut shared, mut kept) = (0usize, 0usize); + for y in 0..n.height { + for x in 0..n.width { + if cfa.color_at(x, y) == rggb.color_at(x, y) { + shared += 1; + kept += usize::from(r.data[y * n.width + x].to_bits() == n.data[y * n.width + x].to_bits()); + } + } + } + let t = std::time::Instant::now(); + let direct = demosaic(&n, Method::Ahd); + let direct_ms = t.elapsed().as_secs_f64() * 1e3; + println!( + "{}×{}: re-mosaic {ms:.0} ms (a full demosaic {direct_ms:.0} ms), {shared} shared sites ({:.1} %), {kept} of them \ + untouched, PSNR through RGGB against the direct demosaic {:.1} dB", + n.width, + n.height, + 100.0 * shared as f64 / (n.width * n.height) as f64, + psnr(&direct, &demosaic(&r, Method::Ahd), 8) + ); + assert_eq!(kept, shared, "a shared site lost its own sample"); + } + + #[test] + #[ignore] + fn throughput() { + let (w, h) = (6000, 4000); + let img = smooth_scene(w, h); + let cfa = Cfa::bayer("RGGB").unwrap(); + let n = mosaic_from_rgb(&img, &cfa); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let t = std::time::Instant::now(); + let _ = demosaic(&n, m); + let s = t.elapsed().as_secs_f64(); + println!("{m:?}: {:.1} MP/s ({:.0} ms for 24 MP)", (w * h) as f64 / 1e6 / s, s * 1e3); + } + let n = mosaic_from_rgb(&img, &Cfa::xtrans()); + let t = std::time::Instant::now(); + let _ = demosaic(&n, Method::Ahd); + println!("X-Trans directional: {:.1} MP/s", (w * h) as f64 / 1e6 / t.elapsed().as_secs_f64()); + } } diff --git a/crates/raw/src/demosaic/xtrans.rs b/crates/raw/src/demosaic/xtrans.rs index 32768ea8d6..af814f4bb4 100644 --- a/crates/raw/src/demosaic/xtrans.rs +++ b/crates/raw/src/demosaic/xtrans.rs @@ -139,6 +139,45 @@ fn green(m: &Mosaic, off: &Offsets) -> Vec { g } +/// Step 2 at an interior pixel `i` with green `gp`: green plus the edge-weighted mean colour difference of +/// the same-colour samples at `list` (precomputed offsets, no reflection). +#[inline] +fn colour_inside(m: &Mosaic, g: &[f32], i: usize, gp: f32, list: &[(isize, isize)]) -> f32 { + let w = m.w as isize; + let (mut s, mut ws) = (0.0f32, 0.0f32); + for &(dx, dy) in list { + let j = (i as isize + dy * w + dx) as usize; + let gq = g[j]; + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.data[j] - gq); + ws += wt; + } + if ws > 0.0 { gp + s / ws } else { gp } +} + +/// Step 2 near the border, for colour `c` (0 red, 2 blue) at `(x, y)` with green `gp`: the 5×5 +/// neighbourhood read with reflection. +#[inline] +fn colour_at_border(m: &Mosaic, g: &[f32], x: isize, y: isize, gp: f32, c: usize) -> f32 { + let (w, h) = (m.w, m.h); + let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; + let (mut s, mut ws) = (0.0f32, 0.0f32); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if m.color(x + dx, y + dy) as usize != c { + continue; + } + let gq = gg(x + dx, y + dy); + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.get(x + dx, y + dy) - gq); + ws += wt; + } + } + if ws > 0.0 { gp + s / ws } else { gp } +} + pub(crate) fn directional(m: &Mosaic) -> Rgb32f { let (w, h) = (m.w, m.h); let off = Offsets::new(m); @@ -153,50 +192,50 @@ pub(crate) fn directional(m: &Mosaic) -> Rgb32f { let i = y * w + x; let own = m.cfa.color_at(x, y) as usize; let gp = g[i]; - px[1] = gp; let lists = &off.rb[off.phase(x, y)]; - for (li, c) in [0usize, 2].into_iter().enumerate() { - if c == own { - px[c] = m.data[i]; - continue; - } - let (mut s, mut ws) = (0.0f32, 0.0f32); - for &(dx, dy) in &lists[li] { - let j = (i as isize + dy * w as isize + dx) as usize; - let gq = g[j]; - let d2 = (dx * dx + dy * dy) as f32; - let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); - s += wt * (m.data[j] - gq); - ws += wt; - } - px[c] = if ws > 0.0 { gp + s / ws } else { gp }; - } + px[1] = gp; + px[0] = if own == 0 { m.data[i] } else { colour_inside(m, &g, i, gp, &lists[0]) }; + px[2] = if own == 2 { m.data[i] } else { colour_inside(m, &g, i, gp, &lists[1]) }; continue; } let x = x as isize; let own = m.color(x, yi) as usize; let gp = gg(x, yi); px[1] = gp; - for c in [0usize, 2] { - if c == own { - px[c] = m.get(x, yi); + px[0] = if own == 0 { m.get(x, yi) } else { colour_at_border(m, &g, x, yi, gp, 0) }; + px[2] = if own == 2 { m.get(x, yi) } else { colour_at_border(m, &g, x, yi, gp, 2) }; + } + }); + out +} + +/// The mosaic interpolated and read back as RGGB: sample for sample what [`directional`] followed by +/// keeping the RGGB colour of each site gives, without the full RGB picture in between — a third of the +/// memory, and one colour interpolated only at the sites that want red or blue. +pub(crate) fn rggb(m: &Mosaic) -> Vec { + let (w, h) = (m.w, m.h); + let off = Offsets::new(m); + let g = green(m, &off); + let mut out = vec![0f32; w * h]; + par_rows(&mut out, w, |y, row| { + let interior_y = y >= 2 && y + 2 < h; + let yi = y as isize; + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + let c = match (y % 2, x % 2) { + (0, 0) => 0, + (1, 1) => 2, + _ => { + *o = g[i]; continue; } - let (mut s, mut ws) = (0.0f32, 0.0f32); - for dy in -2isize..=2 { - for dx in -2isize..=2 { - if m.color(x + dx, yi + dy) as usize != c { - continue; - } - let gq = gg(x + dx, yi + dy); - let d2 = (dx * dx + dy * dy) as f32; - let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); - s += wt * (m.get(x + dx, yi + dy) - gq); - ws += wt; - } - } - px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + }; + if interior_y && x >= 2 && x + 2 < w { + *o = if m.cfa.color_at(x, y) as usize == c { m.data[i] } else { colour_inside(m, &g, i, g[i], &off.rb[off.phase(x, y)][c / 2]) }; + continue; } + let x = x as isize; + *o = if m.color(x, yi) as usize == c { m.get(x, yi) } else { colour_at_border(m, &g, x, yi, g[i], c) }; } }); out diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index d9b8b21b3f..82cdeef94f 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -17,7 +17,9 @@ //! `jxl` feature, on by default), tiled/stripped, CFA and LinearRaw), //! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer //! and X-Trans, lossless and lossy compressed), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format: compressed 4 and 6, the prefix-coded strips of 8, -//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500). +//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500), +//! Minolta MRW, Canon CRW, Epson ERF, Mamiya MEF, Kodak DCS, and FITS (astrophotography: integer and floating-point +//! monochrome, colour-filter-array and red / green / blue images, [`vendor::fits`]). //! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (compressed ORF, CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources //! (public specifications, tag-name documentation, black-box analysis of CC0 samples) and gaps. Non-DNG files carry no //! colour matrix: [`spectral`] has matrices fitted to measured spectral sensitivities for 52 models, and @@ -157,6 +159,9 @@ pub enum RawFormat { Erf, /// Mamiya MEF: an uncompressed 12-bit packed CFA sub-IFD (`vendor::mef`). Mef, + /// FITS, the format of astrophotography cameras and software: 2880-byte blocks of ASCII cards, then big-endian + /// samples (`vendor::fits`). + Fits, /// Another TIFF-based raw (3FR, IIQ, ERF, KDC, DCR, MOS, …). OtherTiff, } @@ -182,6 +187,7 @@ impl RawFormat { | RawFormat::Erf | RawFormat::Mef | RawFormat::Crw + | RawFormat::Fits ) } } @@ -206,6 +212,10 @@ pub fn probe(bytes: &[u8]) -> Option { if bytes.starts_with(b"FOVb") { return Some(RawFormat::X3f); } + // a FITS file's first card (even `SIMPLE = F`: the decoder says why it can't be read) + if lcc_meta::fits::is_fits(bytes) { + return Some(RawFormat::Fits); + } if bytes.len() >= 14 && bytes.starts_with(b"II") && &bytes[6..14] == b"HEAPCCDR" { return Some(RawFormat::Crw); } @@ -455,6 +465,7 @@ fn decode_with(bytes: &[u8], mode: Mode) -> Result { RawFormat::Mrw => vendor::mrw::decode(bytes, mode), RawFormat::Erf => vendor::erf::decode(bytes, mode), RawFormat::Mef => vendor::mef::decode(bytes, mode), + RawFormat::Fits => vendor::fits::decode(bytes, mode), RawFormat::Crw => vendor::crw::decode(bytes, mode), RawFormat::OtherTiff => Err(RawError::Unsupported(other_tiff_reason(bytes))), other => Err(RawError::Unsupported(format!("{other:?} files are not decoded yet"))), @@ -1374,6 +1385,10 @@ mod tests { assert_eq!(probe(b"II\x1a\0\0\0HEAPCCDR\0\0"), Some(RawFormat::Crw)); assert_eq!(probe(b"\0MRM\0\x01\0\0"), Some(RawFormat::Mrw)); assert_eq!(probe(b"FOVb\x02\0\x02\0"), Some(RawFormat::X3f)); + // FITS: the `SIMPLE` card, recognised before any TIFF structure is looked for + assert_eq!(probe(b"SIMPLE = T"), Some(RawFormat::Fits)); + assert!(RawFormat::Fits.is_supported()); + assert!(matches!(decode(b"SIMPLE = T"), Err(RawError::Corrupt(_)))); assert!(!RawFormat::X3f.is_supported()); assert!(RawFormat::Crw.is_supported()); assert!(RawFormat::Mrw.is_supported()); diff --git a/crates/raw/src/vendor/fits.rs b/crates/raw/src/vendor/fits.rs new file mode 100644 index 0000000000..5e26f5353c --- /dev/null +++ b/crates/raw/src/vendor/fits.rs @@ -0,0 +1,832 @@ +#![deny(clippy::indexing_slicing, clippy::arithmetic_side_effects)] +//! FITS pixels (Flexible Image Transport System, the FITS 4.0 standard of NASA / IAU): the file format of +//! astrophotography cameras, and of the images astrophotography software exports (issue #1604). The header cards are +//! read by `lcc_meta::fits`, which also takes the photo's metadata from them; this module turns the data into samples. +//! +//! Sources: the FITS standard, read as a reference (the order of the data, `BITPIX`, `BZERO` / `BSCALE`). The +//! `BAYERPAT`, `XBAYOFF` / `YBAYOFF` cards are not in the standard: they are a convention of astrophotography +//! software (MaxIm DL, Sequence Generator Pro, N.I.N.A., KStars), read as KStars' reader documents and applies them. +//! No decoder source was copied. +//! +//! - Data: big-endian samples, row after row. A colour image keeps one plane after another (all of red, then green, +//! then blue), so its third axis is 3 long. +//! - Two dimensions are one sample a pixel: a monochrome picture, or a colour filter array when the header names its +//! pattern in `BAYERPAT` (`RGGB`, `GBRG`, `GRBG`, `BGGR`; `XBAYOFF` / `YBAYOFF`, also spelled `XBAYROFF` / +//! `YBAYROFF`, say which element of the pattern the first pixel is). Three planes are red, green and blue, +//! demosaiced already. +//! - 8-bit samples and 16-bit ones are read as 16-bit samples; everything else (32-bit integers, floating-point data, +//! any other `BSCALE` / `BZERO`) as floating-point samples. +//! - Rows are read in file order, top row first, the way camera and stacking software show them. A file that says +//! `ROWORDER = 'BOTTOM-UP'` keeps its bottom row first, and is turned upright. +//! - Levels: black 0, white the top of the sample type's range (255; 65 535 with `BZERO` 32768; 32 767 for signed +//! 16-bit samples, whose negative ones read as black; 1.0 for floating-point data). `DATAMIN` / `DATAMAX` describe the +//! data, not where it clips, and are not used. A file states no white balance and no colour matrix. +//! - Refused, saying why ([`RawError::Unsupported`]): 64-bit integers, any other axis count (a row, a data cube, two +//! or four and more planes), colour filter patterns with colours other than red, green and blue, random-groups +//! records, tile-compressed images (`ZIMAGE`). The checksum cards are not verified. +use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use lcc_geom::Orientation; +use lcc_meta::fits::Problem; + +/// What `lcc_meta::fits` could not read of a file's header, as this decoder's error. +fn unreadable(problem: Problem) -> RawError { + match problem { + Problem::NotFits => RawError::NotRaw, + Problem::NotStandard => RawError::Unsupported("FITS files that do not follow the standard (SIMPLE = F)".into()), + Problem::NoEnd => RawError::Corrupt("FITS: the header ends before its END card".into()), + Problem::TooLong => RawError::Limit("a FITS header of more than 4096 blocks"), + Problem::TooLarge => RawError::Limit("image too large"), + Problem::Card(what) => RawError::Corrupt(format!("FITS: {what}")), + Problem::NoImage => RawError::Unsupported(format!("FITS files whose first {} header units hold no image", lcc_meta::fits::MAX_UNITS)), + } +} + +/// How the stored samples are read. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Kind { + /// Bytes, 0 to 255. + U8, + /// 16-bit words read unsigned (`BZERO` 32768): 0 to 65 535. + U16, + /// 16-bit signed words: a negative sample (noise, after calibration) reads as black. + I16, + I32, + /// 32-bit words read unsigned (`BZERO` 2^31). + U32, + F32, + F64, + /// Any other `BSCALE` / `BZERO`: `BZERO + BSCALE × stored`. + Scaled { + bitpix: i64, + bzero: f64, + bscale: f64, + }, +} + +impl Kind { + fn of(bitpix: i64, bzero: Option, bscale: Option) -> Result { + let unsupported = |m: String| RawError::Unsupported(format!("FITS {m}")); + // a missing card has the standard's default + let (bzero, bscale) = (bzero.unwrap_or(0.0), bscale.unwrap_or(1.0)); + let kind = match bitpix { + 64 => return Err(unsupported("64-bit integer samples are not supported".into())), + // (8-bit samples are bytes already: `BZERO` -128 on them is a signed-byte offset, read like any scaling) + 8 | 16 | 32 | -32 | -64 if bscale == 1.0 => match (bitpix, bzero) { + (8, 0.0) => Kind::U8, + (16, 0.0) => Kind::I16, + (16, 32768.0) => Kind::U16, + (32, 0.0) => Kind::I32, + (32, 2147483648.0) => Kind::U32, + (-32, 0.0) => Kind::F32, + (-64, 0.0) => Kind::F64, + _ => Kind::Scaled { bitpix, bzero, bscale }, + }, + 8 | 16 | 32 | -32 | -64 => Kind::Scaled { bitpix, bzero, bscale }, + _ => return Err(unsupported(format!("samples of {bitpix} bits are not supported"))), + }; + if kind.white().is_none() { + return Err(unsupported(format!("scaling (BZERO {bzero}, BSCALE {bscale}) leaves no positive sample"))); + } + Ok(kind) + } + + /// Bytes a stored sample takes. + fn bytes(self) -> usize { + match self { + Kind::U8 => 1, + Kind::U16 | Kind::I16 => 2, + Kind::I32 | Kind::U32 | Kind::F32 => 4, + Kind::F64 => 8, + Kind::Scaled { bitpix, .. } => usize::try_from(bitpix.unsigned_abs()).unwrap_or(0).div_ceil(8), + } + } + + /// White: the top of the sample type's range, 1.0 for floating-point data. `None` when scaling leaves no + /// positive value. + fn white(self) -> Option { + let top = match self { + Kind::U8 => 255.0, + Kind::U16 => 65535.0, + Kind::I16 => 32767.0, + // one past the largest sample: exactly representable, where 2^31 - 1 is not + Kind::I32 => 2147483648.0, + Kind::U32 => 4294967296.0, + Kind::F32 | Kind::F64 => 1.0, + Kind::Scaled { bitpix, bzero, bscale } => { + // the largest value a stored sample can hold (1.0 for a floating-point one, whose white is 1.0) + let top = match bitpix { + 8 => 255.0, + 16 => 32767.0, + 32 => 2147483647.0, + -32 | -64 => 1.0, + _ => return None, + }; + let top = bscale.mul_add(top, bzero); + return (top.is_finite() && top > 0.0).then_some(top as f32); + } + }; + Some(top) + } + + /// Read as 16-bit samples ([`RawData::U16`]). + fn is_u16(self) -> bool { + matches!(self, Kind::U8 | Kind::U16 | Kind::I16) + } + + /// Significant bits of the samples (informational). + fn bits(self) -> u32 { + match self { + Kind::U8 => 8, + Kind::U16 | Kind::I16 => 16, + Kind::I32 | Kind::U32 | Kind::F32 => 32, + Kind::F64 => 64, + Kind::Scaled { bitpix, .. } => u32::try_from(bitpix.unsigned_abs()).unwrap_or(32), + } + } +} + +/// The image a FITS file holds, as its header describes it. +#[derive(Debug, PartialEq)] +struct Header { + width: usize, + height: usize, + /// 1 (one sample a pixel) or 3 (red, green and blue planes). + planes: usize, + kind: Kind, + /// Offset of the data. + data: usize, + /// `BAYERPAT` as written. + bayer: Option, + /// `XBAYOFF` / `YBAYOFF`: which element of the pattern the first pixel is (0 or 1). + xoff: usize, + yoff: usize, +} + +/// `XBAYOFF` / `YBAYOFF` (also spelled `XBAYROFF` / `YBAYROFF`): 0 or 1. +fn bayoff(cards: &lcc_meta::fits::Cards, spelling: &str, other: &str) -> usize { + cards.int(spelling).or_else(|| cards.int(other)).and_then(|v| usize::try_from(v.rem_euclid(2)).ok()).unwrap_or(0) +} + +/// The image's header, read as this decoder needs it: the primary header's image, or the first `IMAGE` extension's +/// when the primary has no data (`lcc_meta::fits::image_header`). +fn header(bytes: &[u8]) -> Result
{ + let image = lcc_meta::fits::image_header(bytes).map_err(unreadable)?; + let cards = &image.cards; + if image.compressed { + return Err(RawError::Unsupported("tile-compressed FITS images (ZIMAGE) are not supported".into())); + } + if cards.flag("GROUPS") == Some(true) { + return Err(RawError::Unsupported("FITS random-groups records are not images".into())); + } + let corrupt = |m: &str| RawError::Corrupt(format!("FITS: {m}")); + let unsupported = |m: String| RawError::Unsupported(m); + let (width, height, planes) = match image.axes.as_slice() { + [w, h] => (*w, *h, 1), + [w, h, p] => (*w, *h, *p), + [_] => return Err(unsupported("FITS images with one axis (a row of values) are not pictures".into())), + _ => return Err(unsupported(format!("FITS images with {} axes are not supported", image.axes.len()))), + }; + if width == 0 || height == 0 { + return Err(corrupt("the image is empty")); + } + if planes != 1 && planes != 3 { + return Err(unsupported(format!("FITS images with {planes} planes are not supported (one, or red, green and blue)"))); + } + Ok(Header { + width, + height, + planes, + kind: Kind::of(image.bitpix, cards.real("BZERO"), cards.real("BSCALE"))?, + data: image.data, + bayer: cards.text("BAYERPAT"), + xoff: bayoff(cards, "XBAYOFF", "XBAYROFF"), + yoff: bayoff(cards, "YBAYOFF", "YBAYROFF"), + }) +} + +/// A stored sample as a 16-bit one, for the kinds that fit. +fn stored_u16(kind: Kind, c: &[u8]) -> Option { + match kind { + Kind::U8 => c.first().map(|&b| u16::from(b)), + Kind::I16 => Some(u16::try_from(i16::from_be_bytes(*c.as_array::<2>()?)).unwrap_or(0)), + // `BZERO` + a signed word: the unsigned value is the stored bits with their top bit turned over + // (0 is stored as -32768, 65 535 as 32 767) + Kind::U16 => Some(u16::from_be_bytes(*c.as_array::<2>()?) ^ 0x8000), + _ => None, + } +} + +/// A stored sample as a real number, before `BSCALE` / `BZERO`. +fn stored_f64(kind: Kind, c: &[u8]) -> Option { + match kind { + Kind::I32 => Some(f64::from(i32::from_be_bytes(*c.as_array::<4>()?))), + // as the 16-bit words above, with 2^31 for `BZERO` + Kind::U32 => Some(f64::from(u32::from_be_bytes(*c.as_array::<4>()?) ^ 0x8000_0000)), + Kind::F32 => Some(f64::from(f32::from_be_bytes(*c.as_array::<4>()?))), + Kind::F64 => Some(f64::from_be_bytes(*c.as_array::<8>()?)), + Kind::Scaled { bitpix, .. } => match bitpix { + 8 => Some(f64::from(c.first().copied()?)), + 16 => Some(f64::from(i16::from_be_bytes(*c.as_array::<2>()?))), + 32 => Some(f64::from(i32::from_be_bytes(*c.as_array::<4>()?))), + -32 => Some(f64::from(f32::from_be_bytes(*c.as_array::<4>()?))), + -64 => Some(f64::from_be_bytes(*c.as_array::<8>()?)), + _ => None, + }, + _ => None, + } +} + +/// A sample's value: a real number, with `BSCALE` / `BZERO` applied. +fn value_f32(kind: Kind, c: &[u8]) -> Option { + let stored = stored_f64(kind, c)?; + Some(match kind { + Kind::Scaled { bzero, bscale, .. } => bscale.mul_add(stored, bzero) as f32, + _ => stored as f32, + }) +} + +/// The image's samples from `src` (the data of every plane, row-major within a plane), interleaved per pixel. +fn samples(src: &[u8], h: &Header, value: impl Fn(&[u8]) -> Option) -> Result> { + let corrupt = || RawError::Corrupt("FITS: the data is shorter than its header says".into()); + let too_big = || RawError::Limit("image too large"); + let plane = crate::checked_samples(&[h.width, h.height])?; + let size = h.kind.bytes(); + if size == 0 { + return Err(RawError::Corrupt("FITS: the sample type is not one the file can hold".into())); + } + let mut out = vec![T::default(); crate::checked_samples(&[h.width, h.height, h.planes])?]; + for p in 0..h.planes { + let from = p.checked_mul(plane).and_then(|n| n.checked_mul(size)).ok_or_else(too_big)?; + let to = from.checked_add(plane.checked_mul(size).ok_or_else(too_big)?).ok_or_else(too_big)?; + let rows = src.get(from..to).ok_or_else(corrupt)?; + // the first slot is this plane's at the first pixel; every `planes`-th one after it is too + for (slot, c) in out.iter_mut().skip(p).step_by(h.planes).zip(rows.chunks_exact(size)) { + *slot = value(c).ok_or_else(corrupt)?; + } + } + Ok(out) +} + +pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { + let h = header(bytes)?; + let corrupt = |m: &str| RawError::Corrupt(format!("FITS: {m}")); + let need = u64::try_from(crate::checked_samples(&[h.width, h.height, h.planes])?) + .unwrap_or(u64::MAX) + .checked_mul(h.kind.bytes() as u64) + .ok_or(RawError::Limit("image too large"))?; + let need = usize::try_from(need).map_err(|_| corrupt("the data is larger than this build reads"))?; + let src = bytes.get(h.data..).and_then(|s| s.get(..need)).ok_or_else(|| corrupt("the data is truncated"))?; + // a colour filter array belongs to one sample a pixel; three planes are demosaiced already + let pattern = (h.planes == 1).then_some(h.bayer.as_deref()).flatten().map(|p| p.trim().to_ascii_uppercase()); + let cfa = match pattern.as_deref() { + None => None, + Some(p) => { + let c = Cfa::bayer(p) + .filter(|c| c.is_bayer()) + .ok_or_else(|| RawError::Unsupported(format!("FITS colour filter pattern '{p}' is not supported (RGGB, GBRG, GRBG, BGGR)")))?; + Some(c.shifted(h.xoff, h.yoff)) + } + }; + let data = if mode == Mode::Header { + RawData::U16(Vec::new()) + } else if h.kind.is_u16() { + RawData::U16(samples(src, &h, |c| stored_u16(h.kind, c))?) + } else { + RawData::F32(samples(src, &h, |c| value_f32(h.kind, c))?) + }; + let metadata = lcc_meta::fits::metadata(bytes).unwrap_or_default(); + let img = RawImage { + format: RawFormat::Fits, + width: h.width, + height: h.height, + cpp: h.planes, + data, + cfa, + bits: h.kind.bits(), + black: BlackLevel::uniform(0.0), + white: vec![h.kind.white().unwrap_or(1.0)], + active_area: Rect::new(0, 0, h.width, h.height), + crop: Rect::new(0, 0, h.width, h.height), + // a file that keeps its bottom row first is turned upright + orientation: if metadata.orientation == Some(Orientation::FlipV) { Orientation::FlipV } else { Orientation::Normal }, + color: ColorData::default(), + wb_multipliers: None, + linearized: false, + opcodes: OpcodeLists::default(), + metadata, + lens_metadata: Default::default(), + pixel_aspect: 1.0, + }; + img.validate_for(mode)?; + Ok(img) +} + +#[cfg(test)] +mod tests { + // the inputs are small literals; it is the decoder above that must not overflow + #![allow(clippy::arithmetic_side_effects)] + + use super::*; + use lcc_meta::fits::{BLOCK, CARD, MAX_UNITS}; + + /// A header and more cards. + fn plus(mut cards: Vec, extra: &[String]) -> Vec { + cards.extend_from_slice(extra); + cards + } + + /// One 80-column card. + fn card(text: &str) -> String { + format!("{text:<80}") + } + + /// A numeric card, its value right-justified the way writers lay them out. + fn kw(name: &str, value: impl std::fmt::Display) -> String { + card(&format!("{name:<8}= {value:>20}")) + } + + /// A string card (at least eight characters, as the standard asks). + fn text(name: &str, value: &str) -> String { + card(&format!("{name:<8}= '{value:<8}'")) + } + + /// A header unit: its cards and `END`, in whole blocks. + fn unit(cards: &[String]) -> Vec { + let mut out: Vec = cards.iter().flat_map(|c| c.as_bytes().iter().copied()).collect(); + out.extend_from_slice(card("END").as_bytes()); + out.resize(out.len().div_ceil(BLOCK) * BLOCK, b' '); + out + } + + /// A header unit and its data, in whole blocks. + fn with_data(mut out: Vec, data: &[u8]) -> Vec { + out.extend_from_slice(data); + out.resize(out.len().div_ceil(BLOCK) * BLOCK, 0); + out + } + + /// The primary header of a `w × h` image with `bitpix`-bit samples. + fn image(w: u32, h: u32, bitpix: i32) -> Vec { + vec![card("SIMPLE = T"), kw("BITPIX", bitpix), kw("NAXIS", 2), kw("NAXIS1", w), kw("NAXIS2", h)] + } + + /// 16-bit unsigned samples (`BZERO` 32768) as a file stores them: signed words, the value less 32 768. + fn u16s(values: &[u16]) -> Vec { + values.iter().flat_map(|v| ((*v as i32 - 32768) as i16).to_be_bytes()).collect() + } + + fn be32s(values: &[i32]) -> Vec { + values.iter().flat_map(|v| v.to_be_bytes()).collect() + } + + fn f32s(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_be_bytes()).collect() + } + + fn f64s(values: &[f64]) -> Vec { + values.iter().flat_map(|v| v.to_be_bytes()).collect() + } + + fn samples_of(img: &RawImage) -> Vec { + (0..img.data.len()).map(|i| img.data.get(i)).collect() + } + + /// A 2×2 file of 16-bit unsigned samples, four of them: a base to corrupt. + fn small() -> Vec { + let mut cards = image(2, 2, 16); + cards.push(kw("BZERO", 32768)); + with_data(unit(&cards), &u16s(&[0, 1000, 40000, 65535])) + } + + #[test] + fn unsigned_16_bit_colour_filter_array() { + let mut cards = image(4, 3, 16); + cards.push(kw("BZERO", 32768)); + cards.push(text("BAYERPAT", "RGGB")); + let values: Vec = (0..12).map(|i| [0u16, 32768, 1000, 60000][i % 4] + (i as u16 % 3)).collect(); + let f = with_data(unit(&cards), &u16s(&values)); + assert_eq!(crate::probe(&f), Some(RawFormat::Fits)); + assert!(RawFormat::Fits.is_supported()); + let img = crate::decode(&f).unwrap(); + assert_eq!((img.format, img.width, img.height, img.cpp), (RawFormat::Fits, 4, 3, 1)); + assert_eq!(img.data, RawData::U16(values)); + assert_eq!((img.bits, img.black.mean()), (16, 0.0)); + assert_eq!(img.white, vec![65535.0]); + assert_eq!(img.active_area, Rect::new(0, 0, 4, 3)); + assert_eq!(img.crop, Rect::new(0, 0, 4, 3)); + assert_eq!(img.cfa.as_ref().map(|c| c.name()).as_deref(), Some("RGGB")); + assert_eq!(img.orientation, Orientation::Normal); + assert!(img.wb_multipliers.is_none()); + assert_eq!(crate::probe_info(&f).unwrap(), img.info()); + let rgb = img.develop(crate::Method::Ahd).unwrap(); + assert_eq!((rgb.width, rgb.height), (4, 3)); + } + + #[test] + fn signed_16_bit_monochrome_image() { + // negative samples (noise after calibration) read as black + let f = with_data(unit(&image(2, 2, 16)), &[-5i16, 0, 1000, 32767].iter().flat_map(|v| v.to_be_bytes()).collect::>()); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.data, RawData::U16(vec![0, 0, 1000, 32767])); + assert_eq!(img.white, vec![32767.0]); + assert!(img.cfa.is_none()); + assert_eq!(crate::probe_info(&f).unwrap(), img.info()); + // developed to grey + let rgb = img.develop(crate::Method::Ahd).unwrap(); + let last = rgb.data.last().unwrap(); + assert_eq!(last, &[1.0, 1.0, 1.0]); + } + + /// Unsigned words are signed words plus `BZERO`: the file's bytes are not the value's own. (Read as unsigned + /// directly, 0 came out as 32 768 and every star of a camera frame as a dark dot.) + #[test] + fn unsigned_words_are_the_stored_signed_words_plus_bzero() { + // values 0, 32 768 and 65 535 are stored as -32 768, 0 and 32 767 + let mut cards = image(3, 1, 16); + cards.push(kw("BZERO", 32768)); + let f = with_data(unit(&cards), &[-32768i16, 0, 32767].iter().flat_map(|v| v.to_be_bytes()).collect::>()); + assert_eq!(crate::decode(&f).unwrap().data, RawData::U16(vec![0, 32768, 65535])); + // and 32-bit ones the same way, with 2^31 + let mut cards = image(3, 1, 32); + cards.push(kw("BZERO", 2147483648u32)); + let stored = [0i64, 1, 3_000_000_000].map(|v| (v - (1i64 << 31)) as i32); + let f = with_data(unit(&cards), &be32s(&stored)); + assert_eq!(crate::decode(&f).unwrap().data, RawData::F32(vec![0.0, 1.0, 3_000_000_000.0])); + } + + #[test] + fn eight_bit_and_wide_integer_samples() { + // bytes are 0 to 255 as they are + let f = with_data(unit(&image(4, 1, 8)), &[0, 1, 200, 255]); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.data, RawData::U16(vec![0, 1, 200, 255])); + assert_eq!((img.bits, img.white.clone()), (8, vec![255.0])); + assert_eq!(crate::probe_info(&f).unwrap(), img.info()); + // `BZERO` -128 on bytes is a signed-byte offset (-128 to 127), read like any other scaling + let mut cards = image(4, 1, 8); + cards.push(kw("BZERO", -128)); + let f = with_data(unit(&cards), &[0, 1, 200, 255]); + let img = crate::decode(&f).unwrap(); + assert_eq!(samples_of(&img), vec![-128.0, -127.0, 72.0, 127.0]); + assert_eq!(img.white, vec![127.0]); + let f = with_data(unit(&image(3, 1, 32)), &be32s(&[-1, 0, 2_000_000_000])); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.data, RawData::F32(vec![-1.0, 0.0, 2_000_000_000.0])); + assert_eq!(img.white, vec![2147483648.0]); + // unsigned 32-bit (`BZERO` 2^31): 0 is stored as i32::MIN + let mut cards = image(2, 1, 32); + cards.push(kw("BZERO", 2147483648u32)); + let f = with_data(unit(&cards), &be32s(&[i32::MIN, i32::MAX])); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.data, RawData::F32(vec![0.0, 4294967295.0])); + assert_eq!(img.white, vec![4294967296.0]); + assert_eq!(img.bits, 32); + } + + #[test] + fn floating_point_and_scaled_samples() { + let f = with_data(unit(&image(4, 1, -32)), &f32s(&[0.25, 1.0, 2.5, -0.5])); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.data, RawData::F32(vec![0.25, 1.0, 2.5, -0.5])); + assert_eq!((img.white.as_slice(), img.bits), ([1.0].as_slice(), 32)); + assert_eq!(crate::probe_info(&f).unwrap(), img.info()); + + let f = with_data(unit(&image(2, 1, -64)), &f64s(&[0.125, 3.0])); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.data, RawData::F32(vec![0.125, 3.0])); + assert_eq!((img.white.as_slice(), img.bits), ([1.0].as_slice(), 64)); + + // `BZERO + BSCALE × stored`, white the top of the stored range + let mut cards = image(3, 1, 16); + cards.extend([kw("BZERO", 100), kw("BSCALE", "0.5D0")]); + let f = with_data(unit(&cards), &[-100i16, 0, 32767].iter().flat_map(|v| v.to_be_bytes()).collect::>()); + let img = crate::decode(&f).unwrap(); + assert_eq!(samples_of(&img), vec![50.0, 100.0, 16483.5]); + assert_eq!(img.white, vec![16483.5]); + assert_eq!(img.bits, 16); + assert_eq!(crate::probe_info(&f).unwrap(), img.info()); + + // floating-point data with a scale + let mut cards = image(2, 1, -32); + cards.extend([kw("BZERO", 1), kw("BSCALE", 2)]); + let f = with_data(unit(&cards), &f32s(&[0.5, -0.25])); + assert_eq!(samples_of(&crate::decode(&f).unwrap()), vec![2.0, 0.5]); + } + + #[test] + fn colour_planes_are_interleaved() { + let mut cards = vec![ + card("SIMPLE = T"), + kw("BITPIX", 16), + kw("NAXIS", 3), + kw("NAXIS1", 2), + kw("NAXIS2", 1), + kw("NAXIS3", 3), + kw("BZERO", 32768), + ]; + // the red plane, then green, then blue + let f = with_data(unit(&cards), &u16s(&[10, 20, 30, 40, 50, 60])); + let img = crate::decode(&f).unwrap(); + assert_eq!((img.cpp, img.cfa.is_none()), (3, true)); + assert_eq!(img.data, RawData::U16(vec![10, 30, 50, 20, 40, 60])); + assert_eq!(crate::probe_info(&f).unwrap(), img.info()); + + // three planes in floating point + cards[1] = kw("BITPIX", -32); + cards.pop(); + let f = with_data(unit(&cards), &f32s(&[0.1, 0.2, 0.3, 0.4, 0.5, 0.6])); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.data, RawData::F32(vec![0.1, 0.3, 0.5, 0.2, 0.4, 0.6])); + + // two rows of three planes: every sample lands in its pixel + let cards = [card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", 3), kw("NAXIS1", 2), kw("NAXIS2", 2), kw("NAXIS3", 3)]; + let stored: Vec = (0..12).map(|i| i * 1000).collect(); + let f = with_data(unit(&cards), &stored.iter().flat_map(|v| v.to_be_bytes()).collect::>()); + let img = crate::decode(&f).unwrap(); + assert_eq!(samples_of(&img), vec![0.0, 4000.0, 8000.0, 1000.0, 5000.0, 9000.0, 2000.0, 6000.0, 10000.0, 3000.0, 7000.0, 11000.0]); + + // a single plane behind a third axis is a two-dimensional image + let cards = [ + card("SIMPLE = T"), + kw("BITPIX", 16), + kw("NAXIS", 3), + kw("NAXIS1", 2), + kw("NAXIS2", 2), + kw("NAXIS3", 1), + kw("BZERO", 32768), + ]; + let f = with_data(unit(&cards), &u16s(&[1, 2, 3, 4])); + let img = crate::decode(&f).unwrap(); + assert_eq!((img.cpp, img.width, img.height), (1, 2, 2)); + assert_eq!(img.data, RawData::U16(vec![1, 2, 3, 4])); + } + + #[test] + fn bayer_offsets_and_row_order() { + // The colour filter array of a 2×2 file with the extra cards `extra`. + let cfa = |extra: &[String]| { + let mut cards = image(2, 2, 16); + cards.push(text("BAYERPAT", "RGGB")); + cards.extend_from_slice(extra); + crate::decode(&with_data(unit(&cards), &u16s(&[0; 4]))).map(|i| i.cfa.map(|c| c.name())) + }; + let name = |extra: &[String]| cfa(extra).unwrap(); + assert_eq!(name(&[]).as_deref(), Some("RGGB")); + // the offsets say which element of the pattern the first pixel is + assert_eq!(name(&[kw("XBAYOFF", 1)]).as_deref(), Some("GRBG")); + assert_eq!(name(&[kw("YBAYOFF", 1)]).as_deref(), Some("GBRG")); + assert_eq!(name(&[kw("XBAYOFF", 1), kw("YBAYOFF", 1)]).as_deref(), Some("BGGR")); + // the other spelling, and offsets outside 0 and 1 + assert_eq!(name(&[kw("XBAYROFF", 1)]).as_deref(), Some("GRBG")); + assert_eq!(name(&[kw("XBAYROFF", 3), kw("YBAYROFF", 7)]).as_deref(), Some("BGGR")); + assert_eq!(name(&[kw("XBAYOFF", -1)]).as_deref(), Some("GRBG")); + assert_eq!(name(&[kw("XBAYOFF", i64::MIN)]).as_deref(), Some("RGGB")); + // written in lower case, with a comment, or three planes (demosaiced already: no array) + let mut cards = image(2, 2, 16); + cards.push(card("BAYERPAT= 'rggb ' / the sensor's pattern")); + let img = crate::decode(&with_data(unit(&cards), &u16s(&[0; 4]))).unwrap(); + assert_eq!(img.cfa.map(|c| c.name()).as_deref(), Some("RGGB")); + let cards = [ + card("SIMPLE = T"), + kw("BITPIX", 16), + kw("NAXIS", 3), + kw("NAXIS1", 2), + kw("NAXIS2", 2), + kw("NAXIS3", 3), + text("BAYERPAT", "RGGB"), + ]; + let img = crate::decode(&with_data(unit(&cards), &u16s(&[0; 12]))).unwrap(); + assert!(img.cfa.is_none()); + // patterns with other colours, or none + for pattern in ["CMYG", "GYCM", "RRGG", "RGB", "", "RGGBGRBG"] { + let mut cards = image(2, 2, 16); + cards.push(text("BAYERPAT", pattern)); + let err = crate::decode(&with_data(unit(&cards), &u16s(&[0; 4]))).unwrap_err(); + assert!(matches!(&err, RawError::Unsupported(m) if m.contains("colour filter pattern")), "{pattern}: {err}"); + } + + // row order: a file that keeps its bottom row first is turned upright + let orientation = |order: &str| { + let mut cards = image(2, 2, 16); + cards.push(text("ROWORDER", order)); + crate::decode(&with_data(unit(&cards), &u16s(&[0; 4]))).map(|i| (i.orientation, i.metadata.orientation)) + }; + assert_eq!(orientation("BOTTOM-UP").unwrap(), (Orientation::FlipV, Some(Orientation::FlipV))); + assert_eq!(orientation("bottom-up").unwrap(), (Orientation::FlipV, Some(Orientation::FlipV))); + assert_eq!(orientation("TOP-DOWN").unwrap(), (Orientation::Normal, None)); + assert_eq!(orientation("SIDEWAYS").unwrap(), (Orientation::Normal, None)); + let plain = crate::decode(&with_data(unit(&image(2, 2, 16)), &u16s(&[0; 4]))).unwrap(); + assert_eq!((plain.orientation, plain.metadata.orientation), (Orientation::Normal, None)); + assert_eq!(crate::probe_info(&plain_bytes()).unwrap().orientation, Orientation::FlipV); + } + + fn plain_bytes() -> Vec { + let mut cards = image(2, 2, 16); + cards.push(text("ROWORDER", "BOTTOM-UP")); + with_data(unit(&cards), &u16s(&[0; 4])) + } + + /// The decoded image carries what the header says about the shot (`lcc_meta::fits` reads the cards). + #[test] + fn the_image_carries_the_header_metadata() { + let cards = plus( + image(2, 2, 16), + &[ + text("DATE-OBS", "2026-11-28 12:34:56"), + kw("EXPTIME", "120.5"), + text("INSTRUME", "ZWO ASI2600MC"), + text("OBJECT", "M 31 / Andromeda"), + kw("FOCALLEN", 530), + ], + ); + let f = with_data(unit(&cards), &u16s(&[0; 4])); + let img = crate::decode(&f).unwrap(); + assert_eq!(img.metadata, lcc_meta::extract(&f)); + assert_eq!((img.metadata.width, img.metadata.height), (Some(2), Some(2))); + assert_eq!(img.metadata.capture_time, crate::probe_info(&f).unwrap().metadata.capture_time); + assert!(img.metadata.capture_time.is_some_and(|t| (t.year, t.month, t.day, t.hour, t.minute, t.second) == (2026, 11, 28, 12, 34, 56))); + assert_eq!(img.metadata.exposure_time, Some(120.5)); + assert_eq!(img.metadata.model.as_deref(), Some("ZWO ASI2600MC")); + assert_eq!(img.metadata.title.as_deref(), Some("M 31 / Andromeda")); + assert_eq!(img.metadata.focal_length, Some(530.0)); + // a header that states nothing + let img = crate::decode(&small()).unwrap(); + assert_eq!((img.metadata.width, img.metadata.height), (Some(2), Some(2))); + assert!(img.metadata.capture_time.is_none() && img.metadata.exposure_time.is_none() && img.metadata.model.is_none()); + } + + /// A primary header without data, then `IMAGE` and table extensions: the first image is read. + #[test] + fn the_first_image_extension_when_the_primary_has_no_data() { + let empty = unit(&[card("SIMPLE = T"), kw("BITPIX", 8), kw("NAXIS", 0), kw("EXTEND", "T")]); + let table = |cards: &[String], rows: usize| { + let mut all = vec![text("XTENSION", "BINTABLE"), kw("BITPIX", 8), kw("NAXIS", 2), kw("NAXIS1", 8), kw("NAXIS2", rows)]; + all.extend_from_slice(cards); + with_data(unit(&all), &vec![0x5a; 8 * rows]) + }; + let mut picture = vec![text("XTENSION", "IMAGE"), kw("BITPIX", 16), kw("NAXIS", 2), kw("NAXIS1", 2), kw("NAXIS2", 2), kw("BZERO", 32768)]; + picture.push(text("OBJECT", "M 31")); + let image_unit = with_data(unit(&picture), &u16s(&[1, 2, 3, 4])); + // with the table's heap (PCOUNT bytes) after its rows + let mut all = table(&[kw("PCOUNT", 16), kw("GCOUNT", 1), kw("TFIELDS", 0)], 3); + all.truncate(all.len() - BLOCK); + all.extend_from_slice(&[0xee; 16]); + all.resize(all.len().div_ceil(BLOCK) * BLOCK, 0); + + let mut f = empty.clone(); + f.extend_from_slice(&all); + f.extend_from_slice(&image_unit); + // a second image after the first one is not read + f.extend_from_slice(&image_unit); + let img = crate::decode(&f).unwrap(); + assert_eq!((img.width, img.height), (2, 2)); + assert_eq!(img.data, RawData::U16(vec![1, 2, 3, 4])); + assert_eq!(img.metadata.title.as_deref(), Some("M 31")); + assert_eq!(crate::probe_info(&f).unwrap(), img.info()); + // the image straight after the primary header + let mut f = empty.clone(); + f.extend_from_slice(&image_unit); + assert_eq!(crate::decode(&f).unwrap().data, RawData::U16(vec![1, 2, 3, 4])); + // the header alone says whether there is an image: a table is skipped to find one + let mut f = empty.clone(); + f.extend_from_slice(&table(&[kw("PCOUNT", 0)], 3)); + f.extend_from_slice(&image_unit); + assert!(crate::probe_info(&f).is_ok()); + // only tables: nothing to show + let mut f = empty.clone(); + f.extend_from_slice(&table(&[kw("PCOUNT", 0)], 3)); + let err = crate::probe_info(&f).unwrap_err(); + assert!(matches!(&err, RawError::Unsupported(m) if m.contains("hold no image")), "{err}"); + // tile-compressed images are named + let mut f = empty.clone(); + f.extend_from_slice(&table(&[kw("PCOUNT", 0), kw("ZIMAGE", "T"), text("ZCMPTYPE", "RICE_1")], 3)); + let err = crate::probe_info(&f).unwrap_err(); + assert!(matches!(&err, RawError::Unsupported(m) if m.contains("tile-compressed")), "{err}"); + // an empty primary alone + let err = crate::probe_info(&empty).unwrap_err(); + assert!(matches!(&err, RawError::Unsupported(m) if m.contains("hold no image")), "{err}"); + } + + #[test] + fn variants_we_refuse_say_why() { + let refused = |cards: &[String], data: &[u8], why: &str| { + let err = crate::decode(&with_data(unit(cards), data)).unwrap_err(); + assert!(matches!(&err, RawError::Unsupported(m) if m.contains(why)), "{why}: {err}"); + let err = crate::probe_info(&with_data(unit(cards), data)).unwrap_err(); + assert!(matches!(&err, RawError::Unsupported(m) if m.contains(why)), "{why}: {err}"); + }; + let axes = |naxis: i64, lengths: &[u32]| { + let mut cards = vec![card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", naxis)]; + cards.extend(lengths.iter().enumerate().map(|(i, l)| kw(&format!("NAXIS{}", i + 1), l))); + cards + }; + refused(&axes(1, &[4]), &[0; 4], "one axis"); + refused(&axes(4, &[2, 2, 1, 1]), &[0; 4], "4 axes"); + refused(&axes(3, &[2, 2, 2]), &[0; 8], "2 planes"); + refused(&axes(3, &[2, 2, 4]), &[0; 16], "4 planes"); + refused(&axes(3, &[2, 2, 1000]), &[0; 4000], "1000 planes"); + for (bitpix, why) in [(64, "64-bit"), (12, "12 bits"), (0, "0 bits"), (-16, "-16 bits"), (1, "1 bits")] { + let mut cards = image(2, 2, bitpix); + cards.push(kw("BZERO", 0)); + refused(&cards, &[0; 16], why); + } + refused(&[card("SIMPLE = F"), kw("BITPIX", 8), kw("NAXIS", 0)], &[], "SIMPLE = F"); + refused(&plus(image(2, 2, 16), &[kw("GROUPS", "T")]), &[0; 8], "random-groups"); + // scaling that leaves nothing above black + for scale in [kw("BZERO", -32768), kw("BSCALE", 0), kw("BSCALE", -1)] { + refused(&plus(image(2, 2, 16), &[scale]), &[0; 8], "no positive sample"); + } + // a NaN scaling card is one the file does not state: the default applies + let scaled = plus(image(2, 2, 16), &[kw("BZERO", "NaN")]); + assert!(crate::decode(&with_data(unit(&scaled), &u16s(&[0; 4]))).is_ok()); + // a corrupt header + let corrupt = |cards: &[String], data: &[u8]| { + let err = crate::decode(&with_data(unit(cards), data)).unwrap_err(); + assert!(matches!(&err, RawError::Corrupt(m) if m.starts_with("FITS: ")), "{err}"); + }; + corrupt(&axes(2, &[0, 3]), &[0; 8]); + corrupt(&axes(2, &[2, 0]), &[0; 8]); + corrupt(&axes(999, &[2, 2]), &[0; 8]); + corrupt(&axes(-1, &[]), &[0; 8]); + corrupt(&[card("SIMPLE = T"), kw("BITPIX", 16), card("NAXIS = 2.0")], &[0; 8]); + corrupt(&[card("SIMPLE = T"), kw("NAXIS", 2), kw("NAXIS1", 2), kw("NAXIS2", 2)], &[0; 8]); + corrupt(&[card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", 2), kw("NAXIS1", 2)], &[0; 8]); + corrupt(&[card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", "TWO")], &[0; 8]); + corrupt(&[card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", 1000)], &[0; 8]); + corrupt(&[card("SIMPLE = T"), kw("BITPIX", 16), kw("NAXIS", 2), kw("NAXIS1", -2), kw("NAXIS2", 2)], &[0; 8]); + // an extension whose data size cannot be walked + let mut f = unit(&[card("SIMPLE = T"), kw("BITPIX", 8), kw("NAXIS", 0), kw("EXTEND", "T")]); + f.extend_from_slice(&unit(&[text("XTENSION", "BINTABLE"), kw("BITPIX", 8), kw("NAXIS", 1), kw("NAXIS1", 2), kw("PCOUNT", -1)])); + assert!(matches!(crate::decode(&f).unwrap_err(), RawError::Corrupt(_))); + // the data shorter than the header says (not padded to whole blocks here, as the builder does) + let mut short = unit(&image(2, 2, 16)); + short.extend_from_slice(&[0; 7]); + assert!(matches!(crate::decode(&short).unwrap_err(), RawError::Corrupt(_))); + // a file that is not FITS + assert_eq!(header(b"Not a FITS file at all").unwrap_err(), RawError::NotRaw); + } + + #[test] + fn hostile_files_are_errors() { + let good = small(); + assert!(crate::decode(&good).is_ok()); + // every truncation + for cut in 0..good.len() { + let _ = crate::decode(&good[..cut]); + let _ = crate::probe_info(&good[..cut]); + } + // the data without its block padding, or a byte short + let bare = good.len() - BLOCK + 8; + assert!(crate::decode(&good[..bare]).is_ok(), "the padding may be missing"); + assert!(crate::decode(&good[..bare - 1]).is_err()); + // every byte of the header, set to a few hostile values + for i in 0..BLOCK { + for v in [0u8, 0xff, 0x80, b'/', b'\'', b'=', b'-'] { + let mut f = good.clone(); + f[i] = v; + let _ = crate::decode(&f); + let _ = crate::probe_info(&f); + } + } + // dimensions that would need more memory than there is + for (w, h) in [(2_000_000_000u32, 2_000_000_000u32), (65_536, 65_536), (u32::MAX, 1), (1, u32::MAX), (0, 0)] { + let f = with_data(unit(&image(w, h, 16)), &[0; 64]); + let err = crate::decode(&f).unwrap_err(); + assert!(matches!(err, RawError::Corrupt(_) | RawError::Limit(_)), "{w} x {h}: {err}"); + } + // a header that never ends + let simple = card("SIMPLE = T"); + let comments = card("COMMENT no end in sight"); + let endless = [simple.as_str(), &comments.repeat(BLOCK / CARD * 2 - 1)].concat(); + assert!(matches!(crate::decode(endless.as_bytes()), Err(RawError::Corrupt(_)))); + let endless = [simple.as_str(), &comments.repeat(BLOCK / CARD * (4096 + 1))].concat(); + assert!(matches!(crate::decode(endless.as_bytes()), Err(RawError::Limit(_)))); + // more header units without an image than are walked + let empty = unit(&[card("SIMPLE = T"), kw("BITPIX", 8), kw("NAXIS", 0), kw("EXTEND", "T")]); + let mut f = empty.clone(); + let table = unit(&[text("XTENSION", "BINTABLE"), kw("BITPIX", 8), kw("NAXIS", 0)]); + for _ in 0..MAX_UNITS { + f.extend_from_slice(&table); + } + let err = crate::decode(&f).unwrap_err(); + assert!(matches!(&err, RawError::Unsupported(m) if m.contains("hold no image")), "{err}"); + // a unit whose data runs past the end of the file, then a unit header after it + let mut f = empty.clone(); + f.extend_from_slice(&unit(&[text("XTENSION", "IMAGE"), kw("BITPIX", 32), kw("NAXIS", 2), kw("NAXIS1", u32::MAX), kw("NAXIS2", 2)])); + assert!(crate::decode(&f).is_err()); + let mut f = empty; + f.extend_from_slice(&unit(&[text("XTENSION", "BINTABLE"), kw("BITPIX", 32), kw("NAXIS", 2), kw("NAXIS1", u32::MAX), kw("NAXIS2", u32::MAX)])); + f.resize(f.len() + BLOCK, 0); + assert!(crate::decode(&f).is_err()); + // a card that is not text is skipped, not read + let mut f = small(); + let at = BLOCK - CARD * 2; + f[at] = 0xff; + assert!(crate::decode(&f).is_ok()); + // repeated keywords: the first one counts + let mut cards = image(2, 2, 16); + cards.extend([kw("BZERO", 32768), kw("NAXIS1", 1), kw("BZERO", 0)]); + let img = crate::decode(&with_data(unit(&cards), &u16s(&[0; 4]))).unwrap(); + assert_eq!((img.width, img.white.as_slice()), (2, [65535.0].as_slice())); + } +} diff --git a/crates/raw/src/vendor/mod.rs b/crates/raw/src/vendor/mod.rs index dbfdc08a5f..c366fce5b2 100644 --- a/crates/raw/src/vendor/mod.rs +++ b/crates/raw/src/vendor/mod.rs @@ -17,6 +17,7 @@ pub mod crw; pub mod crx; pub(crate) mod crx_wavelet; pub mod erf; +pub mod fits; pub(crate) mod hasselblad; pub mod kodak; pub mod mef; diff --git a/crates/raw/tests/fuzz_target.rs b/crates/raw/tests/fuzz_target.rs index bc6165607e..2330369d8d 100644 --- a/crates/raw/tests/fuzz_target.rs +++ b/crates/raw/tests/fuzz_target.rs @@ -1,4 +1,4 @@ -//! Fuzz target `raw` (`cargo xtask fuzz raw`): mutated DNGs (uncompressed, LJ92, lossy) and corpus raws +//! Fuzz target `raw` (`cargo xtask fuzz raw`): mutated DNGs (uncompressed, LJ92, lossy), a FITS file and corpus raws //! through probe, preview, decode and a small develop. A short run in `cargo test`; time-boxed long runs //! under `LCC_FUZZ_SECS` (see `lcc-fuzzkit`). Crash inputs go into `tests/it/robust.rs`'s tables. @@ -30,6 +30,27 @@ fn sample(comp: DngCompression) -> Vec { lcc_raw::write_dng(&raw, &DngWriteOptions { compression: comp, ..Default::default() }).unwrap() } +/// A 16-bit FITS colour filter array (issue #1604): one header block with the cards a mutation can reach, then +/// the samples. +fn fits() -> Vec { + let (w, h) = (8usize, 6usize); + let kw = |name: &str, value: i32| format!("{:<80}", format!("{name:<8}= {value:>20}")); + let cards = [ + format!("{:<80}", "SIMPLE = T"), + kw("BITPIX", 16), + kw("NAXIS", 2), + kw("NAXIS1", w as i32), + kw("NAXIS2", h as i32), + kw("BZERO", 32768), + format!("{:<80}", "BAYERPAT= 'RGGB '"), + ]; + let mut out: Vec = cards.iter().flat_map(|c| c.as_bytes().iter().copied()).collect(); + out.extend_from_slice(b"END"); + out.resize(2880, b' '); + out.extend((0..w * h).flat_map(|i| (((i * 997 % 60000 + 500) as i32 - 32768) as i16).to_be_bytes())); + out +} + #[test] fn fuzz_target() { let seeds = [ @@ -37,10 +58,11 @@ fn fuzz_target() { sample(DngCompression::Lj92 { tile: 16 }), sample(DngCompression::LossyJpeg { tile: 16, quality: 80, long_edge: None }), b"II*\0\x10\0\0\0CR\x02\0".to_vec(), + fits(), ]; let exts = [ "dng", "cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef", "srw", "3fr", "iiq", "x3f", "erf", "mos", "kdc", - "dcr", "mrw", "gpr", + "dcr", "mrw", "gpr", "fits", ]; lcc_fuzzkit::run_target("raw", &seeds, &exts, 300, |bytes| { let _ = lcc_raw::probe(bytes); diff --git a/crates/raw/tests/it/vendor_robust.rs b/crates/raw/tests/it/vendor_robust.rs index f1a08bc19d..44f7c60977 100644 --- a/crates/raw/tests/it/vendor_robust.rs +++ b/crates/raw/tests/it/vendor_robust.rs @@ -1,4 +1,5 @@ -//! Malformed vendor raw files (NEF, ARW, PEF, ORF, RW2 of every raw format, CR2, RAF) must decode to an error, never panic. +//! Malformed vendor raw files (NEF, ARW, PEF, ORF, RW2 of every raw format, CR2, RAF, FITS) must decode to an error, +//! never panic. use lcc_tiff::tags as t; use lcc_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; @@ -231,6 +232,77 @@ fn raf() -> Vec { raf_file(W, H, 16, strip, Some(layout), b"\xff\xd8\xff\xd9") } +/// A FITS file (issue #1604): `cards` each 80 columns, `END`, then big-endian `data`, in 2880-byte blocks. +fn fits(cards: &[String], data: &[u8]) -> Vec { + let mut out: Vec = cards.iter().flat_map(|c| c.as_bytes().iter().copied()).collect(); + out.extend_from_slice(b"END"); + out.resize(out.len().div_ceil(2880) * 2880, b' '); + out.extend_from_slice(data); + out.resize(out.len().div_ceil(2880) * 2880, 0); + out +} + +/// A FITS card: 80 columns, as the standard asks (`kw`: a keyword and a right-justified numeric value). +fn fits_card(text: &str) -> String { + format!("{text:<80}") +} + +fn fits_kw(name: &str, value: i32) -> String { + fits_card(&format!("{name:<8}= {value:>20}")) +} + +/// The cards an image header starts with (`NAXIS1` is the width). +fn fits_image(bitpix: i32, axes: &[u32]) -> Vec { + let mut cards = vec![fits_card("SIMPLE = T"), fits_kw("BITPIX", bitpix), fits_kw("NAXIS", axes.len() as i32)]; + cards.extend(axes.iter().enumerate().map(|(i, n)| fits_kw(&format!("NAXIS{}", i + 1), *n as i32))); + cards +} + +/// FITS images: a 16-bit unsigned colour filter array with an offset and its rows bottom first, a signed 16-bit +/// monochrome one, 32-bit floats in three colour planes, 8-bit samples with a scale, and an image behind an empty +/// primary header. +fn fits_files() -> Vec> { + let n = (W * H) as usize; + let file = |bitpix: i32, axes: &[u32], extra: &[String], data: Vec| { + let mut cards = fits_image(bitpix, axes); + cards.extend_from_slice(extra); + fits(&cards, &data) + }; + let floats = || (0..n).flat_map(|i| (i as f32 / 97.0 - 0.5).to_be_bytes()).collect::>(); + vec![ + file( + 16, + &[W, H], + &[fits_kw("BZERO", 32768), fits_card("BAYERPAT= 'RGGB '"), fits_kw("XBAYOFF", 1), fits_card("ROWORDER= 'BOTTOM-UP'")], + (0..n).flat_map(|i| (((i * 397 % 60000 + 500) as i32 - 32768) as i16).to_be_bytes()).collect(), + ), + file(16, &[W, H], &[], (0..n).map(|i| i as i16 - 100).flat_map(|v| v.to_be_bytes()).collect()), + file(-32, &[W, H, 3], &[], floats().into_iter().chain(floats()).chain(floats()).collect()), + file(8, &[W, H], &[fits_kw("BSCALE", 2), fits_kw("BZERO", 10)], (0..n).map(|i| (i * 37 % 251) as u8).collect()), + ] + .into_iter() + .chain([behind_empty_primary()]) + .collect() +} + +/// A FITS file whose primary header has no data, its image in the first `IMAGE` extension. +fn behind_empty_primary() -> Vec { + let mut image = vec![fits_card("XTENSION= 'IMAGE '")]; + image.extend(fits_image(-32, &[W, H]).into_iter().skip(1)); + let mut out = fits( + &[fits_card("SIMPLE = T"), fits_kw("BITPIX", 8), fits_kw("NAXIS", 0), fits_card("EXTEND = T")], + &[], + ); + let data: Vec = (0..n_of(W, H)).flat_map(|i| (i as f32 / 300.0).to_be_bytes()).collect(); + out.extend_from_slice(&fits(&image, &data)); + out +} + +/// How many samples a `w × h` image holds. +fn n_of(w: u32, h: u32) -> usize { + (w * h) as usize +} + fn samples() -> Vec> { vec![ cfa_tiff("NIKON CORPORATION", 1, 12, ByteOrder::Big), @@ -251,9 +323,24 @@ fn samples() -> Vec> { ] .into_iter() .chain(rw2_formats()) + .chain(fits_files()) .collect() } +/// How many files [`samples`] holds: the range the mutation test chooses from. +const SAMPLES: usize = 25; + +/// The FITS samples decode as they are, so the mutations above reach each of the FITS decoder's sample readers; and +/// the count is what the mutation test chooses from (the older samples include files no decoder reads). +#[test] +fn fits_samples_decode_unmutated() { + assert_eq!(samples().len(), SAMPLES); + for s in fits_files() { + let img = lcc_raw::decode(&s).unwrap(); + assert_eq!((img.width, img.height), (W as usize, H as usize)); + } +} + /// One RW2 per encoding with a sample decoder of its own (formats 4, 6 at 14 and 12 bits, 8, and 16-bit words). fn rw2_formats() -> Vec> { vec![ @@ -290,7 +377,7 @@ proptest! { #![proptest_config(ProptestConfig { cases: 2000, .. ProptestConfig::default() })] #[test] - fn mutated_vendor_files_never_panic(kind in 0usize..20, flips in proptest::collection::vec((any::(), any::()), 1..16), cut in any::()) { + fn mutated_vendor_files_never_panic(kind in 0usize..SAMPLES, flips in proptest::collection::vec((any::(), any::()), 1..16), cut in any::()) { let mut data = samples().swap_remove(kind); let n = data.len(); for (i, v) in flips { diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index 0cdfd63d26..838733807a 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -2,7 +2,8 @@ name = "lcc-segment" version.workspace = true edition.workspace = true -license = "Apache-2.0 OR GPL-3.0-or-later" +# The project distribution is GPL-3.0-or-later; Apache-2.0 portions keep their notices (NOTICE). +license = "GPL-3.0-or-later OR Apache-2.0" description = "Segmentation: SAM 3 (Segment Anything with Concepts) inference in pure Rust (L3)" [lints] diff --git a/crates/slideshow/src/compose.rs b/crates/slideshow/src/compose.rs index 6ea02cd2b1..89ca02bf98 100644 --- a/crates/slideshow/src/compose.rs +++ b/crates/slideshow/src/compose.rs @@ -252,6 +252,9 @@ pub fn compose_with( }); } behind(&mut out, &l); + if !has_photo { + return (out, l); + } // cast shadow: a blurred rectangle (separable: the product of two blurred steps) if let Some((r, sigma)) = l.shadow { let op = s.shadow_opacity as f32; @@ -273,9 +276,7 @@ pub fn compose_with( if l.frame != l.visible { fill(&mut out, &l.frame, s.stroke_color); } - if has_photo { - draw_image(&mut out, photo, &l.photo, &l.cell, 1.0); - } + draw_image(&mut out, photo, &l.photo, &l.cell, 1.0); (out, l) } @@ -487,6 +488,24 @@ mod tests { assert_eq!(px(&img, 100, 50), GREEN, "and the photo covers it"); } + #[test] + fn an_empty_photo_draws_the_backdrop_without_a_frame() { + let s = SlideSettings { + backdrop_color: RED, + margin_left: 0.25, + stroke_border: true, + stroke_color: GREEN, + stroke_width: 0.05, + cast_shadow: true, + shadow_opacity: 1.0, + ..SlideSettings::default() + }; + let mut drew_behind = false; + let (img, _) = compose_with(&Rgba8::new(0, 0), None, &s, 40, 24, &mut |_, _| drew_behind = true); + assert!(drew_behind); + assert!(img == solid(40, 24, RED), "photo effects changed the backdrop"); + } + #[test] fn hostile_input_never_panics() { let wild = SlideSettings { diff --git a/crates/surface/src/loupedeck.rs b/crates/surface/src/loupedeck.rs index 28bb1f295f..066544f271 100644 --- a/crates/surface/src/loupedeck.rs +++ b/crates/surface/src/loupedeck.rs @@ -390,7 +390,7 @@ pub fn map_action(action: &str, preset: &dyn Fn(&str) -> Option) -> Mapp "MoveToNextPhoto" | "SelectRight" | "MoveRight" => c("library.next"), "MoveToPreviousPhoto" | "SelectLeft" | "MoveLeft" => c("library.previous"), "SelectAll" => c("library.selectAll"), - "DeselectOtherPhotos" | "SelectNone" => c("library.selectNone"), + "SelectNone" => c("library.selectNone"), "ToggleZoomView" => c("view.zoomToggle"), "ZoomIn" => c("view.zoomIn"), "ZoomOut" => c("view.zoomOut"), diff --git a/crates/tflite/Cargo.toml b/crates/tflite/Cargo.toml index 3a808a3940..729a700262 100644 --- a/crates/tflite/Cargo.toml +++ b/crates/tflite/Cargo.toml @@ -2,7 +2,8 @@ name = "lcc-tflite" version.workspace = true edition.workspace = true -license = "Apache-2.0" +# The project distribution is GPL-3.0-or-later; the Apache-2.0 provenance notices remain in NOTICE. +license = "GPL-3.0-or-later OR Apache-2.0" description = "A small, bounded TensorFlow Lite interpreter in pure Rust for the MediaPipe models, and their pre/post-processing (L1)" [lints] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index e332a84264..6bf982ffa4 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -68,8 +68,8 @@ lcc-faces = { workspace = true } lcc-merge = { workspace = true } # the update tests offer a release the way a check would (native only, like the updater itself) lcc-updater = { workspace = true } -filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } wat = "1.228" # G19: a slow export-hook plug-in for the worker test # the Plug-in Manager test lists a module that didn't load lcc-plugins = { workspace = true } diff --git a/crates/ui-egui/locales/fork/cs-formats.json b/crates/ui-egui/locales/fork/cs-formats.json index 9ee839bc69..4ed318e0f5 100644 --- a/crates/ui-egui/locales/fork/cs-formats.json +++ b/crates/ui-egui/locales/fork/cs-formats.json @@ -127,6 +127,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Jeho manifest obsahuje hodnoty, které tato verze nemůže použít, a proto je vynechává: {values}", "JPEG quality {q} to fit the size limit": "Kvalita JPEG {q}, aby se soubor vešel do limitu velikosti", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Kvalita JPEG {q}, aby se soubor vešel do limitu velikosti (menší rozměr nebo vyšší limit zachová více kvality)", + "Kept with {raw} as its companion: not a photo of its own.": "Uchováno s {raw} jako doprovod: není to samostatná fotografie.", "Kept. Groups left: {left}": "Ponecháno. Zbývá skupin: {left}", "Key from the environment variable {}": "Klíč z proměnné prostředí {}", "Key saved ({})": "Klíč uložen ({})", @@ -345,6 +346,7 @@ "{} fixed: {} known for camera {}, {} found in this photo": "Opraveno: {}; známých pro fotoaparát: {} ({}), nalezených na této fotce: {}", "{} keys": "Klávesy pro {}", "{} spot(s) from Remove Dust (outlined in amber)": "Smítka z Odstranění prachu: {} (jantarově ohraničená)", + "· {companions} kept with their RAWs": "· {companions} ponechány se svými RAW", "“{name}” added to Camera Profiles": "„{name}“ přidán do profilů fotoaparátu", "“{name}” has its old settings again": "„{name}“ má opět původní nastavení", "“{name}” is new. What may the other devices syncing this catalog have of it?": "„{name}“ je nová. Co z ní smějí mít ostatní zařízení synchronizující tento katalog?", diff --git a/crates/ui-egui/locales/fork/cs.json b/crates/ui-egui/locales/fork/cs.json index 992a1e5244..2e45a5b2b0 100644 --- a/crates/ui-egui/locales/fork/cs.json +++ b/crates/ui-egui/locales/fork/cs.json @@ -41,6 +41,7 @@ "6 Blades": "6 lamel", "8 bits/component": "8 bitů na složku", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} přijato, {pending} k posouzení, {rejected} odmítnuto", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "JPEG se stejným názvem jako surový soubor vedle něj je jeho doprovod: jedna fotografie, jedno skenování obličejů, jedna sada metadat. Chcete-li importovat JPEG jako samostatné fotografie, odškrtněte volbu doprovodů.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Je čas zálohovat katalog. Zálohovat jej teď, před ukončením aplikace {app}?", "A camera profile is being built": "Vytváří se profil fotoaparátu", "A camera profile is for one camera: use a photo from the same camera body.": "Profil fotoaparátu platí pro jeden fotoaparát: použijte fotografii ze stejného těla.", @@ -104,6 +105,7 @@ "Add Blank": "Přidat prázdnou", "Add Cell": "Přidat buňku", "Add Column": "Přidat sloupec", + "Add Editor": "Přidat editor", "Add Face Region": "Přidat oblast obličeje", "Add Filter…": "Přidat filtr…", "Add Folder": "Přidat složku", @@ -254,6 +256,7 @@ "Assign to Someone Else…": "Přiřadit někomu jinému…", "Assign to…": "Přiřadit k…", "At Import": "Při importu", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Při importu není JPEG se stejným názvem jako surový soubor vedle něj samostatnou fotografií, ale jeho doprovodem: jedna miniatura, jedno skenování obličejů, jedna sada metadat. Při kopírování, přesunu či přejmenování putuje se surovým souborem.", "At launch": "Při spuštění", "At most one request per second.": "Nejvýše jeden požadavek za sekundu.", "Attribution (shown on the map)": "Uvedení zdroje (zobrazeno na mapě)", @@ -310,6 +313,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Mezi oběma si fotografie ponechá svůj příznak (bez příznaku zůstane bez něj).", "Big steps": "Velké kroky", "Bit Depth": "Bitová hloubka", + "Bit Level": "Bitová hloubka", "Black": "Černá", "Black Point Compensation": "Kompenzace černého bodu", "Blank": "Prázdné", @@ -365,7 +369,9 @@ "Brush Flow": "Tok štětce", "Brush Refinement": "Doladění štětcem", "Brush Size": "Velikost štětce", + "Build Face Thumbnails": "Vytvořit miniatury obličejů", "Build at import": "Vytvářet při importu", + "Building face thumbnails": "Vytváření miniatur obličejů", "Building the profile…": "Vytváření profilu…", "Built in the background once the photos are in, from the one on screen outward.": "Vytváří se na pozadí, jakmile jsou fotografie v knihovně, od té na obrazovce směrem ven.", "Built-in (lcc-raw)": "Vestavěný (lcc-raw)", @@ -513,6 +519,7 @@ "Choose folder later": "Vybrat složku později", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Vyberte vzhled aplikace. Každá změna se projeví hned; více najdete v Nastavení → Rozhraní.", "Choose in Sync…": "Vybrat v Synchronizaci…", + "Choose the Editor's Program": "Zvolit program editoru", "Choose the catalog to open.": "Vyberte katalog, který chcete otevřít.", "Choose where to import from": "Vyberte, odkud importovat", "Circle": "Kruh", @@ -606,6 +613,7 @@ "Color to Replace": "Barva k nahrazení", "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "Barvy odpovídají terči; každá si ponechá světlost zaznamenanou fotoaparátem. Pro lidi a běžné fotografie.", "Colour Profile": "Barevný profil", + "Colour Space": "Barevný prostor", "Colour space of the TIFF": "Barevný prostor TIFF", "Colours are #RRGGBB.": "Barvy se zadávají jako #RRGGBB.", "Column of Three": "Sloupec tří", @@ -622,13 +630,15 @@ "Compact Cells": "Kompaktní buňky", "Compact Layout": "Kompaktní rozvržení", "Compact – Dense": "Kompaktní – husté", + "Companion": "Doprovod", + "Companion JPEG:": "Doprovodný JPEG:", "Compare Group in Survey": "Porovnat skupinu v Přehledu", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Hotovo", "Compression (quality scan)": "Komprese (sken kvality)", "Compression artifacts": "Artefakty komprese", "Computing AI masks": "Výpočet AI masek", - "Confidence required": "Požadovaná jistota", + "Confidence required": "Požadovaná spolehlivost", "Confirm": "Potvrdit", "Confirm Dialog": "Potvrdit dialogové okno", "Confirm Faces from Immich": "Potvrdit obličeje z Immich", @@ -972,6 +982,8 @@ "Edit at History Step": "Upravit v kroku historie", "Edit date": "Datum úpravy", "Edit in (one item)": "Upravit v (jedna položka)", + "Edit in Default Editor": "Upravit ve výchozím editoru", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Upravit v jiném editoru (⌥⌘E) otevře kopii v této aplikaci (název aplikace na macOS, cesta programu jinde). Je-li místo prázdné, otevře ji výchozí aplikace systému.", "Edit this saved location": "Upravit toto uložené místo", "Edit: Color": "Úpravy: Barva", "Edit: Detail": "Úpravy: Detail", @@ -981,6 +993,7 @@ "Edit: Optics": "Úpravy: Optika", "Edited Version Saved Again": "Upravená verze znovu uložena", "Editing": "Úpravy", + "Editors": "Editory", "Edit…": "Upravit…", "Elsewhere": "Jinde", "Email": "E-mail", @@ -1268,6 +1281,7 @@ "Forget Remembered Object": "Zapomenout zapamatovaný objekt", "Forget This Person": "Zapomenout tuto osobu", "Forget a Paired Surface": "Zapomenout spárované zařízení", + "Format Options": "Volby formátu", "Four with Caption": "Čtyři s popiskem", "Frame": "Snímek", "Frame Rate": "Snímková frekvence", @@ -1395,6 +1409,7 @@ "Hard Drive": "Pevný disk", "Hardcover": "Pevná vazba", "Has a GPS position (click to show it on the map)": "Má polohu GPS (kliknutím ji zobrazíte na mapě)", + "Has a companion JPEG (click to open the Info panel)": "Má doprovodný JPEG (kliknutím otevřete panel informací)", "Headline metadata": "Metadata titulku", "Headroom": "Rezerva HDR", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Retušuje malé tmavé nebo červené skvrny na pleti obličejů; oči, obočí, nosní dírky a rty zůstanou beze změny", @@ -1422,7 +1437,7 @@ "Hide this wheel's effect": "Skrýt účinek tohoto kola", "High Range": "Horní rozsah", "High quality adjustment previews": "Náhledy úprav ve vysoké kvalitě", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Vyšší jistota najde méně falešných tváří, ale může přehlédnout skutečné. Platí pro budoucí detekce; pro aktualizaci stávajících spusťte nové prohledání.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Vyšší spolehlivost najde méně falešných obličejů, ale může přehlédnout skutečné. Vztahuje se na budoucí detekce; existující aktualizujete novým skenem.", "Highlight Hue": "Odstín světel", "Highlight Luminance": "Jas světel", "Highlight Reconstruction": "Rekonstrukce světel", @@ -1520,6 +1535,7 @@ "Import Lightroom or Capture One Catalog…": "Importovat katalog Lightroom nebo Capture One…", "Import Metadata Presets": "Importovat přednastavení metadat", "Import New Shots": "Importovat nové snímky", + "Import Order": "Pořadí importu", "Import People": "Importovat osoby", "Import People from Immich": "Importovat osoby z Immich", "Import Photos and Video…": "Importovat fotografie a video…", @@ -1598,6 +1614,7 @@ "Install the plugin": "Nainstalovat plugin", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Nainstalujte vlastní model ONNX se souborem denoise-model.json vedle něj. Toto sestavení stahování modelů nenabízí.", "Installed": "Nainstalováno", + "Installed editors…": "Nainstalované editory…", "Installed in": "Nainstalováno v", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Instalací nic z toho nepovolíte: zásuvný modul se zeptá, až bude dané oprávnění poprvé potřebovat.", "Installing the surface plugin": "Instalace pluginu ovládacího zařízení", @@ -1700,6 +1717,7 @@ "Large Landscape (13 × 11 in)": "Velká na šířku (13 × 11 in)", "Large and Small": "Velká a malá", "Large image size": "Velká velikost obrázku", + "Largest Face": "Největší obličej", "Last Photo": "Poslední fotografie", "Last backup:": "Poslední záloha:", "Last checked 1 hour ago": "Naposledy zkontrolováno před 1 h", @@ -1712,6 +1730,7 @@ "Last synced on {}": "Naposledy synchronizováno {}", "Last synced {} h ago": "Naposledy synchronizováno před {} h", "Last synced {} min ago": "Naposledy synchronizováno před {} min", + "Launch Options": "Volby spuštění", "Layout Image Off": "Obrázek rozložení vypnut", "Layout Image On": "Obrázek rozložení zapnut", "Layout Style": "Styl rozložení", @@ -2018,6 +2037,7 @@ "New Template Folder": "Nová složka šablon", "New Web Template Folder": "Nová složka šablon webu", "New collections": "Nové kolekce", + "New editor": "Nový editor", "New group name": "Název nové skupiny", "New group:": "Nová skupina:", "New location name": "Název nového místa", @@ -2027,6 +2047,7 @@ "New preset…": "Nové přednastavení…", "New red eye correction (Return adds it here)": "Nová korekce červených očí (Return ji zde přidá)", "New shots:": "Nové snímky:", + "Newest First": "Nejnovější první", "Next": "Další", "Next Filmstrip Background": "Další pozadí filmového pásu", "Next Frame": "Další snímek", @@ -2188,6 +2209,7 @@ "Offset Hue": "Odstín offset", "Offset Luminance": "Jas offset", "Offset Saturation": "Sytost offset", + "Oldest First": "Nejstarší první", "On": "Zapnuto", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "U naskenovaného negativu nebo diapozitivu: najde a vyretušuje prachová zrnka, vlasy a škrábance na filmu. Infračervený průchod skeneru (soubor RGBI z VueScanu nebo SilverFastu) říká, kde jsou; jinak se prohledávají hladké plochy obrazu", "On photo": "Na fotografii", @@ -2259,6 +2281,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "Volitelné: fotografie terče pod jiným světlem, např. žárovkovým, vytvoří profil se dvěma osvětleními.", "Optional: where downloads go": "Volitelné: kam se ukládají stažené soubory", "Orientation Detection Status": "Stav zjišťování orientace", + "Original (+XMP)": "Originál (+XMP)", "Original Photo": "Původní fotografie", "Other": "Jiné", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Jiné aplikace pak uvidí vaše hodnocení, klíčová slova a úpravy. Vedle každé fotky se zapíše malý soubor.", @@ -2340,6 +2363,7 @@ "Permissions": "Oprávnění", "Permissions:": "Oprávnění:", "Persistent": "Trvalé", + "Person Sort": "Řazení osoby", "Personalize {app} with your own branding elements.": "Přizpůsobte si {app} vlastními prvky značky.", "Personalized": "Přizpůsobené", "Phone": "Telefon", @@ -2353,6 +2377,7 @@ "Photo with Side Text": "Fotografie s bočním textem", "Photo with Title": "Fotografie s nadpisem", "Photo zoom": "Zvětšení fotografií", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Fotografie → Upravit v uvádí zde každý editor. První dva jsou vestavěné; přidejte jich, kolik chcete, a klikněte na řádek, abyste změnili, co předává.", "Photograph Information": "Informace o fotografii", "Photographic": "Fotografické", "Photos affected": "Dotčené fotografie", @@ -3277,6 +3302,7 @@ "Text Page": "Textová stránka", "Text Style Preset": "Přednastavení stylu textu", "Text size": "Velikost textu", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "JPEG vedle surového souboru, který zůstává s ním: není to samostatná fotografie.", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console se s aplikací {app} propojuje přes plugin {app} pro Logi Options+. Instalace předá plugin do Logi Options+, který vás požádá o potvrzení.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Správce profilů zobrazuje všechny vzhledy, profily LUT a profily fotoaparátů: můžete je skrýt z nabídek, přejmenovat a seskupit, importovat nové a odstranit vlastní.", "The account has no PIN or password, so there is nothing to unlock.": "Účet nemá kód PIN ani heslo, takže není co odemykat.", @@ -3489,6 +3515,7 @@ "Tracklog": "Záznam trasy", "Transform": "Transformace", "Trash renders taken out of a collection": "Přesunout do koše vykreslené soubory vyjmuté z kolekce", + "Treat JPEGs next to raw files as companions": "Považovat JPEG vedle surových souborů za doprovodné", "Trim": "Zkrátit", "Trim End": "Zkrátit konec", "Trim Start": "Zkrátit začátek", @@ -3578,6 +3605,7 @@ "Update this one automatically": "Aktualizovat tento modul automaticky", "Update to Current Process Version": "Aktualizovat na aktuální verzi procesu", "Update with Current Settings…": "Aktualizovat podle aktuálního nastavení…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Aktualizace jsou vypnuté (je nastaveno {env}_DISABLE_UPDATES); aktualizace obstarává správce balíčků.", "Updates the installed version": "Aktualizuje nainstalovanou verzi", "Updates…": "Aktualizace…", "Updating the DNG previews stopped unexpectedly": "Aktualizace náhledů DNG se neočekávaně zastavila", @@ -3710,6 +3738,7 @@ "Wrong passphrase.": "Nesprávné heslo.", "Wrote {} XMP sidecars": "Zapsané přidružené soubory XMP: {}", "X": "X", + "XMP Sidecar": "Sidecar XMP", "XMP Sidecars": "Přidružené soubory XMP", "Y": "Y", "Yellow Label": "Žlutý štítek", @@ -3748,9 +3777,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` se souborem samotné knihovny (`catalog.snap`) otevře její složku, místo aby selhal s chybou", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (a nástroje MCP, které přijímají složky) nyní načítá i HEIC, HEIF a Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` zapisuje varování také na stderr (issue #168); `{env}_LOG` nebo `RUST_LOG` zvolí jinou úroveň.", + "a copy of the original": "kopie originálu", + "a copy of the original, with an XMP sidecar": "kopie originálu, se sidecarem XMP", "a photo matches any group": "fotka odpovídá kterékoli skupině", "a photo matches every group": "fotka odpovídá každé skupině", "a word per topic; every word must match": "jedno slovo na téma; všechna slova se musí shodovat", + "adds an editor; click its row to name it and choose its program and file": "přidá řádek; klikněte na něj, abyste editor pojmenovali a zvolili jeho program a soubor", "all of": "všechny z", "allowed": "povoleno", "any of": "libovolné z", @@ -3833,17 +3865,23 @@ "published": "publikováno", "removed": "odebráno", "role": "role", + "scene-linear Rec. 2020": "lineární Rec. 2020", "selected photos": "vybrané fotografie", "shots": "snímků", "steps": "kroků", "the active photo isn't a video": "aktivní fotografie není video", + "the arguments before the file; `{file}` places the file's path where it stands": "argumenty před souborem; `{file}` vloží cestu souboru na toto místo", "the camera roll could not be read": "složku fotoaparátu nelze přečíst", + "the file's own": "jako v souboru", "the folder shown": "zobrazená složka", "the folder shown (no folder is: pick one first)": "zobrazená složka (žádná: nejprve ji vyberte)", "the frames could not be matched to each other": "snímky se nepodařilo navzájem přiřadit", "the measured positions were less reliable than the camera's own pattern": "změřené polohy byly méně spolehlivé než vlastní vzor fotoaparátu", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "výchozí aplikace systému pro typ souboru: „Upravit ve výchozím editoru“ vytvoří kopii a předá ji", + "the original, with an XMP sidecar": "originál, se sidecarem XMP", "the photos in view": "fotografie v zobrazení", "the plug-in worker stopped unexpectedly": "pracovní vlákno zásuvného modulu se nečekaně zastavilo", + "the raw data's own": "jako v surových datech", "the selected photos": "vybrané fotografie", "the whole catalog": "celý katalog", "there was not enough memory for the registered merge": "pro registrované sloučení nebylo dost paměti", @@ -3862,6 +3900,7 @@ "video playback isn't available in this build": "přehrávání videa není v této verzi dostupné", "waiting for Apple Photos": "čeká na Apple Photos", "width": "šířka", + "write the edits beside the file": "zapisuje úpravy vedle souboru", "{app}": "{app}", "{app} Export Presets": "Předvolby exportu {app}", "{app} Metadata Presets": "Předvolby metadat {app}", diff --git a/crates/ui-egui/locales/fork/de-formats.json b/crates/ui-egui/locales/fork/de-formats.json index 5db026dfce..6393a7a804 100644 --- a/crates/ui-egui/locales/fork/de-formats.json +++ b/crates/ui-egui/locales/fork/de-formats.json @@ -123,6 +123,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Sein Manifest hat Werte, die diese Version nicht verwenden kann und weglässt: {values}", "JPEG quality {q} to fit the size limit": "JPEG-Qualität {q}, damit die Datei in die Größengrenze passt", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "JPEG-Qualität {q}, damit die Datei in die Größengrenze passt (eine kleinere Größe oder eine höhere Grenze erhält mehr Qualität)", + "Kept with {raw} as its companion: not a photo of its own.": "Zusammen mit {raw} als Begleitdatei aufbewahrt: kein eigenes Foto.", "Kept. Groups left: {left}": "Behalten. Verbleibende Gruppen: {left}", "Last checked {n} hours ago": "Zuletzt geprüft: vor {n} Stunden", "Last checked {n} minutes ago": "Zuletzt geprüft: vor {n} Minuten", @@ -336,6 +337,7 @@ "{} keys": "Tasten für {}", "{} of {} from {host}": "{} von {} von {host}", "{} · {}. Kept in the catalog's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Gespeichert im Ordner „denoise“ des Katalogs; ist die Obergrenze erreicht, werden zuerst die ältesten Bilder entfernt, die kein Foto mehr verwendet.", + "· {companions} kept with their RAWs": "· {companions} mit ihren RAWs aufbewahrt", "“{name}” added to Camera Profiles": "„{name}“ zu Kameraprofilen hinzugefügt", "“{name}” has its old settings again": "„{name}“ hat wieder seine alten Einstellungen", "“{name}” is new. What may the other devices syncing this catalog have of it?": "„{name}“ ist neu. Was dürfen die anderen Geräte, die diesen Katalog synchronisieren, davon haben?", diff --git a/crates/ui-egui/locales/fork/de.json b/crates/ui-egui/locales/fork/de.json index f6af762358..7c16f84455 100644 --- a/crates/ui-egui/locales/fork/de.json +++ b/crates/ui-egui/locales/fork/de.json @@ -36,6 +36,7 @@ "6 Blades": "6 Lamellen", "8 bits/component": "8 Bit/Kanal", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} akzeptiert, {pending} zu prüfen, {rejected} abgelehnt", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "Ein JPEG mit dem Namen eines Raw daneben ist dessen Begleitdatei: ein Foto, ein Gesichtsscan, ein Satz Metadaten. Zum Import als eigene Fotos die Option für Begleitdateien abwählen.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Eine Sicherung des Katalogs ist fällig. Jetzt sichern, bevor {app} beendet wird?", "A card, a drive or a folder": "Eine Karte, ein Laufwerk oder ein Ordner", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "Ein Katalog ist ein Ordner: die Datensätze, Einstellungen und der Verlauf seiner Fotos. Die Fotos selbst bleiben, wo sie sind.", @@ -94,6 +95,7 @@ "Add Blank": "Leere Seite hinzufügen", "Add Cell": "Zelle hinzufügen", "Add Column": "Spalte hinzufügen", + "Add Editor": "Editor hinzufügen", "Add Face Model…": "Gesichtsmodell hinzufügen…", "Add Face Region": "Gesichtsregion hinzufügen", "Add Filter…": "Filter hinzufügen…", @@ -235,6 +237,7 @@ "Assign to Someone Else…": "Jemand anderem zuweisen…", "Assign to…": "Zuweisen an…", "At Import": "Beim Import", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Beim Import ist ein JPEG mit dem Namen eines Raw daneben kein eigenes Foto, sondern dessen Begleitdatei: eine Miniatur, ein Gesichtsscan, ein Satz Metadaten. Beim Kopieren, Verschieben oder Umbenennen wandert es mit dem Raw.", "At launch": "Beim Start", "At most one request per second.": "Höchstens eine Anfrage pro Sekunde.", "Attribution (shown on the map)": "Quellenangabe (auf der Karte angezeigt)", @@ -294,6 +297,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "Unter der ersten Schwelle bleibt es bei 0★; die Vorgaben sind 20, 40, 55, 70 und 85.", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Dazwischen behält ein Foto sein Flag (ohne Flag bleibt es ohne).", "Bit Depth": "Bittiefe", + "Bit Level": "Bittiefe", "Black": "Schwarz", "Black Point Compensation": "Tiefenkompensierung", "Blank": "Leer", @@ -342,7 +346,9 @@ "Browse your photos in a grid. Rate them with stars, flag the keepers and reject the rest, then sort them into collections and keywords. Filters find any photo by date, camera, rating or text.": "Durchsuchen Sie Ihre Fotos im Raster. Bewerten Sie sie mit Sternen, markieren Sie die guten und lehnen Sie den Rest ab, dann ordnen Sie sie in Sammlungen und Stichwörter. Filter finden jedes Foto nach Datum, Kamera, Bewertung oder Text.", "Brush (Return puts it down and paints, the arrows paint while it is down)": "Pinsel (Eingabe setzt ihn auf und malt, die Pfeiltasten malen, solange er aufliegt)", "Brush Refinement": "Pinselkorrektur", + "Build Face Thumbnails": "Gesichter-Miniaturen erstellen", "Build at import": "Beim Import erstellen", + "Building face thumbnails": "Gesichter-Miniaturen werden erstellt", "Building the profile…": "Profil wird erstellt…", "Built in the background once the photos are in, from the one on screen outward.": "Wird im Hintergrund erstellt, sobald die Fotos importiert sind, ausgehend vom angezeigten Foto.", "Built-in": "Integriert", @@ -499,6 +505,7 @@ "Choose folder later": "Ordner später auswählen", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Wählen Sie das Aussehen der App. Jede Änderung wird sofort sichtbar; mehr unter Einstellungen → Oberfläche.", "Choose in Sync…": "In Synchronisierung wählen …", + "Choose the Editor's Program": "Programm des Editors wählen", "Choose the catalog to open.": "Wählen Sie den Katalog zum Öffnen.", "Choose where to import from": "Importquelle wählen", "Circle": "Kreis", @@ -588,6 +595,7 @@ "Color space: sRGB with an HDR gain map (AVIF)": "Farbraum: sRGB mit einer HDR-Gain-Map (AVIF)", "Color to Replace": "Zu ersetzende Farbe", "Colour Profile": "Farbprofil", + "Colour Space": "Farbraum", "Colour space of the TIFF": "Farbraum des TIFF", "Column of Three": "Drei untereinander", "Columns": "Spalten", @@ -600,13 +608,15 @@ "Compact Cells": "Kompakte Zellen", "Compact Layout": "Kompaktes Layout", "Compact – Dense": "Kompakt – Dicht", + "Companion": "Begleitdatei", + "Companion JPEG:": "Begleit-JPEG:", "Compare Group in Survey": "Gruppe in Übersicht vergleichen", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Fertig", "Compression (quality scan)": "Komprimierung (Qualitätsscan)", "Compression artifacts": "Kompressionsartefakte", "Computing AI masks": "KI-Masken werden berechnet", - "Confidence required": "Erforderliche Konfidenz", + "Confidence required": "Erforderliche Treffsicherheit", "Confirm": "Bestätigen", "Confirm Faces from Immich": "Gesichter aus Immich bestätigen", "Confirm Immich Link": "Immich-Verknüpfung bestätigen", @@ -944,8 +954,11 @@ "Edit at History Step": "Bei Verlaufsschritt bearbeiten", "Edit date": "Bearbeitungsdatum", "Edit in (one item)": "Bearbeiten in (ein Eintrag)", + "Edit in Default Editor": "Im Standard-Editor bearbeiten", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "In anderem Editor bearbeiten (⌥⌘E) öffnet die Kopie in dieser Anwendung (ein Anwendungsname unter macOS, ein Programmpfad sonst). Bleibt der Ort leer, öffnet die Standardanwendung des Systems die Kopie.", "Edit this saved location": "Diesen gespeicherten Ort bearbeiten", "Edited Version Saved Again": "Bearbeitete Version erneut gespeichert", + "Editors": "Editoren", "Edit…": "Bearbeiten…", "Elsewhere": "Anderswo", "Email": "E-Mail", @@ -1222,6 +1235,7 @@ "Forget Remembered Object": "Gemerktes Objekt vergessen", "Forget This Person": "Diese Person vergessen", "Forget a Paired Surface": "Gekoppelte Oberfläche vergessen", + "Format Options": "Formatoptionen", "Four with Caption": "Vier mit Bildunterschrift", "Frame": "Rahmen", "Frame Rate": "Bildrate", @@ -1342,6 +1356,7 @@ "Hard Drive": "Festplatte", "Hardcover": "Hardcover", "Has a GPS position (click to show it on the map)": "Hat eine GPS-Position (klicken, um sie auf der Karte zu zeigen)", + "Has a companion JPEG (click to open the Info panel)": "Hat eine Begleit-JPEG (Klick öffnet den Infobereich)", "Headline metadata": "Schlagzeile aus Metadaten", "Headroom": "Spielraum", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Kleine dunkle oder rote Stellen auf der Gesichtshaut reparieren; Augen, Brauen, Nasenlöcher und Lippen bleiben unberührt", @@ -1368,7 +1383,7 @@ "Hide {app}": "{app} ausblenden", "High Range": "Oberer Bereich", "High quality adjustment previews": "Anpassungsvorschauen in hoher Qualität", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Höhere Konfidenz findet weniger falsche Gesichter, kann aber echte übersehen. Gilt für künftige Erkennungen; erneut scannen, um bestehende zu aktualisieren.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Höhere Treffsicherheit findet weniger falsche Gesichter, kann aber echte übersehen. Gilt für künftige Erkennungen; scannen Sie erneut, um bestehende zu aktualisieren.", "Highlight Hue": "Lichter – Farbton", "Highlight Luminance": "Lichter – Luminanz", "Highlight Reconstruction": "Lichterrekonstruktion", @@ -1464,6 +1479,7 @@ "Import Lightroom or Capture One Catalog…": "Lightroom- oder Capture-One-Katalog importieren…", "Import Metadata Presets": "Metadatenvorgaben importieren", "Import New Shots": "Neue Aufnahmen importieren", + "Import Order": "Importreihenfolge", "Import People": "Personen importieren", "Import People from Immich": "Personen aus Immich importieren", "Import Photos and Video…": "Fotos und Videos importieren…", @@ -1548,6 +1564,7 @@ "Install the Surface Plugin": "Surface-Plugin installieren", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Installiere ein eigenes ONNX-Modell mit denoise-model.json daneben. Dieser Build bietet keine Modell-Downloads an.", "Installed": "Installiert", + "Installed editors…": "Installierte Editoren…", "Installed in": "Installiert in", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Die Installation erlaubt nichts davon: Das Zusatzmodul fragt Sie, sobald es eine Berechtigung zum ersten Mal braucht.", "Install…": "Installieren…", @@ -1630,6 +1647,7 @@ "Large Landscape (13 × 11 in)": "Großes Querformat (13 × 11 in)", "Large and Small": "Groß und klein", "Large image size": "Große Bildgröße", + "Largest Face": "Größtes Gesicht", "Last Photo": "Letztes Foto", "Last backup:": "Letzte Sicherung:", "Last checked 1 hour ago": "Zuletzt geprüft: vor 1 Stunde", @@ -1642,6 +1660,7 @@ "Last synced on {}": "Zuletzt synchronisiert am {}", "Last synced {} h ago": "Zuletzt synchronisiert vor {} Std.", "Last synced {} min ago": "Zuletzt synchronisiert vor {} Min.", + "Launch Options": "Startoptionen", "Layout": "Layout", "Layout Image Off": "Layoutbild aus", "Layout Image On": "Layoutbild ein", @@ -1937,6 +1956,7 @@ "New Template Folder": "Neuer Vorlagenordner", "New Web Template Folder": "Neuer Web-Vorlagenordner", "New collections": "Neue Sammlungen", + "New editor": "Neuer Editor", "New group name": "Name der neuen Gruppe", "New group:": "Neue Gruppe:", "New location name": "Name des neuen Orts", @@ -1946,6 +1966,7 @@ "New preset…": "Neue Vorgabe…", "New red eye correction (Return adds it here)": "Neue Rote-Augen-Korrektur (Eingabetaste fügt sie hier hinzu)", "New shots:": "Neue Aufnahmen:", + "Newest First": "Neueste zuerst", "Next Filmstrip Background": "Nächster Filmstreifenhintergrund", "Next Frame": "Nächstes Bild", "Next Light Mode": "Nächster Lichtmodus", @@ -2097,6 +2118,7 @@ "Offset Hue": "Offset-Farbton", "Offset Luminance": "Offset-Helligkeit", "Offset Saturation": "Offset-Sättigung", + "Oldest First": "Älteste zuerst", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Bei einem gescannten Negativ oder Dia: Staubkörner, Haare und Kratzer auf dem Film finden und reparieren. Der Infrarotdurchgang des Scanners (eine RGBI-Datei aus VueScan oder SilverFast) sagt, wo sie sind; sonst werden die glatten Flächen des Bildes durchsucht", "On photo": "Auf dem Foto", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "Auf dem Gerät, dem eine Sammlung gehört, wählen, was die anderen haben dürfen; auf den anderen wählen, was dieses Gerät übernimmt.", @@ -2168,6 +2190,7 @@ "Optimize catalog after backing up": "Katalog nach dem Sichern optimieren", "Optional: where downloads go": "Optional: wohin Downloads gehen", "Orientation Detection Status": "Status der Ausrichtungserkennung", + "Original (+XMP)": "Original (+XMP)", "Original Photo": "Originalfoto", "Other": "Andere", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Andere Apps sehen dann Ihre Bewertungen, Stichwörter und Bearbeitungen. Neben jedes Foto wird eine kleine Datei geschrieben.", @@ -2247,6 +2270,7 @@ "Permissions": "Berechtigungen", "Permissions:": "Berechtigungen:", "Persistent": "Dauerhaft", + "Person Sort": "Personensortierung", "Personalize {app} with your own branding elements.": "Gestalten Sie {app} mit Ihren eigenen Markenelementen.", "Personalized": "Personalisiert", "Phone": "Telefon", @@ -2260,6 +2284,7 @@ "Photo with Side Text": "Foto mit seitlichem Text", "Photo with Title": "Foto mit Titel", "Photo zoom": "Fotozoom", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Foto → Bearbeiten in listet hier jeden Editor auf. Die ersten beiden sind fest eingebaut; fügen Sie so viele hinzu, wie Sie möchten, und klicken Sie auf eine Zeile, um zu ändern, was sie übergeben.", "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.": "Foto → Bearbeiten in → In PhotoCraft bearbeiten (⇧⌘E oder Rechtsklick auf ein Foto) rendert eine Kopie mit Ihren Bearbeitungen, stapelt sie mit dem Original und öffnet sie in PhotoCraft. Speichern Sie dort, wird die Kopie hier aktualisiert. Als PSD speichert PhotoCraft direkt in sie zurück. Lassen Sie den Speicherort leer, sofern Sie keine portable Kopie verwenden.", "Photograph Information": "Fotoinformationen", "Photos affected": "Betroffene Fotos", @@ -3150,6 +3175,7 @@ "Text Page": "Textseite", "Text Style Preset": "Textstilvorgabe", "Text size": "Textgröße", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "Das JPEG neben der Raw-Datei, das mit ihr zusammen bleibt: kein eigenes Foto.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Die Profilverwaltung listet jeden Look, jedes LUT-Profil und jedes Kameraprofil: Blenden Sie sie in den Menüs aus, benennen und gruppieren Sie sie, importieren Sie neue und löschen Sie Ihre eigenen.", "The account has no PIN or password, so there is nothing to unlock.": "Das Konto hat keine PIN und kein Passwort, daher gibt es nichts zu entsperren.", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "Das aktive Foto wurde dort aufgenommen, wo es geotaggt ist (oder in der Kartenmitte): an den Track anpassen", @@ -3359,6 +3385,7 @@ "Tracklog": "Tracklog", "Transform": "Transformieren", "Trash renders taken out of a collection": "Aus einer Sammlung entfernte Renderings in den Papierkorb", + "Treat JPEGs next to raw files as companions": "JPEGs neben Raw-Dateien als Begleitdateien behandeln", "Trim": "Zuschnitt", "Trim End": "Trimmende", "Trim Start": "Trimmanfang", @@ -3447,6 +3474,7 @@ "Update this one automatically": "Dieses automatisch aktualisieren", "Update to Current Process Version": "Auf aktuelle Prozessversion aktualisieren", "Update with Current Settings…": "Mit aktuellen Einstellungen aktualisieren…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Updates sind ausgeschaltet ({env}_DISABLE_UPDATES ist gesetzt); Ihre Paketverwaltung kümmert sich um Updates.", "Updates the installed version": "Aktualisiert die installierte Version", "Updates…": "Aktualisierungen…", "Updating the DNG previews stopped unexpectedly": "Das Aktualisieren der DNG-Vorschauen wurde unerwartet angehalten", @@ -3571,6 +3599,7 @@ "Wrong passphrase.": "Falsche Passphrase.", "Wrote {} XMP sidecars": "{} XMP-Filialdateien geschrieben", "X": "X", + "XMP Sidecar": "XMP-Seitendatei", "XMP Sidecars": "XMP-Begleitdateien", "Y": "Y", "Yellow Label": "Gelbe Farbmarkierung", @@ -3599,9 +3628,12 @@ "Zoomed Page View": "Gezoomte Seitenansicht", "`lcc-cli --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`lcc-cli --library` öffnet bei Angabe der Bibliotheksdatei selbst (`catalog.snap`) deren Ordner, statt fehlzuschlagen mit", "`lcc-cli run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`lcc-cli run --import ` (und die MCP-Werkzeuge, die Ordner annehmen) erfasst jetzt HEIC, HEIF und Nikon NRW", + "a copy of the original": "eine Kopie des Originals", + "a copy of the original, with an XMP sidecar": "eine Kopie des Originals, mit einer XMP-Seitendatei", "a photo matches any group": "ein Foto passt zu einer beliebigen Gruppe", "a photo matches every group": "ein Foto passt zu jeder Gruppe", "a word per topic; every word must match": "ein Wort pro Begriff; jedes Wort muss passen", + "adds an editor; click its row to name it and choose its program and file": "fügt eine Zeile hinzu; klicken Sie sie an, um den Editor zu benennen und Programm und Datei zu wählen", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "(Issue #101). Vor einem erneuten Versuch wird das Schreibfragment entfernt; beim nächsten Start werden alle Änderungen wiederhergestellt.", "all of": "alle von", "allowed": "erlaubt", @@ -3699,6 +3731,7 @@ "published": "veröffentlicht", "removed": "entfernt", "role": "Rolle", + "scene-linear Rec. 2020": "szene-linear in Rec. 2020", "selected photos": "ausgewählte Fotos", "shots": "Aufnahmen", "size": "Größe", @@ -3709,15 +3742,20 @@ "steps": "Schritte", "terms unclear": "Bedingungen unklar", "the active photo isn't a video": "das aktive Foto ist kein Video", + "the arguments before the file; `{file}` places the file's path where it stands": "die Argumente vor der Datei; `{file}` setzt den Pfad der Datei an diese Stelle", "the camera roll could not be read": "die Kamerarolle konnte nicht gelesen werden", + "the file's own": "wie in der Datei", "the folder shown": "der angezeigte Ordner", "the folder shown (no folder is: pick one first)": "der angezeigte Ordner (keiner angezeigt: zuerst einen wählen)", "the frames could not be matched to each other": "die Bilder konnten einander nicht zugeordnet werden", "the graphics card": "die Grafikkarte", "the graphics card is not used": "die Grafikkarte wird nicht verwendet", "the measured positions were less reliable than the camera's own pattern": "die gemessenen Positionen waren weniger zuverlässig als das eigene Muster der Kamera", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "die Standardanwendung des Systems für den Dateityp: Im Standard-Editor bearbeiten rendert die Kopie und übergibt sie", + "the original, with an XMP sidecar": "das Original, mit einer XMP-Seitendatei", "the photos in view": "die Fotos in der Ansicht", "the plug-in worker stopped unexpectedly": "der Plug-in-Worker wurde unerwartet beendet", + "the raw data's own": "wie in den Rohdaten", "the selected photos": "die ausgewählten Fotos", "the whole catalog": "der ganze Katalog", "there was not enough memory for the registered merge": "für die registrierte Zusammenführung war nicht genug Speicher vorhanden", @@ -3736,6 +3774,7 @@ "video playback isn't available in this build": "Videowiedergabe ist in diesem Build nicht verfügbar", "waiting for Apple Photos": "wartet auf Apple Photos", "width": "Breite", + "write the edits beside the file": "schreibt die Bearbeitungen neben die Datei", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "einer neueren Version wird mit entsprechendem Hinweis abgelehnt und bleibt unverändert.", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "neueren {app}-Version geschrieben ist, erklärt die App den Grund und bietet Erneut versuchen, Andere Bibliothek auswählen…,", "{app}": "{app}", diff --git a/crates/ui-egui/locales/fork/es-formats.json b/crates/ui-egui/locales/fork/es-formats.json index d1912e66b0..5252dcfbcb 100644 --- a/crates/ui-egui/locales/fork/es-formats.json +++ b/crates/ui-egui/locales/fork/es-formats.json @@ -123,6 +123,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Su manifiesto tiene valores que esta versión no puede usar y que omite: {values}", "JPEG quality {q} to fit the size limit": "Calidad JPEG {q} para ajustarse al límite de tamaño", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Calidad JPEG {q} para ajustarse al límite de tamaño (un tamaño menor o un límite mayor conserva más calidad)", + "Kept with {raw} as its companion: not a photo of its own.": "Conservado con {raw} como acompañante: no es una foto propia.", "Kept. Groups left: {left}": "Conservado. Grupos restantes: {left}", "Last checked {n} hours ago": "Última comprobación: hace {n} horas", "Last checked {n} minutes ago": "Última comprobación: hace {n} minutos", @@ -336,6 +337,7 @@ "{} keys": "Teclas de {}", "{} of {} from {host}": "{} de {} desde {host}", "{} · {}. Kept in the catalog's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Se guardan en la carpeta «denoise» del catálogo; al alcanzar el límite, se eliminan primero las más antiguas que ninguna foto usa.", + "· {companions} kept with their RAWs": "· {companions} conservados con sus raw", "“{name}” added to Camera Profiles": "«{name}» añadido a Perfiles de cámara", "“{name}” has its old settings again": "«{name}» vuelve a tener sus ajustes anteriores", "“{name}” is new. What may the other devices syncing this catalog have of it?": "«{name}» es nueva. ¿Qué pueden tener de ella los demás dispositivos que sincronizan este catálogo?", diff --git a/crates/ui-egui/locales/fork/es.json b/crates/ui-egui/locales/fork/es.json index 9d7c832a2a..76d7e2bd89 100644 --- a/crates/ui-egui/locales/fork/es.json +++ b/crates/ui-egui/locales/fork/es.json @@ -45,6 +45,7 @@ "630 drivers): on Windows the window and GPU rendering use DirectX 12 only and never load the Vulkan driver unless": "controladores 630): en Windows la ventana y el renderizado por GPU usan solo DirectX 12 y nunca cargan el controlador Vulkan salvo que", "8 bits/component": "8 bits/componente", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} aceptadas, {pending} por revisar, {rejected} rechazadas", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "Un JPEG con el nombre de un raw al lado es su acompañante: una foto, un escaneo de rostros, un juego de metadatos. Desmarque la opción de acompañantes para importar los JPEG como fotos propias.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Toca hacer una copia de seguridad del catálogo. ¿Hacerla ahora, antes de que {app} se cierre?", "A card, a drive or a folder": "Una tarjeta, una unidad o una carpeta", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "Un catálogo es una carpeta: los registros, ajustes e historial de sus fotos. Las fotos se quedan donde están.", @@ -108,6 +109,7 @@ "Add Blank": "Añadir en blanco", "Add Cell": "Añadir celda", "Add Column": "Añadir columna", + "Add Editor": "Añadir editor", "Add Face Model…": "Añadir modelo de rostros…", "Add Face Region": "Añadir región de cara", "Add Filter…": "Añadir filtro…", @@ -261,6 +263,7 @@ "Assign to Someone Else…": "Asignar a otra persona…", "Assign to…": "Asignar a…", "At Import": "Al importar", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Al importar, un JPEG con el nombre de un raw al lado no es una foto propia sino su acompañante: una miniatura, un escaneo de rostros, un juego de metadatos. Viaja con el raw al copiarlo, moverlo o renombrarlo.", "At launch": "Al iniciar", "At most one request per second.": "Como máximo una solicitud por segundo.", "Attribution (shown on the map)": "Atribución (se muestra en el mapa)", @@ -323,6 +326,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "Por debajo del primer umbral se queda en 0★; los valores predeterminados son 20, 40, 55, 70 y 85.", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Entre ambas, la foto conserva su marca (sin marca sigue sin marca).", "Bit Depth": "Profundidad de bits", + "Bit Level": "Nivel de bits", "Black": "Negro", "Black Point Compensation": "Compensación de punto negro", "Blank": "En blanco", @@ -372,7 +376,9 @@ "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "Versión de navegador (experimental), mantener segura una biblioteca (issue #107): Archivo → Copia de seguridad de la biblioteca… descarga el catálogo", "Brush (Return puts it down and paints, the arrows paint while it is down)": "Pincel (Intro lo apoya y pinta; las flechas pintan mientras está apoyado)", "Brush Refinement": "Refinamiento con pincel", + "Build Face Thumbnails": "Crear miniaturas de caras", "Build at import": "Generar al importar", + "Building face thumbnails": "Creando miniaturas de caras", "Building the profile…": "Creando el perfil…", "Built in the background once the photos are in, from the one on screen outward.": "Se crean en segundo plano una vez importadas las fotos, empezando por la que está en pantalla.", "Built-in": "Integradas", @@ -539,6 +545,7 @@ "Choose folder later": "Elegir carpeta más tarde", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Elige el aspecto de la aplicación. Cada cambio se ve al instante; Ajustes → Interfaz tiene más.", "Choose in Sync…": "Elegir en Sincronización…", + "Choose the Editor's Program": "Elegir el programa del editor", "Choose the catalog to open.": "Elige el catálogo que abrir.", "Choose where to import from": "Elija desde dónde importar", "Circle": "Círculo", @@ -636,6 +643,7 @@ "Color to Replace": "Color a reemplazar", "Color wheel": "Rueda de color", "Colour Profile": "Perfil de color", + "Colour Space": "Espacio de color", "Colour space of the TIFF": "Espacio de color del TIFF", "Colour-label filter with several labels at once; expandable folder tree in Local.": "Filtro por etiqueta de color con varias etiquetas a la vez; árbol de carpetas desplegable en Local.", "Colour-range masks: click the photo to sample. Luminance ranges: range bar, smoothness, luminance map.": "Máscaras de rango de color: haz clic en la foto para muestrear. Rangos de luminancia: barra de rango, suavidad, mapa de luminancia.", @@ -651,6 +659,8 @@ "Compact Cells": "Celdas compactas", "Compact Layout": "Diseño compacto", "Compact – Dense": "Compacto – Denso", + "Companion": "Acompañante", + "Companion JPEG:": "JPEG acompañante:", "Compare Group in Survey": "Comparar grupo en Encuesta", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Completado", @@ -1018,13 +1028,16 @@ "Edit at History Step": "Editar en el paso del historial", "Edit date": "Fecha de edición", "Edit in (one item)": "Editar en (un elemento)", + "Edit in Default Editor": "Editar en el editor predeterminado", "Edit in External Editor (⇧⌘E): a 16-bit TIFF copy, stacked, refreshed when you come back.": "Editar en editor externo (⇧⌘E): una copia TIFF de 16 bits, apilada, actualizada al volver.", "Edit in HDR: highlights above SDR white, for HDR exports and displays": "Editar en HDR: iluminaciones por encima del blanco SDR, para exportaciones y pantallas HDR", "Edit in Other Editor": "Editar en otro editor", "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Editar en otro editor (⌥⌘E) abre la copia en esta aplicación (un nombre de app en macOS, la ruta de un programa en los demás sistemas).", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Editar en otro editor (⌥⌘E) abre la copia en esta aplicación (un nombre de aplicación en macOS, una ruta de programa en otros casos). Si la ubicación queda vacía, la aplicación predeterminada del sistema la abre.", "Edit in PhotoCraft": "Editar en PhotoCraft", "Edit this saved location": "Editar esta ubicación guardada", "Edited Version Saved Again": "Versión editada guardada de nuevo", + "Editors": "Editores", "Edit…": "Editar…", "Elsewhere": "En otros sitios", "Email": "Correo electrónico", @@ -1318,6 +1331,7 @@ "Forget Remembered Object": "Olvidar objeto recordado", "Forget This Person": "Olvidar a esta persona", "Forget a Paired Surface": "Olvidar una superficie emparejada", + "Format Options": "Opciones de formato", "Found automatically": "Encontrado automáticamente", "Four with Caption": "Cuatro con pie de foto", "Frame": "Marco", @@ -1442,6 +1456,7 @@ "Hard Drive": "Disco duro", "Hardcover": "Tapa dura", "Has a GPS position (click to show it on the map)": "Tiene una posición GPS (haz clic para verla en el mapa)", + "Has a companion JPEG (click to open the Info panel)": "Tiene un JPEG acompañante (clic para abrir el panel de información)", "Headline metadata": "Titular en los metadatos", "Headroom": "Margen", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Corrige las pequeñas manchas oscuras o rojas de la piel de las caras; ojos, cejas, fosas nasales y labios no se tocan", @@ -1469,7 +1484,7 @@ "Hide {app}": "Ocultar {app}", "High Range": "Rango alto", "High quality adjustment previews": "Vistas previas de ajustes de alta calidad", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Una confianza mayor encuentra menos caras falsas, pero puede pasar por alto caras reales. Se aplica a detecciones futuras; vuelve a escanear para actualizar las existentes.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Una confianza mayor encuentra menos rostros falsos, pero puede pasar por alto rostros reales. Se aplica a detecciones futuras; vuelva a analizar para actualizar las existentes.", "Highlight Hue": "Tono de iluminaciones", "Highlight Luminance": "Luminancia de iluminaciones", "Highlight Reconstruction": "Reconstrucción de altas luces", @@ -1569,6 +1584,7 @@ "Import Mask Effects": "Importar efectos de máscara", "Import Metadata Presets": "Importar ajustes preestablecidos de metadatos", "Import New Shots": "Importar tomas nuevas", + "Import Order": "Orden de importación", "Import People": "Importar personas", "Import People from Immich": "Importar personas de Immich", "Import Photos and Video…": "Importar fotos y vídeo…", @@ -1663,6 +1679,7 @@ "Install the Surface Plugin": "Instalar el complemento Surface", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Instale su propio modelo ONNX con denoise-model.json junto a él. Esta versión no ofrece descargas de modelos.", "Installed": "Instalado", + "Installed editors…": "Editores instalados…", "Installed in": "Instalado en", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Instalarlo no concede nada de esto: el complemento te lo pide la primera vez que necesita cada permiso.", "Install…": "Instalar…", @@ -1749,6 +1766,7 @@ "Large Landscape (13 × 11 in)": "Horizontal grande (13 × 11 in)", "Large and Small": "Grande y pequeña", "Large image size": "Tamaño de imagen grande", + "Largest Face": "Cara más grande", "Last Photo": "Última foto", "Last backup:": "Última copia de seguridad:", "Last checked 1 hour ago": "Última comprobación: hace 1 hora", @@ -1761,6 +1779,7 @@ "Last synced on {}": "Última sincronización el {}", "Last synced {} h ago": "Última sincronización hace {} h", "Last synced {} min ago": "Última sincronización hace {} min", + "Launch Options": "Opciones de inicio", "Layout": "Diseño", "Layout Image Matte": "Mate de la imagen de diseño", "Layout Image Off": "Imagen de diseño desactivada", @@ -2078,6 +2097,7 @@ "New Template Folder": "Nueva carpeta de plantillas", "New Web Template Folder": "Nueva carpeta de plantillas web", "New collections": "Colecciones nuevas", + "New editor": "Editor nuevo", "New group (press Return)": "Nuevo grupo (pulsa Intro)", "New group name": "Nombre del nuevo grupo", "New group:": "Nuevo grupo:", @@ -2089,6 +2109,7 @@ "New red eye correction (Return adds it here)": "Nueva corrección de ojos rojos (Intro la añade aquí)", "New shots:": "Nuevas tomas:", "New spot (Return adds it here)": "Nueva mancha (Intro la añade aquí)", + "Newest First": "Más recientes primero", "Next Filmstrip Background": "Siguiente fondo de tira de película", "Next Frame": "Fotograma siguiente", "Next History Step": "Siguiente paso del historial", @@ -2252,6 +2273,7 @@ "Offset Hue": "Tono de offset", "Offset Luminance": "Luminancia de offset", "Offset Saturation": "Saturación de offset", + "Oldest First": "Más antiguas primero", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "En un negativo o diapositiva escaneados: busca y corrige motas de polvo, pelos y rayas en la película. La pasada infrarroja del escáner (un archivo RGBI de VueScan o SilverFast) dice dónde están; si no, se buscan en las zonas lisas de la imagen", "On photo": "En la foto", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "En el dispositivo propietario de una colección, elige qué pueden tener los demás; en los demás, elige qué toma este dispositivo.", @@ -2326,6 +2348,7 @@ "Optimize catalog after backing up": "Optimizar el catálogo después de la copia", "Optional: where downloads go": "Opcional: dónde van las descargas", "Orientation Detection Status": "Estado de la detección de orientación", + "Original (+XMP)": "Original (+XMP)", "Original Photo": "Foto original", "Other": "Otras", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Así otras aplicaciones ven tus valoraciones, palabras clave y ediciones. Escribe un archivo pequeño junto a cada foto.", @@ -2408,6 +2431,7 @@ "Permissions": "Permisos", "Permissions:": "Permisos:", "Persistent": "Persistente", + "Person Sort": "Ordenación de persona", "Personalize {app} with your own branding elements.": "Personaliza {app} con tus propios elementos de marca.", "Personalized": "Personalizada", "Phone": "Teléfono", @@ -2424,6 +2448,7 @@ "Photo with Side Text": "Foto con texto lateral", "Photo with Title": "Foto con título", "Photo zoom": "Zoom de las fotos", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Foto → Editar en enumera aquí cada editor. Los dos primeros están integrados; añade tantos como quieras y haz clic en una fila para cambiar lo que entrega.", "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.": "Foto → Editar en → Editar en PhotoCraft (⇧⌘E, o clic derecho en una foto) renderiza una copia con tus ediciones, la apila con el original y la abre en PhotoCraft. Guarda allí y la copia se actualiza aquí. En PSD, PhotoCraft guarda directamente en ella. Deja la ubicación vacía salvo que uses una copia portátil.", "PhotoCraft": "PhotoCraft", "Photograph Information": "Información de la fotografía", @@ -3396,6 +3421,7 @@ "Text Page": "Página de texto", "Text Style Preset": "Ajuste preestablecido de estilo de texto", "Text size": "Tamaño del texto", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "El JPEG junto al archivo raw, que se conserva con él: no es una foto propia.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "El Administrador de perfiles lista todos los estilos, perfiles LUT y perfiles de cámara: ocúltalos de los menús, cámbiales el nombre y agrúpalos, importa otros nuevos y elimina los tuyos.", "The account has no PIN or password, so there is nothing to unlock.": "La cuenta no tiene PIN ni contraseña, así que no hay nada que desbloquear.", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "La foto activa se tomó donde está geoetiquetada (o en el centro del mapa): ajústala al trayecto", @@ -3617,6 +3643,7 @@ "Tracklog": "Registro de trayecto", "Transform": "Transformar", "Trash renders taken out of a collection": "Enviar a la papelera los renders quitados de una colección", + "Treat JPEGs next to raw files as companions": "Tratar los JPEG junto a archivos raw como acompañantes", "Trim": "Recorte", "Trim End": "Fin del recorte", "Trim Start": "Inicio del recorte", @@ -3710,6 +3737,7 @@ "Update to Current Process": "Actualizar al proceso actual", "Update to Current Process Version": "Actualizar a la versión de proceso actual", "Update with Current Settings…": "Actualizar con la configuración actual…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Las actualizaciones están desactivadas ({env}_DISABLE_UPDATES está definida); su gestor de paquetes se encarga de ellas.", "Updates the installed version": "Actualiza la versión instalada", "Updates…": "Actualizaciones…", "Updating the DNG previews stopped unexpectedly": "La actualización de las vistas previas DNG se detuvo inesperadamente", @@ -3841,6 +3869,7 @@ "Wrong passphrase.": "Frase de contraseña incorrecta.", "Wrote {} XMP sidecars": "Se escribieron {} archivos XMP adjuntos", "X": "X", + "XMP Sidecar": "Sidecar XMP", "XMP Sidecars": "Archivos XMP auxiliares", "Y": "Y", "Yellow Label": "Etiqueta amarilla", @@ -3874,10 +3903,13 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` con el archivo propio de una biblioteca (`catalog.snap`) abre su carpeta en lugar de fallar con", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (y las herramientas MCP que aceptan carpetas) ahora recoge archivos HEIC, HEIF y Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` también registra avisos en stderr (issue #168); `{env}_LOG` o `RUST_LOG` eligen otro nivel.", + "a copy of the original": "una copia del original", + "a copy of the original, with an XMP sidecar": "una copia del original, con un sidecar XMP", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "una unidad llena) ya no cuenta como creada y Crear vistas previas inteligentes la reemplaza.", "a photo matches any group": "una foto coincide con cualquier grupo", "a photo matches every group": "una foto coincide con todos los grupos", "a word per topic; every word must match": "una palabra por tema; todas deben coincidir", + "adds an editor; click its row to name it and choose its program and file": "añade una fila; haz clic en ella para nombrar el editor y elegir su programa y archivo", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "después (issue #101): la escritura parcial se recorta antes de que {app} reintente, así que el siguiente inicio reproduce cada", "again. Change the period (or turn it off) in Settings → Performance.": "de nuevo. Cambia el periodo (o desactívalo) en Ajustes → Rendimiento.", "against the library's originals no longer scans the whole library when nothing is at that path.": "con los originales de la biblioteca ya no recorre toda la biblioteca cuando no hay nada en esa ruta.", @@ -4035,6 +4067,7 @@ "renders and screenshots are still written to a temp file and renamed into place, but no longer forced to disk": "los renderizados y capturas de pantalla se siguen escribiendo en un archivo temporal y renombrando a su sitio, pero ya no se fuerzan al disco", "role": "función", "save goes through.": "guardado se complete.", + "scene-linear Rec. 2020": "lineal de escena en Rec. 2020", "selected photos": "fotos seleccionadas", "shots": "tomas", "siblings) no longer open bright green (issue #148): their as-shot white balance and black level are read from the": "hermanas) ya no se abren en verde brillante (issue #148): su balance de blancos de toma y su nivel de negro se leen del", @@ -4054,16 +4087,21 @@ "the Local folder tree and Auto Import read the disk on worker threads too. The import progress window has Cancel.": "el árbol de carpetas Local y la importación automática también leen el disco en hilos de trabajo. La ventana de progreso de importación tiene Cancelar.", "the Photo menu and the photo context menu) picks up the full-size preview and fills in the camera metadata they": "el menú Foto y el menú contextual de la foto) toma la vista previa a tamaño completo y rellena los metadatos de cámara que", "the active photo isn't a video": "la foto activa no es un vídeo", + "the arguments before the file; `{file}` places the file's path where it stands": "los argumentos antes del archivo; `{file}` coloca la ruta del archivo donde esté", "the camera roll could not be read": "no se pudo leer el carrete", "the camera; mapped-out sensor defects are filled in. `.rwl` and `.raw` files are imported too. Photos already": "la cámara; los defectos del sensor mapeados se rellenan. También se importan los archivos `.rwl` y `.raw`. Las fotos ya", + "the file's own": "el propio del archivo", "the folder shown": "la carpeta mostrada", "the folder shown (no folder is: pick one first)": "la carpeta mostrada (no hay ninguna: elige una primero)", "the frames could not be matched to each other": "no se pudieron emparejar los fotogramas entre sí", "the graphics card": "la tarjeta gráfica", "the graphics card is not used": "no se usa la tarjeta gráfica", "the measured positions were less reliable than the camera's own pattern": "las posiciones medidas eran menos fiables que el patrón propio de la cámara", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "la aplicación predeterminada del sistema para el tipo de archivo: Editar en el editor predeterminado renderiza la copia y la entrega", + "the original, with an XMP sidecar": "el original, con un sidecar XMP", "the photos in view": "las fotos en la vista", "the plug-in worker stopped unexpectedly": "el proceso del complemento se detuvo inesperadamente", + "the raw data's own": "el propio de los datos RAW", "the same name and \"Overwrite\" (or Export with Previous repeating it), an exact output path from the control": "el mismo nombre y «Sobrescribir» (o Exportar con anterior repitiéndolo), una ruta de salida exacta del canal de", "the selected photos": "las fotos seleccionadas", "the whole catalog": "todo el catálogo", @@ -4093,6 +4131,7 @@ "whether originals are there is checked on a worker thread (grid thumbnails, the Info panel, the photo menu, Missing": "si los originales están presentes se comprueba en un hilo de trabajo (miniaturas de la cuadrícula, el panel Información, el menú de la foto, Fotos", "width": "ancho", "with a counterpart here come along, the rest is listed.": "con un equivalente aquí se importan, el resto se enumera.", + "write the edits beside the file": "escribe las ediciones junto al archivo", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "escrita por un {app} más reciente se rechaza con «esta biblioteca fue escrita por una versión más reciente de {app}» y se deja", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "escrita por un {app} más reciente), {app} lo dice y explica por qué, y ofrece Intentar de nuevo, Elegir otra biblioteca…, Continuar", "{app}": "{app}", diff --git a/crates/ui-egui/locales/fork/fi-formats.json b/crates/ui-egui/locales/fork/fi-formats.json index 0defacd175..a9c7bce96a 100644 --- a/crates/ui-egui/locales/fork/fi-formats.json +++ b/crates/ui-egui/locales/fork/fi-formats.json @@ -129,6 +129,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Sen manifestissa on arvoja, joita tämä versio ei voi käyttää, joten se jättää ne pois: {values}", "JPEG quality {q} to fit the size limit": "JPEG-laatu {q}, jotta tiedosto mahtuu kokorajaan", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "JPEG-laatu {q}, jotta tiedosto mahtuu kokorajaan (pienempi koko tai suurempi raja säilyttää enemmän laatua)", + "Kept with {raw} as its companion: not a photo of its own.": "Säilytetään {raw}:n mukana kulkevana kuvana: ei oma kuva.", "Kept. Groups left: {left}": "Säilytetty. Ryhmiä jäljellä: {left}", "Key from the environment variable {}": "Avain ympäristömuuttujasta {}", "Key saved (ends in {})": "Avain tallennettu (päättyy {})", @@ -364,6 +365,7 @@ "{} photos · {} aligned": "Kuvia {} · kohdistettu {}", "{} photos · {} aligned · {} left out": "Kuvia {} · kohdistettu {} · jätetty pois {}", "{} spot(s) from Remove Dust (outlined in amber)": "{} täplää Poista pöly -toiminnosta (ääriviiva meripihkalla)", + "· {companions} kept with their RAWs": "· {companions} säilytetään raakatiedostojensa kanssa", "“{name}” added to Camera Profiles": "”{name}” lisätty kameraprofiileihin", "“{name}” has its old settings again": "”{name}” sai vanhat asetuksensa takaisin", "“{name}” is new. What may the other devices syncing this catalog have of it?": "”{name}” on uusi. Mitä tätä katalogia synkronoivat muut laitteet saavat siitä?", diff --git a/crates/ui-egui/locales/fork/fi.json b/crates/ui-egui/locales/fork/fi.json index 97a49dc908..db3f3af5a6 100644 --- a/crates/ui-egui/locales/fork/fi.json +++ b/crates/ui-egui/locales/fork/fi.json @@ -43,6 +43,7 @@ "6 Blades": "6 lamellia", "8 bits/component": "8 bittiä/komponentti", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} hyväksytty, {pending} tarkistettava, {rejected} hylätty", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "Raakatiedoston vieressä samalla nimellä oleva JPEG on sen mukana kulkeva kuva: yksi kuva, yksi kasvojen tunnistus, yksi metadatajoukko. Tuodaksesi JPEG-kuvat omina kuvinaan poista mukana kulkevien valinta.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Katalogin varmuuskopiointi on ajankohtainen. Varmuuskopioidaanko nyt, ennen kuin {app} sulkeutuu?", "A camera profile is being built": "Kameraprofiilia luodaan", "A camera profile is for one camera: use a photo from the same camera body.": "Kameraprofiili on yhtä kameraa varten: käytä saman kamerarungon kuvaa.", @@ -111,6 +112,7 @@ "Add Blank": "Lisää tyhjä", "Add Cell": "Lisää solu", "Add Column": "Lisää sarake", + "Add Editor": "Lisää muokkain", "Add Face Region": "Lisää kasvoalue", "Add Filter…": "Lisää suodatin…", "Add Folder": "Lisää kansio", @@ -272,6 +274,7 @@ "Assign to Someone Else…": "Määritä jollekulle muulle…", "Assign to…": "Määritä…", "At Import": "Tuonnin yhteydessä", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Tuonnissa raakatiedoston vieressä samalla nimellä oleva JPEG ei ole oma kuvansa vaan sen mukana kulkeva kuva: yksi pikkukuva, yksi kasvojen tunnistus, yksi metadatajoukko. Se kulkee raakatiedoston mukana kopioitaessa, siirrettäessä tai nimettäessä uudelleen.", "At launch": "Käynnistettäessä", "At most one request per second.": "Enintään yksi pyyntö sekunnissa.", "Attribution (shown on the map)": "Lähdemaininta (näytetään kartalla)", @@ -331,6 +334,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Näiden välissä kuva pitää merkintänsä (merkitsemätön pysyy merkitsemättömänä).", "Big steps": "Isot askeleet", "Bit Depth": "Bittisyvyys", + "Bit Level": "Bittitaso", "Black": "Musta", "Black Point Compensation": "Mustan pisteen kompensointi", "Blank": "Tyhjä", @@ -386,7 +390,9 @@ "Brush Flow": "Siveltimen virtaus", "Brush Refinement": "Siveltimellä tarkennus", "Brush Size": "Siveltimen koko", + "Build Face Thumbnails": "Luo kasvojen pikkukuvat", "Build at import": "Luo tuonnin yhteydessä", + "Building face thumbnails": "Luodaan kasvojen pikkukuvia", "Building the profile…": "Luodaan profiilia…", "Built in the background once the photos are in, from the one on screen outward.": "Luodaan taustalla, kun kuvat on tuotu, alkaen näytöllä olevasta.", "Built-in (lcc-raw)": "Sisäänrakennettu (lcc-raw)", @@ -537,6 +543,7 @@ "Choose folder later": "Valitse kansio myöhemmin", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Valitse sovelluksen ulkoasu. Jokainen muutos näkyy heti; lisää kohdassa Asetukset → Käyttöliittymä.", "Choose in Sync…": "Valitse Synkronoinnissa…", + "Choose the Editor's Program": "Valitse muokkaimen ohjelma", "Choose the catalog to open.": "Valitse avattava katalogi.", "Choose where to import from": "Valitse, mistä tuodaan", "Chroma": "Kroma", @@ -632,6 +639,7 @@ "Color to Replace": "Korvattava väri", "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "Värit vastaavat värikarttaa; kukin säilyttää kameran tallentaman vaaleuden. Ihmisille ja arkikuville.", "Colour Profile": "Väriprofiili", + "Colour Space": "Väriavaruus", "Colour knobs P1–P8": "Värinupit P1–P8", "Colour space of the TIFF": "TIFF-tiedoston väriavaruus", "Colours are #RRGGBB.": "Värit ovat muodossa #RRGGBB.", @@ -649,6 +657,8 @@ "Compact Cells": "Tiiviit solut", "Compact Layout": "Tiivis asettelu", "Compact – Dense": "Tiivis – tiheä", + "Companion": "Mukana kulkeva", + "Companion JPEG:": "Mukana kulkeva JPEG:", "Compare Before and After": "Vertaa ennen ja jälkeen", "Compare Group in Survey": "Vertaile ryhmää Vertailussa", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", @@ -1021,6 +1031,8 @@ "Edit at History Step": "Muokkaa historiavaiheessa", "Edit date": "Muokkauspäivä", "Edit in (one item)": "Muokkaa (yksi kohta)", + "Edit in Default Editor": "Muokkaa oletusmuokkaimessa", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Muokkaa toisessa muokkaimessa (⌥⌘E) avaa kopion tässä sovelluksessa (sovelluksen nimi macOSissa, ohjelman polku muualla). Jos sijainti jätetään tyhjäksi, järjestelmän oletussovellus avaa sen.", "Edit this saved location": "Muokkaa tätä tallennettua sijaintia", "Edit: Color": "Muokkaus: väri", "Edit: Detail": "Muokkaus: yksityiskohdat", @@ -1030,6 +1042,7 @@ "Edit: Optics": "Muokkaus: optiikka", "Edited Version Saved Again": "Muokattu versio tallennettu uudelleen", "Editing": "Muokkaus", + "Editors": "Muokkaimet", "Edit…": "Muokkaa…", "Elsewhere": "Muualla", "Email": "Sähköposti", @@ -1326,6 +1339,7 @@ "Forget Remembered Object": "Unohda muistettu kohde", "Forget This Person": "Unohda tämä henkilö", "Forget a Paired Surface": "Unohda pariliitetty pinta", + "Format Options": "Muotovalinnat", "Four with Caption": "Neljä kuvatekstillä", "Frame": "Kehys", "Frame Rate": "Kuvataajuus", @@ -1454,6 +1468,7 @@ "Hard Drive": "Kiintolevy", "Hardcover": "Kovakantinen", "Has a GPS position (click to show it on the map)": "Kuvalla on GPS-sijainti (näytä se kartalla napsauttamalla)", + "Has a companion JPEG (click to open the Info panel)": "Mukana kulkeva JPEG (napsauta avataksesi tietoruudun)", "Headline metadata": "Lehtiotsikon metatiedot", "Headroom": "Varakorkeus", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Paranna kasvojen ihon pienet tummat tai punaiset täplät; silmiin, kulmakarvoihin, sieraimiin ja huuliin ei kosketa", @@ -1483,7 +1498,7 @@ "Hide this wheel's effect": "Piilota tämän pyörän vaikutus", "High Range": "Ylempi alue", "High quality adjustment previews": "Laadukkaat esikatselut säädettäessä", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Suurempi varmuus löytää vähemmän vääriä kasvoja, mutta voi ohittaa oikeita. Koskee tulevia tunnistuksia; päivitä nykyiset skannaamalla uudelleen.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Suurempi varmuus löytää vähemmän vääriä kasvoja mutta voi ohittaa oikeat. Koskee tulevia tunnistuksia; päivitä olemassa olevat skannaamalla uudelleen.", "Highlight Hue": "Huippuvalojen sävy", "Highlight Luminance": "Huippuvalojen kirkkaus", "Highlight Reconstruction": "Valoalueiden rekonstruktio", @@ -1585,6 +1600,7 @@ "Import Mask Effects": "Tuo maskitehosteet", "Import Metadata Presets": "Tuo metatietoesiasetukset", "Import New Shots": "Tuo uudet otokset", + "Import Order": "Tuontijärjestys", "Import People": "Tuo henkilöt", "Import People from Immich": "Tuo henkilöt Immichistä", "Import Photos and Video…": "Tuo kuvat ja video…", @@ -1668,6 +1684,7 @@ "Install the plugin": "Asenna laajennus", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Asenna oma ONNX-mallisi, jonka vieressä on denoise-model.json. Tämä versio ei tarjoa mallilatauksia.", "Installed": "Asennettu", + "Installed editors…": "Asennetut muokkaimet…", "Installed in": "Asennettu kansioon", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Asentaminen ei salli näistä mitään: laajennus kysyy sinulta, kun se tarvitsee kutakin ensimmäisen kerran.", "Installing the surface plugin": "Asennetaan ohjauspinnan laajennusta", @@ -1772,6 +1789,7 @@ "Large Landscape (13 × 11 in)": "Suuri vaaka (13 × 11 tuumaa)", "Large and Small": "Suuri ja pieni", "Large image size": "Suuri kuvakoko", + "Largest Face": "Suurimmat kasvot", "Last Photo": "Viimeinen kuva", "Last backup:": "Viimeisin varmuuskopio:", "Last checked 1 hour ago": "Viimeksi tarkistettu 1 tunti sitten", @@ -1784,6 +1802,7 @@ "Last synced on {}": "Synkronoitu viimeksi {}", "Last synced {} h ago": "Synkronoitu viimeksi {} h sitten", "Last synced {} min ago": "Synkronoitu viimeksi {} min sitten", + "Launch Options": "Käynnistysvalinnat", "Layout Image Off": "Asettelukuva pois", "Layout Image On": "Asettelukuva päälle", "Layout Style": "Asettelutyyli", @@ -2105,6 +2124,7 @@ "New Template Folder": "Uusi mallipohjakansio", "New Web Template Folder": "Uusi verkkomallikansio", "New collections": "Uudet kokoelmat", + "New editor": "Uusi muokkain", "New group name": "Uuden ryhmän nimi", "New group:": "Uusi ryhmä:", "New location name": "Uuden sijainnin nimi", @@ -2116,6 +2136,7 @@ "New raw photos shot at this ISO or above start with AI Denoise on, and their denoised pictures are made in the background after the import. Needs a denoise model (Settings, AI Denoise).": "Uusissa tällä tai suuremmalla ISO-arvolla kuvatuissa raw-kuvissa tekoälykohinanpoisto on aluksi päällä, ja kohinasta puhdistetut kuvat luodaan taustalla tuonnin jälkeen. Vaatii kohinanpoistomallin (Asetukset, Tekoälykohinanpoisto).", "New red eye correction (Return adds it here)": "Uusi punasilmäisyyden korjaus (Return lisää sen tähän)", "New shots:": "Uudet otokset:", + "Newest First": "Uusimmat ensin", "Next": "Seuraava", "Next Dial Page": "Seuraava kiekkosivu", "Next Filmstrip Background": "Seuraava filminauhan tausta", @@ -2281,6 +2302,7 @@ "Offset Hue": "Offset-sävy", "Offset Luminance": "Offset-kirkkaus", "Offset Saturation": "Offset-kylläisyys", + "Oldest First": "Vanhimmat ensin", "On": "Päällä", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Skannatulla negatiivilla tai dialla: etsi ja korjaa filmin pölyhiukkaset, hiukset ja naarmut. Skannerin infrapunakuva (VueScanin tai SilverFastin RGBI-tiedosto) kertoo, missä ne ovat; muuten etsitään kuvan tasaisilta alueilta", "On photo": "Kuvassa", @@ -2355,6 +2377,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "Valinnainen: värikarttakuva toisessa valossa, kuten hehkulampun valossa, tuottaa kahden valaistuksen profiilin.", "Optional: where downloads go": "Valinnainen: latausten sijainti", "Orientation Detection Status": "Suunnan tunnistuksen tila", + "Original (+XMP)": "Alkuperäinen (+XMP)", "Original Photo": "Alkuperäinen kuva", "Other": "Muu", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Muut sovellukset näkevät silloin arviosi, avainsanasi ja muokkauksesi. Jokaisen kuvan viereen kirjoitetaan pieni tiedosto.", @@ -2443,6 +2466,7 @@ "Permissions": "Käyttöoikeudet", "Permissions:": "Käyttöoikeudet:", "Persistent": "Pysyvä", + "Person Sort": "Henkilön järjestys", "Personalize {app} with your own branding elements.": "Mukauta sovellusta {app} omilla brändielementeilläsi.", "Personalized": "Mukautettu", "Phone": "Puhelin", @@ -2456,6 +2480,7 @@ "Photo with Side Text": "Kuva ja sivuteksti", "Photo with Title": "Kuva ja otsikko", "Photo zoom": "Valokuvien zoomaus", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Kuva → Muokkaa ohjelmassa listaa tähän jokaisen muokkaimen. Kaksi ensimmäistä ovat sisäänrakennettuja; lisää niin monta kuin haluat ja napsauta riviä muuttaaksesi, mitä se luovuttaa.", "Photograph Information": "Kuvaustiedot", "Photographic": "Valokuvallinen", "Photographic realism: re-creating textures, extending a scene. Up to 2048 px per request.": "Valokuvamainen realismi: tekstuurien uudelleenluonti, näkymän laajentaminen. Enintään 2048 px pyyntöä kohden.", @@ -3460,6 +3485,7 @@ "Text Page": "Tekstisivu", "Text Style Preset": "Tekstityylin esiasetus", "Text size": "Tekstin koko", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "Raakatiedoston vieressä oleva JPEG, joka säilyy sen kanssa: ei oma kuva.", "The Loupedeck+ works through the {app} plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ toimii {app}-laajennuksen kautta. Jokainen nuppi ja painike tekee sen, mitä sen merkintä sanoo, kunnes määrität sen täällä tai tuot oman Loupedeck-profiilisi (vain asettelu siirtyy).", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console on yhteydessä ohjelmaan {app} Logi Options+ -ohjelman {app}-laajennuksen kautta. Asennus luovuttaa laajennuksen Logi Options+ -ohjelmalle, joka pyytää sinua vahvistamaan.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Profiilien hallinta luettelee kaikki tyylit, LUT-profiilit ja kameraprofiilit: piilota niitä valikoista, nimeä ja ryhmittele niitä uudelleen, tuo uusia ja poista omiasi.", @@ -3685,6 +3711,7 @@ "Transform": "Muunnos", "Trash": "Roskakori", "Trash renders taken out of a collection": "Siirrä kokoelmasta poistetut renderöinnit roskakoriin", + "Treat JPEGs next to raw files as companions": "Kohtele raakatiedostojen vieressä olevia JPEG-kuvia mukana kulkevina", "Trim": "Trimmaa", "Trim End": "Trimmaa loppu", "Trim Start": "Trimmaa alku", @@ -3778,6 +3805,7 @@ "Update this one automatically": "Päivitä tämä automaattisesti", "Update to Current Process Version": "Päivitä nykyiseen prosessiversioon", "Update with Current Settings…": "Päivitä nykyisillä asetuksilla…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Päivitykset ovat pois päältä ({env}_DISABLE_UPDATES on asetettu); paketinhallinta hoitaa päivitykset.", "Updates the installed version": "Päivittää asennetun version", "Updates…": "Päivitykset…", "Updating the DNG previews stopped unexpectedly": "DNG-esikatselujen päivitys pysähtyi odottamatta", @@ -3919,6 +3947,7 @@ "Wrong passphrase.": "Väärä tunnuslause.", "Wrote {} XMP sidecars": "XMP-sivutiedostoja kirjoitettu: {}", "X": "X", + "XMP Sidecar": "XMP-sivutiedosto", "XMP Sidecars": "XMP-sivutiedostot", "Y": "Y", "Yellow Label": "Keltainen merkintä", @@ -3958,9 +3987,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library`, jolle annetaan kirjaston oma tiedosto (`catalog.snap`), avaa sen kansion sen sijaan, että epäonnistuisi virheellä", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (ja kansioita ottavat MCP-työkalut) poimii nyt HEIC-, HEIF- ja Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` kirjaa varoitukset myös stderriin (issue #168); `{env}_LOG` tai `RUST_LOG` valitsee toisen tason.", + "a copy of the original": "kopio alkuperäisestä", + "a copy of the original, with an XMP sidecar": "kopio alkuperäisestä, XMP-sivutiedostolla", "a photo matches any group": "kuva vastaa mitä tahansa ryhmää", "a photo matches every group": "kuva vastaa jokaista ryhmää", "a word per topic; every word must match": "yksi sana per aihe; jokaisen sanan on vastattava", + "adds an editor; click its row to name it and choose its program and file": "lisää rivin; napsauta sitä nimetäksesi muokkaimen ja valitaksesi sen ohjelman ja tiedoston", "all": "kaikki", "all of": "kaikki", "allowed": "sallittu", @@ -4060,6 +4092,7 @@ "red": "punainen", "removed": "poistettu", "role": "rooli", + "scene-linear Rec. 2020": "skene-lineaarinen Rec. 2020", "selected photos": "valittua kuvaa", "shots": "otosta", "size": "koko", @@ -4070,13 +4103,18 @@ "steps": "vaihetta", "tested": "testattu", "the active photo isn't a video": "aktiivinen kuva ei ole video", + "the arguments before the file; `{file}` places the file's path where it stands": "argumentit ennen tiedostoa; `{file}` sijoittaa tiedoston polun kyseiseen kohtaan", "the camera roll could not be read": "kamerarullaa ei voitu lukea", + "the file's own": "tiedoston oma", "the folder shown": "näkyvä kansio", "the folder shown (no folder is: pick one first)": "näkyvä kansio (ei kansiota: valitse ensin)", "the frames could not be matched to each other": "kuvia ei voitu sovittaa toisiinsa", "the measured positions were less reliable than the camera's own pattern": "mitatut paikat olivat epäluotettavampia kuin kameran oma kuvio", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "järjestelmän oletussovellus tiedostotyypille: Muokkaa oletusmuokkaimessa renderöi kopion ja luovuttaa sen", + "the original, with an XMP sidecar": "alkuperäinen, XMP-sivutiedostolla", "the photos in view": "näkyvissä olevat kuvat", "the plug-in worker stopped unexpectedly": "laajennuksen työsäie pysähtyi odottamatta", + "the raw data's own": "raakadatan oma", "the selected photos": "valitut kuvat", "the whole catalog": "koko katalogi", "there was not enough memory for the registered merge": "rekisteröityyn yhdistämiseen ei ollut tarpeeksi muistia", @@ -4098,6 +4136,7 @@ "video playback isn't available in this build": "videon toisto ei ole käytettävissä tässä versiossa", "waiting for Apple Photos": "odottaa Apple Photosia", "width": "leveys", + "write the edits beside the file": "kirjoittaa muokkaukset tiedoston viereen", "yellow": "keltainen", "{app}": "{app}", "{app} Export Presets": "{app} – vientiesiasetukset", diff --git a/crates/ui-egui/locales/fork/fr-formats.json b/crates/ui-egui/locales/fork/fr-formats.json index 6846b5272d..803df41192 100644 --- a/crates/ui-egui/locales/fork/fr-formats.json +++ b/crates/ui-egui/locales/fork/fr-formats.json @@ -120,6 +120,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Son manifeste contient des valeurs que cette version ne peut pas utiliser et qu'elle laisse de côté : {values}", "JPEG quality {q} to fit the size limit": "Qualité JPEG {q} pour respecter la limite de taille", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Qualité JPEG {q} pour respecter la limite de taille (une taille plus petite ou une limite plus grande conserve plus de qualité)", + "Kept with {raw} as its companion: not a photo of its own.": "Conservé avec {raw} comme compagnon : ce n'est pas une photo à part.", "Kept. Groups left: {left}": "Conservé. Groupes restants : {left}", "Last checked {n} hours ago": "Dernière vérification : il y a {n} heures", "Last checked {n} minutes ago": "Dernière vérification : il y a {n} minutes", @@ -326,6 +327,7 @@ "{} faces wait under 1 person": "{} visages attendent sous 1 personne", "{} faces wait under {} people": "{} visages attendent sous {} personnes", "{} keys": "Touches {}", + "· {companions} kept with their RAWs": "· {companions} conservés avec leurs raw", "“{name}” added to Camera Profiles": "« {name} » ajouté aux profils d’appareil", "“{name}” has its old settings again": "« {name} » a retrouvé ses anciens réglages", "“{name}” is new. What may the other devices syncing this catalog have of it?": "« {name} » est nouveau. Qu’en peuvent avoir les autres appareils qui synchronisent ce catalogue ?", diff --git a/crates/ui-egui/locales/fork/fr.json b/crates/ui-egui/locales/fork/fr.json index 6747f4c855..acd7fd0cfb 100644 --- a/crates/ui-egui/locales/fork/fr.json +++ b/crates/ui-egui/locales/fork/fr.json @@ -45,6 +45,7 @@ "630 drivers): on Windows the window and GPU rendering use DirectX 12 only and never load the Vulkan driver unless": "pilotes 630) : sous Windows, la fenêtre et le rendu GPU utilisent uniquement DirectX 12 et ne chargent jamais le pilote Vulkan, sauf si", "8 bits/component": "8 bits/composante", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} acceptées, {pending} à revoir, {rejected} rejetées", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "Un JPEG portant le nom d'un raw voisin est son compagnon : une photo, une analyse des visages, un jeu de métadonnées. Décochez l'option des compagnons pour importer les JPEG comme des photos à part.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Une sauvegarde du catalogue est due. La faire maintenant, avant de quitter {app} ?", "A card, a drive or a folder": "Une carte, un disque ou un dossier", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "Un catalogue est un dossier : les fiches de ses photos, ses réglages et son historique. Les photos elles-mêmes restent où elles sont.", @@ -104,6 +105,7 @@ "Add Blank": "Ajouter une page vierge", "Add Cell": "Ajouter une cellule", "Add Column": "Ajouter une colonne", + "Add Editor": "Ajouter un éditeur", "Add Face Model…": "Ajouter un modèle de visages…", "Add Face Region": "Ajouter une zone de visage", "Add Filter…": "Ajouter un filtre…", @@ -240,6 +242,7 @@ "Assign to Someone Else…": "Attribuer à quelqu’un d’autre…", "Assign to…": "Attribuer à…", "At Import": "À l'importation", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "À l'import, un JPEG portant le nom d'un raw voisin n'est pas une photo à part mais son compagnon : une vignette, une analyse des visages, un jeu de métadonnées. Il suit le raw quand celui-ci est copié, déplacé ou renommé.", "At most one request per second.": "Au plus une requête par seconde.", "Attribution (shown on the map)": "Attribution (affichée sur la carte)", "Audio": "Audio", @@ -298,6 +301,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "Sous le premier seuil, la note reste 0★ ; les valeurs par défaut sont 20, 40, 55, 70 et 85.", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Entre les deux, la photo garde son marqueur (sans marqueur, elle le reste).", "Bit Depth": "Profondeur", + "Bit Level": "Niveau de bits", "Black": "Noir", "Black Point Compensation": "Compensation du point noir", "Blank": "Vierge", @@ -347,7 +351,9 @@ "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "Version navigateur (expérimentale), protéger une bibliothèque (issue #107) : Fichier → Sauvegarder la bibliothèque… télécharge le catalogue", "Brush (Return puts it down and paints, the arrows paint while it is down)": "Pinceau (Entrée le pose et peint, les flèches peignent tant qu'il est posé)", "Brush Refinement": "Affinage au pinceau", + "Build Face Thumbnails": "Créer les miniatures des visages", "Build at import": "Générer à l’importation", + "Building face thumbnails": "Création des miniatures des visages", "Building the profile…": "Création du profil…", "Built in the background once the photos are in, from the one on screen outward.": "Créés en arrière-plan une fois les photos importées, à partir de celle affichée.", "Built-in": "Intégrés", @@ -499,6 +505,7 @@ "Choose folder later": "Choisir le dossier plus tard", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Choisissez l’apparence de l’application. Chaque changement s’affiche aussitôt ; Réglages → Interface en propose davantage.", "Choose in Sync…": "Choisir dans Synchronisation…", + "Choose the Editor's Program": "Choisir le programme de l'éditeur", "Choose where to import from": "Choisissez la source de l'importation", "Circle": "Cercle", "City": "Ville", @@ -586,6 +593,7 @@ "Color space: sRGB with an HDR gain map (AVIF)": "Espace colorimétrique : sRGB avec une carte de gain HDR (AVIF)", "Color to Replace": "Couleur à remplacer", "Colour Profile": "Profil colorimétrique", + "Colour Space": "Espace colorimétrique", "Colour space of the TIFF": "Espace colorimétrique du TIFF", "Colour-label filter with several labels at once; expandable folder tree in Local.": "Filtre par libellé de couleur avec plusieurs libellés à la fois ; arborescence de dossiers dépliable dans Local.", "Colour-range masks: click the photo to sample. Luminance ranges: range bar, smoothness, luminance map.": "Masques de plage de couleurs : cliquez sur la photo pour échantillonner. Plages de luminance : barre de plage, lissage, carte de luminance.", @@ -600,6 +608,8 @@ "Compact Cells": "Cellules compactes", "Compact Layout": "Disposition compacte", "Compact – Dense": "Compact – Dense", + "Companion": "Compagnon", + "Companion JPEG:": "JPEG compagnon :", "Compare Group in Survey": "Comparer le groupe en Vue multiple", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Terminé", @@ -932,9 +942,12 @@ "Edit at History Step": "Modifier à l’étape d’historique", "Edit date": "Date de modification", "Edit in (one item)": "Modifier dans (un élément)", + "Edit in Default Editor": "Ouvrir dans l'éditeur par défaut", "Edit in External Editor (⇧⌘E): a 16-bit TIFF copy, stacked, refreshed when you come back.": "Modifier dans un éditeur externe (⇧⌘E) : une copie TIFF 16 bits, empilée, actualisée à votre retour.", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Ouvrir dans un autre éditeur (⌥⌘E) ouvre la copie dans cette application (un nom d'application sous macOS, un chemin de programme ailleurs). Si l'emplacement reste vide, l'application par défaut du système l'ouvre.", "Edit this saved location": "Modifier ce lieu enregistré", "Edited Version Saved Again": "Version modifiée enregistrée à nouveau", + "Editors": "Éditeurs", "Edit…": "Modifier…", "Elsewhere": "Ailleurs", "Email": "E-mail", @@ -1214,6 +1227,7 @@ "Forget Remembered Object": "Oublier l’objet mémorisé", "Forget This Person": "Oublier cette personne", "Forget a Paired Surface": "Oublier une surface appairée", + "Format Options": "Options de format", "Four with Caption": "Quatre avec légende", "Frame": "Cadre", "Frame Rate": "Fréquence d’images", @@ -1328,6 +1342,7 @@ "Hard Drive": "Disque dur", "Hardcover": "Couverture rigide", "Has a GPS position (click to show it on the map)": "A une position GPS (cliquez pour l'afficher sur la carte)", + "Has a companion JPEG (click to open the Info panel)": "A un JPEG compagnon (cliquer pour ouvrir le panneau Informations)", "Headline metadata": "Métadonnées de la manchette", "Headroom": "Marge", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Corrige les petites taches sombres ou rouges de la peau des visages ; les yeux, les sourcils, les narines et les lèvres ne sont pas touchés", @@ -1354,7 +1369,7 @@ "Hide {app}": "Masquer {app}", "High Range": "Plage haute", "High quality adjustment previews": "Aperçus des réglages en haute qualité", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Une confiance plus élevée trouve moins de faux visages, mais peut manquer de vrais visages. S’applique aux détections futures ; relancez l’analyse pour mettre à jour les détections existantes.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Une confiance plus élevée trouve moins de faux visages, mais peut en manquer de vrais. S'applique aux détections futures ; rescannez pour mettre à jour celles qui existent.", "Highlight Hue": "Teinte des hautes lumières", "Highlight Luminance": "Luminance des hautes lumières", "Highlight Reconstruction": "Reconstruction des hautes lumières", @@ -1450,6 +1465,7 @@ "Import Lightroom or Capture One Catalog…": "Importer un catalogue Lightroom ou Capture One…", "Import Metadata Presets": "Importer des paramètres de métadonnées", "Import New Shots": "Importer les nouvelles prises", + "Import Order": "Ordre d’importation", "Import People": "Importer les personnes", "Import People from Immich": "Importer les personnes depuis Immich", "Import Photos and Video…": "Importer des photos et des vidéos…", @@ -1535,6 +1551,7 @@ "Install from Plug-in Marketplace": "Installer depuis la place de marché des modules externes", "Install the Surface Plugin": "Installer le module Surface", "Installed": "Installé", + "Installed editors…": "Éditeurs installés…", "Installed in": "Installé dans", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "L’installation n’accorde rien de tout cela : le module vous le demande la première fois qu’il en a besoin.", "Install…": "Installer…", @@ -1617,6 +1634,7 @@ "Large Landscape (13 × 11 in)": "Grand paysage (13 × 11 in)", "Large and Small": "Grande et petite", "Large image size": "Taille des grandes images", + "Largest Face": "Visage le plus grand", "Last Photo": "Dernière photo", "Last backup:": "Dernière sauvegarde :", "Last checked 1 hour ago": "Dernière vérification : il y a 1 heure", @@ -1628,6 +1646,7 @@ "Last synced on {}": "Dernière synchronisation le {}", "Last synced {} h ago": "Dernière synchronisation il y a {} h", "Last synced {} min ago": "Dernière synchronisation il y a {} min", + "Launch Options": "Options de lancement", "Layout": "Disposition", "Layout Image Off": "Image de mise en page désactivée", "Layout Image On": "Image de mise en page activée", @@ -1917,6 +1936,7 @@ "New Template Folder": "Nouveau dossier de modèles", "New Web Template Folder": "Nouveau dossier de modèles web", "New collections": "Nouvelles collections", + "New editor": "Nouvel éditeur", "New group name": "Nom du nouveau groupe", "New group:": "Nouveau groupe :", "New location name": "Nom du nouveau lieu", @@ -1926,6 +1946,7 @@ "New preset…": "Nouveau préréglage…", "New red eye correction (Return adds it here)": "Nouvelle correction des yeux rouges (Entrée l’ajoute ici)", "New shots:": "Nouvelles prises :", + "Newest First": "Les plus récents d’abord", "Next Filmstrip Background": "Arrière-plan du film fixe suivant", "Next Frame": "Image suivante", "Next Light Mode": "Mode d'éclairage suivant", @@ -2069,6 +2090,7 @@ "Offset Hue": "Teinte du offset", "Offset Luminance": "Luminance du offset", "Offset Saturation": "Saturation du offset", + "Oldest First": "Les plus anciens d’abord", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Sur un négatif ou une diapositive numérisés : trouver et corriger les poussières, cheveux et rayures du film. La passe infrarouge du scanner (un fichier RGBI de VueScan ou SilverFast) dit où ils sont ; sinon les zones lisses de l'image sont parcourues", "On photo": "Sur la photo", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "Sur l’appareil propriétaire d’une collection, choisissez ce que les autres peuvent avoir ; sur les autres, choisissez ce que cet appareil prend.", @@ -2130,6 +2152,7 @@ "Optimize catalog after backing up": "Optimiser le catalogue après la sauvegarde", "Optional: where downloads go": "Facultatif : où vont les téléchargements", "Orientation Detection Status": "État de la détection d’orientation", + "Original (+XMP)": "Original (+XMP)", "Original Photo": "Photo originale", "Other": "Autre", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Les autres applications voient alors vos notes, mots-clés et retouches. Un petit fichier est écrit à côté de chaque photo.", @@ -2208,6 +2231,7 @@ "Permissions": "Autorisations", "Permissions:": "Autorisations :", "Persistent": "Persistant", + "Person Sort": "Tri de la personne", "Personalize {app} with your own branding elements.": "Personnalisez {app} avec vos propres éléments de marque.", "Personalized": "Personnalisée", "Phone": "Téléphone", @@ -2222,6 +2246,7 @@ "Photo with Side Text": "Photo avec texte latéral", "Photo with Title": "Photo avec titre", "Photo zoom": "Zoom des photos", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Photo → Modifier dans liste ici chaque éditeur. Les deux premiers sont intégrés ; ajoutez-en autant que vous voulez, et cliquez sur une ligne pour changer ce qu'elle remet.", "Photograph Information": "Informations photographiques", "Photos affected": "Photos concernées", "Photos ahead": "Photos à l’avance", @@ -3118,6 +3143,7 @@ "Text Page": "Page de texte", "Text Style Preset": "Style de texte prédéfini", "Text size": "Taille du texte", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "Le JPEG à côté du fichier raw, conservé avec lui : ce n'est pas une photo à part.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Le Gestionnaire de profils liste chaque rendu, profil LUT et profil d’appareil : masquez-les des menus, renommez-les et groupez-les, importez-en de nouveaux et supprimez les vôtres.", "The account has no PIN or password, so there is nothing to unlock.": "Le compte n'a ni code ni mot de passe, il n'y a donc rien à déverrouiller.", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "La photo active a été prise là où elle est géolocalisée (ou au centre de la carte) : faites-la correspondre au tracé", @@ -3308,6 +3334,7 @@ "Tracklog": "Journal de suivi", "Transform": "Transformation", "Trash renders taken out of a collection": "Mettre à la corbeille les rendus retirés d’une collection", + "Treat JPEGs next to raw files as companions": "Traiter les JPEG voisins des fichiers raw comme compagnons", "Trim": "Découpe", "Trim End": "Fin du découpage", "Trim Start": "Début du découpage", @@ -3391,6 +3418,7 @@ "Update this one automatically": "Mettre à jour celui-ci automatiquement", "Update to Current Process Version": "Mettre à jour vers la version de traitement actuelle", "Update with Current Settings…": "Mettre à jour avec les réglages actuels…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Les mises à jour sont désactivées ({env}_DISABLE_UPDATES est défini) ; votre gestionnaire de paquets s’en charge.", "Updates the installed version": "Met à jour la version installée", "Updates…": "Mises à jour…", "Updating the DNG previews stopped unexpectedly": "La mise à jour des aperçus DNG s'est arrêtée de façon inattendue", @@ -3510,6 +3538,7 @@ "Wrong passphrase.": "Phrase secrète incorrecte.", "Wrote {} XMP sidecars": "{} fichiers annexes XMP écrits", "X": "X", + "XMP Sidecar": "Fichier sidecar XMP", "XMP Sidecars": "Fichiers annexes XMP", "Y": "Y", "Yellow Label": "Étiquette jaune", @@ -3540,10 +3569,13 @@ "`img_1-1.JPG`; on case-insensitive volumes the case change still goes through.": "`img_1-1.JPG` ; sur les volumes insensibles à la casse, le changement de casse s’effectue quand même.", "`lcc-cli --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`lcc-cli --library` avec le fichier propre d’une bibliothèque (`catalog.snap`) ouvre son dossier au lieu d’échouer avec", "`lcc-cli run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`lcc-cli run --import ` (et les outils MCP qui prennent des dossiers) reconnaît désormais HEIC, HEIF et Nikon NRW", + "a copy of the original": "une copie de l'original", + "a copy of the original, with an XMP sidecar": "une copie de l'original, avec un sidecar XMP", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "un disque plein) n’est plus considéré comme créé et Créer des aperçus dynamiques le remplace.", "a photo matches any group": "une photo correspond à n’importe quel groupe", "a photo matches every group": "une photo correspond à tous les groupes", "a word per topic; every word must match": "un mot par sujet ; chaque mot doit correspondre", + "adds an editor; click its row to name it and choose its program and file": "ajoute une ligne ; cliquez dessus pour nommer l'éditeur et choisir son programme et son fichier", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "par la suite (issue #101) : l’écriture partielle est tronquée avant que {app} réessaie, de sorte que le lancement suivant rejoue chaque", "again. Change the period (or turn it off) in Settings → Performance.": "de nouveau. Modifiez la période (ou désactivez-la) dans Réglages → Performances.", "against the library's originals no longer scans the whole library when nothing is at that path.": "par rapport aux originaux de la bibliothèque n’analyse plus toute la bibliothèque quand rien ne se trouve à ce chemin.", @@ -3685,6 +3717,7 @@ "renders and screenshots are still written to a temp file and renamed into place, but no longer forced to disk": "les rendus et captures d’écran sont toujours écrits dans un fichier temporaire puis renommés à leur place, mais ne sont plus forcés sur le disque", "role": "rôle", "save goes through.": "l’enregistrement aboutit.", + "scene-linear Rec. 2020": "linéaire de scène en Rec. 2020", "selected photos": "photos sélectionnées", "shots": "prises", "siblings) no longer open bright green (issue #148): their as-shot white balance and black level are read from the": "leurs déclinaisons) ne s’ouvrent plus vert vif (issue #148) : leur balance des blancs telle que prise et leur niveau de noir sont lus depuis le", @@ -3700,14 +3733,19 @@ "the Local folder tree and Auto Import read the disk on worker threads too. The import progress window has Cancel.": "l’arborescence des dossiers Local et l’importation automatique lisent aussi le disque sur des threads de travail. La fenêtre de progression de l’importation a un bouton Annuler.", "the Photo menu and the photo context menu) picks up the full-size preview and fills in the camera metadata they": "le menu Photo et le menu contextuel de photo) récupère l’aperçu en pleine taille et complète les métadonnées d’appareil qui", "the active photo isn't a video": "la photo active n’est pas une vidéo", + "the arguments before the file; `{file}` places the file's path where it stands": "les arguments avant le fichier ; `{file}` place le chemin du fichier à cet endroit", "the camera roll could not be read": "la pellicule photo n’a pas pu être lue", "the camera; mapped-out sensor defects are filled in. `.rwl` and `.raw` files are imported too. Photos already": "l’appareil ; les défauts de capteur cartographiés sont comblés. Les fichiers `.rwl` et `.raw` sont aussi importés. Les photos déjà", + "the file's own": "celui du fichier", "the folder shown": "le dossier affiché", "the folder shown (no folder is: pick one first)": "le dossier affiché (aucun dossier : choisissez-en un d'abord)", "the frames could not be matched to each other": "les prises de vue n’ont pas pu être mises en correspondance", "the measured positions were less reliable than the camera's own pattern": "les positions mesurées étaient moins fiables que le motif propre de l’appareil", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "l'application par défaut du système pour le type de fichier : Ouvrir dans l'éditeur par défaut rend la copie et la remet", + "the original, with an XMP sidecar": "l'original, avec un sidecar XMP", "the photos in view": "les photos affichées", "the plug-in worker stopped unexpectedly": "le processus du module s’est arrêté de façon inattendue", + "the raw data's own": "celui des données brutes", "the same name and \"Overwrite\" (or Export with Previous repeating it), an exact output path from the control": "le même nom et « Écraser » (ou Exporter avec les paramètres précédents qui le répète), un chemin de sortie exact depuis le", "the selected photos": "les photos sélectionnées", "the whole catalog": "le catalogue entier", @@ -3736,6 +3774,7 @@ "whether originals are there is checked on a worker thread (grid thumbnails, the Info panel, the photo menu, Missing": "la présence des originaux est vérifiée sur un thread de travail (vignettes de la grille, panneau Infos, menu Photo, Manquantes", "width": "largeur", "with a counterpart here come along, the rest is listed.": "ayant un équivalent ici sont repris, le reste est listé.", + "write the edits beside the file": "écrit les retouches à côté du fichier", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "écrite par un {app} plus récent est refusée avec « cette bibliothèque a été écrite par une version plus récente de {app} » et laissée", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "écrite par un {app} plus récent), {app} le dit et explique pourquoi, et propose Réessayer, Choisir une autre bibliothèque…, Continuer", "{app}": "{app}", diff --git a/crates/ui-egui/locales/fork/id-formats.json b/crates/ui-egui/locales/fork/id-formats.json index 77f02bfbdb..e5f9276d6c 100644 --- a/crates/ui-egui/locales/fork/id-formats.json +++ b/crates/ui-egui/locales/fork/id-formats.json @@ -128,6 +128,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Manifesnya berisi nilai yang tidak dapat digunakan versi ini, yang dilewatinya: {values}", "JPEG quality {q} to fit the size limit": "Kualitas JPEG {q} agar sesuai batas ukuran", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Kualitas JPEG {q} agar sesuai batas ukuran (ukuran lebih kecil atau batas lebih besar mempertahankan lebih banyak kualitas)", + "Kept with {raw} as its companion: not a photo of its own.": "Disimpan dengan {raw} sebagai pendamping: bukan foto tersendiri.", "Kept. Groups left: {left}": "Disimpan. Grup tersisa: {left}", "Key from the environment variable {}": "Kunci dari variabel lingkungan {}", "Key saved (ends in {})": "Kunci disimpan (berakhiran {})", @@ -363,6 +364,7 @@ "{} photos · {} aligned": "{} foto · {} diselaraskan", "{} photos · {} aligned · {} left out": "{} foto · {} diselaraskan · {} tidak disertakan", "{} spot(s) from Remove Dust (outlined in amber)": "{} bintik dari Hapus Debu (bergaris kuning amber)", + "· {companions} kept with their RAWs": "· {companions} disimpan dengan raw masing-masing", "“{name}” added to Camera Profiles": "“{name}” ditambahkan ke Profil Kamera", "“{name}” has its old settings again": "“{name}” kembali memiliki pengaturan lamanya", "“{name}” is new. What may the other devices syncing this catalog have of it?": "“{name}” baru. Apa yang boleh dimiliki perangkat lain yang menyinkronkan katalog ini darinya?", diff --git a/crates/ui-egui/locales/fork/id.json b/crates/ui-egui/locales/fork/id.json index 6243d4a8bb..655d4efd13 100644 --- a/crates/ui-egui/locales/fork/id.json +++ b/crates/ui-egui/locales/fork/id.json @@ -43,6 +43,7 @@ "6 Blades": "6 Bilah", "8 bits/component": "8 bit/komponen", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} diterima, {pending} untuk ditinjau, {rejected} ditolak", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "JPEG dengan nama raw di sebelahnya adalah pendampingnya: satu foto, satu pemindaian wajah, satu set metadata. Hapus centang opsi pendamping untuk mengimpor JPEG sebagai foto tersendiri.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Sudah waktunya mencadangkan katalog. Cadangkan sekarang, sebelum {app} ditutup?", "A camera profile is being built": "Profil kamera sedang dibuat", "A camera profile is for one camera: use a photo from the same camera body.": "Profil kamera hanya berlaku untuk satu kamera: gunakan foto dari bodi kamera yang sama.", @@ -112,6 +113,7 @@ "Add Blank": "Tambahkan halaman kosong", "Add Cell": "Tambah Sel", "Add Column": "Tambah Kolom", + "Add Editor": "Tambahkan editor", "Add Face Region": "Tambahkan area wajah", "Add Filter…": "Tambahkan filter…", "Add Folder": "Tambahkan folder", @@ -270,6 +272,7 @@ "Assign to Someone Else…": "Tetapkan ke orang lain…", "Assign to…": "Tetapkan ke…", "At Import": "Saat impor", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Saat impor, JPEG dengan nama raw di sebelahnya bukan foto tersendiri melainkan pendamping raw itu: satu gambar mini, satu pemindaian wajah, satu set metadata. JPEG ikut bersama raw saat disalin, dipindahkan, atau diganti namanya.", "At launch": "Saat dibuka", "At most one request per second.": "Paling banyak satu permintaan per detik.", "Attribution (shown on the map)": "Atribusi (ditampilkan di peta)", @@ -327,6 +330,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Di antara keduanya, foto mempertahankan tandanya (tanpa tanda tetap tanpa tanda).", "Big steps": "Langkah besar", "Bit Depth": "Kedalaman bit", + "Bit Level": "Kedalaman bit", "Black": "Hitam", "Black Point Compensation": "Kompensasi titik hitam", "Blank": "Kosong", @@ -383,7 +387,9 @@ "Brush Flow": "Aliran kuas", "Brush Refinement": "Penyempurnaan kuas", "Brush Size": "Ukuran kuas", + "Build Face Thumbnails": "Buat thumbnail wajah", "Build at import": "Buat saat impor", + "Building face thumbnails": "Membuat thumbnail wajah", "Building the profile…": "Membuat profil…", "Built in the background once the photos are in, from the one on screen outward.": "Dibuat di latar belakang setelah foto masuk, mulai dari foto di layar lalu meluas ke sekitarnya.", "Built-in (lcc-raw)": "Bawaan (lcc-raw)", @@ -536,6 +542,7 @@ "Choose folder later": "Pilih folder nanti", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Pilih tampilan aplikasi. Setiap perubahan langsung terlihat; Pengaturan → Antarmuka punya lebih banyak pilihan.", "Choose in Sync…": "Pilih di Sinkronisasi…", + "Choose the Editor's Program": "Pilih program editor", "Choose the catalog to open.": "Pilih katalog yang akan dibuka.", "Choose where to import from": "Pilih sumber impor", "Chroma": "Kroma", @@ -632,6 +639,7 @@ "Color wheel": "Roda warna", "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "Warna disesuaikan dengan bagan; masing-masing mempertahankan kecerahan yang direkam kamera. Untuk foto orang dan foto sehari-hari.", "Colour Profile": "Profil warna", + "Colour Space": "Ruang warna", "Colour knobs P1–P8": "Kenop warna P1–P8", "Colour space of the TIFF": "Ruang warna TIFF", "Colours are #RRGGBB.": "Warna ditulis sebagai #RRGGBB.", @@ -650,6 +658,8 @@ "Compact Cells": "Sel ringkas", "Compact Layout": "Tata letak ringkas", "Compact – Dense": "Ringkas – Padat", + "Companion": "Pendamping", + "Companion JPEG:": "JPEG pendamping:", "Compare Before and After": "Bandingkan sebelum dan sesudah", "Compare Group in Survey": "Bandingkan Grup di Survei", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", @@ -657,7 +667,7 @@ "Compression (quality scan)": "Kompresi (pemindaian kualitas)", "Compression artifacts": "Artefak kompresi", "Computing AI masks": "Menghitung masker AI", - "Confidence required": "Keyakinan yang diperlukan", + "Confidence required": "Keyakinan minimum", "Confirm": "Konfirmasi", "Confirm Dialog": "Konfirmasi dialog", "Confirm Faces from Immich": "Konfirmasi wajah dari Immich", @@ -1019,6 +1029,8 @@ "Edit at History Step": "Edit pada langkah riwayat", "Edit date": "Tanggal edit", "Edit in (one item)": "Edit in (satu item)", + "Edit in Default Editor": "Edit di Editor Bawaan", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Edit di Editor Lain (⌥⌘E) membuka salinan di aplikasi ini (nama aplikasi di macOS, path program di tempat lain). Bila lokasi kosong, aplikasi bawaan sistem yang membukanya.", "Edit this saved location": "Edit lokasi tersimpan ini", "Edit: Color": "Edit: Warna", "Edit: Detail": "Edit: Detail", @@ -1028,6 +1040,7 @@ "Edit: Optics": "Edit: Optik", "Edited Version Saved Again": "Versi hasil edit disimpan ulang", "Editing": "Pengeditan", + "Editors": "Editor", "Edit…": "Edit…", "Elsewhere": "Di tempat lain", "Email": "Email", @@ -1324,6 +1337,7 @@ "Forget Remembered Object": "Lupakan objek yang diingat", "Forget This Person": "Lupakan orang ini", "Forget a Paired Surface": "Lupakan permukaan kontrol yang dipasangkan", + "Format Options": "Opsi format", "Four with Caption": "Empat dengan keterangan", "Frame": "Bingkai", "Frame Rate": "Kecepatan frame", @@ -1456,6 +1470,7 @@ "Hard Drive": "Hard disk", "Hardcover": "Sampul keras", "Has a GPS position (click to show it on the map)": "Memiliki posisi GPS (klik untuk menampilkannya di peta)", + "Has a companion JPEG (click to open the Info panel)": "Punya JPEG pendamping (klik untuk membuka panel Info)", "Headline metadata": "Metadata judul utama", "Headroom": "Ruang HDR", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Perbaiki bintik gelap atau merah kecil di kulit wajah; mata, alis, lubang hidung, dan bibir dibiarkan", @@ -1485,7 +1500,7 @@ "Hide this wheel's effect": "Sembunyikan efek roda ini", "High Range": "Rentang tinggi", "High quality adjustment previews": "Pratinjau penyesuaian berkualitas tinggi", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Keyakinan lebih tinggi menemukan lebih sedikit wajah palsu, tetapi dapat melewatkan wajah asli. Berlaku untuk deteksi berikutnya; pindai ulang untuk memperbarui deteksi yang ada.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Keyakinan lebih tinggi menemukan lebih sedikit wajah palsu, tetapi bisa melewatkan wajah sungguhan. Berlaku untuk deteksi berikutnya; pindai ulang untuk memperbarui deteksi yang ada.", "Highlight Hue": "Hue sorotan", "Highlight Luminance": "Luminans sorotan", "Highlight Reconstruction": "Rekonstruksi sorotan", @@ -1586,6 +1601,7 @@ "Import Lightroom or Capture One Catalog…": "Impor katalog Lightroom atau Capture One…", "Import Metadata Presets": "Impor preset metadata", "Import New Shots": "Impor bidikan baru", + "Import Order": "Urutan impor", "Import People": "Impor orang", "Import People from Immich": "Impor orang dari Immich", "Import Photos and Video…": "Impor foto dan video…", @@ -1668,6 +1684,7 @@ "Install the plugin": "Instal plugin", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Instal model ONNX Anda sendiri dengan denoise-model.json di sebelahnya. Build ini tidak menyediakan unduhan model.", "Installed": "Terinstal", + "Installed editors…": "Editor terpasang…", "Installed in": "Terinstal di", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Menginstal tidak mengizinkan satu pun: plug-in akan bertanya saat pertama kali memerlukannya.", "Installing the surface plugin": "Menginstal plugin permukaan kontrol", @@ -1773,6 +1790,7 @@ "Large Landscape (13 × 11 in)": "Lanskap besar (13 × 11 in)", "Large and Small": "Besar dan kecil", "Large image size": "Ukuran gambar besar", + "Largest Face": "Wajah terbesar", "Last Photo": "Foto terakhir", "Last backup:": "Cadangan terakhir:", "Last checked 1 hour ago": "Terakhir diperiksa 1 jam lalu", @@ -1785,6 +1803,7 @@ "Last synced on {}": "Terakhir disinkronkan pada {}", "Last synced {} h ago": "Terakhir disinkronkan {} jam lalu", "Last synced {} min ago": "Terakhir disinkronkan {} menit lalu", + "Launch Options": "Opsi peluncuran", "Layout Image Off": "Gambar tata letak nonaktif", "Layout Image On": "Gambar tata letak aktif", "Layout Style": "Gaya tata letak", @@ -2109,6 +2128,7 @@ "New Template Folder": "Folder templat baru", "New Web Template Folder": "Folder templat web baru", "New collections": "Koleksi baru", + "New editor": "Editor baru", "New group (press Return)": "Grup baru (tekan Return)", "New group name": "Nama grup baru", "New group:": "Grup baru:", @@ -2122,6 +2142,7 @@ "New red eye correction (Return adds it here)": "Koreksi mata merah baru (Return menambahkannya di sini)", "New shots:": "Bidikan baru:", "New spot (Return adds it here)": "Bintik baru (Return menambahkannya di sini)", + "Newest First": "Terbaru dulu", "Next": "Berikutnya", "Next Dial Page": "Halaman dial berikutnya", "Next Filmstrip Background": "Latar filmstrip berikutnya", @@ -2298,6 +2319,7 @@ "Offset Hue": "Rona offset", "Offset Luminance": "Luminansi offset", "Offset Saturation": "Saturasi offset", + "Oldest First": "Terlama dulu", "On": "Aktif", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Pada negatif atau slide hasil pindaian: temukan dan perbaiki bintik debu, rambut, dan goresan pada film. Lintasan inframerah pemindai (berkas RGBI dari VueScan atau SilverFast) menunjukkan letaknya; jika tidak, area halus pada gambar yang dicari", "On photo": "Di foto", @@ -2373,6 +2395,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "Opsional: foto bagan di bawah cahaya lain, misalnya tungsten, menghasilkan profil dua iluminan.", "Optional: where downloads go": "Opsional: lokasi unduhan", "Orientation Detection Status": "Status deteksi orientasi", + "Original (+XMP)": "Asli (+XMP)", "Original Photo": "Foto asli", "Other": "Lainnya", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Aplikasi lain lalu dapat melihat nilai, kata kunci, dan editan Anda. Berkas kecil ditulis di samping setiap foto.", @@ -2463,6 +2486,7 @@ "Permissions": "Izin", "Permissions:": "Izin:", "Persistent": "Persisten", + "Person Sort": "Urutan orang", "Personalize {app} with your own branding elements.": "Personalisasikan {app} dengan elemen merek Anda sendiri.", "Personalized": "Personal", "Phone": "Telepon", @@ -2476,6 +2500,7 @@ "Photo with Side Text": "Foto dengan teks samping", "Photo with Title": "Foto dengan judul", "Photo zoom": "Zoom foto", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Foto → Edit di mencantumkan setiap editor di sini. Dua yang pertama sudah tertanam; tambahkan sebanyak yang Anda mau, dan klik baris untuk mengubah file yang diserahkan.", "Photograph Information": "Informasi pemotretan", "Photographic": "Fotografis", "Photographic realism: re-creating textures, extending a scene. Up to 2048 px per request.": "Realisme fotografis: membuat ulang tekstur, memperluas pemandangan. Hingga 2048 px per permintaan.", @@ -3467,6 +3492,7 @@ "Text Page": "Halaman teks", "Text Style Preset": "Preset gaya teks", "Text size": "Ukuran teks", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "JPEG di samping berkas raw, disimpan bersamanya: bukan foto tersendiri.", "The Loupedeck+ works through the {app} plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ bekerja melalui plugin {app}. Setiap kenop dan tombol melakukan apa yang tertera pada labelnya sampai Anda mengaturnya di sini, atau membawa profil Loupedeck Anda sendiri (hanya tata letaknya yang ikut).", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console terhubung dengan {app} melalui plugin {app} untuk Logi Options+. Saat diinstal, plugin diserahkan ke Logi Options+, yang akan meminta konfirmasi Anda.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Pengelola profil menampilkan setiap gaya, profil LUT, dan profil kamera: sembunyikan dari menu, ganti nama dan kelompokkan, impor yang baru, dan hapus milik Anda sendiri.", @@ -3697,6 +3723,7 @@ "Transform": "Transformasi", "Trash": "Tempat sampah", "Trash renders taken out of a collection": "Buang render yang dikeluarkan dari koleksi ke tempat sampah", + "Treat JPEGs next to raw files as companions": "Anggap JPEG di samping berkas raw sebagai pendamping", "Trim": "Potong", "Trim End": "Potong akhir", "Trim Start": "Potong awal", @@ -3791,6 +3818,7 @@ "Update this one automatically": "Perbarui yang ini secara otomatis", "Update to Current Process Version": "Perbarui ke versi proses terbaru", "Update with Current Settings…": "Perbarui dengan pengaturan saat ini…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Pembaruan dimatikan ({env}_DISABLE_UPDATES disetel); pengelola paket Anda yang menangani pembaruan.", "Updates the installed version": "Memperbarui versi yang terinstal", "Updates…": "Pembaruan…", "Updating the DNG previews stopped unexpectedly": "Pembaruan pratinjau DNG berhenti tanpa diduga", @@ -3932,6 +3960,7 @@ "Wrong passphrase.": "Frasa sandi salah.", "Wrote {} XMP sidecars": "{} sidecar XMP ditulis", "X": "X", + "XMP Sidecar": "Sidecar XMP", "XMP Sidecars": "Sidecar XMP", "Y": "Y", "Yellow Label": "Label kuning", @@ -3971,9 +4000,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` yang diberi file pustaka itu sendiri (`catalog.snap`) kini membuka foldernya alih-alih gagal dengan", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (dan alat MCP yang menerima folder) kini mengambil HEIC, HEIF, dan Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` juga mencatat peringatan di stderr (issue #168); `{env}_LOG` atau `RUST_LOG` memilih tingkat lain.", + "a copy of the original": "salinan asli", + "a copy of the original, with an XMP sidecar": "salinan asli, dengan sidecar XMP", "a photo matches any group": "foto cocok dengan grup mana pun", "a photo matches every group": "foto cocok dengan setiap grup", "a word per topic; every word must match": "satu kata per topik; setiap kata harus cocok", + "adds an editor; click its row to name it and choose its program and file": "menambahkan baris; klik untuk memberi nama editor dan memilih program serta file", "all of": "semua", "allowed": "diizinkan", "any of": "salah satu", @@ -4060,6 +4092,7 @@ "published": "diterbitkan", "removed": "dikeluarkan", "role": "peran", + "scene-linear Rec. 2020": "linear scene Rec. 2020", "selected photos": "foto yang dipilih", "shots": "jepretan", "size": "ukuran", @@ -4067,13 +4100,18 @@ "steps": "langkah", "tested": "diuji", "the active photo isn't a video": "foto aktif bukan video", + "the arguments before the file; `{file}` places the file's path where it stands": "argumen sebelum file; `{file}` menempatkan path file di posisi itu", "the camera roll could not be read": "rol kamera tidak dapat dibaca", + "the file's own": "milik file", "the folder shown": "folder yang ditampilkan", "the folder shown (no folder is: pick one first)": "folder yang ditampilkan (belum ada: pilih dulu)", "the frames could not be matched to each other": "bingkai tidak dapat dicocokkan satu sama lain", "the measured positions were less reliable than the camera's own pattern": "posisi yang diukur kurang andal dibandingkan pola bawaan kamera", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "aplikasi bawaan sistem untuk jenis file ini: Edit di Editor Bawaan merender salinan dan menyerahkannya", + "the original, with an XMP sidecar": "asli, dengan sidecar XMP", "the photos in view": "foto yang terlihat", "the plug-in worker stopped unexpectedly": "proses plug-in berhenti secara tak terduga", + "the raw data's own": "milik data RAW", "the selected photos": "foto yang dipilih", "the whole catalog": "seluruh katalog", "there was not enough memory for the registered merge": "memori tidak cukup untuk penggabungan terdaftar", @@ -4093,6 +4131,7 @@ "video playback isn't available in this build": "pemutaran video tidak tersedia di build ini", "waiting for Apple Photos": "menunggu Apple Photos", "width": "lebar", + "write the edits beside the file": "menyimpan editan di samping file", "{app}": "{app}", "{app} Effect Presets": "Preset efek {app}", "{app} Export Presets": "Preset ekspor {app}", diff --git a/crates/ui-egui/locales/fork/it-formats.json b/crates/ui-egui/locales/fork/it-formats.json index aa20ea8c25..e986dc6491 100644 --- a/crates/ui-egui/locales/fork/it-formats.json +++ b/crates/ui-egui/locales/fork/it-formats.json @@ -128,6 +128,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Il suo manifest ha valori che questa versione non può usare e tralascia: {values}", "JPEG quality {q} to fit the size limit": "Qualità JPEG {q} per rientrare nel limite di dimensione", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Qualità JPEG {q} per rientrare nel limite di dimensione (una dimensione minore o un limite maggiore mantiene più qualità)", + "Kept with {raw} as its companion: not a photo of its own.": "Conservato con {raw} come file abbinato: non è una foto a sé.", "Kept. Groups left: {left}": "Conservato. Gruppi rimasti: {left}", "Key from the environment variable {}": "Chiave dalla variabile d'ambiente {}", "Key saved ({})": "Chiave salvata ({})", @@ -346,6 +347,7 @@ "{} fixed: {} known for camera {}, {} found in this photo": "{} corrette: {} note per la fotocamera {}, {} trovate in questa foto", "{} keys": "Tasti per {}", "{} spot(s) from Remove Dust (outlined in amber)": "{} macchie da Rimuovi polvere (contornate in ambra)", + "· {companions} kept with their RAWs": "· {companions} conservati con i loro raw", "“{name}” added to Camera Profiles": "«{name}» aggiunto ai profili fotocamera", "“{name}” has its old settings again": "«{name}» ha di nuovo le impostazioni precedenti", "“{name}” is new. What may the other devices syncing this catalog have of it?": "«{name}» è nuova. Cosa possono averne gli altri dispositivi che sincronizzano questo catalogo?", diff --git a/crates/ui-egui/locales/fork/it.json b/crates/ui-egui/locales/fork/it.json index fa57cc6071..0d6a6e7d10 100644 --- a/crates/ui-egui/locales/fork/it.json +++ b/crates/ui-egui/locales/fork/it.json @@ -41,6 +41,7 @@ "6 Blades": "6 lamelle", "8 bits/component": "8 bit/componente", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} accettate, {pending} da rivedere, {rejected} rifiutate", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "Un JPEG con il nome di un raw accanto è il suo file abbinato: una foto, una scansione dei volti, un set di metadati. Deseleziona l'opzione dei file abbinati per importare i JPEG come foto a sé.", "A backup of the catalog is due. Back it up now, before {app} quits?": "È ora di fare il backup del catalogo. Farlo adesso, prima che {app} si chiuda?", "A camera profile is being built": "Creazione di un profilo fotocamera in corso", "A camera profile is for one camera: use a photo from the same camera body.": "Un profilo fotocamera vale per una sola fotocamera: usa una foto dello stesso corpo macchina.", @@ -105,6 +106,7 @@ "Add Blank": "Aggiungi vuota", "Add Cell": "Aggiungi cella", "Add Column": "Aggiungi colonna", + "Add Editor": "Aggiungi editor", "Add Face Region": "Aggiungi regione del volto", "Add Filter…": "Aggiungi filtro…", "Add Folder": "Aggiungi cartella", @@ -253,6 +255,7 @@ "Assign to Someone Else…": "Assegna a qualcun altro…", "Assign to…": "Assegna a…", "At Import": "All'importazione", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "All'importazione, un JPEG con il nome di un raw accanto non è una foto a sé ma il suo file abbinato: una miniatura, una scansione dei volti, un set di metadati. Segue il raw quando viene copiato, spostato o rinominato.", "At most one request per second.": "Al massimo una richiesta al secondo.", "Attribution (shown on the map)": "Attribuzione (mostrata sulla mappa)", "Audio": "Audio", @@ -308,6 +311,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Tra i due, una foto mantiene il suo contrassegno (senza contrassegno resta tale).", "Big steps": "Passi grandi", "Bit Depth": "Profondità bit", + "Bit Level": "Livello di bit", "Black": "Nero", "Black Point Compensation": "Compensazione punto nero", "Blank": "Vuota", @@ -363,7 +367,9 @@ "Brush Flow": "Flusso del pennello", "Brush Refinement": "Rifinitura a pennello", "Brush Size": "Dimensione del pennello", + "Build Face Thumbnails": "Crea le miniature dei volti", "Build at import": "Genera all'importazione", + "Building face thumbnails": "Creazione delle miniature dei volti", "Building the profile…": "Creazione del profilo…", "Built in the background once the photos are in, from the one on screen outward.": "Generate in background una volta arrivate le foto, a partire da quella sullo schermo.", "Built-in (lcc-raw)": "Integrato (lcc-raw)", @@ -510,6 +516,7 @@ "Choose folder later": "Scegli la cartella più tardi", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Scegli l’aspetto dell’app. Ogni modifica si vede subito; Impostazioni → Interfaccia ne offre di più.", "Choose in Sync…": "Scegli in Sincronizzazione…", + "Choose the Editor's Program": "Scegli il programma dell'editor", "Choose where to import from": "Scegli da dove importare", "Circle": "Cerchio", "City": "Città", @@ -600,6 +607,7 @@ "Color wheel": "Ruota dei colori", "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "I colori corrispondono alla tavola; ognuno mantiene la luminosità registrata dalla fotocamera. Per persone e foto di tutti i giorni.", "Colour Profile": "Profilo colore", + "Colour Space": "Spazio colore", "Colour space of the TIFF": "Spazio colore del TIFF", "Colours are #RRGGBB.": "I colori sono nel formato #RRGGBB.", "Column of Three": "Colonna da tre", @@ -617,13 +625,15 @@ "Compact Cells": "Celle compatte", "Compact Layout": "Layout compatto", "Compact – Dense": "Compatto – Denso", + "Companion": "Abbinato", + "Companion JPEG:": "JPEG abbinato:", "Compare Group in Survey": "Confronta gruppo in Panoramica", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Completato", "Compression (quality scan)": "Compressione (scansione qualità)", "Compression artifacts": "Artefatti di compressione", "Computing AI masks": "Calcolo delle maschere IA", - "Confidence required": "Confidenza richiesta", + "Confidence required": "Affidabilità richiesta", "Confirm": "Conferma", "Confirm Dialog": "Conferma finestra di dialogo", "Confirm Faces from Immich": "Conferma i volti da Immich", @@ -968,6 +978,8 @@ "Edit at History Step": "Modifica al passo della cronologia", "Edit date": "Data di modifica", "Edit in (one item)": "Modifica in (una voce)", + "Edit in Default Editor": "Modifica nell'editor predefinito", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Modifica in altro editor (⌥⌘E) apre la copia in questa applicazione (un nome di applicazione su macOS, un percorso di programma altrove). Con la posizione vuota la apre l'applicazione predefinita del sistema.", "Edit this saved location": "Modifica questa posizione salvata", "Edit: Color": "Modifica: Colore", "Edit: Detail": "Modifica: Dettaglio", @@ -976,6 +988,7 @@ "Edit: Light": "Modifica: Luce", "Edit: Optics": "Modifica: Ottica", "Edited Version Saved Again": "Versione modificata salvata di nuovo", + "Editors": "Editor", "Edit…": "Modifica…", "Elsewhere": "Altrove", "Email": "E-mail", @@ -1266,6 +1279,7 @@ "Forget Remembered Object": "Dimentica oggetto memorizzato", "Forget This Person": "Dimentica questa persona", "Forget a Paired Surface": "Dimentica una superficie associata", + "Format Options": "Opzioni formato", "Four with Caption": "Quattro con didascalia", "Frame": "Inquadratura", "Frame Rate": "Frequenza fotogrammi", @@ -1394,6 +1408,7 @@ "Hard Drive": "Disco rigido", "Hardcover": "Copertina rigida", "Has a GPS position (click to show it on the map)": "Ha una posizione GPS (fai clic per vederla sulla mappa)", + "Has a companion JPEG (click to open the Info panel)": "Ha un JPEG abbinato (clic per aprire il pannello info)", "Headline metadata": "Metadati dell’intestazione", "Headroom": "Margine HDR", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Correggi le piccole macchie scure o rosse sulla pelle dei volti; occhi, sopracciglia, narici e labbra restano intatti", @@ -1421,7 +1436,7 @@ "Hide this wheel's effect": "Nascondi l'effetto di questa ruota", "High Range": "Intervallo alto", "High quality adjustment previews": "Anteprime delle regolazioni di alta qualità", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Una confidenza più alta trova meno volti falsi, ma può non rilevare volti reali. Si applica ai rilevamenti futuri; ripeti la scansione per aggiornare quelli esistenti.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Un'affidabilità più alta trova meno falsi volti, ma può perdere volti reali. Vale per i rilevamenti futuri; rifai la scansione per aggiornare quelli esistenti.", "Highlight Hue": "Tonalità delle luci", "Highlight Luminance": "Luminanza delle luci", "Highlight Reconstruction": "Ricostruzione delle alte luci", @@ -1518,6 +1533,7 @@ "Import Lightroom or Capture One Catalog…": "Importa catalogo Lightroom o Capture One…", "Import Metadata Presets": "Importa preset metadati", "Import New Shots": "Importa nuovi scatti", + "Import Order": "Ordine di importazione", "Import People": "Importa persone", "Import People from Immich": "Importa persone da Immich", "Import Photos and Video…": "Importa foto e video…", @@ -1597,6 +1613,7 @@ "Install the Surface Plugin": "Installa il plugin della superficie", "Install the plugin": "Installa il plugin", "Installed": "Installato", + "Installed editors…": "Editor installati…", "Installed in": "Installato in", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "L’installazione non concede nulla di tutto ciò: il plug-in te lo chiede la prima volta che gli serve.", "Installing the surface plugin": "Installazione del plugin della superficie", @@ -1699,6 +1716,7 @@ "Large Landscape (13 × 11 in)": "Orizzontale grande (13 × 11 in)", "Large and Small": "Grande e piccolo", "Large image size": "Dimensione immagine grande", + "Largest Face": "Volto più grande", "Last Photo": "Ultima foto", "Last backup:": "Ultimo backup:", "Last checked 1 hour ago": "Ultimo controllo: 1 ora fa", @@ -1710,6 +1728,7 @@ "Last synced on {}": "Ultima sincronizzazione il {}", "Last synced {} h ago": "Ultima sincronizzazione {} h fa", "Last synced {} min ago": "Ultima sincronizzazione {} min fa", + "Launch Options": "Opzioni di avvio", "Layout Image Off": "Immagine di layout disattivata", "Layout Image On": "Immagine di layout attivata", "Layout Style": "Stile di layout", @@ -2017,6 +2036,7 @@ "New Template Folder": "Nuova cartella di modelli", "New Web Template Folder": "Nuova cartella di modelli web", "New collections": "Nuove raccolte", + "New editor": "Nuovo editor", "New group (press Return)": "Nuovo gruppo (premi Invio)", "New group name": "Nome del nuovo gruppo", "New group:": "Nuovo gruppo:", @@ -2028,6 +2048,7 @@ "New red eye correction (Return adds it here)": "Nuova correzione occhi rossi (Invio la aggiunge qui)", "New shots:": "Nuovi scatti:", "New spot (Return adds it here)": "Nuova macchia (Invio la aggiunge qui)", + "Newest First": "I più recenti prima", "Next": "Avanti", "Next Filmstrip Background": "Sfondo pellicola successivo", "Next Frame": "Fotogramma successivo", @@ -2190,6 +2211,7 @@ "Offset Hue": "Tonalità del offset", "Offset Luminance": "Luminanza del offset", "Offset Saturation": "Saturazione del offset", + "Oldest First": "I più vecchi prima", "On": "Attivo", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Su un negativo o una diapositiva scansionati: trova e corregge granelli di polvere, peli e graffi sulla pellicola. La passata a infrarossi dello scanner (un file RGBI di VueScan o SilverFast) dice dove sono; altrimenti si cercano nelle zone uniformi dell'immagine", "On photo": "Sulla foto", @@ -2257,6 +2279,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "Facoltativo: una foto della tavola sotto un'altra luce, ad esempio al tungsteno, crea un profilo a doppio illuminante.", "Optional: where downloads go": "Facoltativo: dove vanno i download", "Orientation Detection Status": "Stato del rilevamento dell’orientamento", + "Original (+XMP)": "Originale (+XMP)", "Original Photo": "Foto originale", "Other": "Altro", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Le altre app vedono così valutazioni, parole chiave e modifiche. Viene scritto un piccolo file accanto a ogni foto.", @@ -2341,6 +2364,7 @@ "Permissions": "Autorizzazioni", "Permissions:": "Autorizzazioni:", "Persistent": "Persistente", + "Person Sort": "Ordinamento persona", "Personalize {app} with your own branding elements.": "Personalizza {app} con i tuoi elementi di branding.", "Personalized": "Personalizzata", "Phone": "Telefono", @@ -2354,6 +2378,7 @@ "Photo with Side Text": "Foto con testo laterale", "Photo with Title": "Foto con titolo", "Photo zoom": "Zoom delle foto", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Foto → Modifica in elenca qui ogni editor. I primi due sono integrati; aggiungine quanti vuoi e clicca una riga per cambiare cosa consegna.", "Photograph Information": "Informazioni fotografiche", "Photographic": "Fotografica", "Photos affected": "Foto interessate", @@ -3287,6 +3312,7 @@ "Text Page": "Pagina di testo", "Text Style Preset": "Preset di stile del testo", "Text size": "Dimensione testo", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "Il JPEG accanto al file raw, conservato insieme: non è una foto a sé.", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "La MX Creative Console comunica con {app} tramite il plugin di {app} per Logi Options+. L'installazione passa il plugin a Logi Options+, che ti chiede di confermare.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "La finestra Gestione profili elenca ogni look, profilo LUT e profilo fotocamera: nascondili dai menu, rinominali e raggruppali, importane di nuovi ed elimina i tuoi.", "The account has no PIN or password, so there is nothing to unlock.": "L'account non ha un PIN né una password, quindi non c'è nulla da sbloccare.", @@ -3491,6 +3517,7 @@ "Tracklog": "Tracciato", "Transform": "Trasforma", "Trash renders taken out of a collection": "Cestina le versioni generate tolte da una raccolta", + "Treat JPEGs next to raw files as companions": "Tratta i JPEG accanto ai file raw come file abbinati", "Trim": "Taglia", "Trim End": "Taglia fine", "Trim Start": "Taglia inizio", @@ -3583,6 +3610,7 @@ "Update this one automatically": "Aggiorna questo automaticamente", "Update to Current Process Version": "Aggiorna alla versione processo corrente", "Update with Current Settings…": "Aggiorna con le impostazioni attuali…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Gli aggiornamenti sono disattivati ({env}_DISABLE_UPDATES è impostata); se ne occupa il gestore di pacchetti.", "Updates the installed version": "Aggiorna la versione installata", "Updates…": "Aggiornamenti…", "Updating the DNG previews stopped unexpectedly": "L'aggiornamento delle anteprime DNG si è interrotto inaspettatamente", @@ -3710,6 +3738,7 @@ "Wrong passphrase.": "Passphrase errata.", "Wrote {} XMP sidecars": "File XMP collaterali scritti: {}", "X": "X", + "XMP Sidecar": "Sidecar XMP", "XMP Sidecars": "File XMP collaterali", "Y": "Y", "Yellow Label": "Etichetta gialla", @@ -3748,9 +3777,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library`, se riceve il file proprio di una libreria (`catalog.snap`), apre la sua cartella invece di fallire con", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (e gli strumenti MCP che accettano cartelle) ora rileva HEIC, HEIF e Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` registra gli avvisi anche su stderr (issue #168); `{env}_LOG` o `RUST_LOG` sceglie un altro livello.", + "a copy of the original": "una copia dell'originale", + "a copy of the original, with an XMP sidecar": "una copia dell'originale, con un sidecar XMP", "a photo matches any group": "una foto corrisponde a un gruppo qualsiasi", "a photo matches every group": "una foto corrisponde a ogni gruppo", "a word per topic; every word must match": "una parola per argomento; ogni parola deve corrispondere", + "adds an editor; click its row to name it and choose its program and file": "aggiunge una riga; cliccala per dare un nome all'editor e scegliere programma e file", "all of": "tutte", "allowed": "consentita", "any of": "almeno una", @@ -3836,6 +3868,7 @@ "published": "pubblicati", "removed": "rimossi", "role": "ruolo", + "scene-linear Rec. 2020": "lineare di scena in Rec. 2020", "selected photos": "foto selezionate", "shots": "scatti", "size": "dimensione", @@ -3843,13 +3876,18 @@ "source": "origine", "steps": "passaggi", "the active photo isn't a video": "la foto attiva non è un video", + "the arguments before the file; `{file}` places the file's path where it stands": "gli argomenti prima del file; `{file}` mette il percorso del file al suo posto", "the camera roll could not be read": "impossibile leggere il rullino", + "the file's own": "quello del file", "the folder shown": "la cartella mostrata", "the folder shown (no folder is: pick one first)": "la cartella mostrata (nessuna: scegline prima una)", "the frames could not be matched to each other": "non è stato possibile far corrispondere i fotogrammi tra loro", "the measured positions were less reliable than the camera's own pattern": "le posizioni misurate erano meno affidabili del disegno proprio della fotocamera", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "l'applicazione predefinita del sistema per il tipo di file: Modifica nell'editor predefinito rende la copia e la consegna", + "the original, with an XMP sidecar": "l'originale, con un sidecar XMP", "the photos in view": "le foto nella vista", "the plug-in worker stopped unexpectedly": "il processo del plug-in si è fermato in modo imprevisto", + "the raw data's own": "quello dei dati raw", "the selected photos": "le foto selezionate", "the whole catalog": "l’intero catalogo", "there was not enough memory for the registered merge": "memoria insufficiente per l’unione registrata", @@ -3868,6 +3906,7 @@ "video playback isn't available in this build": "la riproduzione video non è disponibile in questa versione", "waiting for Apple Photos": "in attesa di Apple Photos", "width": "larghezza", + "write the edits beside the file": "scrive le modifiche accanto al file", "{app}": "{app}", "{app} Effect Presets": "Preset di effetti di {app}", "{app} Export Presets": "Predefiniti di esportazione di {app}", diff --git a/crates/ui-egui/locales/fork/ja-formats.json b/crates/ui-egui/locales/fork/ja-formats.json index 9e98702f82..fa21d54e78 100644 --- a/crates/ui-egui/locales/fork/ja-formats.json +++ b/crates/ui-egui/locales/fork/ja-formats.json @@ -123,6 +123,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "マニフェストに、このバージョンが使えず省く値があります: {values}", "JPEG quality {q} to fit the size limit": "サイズ制限に収めるため JPEG 画質 {q}", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "サイズ制限に収めるため JPEG 画質 {q}(サイズを小さくするか制限を大きくすると画質を保てます)", + "Kept with {raw} as its companion: not a photo of its own.": "{raw} のコンパニオンとして一緒に保管されています。単独の写真ではありません。", "Kept. Groups left: {left}": "保持しました。残りのグループ: {left}", "Last checked {n} hours ago": "最後の確認: {n}時間前", "Last checked {n} minutes ago": "最後の確認: {n}分前", @@ -336,6 +337,7 @@ "{} keys": "{} のキー", "{} of {} from {host}": "{host}から {}/{}", "{} · {}. Kept in the catalog's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}。カタログの「denoise」フォルダーに保存されます。上限に達すると、どの写真にも使われていない古いものから削除されます。", + "· {companions} kept with their RAWs": "· {companions} は RAW と共に保管", "“{name}” added to Camera Profiles": "「{name}」をカメラプロファイルに追加しました", "“{name}” has its old settings again": "「{name}」は以前の設定に戻りました", "“{name}” is new. What may the other devices syncing this catalog have of it?": "「{name}」は新規です。このカタログを同期している他のデバイスに何を許可しますか?", diff --git a/crates/ui-egui/locales/fork/ja.json b/crates/ui-egui/locales/fork/ja.json index 456f352d56..ea4280bac7 100644 --- a/crates/ui-egui/locales/fork/ja.json +++ b/crates/ui-egui/locales/fork/ja.json @@ -45,6 +45,7 @@ "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 ドライバーを読み込みません:", "8 bits/component": "8 bit/チャンネル", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} 枚合格、{pending} 枚要確認、{rejected} 枚不合格", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "RAW ファイルの隣にある同一名の JPEG はそのコンパニオンです。写真は 1 枚、顔検出は 1 回、メタデータは 1 組だけです。JPEG を個別の写真として読み込むには、コンパニオンのオプションをオフにしてください。", "A backup of the catalog is due. Back it up now, before {app} quits?": "カタログのバックアップの時期です。{app} を終了する前に今すぐバックアップしますか?", "A card, a drive or a folder": "カード、ドライブ、またはフォルダー", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "カタログはフォルダです:写真の記録、設定、履歴が入っています。写真そのものは元の場所に残ります。", @@ -108,6 +109,7 @@ "Add Blank": "空白ページを追加", "Add Cell": "セルを追加", "Add Column": "列を追加", + "Add Editor": "エディターを追加", "Add Face Model…": "顔モデルを追加…", "Add Face Region": "顔の領域を追加", "Add Filter…": "フィルターを追加…", @@ -261,6 +263,7 @@ "Assign to Someone Else…": "別の人物に割り当て…", "Assign to…": "割り当て先…", "At Import": "読み込み時", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "読み込み時、RAW ファイルの隣にある同一名の JPEG は個別の写真ではなく、その RAW のコンパニオンになります。サムネイルは 1 枚、顔検出は 1 回、メタデータは 1 組だけです。RAW のコピー、移動、名前変更にも一緒に付いていきます。", "At launch": "起動時", "At most one request per second.": "リクエストは最大で毎秒 1 回です。", "Attribution (shown on the map)": "帰属表示(地図に表示)", @@ -323,6 +326,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "最初のしきい値を下回ると 0★ のままです。既定値は 20、40、55、70、85 です。", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "両者の間では写真のフラグは変わりません(未設定は未設定のまま)。", "Bit Depth": "ビット数", + "Bit Level": "ビットレベル", "Black": "ブラック", "Black Point Compensation": "黒点の補正", "Blank": "空白", @@ -372,7 +376,9 @@ "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "ブラウザー版(試験的)、ライブラリを安全に保つ(issue #107): ファイル → ライブラリをバックアップ… でカタログを", "Brush (Return puts it down and paints, the arrows paint while it is down)": "ブラシ(Return で下ろして描画、下ろしている間は矢印キーで描画)", "Brush Refinement": "ブラシで調整", + "Build Face Thumbnails": "顔のサムネールを作成", "Build at import": "読み込み時に作成", + "Building face thumbnails": "顔のサムネールを作成中", "Building the profile…": "プロファイルを作成中…", "Built in the background once the photos are in, from the one on screen outward.": "写真の読み込み後、表示中の写真から順にバックグラウンドで作成されます。", "Built-in": "ビルトイン", @@ -540,6 +546,7 @@ "Choose folder later": "後でフォルダーを選択", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "アプリの見た目を選びます。変更はすぐに反映されます。さらに詳しくは 設定 → インターフェース へ。", "Choose in Sync…": "同期で選択…", + "Choose the Editor's Program": "エディターのプログラムを選択", "Choose the catalog to open.": "開くカタログを選択してください。", "Choose where to import from": "読み込み元を選択", "Circle": "円形", @@ -638,6 +645,7 @@ "Color to Replace": "置き換える色", "Color wheel": "カラーホイール", "Colour Profile": "カラープロファイル", + "Colour Space": "カラースペース", "Colour space of the TIFF": "TIFF のカラースペース", "Colour-label filter with several labels at once; expandable folder tree in Local.": "複数のカラーラベルで同時に絞り込み。ローカルで展開できるフォルダーツリー。", "Colour-range masks: click the photo to sample. Luminance ranges: range bar, smoothness, luminance map.": "カラー範囲マスク: 写真をクリックしてサンプリング。輝度範囲: 範囲バー、滑らかさ、輝度マップ。", @@ -653,6 +661,8 @@ "Compact Cells": "コンパクトセル", "Compact Layout": "コンパクトレイアウト", "Compact – Dense": "コンパクト – 高密度", + "Companion": "コンパニオン", + "Companion JPEG:": "コンパニオン JPEG:", "Compare Group in Survey": "グループを一覧比較で表示", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "完了", @@ -891,7 +901,7 @@ "Detecting faces…": "顔を検出しています…", "Detecting orientation": "向きを判定中", "Detection": "検出", - "Detection sensitivity": "検出感度", + "Detection sensitivity": "検出の感度", "Develop": "現像", "Develop Settings": "現像設定", "Develop preset": "現像プリセット", @@ -1020,13 +1030,16 @@ "Edit at History Step": "履歴の手順で編集", "Edit date": "編集日", "Edit in (one item)": "他で編集(1項目)", + "Edit in Default Editor": "標準エディターで編集", "Edit in External Editor (⇧⌘E): a 16-bit TIFF copy, stacked, refreshed when you come back.": "外部エディターで編集(⇧⌘E): 16 ビット TIFF のコピーをスタックし、戻ると更新します。", "Edit in HDR: highlights above SDR white, for HDR exports and displays": "HDR で編集:SDR の白を超えるハイライトを、HDR の書き出しとディスプレイ向けに扱います", "Edit in Other Editor": "他のエディターで編集", "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "他のエディターで編集(⌥⌘E)はこのアプリケーションでコピーを開きます(macOS ではアプリ名、その他ではプログラムのパス)。", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "別のエディターで編集 (⌥⌘E) はコピーをこのアプリケーションで開きます (macOS はアプリケーション名、その他はプログラムのパス)。場所が空ならシステムの標準アプリケーションが開きます。", "Edit in PhotoCraft": "PhotoCraft で編集", "Edit this saved location": "この保存済みの場所を編集", "Edited Version Saved Again": "編集したバージョンを再保存しました", + "Editors": "エディター", "Edit…": "編集…", "Elsewhere": "それ以外では", "Email": "メール", @@ -1321,6 +1334,7 @@ "Forget Remembered Object": "記憶したオブジェクトを消去", "Forget This Person": "この人物を消去", "Forget a Paired Surface": "ペアリングしたサーフェスを解除", + "Format Options": "形式オプション", "Found automatically": "自動検出", "Four with Caption": "4 枚とキャプション", "Frame": "フレーム", @@ -1446,6 +1460,7 @@ "Hard Drive": "ハードドライブ", "Hardcover": "ハードカバー", "Has a GPS position (click to show it on the map)": "GPS 位置情報あり(クリックで地図に表示)", + "Has a companion JPEG (click to open the Info panel)": "コンパニオン JPEG があります(クリックで情報パネルを開く)", "Headline metadata": "メタデータの見出し", "Headroom": "ヘッドルーム", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "顔の肌にある小さな暗い点や赤い点を修復します。目・眉・鼻の穴・唇はそのままです", @@ -1473,7 +1488,7 @@ "Hide {app}": "{app}を隠す", "High Range": "高レンジ", "High quality adjustment previews": "調整中の高画質プレビュー", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "信頼度を高くすると誤検出の顔は減りますが、実際の顔を見落とすことがあります。今後の検出に適用されます。既存の検出を更新するには再スキャンしてください。", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "信頼度を上げると誤検出は減りますが、実際の顔を見逃すことがあります。今後の検出に適用されます。既存の検出を更新するには再スキャンしてください。", "Highlight Hue": "ハイライトの色相", "Highlight Luminance": "ハイライトの輝度", "Highlight Reconstruction": "ハイライト再構築", @@ -1574,6 +1589,7 @@ "Import Mask Effects": "マスクエフェクトを読み込み", "Import Metadata Presets": "メタデータプリセットを読み込む", "Import New Shots": "新しいショットを読み込む", + "Import Order": "読み込み順", "Import People": "人物を読み込み", "Import People from Immich": "Immich から人物を読み込む", "Import Photos and Video…": "写真とビデオを読み込む…", @@ -1668,6 +1684,7 @@ "Install the Surface Plugin": "サーフェスプラグインをインストール", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "独自のONNXモデルを、同じ場所に denoise-model.json を置いてインストールしてください。このビルドではモデルをダウンロードできません。", "Installed": "インストール済み", + "Installed editors…": "インストール済みのエディター…", "Installed in": "インストール先", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "インストールしただけでは何も許可されません。プラグインは各権限が初めて必要になったときに確認を求めます。", "Install…": "インストール…", @@ -1754,6 +1771,7 @@ "Large Landscape (13 × 11 in)": "ラージ横 (13 × 11 in)", "Large and Small": "大と小", "Large image size": "大きい画像のサイズ", + "Largest Face": "顔の大きい順", "Last Photo": "最後の写真", "Last backup:": "前回のバックアップ:", "Last checked 1 hour ago": "最後の確認: 1時間前", @@ -1766,6 +1784,7 @@ "Last synced on {}": "最終同期:{}", "Last synced {} h ago": "最終同期:{} 時間前", "Last synced {} min ago": "最終同期:{} 分前", + "Launch Options": "起動オプション", "Layout": "レイアウト", "Layout Image Matte": "レイアウト画像のマット", "Layout Image Off": "レイアウト画像をオフ", @@ -2083,6 +2102,7 @@ "New Template Folder": "新規テンプレートフォルダ", "New Web Template Folder": "新規Webテンプレートフォルダー", "New collections": "新しいコレクション", + "New editor": "新しいエディター", "New group (press Return)": "新規グループ(Return キー)", "New group name": "新しいグループ名", "New group:": "新規グループ:", @@ -2094,6 +2114,7 @@ "New red eye correction (Return adds it here)": "新しい赤目補正(Return でここに追加)", "New shots:": "新しい撮影:", "New spot (Return adds it here)": "新しいスポット(Return でここに追加)", + "Newest First": "新しい順", "Next Filmstrip Background": "次のフィルムストリップの背景", "Next Frame": "次のフレーム", "Next History Step": "次の履歴の手順", @@ -2256,6 +2277,7 @@ "Offset Hue": "Offsetの色相", "Offset Luminance": "Offsetの明度", "Offset Saturation": "Offsetの彩度", + "Oldest First": "古い順", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "スキャンしたネガやポジで、フィルム上のゴミ、毛、傷を見つけて修復します。スキャナーの赤外線パス(VueScanやSilverFastのRGBIファイル)があればその位置を使い、なければ画像の平坦な部分を探します", "On photo": "写真上", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "コレクションを所有するデバイスでは他のデバイスに許可する内容を、その他のデバイスではこのデバイスが受け取る内容を選びます。", @@ -2330,6 +2352,7 @@ "Optimize catalog after backing up": "バックアップ後にカタログを最適化", "Optional: where downloads go": "任意:ダウンロード先", "Orientation Detection Status": "向き判定の状態", + "Original (+XMP)": "オリジナル (+XMP)", "Original Photo": "元の写真", "Other": "その他", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "他のアプリでも評価、キーワード、編集が見えるようになります。各写真の隣に小さなファイルを書き込みます。", @@ -2412,6 +2435,7 @@ "Permissions": "権限", "Permissions:": "権限:", "Persistent": "常駐", + "Person Sort": "人物の並べ替え", "Personalize {app} with your own branding elements.": "独自のブランド要素で {app} をパーソナライズします。", "Personalized": "パーソナライズ", "Phone": "電話", @@ -2428,6 +2452,7 @@ "Photo with Side Text": "写真と横テキスト", "Photo with Title": "写真とタイトル", "Photo zoom": "写真のズーム", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "写真 → 他のツールで編集 にエディターを並べます。最初の 2 つは内蔵です。好きなだけ追加し、行をクリックして渡すファイルを設定できます。", "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.": "写真 → 他のツールで編集 → PhotoCraft で編集(⇧⌘E、または写真を右クリック)は、編集を反映したコピーを書き出し、元の写真とスタックして PhotoCraft で開きます。PhotoCraft で保存すると、ここのコピーも更新されます。PSD の場合、PhotoCraft はそのファイルに直接保存します。ポータブル版を使う場合を除き、場所は空欄のままにしてください。", "PhotoCraft": "PhotoCraft", "Photograph Information": "撮影情報", @@ -3398,6 +3423,7 @@ "Text Page": "テキストページ", "Text Style Preset": "テキストスタイルプリセット", "Text size": "文字サイズ", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "この RAW ファイルの隣にある JPEG は一緒に保管されます。単独の写真ではありません。", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "プロファイルマネージャーには、すべてのルック、LUT プロファイル、カメラプロファイルが一覧表示されます。メニューから非表示にしたり、名前の変更やグループ化、新規の読み込み、自分のプロファイルの削除ができます。", "The account has no PIN or password, so there is nothing to unlock.": "このアカウントには PIN もパスワードも設定されていないため、ロック解除できるものがありません。", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "アクティブな写真はジオタグの位置(または地図の中心)で撮影されました:トラックに合わせます", @@ -3619,6 +3645,7 @@ "Tracklog": "トラックログ", "Transform": "変形", "Trash renders taken out of a collection": "コレクションから外した書き出し版をゴミ箱へ", + "Treat JPEGs next to raw files as companions": "RAW ファイルの隣の JPEG をコンパニオンとして扱う", "Trim": "トリミング", "Trim End": "トリム終了", "Trim Start": "トリム開始", @@ -3712,6 +3739,7 @@ "Update to Current Process": "現在のプロセスに更新", "Update to Current Process Version": "現在のプロセスバージョンに更新", "Update with Current Settings…": "現在の設定で更新…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "アップデートはオフです({env}_DISABLE_UPDATES が設定されています)。アップデートはパッケージマネージャーが行います。", "Updates the installed version": "インストール済みのバージョンを更新します", "Updates…": "アップデート…", "Updating the DNG previews stopped unexpectedly": "DNG プレビューの更新が予期せず停止しました", @@ -3843,6 +3871,7 @@ "Wrong passphrase.": "パスフレーズが違います。", "Wrote {} XMP sidecars": "{} 個の XMP サイドカーを書き出しました", "X": "X", + "XMP Sidecar": "XMP サイドカー", "XMP Sidecars": "XMP サイドカー", "Y": "Y", "Yellow Label": "イエローラベル", @@ -3876,10 +3905,13 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` にライブラリ自体のファイル(`catalog.snap`)を指定すると、エラーで失敗せずにそのフォルダーを開くようになりました:", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import `(およびフォルダーを受け取る MCP ツール)で、HEIC、HEIF、ニコン NRW も読み込むようになりました", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` は警告も stderr に出力します(issue #168)。`{env}_LOG` または `RUST_LOG` で別のレベルを選べます。", + "a copy of the original": "オリジナルのコピー", + "a copy of the original, with an XMP sidecar": "オリジナルのコピー (XMP サイドカー付き)", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "ドライブがいっぱい)は作成済みとみなされず、スマートプレビューを作成で置き換えられます。", "a photo matches any group": "写真がいずれかのグループに一致", "a photo matches every group": "写真がすべてのグループに一致", "a word per topic; every word must match": "1語が1つの話題。すべての語が一致する必要があります", + "adds an editor; click its row to name it and choose its program and file": "行を追加します。クリックして名前を付け、プログラムと渡すファイルを選びます", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "後で(issue #101): {app} が再試行する前に部分的な書き込みは切り捨てられるため、次回起動時にすべて", "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.": "ライブラリの元ファイルとの照合で、そのパスに何もない場合にライブラリ全体をスキャンしなくなりました。", @@ -4037,6 +4069,7 @@ "renders and screenshots are still written to a temp file and renamed into place, but no longer forced to disk": "レンダリングとスクリーンショットは引き続き一時ファイルに書き込んで名前を変えますが、ディスクへの強制書き込みはしなくなりました", "role": "役割", "save goes through.": "保存が完了するまで。", + "scene-linear Rec. 2020": "シーンリニア Rec. 2020", "selected photos": "選択した写真", "shots": "枚", "siblings) no longer open bright green (issue #148): their as-shot white balance and black level are read from the": "兄弟機種)が鮮やかな緑で開かなくなりました(issue #148): 撮影時のホワイトバランスと黒レベルを次から読み取ります:", @@ -4054,16 +4087,21 @@ "the Local folder tree and Auto Import read the disk on worker threads too. The import progress window has Cancel.": "ローカルのフォルダーツリーと自動読み込みもワーカースレッドでディスクを読みます。読み込みの進行状況ウィンドウにキャンセルがあります。", "the Photo menu and the photo context menu) picks up the full-size preview and fills in the camera metadata they": "写真メニューと写真のコンテキストメニュー)でフルサイズのプレビューを取得し、カメラのメタデータを補います", "the active photo isn't a video": "アクティブな写真はビデオではありません", + "the arguments before the file; `{file}` places the file's path where it stands": "ファイルの前に渡す引数。`{file}` の位置にファイルのパスが入ります", "the camera roll could not be read": "カメラロールを読み取れませんでした", "the camera; mapped-out sensor defects are filled in. `.rwl` and `.raw` files are imported too. Photos already": "カメラ。マップされたセンサー欠陥は補間されます。`.rwl` と `.raw` ファイルも読み込まれます。既に", + "the file's own": "ファイルのまま", "the folder shown": "表示中のフォルダー", "the folder shown (no folder is: pick one first)": "表示中のフォルダー(フォルダー未選択:先に選んでください)", "the frames could not be matched to each other": "コマどうしを対応づけられませんでした", "the graphics card": "グラフィックカード", "the graphics card is not used": "グラフィックカードは使用しません", "the measured positions were less reliable than the camera's own pattern": "測定した位置は、カメラ自身のパターンより信頼できませんでした", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "このファイル形式に対するシステムの標準アプリケーション。「標準エディターで編集」はコピーをレンダリングして渡します", + "the original, with an XMP sidecar": "オリジナル (XMP サイドカー付き)", "the photos in view": "表示中の写真", "the plug-in worker stopped unexpectedly": "プラグインのワーカーが予期せず停止しました", + "the raw data's own": "RAW データのまま", "the same name and \"Overwrite\" (or Export with Previous repeating it), an exact output path from the control": "同じ名前で「上書き」(または前回の設定で書き出しで繰り返す)、コントロールの正確な出力パス", "the selected photos": "選択した写真", "the whole catalog": "カタログ全体", @@ -4092,6 +4130,7 @@ "whether originals are there is checked on a worker thread (grid thumbnails, the Info panel, the photo menu, Missing": "元ファイルの有無はワーカースレッドで確認されます(グリッドのサムネイル、情報パネル、写真メニュー、見つからない", "width": "幅", "with a counterpart here come along, the rest is listed.": "ここに対応するものがあれば一緒に読み込まれ、残りは一覧表示されます。", + "write the edits beside the file": "編集内容をファイルの横に書き込む", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "より新しい {app} で書かれたものは「このライブラリはより新しいバージョンの {app} で書かれています」として拒否され、", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "より新しい {app} で書かれている)、{app} はその旨と理由を表示し、再試行、別のライブラリを選択…、続行", "{app}": "{app}", diff --git a/crates/ui-egui/locales/fork/ka-formats.json b/crates/ui-egui/locales/fork/ka-formats.json index f149d4add3..2833d976d6 100644 --- a/crates/ui-egui/locales/fork/ka-formats.json +++ b/crates/ui-egui/locales/fork/ka-formats.json @@ -148,6 +148,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "მის მანიფესტს აქვს მნიშვნელობები, რომლებსაც ეს ვერსია ვერ იყენებს და გამოტოვებს: {values}", "JPEG quality {q} to fit the size limit": "JPEG-ის ხარისხი {q}, ზომის ლიმიტში მოსახვედრად", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "JPEG-ის ხარისხი {q}, ზომის ლიმიტში მოსახვედრად (უფრო მცირე ზომა ან უფრო დიდი ლიმიტი მეტ ხარისხს ინარჩუნებს)", + "Kept with {raw} as its companion: not a photo of its own.": "{raw}-თან ერთად თანმხლებად ინახება: ცალკე ფოტო არ არის.", "Kept. Groups left: {left}": "შენარჩუნებულია. დარჩენილი ჯგუფები: {left}", "Key from the environment variable {}": "გასაღები გარემოს ცვლადიდან {}", "Key saved (ends in {})": "გასაღები შენახულია (ბოლოვდება {}-ით)", @@ -418,6 +419,7 @@ "{} fixed: {} known for camera {}, {} found in this photo": "გასწორდა {}: {} ცნობილია კამერისთვის {}, {} ნაპოვნია ამ ფოტოში", "{} keys": "{}-ის კლავიშები", "{} spot(s) from Remove Dust (outlined in amber)": "{} ლაქა მტვრის მოცილებიდან (ქარვისფრად შემოხაზული)", + "· {companions} kept with their RAWs": "· {companions} თავის raw-ებთან ერთად ინახება", "“{name}” added to Camera Profiles": "„{name}“ დაემატა კამერის პროფილებს", "“{name}” has its old settings again": "„{name}“-ს კვლავ ძველი პარამეტრები აქვს", "“{name}” is new. What may the other devices syncing this catalog have of it?": "„{name}“ ახალია. რა შეიძლება ჰქონდეთ მისგან ამ კატალოგის სინქრონიზებულ სხვა მოწყობილობებს?", diff --git a/crates/ui-egui/locales/fork/ka.json b/crates/ui-egui/locales/fork/ka.json index fb819e38e9..50faf8a3d5 100644 --- a/crates/ui-egui/locales/fork/ka.json +++ b/crates/ui-egui/locales/fork/ka.json @@ -46,6 +46,7 @@ "8 bits/component": "8 ბიტი/კომპონენტი", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} მიღებული, {pending} გადასახედი, {rejected} უარყოფილი", "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 JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "raw ფაილის გვერდით იმავე სახელით არსებული JPEG მისი თანმხლებია: ერთი ფოტო, ერთი სახის სკანირება, მეტამონაცემთა ერთი ნაკრები. JPEG-ების ცალკე ფოტოებად შესამოღებლად მოაშორეთ მონიშვნა თანმხლებების ვარიანტს.", "A backup of the catalog is due. Back it up now, before {app} quits?": "კატალოგის სარეზერვო ასლის დროა. შევქმნათ ახლავე, სანამ {app} დაიხურება?", "A camera profile is being built": "კამერის პროფილი იქმნება", "A camera profile is for one camera: use a photo from the same camera body.": "კამერის პროფილი ერთი კამერისთვისაა: გამოიყენეთ იმავე კამერის კორპუსით გადაღებული ფოტო.", @@ -118,6 +119,7 @@ "Add Blank": "ცარიელის დამატება", "Add Cell": "უჯრის დამატება", "Add Column": "სვეტის დამატება", + "Add Editor": "რედაქტორის დამატება", "Add Face Region": "სახის რეგიონის დამატება", "Add Filter…": "ფილტრის დამატება…", "Add Folder": "საქაღალდის დამატება", @@ -286,6 +288,7 @@ "Assign to Someone Else…": "სხვისთვის მინიჭება…", "Assign to…": "მინიჭება…", "At Import": "იმპორტისას", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "იმპორტისას raw ფაილის გვერდით იმავე სახელით არსებული JPEG ცალკე ფოტო კი არ არის, არამედ მისი თანმხლები: ერთი მინიატურა, ერთი სახის სკანირება, მეტამონაცემთა ერთი ნაკრები. კოპირებისას, გადატანისას ან გადარქმევისას ის raw ფაილს მიჰყვება.", "At launch": "გაშვებისას", "At most one request per second.": "წამში მაქსიმუმ ერთი მოთხოვნა.", "Attribution (shown on the map)": "ავტორობა (ნაჩვენებია რუკაზე)", @@ -350,6 +353,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "მათ შორის ფოტო ინარჩუნებს თავის დროშას (დროშის გარეშე დარჩება დროშის გარეშე).", "Big steps": "დიდი ნაბიჯები", "Bit Depth": "ბიტური სიღრმე", + "Bit Level": "ბიტური სიღრმე", "Black": "შავი", "Black Point Compensation": "შავი წერტილის კომპენსაცია", "Blank": "ცარიელი", @@ -406,7 +410,9 @@ "Brush Flow": "ფუნჯის ნაკადი", "Brush Refinement": "ფუნჯით დახვეწა", "Brush Size": "ფუნჯის ზომა", + "Build Face Thumbnails": "სახეების მინიატურების შექმნა", "Build at import": "შექმნა იმპორტისას", + "Building face thumbnails": "სახეების მინიატურების შექმნა", "Building the profile…": "პროფილი იქმნება…", "Built in the background once the photos are in, from the one on screen outward.": "იქმნება ფონურ რეჟიმში ფოტოების დამატების შემდეგ, ეკრანზე ნაჩვენებიდან დაწყებული.", "Built-in": "ჩაშენებული", @@ -568,6 +574,7 @@ "Choose folder later": "საქაღალდის მოგვიანებით არჩევა", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "აირჩიეთ აპის იერსახე. ყოველი ცვლილება მაშინვე ჩანს; მეტი იხილეთ პარამეტრები → ინტერფეისში.", "Choose in Sync…": "არჩევა სინქრონიზაციაში…", + "Choose the Editor's Program": "აირჩიეთ რედაქტორის პროგრამა", "Choose the catalog to open.": "აირჩიეთ გასახსნელი კატალოგი.", "Choose where to import from": "აირჩიეთ, საიდან მოხდეს იმპორტი", "Cinema Wide": "კინოს ფართო", @@ -675,6 +682,7 @@ "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "ფერები ცხრილს ემთხვევა; თითოეული ინარჩუნებს კამერის მიერ ჩაწერილ სიღიავეს. ადამიანებისა და ყოველდღიური ფოტოებისთვის.", "Colour": "ფერი", "Colour Profile": "ფერის პროფილი", + "Colour Space": "ფერთა სივრცე", "Colour knobs P1–P8": "ფერის სახელურები P1–P8", "Colour only": "მხოლოდ ფერი", "Colour space of the TIFF": "TIFF-ის ფერთა სივრცე", @@ -695,6 +703,8 @@ "Compact Cells": "კომპაქტური უჯრები", "Compact Layout": "კომპაქტური განლაგება", "Compact – Dense": "კომპაქტური – მჭიდრო", + "Companion": "თანმხლები", + "Companion JPEG:": "თანმხლები JPEG:", "Compare Group in Survey": "ჯგუფის შედარება მიმოხილვაში", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "დასრულებულია", @@ -1078,6 +1088,8 @@ "Edit at History Step": "რედაქტირება ისტორიის ნაბიჯზე", "Edit date": "რედაქტირების თარიღი", "Edit in (one item)": "რედაქტირება პროგრამაში (ერთი პუნქტი)", + "Edit in Default Editor": "ნაგულისხმევ რედაქტორში რედაქტირება", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "სხვა რედაქტორში რედაქტირება (⌥⌘E) ასლს ამ აპლიკაციაში ხსნის (macOS-ზე აპლიკაციის სახელი, სხვაგან, პროგრამის ბილიკი). ადგილი ცარიელია, სისტემის ნაგულისხმევი აპლიკაცია ხსნის.", "Edit this saved location": "ამ შენახული მდებარეობის რედაქტირება", "Edit: Color": "რედაქტირება: ფერი", "Edit: Detail": "რედაქტირება: დეტალი", @@ -1086,6 +1098,7 @@ "Edit: Light": "რედაქტირება: სინათლე", "Edit: Optics": "რედაქტირება: ოპტიკა", "Edited Version Saved Again": "რედაქტირებული ვერსია ხელახლა შეინახა", + "Editors": "რედაქტორები", "Edit…": "რედაქტირება…", "Elsewhere": "სხვაგან", "Email": "ელფოსტა", @@ -1406,6 +1419,7 @@ "Forget Remembered Object": "დამახსოვრებული ობიექტის დავიწყება", "Forget This Person": "ამ ადამიანის დავიწყება", "Forget a Paired Surface": "დაწყვილებული პანელის დავიწყება", + "Format Options": "ფორმატის პარამეტრები", "Four with Caption": "ოთხი წარწერით", "Frame": "ჩარჩო", "Frame Rate": "კადრების სიხშირე", @@ -1544,6 +1558,7 @@ "Hard Drive": "მყარი დისკი", "Hardcover": "მაგარი ყდა", "Has a GPS position (click to show it on the map)": "აქვს GPS მდებარეობა (დააწკაპუნეთ რუკაზე საჩვენებლად)", + "Has a companion JPEG (click to open the Info panel)": "აქვს თანმხლები JPEG (დააკლიკეთ ინფო-პანელის გასახსნელად)", "Headline metadata": "მთავარი სათაურის მეტამონაცემები", "Headroom": "HDR მარაგი", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "სახეების კანზე პატარა მუქი ან წითელი ლაქების აღდგენა; თვალები, წარბები, ნესტოები და ტუჩები ხელუხლებელი რჩება", @@ -1572,7 +1587,7 @@ "Hide this wheel's effect": "ამ ბორბლის ეფექტის დამალვა", "High Range": "მაღალი დიაპაზონი", "High quality adjustment previews": "მაღალი ხარისხის გადახედვა კორექტირებისას", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "მაღალი სანდოობა ნაკლებ ცრუ სახეს პოულობს, მაგრამ შეიძლება ნამდვილი სახეები გამოტოვოს. ვრცელდება მომავალ აღმოჩენებზე; არსებულის გასაახლებლად ხელახლა დაასკანერეთ.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "უფრო მაღალი სანდოობა ნაკლებ ცრუ სახეს პოულობს, მაგრამ რეალური შეიძლება გამოეპაროს. მომავალ აღმოჩენებზე ვრცელდება; არსებულის გასაახალისებლად ხელახლა დაასკანერეთ.", "Highlight Hue": "ღია ტონების ფერის ტონი", "Highlight Luminance": "ღია ტონების სიკაშკაშე", "Highlight Reconstruction": "ნათელი უბნების აღდგენა", @@ -1676,6 +1691,7 @@ "Import Mask Effects": "ნიღბის ეფექტების იმპორტი", "Import Metadata Presets": "მეტამონაცემების პრესეტების იმპორტი", "Import New Shots": "ახალი კადრების იმპორტი", + "Import Order": "იმპორტის თანმიმდევრობა", "Import People": "ადამიანების იმპორტი", "Import People from Immich": "ადამიანების იმპორტი Immich-იდან", "Import Photos and Video…": "ფოტოებისა და ვიდეოს იმპორტი…", @@ -1764,6 +1780,7 @@ "Install the plugin": "დანამატის ინსტალაცია", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "დააინსტალირეთ საკუთარი ONNX მოდელი, მის გვერდით denoise-model.json-ით. ეს ვერსია მოდელების ჩამოტვირთვას არ გთავაზობთ.", "Installed": "დაინსტალირებულია", + "Installed editors…": "დაინსტალირებული რედაქტორები…", "Installed in": "დაინსტალირებულია აქ:", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "ინსტალაცია არცერთს არ რთავს: დანამატი გკითხავთ, როცა თითოეული პირველად დასჭირდება.", "Installing the surface plugin": "პანელის დანამატის ინსტალაცია მიმდინარეობს", @@ -1871,6 +1888,7 @@ "Large Landscape (13 × 11 in)": "დიდი ჰორიზონტალური (13 × 11 in)", "Large and Small": "დიდი და პატარა", "Large image size": "დიდი გამოსახულების ზომა", + "Largest Face": "უდიდესი სახე", "Last Photo": "ბოლო ფოტო", "Last backup:": "ბოლო სარეზერვო ასლი:", "Last checked 1 hour ago": "ბოლოს შემოწმდა 1 საათის წინ", @@ -1883,6 +1901,7 @@ "Last synced on {}": "ბოლოს სინქრონიზებულია: {}", "Last synced {} h ago": "ბოლოს სინქრონიზებულია {} სთ-ის წინ", "Last synced {} min ago": "ბოლოს სინქრონიზებულია {} წთ-ის წინ", + "Launch Options": "გაშვების პარამეტრები", "Layout": "განლაგება", "Layout Image Matte": "განლაგების სურათის პასპარტუ", "Layout Image Off": "განლაგების სურათი გამორთულია", @@ -2221,6 +2240,7 @@ "New Template Folder": "შაბლონების ახალი საქაღალდე", "New Web Template Folder": "ვებ შაბლონების ახალი საქაღალდე", "New collections": "ახალი კოლექციები", + "New editor": "ახალი რედაქტორი", "New group (press Return)": "ახალი ჯგუფი (დააჭირეთ Return-ს)", "New group name": "ახალი ჯგუფის სახელი", "New group:": "ახალი ჯგუფი:", @@ -2233,6 +2253,7 @@ "New shots:": "ახალი კადრები:", "New spot (Return adds it here)": "ახალი ლაქა (Return მას აქ ამატებს)", "New template name": "ახალი შაბლონის სახელი", + "Newest First": "ჯერ უახლესი", "Next": "შემდეგი", "Next Dial Page": "სახელურების შემდეგი გვერდი", "Next Filmstrip Background": "ფირის ზოლის შემდეგი ფონი", @@ -2414,6 +2435,7 @@ "Offset Hue": "Offset-ის ტონი", "Offset Luminance": "Offset-ის სიკაშკაშე", "Offset Saturation": "Offset-ის გაჯერება", + "Oldest First": "ჯერ უძველესი", "On": "ჩართული", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "დასკანერებულ ნეგატივზე ან სლაიდზე: ფირზე მტვრის, თმისა და ნაკაწრების პოვნა და გასწორება. სკანერის ინფრაწითელი გავლა (VueScan-ის ან SilverFast-ის RGBI ფაილი) ამბობს, სად არიან; სხვა შემთხვევაში სურათის გლუვი უბნები იძებნება", "On photo": "ფოტოზე", @@ -2491,6 +2513,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "არასავალდებულო: ცხრილის ფოტო სხვა განათებით, მაგალითად ვარვარების ნათურით, ორგანათებიან პროფილს ქმნის.", "Optional: where downloads go": "არასავალდებულო: ჩამოტვირთვების ადგილი", "Orientation Detection Status": "ორიენტაციის დადგენის სტატუსი", + "Original (+XMP)": "ორიგინალი (+XMP)", "Original Photo": "ორიგინალი ფოტო", "Other": "სხვა", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "მაშინ სხვა აპები დაინახავენ თქვენს შეფასებებს, საკვანძო სიტყვებს და რედაქტირებებს. ყოველი ფოტოს გვერდით პატარა ფაილი იწერება.", @@ -2585,6 +2608,7 @@ "Permissions": "ნებართვები", "Permissions:": "ნებართვები:", "Persistent": "მუდმივი", + "Person Sort": "პიროვნების სორტირება", "Personalize {app} with your own branding elements.": "მოარგეთ აპი საკუთარი ბრენდინგის ელემენტებით ({app}).", "Personalized": "პერსონალიზებული", "Phone": "ტელეფონი", @@ -2598,6 +2622,7 @@ "Photo with Side Text": "ფოტო გვერდითი ტექსტით", "Photo with Title": "ფოტო დასახელებით", "Photo zoom": "ფოტოების გადიდება", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "ფოტო → რედაქტირება სხვა პროგრამაში აქ თითოეულ რედაქტორს ჩამოთვლის. პირველი ორი ჩაშენებულია; დაამატეთ რამდენიც გინდათ და დააჭირეთ სტრიქონს, რომ შეცვალოთ რას გადასცემს.", "PhotoCraft": "PhotoCraft", "Photograph Information": "გადაღების ინფორმაცია", "Photographic": "ფოტოგრაფიული", @@ -3648,6 +3673,7 @@ "Text Style Preset": "ტექსტის სტილის პრესეტი", "Text overlays": "ტექსტური ზედდებები", "Text size": "ტექსტის ზომა", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "ამ raw ფაილის გვერდით მყოფი JPEG, მასთან ერთად ინახება: ცალკე ფოტო არ არის.", "The Loupedeck+ works through the {app} plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ მუშაობს დანამატით ({app}). ყოველი სახელური და ღილაკი იმას აკეთებს, რაც მასზე წერია, სანამ აქ არ დააყენებთ ან საკუთარ Loupedeck-ის პროფილს არ გადმოიტანთ (მხოლოდ განლაგება გადმოდის).", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console აპს ({app}) Logi Options+-ის დანამატით ({app}) უკავშირდება. ინსტალაცია დანამატს Logi Options+-ს გადასცემს, რომელიც დადასტურებას მოგთხოვთ.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "პროფილების მენეჯერი ჩამოთვლის ყველა იერსახეს, LUT პროფილს და კამერის პროფილს: დამალეთ ისინი მენიუებიდან, შეუცვალეთ სახელი და დააჯგუფეთ, შემოიტანეთ ახლები და წაშალეთ საკუთარი.", @@ -3896,6 +3922,7 @@ "Transform": "გარდაქმნა", "Trash": "ურნა", "Trash renders taken out of a collection": "კოლექციიდან ამოღებული რენდერების ურნაში გადატანა", + "Treat JPEGs next to raw files as companions": "JPEG-ების raw ფაილების გვერდით თანმხლებად ჩათვლა", "Trim": "მოჭრა", "Trim End": "ბოლოს მოჭრა", "Trim Start": "დასაწყისის მოჭრა", @@ -3992,6 +4019,7 @@ "Update this one automatically": "ამის ავტომატურად განახლება", "Update to Current Process Version": "მიმდინარე დამუშავების ვერსიამდე განახლება", "Update with Current Settings…": "განახლება მიმდინარე პარამეტრებით…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "განახლებები გამორთულია ({env}_DISABLE_UPDATES დაყენებულია); განახლებებს პაკეტების მმართველი უზრუნველყოფს.", "Updates the installed version": "აახლებს დაინსტალირებულ ვერსიას", "Updates…": "განახლებები…", "Updating the DNG previews stopped unexpectedly": "DNG გადახედვების განახლება მოულოდნელად შეჩერდა", @@ -4136,6 +4164,7 @@ "Wrote the XMP sidecars that were waiting": "მომლოდინე XMP თანმხლები ფაილები ჩაიწერა", "Wrote {} XMP sidecars": "ჩაიწერა XMP თანმხლები ფაილი: {}", "X": "X", + "XMP Sidecar": "XMP-საიდკარი", "XMP Sidecars": "XMP თანმხლები ფაილები", "Y": "Y", "Yellow Label": "ყვითელი იარლიყი", @@ -4177,9 +4206,12 @@ "Zoom to fill frame": "კადრის შევსებამდე მასშტაბირება", "Zoomed Page": "გადიდებული გვერდი", "Zoomed Page View": "გადიდებული გვერდის ხედი", + "a copy of the original": "ორიგინალის ასლი", + "a copy of the original, with an XMP sidecar": "ორიგინალის ასლი, XMP-საიდკარით", "a photo matches any group": "ფოტო ემთხვევა რომელიმე ჯგუფს", "a photo matches every group": "ფოტო ემთხვევა ყველა ჯგუფს", "a word per topic; every word must match": "თითო თემაზე ერთი სიტყვა; ყველა სიტყვა უნდა ემთხვეოდეს", + "adds an editor; click its row to name it and choose its program and file": "სტრიქონს ამატებს; დააჭირეთ მას, რომ რედაქტორს სახელი დაარქვათ და აირჩიოთ პროგრამა და ფაილი", "all of": "ყველა", "allowed": "დაშვებულია", "any of": "რომელიმე", @@ -4266,19 +4298,25 @@ "published": "გამოქვეყნებულია", "removed": "წაშლილია", "role": "როლი", + "scene-linear Rec. 2020": "სცენურ-ლინეარული Rec. 2020", "selected photos": "მონიშნული ფოტოები", "shots": "კადრი", "size": "ზომა", "source": "წყარო", "steps": "ნაბიჯი", "the active photo isn't a video": "აქტიური ფოტო ვიდეო არ არის", + "the arguments before the file; `{file}` places the file's path where it stands": "არგუმენტები ფაილამდე; `{file}` ფაილის ბილიკს ამ ადგილას დადებს", "the camera roll could not be read": "კამერის გალერეის წაკითხვა ვერ მოხერხდა", + "the file's own": "ფაილის საკუთარი", "the folder shown": "ნაჩვენები საქაღალდე", "the folder shown (no folder is: pick one first)": "ნაჩვენები საქაღალდე (საქაღალდე არ არის: ჯერ აირჩიეთ)", "the frames could not be matched to each other": "კადრების ერთმანეთთან შედარება ვერ მოხერხდა", "the measured positions were less reliable than the camera's own pattern": "გაზომილი პოზიციები კამერის საკუთარ შაბლონზე ნაკლებად საიმედო იყო", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "სისტემის ნაგულისხმევი აპლიკაცია ფაილის ამ ტიპისთვის: ნაგულისხმევ რედაქტორში რედაქტირება ასლს ასახავს და გადასცემს", + "the original, with an XMP sidecar": "ორიგინალი, XMP-საიდკარით", "the photos in view": "ხედში არსებული ფოტოები", "the plug-in worker stopped unexpectedly": "დანამატის დამმუშავებელი მოულოდნელად გაჩერდა", + "the raw data's own": "ნედლეული მონაცემების საკუთარი", "the selected photos": "არჩეული ფოტოები", "the whole catalog": "მთელი კატალოგი", "there was not enough memory for the registered merge": "რეგისტრირებული გაერთიანებისთვის მეხსიერება საკმარისი არ იყო", @@ -4298,6 +4336,7 @@ "video playback isn't available in this build": "ვიდეოს დაკვრა ამ ვერსიაში მიუწვდომელია", "waiting for Apple Photos": "ელოდება Apple Photos-ს", "width": "სიგანე", + "write the edits beside the file": "ჩასწორებებს ფაილის გვერდით წერს", "{app}": "{app}", "{app} Effect Presets": "ეფექტების პრესეტები ({app})", "{app} Export Presets": "{app}-ის ექსპორტის პრესეტები", diff --git a/crates/ui-egui/locales/fork/pl-formats.json b/crates/ui-egui/locales/fork/pl-formats.json index ebd5a3f86c..0f726bc435 100644 --- a/crates/ui-egui/locales/fork/pl-formats.json +++ b/crates/ui-egui/locales/fork/pl-formats.json @@ -127,6 +127,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Jego manifest zawiera wartości, których ta wersja nie może użyć, więc je pomija: {values}", "JPEG quality {q} to fit the size limit": "Jakość JPEG {q}, aby zmieścić się w limicie rozmiaru", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Jakość JPEG {q}, aby zmieścić się w limicie rozmiaru (mniejszy rozmiar lub większy limit zachowuje więcej jakości)", + "Kept with {raw} as its companion: not a photo of its own.": "Przechowywany z {raw} jako plik towarzyszący: to nie jest osobne zdjęcie.", "Kept. Groups left: {left}": "Zachowano. Pozostało grup: {left}", "Key from the environment variable {}": "Klucz ze zmiennej środowiskowej {}", "Key saved ({})": "Klucz zapisany ({})", @@ -345,6 +346,7 @@ "{} fixed: {} known for camera {}, {} found in this photo": "Usunięto: {}; znanych dla aparatu: {} ({}), znalezionych na tym zdjęciu: {}", "{} keys": "Klawisze dla {}", "{} spot(s) from Remove Dust (outlined in amber)": "Plamy z Usuwania kurzu: {} (obrysowane na bursztynowo)", + "· {companions} kept with their RAWs": "· {companions} przechowywane ze swoimi surowymi plikami", "“{name}” added to Camera Profiles": "Dodano „{name}” do profili aparatu", "“{name}” has its old settings again": "„{name}” ma znów dawne ustawienia", "“{name}” is new. What may the other devices syncing this catalog have of it?": "„{name}” jest nowa. Co mogą z niej mieć inne urządzenia synchronizujące ten katalog?", diff --git a/crates/ui-egui/locales/fork/pl.json b/crates/ui-egui/locales/fork/pl.json index 1ec7a691e8..ab1db9eb75 100644 --- a/crates/ui-egui/locales/fork/pl.json +++ b/crates/ui-egui/locales/fork/pl.json @@ -45,6 +45,7 @@ "8 bits/component": "8 bitów/składową", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} zaakceptowanych, {pending} do przejrzenia, {rejected} odrzuconych", "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Kadr 16:9 z czarnymi pasami u góry i u dołu, tytuł w rogu, przejścia przez czerń i plansza końcowa.", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "JPEG o nazwie surowego pliku obok niego jest jego plikiem towarzyszącym: jedno zdjęcie, jedno skanowanie twarzy, jeden zestaw metadanych. Aby importować JPEG jako osobne zdjęcia, odznacz opcję plików towarzyszących.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Nadszedł czas na kopię zapasową katalogu. Utworzyć ją teraz, przed zamknięciem programu {app}?", "A camera profile is being built": "Trwa tworzenie profilu aparatu", "A camera profile is for one camera: use a photo from the same camera body.": "Profil aparatu dotyczy jednego aparatu: użyj zdjęcia z tego samego korpusu.", @@ -113,6 +114,7 @@ "Add Blank": "Dodaj pustą", "Add Cell": "Dodaj komórkę", "Add Column": "Dodaj kolumnę", + "Add Editor": "Dodaj edytor", "Add Face Region": "Dodaj obszar twarzy", "Add Filter…": "Dodaj filtr…", "Add Folder": "Dodaj folder", @@ -274,6 +276,7 @@ "Assign to Someone Else…": "Przypisz komuś innemu…", "Assign to…": "Przypisz do…", "At Import": "Przy imporcie", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Przy imporcie JPEG o nazwie surowego pliku obok niego nie jest osobnym zdjęciem, lecz jego plikiem towarzyszącym: jedna miniatura, jedno skanowanie twarzy, jeden zestaw metadanych. Podąża za surowym plikiem przy kopiowaniu, przenoszeniu i zmianie nazwy.", "At launch": "Przy uruchomieniu", "At most one request per second.": "Najwyżej jedno zapytanie na sekundę.", "Attribution (shown on the map)": "Atrybucja (wyświetlana na mapie)", @@ -335,6 +338,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Pomiędzy nimi zdjęcie zachowuje swój znacznik (bez znacznika pozostaje bez niego).", "Big steps": "Duże kroki", "Bit Depth": "Głębia bitowa", + "Bit Level": "Głębia bitów", "Black": "Czerń", "Black Point Compensation": "Kompensacja punktu czerni", "Blank": "Puste", @@ -391,7 +395,9 @@ "Brush Flow": "Przepływ pędzla", "Brush Refinement": "Korekta pędzlem", "Brush Size": "Rozmiar pędzla", + "Build Face Thumbnails": "Utwórz miniatury twarzy", "Build at import": "Twórz przy imporcie", + "Building face thumbnails": "Tworzenie miniatur twarzy", "Building the profile…": "Tworzenie profilu…", "Built in the background once the photos are in, from the one on screen outward.": "Tworzone w tle po dodaniu zdjęć, zaczynając od tego na ekranie.", "Built-in": "Wbudowane", @@ -552,6 +558,7 @@ "Choose folder later": "Wybierz folder później", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Wybierz wygląd aplikacji. Każdą zmianę widać od razu; więcej w Ustawienia → Interfejs.", "Choose in Sync…": "Wybierz w Synchronizacji…", + "Choose the Editor's Program": "Wybierz program edytora", "Choose the catalog to open.": "Wybierz katalog do otwarcia.", "Choose where to import from": "Wybierz, skąd importować", "Cinema Wide": "Kinowy panoramiczny", @@ -655,6 +662,7 @@ "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "Kolory zgodne ze wzornikiem; każdy zachowuje jasność zarejestrowaną przez aparat. Do zdjęć ludzi i codziennych.", "Colour": "Kolor", "Colour Profile": "Profil kolorów", + "Colour Space": "Przestrzeń barw", "Colour only": "Tylko kolor", "Colour space of the TIFF": "Przestrzeń barw pliku TIFF", "Colour wash": "Przebarwienie", @@ -674,6 +682,8 @@ "Compact Cells": "Kompaktowe komórki", "Compact Layout": "Układ kompaktowy", "Compact – Dense": "Kompaktowy – gęsty", + "Companion": "Towarzyszący", + "Companion JPEG:": "Towarzyszący JPEG:", "Compare Group in Survey": "Porównaj grupę w Przeglądzie", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Gotowe", @@ -1041,8 +1051,10 @@ "Edit at History Step": "Edytuj od kroku historii", "Edit date": "Data edycji", "Edit in (one item)": "Edytuj w (jeden element)", + "Edit in Default Editor": "Edytuj w edytorze domyślnym", "Edit in HDR: highlights above SDR white, for HDR exports and displays": "Edycja w HDR: światła powyżej bieli SDR, do eksportu i ekranów HDR", "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Edytuj w innym edytorze (⌥⌘E) otwiera kopię w tej aplikacji (nazwa aplikacji w macOS, ścieżka programu w innych systemach).", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Edytuj w innym edytorze (⌥⌘E) otwiera kopię w tej aplikacji (nazwa aplikacji na macOS, ścieżka programu w pozostałych). Gdy miejsce jest puste, kopię otwiera domyślna aplikacja systemu.", "Edit this saved location": "Edytuj tę zapisaną lokalizację", "Edit: Color": "Edycja: Kolor", "Edit: Detail": "Edycja: Szczegóły", @@ -1051,6 +1063,7 @@ "Edit: Light": "Edycja: Światło", "Edit: Optics": "Edycja: Optyka", "Edited Version Saved Again": "Wersja edytowana zapisana ponownie", + "Editors": "Edytory", "Edit…": "Edytuj…", "Elsewhere": "Gdzie indziej", "Email": "E-mail", @@ -1361,6 +1374,7 @@ "Forget Remembered Object": "Zapomnij zapamiętany obiekt", "Forget This Person": "Zapomnij tę osobę", "Forget a Paired Surface": "Zapomnij sparowane urządzenie", + "Format Options": "Opcje formatu", "Found automatically": "Znaleziono automatycznie", "Four with Caption": "Cztery z podpisem", "Frame": "Ramka", @@ -1496,6 +1510,7 @@ "Hard Drive": "Dysk twardy", "Hardcover": "Twarda oprawa", "Has a GPS position (click to show it on the map)": "Ma pozycję GPS (kliknij, aby pokazać ją na mapie)", + "Has a companion JPEG (click to open the Info panel)": "Ma towarzyszący JPEG (kliknij, aby otworzyć panel informacji)", "Headline metadata": "Metadane nagłówka", "Headroom": "Zapas jasności HDR", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Koryguj drobne ciemne lub czerwone plamki na skórze twarzy; oczy, brwi, nozdrza i usta pozostają nietknięte", @@ -1523,7 +1538,7 @@ "Hide this wheel's effect": "Ukryj działanie tego koła", "High Range": "Górny zakres", "High quality adjustment previews": "Podgląd korekt w wysokiej jakości", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Wyższa pewność daje mniej fałszywych twarzy, ale może pominąć prawdziwe. Dotyczy przyszłych wykryć; przeskanuj ponownie, aby zaktualizować istniejące.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Wyższa pewność znajduje mniej fałszywych twarzy, ale może przeoczyć prawdziwe. Dotyczy przyszłych wykryć; aby zaktualizować istniejące, skanuj ponownie.", "Highlight Hue": "Odcień świateł", "Highlight Luminance": "Luminancja świateł", "Highlight Reconstruction": "Rekonstrukcja świateł", @@ -1625,6 +1640,7 @@ "Import Lightroom or Capture One Catalog…": "Importuj katalog Lightroom lub Capture One…", "Import Metadata Presets": "Importuj ustawienia wstępne metadanych", "Import New Shots": "Importuj nowe ujęcia", + "Import Order": "Kolejność importu", "Import People": "Importuj osoby", "Import People from Immich": "Importuj osoby z Immich", "Import Photos and Video…": "Importuj zdjęcia i wideo…", @@ -1707,6 +1723,7 @@ "Install the Surface Plugin": "Zainstaluj wtyczkę urządzenia sterującego", "Install the plugin": "Zainstaluj wtyczkę", "Installed": "Zainstalowane", + "Installed editors…": "Zainstalowane edytory…", "Installed in": "Zainstalowane w", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Instalacja nie przyznaje żadnego z nich: wtyczka zapyta, gdy po raz pierwszy będzie potrzebować danego uprawnienia.", "Installing the surface plugin": "Instalowanie wtyczki urządzenia sterującego", @@ -1813,6 +1830,7 @@ "Large Landscape (13 × 11 in)": "Duży poziomy (13 × 11 in)", "Large and Small": "Duże i małe", "Large image size": "Duży rozmiar obrazu", + "Largest Face": "Największa twarz", "Last Photo": "Ostatnie zdjęcie", "Last backup:": "Ostatnia kopia zapasowa:", "Last checked 1 hour ago": "Ostatnio sprawdzono 1 godz. temu", @@ -1825,6 +1843,7 @@ "Last synced on {}": "Ostatnia synchronizacja: {}", "Last synced {} h ago": "Ostatnia synchronizacja {} godz. temu", "Last synced {} min ago": "Ostatnia synchronizacja {} min temu", + "Launch Options": "Opcje uruchamiania", "Layout": "Układ", "Layout Image Off": "Obraz układu wyłączony", "Layout Image On": "Obraz układu włączony", @@ -2153,6 +2172,7 @@ "New Template Folder": "Nowy folder szablonów", "New Web Template Folder": "Nowy folder szablonów witryny", "New collections": "Nowe kolekcje", + "New editor": "Nowy edytor", "New group (press Return)": "Nowa grupa (naciśnij Return)", "New group name": "Nazwa nowej grupy", "New group:": "Nowa grupa:", @@ -2165,6 +2185,7 @@ "New shots:": "Nowe ujęcia:", "New spot (Return adds it here)": "Nowa plamka (Return dodaje ją tutaj)", "New template name": "Nazwa nowego szablonu", + "Newest First": "Najnowsze najpierw", "Next": "Dalej", "Next Filmstrip Background": "Następne tło taśmy filmowej", "Next Frame": "Następna klatka", @@ -2338,6 +2359,7 @@ "Offset Hue": "Odcień offset", "Offset Luminance": "Jasność offset", "Offset Saturation": "Nasycenie offset", + "Oldest First": "Najstarsze najpierw", "On": "Wł.", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Na zeskanowanym negatywie lub slajdzie: znajdź i napraw drobiny kurzu, włosy i rysy na filmie. Przebieg skanera w podczerwieni (plik RGBI z VueScan lub SilverFast) mówi, gdzie są; w przeciwnym razie przeszukiwane są gładkie obszary obrazu", "On photo": "Na zdjęciu", @@ -2412,6 +2434,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "Opcjonalnie: zdjęcie tablicy w innym świetle, np. żarowym, pozwala utworzyć profil dla dwóch iluminantów.", "Optional: where downloads go": "Opcjonalnie: miejsce pobierania", "Orientation Detection Status": "Stan wykrywania orientacji", + "Original (+XMP)": "Oryginał (+XMP)", "Original Photo": "Oryginalne zdjęcie", "Other": "Inne", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Inne aplikacje widzą wtedy oceny, słowa kluczowe i edycje. Obok każdego zdjęcia zapisywany jest mały plik.", @@ -2501,6 +2524,7 @@ "Permissions": "Uprawnienia", "Permissions:": "Uprawnienia:", "Persistent": "Trwały", + "Person Sort": "Sortowanie osoby", "Personalize {app} with your own branding elements.": "Spersonalizuj aplikację {app} własnymi elementami marki.", "Personalized": "Spersonalizowana", "Phone": "Telefon", @@ -2514,6 +2538,7 @@ "Photo with Side Text": "Zdjęcie z tekstem z boku", "Photo with Title": "Zdjęcie z tytułem", "Photo zoom": "Powiększenie zdjęć", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Zdjęcie → Edytuj w wymienia tu każdy edytor. Dwa pierwsze są wbudowane; dodaj ile chcesz i kliknij wiersz, aby zmienić, co przekazuje.", "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.": "Zdjęcie → Edytuj w → Edytuj w PhotoCraft (⇧⌘E lub prawy przycisk na zdjęciu) renderuje kopię z Twoimi zmianami, łączy ją w stos z oryginałem i otwiera w PhotoCraft. Zapisz tam, a kopia zaktualizuje się tutaj. W formacie PSD PhotoCraft zapisuje bezpośrednio do niej. Pozostaw lokalizację pustą, chyba że używasz wersji przenośnej.", "PhotoCraft": "PhotoCraft", "Photograph Information": "Informacje o fotografii", @@ -3500,6 +3525,7 @@ "Text Style Preset": "Ustawienie wstępne stylu tekstu", "Text overlays": "Nakładki tekstowe", "Text size": "Rozmiar tekstu", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "JPEG obok pliku surowego, przechowywany razem z nim: to nie jest osobne zdjęcie.", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console komunikuje się z {app} przez wtyczkę {app} dla Logi Options+. Instalacja przekazuje wtyczkę do Logi Options+, który poprosi o potwierdzenie.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Menedżer profili zawiera każdy wygląd, profil LUT i profil aparatu: ukrywaj je w menu, zmieniaj im nazwy i grupuj, importuj nowe i usuwaj własne.", "The account has no PIN or password, so there is nothing to unlock.": "Konto nie ma kodu PIN ani hasła, więc nie ma czego odblokowywać.", @@ -3735,6 +3761,7 @@ "Tracklog": "Ślad GPS", "Transform": "Przekształcenie", "Trash renders taken out of a collection": "Przenoś do kosza rendery wyjęte z kolekcji", + "Treat JPEGs next to raw files as companions": "Traktuj pliki JPEG obok surowych plików jako towarzyszące", "Trim": "Przytnij", "Trim End": "Przytnij koniec", "Trim Start": "Przytnij początek", @@ -3827,6 +3854,7 @@ "Update this one automatically": "Aktualizuj tę automatycznie", "Update to Current Process Version": "Zaktualizuj do bieżącej wersji procesu", "Update with Current Settings…": "Aktualizuj bieżącymi ustawieniami…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Aktualizacje są wyłączone (ustawiono {env}_DISABLE_UPDATES); aktualizacjami zajmuje się menedżer pakietów.", "Updates the installed version": "Aktualizuje zainstalowaną wersję", "Updates…": "Aktualizacje…", "Updating the DNG previews stopped unexpectedly": "Aktualizacja podglądów DNG nieoczekiwanie się zatrzymała", @@ -3968,6 +3996,7 @@ "Wrote the XMP sidecars that were waiting": "Zapisano oczekujące pliki pomocnicze XMP", "Wrote {} XMP sidecars": "Zapisane pliki pomocnicze XMP: {}", "X": "X", + "XMP Sidecar": "Plik sidecar XMP", "XMP Sidecars": "Pliki pomocnicze XMP", "Y": "Y", "Yellow Label": "Żółta etykieta", @@ -4012,9 +4041,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` z plikiem samej biblioteki (`catalog.snap`) otwiera jej folder zamiast kończyć się błędem", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (i narzędzia MCP przyjmujące foldery) wykrywa teraz HEIC, HEIF i Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` zapisuje ostrzeżenia także na stderr (zgłoszenie #168); `{env}_LOG` lub `RUST_LOG` wybiera inny poziom.", + "a copy of the original": "kopia oryginału", + "a copy of the original, with an XMP sidecar": "kopia oryginału, z plikiem sidecar XMP", "a photo matches any group": "zdjęcie pasuje do dowolnej grupy", "a photo matches every group": "zdjęcie pasuje do każdej grupy", "a word per topic; every word must match": "jedno słowo na temat; każde słowo musi pasować", + "adds an editor; click its row to name it and choose its program and file": "dodaje wiersz; kliknij go, aby nazwać edytor i wybrać program oraz plik", "all of": "wszystkie", "allowed": "dozwolone", "any of": "dowolne", @@ -4101,6 +4133,7 @@ "published": "opublikowane", "removed": "usunięte", "role": "rola", + "scene-linear Rec. 2020": "liniowy Rec. 2020", "selected photos": "zaznaczone zdjęcia", "shots": "zdj.", "size": "rozmiar", @@ -4109,13 +4142,18 @@ "source": "źródło", "steps": "kr.", "the active photo isn't a video": "aktywne zdjęcie nie jest wideo", + "the arguments before the file; `{file}` places the file's path where it stands": "argumenty przed plikiem; `{file}` wstawia ścieżkę pliku w tym miejscu", "the camera roll could not be read": "nie udało się odczytać rolki aparatu", + "the file's own": "jak w pliku", "the folder shown": "wyświetlany folder", "the folder shown (no folder is: pick one first)": "wyświetlany folder (brak folderu: najpierw go wybierz)", "the frames could not be matched to each other": "nie udało się dopasować klatek do siebie", "the measured positions were less reliable than the camera's own pattern": "zmierzone położenia były mniej wiarygodne niż własny wzór aparatu", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "domyślna aplikacja systemu dla tego typu pliku: „Edytuj w edytorze domyślnym” renderuje kopię i przekazuje ją", + "the original, with an XMP sidecar": "oryginał, z plikiem sidecar XMP", "the photos in view": "zdjęcia w widoku", "the plug-in worker stopped unexpectedly": "wątek roboczy wtyczki nieoczekiwanie się zatrzymał", + "the raw data's own": "jak w danych surowych", "the selected photos": "wybrane zdjęcia", "the whole catalog": "cały katalog", "there was not enough memory for the registered merge": "za mało pamięci na scalenie z rejestracją", @@ -4136,6 +4174,7 @@ "video playback isn't available in this build": "odtwarzanie wideo jest niedostępne w tej kompilacji", "waiting for Apple Photos": "czeka na Apple Photos", "width": "szerokość", + "write the edits beside the file": "zapisuje edycje obok pliku", "{app}": "{app}", "{app} Effect Presets": "Ustawienia wstępne efektów {app}", "{app} Export Presets": "Ustawienia eksportu {app}", diff --git a/crates/ui-egui/locales/fork/pt-br-formats.json b/crates/ui-egui/locales/fork/pt-br-formats.json index 6409ab10d2..ad78916331 100644 --- a/crates/ui-egui/locales/fork/pt-br-formats.json +++ b/crates/ui-egui/locales/fork/pt-br-formats.json @@ -123,6 +123,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "O manifesto tem valores que esta versão não pode usar e deixa de fora: {values}", "JPEG quality {q} to fit the size limit": "Qualidade JPEG {q} para caber no limite de tamanho", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Qualidade JPEG {q} para caber no limite de tamanho (um tamanho menor ou um limite maior mantém mais qualidade)", + "Kept with {raw} as its companion: not a photo of its own.": "Mantido com {raw} como companheiro: não é uma foto própria.", "Kept. Groups left: {left}": "Mantido. Grupos restantes: {left}", "Last checked {n} hours ago": "Última verificação: há {n} horas", "Last checked {n} minutes ago": "Última verificação: há {n} minutos", @@ -336,6 +337,7 @@ "{} keys": "Teclas de {}", "{} of {} from {host}": "{} de {} de {host}", "{} · {}. Kept in the catalog's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Guardadas na pasta “denoise” do catálogo; ao atingir o limite, as mais antigas que nenhuma foto usa saem primeiro.", + "· {companions} kept with their RAWs": "· {companions} mantidos com seus raws", "“{name}” added to Camera Profiles": "“{name}” adicionado aos Perfis de câmera", "“{name}” has its old settings again": "“{name}” voltou às configurações antigas", "“{name}” is new. What may the other devices syncing this catalog have of it?": "“{name}” é nova. O que os outros dispositivos que sincronizam este catálogo podem ter dela?", diff --git a/crates/ui-egui/locales/fork/pt-br.json b/crates/ui-egui/locales/fork/pt-br.json index 0c184417e7..ddb1acf269 100644 --- a/crates/ui-egui/locales/fork/pt-br.json +++ b/crates/ui-egui/locales/fork/pt-br.json @@ -45,6 +45,7 @@ "630 drivers): on Windows the window and GPU rendering use DirectX 12 only and never load the Vulkan driver unless": "drivers 630): no Windows a janela e a renderização por GPU usam só DirectX 12 e nunca carregam o driver Vulkan, a menos que", "8 bits/component": "8 bits/componente", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} aceitas, {pending} a revisar, {rejected} rejeitadas", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "Um JPEG com o nome de um raw ao lado é seu companheiro: uma foto, uma detecção de rostos, um conjunto de metadados. Desmarque a opção de companheiros para importar os JPEGs como fotos próprias.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Está na hora de fazer backup do catálogo. Fazer agora, antes de o {app} fechar?", "A card, a drive or a folder": "Um cartão, uma unidade ou uma pasta", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "Um catálogo é uma pasta: os registros, as configurações e o histórico das fotos. As fotos em si ficam onde estão.", @@ -108,6 +109,7 @@ "Add Blank": "Adicionar em branco", "Add Cell": "Adicionar célula", "Add Column": "Adicionar coluna", + "Add Editor": "Adicionar editor", "Add Face Model…": "Adicionar modelo de rosto…", "Add Face Region": "Adicionar região de rosto", "Add Filter…": "Adicionar filtro…", @@ -261,6 +263,7 @@ "Assign to Someone Else…": "Atribuir a outra pessoa…", "Assign to…": "Atribuir a…", "At Import": "Na importação", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Na importação, um JPEG com o nome de um raw ao lado não é uma foto própria, mas o companheiro do raw: uma miniatura, uma detecção de rostos, um conjunto de metadados. Ele acompanha o raw ao copiar, mover ou renomear.", "At launch": "Ao iniciar", "At most one request per second.": "No máximo uma solicitação por segundo.", "Attribution (shown on the map)": "Atribuição (mostrada no mapa)", @@ -323,6 +326,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "Abaixo do primeiro limite fica 0★; os padrões são 20, 40, 55, 70 e 85.", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Entre os dois, a foto mantém seu marcador (sem marcador continua sem).", "Bit Depth": "Profundidade de bits", + "Bit Level": "Nível de bits", "Black": "Preto", "Black Point Compensation": "Compensação de ponto preto", "Blank": "Em branco", @@ -372,7 +376,9 @@ "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "Versão para navegador (experimental), mantendo a biblioteca segura (issue #107): Arquivo → Fazer backup da biblioteca… baixa o catálogo", "Brush (Return puts it down and paints, the arrows paint while it is down)": "Pincel (Enter o abaixa e pinta; as setas pintam enquanto ele está abaixado)", "Brush Refinement": "Refinamento com pincel", + "Build Face Thumbnails": "Criar miniaturas de rostos", "Build at import": "Gerar na importação", + "Building face thumbnails": "Criando miniaturas de rostos", "Building the profile…": "Criando o perfil…", "Built in the background once the photos are in, from the one on screen outward.": "Criadas em segundo plano depois que as fotos entram, a partir da que está na tela.", "Built-in": "Integrados", @@ -539,6 +545,7 @@ "Choose folder later": "Escolher pasta depois", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Escolha a aparência do app. Cada mudança aparece na hora; Configurações → Interface tem mais.", "Choose in Sync…": "Escolher em Sincronização…", + "Choose the Editor's Program": "Escolher o programa do editor", "Choose the catalog to open.": "Escolha o catálogo a abrir.", "Choose where to import from": "Escolha de onde importar", "Circle": "Círculo", @@ -637,6 +644,7 @@ "Color to Replace": "Cor a substituir", "Color wheel": "Roda de cores", "Colour Profile": "Perfil de cor", + "Colour Space": "Espaço de cor", "Colour space of the TIFF": "Espaço de cor do TIFF", "Colour-label filter with several labels at once; expandable folder tree in Local.": "Filtro de rótulo de cor com vários rótulos de uma vez; árvore de pastas expansível em Local.", "Colour-range masks: click the photo to sample. Luminance ranges: range bar, smoothness, luminance map.": "Máscaras de faixa de cor: clique na foto para amostrar. Faixas de luminância: barra de faixa, suavidade, mapa de luminância.", @@ -652,6 +660,8 @@ "Compact Cells": "Células compactas", "Compact Layout": "Layout compacto", "Compact – Dense": "Compacto – Denso", + "Companion": "Companheiro", + "Companion JPEG:": "JPEG companheiro:", "Compare Group in Survey": "Comparar grupo na Inspeção", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Concluído", @@ -659,7 +669,7 @@ "Compression (quality scan)": "Compactação (verificação de qualidade)", "Compression artifacts": "Artefatos de compressão", "Computing AI masks": "Calculando máscaras de IA", - "Confidence required": "Confiança necessária", + "Confidence required": "Confiança exigida", "Confirm": "Confirmar", "Confirm Faces from Immich": "Confirmar rostos do Immich", "Confirm Immich Link": "Confirmar vínculo com o Immich", @@ -1020,13 +1030,16 @@ "Edit at History Step": "Editar na etapa do histórico", "Edit date": "Data de edição", "Edit in (one item)": "Editar em (um item)", + "Edit in Default Editor": "Editar no editor padrão", "Edit in External Editor (⇧⌘E): a 16-bit TIFF copy, stacked, refreshed when you come back.": "Editar em editor externo (⇧⌘E): uma cópia TIFF de 16 bits, empilhada, atualizada quando você volta.", "Edit in HDR: highlights above SDR white, for HDR exports and displays": "Editar em HDR: altas luzes acima do branco SDR, para exportações e telas HDR", "Edit in Other Editor": "Editar em outro editor", "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Editar em outro editor (⌥⌘E) abre a cópia neste aplicativo (um nome de aplicativo no macOS, um caminho de programa nos outros sistemas).", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Editar em outro editor (⌥⌘E) abre a cópia neste aplicativo (um nome de aplicativo no macOS, um caminho de programa nos demais). Com o local vazio, o aplicativo padrão do sistema a abre.", "Edit in PhotoCraft": "Editar no PhotoCraft", "Edit this saved location": "Editar este local salvo", "Edited Version Saved Again": "Versão editada salva novamente", + "Editors": "Editores", "Edit…": "Editar…", "Elsewhere": "Em outros lugares", "Email": "E-mail", @@ -1321,6 +1334,7 @@ "Forget Remembered Object": "Esquecer objeto lembrado", "Forget This Person": "Esquecer esta pessoa", "Forget a Paired Surface": "Esquecer uma superfície pareada", + "Format Options": "Opções de formato", "Found automatically": "Encontrado automaticamente", "Four with Caption": "Quatro com legenda", "Frame": "Moldura", @@ -1445,6 +1459,7 @@ "Hard Drive": "Disco rígido", "Hardcover": "Capa dura", "Has a GPS position (click to show it on the map)": "Tem uma posição GPS (clique para vê-la no mapa)", + "Has a companion JPEG (click to open the Info panel)": "Tem um JPEG companheiro (clique para abrir o painel de informações)", "Headline metadata": "Manchete nos metadados", "Headroom": "Margem", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Corrige as pequenas manchas escuras ou vermelhas na pele dos rostos; olhos, sobrancelhas, narinas e lábios ficam intactos", @@ -1472,7 +1487,7 @@ "Hide {app}": "Ocultar {app}", "High Range": "Faixa alta", "High quality adjustment previews": "Prévias de ajustes em alta qualidade", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Uma confiança maior encontra menos rostos falsos, mas pode deixar passar rostos reais. Vale para detecções futuras; escaneie novamente para atualizar as existentes.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Uma confiança maior encontra menos rostos falsos, mas pode perder rostos reais. Vale para detecções futuras; refaça a análise para atualizar as existentes.", "Highlight Hue": "Matiz das altas luzes", "Highlight Luminance": "Luminância das altas luzes", "Highlight Reconstruction": "Reconstrução de realces", @@ -1572,6 +1587,7 @@ "Import Mask Effects": "Importar efeitos de máscara", "Import Metadata Presets": "Importar predefinições de metadados", "Import New Shots": "Importar novas capturas", + "Import Order": "Ordem de importação", "Import People": "Importar pessoas", "Import People from Immich": "Importar pessoas do Immich", "Import Photos and Video…": "Importar fotos e vídeo…", @@ -1667,6 +1683,7 @@ "Install the Surface Plugin": "Instalar o plug-in Surface", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Instale seu próprio modelo ONNX com o denoise-model.json ao lado. Esta versão não oferece download de modelos.", "Installed": "Instalado", + "Installed editors…": "Editores instalados…", "Installed in": "Instalado em", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Instalar não permite nada disso: o plug-in pede a você na primeira vez que precisar de cada item.", "Install…": "Instalar…", @@ -1753,6 +1770,7 @@ "Large Landscape (13 × 11 in)": "Paisagem grande (13 × 11 in)", "Large and Small": "Grande e pequena", "Large image size": "Tamanho da imagem grande", + "Largest Face": "Maior rosto", "Last Photo": "Última foto", "Last backup:": "Último backup:", "Last checked 1 hour ago": "Última verificação: há 1 hora", @@ -1765,6 +1783,7 @@ "Last synced on {}": "Última sincronização em {}", "Last synced {} h ago": "Última sincronização há {} h", "Last synced {} min ago": "Última sincronização há {} min", + "Launch Options": "Opções de inicialização", "Layout": "Layout", "Layout Image Matte": "Fosco da imagem de layout", "Layout Image Off": "Imagem de layout desativada", @@ -2082,6 +2101,7 @@ "New Template Folder": "Nova pasta de modelos", "New Web Template Folder": "Nova pasta de modelos da web", "New collections": "Novas coleções", + "New editor": "Novo editor", "New group (press Return)": "Novo grupo (pressione Return)", "New group name": "Nome do novo grupo", "New group:": "Novo grupo:", @@ -2093,6 +2113,7 @@ "New red eye correction (Return adds it here)": "Nova correção de olhos vermelhos (Return a adiciona aqui)", "New shots:": "Novas fotos:", "New spot (Return adds it here)": "Novo ponto (Return o adiciona aqui)", + "Newest First": "Mais recentes primeiro", "Next Filmstrip Background": "Próximo fundo da tira de filme", "Next Frame": "Próximo quadro", "Next History Step": "Próxima etapa do histórico", @@ -2255,6 +2276,7 @@ "Offset Hue": "Matiz do offset", "Offset Luminance": "Luminância do offset", "Offset Saturation": "Saturação do offset", + "Oldest First": "Mais antigos primeiro", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Em um negativo ou slide digitalizado: encontra e corrige grãos de poeira, fios e riscos no filme. A passagem infravermelha do scanner (um arquivo RGBI do VueScan ou SilverFast) diz onde estão; caso contrário, as áreas lisas da imagem são examinadas", "On photo": "Na foto", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "No dispositivo dono de uma coleção, escolha o que os outros podem ter; nos outros, escolha o que este dispositivo recebe.", @@ -2329,6 +2351,7 @@ "Optimize catalog after backing up": "Otimizar o catálogo após o backup", "Optional: where downloads go": "Opcional: para onde vão os downloads", "Orientation Detection Status": "Status da detecção de orientação", + "Original (+XMP)": "Original (+XMP)", "Original Photo": "Foto original", "Other": "Outras", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Assim outros apps veem suas avaliações, palavras-chave e edições. Um arquivo pequeno é gravado ao lado de cada foto.", @@ -2411,6 +2434,7 @@ "Permissions": "Permissões", "Permissions:": "Permissões:", "Persistent": "Persistente", + "Person Sort": "Classificação de pessoa", "Personalize {app} with your own branding elements.": "Personalize o {app} com seus próprios elementos de marca.", "Personalized": "Personalizada", "Phone": "Telefone", @@ -2427,6 +2451,7 @@ "Photo with Side Text": "Foto com texto lateral", "Photo with Title": "Foto com título", "Photo zoom": "Zoom das fotos", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Foto → Editar em lista aqui cada editor. Os dois primeiros são integrados; adicione quantos quiser e clique em uma linha para mudar o que ela entrega.", "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.": "Foto → Editar em → Editar no PhotoCraft (⇧⌘E, ou clique com o botão direito em uma foto) renderiza uma cópia com suas edições, empilha-a com o original e a abre no PhotoCraft. Salve lá e a cópia é atualizada aqui. Como PSD, o PhotoCraft salva direto nela. Deixe o local vazio, a menos que use uma cópia portátil.", "PhotoCraft": "PhotoCraft", "Photograph Information": "Informações da fotografia", @@ -3395,6 +3420,7 @@ "Text Page": "Página de texto", "Text Style Preset": "Predefinição de estilo de texto", "Text size": "Tamanho do texto", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "O JPEG ao lado do arquivo raw, mantido junto a ele: não é uma foto própria.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "O Gerenciador de perfis lista todos os visuais, perfis LUT e perfis de câmera: oculte-os dos menus, renomeie e agrupe-os, importe novos e exclua os seus.", "The account has no PIN or password, so there is nothing to unlock.": "A conta não tem PIN nem senha, então não há nada para desbloquear.", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "A foto ativa foi tirada onde está geomarcada (ou no centro do mapa): ajuste-a ao trajeto", @@ -3616,6 +3642,7 @@ "Tracklog": "Registro de trajeto", "Transform": "Transformar", "Trash renders taken out of a collection": "Enviar para a lixeira renderizações removidas de uma coleção", + "Treat JPEGs next to raw files as companions": "Tratar JPEGs ao lado de arquivos raw como companheiros", "Trim": "Corte", "Trim End": "Fim do corte", "Trim Start": "Início do corte", @@ -3709,6 +3736,7 @@ "Update to Current Process": "Atualizar para o processo atual", "Update to Current Process Version": "Atualizar para a versão do processo atual", "Update with Current Settings…": "Atualizar com as configurações atuais…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "As atualizações estão desativadas ({env}_DISABLE_UPDATES está definida); seu gerenciador de pacotes cuida delas.", "Updates the installed version": "Atualiza a versão instalada", "Updates…": "Atualizações…", "Updating the DNG previews stopped unexpectedly": "A atualização das pré-visualizações DNG parou inesperadamente", @@ -3840,6 +3868,7 @@ "Wrong passphrase.": "Frase secreta incorreta.", "Wrote {} XMP sidecars": "{} arquivos XMP auxiliares gravados", "X": "X", + "XMP Sidecar": "Sidecar XMP", "XMP Sidecars": "Arquivos XMP auxiliares", "Y": "Y", "Yellow Label": "Rótulo amarelo", @@ -3873,10 +3902,13 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` recebendo o próprio arquivo de uma biblioteca (`catalog.snap`) abre a pasta dela em vez de falhar com", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (e as ferramentas MCP que recebem pastas) agora encontra HEIC, HEIF e Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` também registra avisos no stderr (issue #168); `{env}_LOG` ou `RUST_LOG` escolhe outro nível.", + "a copy of the original": "uma cópia do original", + "a copy of the original, with an XMP sidecar": "uma cópia do original, com um sidecar XMP", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "uma unidade cheia) não conta mais como criada e Criar prévias inteligentes a substitui.", "a photo matches any group": "uma foto corresponde a qualquer grupo", "a photo matches every group": "uma foto corresponde a todos os grupos", "a word per topic; every word must match": "uma palavra por tema; todas devem corresponder", + "adds an editor; click its row to name it and choose its program and file": "adiciona uma linha; clique nela para nomear o editor e escolher o programa e o arquivo", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "depois (issue #101): a gravação parcial é cortada antes que o {app} tente de novo, então a próxima inicialização reaplica cada", "again. Change the period (or turn it off) in Settings → Performance.": "de novo. Altere o período (ou desative) em Configurações → Desempenho.", "against the library's originals no longer scans the whole library when nothing is at that path.": "com os originais da biblioteca não varre mais a biblioteca inteira quando não há nada nesse caminho.", @@ -4034,6 +4066,7 @@ "renders and screenshots are still written to a temp file and renamed into place, but no longer forced to disk": "renderizações e capturas de tela ainda são gravadas em um arquivo temporário e renomeadas no lugar, mas não são mais forçadas para o disco", "role": "papel", "save goes through.": "salvamento seja concluído.", + "scene-linear Rec. 2020": "linear de cena em Rec. 2020", "selected photos": "fotos selecionadas", "shots": "fotos", "siblings) no longer open bright green (issue #148): their as-shot white balance and black level are read from the": "irmãs) não abrem mais em verde brilhante (issue #148): o balanço de branco da captura e o nível de preto são lidos do", @@ -4053,16 +4086,21 @@ "the Local folder tree and Auto Import read the disk on worker threads too. The import progress window has Cancel.": "a árvore de pastas Local e a Importação automática também leem o disco em threads de trabalho. A janela de progresso da importação tem Cancelar.", "the Photo menu and the photo context menu) picks up the full-size preview and fills in the camera metadata they": "o menu Foto e o menu de contexto da foto) pega a prévia em tamanho real e preenche os metadados da câmera que", "the active photo isn't a video": "a foto ativa não é um vídeo", + "the arguments before the file; `{file}` places the file's path where it stands": "os argumentos antes do arquivo; `{file}` coloca o caminho do arquivo onde estiver", "the camera roll could not be read": "o rolo da câmera não pôde ser lido", "the camera; mapped-out sensor defects are filled in. `.rwl` and `.raw` files are imported too. Photos already": "a câmera; defeitos de sensor mapeados são preenchidos. Arquivos `.rwl` e `.raw` também são importados. Fotos já", + "the file's own": "o próprio do arquivo", "the folder shown": "a pasta mostrada", "the folder shown (no folder is: pick one first)": "a pasta mostrada (nenhuma: escolha uma primeiro)", "the frames could not be matched to each other": "não foi possível associar os quadros entre si", "the graphics card": "a placa de vídeo", "the graphics card is not used": "a placa de vídeo não é usada", "the measured positions were less reliable than the camera's own pattern": "as posições medidas eram menos confiáveis que o padrão próprio da câmera", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "o aplicativo padrão do sistema para o tipo de arquivo: Editar no editor padrão renderiza a cópia e a entrega", + "the original, with an XMP sidecar": "o original, com um sidecar XMP", "the photos in view": "as fotos na vista", "the plug-in worker stopped unexpectedly": "o processo do plug-in parou inesperadamente", + "the raw data's own": "o próprio dos dados RAW", "the same name and \"Overwrite\" (or Export with Previous repeating it), an exact output path from the control": "o mesmo nome e “Sobrescrever” (ou Exportar com anterior repetindo-o), um caminho de saída exato do canal de", "the selected photos": "as fotos selecionadas", "the whole catalog": "o catálogo inteiro", @@ -4092,6 +4130,7 @@ "whether originals are there is checked on a worker thread (grid thumbnails, the Info panel, the photo menu, Missing": "se os originais estão presentes é verificado em uma thread de trabalho (miniaturas da grade, o painel Informações, o menu da foto, Fotos", "width": "largura", "with a counterpart here come along, the rest is listed.": "com um equivalente aqui vêm junto, o resto é listado.", + "write the edits beside the file": "grava as edições junto ao arquivo", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "gravada por um {app} mais novo é recusada com “esta biblioteca foi gravada por uma versão mais nova do {app}” e deixada", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "gravada por um {app} mais novo), o {app} avisa e explica por quê, e oferece Tentar de novo, Escolher outra biblioteca…, Continuar", "{app}": "{app}", diff --git a/crates/ui-egui/locales/fork/ru-formats.json b/crates/ui-egui/locales/fork/ru-formats.json index df83f9bb80..1f9e237707 100644 --- a/crates/ui-egui/locales/fork/ru-formats.json +++ b/crates/ui-egui/locales/fork/ru-formats.json @@ -123,6 +123,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "В его манифесте есть значения, которые эта версия не может использовать и пропускает: {values}", "JPEG quality {q} to fit the size limit": "Качество JPEG {q}, чтобы уложиться в ограничение размера", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Качество JPEG {q}, чтобы уложиться в ограничение размера (меньший размер или большее ограничение сохраняют больше качества)", + "Kept with {raw} as its companion: not a photo of its own.": "Хранится вместе с {raw} как спутник: не отдельная фотография.", "Kept. Groups left: {left}": "Оставлено. Осталось групп: {left}", "Last checked {n} hours ago": "Последняя проверка: {n} ч назад", "Last checked {n} minutes ago": "Последняя проверка: {n} мин. назад", @@ -340,6 +341,7 @@ "{} keys": "Клавиши модуля {}", "{} of {} from {host}": "{} из {} с {host}", "{} · {}. Kept in the catalog's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Хранятся в папке «denoise» каталога; при достижении ограничения первыми удаляются самые старые изображения, которые не использует ни одно фото.", + "· {companions} kept with their RAWs": "· {companions} хранятся со своими raw", "“{name}” added to Camera Profiles": "«{name}» добавлен в профили камеры", "“{name}” has its old settings again": "У «{name}» снова прежние настройки", "“{name}” is new. What may the other devices syncing this catalog have of it?": "«{name}»: новая. Что из неё могут получать другие устройства, синхронизирующие этот каталог?", diff --git a/crates/ui-egui/locales/fork/ru.json b/crates/ui-egui/locales/fork/ru.json index 1d0c6b1f40..2524491017 100644 --- a/crates/ui-egui/locales/fork/ru.json +++ b/crates/ui-egui/locales/fork/ru.json @@ -55,6 +55,7 @@ "8 bits/component": "8 бит/канал", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": принято {accepted}, на проверку {pending}, отклонено {rejected}", "= exactly": "= ровно", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "JPEG с именем raw-файла рядом с ним является его спутником: одна фотография, одно сканирование лиц, один набор метаданных. Чтобы импортировать JPEG как отдельные фотографии, снимите флажок параметра спутников.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Пора создать резервную копию каталога. Создать её сейчас, до выхода из {app}?", "A blank template keeps the original names.": "Пустой шаблон сохраняет исходные имена.", "A card, a drive or a folder": "Карта, диск или папка", @@ -118,6 +119,7 @@ "Add Blank": "Добавить пустую страницу", "Add Cell": "Добавить ячейку", "Add Column": "Добавить столбец", + "Add Editor": "Добавить редактор", "Add Face Model…": "Добавить модель лиц…", "Add Face Region": "Добавить область лица", "Add Filter…": "Добавить фильтр…", @@ -266,6 +268,7 @@ "Assign to Someone Else…": "Назначить другому человеку…", "Assign to…": "Назначить…", "At Import": "При импорте", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "При импорте JPEG с именем raw-файла рядом с ним не отдельная фотография, а его спутник: одна миниатюра, одно сканирование лиц, один набор метаданных. Он следует за raw-файлом при копировании, перемещении и переименовании.", "At launch": "При запуске", "At most one request per second.": "Не более одного запроса в секунду.", "Attribution (shown on the map)": "Атрибуция (показывается на карте)", @@ -330,6 +333,7 @@ "Binary assets added": "Добавленные двоичные файлы", "Binary assets removed": "Удалённые двоичные файлы", "Bit Depth": "Глубина цвета", + "Bit Level": "Разрядность", "Black": "Чёрный", "Black Point Compensation": "Компенсация точки чёрного", "Blank": "Пустая", @@ -379,7 +383,9 @@ "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "Браузерная версия (экспериментальная), сохранность библиотеки (issue #107): Файл → Резервная копия библиотеки… загружает каталог", "Brush (Return puts it down and paints, the arrows paint while it is down)": "Кисть (Enter опускает её и рисует, стрелки рисуют, пока она опущена)", "Brush Refinement": "Уточнение кистью", + "Build Face Thumbnails": "Создать миниатюры лиц", "Build at import": "Создавать при импорте", + "Building face thumbnails": "Создание миниатюр лиц", "Building the profile…": "Создание профиля…", "Built in the background once the photos are in, from the one on screen outward.": "Создаются в фоне после импорта, начиная с фото на экране.", "Built-in": "Встроенные", @@ -547,6 +553,7 @@ "Choose folder later": "Выбрать папку позже", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Выберите внешний вид приложения. Каждое изменение видно сразу; больше в Настройки → Интерфейс.", "Choose in Sync…": "Выбрать в синхронизации…", + "Choose the Editor's Program": "Выбрать программу редактора", "Choose the catalog to open.": "Выберите каталог для открытия.", "Choose where to import from": "Выберите, откуда импортировать", "Circle": "Круг", @@ -645,6 +652,7 @@ "Color to Replace": "Заменяемый цвет", "Colors": "Цвета", "Colour Profile": "Цветовой профиль", + "Colour Space": "Цветовое пространство", "Colour space of the TIFF": "Цветовое пространство TIFF", "Colour-label filter with several labels at once; expandable folder tree in Local.": "Фильтр по цветовым меткам с несколькими метками сразу; раскрываемое дерево папок в Локальных.", "Colour-range masks: click the photo to sample. Luminance ranges: range bar, smoothness, luminance map.": "Маски цветового диапазона: щёлкните фото, чтобы взять образец. Диапазоны яркости: полоса диапазона, сглаживание, карта яркости.", @@ -660,6 +668,8 @@ "Compact Cells": "Компактные ячейки", "Compact Layout": "Компактная раскладка", "Compact – Dense": "Компактный – плотный", + "Companion": "Спутник", + "Companion JPEG:": "Сопутствующий JPEG:", "Company": "Компания", "Compare Group in Survey": "Сравнить группу в Обзоре", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", @@ -668,7 +678,7 @@ "Compression (quality scan)": "Сжатие (сканирование качества)", "Compression artifacts": "Артефакты сжатия", "Computing AI masks": "Вычисление ИИ-масок", - "Confidence required": "Требуемая уверенность", + "Confidence required": "Требуемая достоверность", "Confirm": "Подтвердить", "Confirm Faces from Immich": "Подтвердить лица из Immich", "Confirm Immich Link": "Подтвердить связь с Immich", @@ -1019,13 +1029,16 @@ "Edit at History Step": "Править с шага истории", "Edit date": "Дата правки", "Edit in (one item)": "Редактировать в (один пункт)", + "Edit in Default Editor": "Открыть в редакторе по умолчанию", "Edit in External Editor (⇧⌘E): a 16-bit TIFF copy, stacked, refreshed when you come back.": "Редактировать во внешнем редакторе (⇧⌘E): 16-битная копия TIFF, в стопке, обновляется при возвращении.", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Открыть в другом редакторе (⌥⌘E) открывает копию в этом приложении (имя приложения на macOS, путь к программе в остальных случаях). Если место пусто, копию открывает приложение системы по умолчанию.", "Edit in PhotoCraft": "Редактировать в PhotoCraft", "Edit settings copied": "Настройки обработки скопированы", "Edit this saved location": "Изменить это сохранённое место", "Edited Version Saved Again": "Отредактированная версия сохранена снова", "Edited or not": "Обработано или нет", "Editing": "Редактирование", + "Editors": "Редакторы", "Edit…": "Изменить…", "Elsewhere": "В других местах", "Email": "Эл. почта", @@ -1318,6 +1331,7 @@ "Forget Remembered Object": "Забыть запомненный объект", "Forget This Person": "Забыть этого человека", "Forget a Paired Surface": "Забыть связанную поверхность", + "Format Options": "Параметры формата", "Four with Caption": "Четыре с подписью", "Frame": "Рамка", "Frame Rate": "Частота кадров", @@ -1450,6 +1464,7 @@ "Hard Drive": "Жёсткий диск", "Hardcover": "Твёрдая обложка", "Has a GPS position (click to show it on the map)": "Есть GPS-координаты (щёлкните, чтобы показать на карте)", + "Has a companion JPEG (click to open the Info panel)": "Есть сопутствующий JPEG (нажмите, чтобы открыть панель сведений)", "Headline metadata": "Метаданные основного заголовка", "Headroom": "Запас", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Убирает мелкие тёмные и красные точки на коже лиц; глаза, брови, ноздри и губы не трогаются", @@ -1476,7 +1491,7 @@ "Hide {app}": "Скрыть {app}", "High Range": "Верхний диапазон", "High quality adjustment previews": "Высококачественный предпросмотр при настройке", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Более высокая уверенность даёт меньше ложных лиц, но может пропустить настоящие. Применяется к будущим обнаружениям; чтобы обновить существующие, выполните повторное сканирование.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Более высокая достоверность находит меньше ложных лиц, но может пропустить настоящие. Действует для будущих обнаружений; чтобы обновить существующие, просканируйте снова.", "Highlight Hue": "Тон светов", "Highlight Luminance": "Яркость светов", "Highlight Reconstruction": "Восстановление светов", @@ -1577,6 +1592,7 @@ "Import Lightroom or Capture One Catalog…": "Импортировать каталог Lightroom или Capture One…", "Import Metadata Presets": "Импортировать пресеты метаданных", "Import New Shots": "Импортировать новые снимки", + "Import Order": "Порядок импорта", "Import People": "Импортировать людей", "Import People from Immich": "Импортировать людей из Immich", "Import Photos and Video…": "Импортировать фото и видео…", @@ -1668,6 +1684,7 @@ "Install from Plug-in Marketplace": "Установить из маркетплейса плагинов", "Install the Surface Plugin": "Установить плагин Surface", "Installed": "Установлено", + "Installed editors…": "Установленные редакторы…", "Installed in": "Установлены в", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Установка ничего из этого не разрешает: плагин спросит вас, когда разрешение понадобится ему впервые.", "Install…": "Установить…", @@ -1753,6 +1770,7 @@ "Large Landscape (13 × 11 in)": "Большая альбомная (13 × 11 in)", "Large and Small": "Крупная и мелкая", "Large image size": "Размер больших изображений", + "Largest Face": "Самое большое лицо", "Last GPU fallback": "Последний откат с GPU", "Last Photo": "Последнее фото", "Last backup:": "Последняя резервная копия:", @@ -1768,6 +1786,7 @@ "Last synced on {}": "Последняя синхронизация: {}", "Last synced {} h ago": "Последняя синхронизация: {} ч назад", "Last synced {} min ago": "Последняя синхронизация: {} мин назад", + "Launch Options": "Параметры запуска", "Layout": "Макет", "Layout Image Off": "Изображение макета выкл.", "Layout Image On": "Изображение макета вкл.", @@ -2091,6 +2110,7 @@ "New Template Folder": "Новая папка шаблонов", "New Web Template Folder": "Новая папка веб-шаблонов", "New collections": "Новые коллекции", + "New editor": "Новый редактор", "New group name": "Название новой группы", "New group:": "Новая группа:", "New location name": "Имя нового места", @@ -2101,6 +2121,7 @@ "New red eye correction (Return adds it here)": "Новая коррекция красных глаз (Return добавляет её здесь)", "New shots:": "Новые снимки:", "New time": "Новое время", + "Newest First": "Сначала новые", "Next Filmstrip Background": "Следующий фон ленты кадров", "Next Frame": "Следующий кадр", "Next Light Mode": "Следующий режим освещения", @@ -2262,6 +2283,7 @@ "Offset Hue": "Тон offset", "Offset Luminance": "Яркость offset", "Offset Saturation": "Насыщенность offset", + "Oldest First": "Сначала старые", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "На отсканированном негативе или слайде: найти и исправить пылинки, волоски и царапины на плёнке. Инфракрасный проход сканера (файл RGBI из VueScan или SilverFast) говорит, где они; иначе просматриваются гладкие участки изображения", "On photo": "На фото", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "На устройстве-владельце коллекции выберите, что могут получить другие; на остальных выберите, что берёт это устройство.", @@ -2330,6 +2352,7 @@ "Optimize catalog after backing up": "Оптимизировать каталог после копирования", "Optional: where downloads go": "Необязательно: куда сохранять загрузки", "Orientation Detection Status": "Состояние определения ориентации", + "Original (+XMP)": "Оригинал (+XMP)", "Original Photo": "Исходное фото", "Original extension without the dot": "Исходное расширение без точки", "Original file name without its extension": "Исходное имя файла без расширения", @@ -2416,6 +2439,7 @@ "Permissions": "Разрешения", "Permissions:": "Разрешения:", "Persistent": "Постоянное", + "Person Sort": "Сортировка человека", "Personalize {app} with your own branding elements.": "Оформите {app} собственными элементами бренда.", "Personalized": "Персональная", "Phone": "Телефон", @@ -2430,6 +2454,7 @@ "Photo with Side Text": "Фото с боковым текстом", "Photo with Title": "Фото с заголовком", "Photo zoom": "Масштаб фото", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Фото › Редактировать в перечисляет здесь каждый редактор. Первые два встроены; добавьте сколько нужно и щёлкните строку, чтобы изменить, что она передаёт.", "PhotoCraft": "PhotoCraft", "Photograph Information": "Сведения о съёмке", "Photos affected": "Затронутые фото", @@ -3391,6 +3416,7 @@ "Text Style Preset": "Пресет стиля текста", "Text size": "Размер текста", "That includes the photos in the folders inside it.": "Включая фото во вложенных папках.", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "JPEG рядом с raw-файлом, хранится вместе с ним: не отдельная фотография.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Менеджер профилей перечисляет все стили, профили LUT и профили камеры: скрывайте их из меню, переименовывайте и группируйте, импортируйте новые и удаляйте свои.", "The account has no PIN or password, so there is nothing to unlock.": "У учётной записи нет ни PIN-кода, ни пароля, поэтому разблокировать нечего.", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "Активное фото снято там, где оно геотегировано (или в центре карты): сопоставьте его с треком", @@ -3603,6 +3629,7 @@ "Tracklog": "Трек", "Transform": "Трансформация", "Trash renders taken out of a collection": "Удалять в корзину обработанные копии, убранные из коллекции", + "Treat JPEGs next to raw files as companions": "Считать JPEG рядом с raw-файлами сопровождающими", "Trim": "Обрезка", "Trim End": "Конец обрезки", "Trim Start": "Начало обрезки", @@ -3688,6 +3715,7 @@ "Update to Current Process Version": "Обновить до текущей версии обработки", "Update with Current Settings…": "Обновить текущими настройками…", "Updated the edits saved in the external editor": "Обновлены правки, сохранённые во внешнем редакторе", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Обновления отключены (задана переменная {env}_DISABLE_UPDATES); обновлениями занимается менеджер пакетов.", "Updates the installed version": "Обновляет установленную версию", "Updates…": "Обновления…", "Updating the DNG previews stopped unexpectedly": "Обновление превью DNG неожиданно остановилось", @@ -3815,6 +3843,7 @@ "Wrong passphrase.": "Неверная парольная фраза.", "Wrote {} XMP sidecars": "Записано XMP-файлов: {}", "X": "X", + "XMP Sidecar": "XMP-сайдкар", "XMP Sidecars": "XMP-файлы", "Y": "Y", "Yellow Label": "Жёлтая метка", @@ -3849,12 +3878,15 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library`, получив собственный файл библиотеки (`catalog.snap`), открывает её папку, а не завершается с", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (и инструменты MCP, принимающие папки) теперь подхватывает HEIC, HEIF и Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` тоже выводит предупреждения в stderr (issue #168); `{env}_LOG` или `RUST_LOG` задаёт другой уровень.", + "a copy of the original": "копия оригинала", + "a copy of the original, with an XMP sidecar": "копия оригинала с XMP-сайдкаром", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "заполнения диска) больше не считается созданным, и Создать смарт-превью заменяет его.", "a literal %": "символ %", "a photo matches any group": "фото подходит под любую группу", "a photo matches every group": "фото подходит под каждую группу", "a removed photo": "удалённого фото", "a word per topic; every word must match": "одно слово на тему; должны совпасть все слова", + "adds an editor; click its row to name it and choose its program and file": "добавляет строку; щёлкните её, чтобы назвать редактор и выбрать программу и файл", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "после этого (issue #101): частичная запись обрезается до повторной попытки {app}, так что следующий запуск воспроизводит каждое", "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.": "с оригиналами библиотеки больше не сканирует всю библиотеку, когда по этому пути ничего нет.", @@ -4030,6 +4062,7 @@ "renders and screenshots are still written to a temp file and renamed into place, but no longer forced to disk": "рендеры и снимки экрана по-прежнему записываются во временный файл и переименовываются на место, но больше не сбрасываются на диск принудительно", "role": "роль", "save goes through.": "сохранение проходит.", + "scene-linear Rec. 2020": "линейный Rec. 2020", "second": "секунда", "selected photos": "выбранные фото", "shots": "снимков", @@ -4049,14 +4082,19 @@ "the Local folder tree and Auto Import read the disk on worker threads too. The import progress window has Cancel.": "дерево папок Локальных и Автоимпорт тоже читают диск в рабочих потоках. В окне хода импорта есть Отмена.", "the Photo menu and the photo context menu) picks up the full-size preview and fills in the camera metadata they": "меню Фото и контекстное меню фото) подхватывает превью в полном размере и заполняет метаданные камеры, которые", "the active photo isn't a video": "активное фото не является видео", + "the arguments before the file; `{file}` places the file's path where it stands": "аргументы перед файлом; `{file}` ставит путь к файлу на это место", "the camera roll could not be read": "не удалось прочитать фотоплёнку", "the camera; mapped-out sensor defects are filled in. `.rwl` and `.raw` files are imported too. Photos already": "камере; отмеченные дефекты сенсора заполняются. Файлы `.rwl` и `.raw` тоже импортируются. Фото, уже", + "the file's own": "как у файла", "the folder shown": "показанная папка", "the folder shown (no folder is: pick one first)": "показанная папка (папка не открыта: сначала откройте её)", "the frames could not be matched to each other": "не удалось сопоставить кадры друг с другом", "the measured positions were less reliable than the camera's own pattern": "измеренные положения оказались менее надёжными, чем собственный узор камеры", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "приложение системы по умолчанию для этого типа файлов: «Открыть в редакторе по умолчанию» готовит копию и передаёт её", + "the original, with an XMP sidecar": "оригинал с XMP-сайдкаром", "the photos in view": "фото в представлении", "the plug-in worker stopped unexpectedly": "рабочий поток плагина неожиданно остановился", + "the raw data's own": "как у исходных данных", "the same name and \"Overwrite\" (or Export with Previous repeating it), an exact output path from the control": "тем же именем и «Перезаписать» (или Экспорт с прежними настройками, повторяющий его), точный путь вывода из управляющего", "the selected photos": "выбранных фото", "the whole catalog": "весь каталог", @@ -4089,6 +4127,7 @@ "whether originals are there is checked on a worker thread (grid thumbnails, the Info panel, the photo menu, Missing": "наличие оригиналов проверяется в рабочем потоке (миниатюры сетки, панель Сведения, меню фото, Отсутствующие", "width": "ширина", "with a counterpart here come along, the rest is listed.": "с соответствием здесь переносятся, остальное перечисляется.", + "write the edits beside the file": "записывает правки рядом с файлом", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "записанная более новой {app}, отклоняется с сообщением «эта библиотека записана более новой версией {app}» и остаётся", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "записана более новой {app}), {app} сообщает об этом и почему и предлагает Повторить, Выбрать другую библиотеку…, Продолжить", "year, 2 digits": "год, 2 цифры", diff --git a/crates/ui-egui/locales/fork/sv-formats.json b/crates/ui-egui/locales/fork/sv-formats.json index 6ee30e45e8..82bce2f07d 100644 --- a/crates/ui-egui/locales/fork/sv-formats.json +++ b/crates/ui-egui/locales/fork/sv-formats.json @@ -131,6 +131,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Dess manifest har värden som den här versionen inte kan använda och utelämnar: {values}", "JPEG quality {q} to fit the size limit": "JPEG-kvalitet {q} för att rymmas inom storleksgränsen", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "JPEG-kvalitet {q} för att rymmas inom storleksgränsen (en mindre storlek eller en högre gräns behåller mer kvalitet)", + "Kept with {raw} as its companion: not a photo of its own.": "Följer {raw} som tillhörande bild: inte ett eget foto.", "Kept. Groups left: {left}": "Behållet. Grupper kvar: {left}", "Key from the environment variable {}": "Nyckel från miljövariabeln {}", "Key saved (ends in {})": "Nyckel sparad (slutar på {})", @@ -370,6 +371,7 @@ "{} photos · {} aligned · {} left out": "{} foton · {} justerade · {} utelämnade", "{} sample{}": "Prov: {}{:.0}", "{} spot(s) from Remove Dust (outlined in amber)": "{} fläck(ar) från Ta bort damm (markerade i bärnsten)", + "· {companions} kept with their RAWs": "· {companions} följer sin raw-fil", "“{name}” added to Camera Profiles": "”{name}” har lagts till i kameraprofiler", "“{name}” has its old settings again": "”{name}” har sina gamla inställningar igen", "“{name}” is new. What may the other devices syncing this catalog have of it?": "”{name}” är ny. Vad får de andra enheterna som synkar den här katalogen ha av den?", diff --git a/crates/ui-egui/locales/fork/sv.json b/crates/ui-egui/locales/fork/sv.json index fba1a4269b..df7786651b 100644 --- a/crates/ui-egui/locales/fork/sv.json +++ b/crates/ui-egui/locales/fork/sv.json @@ -44,6 +44,7 @@ "6 Blades": "6 lameller", "8 bits/component": "8 bitar/komponent", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} godkända, {pending} att granska, {rejected} avvisade", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "En JPEG med en raw-fils namn bredvid sig är dess tillhörande bild: ett foto, en ansiktssökning, en uppsättning metadata. Avmarkera alternativet för tillhörande bilder för att importera JPEG-bilder som egna foton.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Det är dags att säkerhetskopiera katalogen. Vill du säkerhetskopiera den nu, innan {app} avslutas?", "A camera profile is being built": "En kameraprofil skapas", "A camera profile is for one camera: use a photo from the same camera body.": "En kameraprofil gäller en kamera: använd ett foto från samma kamerahus.", @@ -113,6 +114,7 @@ "Add Blank": "Lägg till tom", "Add Cell": "Lägg till cell", "Add Column": "Lägg till kolumn", + "Add Editor": "Lägg till redigerare", "Add Face Region": "Lägg till ansiktsregion", "Add Filter…": "Lägg till filter…", "Add Folder": "Lägg till mapp", @@ -276,6 +278,7 @@ "Assign to Someone Else…": "Tilldela till någon annan…", "Assign to…": "Tilldela till…", "At Import": "Vid import", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Vid import är en JPEG med en raw-fils namn bredvid sig inte ett eget foto utan rawfilens tillhörande bild: en miniatyr, en ansiktssökning, en uppsättning metadata. Den följer med rawfilen när den kopieras, flyttas eller byter namn.", "At launch": "Vid start", "At most one request per second.": "Högst en begäran per sekund.", "Attribution (shown on the map)": "Tillskrivning (visas på kartan)", @@ -334,6 +337,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Däremellan behåller bilden sin flagga (utan flagga förblir utan).", "Big steps": "Stora steg", "Bit Depth": "Bitdjup", + "Bit Level": "Bitdjup", "Black": "Svart", "Black Point Compensation": "Svartpunktskompensation", "Blank": "Tom", @@ -389,7 +393,9 @@ "Brush Flow": "Penselns flöde", "Brush Refinement": "Penselförfining", "Brush Size": "Penselstorlek", + "Build Face Thumbnails": "Skapa ansiktsminiatyrer", "Build at import": "Bygg vid import", + "Building face thumbnails": "Skapar ansiktsminiatyrer", "Building the profile…": "Skapar profilen…", "Built in the background once the photos are in, from the one on screen outward.": "Byggs i bakgrunden när fotona har kommit in, från det som visas på skärmen och utåt.", "Built-in (lcc-raw)": "Inbyggd (lcc-raw)", @@ -546,6 +552,7 @@ "Choose folder later": "Välj mapp senare", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Välj hur appen ser ut. Varje ändring syns direkt; mer finns under Inställningar → Gränssnitt.", "Choose in Sync…": "Välj i Synkronisering…", + "Choose the Editor's Program": "Välj redigerarens program", "Choose the catalog to open.": "Välj katalogen som ska öppnas.", "Choose where to import from": "Välj var du vill importera från", "Chroma": "Kroma", @@ -645,6 +652,7 @@ "Color to Replace": "Färg att ersätta", "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "Färgerna matchar färgkartan; var och en behåller den ljushet som kameran registrerade. För människor och vardagsfoton.", "Colour Profile": "Färgprofil", + "Colour Space": "Färgrymd", "Colour knobs P1–P8": "Färgrattar P1–P8", "Colour space of the TIFF": "TIFF-filens färgrymd", "Colours are #RRGGBB.": "Färger anges som #RRGGBB.", @@ -662,6 +670,8 @@ "Compact Cells": "Kompakta celler", "Compact Layout": "Kompakt layout", "Compact – Dense": "Kompakt – tät", + "Companion": "Tillhörande", + "Companion JPEG:": "Tillhörande JPEG:", "Compare Before and After": "Jämför före och efter", "Compare Group in Survey": "Jämför gruppen i Översikt", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", @@ -669,7 +679,7 @@ "Compression (quality scan)": "Komprimering (kvalitetsskanning)", "Compression artifacts": "Komprimeringsartefakter", "Computing AI masks": "Beräknar AI-masker", - "Confidence required": "Krävd säkerhet", + "Confidence required": "Kräv säkerhetsgrad", "Confirm": "Bekräfta", "Confirm Dialog": "Bekräfta dialogruta", "Confirm Faces from Immich": "Bekräfta ansikten från Immich", @@ -1043,6 +1053,8 @@ "Edit at History Step": "Redigera vid historiksteg", "Edit date": "Redigeringsdatum", "Edit in (one item)": "Redigera i (ett val)", + "Edit in Default Editor": "Redigera i standardredigeraren", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Redigera i annan redigerare (⌥⌘E) öppnar kopian i det här programmet (ett appnamn på macOS, en programsökväg annars). Lämnas platsen tom öppnar systemets standardprogram den.", "Edit this saved location": "Redigera den här sparade platsen", "Edit: Color": "Redigera: Färg", "Edit: Detail": "Redigera: Detalj", @@ -1051,6 +1063,7 @@ "Edit: Light": "Redigera: Ljus", "Edit: Optics": "Redigera: Optik", "Edited Version Saved Again": "Redigerad version sparad igen", + "Editors": "Redigerare", "Edit…": "Redigera…", "Elsewhere": "På andra ställen", "Email": "E-post", @@ -1355,6 +1368,7 @@ "Forget Remembered Object": "Glöm ihågkommet objekt", "Forget This Person": "Glöm den här personen", "Forget a Paired Surface": "Glöm en parkopplad yta", + "Format Options": "Formatalternativ", "Four with Caption": "Fyra med bildtext", "Frame": "Ram", "Frame Rate": "Bildfrekvens", @@ -1487,6 +1501,7 @@ "Hard Drive": "Hårddisk", "Hardcover": "Inbunden", "Has a GPS position (click to show it on the map)": "Har en GPS-position (klicka för att visa den på kartan)", + "Has a companion JPEG (click to open the Info panel)": "Har en tillhörande JPEG (klicka för att öppna infofönstret)", "Headline metadata": "Rubrikkmetadata", "Headroom": "Marginal", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Läk små mörka eller röda fläckar på ansiktenas hud; ögon, ögonbryn, näsborrar och läppar lämnas orörda", @@ -1516,7 +1531,7 @@ "Hide this wheel's effect": "Dölj hjulets effekt", "High Range": "Övre omfång", "High quality adjustment previews": "Förhandsvisningar med hög kvalitet vid justering", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Högre säkerhet hittar färre falska ansikten men kan missa riktiga. Gäller framtida detekteringar; skanna om för att uppdatera befintliga.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Högre säkerhet hittar färre falska ansikten men kan missa riktiga. Gäller framtida detekteringar; skanna igen för att uppdatera befintliga.", "Highlight Hue": "Nyans för högdagrar", "Highlight Luminance": "Luminans för högdagrar", "Highlight Reconstruction": "Högdagerrekonstruktion", @@ -1621,6 +1636,7 @@ "Import Mask Effects": "Importera maskeffekter", "Import Metadata Presets": "Importera metadataförinställningar", "Import New Shots": "Importera nya bilder", + "Import Order": "Importordning", "Import People": "Importera människor", "Import People from Immich": "Importera människor från Immich", "Import Photos and Video…": "Importera foton och video…", @@ -1705,6 +1721,7 @@ "Install the plugin": "Installera tillägget", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Installera din egen ONNX-modell med denoise-model.json bredvid. Den här versionen erbjuder inga modellhämtningar.", "Installed": "Installerad", + "Installed editors…": "Installerade redigerare…", "Installed in": "Installerad i", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Installationen tillåter inget av detta: tillägget frågar dig första gången det behöver var och en.", "Installing the surface plugin": "Installerar kontrollytans tillägg", @@ -1809,6 +1826,7 @@ "Large Landscape (13 × 11 in)": "Stor liggande (13 × 11 in)", "Large and Small": "Stor och liten", "Large image size": "Stor bildstorlek", + "Largest Face": "Största ansiktet", "Last Photo": "Sista fotot", "Last backup:": "Senaste säkerhetskopia:", "Last checked 1 hour ago": "Senast kontrollerat för 1 timme sedan", @@ -1821,6 +1839,7 @@ "Last synced on {}": "Synkades {}", "Last synced {} h ago": "Synkades för {} h sedan", "Last synced {} min ago": "Synkades för {} min sedan", + "Launch Options": "Startalternativ", "Layout Image Matte": "Passepartout för layoutbild", "Layout Image Off": "Layoutbild av", "Layout Image On": "Layoutbild på", @@ -2153,6 +2172,7 @@ "New Template Folder": "Ny mallmapp", "New Web Template Folder": "Ny webbmallsmapp", "New collections": "Nya samlingar", + "New editor": "Ny redigerare", "New group name": "Nytt gruppnamn", "New group:": "Ny grupp:", "New location name": "Nytt platsnamn", @@ -2164,6 +2184,7 @@ "New raw photos shot at this ISO or above start with AI Denoise on, and their denoised pictures are made in the background after the import. Needs a denoise model (Settings, AI Denoise).": "Nya rawfoton tagna med det här ISO-talet eller högre börjar med AI-brusreducering på, och deras brusreducerade bilder skapas i bakgrunden efter importen. Kräver en brusreduceringsmodell (Inställningar, AI-brusreducering).", "New red eye correction (Return adds it here)": "Ny korrigering av röda ögon (Retur lägger till den här)", "New shots:": "Nya bilder:", + "Newest First": "Nyast först", "Next": "Nästa", "Next Dial Page": "Nästa rattsida", "Next Filmstrip Background": "Nästa filmremsbakgrund", @@ -2338,6 +2359,7 @@ "Offset Hue": "Offset-nyans", "Offset Luminance": "Offset-ljushet", "Offset Saturation": "Offset-mättnad", + "Oldest First": "Äldst först", "On": "På", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "På ett skannat negativ eller en diabild: hitta och laga dammkorn, hårstrån och repor på filmen. Skannerns infraröda pass (en RGBI-fil från VueScan eller SilverFast) säger var de finns; annars söks bildens släta ytor igenom", "On photo": "På fotot", @@ -2414,6 +2436,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "Valfritt: ett foto av färgkartan under ett annat ljus, till exempel glödlampsljus, ger en profil med två ljuskällor.", "Optional: where downloads go": "Valfritt: vart hämtningar hamnar", "Orientation Detection Status": "Status för orienteringsidentifiering", + "Original (+XMP)": "Original (+XMP)", "Original Photo": "Originalfoto", "Other": "Annat", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Då ser andra appar dina betyg, nyckelord och redigeringar. En liten fil skrivs bredvid varje bild.", @@ -2504,6 +2527,7 @@ "Permissions": "Behörigheter", "Permissions:": "Behörigheter:", "Persistent": "Bestående", + "Person Sort": "Personsortering", "Personalize {app} with your own branding elements.": "Anpassa {app} med dina egna varumärkeselement.", "Personalized": "Anpassad", "Phone": "Telefon", @@ -2519,6 +2543,7 @@ "Photo with Side Text": "Foto med sidotext", "Photo with Title": "Foto med titel", "Photo zoom": "Fotozoom", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Foto → Redigera i listar här varje redigerare. De två första är inbyggda; lägg till så många du vill och klicka på en rad för att ändra vad den överlämnar.", "Photograph Information": "Fotoinformation", "Photographic": "Fotografisk", "Photographic realism: re-creating textures, extending a scene. Up to 2048 px per request.": "Fotografisk realism: återskapa texturer, utvidga en scen. Upp till 2048 px per begäran.", @@ -3532,6 +3557,7 @@ "Text Page": "Textsida", "Text Style Preset": "Förinställning för textstil", "Text size": "Textstorlek", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "JPEG-bilden bredvid raw-filen, som den följer: inte ett eget foto.", "The Loupedeck+ works through the {app} plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ fungerar via tillägget för {app}. Varje vred och knapp gör det som dess etikett säger tills du ställer in den här eller tar över din egen Loupedeck-profil (bara layouten följer med).", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console kommunicerar med {app} via tillägget för {app} till Logi Options+. Vid installationen lämnas tillägget över till Logi Options+, som ber dig bekräfta.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Profilhanteraren listar varje look, LUT-profil och kameraprofil: dölj dem i menyerna, byt namn på och gruppera dem, importera nya och radera dina egna.", @@ -3761,6 +3787,7 @@ "Transform": "Transformera", "Trash": "Papperskorg", "Trash renders taken out of a collection": "Kasta renderingar som tas bort ur en samling", + "Treat JPEGs next to raw files as companions": "Behandla JPEG-bilder bredvid råfiler som tillhörande", "Trim": "Trimma", "Trim End": "Trimma slut", "Trim Start": "Trimma början", @@ -3855,6 +3882,7 @@ "Update this one automatically": "Uppdatera det här automatiskt", "Update to Current Process Version": "Uppdatera till aktuell processversion", "Update with Current Settings…": "Uppdatera med aktuella inställningar…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Uppdateringar är avstängda ({env}_DISABLE_UPDATES är satt); din pakethanterare sköter uppdateringar.", "Updates the installed version": "Uppdaterar den installerade versionen", "Updates…": "Uppdateringar…", "Updating the DNG previews stopped unexpectedly": "Uppdateringen av DNG-förhandsvisningarna avbröts oväntat", @@ -3998,6 +4026,7 @@ "Wrong passphrase.": "Fel lösenfras.", "Wrote {} XMP sidecars": "Skrev XMP-sidofiler: {}", "X": "X", + "XMP Sidecar": "XMP-sidfilspar", "XMP Sidecars": "XMP-sidofiler", "Y": "Y", "Yellow Label": "Gul etikett", @@ -4040,9 +4069,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` med ett biblioteks egen fil (`catalog.snap`) öppnar dess mapp i stället för att misslyckas med", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (och de MCP-verktyg som tar mappar) hittar nu HEIC, HEIF och Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` loggar varningar även på stderr (ärende #168); `{env}_LOG` eller `RUST_LOG` väljer en annan nivå.", + "a copy of the original": "en kopia av originalet", + "a copy of the original, with an XMP sidecar": "en kopia av originalet, med en XMP-sidfilspar", "a photo matches any group": "ett foto matchar någon grupp", "a photo matches every group": "ett foto matchar varje grupp", "a word per topic; every word must match": "ett ord per ämne; varje ord måste matcha", + "adds an editor; click its row to name it and choose its program and file": "lägger till en rad; klicka på den för att namnge redigeraren och välja program och fil", "all of": "alla av", "allowed": "tillåten", "any of": "någon av", @@ -4131,18 +4163,24 @@ "published": "publicerade", "removed": "borttagna", "role": "roll", + "scene-linear Rec. 2020": "scenlinjär Rec. 2020", "selected photos": "markerade foton", "shots": "bilder", "steps": "steg", "tested": "testat", "the active photo isn't a video": "det aktiva fotot är inte en video", + "the arguments before the file; `{file}` places the file's path where it stands": "argumenten före filen; `{file}` placerar filens sökväg där det står", "the camera roll could not be read": "kamerarullen kunde inte läsas", + "the file's own": "filens eget", "the folder shown": "den visade mappen", "the folder shown (no folder is: pick one first)": "den visade mappen (ingen mapp: välj en först)", "the frames could not be matched to each other": "bilderna kunde inte matchas mot varandra", "the measured positions were less reliable than the camera's own pattern": "de uppmätta lägena var mindre tillförlitliga än kamerans eget mönster", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "systemets standardprogram för filtypen: Redigera i standardredigeraren renderar kopian och överlämnar den", + "the original, with an XMP sidecar": "originalet, med en XMP-sidfilspar", "the photos in view": "bilderna i vyn", "the plug-in worker stopped unexpectedly": "tilläggets arbetstråd stannade oväntat", + "the raw data's own": "rådatans eget", "the selected photos": "de valda bilderna", "the whole catalog": "hela katalogen", "there was not enough memory for the registered merge": "det fanns inte minne nog för den registrerade sammanfogningen", @@ -4162,6 +4200,7 @@ "video playback isn't available in this build": "videouppspelning är inte tillgänglig i den här versionen", "waiting for Apple Photos": "väntar på Apple Photos", "width": "bredd", + "write the edits beside the file": "skriver redigeringarna bredvid filen", "{app}": "{app}", "{app} Effect Presets": "Effektförinställningar för {app}", "{app} Export Presets": "Exportförinställningar för {app}", diff --git a/crates/ui-egui/locales/fork/uk-formats.json b/crates/ui-egui/locales/fork/uk-formats.json index a866199b0d..d41060650b 100644 --- a/crates/ui-egui/locales/fork/uk-formats.json +++ b/crates/ui-egui/locales/fork/uk-formats.json @@ -120,6 +120,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "У його маніфесті є значення, які ця версія не може використати й пропускає: {values}", "JPEG quality {q} to fit the size limit": "Якість JPEG {q}, щоб вкластися в обмеження розміру", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Якість JPEG {q}, щоб вкластися в обмеження розміру (менший розмір або більше обмеження зберігають більше якості)", + "Kept with {raw} as its companion: not a photo of its own.": "Зберігається разом із {raw} як супутник: не окрема фотографія.", "Kept. Groups left: {left}": "Залишено. Лишилось груп: {left}", "Last checked {n} hours ago": "Остання перевірка: {n} год тому", "Last checked {n} minutes ago": "Остання перевірка: {n} хв тому", @@ -326,6 +327,7 @@ "{} faces wait under 1 person": "Під 1 людиною чекають обличчя: {}", "{} faces wait under {} people": "Під {} людьми чекають обличчя: {}", "{} keys": "Клавіші {}", + "· {companions} kept with their RAWs": "· {companions} зберігаються зі своїми raw", "“{name}” added to Camera Profiles": "«{name}» додано до профілів камери", "“{name}” has its old settings again": "«{name}» знову має попередні налаштування", "“{name}” is new. What may the other devices syncing this catalog have of it?": "«{name}»: нова. Що з неї можуть отримувати інші пристрої, які синхронізують цей каталог?", diff --git a/crates/ui-egui/locales/fork/uk.json b/crates/ui-egui/locales/fork/uk.json index 5bb021e39f..2654c39490 100644 --- a/crates/ui-egui/locales/fork/uk.json +++ b/crates/ui-egui/locales/fork/uk.json @@ -36,6 +36,7 @@ "6 Blades": "6 пелюсток", "8 bits/component": "8 біт/канал", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": прийнято {accepted}, на перегляд {pending}, відхилено {rejected}", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "JPEG з іменем raw-файлу поруч із ним є його супутником: одна фотографія, одне сканування облич, один набір метаданих. Щоб імпортувати JPEG як окремі фотографії, зніміть прапорець параметра супутників.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Час створити резервну копію каталогу. Зробити її зараз, перед виходом з {app}?", "A card, a drive or a folder": "Картка, диск або тека", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "Каталог є текою: записи його фото, налаштування та історія. Самі фото залишаються там, де вони є.", @@ -92,6 +93,7 @@ "Add Blank": "Додати порожню сторінку", "Add Cell": "Додати комірку", "Add Column": "Додати стовпець", + "Add Editor": "Додати редактор", "Add Face Region": "Додати область обличчя", "Add Filter…": "Додати фільтр…", "Add Folder": "Додати теку", @@ -245,6 +247,7 @@ "Assign to Someone Else…": "Призначити іншій особі…", "Assign to…": "Призначити…", "At Import": "Під час імпорту", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Під час імпорту JPEG з іменем raw-файлу поруч із ним не окрема фотографія, а його супутник: одна мініатюра, одне сканування облич, один набір метаданих. Він іде за raw-файлом під час копіювання, переміщення та перейменування.", "At launch": "Під час запуску", "At most one request per second.": "Не більше одного запиту на секунду.", "Attribution (shown on the map)": "Атрибуція (показується на мапі)", @@ -303,6 +306,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "Нижче першого порогу лишається 0★; типові пороги: 20, 40, 55, 70 і 85.", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Між ними фотографія зберігає свій прапорець (без прапорця лишається без нього).", "Bit Depth": "Глибина кольору", + "Bit Level": "Розрядність", "Black": "Чорний", "Black Point Compensation": "Компенсація точки чорного", "Blank": "Порожня", @@ -351,7 +355,9 @@ "Browse your photos in a grid. Rate them with stars, flag the keepers and reject the rest, then sort them into collections and keywords. Filters find any photo by date, camera, rating or text.": "Переглядайте фото в сітці. Оцінюйте їх зірками, позначайте найкращі й відхиляйте решту, потім розкладайте за колекціями та ключовими словами. Фільтри знайдуть будь-яке фото за датою, камерою, оцінкою чи текстом.", "Brush (Return puts it down and paints, the arrows paint while it is down)": "Пензель (Enter опускає його й малює, стрілки малюють, поки він опущений)", "Brush Refinement": "Уточнення пензлем", + "Build Face Thumbnails": "Створити мініатюри облич", "Build at import": "Створювати під час імпорту", + "Building face thumbnails": "Створення мініатюр облич", "Building the profile…": "Створення профілю…", "Built in the background once the photos are in, from the one on screen outward.": "Створюються у фоні після імпорту, починаючи з фото на екрані.", "Built-in": "Вбудовані", @@ -507,6 +513,7 @@ "Choose folder later": "Вибрати теку пізніше", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Виберіть вигляд застосунку. Кожна зміна видна одразу; більше в Налаштування → Інтерфейс.", "Choose in Sync…": "Вибрати в синхронізації…", + "Choose the Editor's Program": "Вибрати програму редактора", "Choose the catalog to open.": "Виберіть каталог для відкриття.", "Choose where to import from": "Виберіть, звідки імпортувати", "Circle": "Коло", @@ -603,6 +610,7 @@ "Color to Replace": "Колір для заміни", "Color wheel": "Колірне коло", "Colour Profile": "Колірний профіль", + "Colour Space": "Колірний простір", "Colour space of the TIFF": "Колірний простір TIFF", "Column of Three": "Стовпець із трьох", "Columns": "Стовпці", @@ -616,13 +624,15 @@ "Compact Cells": "Компактні комірки", "Compact Layout": "Компактне компонування", "Compact – Dense": "Компактний – щільний", + "Companion": "Супутній", + "Companion JPEG:": "Супутній JPEG:", "Compare Group in Survey": "Порівняти групу в Огляді", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "Готово", "Compression (quality scan)": "Стиснення (сканування якості)", "Compression artifacts": "Артефакти стиснення", "Computing AI masks": "Обчислення ШІ-масок", - "Confidence required": "Потрібна впевненість", + "Confidence required": "Потрібна достовірність", "Confirm": "Підтвердити", "Confirm Faces from Immich": "Підтвердити обличчя з Immich", "Confirm Immich Link": "Підтвердити зв’язок з Immich", @@ -965,12 +975,15 @@ "Edit at History Step": "Редагувати на кроці історії", "Edit date": "Дата редагування", "Edit in (one item)": "Редагувати в (один пункт)", + "Edit in Default Editor": "Відкрити в редакторі за замовчуванням", "Edit in HDR: highlights above SDR white, for HDR exports and displays": "Редагувати в HDR: світла понад білий SDR, для експорту й дисплеїв HDR", "Edit in Other Editor": "Редагувати в іншому редакторі", "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "«Редагувати в іншому редакторі» (⌥⌘E) відкриває копію в цьому застосунку (назва застосунку на macOS, шлях до програми деінде).", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Відкрити в іншому редакторі (⌥⌘E) відкриває копію в цій програмі (назва програми на macOS, шлях до програми в інших випадках). Якщо місце порожнє, копію відкриває програма системи за замовчуванням.", "Edit in PhotoCraft": "Редагувати в PhotoCraft", "Edit this saved location": "Редагувати це збережене місце", "Edited Version Saved Again": "Відредаговану версію збережено знову", + "Editors": "Редактори", "Edit…": "Редагувати…", "Elsewhere": "В інших місцях", "Email": "Ел. пошта", @@ -1251,6 +1264,7 @@ "Forget Remembered Object": "Забути запам'ятований об'єкт", "Forget This Person": "Забути цю людину", "Forget a Paired Surface": "Забути пов'язану поверхню", + "Format Options": "Параметри формату", "Found automatically": "Знайдено автоматично", "Four with Caption": "Чотири з підписом", "Frame": "Рамка", @@ -1373,6 +1387,7 @@ "Hard Drive": "Жорсткий диск", "Hardcover": "Тверда обкладинка", "Has a GPS position (click to show it on the map)": "Має GPS-координати (клацніть, щоб показати на мапі)", + "Has a companion JPEG (click to open the Info panel)": "Є супутній JPEG (натисніть, щоб відкрити панель відомостей)", "Headline metadata": "Метадані основного заголовка", "Headroom": "Запас", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Прибирає дрібні темні й червоні цятки на шкірі облич; очі, брови, ніздрі й губи не зачіпаються", @@ -1400,7 +1415,7 @@ "Hide {app}": "Приховати {app}", "High Range": "Верхній діапазон", "High quality adjustment previews": "Високоякісний попередній перегляд під час коригування", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Вища впевненість дає менше хибних облич, але може пропустити справжні. Застосовується до майбутніх виявлень; щоб оновити наявні, виконайте повторне сканування.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Вища достовірність знаходить менше хибних облич, але може пропустити справжні. Стосується майбутніх виявлень; щоб оновити наявні, скануйте знову.", "Highlight Hue": "Тон світлих ділянок", "Highlight Luminance": "Яскравість світлих ділянок", "Highlight Reconstruction": "Відновлення світел", @@ -1498,6 +1513,7 @@ "Import Mask Effects": "Імпортувати ефекти маски", "Import Metadata Presets": "Імпортувати набори метаданих", "Import New Shots": "Імпортувати нові знімки", + "Import Order": "Порядок імпорту", "Import People": "Імпортувати людей", "Import People from Immich": "Імпортувати людей з Immich", "Import Photos and Video…": "Імпортувати фото та відео…", @@ -1580,6 +1596,7 @@ "Install from Plug-in Marketplace": "Установити з маркетплейсу плагінів", "Install the Surface Plugin": "Установити плагін Surface", "Installed": "Встановлено", + "Installed editors…": "Встановлені редактори…", "Installed in": "Установлено в", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Встановлення нічого з цього не дозволяє: плагін запитає вас, коли дозвіл знадобиться йому вперше.", "Install…": "Установити…", @@ -1664,6 +1681,7 @@ "Large Landscape (13 × 11 in)": "Велика альбомна (13 × 11 in)", "Large and Small": "Велика й мала", "Large image size": "Розмір великих зображень", + "Largest Face": "Найбільше обличчя", "Last Photo": "Останнє фото", "Last backup:": "Остання резервна копія:", "Last checked 1 hour ago": "Остання перевірка: 1 год тому", @@ -1676,6 +1694,7 @@ "Last synced on {}": "Остання синхронізація: {}", "Last synced {} h ago": "Остання синхронізація: {} год тому", "Last synced {} min ago": "Остання синхронізація: {} хв тому", + "Launch Options": "Параметри запуску", "Layout": "Макет", "Layout Image Matte": "Підкладка зображення макета", "Layout Image Off": "Зображення макета вимк.", @@ -1987,6 +2006,7 @@ "New Template Folder": "Нова тека шаблонів", "New Web Template Folder": "Нова папка вебшаблонів", "New collections": "Нові колекції", + "New editor": "Новий редактор", "New group (press Return)": "Нова група (натисніть Return)", "New group name": "Назва нової групи", "New group:": "Нова група:", @@ -1998,6 +2018,7 @@ "New red eye correction (Return adds it here)": "Нова корекція червоних очей (Return додає її тут)", "New shots:": "Нові знімки:", "New spot (Return adds it here)": "Нова пляма (Return додає її тут)", + "Newest First": "Спочатку нові", "Next Filmstrip Background": "Наступне тло стрічки кадрів", "Next Frame": "Наступний кадр", "Next History Step": "Наступний крок історії", @@ -2156,6 +2177,7 @@ "Offset Hue": "Відтінок offset", "Offset Luminance": "Яскравість offset", "Offset Saturation": "Насиченість offset", + "Oldest First": "Спочатку старі", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "На відсканованому негативі чи слайді: знайти й виправити порошинки, волосинки та подряпини на плівці. Інфрачервоний прохід сканера (файл RGBI з VueScan або SilverFast) каже, де вони; інакше переглядаються гладкі ділянки зображення", "On photo": "На фото", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "На пристрої-власнику колекції виберіть, що можуть мати інші; на інших виберіть, що бере цей пристрій.", @@ -2226,6 +2248,7 @@ "Optimize catalog after backing up": "Оптимізувати каталог після резервного копіювання", "Optional: where downloads go": "Необов’язково: куди зберігати завантаження", "Orientation Detection Status": "Стан визначення орієнтації", + "Original (+XMP)": "Оригінал (+XMP)", "Original Photo": "Оригінальне фото", "Other": "Інше", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Тоді інші застосунки бачитимуть ваші оцінки, ключові слова й правки. Поруч із кожним фото записується невеликий файл.", @@ -2308,6 +2331,7 @@ "Permissions": "Дозволи", "Permissions:": "Дозволи:", "Persistent": "Постійне", + "Person Sort": "Сортування особи", "Personalize {app} with your own branding elements.": "Оформте {app} власними елементами бренду.", "Personalized": "Персональна", "Phone": "Телефон", @@ -2323,6 +2347,7 @@ "Photo with Side Text": "Фото з бічним текстом", "Photo with Title": "Фото із заголовком", "Photo zoom": "Масштаб фото", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Фото → Редагувати в перелічує тут кожен редактор. Перші два вбудовані; додайте стільки, скільки треба, і клацніть рядок, щоб змінити, що він передає.", "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.": "Фото → Редагувати в → Редагувати в PhotoCraft (⇧⌘E або клацання фото правою кнопкою) рендерить копію з вашими змінами, складає її в стос з оригіналом і відкриває в PhotoCraft. Збережіть там, і копія оновиться тут. У форматі PSD PhotoCraft зберігає прямо в неї. Залиште розташування порожнім, якщо не користуєтеся портативною копією.", "PhotoCraft": "PhotoCraft", "Photograph Information": "Відомості про зйомку", @@ -3264,6 +3289,7 @@ "Text Page": "Текстова сторінка", "Text Style Preset": "Набір стилю тексту", "Text size": "Розмір тексту", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "JPEG біля raw-файлу, зберігається разом із ним: не окрема фотографія.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Менеджер профілів показує всі стилі, профілі LUT і профілі камер: приховуйте їх з меню, перейменовуйте й групуйте, імпортуйте нові та видаляйте власні.", "The account has no PIN or password, so there is nothing to unlock.": "Обліковий запис не має ні PIN-кода, ні пароля, тому розблоковувати нічого.", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "Активне фото знято там, де воно геотеговане (або в центрі мапи): зіставте його з треком", @@ -3473,6 +3499,7 @@ "Tracklog": "Трек", "Transform": "Трансформування", "Trash renders taken out of a collection": "Видаляти в кошик оброблені копії, прибрані з колекції", + "Treat JPEGs next to raw files as companions": "Вважати JPEG біля raw-файлів супровідними", "Trim": "Обрізка", "Trim End": "Кінець обрізання", "Trim Start": "Початок обрізання", @@ -3561,6 +3588,7 @@ "Update to Current Process": "Оновити до поточного процесу", "Update to Current Process Version": "Оновити до поточної версії обробки", "Update with Current Settings…": "Оновити поточними налаштуваннями…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Оновлення вимкнено (задано змінну {env}_DISABLE_UPDATES); оновленнями опікується менеджер пакетів.", "Updates the installed version": "Оновлює встановлену версію", "Updates…": "Оновлення…", "Updating the DNG previews stopped unexpectedly": "Оновлення попередніх переглядів DNG несподівано зупинилося", @@ -3688,6 +3716,7 @@ "Wrong passphrase.": "Неправильна парольна фраза.", "Wrote {} XMP sidecars": "Записано {} супровідних файлів XMP", "X": "X", + "XMP Sidecar": "XMP-сайдкар", "XMP Sidecars": "XMP-файли", "Y": "Y", "Yellow Label": "Жовта мітка", @@ -3719,9 +3748,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library`, отримавши власний файл бібліотеки (`catalog.snap`), відкриває її теку замість помилки", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (і інструменти MCP, що приймають теки) тепер підхоплює HEIC, HEIF і Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` також виводить попередження в stderr (issue #168); `{env}_LOG` або `RUST_LOG` вибирає інший рівень.", + "a copy of the original": "копія оригіналу", + "a copy of the original, with an XMP sidecar": "копія оригіналу з XMP-сайдкаром", "a photo matches any group": "фото відповідає будь-якій групі", "a photo matches every group": "фото відповідає кожній групі", "a word per topic; every word must match": "одне слово на тему; усі слова мають збігтися", + "adds an editor; click its row to name it and choose its program and file": "додає рядок; клацніть його, щоб назвати редактор і вибрати програму та файл", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "після цього (проблема #101): частковий запис обрізається перед повторною спробою {app}, тому наступний запуск відтворює кожну", "all of": "усі з", "allowed": "дозволено", @@ -3811,6 +3843,7 @@ "published": "опубліковано", "removed": "видалено", "role": "роль", + "scene-linear Rec. 2020": "лінійний Rec. 2020", "selected photos": "вибрані фото", "shots": "знімків", "size": "розмір", @@ -3819,13 +3852,18 @@ "source": "джерело", "steps": "кроків", "the active photo isn't a video": "активне фото не є відео", + "the arguments before the file; `{file}` places the file's path where it stands": "аргументи перед файлом; `{file}` ставить шлях до файлу на це місце", "the camera roll could not be read": "не вдалося прочитати фотоплівку", + "the file's own": "як у файлі", "the folder shown": "показана папка", "the folder shown (no folder is: pick one first)": "показана папка (папки немає: спершу виберіть її)", "the frames could not be matched to each other": "не вдалося зіставити кадри один з одним", "the measured positions were less reliable than the camera's own pattern": "виміряні положення виявилися менш надійними, ніж власний візерунок камери", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "програма системи за замовчуванням для цього типу файлів: «Відкрити в редакторі за замовчуванням» готує копію та передає її", + "the original, with an XMP sidecar": "оригінал з XMP-сайдкаром", "the photos in view": "фотографії у поданні", "the plug-in worker stopped unexpectedly": "робочий потік плагіна несподівано зупинився", + "the raw data's own": "як у вихідних даних", "the selected photos": "вибрані фотографії", "the whole catalog": "увесь каталог", "there was not enough memory for the registered merge": "для об’єднання з суміщенням не вистачило пам’яті", @@ -3845,6 +3883,7 @@ "video playback isn't available in this build": "відтворення відео недоступне в цій збірці", "waiting for Apple Photos": "очікування Apple Photos", "width": "ширина", + "write the edits beside the file": "записує правки поруч із файлом", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "створена новішим {app}, відхиляється з повідомленням «цю бібліотеку створено новішою версією {app}» і залишається", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "створена новішим {app}), {app} пояснює причину й пропонує Спробувати знову, Вибрати іншу бібліотеку…, Продовжити", "{app}": "{app}", diff --git a/crates/ui-egui/locales/fork/vi-formats.json b/crates/ui-egui/locales/fork/vi-formats.json index df97d57be3..01792b67bd 100644 --- a/crates/ui-egui/locales/fork/vi-formats.json +++ b/crates/ui-egui/locales/fork/vi-formats.json @@ -146,6 +146,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "Manifest của nó có các giá trị mà phiên bản này không dùng được và sẽ bỏ qua: {values}", "JPEG quality {q} to fit the size limit": "Chất lượng JPEG {q} để vừa giới hạn kích thước", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "Chất lượng JPEG {q} để vừa giới hạn kích thước (kích thước nhỏ hơn hoặc giới hạn lớn hơn giữ được nhiều chất lượng hơn)", + "Kept with {raw} as its companion: not a photo of its own.": "Được giữ cùng {raw} như một ảnh đồng hành: không phải một ảnh riêng.", "Kept. Groups left: {left}": "Đã giữ. Số nhóm còn lại: {left}", "Key from the environment variable {}": "Khóa từ biến môi trường {}", "Key saved (ends in {})": "Đã lưu khóa (kết thúc bằng {})", @@ -407,6 +408,7 @@ "{} photos · {} aligned": "{} ảnh · {} đã căn chỉnh", "{} photos · {} aligned · {} left out": "{} ảnh · {} đã căn chỉnh · {} bị loại", "{} spot(s) from Remove Dust (outlined in amber)": "{} vết từ Xóa bụi (viền màu hổ phách)", + "· {companions} kept with their RAWs": "· {companions} được giữ cùng RAW của chúng", "“{name}” added to Camera Profiles": "Đã thêm “{name}” vào Hồ sơ máy ảnh", "“{name}” has its old settings again": "“{name}” đã có lại cài đặt cũ", "“{name}” is new. What may the other devices syncing this catalog have of it?": "“{name}” là mới. Các thiết bị khác đang đồng bộ catalog này được có gì từ nó?", diff --git a/crates/ui-egui/locales/fork/vi.json b/crates/ui-egui/locales/fork/vi.json index 278fa10004..3e9823b52a 100644 --- a/crates/ui-egui/locales/fork/vi.json +++ b/crates/ui-egui/locales/fork/vi.json @@ -47,6 +47,7 @@ "8 bits/component": "8 bit/thành phần", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} đạt, {pending} cần xem lại, {rejected} loại", "A 16:9 frame with black bars above and below, the title in the corner, fades through black and a closing card.": "Khung 16:9 có dải đen phía trên và dưới, tiêu đề ở góc, chuyển mờ qua màu đen và một thẻ kết thúc.", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "JPEG có cùng tên với tệp raw bên cạnh là ảnh đồng hành của tệp đó: một ảnh, một lần quét khuôn mặt, một bộ siêu dữ liệu. Bỏ chọn tùy chọn đồng hành để nhập JPEG thành các ảnh riêng.", "A backup of the catalog is due. Back it up now, before {app} quits?": "Đã đến hạn sao lưu catalog. Sao lưu ngay trước khi {app} thoát?", "A camera profile is being built": "Đang tạo hồ sơ máy ảnh", "A camera profile is for one camera: use a photo from the same camera body.": "Hồ sơ máy ảnh dành cho một máy ảnh: hãy dùng ảnh chụp từ cùng thân máy.", @@ -121,6 +122,7 @@ "Add Blank": "Thêm trang trống", "Add Cell": "Thêm ô", "Add Column": "Thêm cột", + "Add Editor": "Thêm trình chỉnh sửa", "Add Face Region": "Thêm vùng khuôn mặt", "Add Filter…": "Thêm bộ lọc…", "Add Folder": "Thêm thư mục", @@ -291,6 +293,7 @@ "Assign to Someone Else…": "Giao cho người khác…", "Assign to…": "Giao cho…", "At Import": "Khi nhập", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "Khi nhập, JPEG có cùng tên với tệp raw bên cạnh không phải là ảnh riêng mà là ảnh đồng hành của tệp raw: một ảnh thu nhỏ, một lần quét khuôn mặt, một bộ siêu dữ liệu. Ảnh này đi cùng tệp raw khi sao chép, di chuyển hoặc đổi tên.", "At launch": "Khi khởi động", "At most one request per second.": "Tối đa một yêu cầu mỗi giây.", "Attribution (shown on the map)": "Ghi công (hiện trên bản đồ)", @@ -354,6 +357,7 @@ "Between the two, a photo keeps its flag (unflagged stays unflagged).": "Ở giữa hai mốc, ảnh giữ nguyên dấu (không có dấu vẫn không có).", "Big steps": "Bước lớn", "Bit Depth": "Độ sâu bit", + "Bit Level": "Mức bit", "Black": "Đen", "Black Point Compensation": "Bù điểm đen", "Blank": "Trống", @@ -411,7 +415,9 @@ "Brush Flow": "Dòng cọ", "Brush Refinement": "Tinh chỉnh bằng cọ", "Brush Size": "Kích thước cọ", + "Build Face Thumbnails": "Tạo hình thu nhỏ khuôn mặt", "Build at import": "Tạo khi nhập", + "Building face thumbnails": "Đang tạo hình thu nhỏ khuôn mặt", "Building the profile…": "Đang tạo hồ sơ…", "Built in the background once the photos are in, from the one on screen outward.": "Được tạo ở nền khi ảnh đã vào, bắt đầu từ ảnh trên màn hình rồi lan ra.", "Built-in": "Tích hợp", @@ -575,6 +581,7 @@ "Choose folder later": "Chọn thư mục sau", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "Chọn giao diện cho ứng dụng. Mỗi thay đổi hiện ngay; xem thêm trong Cài đặt → Giao diện.", "Choose in Sync…": "Chọn trong Đồng bộ…", + "Choose the Editor's Program": "Chọn chương trình của trình chỉnh sửa", "Choose the catalog to open.": "Chọn catalog để mở.", "Choose where to import from": "Chọn nguồn nhập", "Chroma": "Sắc độ", @@ -683,6 +690,7 @@ "Colors match the chart; each keeps the lightness the camera recorded. For people and everyday photos.": "Màu khớp với bảng màu; mỗi màu giữ độ sáng mà máy ảnh ghi lại. Dành cho ảnh người và ảnh thường ngày.", "Colour": "Màu", "Colour Profile": "Hồ sơ màu", + "Colour Space": "Không gian màu", "Colour knobs P1–P8": "Núm màu P1–P8", "Colour only": "Chỉ màu", "Colour space of the TIFF": "Không gian màu của TIFF", @@ -703,6 +711,8 @@ "Compact Cells": "Ô gọn", "Compact Layout": "Bố cục gọn", "Compact – Dense": "Gọn – Dày đặc", + "Companion": "Đồng hành", + "Companion JPEG:": "JPEG đồng hành:", "Compare Before and After": "So sánh trước và sau", "Compare Group in Survey": "So sánh nhóm trong Khảo sát", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", @@ -1091,6 +1101,8 @@ "Edit at History Step": "Sửa tại bước lịch sử", "Edit date": "Ngày chỉnh sửa", "Edit in (one item)": "Chỉnh sửa trong (một mục)", + "Edit in Default Editor": "Chỉnh trong trình mặc định", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "Chỉnh trong trình khác (⌥⌘E) mở bản sao trong ứng dụng này (tên ứng dụng trên macOS, đường dẫn chương trình ở nơi khác). Để trống vị trí, ứng dụng mặc định của hệ thống sẽ mở nó.", "Edit this saved location": "Sửa vị trí đã lưu này", "Edit: Color": "Chỉnh sửa: Màu", "Edit: Detail": "Chỉnh sửa: Chi tiết", @@ -1099,6 +1111,7 @@ "Edit: Light": "Chỉnh sửa: Ánh sáng", "Edit: Optics": "Chỉnh sửa: Quang học", "Edited Version Saved Again": "Đã lưu lại phiên bản đã chỉnh", + "Editors": "Trình chỉnh sửa", "Edit…": "Sửa…", "Elsewhere": "Ở nơi khác", "Email": "Email", @@ -1421,6 +1434,7 @@ "Forget Remembered Object": "Quên đối tượng đã ghi nhớ", "Forget This Person": "Quên người này", "Forget a Paired Surface": "Quên một bàn điều khiển đã ghép nối", + "Format Options": "Tùy chọn định dạng", "Four with Caption": "Bốn ảnh có chú thích", "Frame": "Khung", "Frame Rate": "Tốc độ khung hình", @@ -1559,6 +1573,7 @@ "Hard Drive": "Ổ cứng", "Hardcover": "Bìa cứng", "Has a GPS position (click to show it on the map)": "Có vị trí GPS (nhấp để xem trên bản đồ)", + "Has a companion JPEG (click to open the Info panel)": "Có JPEG đồng hành (bấm để mở bảng thông tin)", "Headline metadata": "Siêu dữ liệu tiêu đề chính", "Headroom": "Khoảng dư sáng", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "Sửa các đốm tối hoặc đỏ nhỏ trên da mặt; mắt, lông mày, lỗ mũi và môi được giữ nguyên", @@ -1588,7 +1603,7 @@ "Hide this wheel's effect": "Ẩn hiệu ứng của bánh xe này", "High Range": "Dải cao", "High quality adjustment previews": "Xem trước điều chỉnh chất lượng cao", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Độ tin cậy cao hơn tìm ít khuôn mặt sai hơn nhưng có thể bỏ sót khuôn mặt thật. Áp dụng cho các lần phát hiện sau; quét lại để cập nhật các phát hiện hiện có.", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "Độ tin cậy cao hơn tìm thấy ít khuôn mặt sai hơn, nhưng có thể bỏ sót khuôn mặt thật. Áp dụng cho các lần phát hiện sau; quét lại để cập nhật những phát hiện hiện có.", "Highlight Hue": "Sắc độ vùng sáng", "Highlight Luminance": "Độ sáng vùng sáng", "Highlight Reconstruction": "Tái tạo vùng sáng", @@ -1696,6 +1711,7 @@ "Import Mask Effects": "Nhập hiệu ứng mặt nạ", "Import Metadata Presets": "Nhập thiết lập sẵn siêu dữ liệu", "Import New Shots": "Nhập ảnh mới chụp", + "Import Order": "Thứ tự nhập", "Import People": "Nhập người", "Import People from Immich": "Nhập người từ Immich", "Import Photos and Video…": "Nhập ảnh và video…", @@ -1784,6 +1800,7 @@ "Install the plugin": "Cài plugin", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "Hãy cài mô hình ONNX của riêng bạn kèm denoise-model.json bên cạnh. Bản build này không có tải mô hình.", "Installed": "Đã cài", + "Installed editors…": "Trình chỉnh sửa đã cài…", "Installed in": "Đã cài tại", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "Việc cài đặt không cấp quyền nào: plugin sẽ hỏi bạn khi lần đầu cần từng quyền.", "Installing the surface plugin": "Đang cài plugin bàn điều khiển", @@ -1891,6 +1908,7 @@ "Large Landscape (13 × 11 in)": "Ngang lớn (13 × 11 in)", "Large and Small": "Lớn và nhỏ", "Large image size": "Cỡ ảnh lớn", + "Largest Face": "Khuôn mặt lớn nhất", "Last Photo": "Ảnh cuối", "Last backup:": "Sao lưu gần nhất:", "Last checked 1 hour ago": "Kiểm tra lần cuối: 1 giờ trước", @@ -1903,6 +1921,7 @@ "Last synced on {}": "Đồng bộ lần cuối vào {}", "Last synced {} h ago": "Đồng bộ lần cuối {} giờ trước", "Last synced {} min ago": "Đồng bộ lần cuối {} phút trước", + "Launch Options": "Tùy chọn khởi chạy", "Layout": "Bố cục", "Layout Image Matte": "Lớp mờ ảnh bố cục", "Layout Image Off": "Tắt ảnh bố cục", @@ -2246,6 +2265,7 @@ "New Template Folder": "Thư mục mẫu mới", "New Web Template Folder": "Thư mục mẫu web mới", "New collections": "Bộ sưu tập mới", + "New editor": "Trình chỉnh sửa mới", "New group (press Return)": "Nhóm mới (nhấn Return)", "New group name": "Tên nhóm mới", "New group:": "Nhóm mới:", @@ -2260,6 +2280,7 @@ "New shots:": "Ảnh mới chụp:", "New spot (Return adds it here)": "Điểm mới (Return thêm vào đây)", "New template name": "Tên mẫu mới", + "Newest First": "Mới nhất trước", "Next": "Tiếp", "Next Dial Page": "Trang núm xoay tiếp theo", "Next Filmstrip Background": "Nền dải phim tiếp theo", @@ -2442,6 +2463,7 @@ "Offset Hue": "Sắc độ offset", "Offset Luminance": "Độ sáng offset", "Offset Saturation": "Độ bão hòa offset", + "Oldest First": "Cũ nhất trước", "On": "Bật", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "Trên âm bản hoặc phim dương đã quét: tìm và sửa hạt bụi, sợi tóc và vết xước trên phim. Lượt quét hồng ngoại của máy quét (tệp RGBI từ VueScan hoặc SilverFast) cho biết chúng ở đâu; nếu không, các vùng phẳng của ảnh sẽ được dò tìm", "On photo": "Trên ảnh", @@ -2519,6 +2541,7 @@ "Optional: a chart photo under another light, such as tungsten, makes a dual-illuminant profile.": "Tùy chọn: một ảnh bảng màu dưới nguồn sáng khác, như đèn sợi đốt, tạo hồ sơ hai nguồn sáng.", "Optional: where downloads go": "Tùy chọn: nơi lưu tệp tải xuống", "Orientation Detection Status": "Trạng thái nhận diện chiều ảnh", + "Original (+XMP)": "Bản gốc (+XMP)", "Original Photo": "Ảnh gốc", "Other": "Khác", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "Khi đó ứng dụng khác sẽ thấy xếp hạng, từ khóa và chỉnh sửa của bạn. Một tệp nhỏ được ghi cạnh mỗi ảnh.", @@ -2614,6 +2637,7 @@ "Permissions": "Quyền", "Permissions:": "Quyền:", "Persistent": "Cố định", + "Person Sort": "Sắp xếp người", "Personalize {app} with your own branding elements.": "Cá nhân hóa {app} bằng các yếu tố thương hiệu của riêng bạn.", "Personalized": "Cá nhân hóa", "Phone": "Điện thoại", @@ -2627,6 +2651,7 @@ "Photo with Side Text": "Ảnh kèm văn bản bên cạnh", "Photo with Title": "Ảnh kèm tiêu đề", "Photo zoom": "Thu phóng ảnh", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "Ảnh → Chỉnh trong liệt kê mọi trình chỉnh sửa tại đây. Hai cái đầu có sẵn; thêm bao nhiêu tùy thích, và bấm một dòng để đổi tệp nó chuyển đi.", "Photograph Information": "Thông tin chụp ảnh", "Photographic": "Chân thực", "Photographic realism: re-creating textures, extending a scene. Up to 2048 px per request.": "Chân thực như ảnh chụp: tái tạo kết cấu, mở rộng khung cảnh. Tối đa 2048 px mỗi yêu cầu.", @@ -3687,6 +3712,7 @@ "Text Style Preset": "Thiết lập sẵn kiểu chữ", "Text overlays": "Lớp phủ văn bản", "Text size": "Cỡ chữ", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "JPEG cạnh tệp raw, được giữ cùng với nó: không phải một ảnh riêng.", "The Loupedeck+ works through the {app} plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ hoạt động qua plugin {app}. Mỗi núm và nút làm đúng như nhãn của nó cho đến khi bạn đặt lại ở đây, hoặc mang hồ sơ Loupedeck của riêng bạn sang (chỉ bố cục được chuyển theo).", "The MX Creative Console talks to {app} through the {app} plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console giao tiếp với {app} qua plugin {app} cho Logi Options+. Khi cài, plugin được giao cho Logi Options+, ứng dụng này sẽ yêu cầu bạn xác nhận.", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "Trình quản lý hồ sơ liệt kê mọi giao diện màu, hồ sơ LUT và hồ sơ máy ảnh: ẩn chúng khỏi menu, đổi tên và nhóm chúng, nhập hồ sơ mới và xóa hồ sơ của riêng bạn.", @@ -3936,6 +3962,7 @@ "Transform": "Biến đổi", "Trash": "Thùng rác", "Trash renders taken out of a collection": "Chuyển vào thùng rác các bản kết xuất bị gỡ khỏi bộ sưu tập", + "Treat JPEGs next to raw files as companions": "Coi JPEG cạnh tệp raw là ảnh đồng hành", "Trim": "Cắt đoạn", "Trim End": "Cắt điểm cuối", "Trim Start": "Cắt điểm đầu", @@ -4032,6 +4059,7 @@ "Update this one automatically": "Tự động cập nhật plugin này", "Update to Current Process Version": "Cập nhật lên phiên bản quy trình hiện tại", "Update with Current Settings…": "Cập nhật với cài đặt hiện tại…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "Cập nhật đã bị tắt ({env}_DISABLE_UPDATES được đặt); trình quản lý gói của bạn sẽ lo việc cập nhật.", "Updates the installed version": "Cập nhật phiên bản đã cài", "Updates…": "Cập nhật…", "Updating the DNG previews stopped unexpectedly": "Việc cập nhật bản xem trước DNG đã dừng đột ngột", @@ -4182,6 +4210,7 @@ "Wrote the XMP sidecars that were waiting": "Đã ghi các sidecar XMP đang chờ", "Wrote {} XMP sidecars": "Đã ghi {} sidecar XMP", "X": "X", + "XMP Sidecar": "Tệp sidecar XMP", "XMP Sidecars": "Sidecar XMP", "Y": "Y", "Yellow Label": "Nhãn vàng", @@ -4228,9 +4257,12 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` khi nhận chính tệp của thư viện (`catalog.snap`) sẽ mở thư mục của nó thay vì báo lỗi", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import ` (và các công cụ MCP nhận thư mục) giờ nhận cả HEIC, HEIF và Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` cũng ghi cảnh báo ra stderr (issue #168); `{env}_LOG` hoặc `RUST_LOG` chọn mức khác.", + "a copy of the original": "bản sao của bản gốc", + "a copy of the original, with an XMP sidecar": "bản sao của bản gốc, kèm tệp sidecar XMP", "a photo matches any group": "ảnh khớp với nhóm bất kỳ", "a photo matches every group": "ảnh khớp với mọi nhóm", "a word per topic; every word must match": "mỗi chủ đề một từ; mọi từ đều phải khớp", + "adds an editor; click its row to name it and choose its program and file": "thêm một dòng; bấm vào để đặt tên cho trình chỉnh sửa và chọn chương trình cùng tệp", "all of": "tất cả", "allowed": "đã cho phép", "any of": "bất kỳ", @@ -4321,6 +4353,7 @@ "published": "đã xuất bản", "removed": "đã gỡ", "role": "vai trò", + "scene-linear Rec. 2020": "tuyến tính theo cảnh Rec. 2020", "selected photos": "ảnh đã chọn", "shots": "ảnh chụp", "size": "kích thước", @@ -4328,13 +4361,18 @@ "steps": "bước", "tested": "đã kiểm tra", "the active photo isn't a video": "ảnh đang hoạt động không phải là video", + "the arguments before the file; `{file}` places the file's path where it stands": "các đối số trước tệp; `{file}` đặt đường dẫn của tệp tại vị trí đó", "the camera roll could not be read": "không đọc được thư viện ảnh của máy", + "the file's own": "theo tệp", "the folder shown": "thư mục đang hiển thị", "the folder shown (no folder is: pick one first)": "thư mục đang hiển thị (chưa có: chọn trước)", "the frames could not be matched to each other": "không thể khớp các khung hình với nhau", "the measured positions were less reliable than the camera's own pattern": "các vị trí đo được kém tin cậy hơn mẫu riêng của máy ảnh", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "ứng dụng mặc định của hệ thống cho loại tệp này: Chỉnh trong trình mặc định kết xuất bản sao và chuyển cho nó", + "the original, with an XMP sidecar": "bản gốc, kèm tệp sidecar XMP", "the photos in view": "các ảnh trong chế độ xem", "the plug-in worker stopped unexpectedly": "tiến trình của plugin dừng bất ngờ", + "the raw data's own": "theo dữ liệu RAW", "the selected photos": "các ảnh đã chọn", "the whole catalog": "toàn bộ catalog", "there was not enough memory for the registered merge": "không đủ bộ nhớ cho bản hợp nhất có căn chỉnh", @@ -4354,6 +4392,7 @@ "video playback isn't available in this build": "bản dựng này không phát được video", "waiting for Apple Photos": "đang chờ Apple Photos", "width": "chiều rộng", + "write the edits beside the file": "ghi các chỉnh sửa cạnh tệp", "{app}": "{app}", "{app} Effect Presets": "Thiết lập sẵn hiệu ứng {app}", "{app} Export Presets": "Thiết lập sẵn xuất {app}", diff --git a/crates/ui-egui/locales/fork/zh-hans-formats.json b/crates/ui-egui/locales/fork/zh-hans-formats.json index ed3a72401b..31acdcd040 100644 --- a/crates/ui-egui/locales/fork/zh-hans-formats.json +++ b/crates/ui-egui/locales/fork/zh-hans-formats.json @@ -123,6 +123,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "其清单包含此版本无法使用并省略的值:{values}", "JPEG quality {q} to fit the size limit": "为符合大小限制,JPEG 质量为 {q}", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "为符合大小限制,JPEG 质量为 {q}(缩小尺寸或放宽限制可保留更多质量)", + "Kept with {raw} as its companion: not a photo of its own.": "与 {raw} 一起作为伴随文件保留:不是单独的照片。", "Kept. Groups left: {left}": "已保留。剩余组数:{left}", "Last checked {n} hours ago": "上次检查:{n} 小时前", "Last checked {n} minutes ago": "上次检查:{n} 分钟前", @@ -336,6 +337,7 @@ "{} keys": "{} 按键", "{} of {} from {host}": "{}/{},来自 {host}", "{} · {}. Kept in the catalog's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}。保存在目录的“denoise”文件夹中;达到上限时,会先删除没有照片使用的最旧结果。", + "· {companions} kept with their RAWs": "· {companions} 与其 RAW 保存在一起", "“{name}” added to Camera Profiles": "已将“{name}”添加到相机配置文件", "“{name}” has its old settings again": "“{name}”已恢复原来的设置", "“{name}” is new. What may the other devices syncing this catalog have of it?": "“{name}”是新的。同步此目录的其他设备可以获得它的哪些内容?", diff --git a/crates/ui-egui/locales/fork/zh-hans.json b/crates/ui-egui/locales/fork/zh-hans.json index e7fdb0232e..e86405ad5d 100644 --- a/crates/ui-egui/locales/fork/zh-hans.json +++ b/crates/ui-egui/locales/fork/zh-hans.json @@ -45,6 +45,7 @@ "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,除非", "8 bits/component": "8 位/分量", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} 合格、{pending} 待复核、{rejected} 不合格", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "与旁边 RAW 文件同名的 JPEG 是它的伴随文件:一张照片、一次人脸扫描、一套元数据。要单独导入 JPEG,请取消勾选伴随文件选项。", "A backup of the catalog is due. Back it up now, before {app} quits?": "目录备份已到期。要在 {app} 退出前立即备份吗?", "A card, a drive or a folder": "存储卡、驱动器或文件夹", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "目录是一个文件夹:包含照片的记录、设置和历史记录。照片本身保留在原处。", @@ -105,6 +106,7 @@ "Add Blank": "添加空白页", "Add Cell": "添加单元格", "Add Column": "添加列", + "Add Editor": "添加编辑器", "Add Face Model…": "添加人脸模型…", "Add Face Region": "添加人脸框", "Add Filter…": "添加滤镜…", @@ -257,6 +259,7 @@ "Assign to Someone Else…": "指定给其他人…", "Assign to…": "指定给…", "At Import": "导入时", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "导入时,与旁边 RAW 文件同名的 JPEG 不是单独的照片,而是该 RAW 的伴随文件:一张缩略图、一次人脸扫描、一套元数据。复制、移动或重命名 RAW 时,它会一同跟随。", "At launch": "启动时", "At most one request per second.": "每秒最多一次请求。", "Attribution (shown on the map)": "署名(显示在地图上)", @@ -317,6 +320,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "低于第一个阈值仍为 0★;默认值为 20、40、55、70 和 85。", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "介于两者之间时,照片保留原有标记(未标记的仍不标记)。", "Bit Depth": "位深度", + "Bit Level": "位深", "Black": "黑色", "Black Point Compensation": "黑场补偿", "Blank": "空白", @@ -366,7 +370,9 @@ "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "浏览器版(实验性),保护图库安全(issue #107):“文件 → 备份图库…”会下载目录", "Brush (Return puts it down and paints, the arrows paint while it is down)": "画笔(Return 放下并绘制,放下时方向键绘制)", "Brush Refinement": "画笔调整", + "Build Face Thumbnails": "创建人脸缩略图", "Build at import": "导入时生成", + "Building face thumbnails": "正在创建人脸缩略图", "Building the profile…": "正在生成配置文件…", "Built in the background once the photos are in, from the one on screen outward.": "照片导入后在后台生成,从屏幕上的那张开始。", "Built-in": "内置", @@ -528,6 +534,7 @@ "Choose folder later": "稍后选择文件夹", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "选择应用的外观。每项更改立即生效;更多选项在“设置 → 界面”中。", "Choose in Sync…": "在同步中选择…", + "Choose the Editor's Program": "选择编辑器的程序", "Choose the catalog to open.": "选择要打开的目录。", "Choose where to import from": "选择导入来源", "Circle": "圆形", @@ -623,6 +630,7 @@ "Color to Replace": "要替换的颜色", "Color wheel": "色轮", "Colour Profile": "颜色配置文件", + "Colour Space": "色彩空间", "Colour space of the TIFF": "TIFF 的色彩空间", "Colour-label filter with several labels at once; expandable folder tree in Local.": "可同时按多个颜色标签筛选;“本地”中的文件夹树可展开。", "Colour-range masks: click the photo to sample. Luminance ranges: range bar, smoothness, luminance map.": "颜色范围蒙版:点击照片取样。明亮度范围:范围条、平滑度、明亮度映射。", @@ -638,6 +646,8 @@ "Compact Cells": "紧凑单元格", "Compact Layout": "紧凑布局", "Compact – Dense": "紧凑 – 密集", + "Companion": "伴随文件", + "Companion JPEG:": "伴随 JPEG:", "Compare Group in Survey": "在筛选视图中比较此组", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "已完成", @@ -995,13 +1005,16 @@ "Edit at History Step": "在历史记录步骤处编辑", "Edit date": "编辑日期", "Edit in (one item)": "在外部编辑(一个项目)", + "Edit in Default Editor": "用默认编辑器编辑", "Edit in External Editor (⇧⌘E): a 16-bit TIFF copy, stacked, refreshed when you come back.": "在外部编辑器中编辑(⇧⌘E):16 位 TIFF 副本,自动堆叠,返回时刷新。", "Edit in HDR: highlights above SDR white, for HDR exports and displays": "在 HDR 中编辑:高光超出 SDR 白色,适用于 HDR 导出和显示器", "Edit in Other Editor": "在其他编辑器中编辑", "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "“在其他编辑器中编辑”(⌥⌘E)会在此应用程序中打开副本(macOS 上为应用名称,其他系统上为程序路径)。", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "用其他编辑器编辑 (⌥⌘E) 会在该应用程序中打开副本 (macOS 为应用程序名,其他平台为程序路径)。位置留空时由系统默认应用程序打开。", "Edit in PhotoCraft": "在 PhotoCraft 中编辑", "Edit this saved location": "编辑此存储的位置", "Edited Version Saved Again": "编辑版本已再次保存", + "Editors": "编辑器", "Edit…": "编辑…", "Elsewhere": "在其他位置", "Email": "电子邮件", @@ -1296,6 +1309,7 @@ "Forget Remembered Object": "忘记记住的对象", "Forget This Person": "忘记此人", "Forget a Paired Surface": "忘记已配对的平面设备", + "Format Options": "格式选项", "Found automatically": "自动找到", "Four with Caption": "四张带题注", "Frame": "框架", @@ -1419,6 +1433,7 @@ "Hard Drive": "硬盘", "Hardcover": "精装", "Has a GPS position (click to show it on the map)": "有 GPS 位置(点按可在地图上显示)", + "Has a companion JPEG (click to open the Info panel)": "有伴随 JPEG(点击打开信息面板)", "Headline metadata": "元数据中的主标题", "Headroom": "余量", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "修复面部皮肤上细小的暗点或红点;眼睛、眉毛、鼻孔和嘴唇保持不变", @@ -1446,7 +1461,7 @@ "Hide {app}": "隐藏 {app}", "High Range": "高范围", "High quality adjustment previews": "高质量调整预览", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "置信度越高,误检的人脸越少,但可能漏掉真实人脸。适用于今后的检测;重新扫描以更新现有检测结果。", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "置信度越高,误检的面孔越少,但可能漏掉真实面孔。只影响以后的检测;重新扫描可更新已有检测。", "Highlight Hue": "高光色相", "Highlight Luminance": "高光明亮度", "Highlight Reconstruction": "高光重建", @@ -1545,6 +1560,7 @@ "Import Mask Effects": "导入蒙版效果", "Import Metadata Presets": "导入元数据预设", "Import New Shots": "导入新拍摄的照片", + "Import Order": "导入顺序", "Import People": "导入人物", "Import People from Immich": "从 Immich 导入人物", "Import Photos and Video…": "导入照片和视频…", @@ -1635,6 +1651,7 @@ "Install from Plug-in Marketplace": "从插件市场安装", "Install the Surface Plugin": "安装 Surface 插件", "Installed": "已安装", + "Installed editors…": "已安装的编辑器…", "Installed in": "安装位置", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "安装并不授予其中任何权限:插件首次需要某项权限时会询问你。", "Install…": "安装…", @@ -1720,6 +1737,7 @@ "Large Landscape (13 × 11 in)": "大号横向 (13 × 11 in)", "Large and Small": "一大一小", "Large image size": "大图尺寸", + "Largest Face": "最大的人脸", "Last Photo": "最后一张照片", "Last backup:": "上次备份:", "Last checked 1 hour ago": "上次检查:1 小时前", @@ -1732,6 +1750,7 @@ "Last synced on {}": "上次同步:{}", "Last synced {} h ago": "上次同步:{} 小时前", "Last synced {} min ago": "上次同步:{} 分钟前", + "Launch Options": "启动选项", "Layout": "布局", "Layout Image Matte": "布局图像衬底", "Layout Image Off": "版面图像:关", @@ -2046,6 +2065,7 @@ "New Template Folder": "新建模板文件夹", "New Web Template Folder": "新建网页模板文件夹", "New collections": "新集合", + "New editor": "新编辑器", "New group (press Return)": "新建分组(按 Return)", "New group name": "新分组名称", "New group:": "新建分组:", @@ -2057,6 +2077,7 @@ "New red eye correction (Return adds it here)": "新建红眼校正(按 Return 在此添加)", "New shots:": "新拍摄:", "New spot (Return adds it here)": "新建污点(按 Return 在此添加)", + "Newest First": "从新到旧", "Next Filmstrip Background": "下一个胶片栏背景", "Next Frame": "下一帧", "Next History Step": "下一个历史记录步骤", @@ -2218,6 +2239,7 @@ "Offset Hue": "Offset 色相", "Offset Luminance": "Offset 明亮度", "Offset Saturation": "Offset 饱和度", + "Oldest First": "从旧到新", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "对于扫描的底片或正片:查找并修复胶片上的灰尘、毛发和划痕。扫描仪的红外通道(VueScan 或 SilverFast 的 RGBI 文件)给出它们的位置;否则在图像的平滑区域中查找", "On photo": "在照片上", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "在拥有收藏夹的设备上选择其他设备可获得的内容;在其他设备上选择此设备获取的内容。", @@ -2288,6 +2310,7 @@ "Optimize catalog after backing up": "备份后优化目录", "Optional: where downloads go": "可选:下载文件存放位置", "Orientation Detection Status": "方向检测状态", + "Original (+XMP)": "原始文件 (+XMP)", "Original Photo": "原始照片", "Other": "其他", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "这样其他应用也能看到你的评分、关键字和编辑。每张照片旁会写入一个小文件。", @@ -2370,6 +2393,7 @@ "Permissions": "权限", "Permissions:": "权限:", "Persistent": "常驻", + "Person Sort": "人物排序", "Personalize {app} with your own branding elements.": "用您自己的品牌元素个性化 {app}。", "Personalized": "个性化", "Phone": "电话", @@ -2386,6 +2410,7 @@ "Photo with Side Text": "照片带侧边文本", "Photo with Title": "照片带标题", "Photo zoom": "照片缩放", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "照片 → 在其他应用中编辑 在此列出每个编辑器。前两个是内置的;可以随意添加,点击一行即可更改它接收的文件。", "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.": "照片 → 在其他应用中编辑 → 在 PhotoCraft 中编辑(⇧⌘E,或右键单击照片)会渲染一份包含你编辑内容的副本,将其与原图堆叠,并在 PhotoCraft 中打开。在那里保存后,此处的副本会随之更新。使用 PSD 格式时,PhotoCraft 会直接保存回该副本。除非你使用便携版,否则请将位置留空。", "PhotoCraft": "PhotoCraft", "Photograph Information": "摄影信息", @@ -3347,6 +3372,7 @@ "Text Page": "文本页", "Text Style Preset": "文本样式预设", "Text size": "文字大小", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "此 RAW 文件旁边的 JPEG 与它保存在一起:不是单独的照片。", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "配置文件管理器列出所有风格、LUT 配置文件和相机配置文件:可将其从菜单中隐藏、重命名和分组、导入新的配置文件,以及删除你自己的配置文件。", "The account has no PIN or password, so there is nothing to unlock.": "账户没有设置 PIN 或密码,因此没有可解锁的内容。", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "当前照片拍摄于其地理标记位置(或地图中心):将其与轨迹对齐", @@ -3560,6 +3586,7 @@ "Tracklog": "轨迹记录", "Transform": "变换", "Trash renders taken out of a collection": "将移出收藏集的渲染副本移到废纸篓", + "Treat JPEGs next to raw files as companions": "将 RAW 文件旁边的 JPEG 视为伴随文件", "Trim": "修剪", "Trim End": "剪辑终点", "Trim Start": "剪辑起点", @@ -3649,6 +3676,7 @@ "Update to Current Process": "更新到当前处理版本", "Update to Current Process Version": "更新到当前处理版本", "Update with Current Settings…": "用当前设置更新…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "更新已关闭(已设置 {env}_DISABLE_UPDATES);更新由软件包管理器负责。", "Updates the installed version": "更新已安装的版本", "Updates…": "更新…", "Updating the DNG previews stopped unexpectedly": "更新 DNG 预览意外停止", @@ -3778,6 +3806,7 @@ "Wrong passphrase.": "口令错误。", "Wrote {} XMP sidecars": "已写入 {} 个 XMP 附属文件", "X": "X", + "XMP Sidecar": "XMP 边车文件", "XMP Sidecars": "XMP 附属文件", "Y": "Y", "Yellow Label": "黄色标签", @@ -3811,10 +3840,13 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "向 `{cli} --library` 传入图库自身的文件(`catalog.snap`)时,会打开其所在文件夹,而不是失败并显示", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import `(以及接受文件夹的 MCP 工具)现在会识别 HEIC、HEIF 和尼康 NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` 也会在 stderr 上记录警告(issue #168);`{env}_LOG` 或 `RUST_LOG` 可选择其他级别。", + "a copy of the original": "原始文件的副本", + "a copy of the original, with an XMP sidecar": "原始文件的副本,附 XMP 边车文件", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "磁盘已满)不再被视为已生成,“生成智能预览”会替换它。", "a photo matches any group": "照片匹配任一组", "a photo matches every group": "照片匹配每个组", "a word per topic; every word must match": "每个话题一个词;所有词都必须匹配", + "adds an editor; click its row to name it and choose its program and file": "添加一行;点击它为编辑器命名并选择程序与文件", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "之后(issue #101):部分写入会在 {app} 重试前被截断,因此下次启动会重放每一个", "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.": "在图库原件中不再在该路径无内容时扫描整个图库。", @@ -3961,6 +3993,7 @@ "renders and screenshots are still written to a temp file and renamed into place, but no longer forced to disk": "渲染和截图仍会先写入临时文件再重命名到位,但不再强制刷新到磁盘", "role": "角色", "save goes through.": "保存会完成。", + "scene-linear Rec. 2020": "场景线性 Rec. 2020", "selected photos": "所选照片", "shots": "张", "siblings) no longer open bright green (issue #148): their as-shot white balance and black level are read from the": "同系列机型)不再呈亮绿色(issue #148):其拍摄时白平衡和黑电平从", @@ -3978,14 +4011,19 @@ "the Local folder tree and Auto Import read the disk on worker threads too. The import progress window has Cancel.": "“本地”文件夹树和自动导入也在工作线程中读取磁盘。导入进度窗口有“取消”按钮。", "the Photo menu and the photo context menu) picks up the full-size preview and fills in the camera metadata they": "照片菜单和照片上下文菜单中)会获取全尺寸预览并补全之前", "the active photo isn't a video": "当前照片不是视频", + "the arguments before the file; `{file}` places the file's path where it stands": "文件之前传入的参数;`{file}` 表示文件路径所在位置", "the camera roll could not be read": "无法读取相机胶卷", "the camera; mapped-out sensor defects are filled in. `.rwl` and `.raw` files are imported too. Photos already": "相机;映射出的传感器坏点会被填补。`.rwl` 和 `.raw` 文件也会被导入。已", + "the file's own": "沿用文件", "the folder shown": "显示的文件夹", "the folder shown (no folder is: pick one first)": "显示的文件夹(当前没有:请先选择一个)", "the frames could not be matched to each other": "无法将各帧相互对应起来", "the measured positions were less reliable than the camera's own pattern": "测得的位置不如相机自身的图案可靠", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "系统对这种文件类型的默认应用程序:用默认编辑器编辑会渲染副本并交给它", + "the original, with an XMP sidecar": "原始文件,附 XMP 边车文件", "the photos in view": "视图中的照片", "the plug-in worker stopped unexpectedly": "插件工作线程意外停止", + "the raw data's own": "沿用 RAW 数据", "the same name and \"Overwrite\" (or Export with Previous repeating it), an exact output path from the control": "同名且选择“覆盖”(或用“按上次设置导出”重复),来自控制", "the selected photos": "选中的照片", "the whole catalog": "整个目录", @@ -4015,6 +4053,7 @@ "whether originals are there is checked on a worker thread (grid thumbnails, the Info panel, the photo menu, Missing": "原件是否存在会在工作线程中检查(网格缩略图、信息面板、照片菜单、缺失", "width": "宽度", "with a counterpart here come along, the rest is listed.": "在此处有对应项的会一并导入,其余的会列出。", + "write the edits beside the file": "把编辑内容写在文件旁边", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "由更新版本 {app} 写入的图库会被拒绝,提示“此图库由更新版本的 {app} 写入”,并保持", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "由更新版本的 {app} 写入),{app} 会说明情况和原因,并提供“重试”“选择其他图库…”“继续", "{app}": "{app}", diff --git a/crates/ui-egui/locales/fork/zh-hant-formats.json b/crates/ui-egui/locales/fork/zh-hant-formats.json index 7c52fd18ac..cea46181e8 100644 --- a/crates/ui-egui/locales/fork/zh-hant-formats.json +++ b/crates/ui-egui/locales/fork/zh-hant-formats.json @@ -123,6 +123,7 @@ "Its manifest has values this version can't use, which it leaves out: {values}": "其資訊清單包含此版本無法使用並省略的值:{values}", "JPEG quality {q} to fit the size limit": "為符合大小限制,JPEG 品質為 {q}", "JPEG quality {q} to fit the size limit (a smaller size or a larger limit keeps more quality)": "為符合大小限制,JPEG 品質為 {q}(縮小尺寸或放寬限制可保留更多品質)", + "Kept with {raw} as its companion: not a photo of its own.": "與 {raw} 一起作為伴隨檔案保留:不是單獨的照片。", "Kept. Groups left: {left}": "已保留。剩餘組數:{left}", "Last checked {n} hours ago": "上次檢查:{n} 小時前", "Last checked {n} minutes ago": "上次檢查:{n} 分鐘前", @@ -336,6 +337,7 @@ "{} keys": "{} 按鍵", "{} of {} from {host}": "{}/{},來自 {host}", "{} · {}. Kept in the catalog's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}。保存在目錄的「denoise」資料夾中;達到上限時,會先刪除沒有相片使用的最舊影像。", + "· {companions} kept with their RAWs": "· {companions} 與其 RAW 保存在一起", "“{name}” added to Camera Profiles": "已將「{name}」加入相機描述檔", "“{name}” has its old settings again": "「{name}」已恢復原來的設定", "“{name}” is new. What may the other devices syncing this catalog have of it?": "「{name}」是新的。同步此目錄的其他裝置可以取得它的哪些內容?", diff --git a/crates/ui-egui/locales/fork/zh-hant.json b/crates/ui-egui/locales/fork/zh-hant.json index e077a9d66d..c59496d141 100644 --- a/crates/ui-egui/locales/fork/zh-hant.json +++ b/crates/ui-egui/locales/fork/zh-hant.json @@ -45,6 +45,7 @@ "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,除非", "8 bits/component": "8 位元/色版", ": {accepted} accepted, {pending} to review, {rejected} rejected": ": {accepted} 合格、{pending} 待複核、{rejected} 不合格", + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.": "與旁邊 RAW 檔案同名的 JPEG 是它的伴隨檔案:一張照片、一次人臉掃描、一組中繼資料。要單獨匯入 JPEG,請取消勾選伴隨檔案選項。", "A backup of the catalog is due. Back it up now, before {app} quits?": "目錄備份已到期。要在 {app} 結束前立即備份嗎?", "A card, a drive or a folder": "記憶卡、磁碟機或資料夾", "A catalog is a folder: its photos' records, settings and history. The photos themselves stay where they are.": "目錄是一個資料夾:包含照片的記錄、設定和步驟記錄。照片本身保留在原處。", @@ -108,6 +109,7 @@ "Add Blank": "新增空白頁", "Add Cell": "新增儲存格", "Add Column": "新增欄", + "Add Editor": "新增編輯器", "Add Face Model…": "新增人臉模型…", "Add Face Region": "新增臉部框", "Add Filter…": "新增濾鏡…", @@ -261,6 +263,7 @@ "Assign to Someone Else…": "指派給其他人…", "Assign to…": "指派給…", "At Import": "匯入時", + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.": "匯入時,與旁邊 RAW 檔案同名的 JPEG 不是單獨的照片,而是該 RAW 的伴隨檔案:一張縮圖、一次人臉掃描、一組中繼資料。複製、移動或重新命名 RAW 時,它會一同跟隨。", "At launch": "啟動時", "At most one request per second.": "每秒最多一次請求。", "Attribution (shown on the map)": "署名(顯示在地圖上)", @@ -323,6 +326,7 @@ "Below the first break stays 0★; the defaults are 20, 40, 55, 70 and 85.": "低於第一個門檻仍為 0★;預設值為 20、40、55、70 和 85。", "Between the two, a photo keeps its flag (unflagged stays unflagged).": "介於兩者之間時,相片保留原有標記(未標記的仍不標記)。", "Bit Depth": "位元深度", + "Bit Level": "位元深度", "Black": "黑色", "Black Point Compensation": "黑點補償", "Blank": "空白", @@ -372,7 +376,9 @@ "Browser version (experimental), keeping a library safe (issue #107): File ▸ Back Up Library… downloads the catalog": "瀏覽器版(實驗性),保護照片庫安全(issue #107):“檔案 → 備份照片庫…”會下載目錄", "Brush (Return puts it down and paints, the arrows paint while it is down)": "筆刷(Return 放下並繪製,放下時方向鍵繪製)", "Brush Refinement": "筆刷調整", + "Build Face Thumbnails": "建立人臉縮圖", "Build at import": "匯入時產生", + "Building face thumbnails": "正在建立人臉縮圖", "Building the profile…": "正在建立描述檔…", "Built in the background once the photos are in, from the one on screen outward.": "照片匯入後在背景建立,從畫面上的那張開始。", "Built-in": "內建", @@ -540,6 +546,7 @@ "Choose folder later": "稍後選擇資料夾", "Choose how the app looks. Each change shows at once; Settings ▸ Interface has more.": "選擇應用程式的外觀。每項變更立即生效;更多選項在「設定 → 介面」中。", "Choose in Sync…": "在同步中選擇…", + "Choose the Editor's Program": "選擇編輯器的程式", "Choose the catalog to open.": "選擇要開啟的目錄。", "Choose where to import from": "選擇匯入來源", "Circle": "圓形", @@ -638,6 +645,7 @@ "Color to Replace": "要取代的顏色", "Color wheel": "色輪", "Colour Profile": "色彩描述檔", + "Colour Space": "色彩空間", "Colour space of the TIFF": "TIFF 的色彩空間", "Colour-label filter with several labels at once; expandable folder tree in Local.": "可同時按多個顏色標籤篩選;“本地”中的資料夾樹可展開。", "Colour-range masks: click the photo to sample. Luminance ranges: range bar, smoothness, luminance map.": "顏色範圍遮色片:點擊照片取樣。明亮度範圍:範圍條、平滑度、明亮度映射。", @@ -653,6 +661,8 @@ "Compact Cells": "緊湊儲存格", "Compact Layout": "精簡版面", "Compact – Dense": "精簡 – 密集", + "Companion": "伴隨檔案", + "Companion JPEG:": "伴隨 JPEG:", "Compare Group in Survey": "在總覽中比較此組", "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.": "Comparing the faces in your photos with the people you have named; what looks like them appears here as it is found.", "Complete": "已完成", @@ -1019,13 +1029,16 @@ "Edit at History Step": "在歷史步驟中編輯", "Edit date": "編輯日期", "Edit in (one item)": "在外部編輯(一個項目)", + "Edit in Default Editor": "以預設編輯器編輯", "Edit in External Editor (⇧⌘E): a 16-bit TIFF copy, stacked, refreshed when you come back.": "在外部編輯器中編輯(⇧⌘E):16 位 TIFF 副本,自動堆疊,返回時刷新。", "Edit in HDR: highlights above SDR white, for HDR exports and displays": "以 HDR 編輯:高於 SDR 白色的亮部,適用於 HDR 匯出和顯示器", "Edit in Other Editor": "在其他編輯器中編輯", "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "「在其他編輯器中編輯」(⌥⌘E)會在此應用程式中開啟副本(macOS 上為應用程式名稱,其他平台為程式路徑)。", + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.": "以其他編輯器編輯 (⌥⌘E) 會在該應用程式開啟副本 (macOS 為應用程式名稱,其他平台為程式路徑)。位置留空時由系統預設應用程式開啟。", "Edit in PhotoCraft": "在 PhotoCraft 中編輯", "Edit this saved location": "編輯此儲存的位置", "Edited Version Saved Again": "編輯版本已再次儲存", + "Editors": "編輯器", "Edit…": "編輯…", "Elsewhere": "在其他位置", "Email": "電子郵件", @@ -1321,6 +1334,7 @@ "Forget Remembered Object": "忘記記住的物件", "Forget This Person": "忘記此人", "Forget a Paired Surface": "忘記已配對的 Surface 裝置", + "Format Options": "格式選項", "Found automatically": "自動找到", "Four with Caption": "四張含說明文字", "Frame": "框架", @@ -1446,6 +1460,7 @@ "Hard Drive": "硬碟", "Hardcover": "精裝", "Has a GPS position (click to show it on the map)": "有 GPS 位置(按一下可在地圖上顯示)", + "Has a companion JPEG (click to open the Info panel)": "有伴隨 JPEG(點擊開啟資訊面板)", "Headline metadata": "中繼資料中的主標題", "Headroom": "動態餘裕", "Heal the small dark or red spots on the faces' skin; eyes, brows, nostrils and lips are left alone": "修復臉部皮膚上細小的暗點或紅點;眼睛、眉毛、鼻孔和嘴唇保持不變", @@ -1473,7 +1488,7 @@ "Hide {app}": "隱藏 {app}", "High Range": "高範圍", "High quality adjustment previews": "高品質調整預覽", - "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "信賴度越高,誤判的人臉越少,但可能漏掉真實人臉。適用於之後的偵測;重新掃描以更新現有偵測結果。", + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.": "信賴度越高,誤偵測的面孔越少,但可能漏掉真實面孔。只影響之後的偵測;重新掃描可更新已有偵測。", "Highlight Hue": "亮部色相", "Highlight Luminance": "亮部明度", "Highlight Reconstruction": "高光重建", @@ -1573,6 +1588,7 @@ "Import Mask Effects": "匯入遮色片效果", "Import Metadata Presets": "匯入中繼資料預設集", "Import New Shots": "匯入新拍攝的照片", + "Import Order": "匯入順序", "Import People": "匯入人物", "Import People from Immich": "從 Immich 匯入人物", "Import Photos and Video…": "匯入照片與影片…", @@ -1667,6 +1683,7 @@ "Install the Surface Plugin": "安裝 Surface 外掛程式", "Install your own ONNX model with denoise-model.json beside it. This build offers no model downloads.": "請自行安裝 ONNX 模型,並在旁邊放置 denoise-model.json。此版本不提供模型下載。", "Installed": "已安裝", + "Installed editors…": "已安裝的編輯器…", "Installed in": "安裝於", "Installing allows none of it: the plug-in asks you the first time it needs each one.": "安裝並不會授予其中任何權限:外掛程式首次需要某項權限時會詢問你。", "Install…": "安裝…", @@ -1753,6 +1770,7 @@ "Large Landscape (13 × 11 in)": "大型橫向 (13 × 11 in)", "Large and Small": "一大一小", "Large image size": "大影像尺寸", + "Largest Face": "最大的人臉", "Last Photo": "最後一張照片", "Last backup:": "上次備份:", "Last checked 1 hour ago": "上次檢查:1 小時前", @@ -1765,6 +1783,7 @@ "Last synced on {}": "上次同步:{}", "Last synced {} h ago": "上次同步:{} 小時前", "Last synced {} min ago": "上次同步:{} 分鐘前", + "Launch Options": "啟動選項", "Layout": "版面", "Layout Image Matte": "版面圖像遮罩", "Layout Image Off": "版面圖像:關", @@ -2082,6 +2101,7 @@ "New Template Folder": "新增範本資料夾", "New Web Template Folder": "新增網頁範本資料夾", "New collections": "新集合", + "New editor": "新編輯器", "New group (press Return)": "新群組(按 Return)", "New group name": "新群組名稱", "New group:": "新群組:", @@ -2093,6 +2113,7 @@ "New red eye correction (Return adds it here)": "新的紅眼校正(按 Return 在此加入)", "New shots:": "新拍攝:", "New spot (Return adds it here)": "新的斑點(按 Return 在此加入)", + "Newest First": "由新到舊", "Next Filmstrip Background": "下一個底片顯示窗格背景", "Next Frame": "下一格", "Next History Step": "下一個歷史步驟", @@ -2255,6 +2276,7 @@ "Offset Hue": "Offset 色相", "Offset Luminance": "Offset 明亮度", "Offset Saturation": "Offset 飽和度", + "Oldest First": "由舊到新", "On a scanned negative or slide: find and heal dust specks, hairs and scratches on the film. A scanner's infrared pass (a VueScan or SilverFast RGBI file) says where they are; otherwise the picture's smooth areas are searched": "對於掃描的負片或正片:尋找並修復底片上的灰塵、毛髮與刮痕。掃描器的紅外線通道(VueScan 或 SilverFast 的 RGBI 檔案)指出它們的位置;否則在影像的平滑區域中搜尋", "On photo": "在照片上", "On the device that owns a collection, choose what the others may have; on the others, choose what this device takes.": "在擁有收藏集的裝置上選擇其他裝置可取得的內容;在其他裝置上選擇此裝置取得的內容。", @@ -2329,6 +2351,7 @@ "Optimize catalog after backing up": "備份後最佳化目錄", "Optional: where downloads go": "選用:下載檔案存放位置", "Orientation Detection Status": "方向偵測狀態", + "Original (+XMP)": "原始檔 (+XMP)", "Original Photo": "原始照片", "Other": "其他", "Other apps then see your ratings, keywords and edits. It writes a small file next to each photo.": "這樣其他應用程式也能看到你的評分、關鍵字和編輯。每張照片旁會寫入一個小檔案。", @@ -2411,6 +2434,7 @@ "Permissions": "權限", "Permissions:": "權限:", "Persistent": "常駐", + "Person Sort": "人物排序", "Personalize {app} with your own branding elements.": "用您自己的品牌元素個人化 {app}。", "Personalized": "個人化", "Phone": "電話", @@ -2427,6 +2451,7 @@ "Photo with Side Text": "相片含側邊文字", "Photo with Title": "相片含標題", "Photo zoom": "照片縮放", + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.": "照片 → 在其他應用程式中編輯 在此列出每個編輯器。前兩個是內建的;可隨意新增,點擊一列即可更改它接收的檔案。", "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.": "照片 → 在其他應用程式中編輯 → 在 PhotoCraft 中編輯(⇧⌘E,或在照片上按右鍵)會算繪一份含有您編輯內容的副本,將其與原始檔堆疊,並在 PhotoCraft 中開啟。在那裡儲存後,這裡的副本就會更新。若為 PSD,PhotoCraft 會直接存回該檔案。除非您使用可攜式版本,否則請將位置留空。", "PhotoCraft": "PhotoCraft", "Photograph Information": "攝影資訊", @@ -3395,6 +3420,7 @@ "Text Page": "文字頁", "Text Style Preset": "文字樣式預設集", "Text size": "文字大小", + "The JPEG beside this raw's file, kept with it: not a photo of its own.": "此 RAW 檔案旁的 JPEG 與它保存在一起:不是單獨的照片。", "The Profile Manager lists every look, LUT profile and camera profile: hide them from the menus, rename and group them, import new ones, and delete your own.": "描述檔管理員會列出所有風格、LUT 描述檔和相機描述檔:可將它們從選單中隱藏、重新命名和分組、匯入新的描述檔,以及刪除您自己的描述檔。", "The account has no PIN or password, so there is nothing to unlock.": "帳號未設定 PIN 或密碼,因此沒有可解鎖的內容。", "The active photo was taken where it is geotagged (or at the map's centre): match it to the track": "作用中照片拍攝於其地理標記位置(或地圖中央):將其與軌跡對齊", @@ -3616,6 +3642,7 @@ "Tracklog": "軌跡記錄", "Transform": "變形", "Trash renders taken out of a collection": "將移出收藏集的算繪副本移到垃圾桶", + "Treat JPEGs next to raw files as companions": "將 RAW 檔案旁的 JPEG 視為伴隨檔案", "Trim": "修剪", "Trim End": "剪輯終點", "Trim Start": "剪輯起點", @@ -3709,6 +3736,7 @@ "Update to Current Process": "更新至目前處理版本", "Update to Current Process Version": "更新至目前處理版本", "Update with Current Settings…": "以目前設定更新…", + "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates.": "更新已關閉(已設定 {env}_DISABLE_UPDATES);更新由套件管理員負責。", "Updates the installed version": "更新已安裝的版本", "Updates…": "更新…", "Updating the DNG previews stopped unexpectedly": "更新 DNG 預覽意外停止", @@ -3840,6 +3868,7 @@ "Wrong passphrase.": "密語錯誤。", "Wrote {} XMP sidecars": "已寫入 {} 個 XMP 附屬檔案", "X": "X", + "XMP Sidecar": "XMP 邊車檔案", "XMP Sidecars": "XMP 附屬檔案", "Y": "Y", "Yellow Label": "黃色標籤", @@ -3873,10 +3902,13 @@ "`{cli} --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`{cli} --library` 若指定照片庫本身的檔案(`catalog.snap`),現在會開啟其資料夾,而不是失敗並顯示", "`{cli} run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`{cli} run --import `(以及接受資料夾的 MCP 工具)現在會納入 HEIC、HEIF 和 Nikon NRW", "`{cli}` logs warnings on stderr too (issue #168); `{env}_LOG` or `RUST_LOG` picks another level.": "`{cli}` 也會在 stderr 記錄警告(issue #168);`{env}_LOG` 或 `RUST_LOG` 可選擇其他層級。", + "a copy of the original": "原始檔的副本", + "a copy of the original, with an XMP sidecar": "原始檔的副本,附 XMP 邊車檔案", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "磁碟已滿)不再被視為已生成,“生成智能預覽”會替換它。", "a photo matches any group": "相片符合任一群組", "a photo matches every group": "相片符合每個群組", "a word per topic; every word must match": "每個話題一個詞;所有詞都必須符合", + "adds an editor; click its row to name it and choose its program and file": "新增一列;點擊它為編輯器命名並選擇程式與檔案", "afterwards (issue #101): the partial write is cut off before {app} retries, so the next launch replays every": "之後(issue #101):部分寫入會在 {app} 重試前被截斷,因此下次啟動會重放每一個", "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.": "在照片庫原件中不再在該路徑無內容時掃描整個照片庫。", @@ -4035,6 +4067,7 @@ "renders and screenshots are still written to a temp file and renamed into place, but no longer forced to disk": "算繪和截圖仍會先寫入臨時檔案再重新命名到位,但不再強制刷新到磁碟", "role": "角色", "save goes through.": "保存會完成。", + "scene-linear Rec. 2020": "場景線性 Rec. 2020", "selected photos": "所選照片", "shots": "張", "siblings) no longer open bright green (issue #148): their as-shot white balance and black level are read from the": "同系列機型)不再呈亮綠色(issue #148):其拍攝時白平衡和黑電平從", @@ -4054,16 +4087,21 @@ "the Local folder tree and Auto Import read the disk on worker threads too. The import progress window has Cancel.": "“本地”資料夾樹和自動匯入也在工作執行緒中讀取磁碟。匯入進度窗口有“取消”按鈕。", "the Photo menu and the photo context menu) picks up the full-size preview and fills in the camera metadata they": "照片選單和照片上下文選單中)會獲取全尺寸預覽並補全之前", "the active photo isn't a video": "目前相片不是視訊", + "the arguments before the file; `{file}` places the file's path where it stands": "檔案之前傳入的參數;`{file}` 表示檔案路徑所在位置", "the camera roll could not be read": "無法讀取相機膠卷", "the camera; mapped-out sensor defects are filled in. `.rwl` and `.raw` files are imported too. Photos already": "相機;映射出的傳感器壞點會被填補。`.rwl` 和 `.raw` 檔案也會被匯入。已", + "the file's own": "沿用檔案", "the folder shown": "顯示的檔案夾", "the folder shown (no folder is: pick one first)": "顯示的檔案夾(目前沒有:請先選擇一個)", "the frames could not be matched to each other": "無法將各影格相互對應", "the graphics card": "顯示卡", "the graphics card is not used": "未使用顯示卡", "the measured positions were less reliable than the camera's own pattern": "測得的位置不如相機本身的圖樣可靠", + "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over": "系統對這種檔案類型的預設應用程式:以預設編輯器編輯會渲染副本並交給它", + "the original, with an XMP sidecar": "原始檔,附 XMP 邊車檔案", "the photos in view": "檢視中的相片", "the plug-in worker stopped unexpectedly": "外掛程式工作執行緒意外停止", + "the raw data's own": "沿用 RAW 資料", "the same name and \"Overwrite\" (or Export with Previous repeating it), an exact output path from the control": "同名且選擇“覆蓋”(或用“按上次設定匯出”重復),來自控制", "the selected photos": "選取的相片", "the whole catalog": "整個目錄", @@ -4093,6 +4131,7 @@ "whether originals are there is checked on a worker thread (grid thumbnails, the Info panel, the photo menu, Missing": "原件是否存在會在工作執行緒中檢查(格線縮略圖、資訊面板、照片選單、遺失", "width": "寬度", "with a counterpart here come along, the rest is listed.": "在此處有對應項的會一並匯入,其餘的會列出。", + "write the edits beside the file": "把編輯內容寫在檔案旁邊", "written by a newer {app} is refused with \"this library was written by a newer version of {app}\" and left": "由更新版本 {app} 寫入的照片庫會被拒絕,提示“此照片庫由更新版本的 {app} 寫入”,並保持", "written by a newer {app}), {app} says so and why, and offers Try Again, Choose Another Library…, Continue": "由更新版本的 {app} 寫入),{app} 會說明情況和原因,並提供“重試”“選擇其他照片庫…”“繼續", "{app}": "{app}", diff --git a/crates/ui-egui/src/advanced_search.rs b/crates/ui-egui/src/advanced_search.rs index 713e0b9a64..e5f5859962 100644 --- a/crates/ui-egui/src/advanced_search.rs +++ b/crates/ui-egui/src/advanced_search.rs @@ -5,6 +5,7 @@ //! a refused query (a typo in a number, an unsupported condition) is an error toast, never a //! crash and never a silently empty grid. +use crate::popup_typeahead::PopupItems; use egui::RichText; use crate::dialog_frame; @@ -365,7 +366,7 @@ fn match_row(ui: &mut egui::Ui, id: &str, value: &mut lcc_catalog::advanced_sear dialog_frame::form_row(ui, tr("Find items that"), |ui| { egui::ComboBox::from_id_salt(id).width(300.0).selected_text(tr(label(*value))).show_ui(ui, |ui| { for m in SearchMatch::ALL { - let r = ui.selectable_value(value, m, tr(label(m))); + let r = ui.pick_value(value, m, tr(label(m))); crate::widgets::register(ui.ctx(), format!("{id}:{m:?}"), r.rect); } }); @@ -434,9 +435,9 @@ fn number_choice(ui: &mut egui::Ui, id: &str, label: &str, value: &mut Option, .unwrap_or_else(|| options.first().map(|(_, l)| tr(l)).unwrap_or("")); egui::ComboBox::from_id_salt(id).width(180.0).selected_text(shown).show_ui(ui, |ui| { for (k, l) in options { - ui.selectable_value(value, k.map(str::to_string), tr(l)); + ui.pick_value(value, k.map(str::to_string), tr(l)); } }); }); @@ -477,9 +478,9 @@ fn album_row(ui: &mut egui::Ui, album: &mut Option, app: &LccApp, sfx: &str let shown = album.and_then(|id| albums.iter().find(|(_, a)| *a == id).map(|(n, _)| n.clone())).unwrap_or_else(|| tr("Any collection").to_string()); egui::ComboBox::from_id_salt(format!("field:asAlbum{sfx}")).width(220.0).selected_text(shown).show_ui(ui, |ui| { - ui.selectable_value(album, None, tr("Any collection")); + ui.pick_value(album, None, tr("Any collection")); for (name, id) in &albums { - ui.selectable_value(album, Some(*id), name.clone()); + ui.pick_value(album, Some(*id), name.clone()); } }); }); diff --git a/crates/ui-egui/src/book.rs b/crates/ui-egui/src/book.rs index 06366e45cd..5cf3ab9351 100644 --- a/crates/ui-egui/src/book.rs +++ b/crates/ui-egui/src/book.rs @@ -14,6 +14,7 @@ //! collections holding a layout document) land; `book.save` / `book.open` then move there. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::cell::RefCell; use std::collections::HashMap; use std::sync::Mutex; @@ -1068,7 +1069,7 @@ fn toolbar(ui: &mut egui::Ui, app: &mut LccApp, r: Rect) { ui.horizontal_centered(|ui| { for v in BookView::ALL { let on = app.ui.book.view == v; - let resp = ui.selectable_label(on, crate::i18n::tr(v.label())); + let resp = ui.pick_label(on, crate::i18n::tr(v.label())); register(ui.ctx(), format!("book:view:{}", v.key()), resp.rect); if resp.clicked() { app.ui.book.view = v; @@ -1381,7 +1382,7 @@ fn combo(ui: &mut egui::Ui, salt: &str, label: &str, cur: T } egui::ComboBox::from_id_salt(salt).selected_text(crate::i18n::tr(&name(cur)).to_string()).show_ui(ui, |ui| { for v in all { - if ui.selectable_label(*v == cur, crate::i18n::tr(&name(*v))).clicked() && *v != cur { + if ui.pick_label(*v == cur, crate::i18n::tr(&name(*v))).clicked() && *v != cur { out = Some(*v); } } @@ -1490,7 +1491,7 @@ fn auto_panel(ui: &mut egui::Ui, app: &mut LccApp) { ui.label(crate::i18n::tr("Preset")); egui::ComboBox::from_id_salt("book-preset").selected_text(crate::i18n::tr(&app.ui.book.preset).to_string()).width(170.0).show_ui(ui, |ui| { for n in &names { - if ui.selectable_label(*n == app.ui.book.preset, crate::i18n::tr(n)).clicked() { + if ui.pick_label(*n == app.ui.book.preset, crate::i18n::tr(n)).clicked() { app.ui.book.preset = n.clone(); } } @@ -1740,12 +1741,12 @@ fn type_panel(ui: &mut egui::Ui, app: &mut LccApp) { ui.label(crate::i18n::tr("Text Style Preset")); egui::ComboBox::from_id_salt("book-tpreset").selected_text("…").show_ui(ui, |ui| { for n in &presets { - if ui.selectable_label(false, n).clicked() { + if ui.pick_label(false, n).clicked() { op(app, &ctx, "book.type", json!({"target": target, "preset": n})); } } ui.separator(); - if ui.selectable_label(false, crate::i18n::tr("Save Current Settings as New Preset")).clicked() { + if ui.pick_label(false, crate::i18n::tr("Save Current Settings as New Preset")).clicked() { let name = crate::i18n::tr_format!("Style {n}", n = app.ui.book.book.text_presets.len() + 1); op(app, &ctx, "book.textPreset", json!({"name": name, "style": s})); } @@ -1756,11 +1757,11 @@ fn type_panel(ui: &mut egui::Ui, app: &mut LccApp) { ui.horizontal(|ui| { ui.label(crate::i18n::tr("Font")); egui::ComboBox::from_id_salt("book-font").selected_text(font_label).width(170.0).height(300.0).show_ui(ui, |ui| { - if ui.selectable_label(s.font.is_empty(), crate::i18n::tr("Inter (default)")).clicked() { + if ui.pick_label(s.font.is_empty(), crate::i18n::tr("Inter (default)")).clicked() { set(app, json!({"font": ""})); } for f in &families { - if ui.selectable_label(*f == s.font, f).clicked() { + if ui.pick_label(*f == s.font, f).clicked() { set(app, json!({"font": f})); } } @@ -1841,13 +1842,13 @@ fn type_panel(ui: &mut egui::Ui, app: &mut LccApp) { for (a, l) in [(lcc_book::HAlign::Left, "⇤"), (lcc_book::HAlign::Center, "↔"), (lcc_book::HAlign::Right, "⇥"), (lcc_book::HAlign::Justify, "☰")] { - if ui.selectable_label(s.align == a, l).on_hover_text(crate::i18n::tr(&format!("{a:?}")).to_string()).clicked() { + if ui.pick_label(s.align == a, l).on_hover_text(crate::i18n::tr(&format!("{a:?}")).to_string()).clicked() { set(app, json!({"align": enum_key(a)})); } } ui.separator(); for (a, l) in [(lcc_book::VAlign::Top, "⤒"), (lcc_book::VAlign::Middle, "↕"), (lcc_book::VAlign::Bottom, "⤓")] { - if ui.selectable_label(s.valign == a, l).on_hover_text(crate::i18n::tr(&format!("{a:?}")).to_string()).clicked() { + if ui.pick_label(s.valign == a, l).on_hover_text(crate::i18n::tr(&format!("{a:?}")).to_string()).clicked() { set(app, json!({"valign": enum_key(a)})); } } diff --git a/crates/ui-egui/src/catalog_ui.rs b/crates/ui-egui/src/catalog_ui.rs index 4e73386f4c..d12097050a 100644 --- a/crates/ui-egui/src/catalog_ui.rs +++ b/crates/ui-egui/src/catalog_ui.rs @@ -13,6 +13,7 @@ //! this module only holds the dialogs and the UI commands that switch libraries. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::path::{Path, PathBuf}; use lcc_catalog::library::RecentCatalogs; @@ -590,7 +591,7 @@ fn welcome_ui( .filter(|p| lcc_catalog::library::resolve(p).is_ok_and(|d| lcc_catalog::library::foreign_format(&d).is_none())) .collect(); for (i, p) in recent.iter().enumerate() { - let r = ui.selectable_label(false, display_name(p)); + let r = ui.pick_label(false, display_name(p)); crate::widgets::register(ui.ctx(), format!("item:welcomeRecent{i}"), r.rect); if r.clicked() { *action = Some(("catalog.openRecent".into(), json!({"path": p, "checkAtStartup": *updates}))); @@ -686,7 +687,7 @@ fn combo(ui: &mut egui::Ui, id: &str, label: &str, value: &mut Value, options: & let shown = options.iter().find(|(k, _)| *k == cur).map_or(cur.as_str(), |(_, l)| l); let r = egui::ComboBox::from_id_salt(id).selected_text(crate::i18n::tr(shown)).width(220.0).show_ui(ui, |ui| { for (k, l) in options { - if ui.selectable_label(cur == *k, crate::i18n::tr(l)).clicked() { + if ui.pick_label(cur == *k, crate::i18n::tr(l)).clicked() { *value = json!(k); } } @@ -710,6 +711,18 @@ fn settings_ui(app: &mut LccApp, ui: &mut egui::Ui, s: &mut Value, action: &mut crate::widgets::register(ui.ctx(), widget, r.rect); s[key] = json!(b); } + ui.separator(); + ui.label(egui::RichText::new(crate::i18n::tr("Library")).strong()); + { + let mut b = s["rawJpegCompanions"].as_bool().unwrap_or(true); + let r = ui + .checkbox(&mut b, crate::i18n::tr("Treat JPEGs next to raw files as companions")) + .on_hover_text(crate::i18n::tr( + "At import, a JPEG with a raw's name beside it is not a photo of its own but the raw's companion: one thumbnail, one face scan, one set of metadata. It travels with the raw when copied, moved or renamed.", + )); + crate::widgets::register(ui.ctx(), "check:catalogCompanions", r.rect); + s["rawJpegCompanions"] = json!(b); + } if let Some(last) = s["lastBackup"].as_i64() { let when = lcc_catalog::dates::local(last).unwrap_or_else(|| lcc_catalog::dates::civil(last)); let when = when.get(..19).unwrap_or(&when).replace('T', " "); @@ -731,7 +744,7 @@ fn settings_ui(app: &mut LccApp, ui: &mut egui::Ui, s: &mut Value, action: &mut let cur = s.field("previews").field("standardEdge").as_u64().unwrap_or(2048); let r = egui::ComboBox::from_id_salt("catalogEdge").selected_text(format!("{cur} px")).width(220.0).show_ui(ui, |ui| { for e in EDGES { - if ui.selectable_label(cur == *e, format!("{e} px")).clicked() { + if ui.pick_label(cur == *e, format!("{e} px")).clicked() { *s.field_mut("previews").field_mut("standardEdge") = json!(e); } } @@ -750,6 +763,7 @@ fn settings_ui(app: &mut LccApp, ui: &mut egui::Ui, s: &mut Value, action: &mut "catalog.settings".into(), json!({ "backup": s["backup"], "backupDir": s["backupDir"], "testIntegrity": s["testIntegrity"], "optimize": s["optimize"], + "rawJpegCompanions": s["rawJpegCompanions"], "previews": {"standardEdge": p["standardEdge"], "discardFull": p["discardFull"], "atImport": p["atImport"]}, }), )); diff --git a/crates/ui-egui/src/chart_profile.rs b/crates/ui-egui/src/chart_profile.rs index fa0348630f..7bf43072cb 100644 --- a/crates/ui-egui/src/chart_profile.rs +++ b/crates/ui-egui/src/chart_profile.rs @@ -6,6 +6,7 @@ //! with a row in the activity stack ([`crate::tasks::spawn`]); the profile lands among the camera //! profiles through [`lcc_engine::chart_profiling::install`]. +use crate::popup_typeahead::PopupItems; use std::collections::HashMap; use std::sync::Arc; @@ -538,7 +539,7 @@ fn light_combo(ui: &mut egui::Ui, id: &str, value: &mut String) -> bool { } let r = egui::ComboBox::from_id_salt(id).selected_text(light_label(value)).width(220.0).show_ui(ui, |ui| { for (k, _) in LIGHTS { - if ui.selectable_label(value == k, light_label(k)).clicked() && value != k { + if ui.pick_label(value == k, light_label(k)).clicked() && value != k { *value = k.to_string(); changed = true; } diff --git a/crates/ui-egui/src/comments_ui.rs b/crates/ui-egui/src/comments_ui.rs index 94436d18aa..268a7d64c3 100644 --- a/crates/ui-egui/src/comments_ui.rs +++ b/crates/ui-egui/src/comments_ui.rs @@ -4,6 +4,7 @@ //! comments (Hard Drive, SFTP) says so. Fork-owned. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use chrono::DateTime; use egui::{RichText, vec2}; use lcc_engine::cmd::publish::{CommentsReview, comments_job}; @@ -171,7 +172,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { let selected = all.iter().find(|c| Some(c.album) == current).map(|c| c.label.clone()).unwrap_or_default(); let r = egui::ComboBox::from_id_salt("reviewCommentsCollection").selected_text(selected).width(320.0).show_ui(ui, |ui| { for c in &all { - if ui.selectable_label(Some(c.album) == current, &c.label).clicked() { + if ui.pick_label(Some(c.album) == current, &c.label).clicked() { chosen = Some(c.album); } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c9626e24aa..34ac825b1f 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -300,6 +300,49 @@ pub(crate) fn check_gesture_numbers(method: &str, p: &Value) -> Result<(), Strin check(method, "", p) } +/// Most synthetic events that may wait in `app.synthetic` for the frames that drain them. +/// `count` and `steps` bound one request; this bounds a script that sends requests faster than +/// the app takes them, so the queue (and the time it takes to drain) can't grow without end. +/// Room for several of the largest drags (`steps` 1000 = 1003 events). Adapted from upstream #1736. +pub const MAX_PENDING_EVENTS: usize = 4096; + +/// How many synthetic events `method` with `p` queues, and whether it is a lone release (a +/// pointer `up`, a key `up`). Invalid arguments count 0: the method's own branch refuses them. +fn queued_events(method: &str, p: &Value) -> (usize, bool) { + let n = |key: &str, default: u64, range: (u64, u64)| usize::try_from(bounded_arg(p, key, default, range).unwrap_or(0)).unwrap_or(usize::MAX); + match method { + "ui.move" | "ui.hoverWidget" | "ui.text" | "ui.scroll" | "ui.zoom" | "ui.clipboard" => (1, false), + "ui.clickWidget" | "ui.click" => (n("count", 1, CLICK_COUNT).saturating_mul(2).saturating_add(1), false), + "ui.dragWidget" | "ui.drag" => (n("steps", 10, DRAG_STEPS).saturating_add(3), false), + "ui.pointer" => { + let events = p.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + let kind = |e: &Value| e.get("kind").and_then(Value::as_str).unwrap_or("move").to_string(); + let total = events.iter().fold(0usize, |t, e| t.saturating_add(if kind(e) == "down" { 2 } else { 1 })); + (total, events.len() == 1 && events.iter().all(|e| kind(e) == "up")) + } + "ui.key" => match p.get("action").and_then(Value::as_str).unwrap_or("press") { + "press" => (2, false), + "up" => (1, true), + _ => (1, false), + }, + _ => (0, false), + } +} + +/// Refuses a request whose events would take the queue past [`MAX_PENDING_EVENTS`]. A lone +/// release may go one past it, so a held button or key is never left stuck down by a full queue. +fn event_budget(pending: usize, method: &str, p: &Value) -> Result<(), String> { + let (additional, release) = queued_events(method, p); + let cap = if release { MAX_PENDING_EVENTS.saturating_add(1) } else { MAX_PENDING_EVENTS }; + if additional == 0 || pending.saturating_add(additional) <= cap { + Ok(()) + } else { + Err(format!( + "{method}: {pending} synthetic events still pending, {additional} more would pass the limit of {MAX_PENDING_EVENTS}; wait for the app to catch up" + )) + } +} + pub fn handle(app: &mut LccApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { if let Some(o) = crate::surface::handle(app, req) { return o; @@ -312,6 +355,9 @@ pub fn handle(app: &mut LccApp, ctx: &egui::Context, req: &ControlRequest) -> Ou { return err(e); } + if let Err(e) = event_budget(app.synthetic.len(), &req.method, p) { + return err(e); + } let s = |k: &str| p.get(k).and_then(Value::as_str); let f = |k: &str| p.get(k).and_then(Value::as_f64); match req.method.as_str() { @@ -964,6 +1010,37 @@ mod hostile_gesture_tests { app } + /// Adapted from upstream #1736: requests sent faster than frames drain them can't grow the + /// queue past `MAX_PENDING_EVENTS`; a lone release still gets through, once. + #[test] + fn the_synthetic_queue_is_bounded_but_a_release_gets_through() { + let mut app = app(); + app.synthetic = vec![egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); MAX_PENDING_EVENTS - 1]; + for (method, params) in [ + ("ui.click", json!({"x": 1, "y": 1})), + ("ui.drag", json!({"x": 1, "y": 1, "toX": 5, "toY": 5, "steps": 1000})), + ("ui.pointer", json!({"events": [{"kind": "down"}]})), + ("ui.key", json!({"key": "A"})), + ] { + let r = reply(&mut app, method, params); + assert_eq!(r["ok"], false, "{method}: {r}"); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS - 1, "{method} queued past the limit"); + } + let r = reply(&mut app, "ui.scroll", json!({"dy": 1})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS); + assert_eq!(reply(&mut app, "ui.move", json!({"x": 1, "y": 1}))["ok"], false); + let up = json!({"events": [{"kind": "up"}]}); + assert_eq!(reply(&mut app, "ui.pointer", up.clone())["ok"], true, "a lone release goes one past the limit"); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS + 1); + assert_eq!(reply(&mut app, "ui.pointer", up)["ok"], false, "but only one"); + assert_eq!(reply(&mut app, "ui.key", json!({"key": "A", "action": "up"}))["ok"], false); + assert_eq!(app.synthetic.len(), MAX_PENDING_EVENTS + 1); + // once the frames drain the queue, requests are taken again + app.synthetic.clear(); + assert_eq!(reply(&mut app, "ui.drag", json!({"x": 1, "y": 1, "toX": 5, "toY": 5, "steps": 1000}))["ok"], true); + } + #[test] fn invalid_pointer_events_reject_the_whole_batch() { let mut app = app(); diff --git a/crates/ui-egui/src/date_picker.rs b/crates/ui-egui/src/date_picker.rs index 88b2a8fa11..445fd5fb63 100644 --- a/crates/ui-egui/src/date_picker.rs +++ b/crates/ui-egui/src/date_picker.rs @@ -8,6 +8,7 @@ //! `datePickerPrecision::`, `datePickerPrev:`, `datePickerNext:` and //! `datePickerCell::`. +use crate::popup_typeahead::PopupItems; use egui::{Response, RichText, Ui, vec2}; use crate::icons::Icon; @@ -246,10 +247,12 @@ impl<'a> DatePicker<'a> { // as wide as a month of days, however much room the window has ui.set_min_width(220.0); ui.set_max_width(240.0); + // the precision tabs and the days change the calendar in place + crate::popup_typeahead::stays_open(ui); if precisions.len() > 1 { ui.horizontal(|ui| { for p in precisions { - let r = ui.selectable_label(view.precision == *p, crate::i18n::tr(p.label())); + let r = ui.pick_label(view.precision == *p, crate::i18n::tr(p.label())); register(ui.ctx(), format!("datePickerPrecision:{}:{id}", p.id()), r.rect); if r.clicked() { view.precision = *p; diff --git a/crates/ui-egui/src/edit_in.rs b/crates/ui-egui/src/edit_in.rs index 1945665fe3..108d16b7fe 100644 --- a/crates/ui-egui/src/edit_in.rs +++ b/crates/ui-egui/src/edit_in.rs @@ -24,6 +24,7 @@ //! The windows' state is per UI thread (the app has one), so no shared app state is touched. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::cell::RefCell; use std::path::{Path, PathBuf}; @@ -41,8 +42,21 @@ pub const ACTIONS_PANEL: &str = "panel.actions"; /// One item of a saved preset's menu under Photo ▸ Edit In ([`menu_items`]): `{preset, mode?, action?}`. pub const PRESET_COMMAND: &str = "photo.editInPreset"; -const FORMATS: &[&str] = &["tiff", "psd"]; -const SPACES: &[&str] = &["adobeRgb", "proPhoto", "displayP3", "srgb"]; +/// The formats a rendered copy takes, with their labels. A DNG copy keeps a raw's data (a raw +/// only); OpenEXR is scene-linear Rec. 2020, so its colour space and bit depth don't apply. +const FORMATS: &[(&str, &str)] = &[("tiff", "TIFF"), ("psd", "PSD (layered)"), ("png", "PNG"), ("exr", "OpenEXR"), ("dng", "DNG (+XMP)")]; +const SPACES: &[(&str, &str)] = + &[("adobeRgb", "Adobe RGB"), ("proPhoto", "ProPhoto RGB"), ("displayP3", "Display P3"), ("srgb", "sRGB"), ("rec2020", "Rec. 2020")]; +/// The bit-depth labels a format's depths show (see +/// [`lcc_engine::cmd::edit_in::Format::bit_depths`]). +fn depth_label(format: &str, depth: u8) -> &'static str { + match (format, depth) { + ("exr", 16) => "16-bit half float", + (_, 32) => "32-bit float", + (_, 16) => "16-bit", + _ => "8-bit", + } +} const MODES: &[(&str, &str)] = &[ ("copyWithAdjustments", "Edit a Copy with Adjustments"), ("copy", "Edit a Copy"), @@ -68,6 +82,9 @@ pub struct Draft { pub mode: String, pub naming: String, pub stack: bool, + /// A copy-of/original hand-over also writes an XMP sidecar (a raw developer that reads + /// Lightroom-style sidecars). + pub xmp: bool, /// The preset's menu style (see [`MENUS`]). pub menu: String, /// The items of an `actions` menu: their labels, and their arguments separated by spaces. @@ -92,6 +109,7 @@ impl Default for Draft { mode: "copyWithAdjustments".into(), naming: "{name}-Edit".into(), stack: true, + xmp: false, menu: "choices".into(), actions: FIRST_ITEMS.iter().map(|l| ActionDraft { label: (*l).into(), args: String::new() }).collect(), } @@ -99,7 +117,7 @@ impl Default for Draft { } impl Draft { - fn from_preset(p: &Value) -> Self { + pub(crate) fn from_preset(p: &Value) -> Self { let s = |k: &str, d: &str| p[k].as_str().unwrap_or(d).to_string(); Draft { name: s("name", ""), @@ -111,6 +129,7 @@ impl Draft { mode: s("mode", "copyWithAdjustments"), naming: s("naming", "{name}-Edit"), stack: p["stack"].as_bool().unwrap_or(true), + xmp: p["xmp"].as_bool().unwrap_or(false), menu: s("menu", "choices"), actions: p["actions"] .as_array() @@ -140,6 +159,11 @@ impl Draft { "stack": self.stack, "menu": self.menu, }); + if self.xmp + && let Some(o) = v.as_object_mut() + { + o.insert("xmp".into(), json!(true)); + } if self.menu == "actions" && let Some(o) = v.as_object_mut() { @@ -328,6 +352,15 @@ fn run_choice( return crate::menus::edit_in(app, ctx, &json!({}), photocraft); } let tool = editor_for(app, photocraft); + // the command makes the copies before it returns: a missing editor has to say so first, or + // the failure leaves a copy nobody can open behind (issue #1315) + if let Some(check) = app.services.check_editor.as_ref() + && let Err(e) = check(&tool) + { + let e = e.to_string(); + app.toast_error(ctx, crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e)); + return Err(e); + } let mut results = Vec::new(); for id in ids { let mut p = json!({"id": id.0, "mode": mode}); @@ -367,7 +400,29 @@ pub(crate) fn after_command(app: &mut LccApp, id: &str, r: &Value) { } // (a host that can't open files, e.g. tests and headless runs, starts no programs either) if app.services.open_with.is_some() && !tool.is_empty() && (editor::is_photocraft(&tool) || args.iter().any(|a| a == "--wait")) { - start_editor(app, tool, args, label, PathBuf::from(path)); + // `photocraft` names where its installer put it, not a program on the PATH (#1315): + // the host resolves it first. What it can't start as a plain process (the Flatpak) + // goes through the host opener instead — no `--wait` there, the mtime poll sees its + // saves. A host without the lookup starts the name as it is, as before. + let start = match app.services.resolve_editor.as_ref() { + Some(f) => f(&tool), + None => Some(tool.clone()), + }; + match start { + Some(start) => start_editor(app, start, args, label, PathBuf::from(path)), + None => { + if let Some(f) = app.services.open_with.as_mut() + && let Err(e) = f(path, &tool) + { + let now = app.last_time; + app.ui.show_toast(crate::Toast::new( + crate::ToastKind::Error, + crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e), + now, + )); + } + } + } return; } } @@ -587,7 +642,7 @@ fn combo(ui: &mut egui::Ui, id: &str, label: &str, value: &mut String, choices: let shown = choices.iter().find(|(v, _)| v == value).map(|(_, l)| tr(l)).unwrap_or(value.as_str()).to_string(); egui::ComboBox::from_id_salt(id).selected_text(shown).show_ui(ui, |ui| { for (v, l) in choices { - ui.selectable_value(value, v.to_string(), tr(l)); + ui.pick_value(value, v.to_string(), tr(l)); } }); ui.end_row(); @@ -612,7 +667,7 @@ fn presets_window(app: &mut LccApp, ctx: &egui::Context, st: &mut WorkflowUi) { for p in list.as_ref().and_then(|l| l[kind].as_array()).into_iter().flatten() { let name = p["name"].as_str().unwrap_or_default(); let label = if builtin { format!("{name} ({})", tr("built-in")) } else { name.to_string() }; - if ui.selectable_label(st.draft.name == name, label).clicked() { + if ui.pick_label(st.draft.name == name, label).clicked() { st.draft = Draft::from_preset(p); if builtin { // a built-in is a starting point: saving makes a copy @@ -637,27 +692,26 @@ fn presets_window(app: &mut LccApp, ctx: &egui::Context, st: &mut WorkflowUi) { crate::access::label(&r, "Arguments"); ui.end_row(); combo(ui, "ei-mode", "Mode", &mut st.draft.mode, MODES); - let formats: Vec<(&str, &str)> = FORMATS.iter().map(|f| (*f, if *f == "psd" { "PSD (layered)" } else { "TIFF" })).collect(); - combo(ui, "ei-format", "File Format", &mut st.draft.format, &formats); - let spaces: Vec<(&str, &str)> = SPACES - .iter() - .map(|c| { - ( - *c, - match *c { - "adobeRgb" => "Adobe RGB (1998)", - "proPhoto" => "ProPhoto RGB", - "displayP3" => "Display P3", - _ => "sRGB", - }, - ) - }) - .collect(); - combo(ui, "ei-space", "Color Space", &mut st.draft.color_space, &spaces); + combo(ui, "ei-format", "File Format", &mut st.draft.format, FORMATS); + if matches!(st.draft.format.as_str(), "exr" | "dng") { + // no choice: an OpenEXR copy is scene-linear Rec. 2020, a DNG keeps the raw data + ui.label(tr("Color Space")); + ui.label(egui::RichText::new(tr("scene-linear Rec. 2020")).weak()); + ui.end_row(); + } else { + combo(ui, "ei-space", "Color Space", &mut st.draft.color_space, SPACES); + } ui.label(tr("Bit Depth")); ui.horizontal(|ui| { - ui.radio_value(&mut st.draft.bit_depth, 8, tr("8 bits/component")); - ui.radio_value(&mut st.draft.bit_depth, 16, tr("16 bits/component")); + let depths = lcc_engine::cmd::edit_in::Format::bit_depths( + lcc_engine::cmd::edit_in::Format::parse(&st.draft.format).unwrap_or_default(), + ); + if !depths.contains(&st.draft.bit_depth) { + st.draft.bit_depth = depths.first().copied().unwrap_or(16); + } + for d in depths { + ui.radio_value(&mut st.draft.bit_depth, *d, tr(depth_label(&st.draft.format, *d))); + } }); ui.end_row(); ui.label(tr("File Name")); @@ -665,7 +719,12 @@ fn presets_window(app: &mut LccApp, ctx: &egui::Context, st: &mut WorkflowUi) { crate::access::label(&r, "File Name"); ui.end_row(); ui.label(""); - ui.checkbox(&mut st.draft.stack, tr("Stack With Original")); + ui.horizontal(|ui| { + ui.checkbox(&mut st.draft.stack, tr("Stack With Original")); + if matches!(st.draft.mode.as_str(), "copy" | "original") { + ui.checkbox(&mut st.draft.xmp, tr("XMP Sidecar")); + } + }); ui.end_row(); }); egui::Grid::new("edit-in-grid-menu").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| combo(ui, "ei-menu", "Edit In Menu", &mut st.draft.menu, MENUS)); @@ -1045,7 +1104,7 @@ fn actions_window(app: &mut LccApp, ctx: &egui::Context, st: &mut WorkflowUi) { ui.horizontal(|ui| { let sc = a["shortcut"].as_str().map(|s| format!(" {s}")).unwrap_or_default(); let text = format!("{name} · {} {}{sc}", a["steps"].as_u64().unwrap_or(0), tr("steps")); - if ui.selectable_label(st.selected.as_deref() == Some(&name), text).clicked() { + if ui.pick_label(st.selected.as_deref() == Some(&name), text).clicked() { st.shortcut = a["shortcut"].as_str().unwrap_or_default().to_string(); st.selected = Some(name.clone()); } @@ -1411,6 +1470,64 @@ mod tests { assert!(toast.contains("Couldn't open the editor") && toast.contains("no such editor"), "{toast:?}"); let _ = std::fs::remove_dir_all(&dir); } + + /// #1315: `photocraft` names where its installer put it, not a program on the PATH. The + /// editor is started at the program the host resolved, not at the bare name. + #[test] + fn after_command_starts_the_resolved_program() { + let rec = std::sync::Arc::new(lcc_engine::desktop::Recorder::default()); + let services = crate::Services { + open_with: Some(Box::new(|_, _| Ok(()))), + resolve_editor: Some(Box::new(|app: &str| (app.eq_ignore_ascii_case("photocraft")).then(|| "/found/photocraft".to_string()))), + ..Default::default() + }; + let mut app = LccApp::new(lcc_engine::Session::with_demo(), services); + app.session.desktop = rec.clone(); + let result = json!({ + "path": "/tmp/out-edit.tif", "id": 1, "original": 1, "opened": null, + "openWith": {"path": "/tmp/out-edit.tif", "app": "photocraft", "args": [], "reload": [1], "preset": "", "control": null}, + }); + after_command(&mut app, "photo.editIn", &result); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while std::time::Instant::now() < deadline { + if let Some(lcc_engine::desktop::Request::Launch(line)) = rec.requests().last() { + assert_eq!(line.first().map(String::as_str), Some("/found/photocraft"), "started where the host found it, not at the bare name"); + return; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + panic!("no launch recorded: {:?}", rec.requests()); + } + + /// #1315: the copies are made by the command, so a missing editor is checked first — the + /// failure leaves no copy behind. + #[test] + fn a_failed_editor_check_makes_no_copy() { + let dir = temp("check-first"); + let src = dir.join("a.png"); + png(&src, 20, 12, 1); + let services = crate::Services { + check_editor: Some(Box::new(|_| { + Err("PhotoCraft isn't installed. Install it, or give where it is in Settings ▸ External Editing.".into()) + })), + ..Default::default() + }; + let mut app = LccApp::new(lcc_engine::Session::new().with_fs(), services); + app.session.workflow = lcc_engine::cmd::actions::Workflow::in_dir(Some(dir.join("settings"))); + app.ui.settings.external_editor = "photocraft".into(); + let r = app.session.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = r["imported"].get(0).and_then(Value::as_u64).unwrap(); + app.session.selection = lcc_engine::Selection::single(lcc_catalog::PhotoId(id)); + let ctx = egui::Context::default(); + let before = app.session.catalog.len(); + let e = run_choice(&mut app, &ctx, &json!({}), Some(false), "copy", &[lcc_catalog::PhotoId(id)]).unwrap_err(); + assert!(e.contains("isn't installed"), "{e}"); + assert_eq!(app.session.catalog.len(), before, "no copy was made"); + let edits: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|f| f.file_name().to_string_lossy().to_string()).collect(); + assert!(!edits.iter().any(|n| n.contains("-Edit")), "no -Edit copy on disk: {edits:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A launch that fails on the editor's worker thread is reported as a toast, not only in the status line. #[test] fn worker_launch_failure_shows_an_error_toast() { diff --git a/crates/ui-egui/src/export_module.rs b/crates/ui-egui/src/export_module.rs index db62c2e8e5..36b471a4d3 100644 --- a/crates/ui-egui/src/export_module.rs +++ b/crates/ui-egui/src/export_module.rs @@ -168,7 +168,8 @@ impl Module for ExportModule { if busy { foot_ui.label(egui::RichText::new(crate::i18n::tr("Exporting…")).color(t.text_dim)); } - if b.clicked() { + // (Return in one of the settings' text fields starts the export too) + if b.clicked() || (n > 0 && !busy && crate::panels::dialogs::field_returned(ui.ctx())) { // the photos the preview shows now let ids = targets(app); match crate::panels::dialogs::start_export( diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index c83223f83a..e6fd476ffc 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -1024,6 +1024,9 @@ mod tests { assert_eq!(state["selection"], json!(ids[..3])); assert_eq!(state["active"], ids[2]); h.app.ui.right = crate::state::RightPanel::Crop; + // the right-click's menu holds the keys until it closes + h.request("ui.key", json!({"key": "Escape"}), t); + h.settle(SETTLE); h.request("ui.key", json!({"key": "p"}), t); h.settle(SETTLE); let flag = h.app.session.catalog.photo(lcc_catalog::PhotoId(ids[2])).map(|p| p.flag); @@ -1806,6 +1809,75 @@ mod tests { assert_eq!(h.request("engine.execute", json!({"command": "view.person", "params": {"name": " "}}), t)["ok"], false); } + /// The person page's sort picker: the faces follow what it picks, the page is asked for again, and a sort nobody + /// knows is refused (issue #1691). + #[test] + fn the_sort_picker_orders_a_persons_faces() { + use crate::state::PersonSort; + use lcc_catalog::Op; + let mut h = demo([1400.0, 900.0]); + let t = Duration::from_secs(10); + let ids: Vec<_> = h.app.session.catalog.photos().map(|p| p.id).take(2).collect(); + let face = |x: f64, name: &str| lcc_meta::Region { + rect: lcc_geom::Rect { x0: x, y0: 0.2, x1: x + 0.25, y1: 0.6 }, + kind: lcc_meta::RegionKind::Face, + name: Some(name.to_string()), + description: None, + }; + for (id, regions) in [(ids[0], vec![face(0.1, "Jane Doe")]), (ids[1], vec![face(0.3, "Jane Doe")])] { + let mut meta = h.app.session.catalog.photo(id).unwrap().meta.clone(); + meta.regions = regions; + h.app.session.commit("setup", Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + } + // the first photo is the newest (2024), the second the oldest (2020) + h.app.session.commit("setup", Op::SetCaptured { id: ids[0], captured: Some("2024-05-01T10:00:00".into()) }).unwrap(); + h.app.session.commit("setup", Op::SetCaptured { id: ids[1], captured: Some("2020-01-01T09:00:00".into()) }).unwrap(); + h.request("engine.execute", json!({"command": "view.people"}), t); + h.app.ui.people_category = crate::state::PeopleCategory::Confirmed; + h.settle(SETTLE); + h.step(); + let r = h.request("ui.clickWidget", json!({"id": "person:Jane Doe"}), t); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + let at = |h: &Headless| h.app.caches.person_page.as_ref().unwrap().5.confirmed.iter().map(|f| f.photo).collect::>(); + assert_eq!(at(&h), vec![ids[0].0, ids[1].0], "the import order by default"); + let widgets = h.request("ui.widgets", json!({}), t).to_string(); + assert!(widgets.contains("\"combo:personSort\""), "the picker is there: {widgets}"); + // oldest first: the page is asked for again with the sort, and shows the older photo first + let r = crate::menus::run_ui_command(&mut h.app, "person.sort", &json!({"sort": "oldest"})).unwrap().unwrap(); + assert_eq!(r["sort"], "oldest"); + h.step(); + assert_eq!(h.app.ui.person_sort, PersonSort::Oldest); + assert_eq!(at(&h), vec![ids[1].0, ids[0].0], "the older photo's face first"); + // newest first, then back + crate::menus::run_ui_command(&mut h.app, "person.sort", &json!({"sort": "newest"})).unwrap().unwrap(); + h.step(); + assert_eq!(at(&h), vec![ids[0].0, ids[1].0], "the newer photo's faces first"); + crate::menus::run_ui_command(&mut h.app, "person.sort", &json!({"sort": "photo"})).unwrap().unwrap(); + h.step(); + assert_eq!(h.app.ui.person_sort, PersonSort::Photo); + assert_eq!(at(&h), vec![ids[0].0, ids[1].0]); + // a sort nobody knows is refused, and the choice stays + let r = crate::menus::run_ui_command(&mut h.app, "person.sort", &json!({"sort": "sharpness"})).unwrap(); + assert!(r.is_err(), "{r:?}"); + assert_eq!(h.app.ui.person_sort, PersonSort::Photo); + // the menu item that starts the pre-build: it runs, at the tiles' size, and finishes + let r = crate::menus::run_ui_command(&mut h.app, "people.buildThumbnails", &json!({})).unwrap().unwrap(); + assert_eq!(r["total"], 2, "{r}"); + let edge = r["edge"].as_u64().unwrap(); + assert_eq!(edge % 16, 0, "{r}"); + assert!((16..=512).contains(&edge), "{r}"); + for _ in 0..600 { + let st = h.app.run("faces.buildThumbnails", json!({"status": true})).unwrap(); + if st["done"] == true { + assert_eq!(st["failed"], 0, "{st}"); + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + } + /// A person's More grid confirms a score-bounded batch through either ↑ or the focused tile's A key. Both /// routes use one undo step and leave hidden, lower-score and already named faces alone. #[test] @@ -1841,8 +1913,14 @@ mod tests { pending: 0, }; let set_page = |h: &mut Headless| { - h.app.caches.person_page = - Some(("Jane Doe".into(), h.app.session.catalog.revision, h.app.caches.faces_indexed, 0.0, Arc::new(page.clone()))); + h.app.caches.person_page = Some(( + "Jane Doe".into(), + h.app.session.catalog.revision, + h.app.caches.faces_indexed, + 0.0, + crate::state::PersonSort::default(), + Arc::new(page.clone()), + )); h.step(); }; h.app.ui.dismissed_faces.insert((ids[4].0, 0)); @@ -3598,6 +3676,76 @@ mod tests { let _ = std::fs::remove_dir_all(&out); } + /// Custom Order in a folder of the Folders panel (issue #1583): dragging a thumbnail onto the left half + /// of another one moves it there and the sort becomes Custom Order, as in an album; the order is saved + /// with the folder. It works with Show Photos in Subfolders on (the default) while nothing is below the + /// folder; once a photo in a folder inside it is shown with it, the same drag is no reorder. + #[test] + fn drag_photos_to_reorder_a_folder() { + let mut h = demo([1300.0, 900.0]); + let t = Duration::from_secs(10); + let add = |h: &mut Headless, path: &str, captured: &str| { + let id = h.app.session.catalog.alloc_photo_id(); + let mut p = lcc_catalog::Photo::new( + id, + lcc_catalog::Source::File { path: path.into() }, + path.rsplit('/').next().unwrap_or("x.jpg"), + "JPEG", + 60, + 40, + "2026-01-01", + ); + p.captured = Some(captured.into()); + h.app.session.catalog.apply(lcc_catalog::Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 + }; + let ids: Vec = (0..4).map(|i| add(&mut h, &format!("/pics/trip/{i}.jpg"), &format!("2026-01-0{}T10:00:00", i + 1))).collect(); + assert!(h.app.session.folder_subfolders, "shown with the photos of the folders inside it, the default"); + h.request("engine.execute", json!({"command": "library.source", "params": {"kind": "libraryFolder", "path": "/pics/trip"}}), t); + h.request("engine.execute", json!({"command": "library.sort", "params": {"key": "fileName", "ascending": true}}), t); + h.settle(SETTLE); + let listed: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + assert_eq!(listed, ids, "the folder's own photos, by file name"); + let rect = |h: &mut Headless, id: &str| { + let w = h.request("ui.widgets", json!({"filter": id}), t); + let r = w["result"] + .as_array() + .and_then(|a| a.iter().find(|x| x["id"] == id)) + .map(|x| x["rect"].clone()) + .unwrap_or_else(|| panic!("{id}: {w}")); + let f = |i: usize| r[i].as_f64().unwrap(); + (f(0), f(1), f(2), f(3)) + }; + let (x, y, w, hh) = rect(&mut h, &format!("thumb:{}", ids[3])); + let (tx, ty, _, th) = rect(&mut h, &format!("thumb:{}", ids[1])); + let r = h.request("ui.drag", json!({"x": x + w / 2.0, "y": y + hh / 2.0, "toX": tx + 6.0, "toY": ty + th / 2.0, "steps": 12}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.session.sort.key, lcc_catalog::SortKey::Custom); + let want = vec![ids[0], ids[3], ids[1], ids[2]]; + let now: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + assert_eq!(now, want); + let saved: Vec = h.app.session.catalog.folder_photo_order("/pics/trip").iter().map(|p| p.0).collect(); + assert_eq!(saved, want, "saved with the folder"); + assert!(h.app.ui.dragging_photos.is_none(), "the drag ended"); + + // a photo in a folder inside it, shown with the folder (the default): the photos of two folders + // have no one order, and the same drag rearranges nothing + add(&mut h, "/pics/trip/inside/9.jpg", "2020-01-01T10:00:00"); + h.settle(SETTLE); + let with_subfolders: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + assert_eq!(with_subfolders.len(), 5, "the folder's four and the one inside it"); + let (x, y, w, hh) = rect(&mut h, &format!("thumb:{}", with_subfolders[4])); + let (tx, ty, _, th) = rect(&mut h, &format!("thumb:{}", with_subfolders[0])); + let r = h.request("ui.drag", json!({"x": x + w / 2.0, "y": y + hh / 2.0, "toX": tx + 6.0, "toY": ty + th / 2.0, "steps": 12}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let after: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + assert_eq!(after, with_subfolders, "no one order for the photos of several folders"); + let saved: Vec = h.app.session.catalog.folder_photo_order("/pics/trip").iter().map(|p| p.0).collect(); + assert_eq!(saved, want, "the folder's own order is untouched"); + } + /// Issue #10: a raw shown from its embedded JPEG (an undecodable raw variant) says so — a badge /// on its grid thumbnail, a pill on the loupe, a notice in Edit and Info — and other photos /// show none of it. @@ -3821,6 +3969,7 @@ mod tests { fn browse_a_local_folder() { let dir = lcc_testkit::TempDir::new("lc-ui-browse"); let mut h = demo([1300.0, 900.0]); + h.app.ui.settings.import_as_tab = false; let t = Duration::from_secs(10); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("inner")).unwrap(); @@ -4625,7 +4774,9 @@ mod tests { let (g, n) = (gate.clone(), started.clone()); h.app.session.media.file_probe = Some(std::sync::Arc::new(move |_: &str| { n.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - while !g.load(std::sync::atomic::Ordering::Relaxed) { + // bounded, so a test that fails before opening the gate doesn't leave the scan spinning + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !g.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < end { std::thread::sleep(Duration::from_millis(5)); } Ok(lcc_engine::media::ProbeInfo { format: "PNG".into(), ..Default::default() }) @@ -4751,7 +4902,9 @@ mod tests { let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let g = gate.clone(); h.app.session.media.file_probe = Some(std::sync::Arc::new(move |_: &str| { - while !g.load(std::sync::atomic::Ordering::Relaxed) { + // bounded, so a test that fails before opening the gate doesn't leave the scan spinning + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !g.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < end { std::thread::sleep(Duration::from_millis(5)); } Ok(lcc_engine::media::ProbeInfo { format: "PNG".into(), ..Default::default() }) @@ -6641,6 +6794,9 @@ mod tests { use crate::state::Zoom; let mut h = demo([1000.0, 700.0]); let t = Duration::from_secs(10); + // zoom steps are the loupe's; in a grid Cmd+= opens the loupe at Fit (#1761) + h.app.run("view.loupe", json!({})).unwrap(); + h.app.ui.zoom = Zoom::Fit; assert_eq!(serde_json::from_value::(json!({"percent": 100})).unwrap(), Zoom::Percent(100.0)); for factor in [json!(0), json!(-1), json!(1e308), json!("big"), Value::Null] { let r = h.request("ui.zoom", json!({"factor": factor}), t); diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index c442326b18..e18f36999f 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -10,6 +10,7 @@ //! one undo step. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use lcc_engine::import::{ImportCandidate, ImportWarning, ScanInput, ScanOutput, ScanProgress, scan_with_subfolders}; use serde::{Deserialize, Serialize}; @@ -128,6 +129,16 @@ pub struct ImportDialog { /// "Don't Import Suspected Duplicates" unchecked: files whose content the library already has /// can be checked and come in as new photos (the `importDuplicates` param). pub import_duplicates: bool, + /// Treat JPEGs next to raw files as companions of the raw (issue #1692): the review shows + /// them attached to their raw and the import is asked to attach them. Not persisted: the + /// library setting (`catalog.settings`' `rawJpegCompanions`) is the starting point of every + /// session ([`ImportDialog::companions_touched`]). + #[serde(skip)] + pub companions: bool, + /// Whether [`ImportDialog::companions`] was already given the library setting's value in + /// this session (the Import tab's options persist; their starting point is the setting). + #[serde(skip)] + pub companions_touched: bool, /// The candidate clicked last: where a Shift-click range starts ([`ImportDialog::click`]). #[serde(skip)] pub last_clicked: Option, @@ -220,13 +231,19 @@ impl ImportDialog { pub fn is_browsed(&self, i: usize) -> bool { self.candidates.get(i).is_some_and(|c| c.error.is_none() && c.duplicate.is_none() && c.local) } + /// Candidate `i` is a JPEG the companions setting takes as its raw's (`companionOf`): the + /// review shows it attached to the raw, not as a photo of its own. + pub fn is_companion(&self, i: usize) -> bool { + self.companions && self.candidates.get(i).is_some_and(|c| c.error.is_none() && c.duplicate.is_none() && c.companion_of.is_some()) + } /// Candidate `i` can be checked: a readable file the library doesn't have, or one whose photo /// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285). A browsed /// photo can't be copied or moved: the engine would add it in place, so copying leaves it out. pub fn importable(&self, i: usize) -> bool { - self.candidates.get(i).is_some_and(|c| c.error.is_none() && (c.duplicate.is_none() || self.is_trashed(i))) - && !(self.copy && self.candidates.get(i).is_some_and(|c| c.local)) - || (self.import_duplicates && self.is_suspected_duplicate(i)) + !self.is_companion(i) + && (self.candidates.get(i).is_some_and(|c| c.error.is_none() && (c.duplicate.is_none() || self.is_trashed(i))) + && !(self.copy && self.candidates.get(i).is_some_and(|c| c.local)) + || (self.import_duplicates && self.is_suspected_duplicate(i))) } /// Candidate `i` has the same content as a photo the library has (not in Recently Deleted) or /// as a file earlier in the list: Lightroom's "suspected duplicate". @@ -338,6 +355,7 @@ impl ImportDialog { if self.import_duplicates { *params.field_mut("importDuplicates") = json!(true); } + *params.field_mut("companions") = json!(self.companions); if !self.preset.is_empty() { *params.field_mut("preset") = json!(self.preset); } @@ -755,7 +773,7 @@ pub fn browse(app: &mut LccApp, path: &str, subfolders: Option, show: Opti if app.scan.as_ref().is_some_and(|t| !t.browse) || app.import.as_ref().is_some_and(|t| !t.browse) { return Err("an import is running".into()); } - let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string(); + let dir_s = lcc_engine::import::browse_folder_string(&dir); // subfolders: given, it wins; left out, a re-browse of the same folder keeps the choice and a // new folder starts with subfolders in — a folder picked to import means the tree under it // (the engine's library.browse applies the same rule) @@ -1631,6 +1649,17 @@ pub fn body(app: &mut LccApp, ui: &mut egui::Ui, d: &mut ImportDialog) { if trashed > 0 { ui.label(egui::RichText::new(crate::i18n::tr_format!("· {trashed} in Recently Deleted", trashed = trashed)).color(t.text_dim)); } + let companions = if d.companions { + d.candidates.iter().filter(|c| c.error.is_none() && c.duplicate.is_none() && c.companion_of.is_some()).count() + } else { + 0 + }; + if companions > 0 { + ui.label(egui::RichText::new(crate::i18n::tr_format!("· {companions} kept with their RAWs", companions = companions)).color(t.text_dim)) + .on_hover_text(crate::i18n::tr( + "A JPEG with a raw's name beside it is the raw's companion: one photo, one face scan, one set of metadata. Uncheck the companions option to import JPEGs as photos of their own.", + )); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::text_button(ui, "importNone", crate::i18n::tr("Uncheck All"), false).clicked() { d.checked.iter_mut().for_each(|c| *c = false); @@ -1776,7 +1805,7 @@ pub fn body(app: &mut LccApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let cur = opts.iter().find(|o| o.0 == key).map_or(opts[0].1, |o| o.1); let combo = crate::widgets::combo_box("import-organize").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { for (k, label) in opts { - let r = ui.selectable_label(key == k, crate::i18n::tr(label)); + let r = ui.pick_label(key == k, crate::i18n::tr(label)); register(ui.ctx(), format!("button:importOrganize-{k}"), r.rect); if r.clicked() { d.organize = k.to_string(); @@ -1875,7 +1904,7 @@ pub fn body(app: &mut LccApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let mut pick = None; crate::widgets::combo_box("import-on-deleted").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { for (v, label) in [("restore", "Restore them"), ("fresh", "Import as new"), ("", "Leave them")] { - if ui.selectable_label(d.on_deleted == v, crate::i18n::tr(label)).clicked() { + if ui.pick_label(d.on_deleted == v, crate::i18n::tr(label)).clicked() { pick = Some(v); } } @@ -1904,12 +1933,12 @@ pub fn body(app: &mut LccApp, ui: &mut egui::Ui, d: &mut ImportDialog) { .width(ui.available_width()) .empty_text(empty) .show_with_choices(ui, |ui| { - let none = ui.selectable_label(d.album.is_none() && d.new_album.is_empty(), crate::i18n::tr("None")); + let none = ui.pick_label(d.album.is_none() && d.new_album.is_empty(), crate::i18n::tr("None")); register(ui.ctx(), "importAlbum:none", none.rect); if none.clicked() { extra = Some(false); } - let new = ui.selectable_label(d.album.is_none() && !d.new_album.is_empty(), crate::i18n::tr("New collection…")); + let new = ui.pick_label(d.album.is_none() && !d.new_album.is_empty(), crate::i18n::tr("New collection…")); register(ui.ctx(), "importAlbum:new", new.rect); if new.clicked() { extra = Some(true); @@ -2048,14 +2077,14 @@ pub(crate) fn metadata_preset_picker(app: &mut LccApp, ui: &mut egui::Ui, d: &mu d.metadata_preset.clone() }; let combo = crate::widgets::combo_box("import-metadata").selected_text(cur).height(300.0).show_ui(ui, |ui| { - let none_btn = ui.selectable_label(!d.creating_meta_preset && d.metadata_preset.is_empty(), crate::i18n::tr("None")); + let none_btn = ui.pick_label(!d.creating_meta_preset && d.metadata_preset.is_empty(), crate::i18n::tr("None")); register(ui.ctx(), "button:importMetaNone", none_btn.rect); if none_btn.clicked() { d.metadata_preset.clear(); d.creating_meta_preset = false; } for m in &app.session.metadata_presets { - let r = ui.selectable_label(!d.creating_meta_preset && d.metadata_preset == m.name, &m.name); + let r = ui.pick_label(!d.creating_meta_preset && d.metadata_preset == m.name, &m.name); register(ui.ctx(), format!("button:importMetaPreset-{}", m.name), r.rect); if r.clicked() { d.metadata_preset = m.name.clone(); @@ -2063,7 +2092,7 @@ pub(crate) fn metadata_preset_picker(app: &mut LccApp, ui: &mut egui::Ui, d: &mu } } ui.separator(); - let new_btn = ui.selectable_label(d.creating_meta_preset, crate::i18n::tr("New Preset…")); + let new_btn = ui.pick_label(d.creating_meta_preset, crate::i18n::tr("New Preset…")); register(ui.ctx(), "button:importMetaNewPreset", new_btn.rect); if new_btn.clicked() { d.creating_meta_preset = true; @@ -2182,6 +2211,7 @@ pub(crate) fn candidate_cell(app: &mut LccApp, ui: &mut egui::Ui, d: &mut Import (Some(_), _) if in_trash && on => Some(if d.on_deleted == "fresh" { "Will be replaced" } else { "Will be restored" }), (Some(_), _) if in_trash => Some("In Recently Deleted"), (Some(r), _) if r == "path" => Some("In catalog"), + (None, None) if d.is_companion(i) => Some("Companion"), (None, None) if d.copy && d.is_browsed(i) => Some("In catalog"), (Some(_), _) if on => Some("Will be copied"), (Some(_), _) => Some("Duplicate"), @@ -2212,7 +2242,13 @@ pub(crate) fn candidate_cell(app: &mut LccApp, ui: &mut egui::Ui, d: &mut Import )) .unwrap_or_default() ); - let resp = resp.on_hover_text(tip); + let resp = resp.on_hover_text(if let Some(raw) = &c.companion_of { + // the JPEG is shown as its raw's companion (issue #1692): the raw is named + let name = std::path::Path::new(raw).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| raw.clone()); + format!("{}\n\n{}", crate::i18n::tr_format!("Kept with {raw} as its companion: not a photo of its own.", raw = name), tip) + } else { + tip + }); if resp.clicked() && ok { let shift = ui.input(|input| input.modifiers.shift); d.click(i, shift); @@ -2462,7 +2498,7 @@ fn profile_combo(ui: &mut egui::Ui, id: &str, options: &[(String, String)], valu let combo = crate::widgets::combo_box(id.to_string()).selected_text(cur).width(width).height(300.0).show_ui(ui, |ui| { ui.set_min_width(list_w); for (o, name) in options { - ui.selectable_value(value, o.clone(), name); + ui.pick_value(value, o.clone(), name); } }); register(ui.ctx(), format!("combo:{id}"), combo.response.rect); diff --git a/crates/ui-egui/src/import_screen.rs b/crates/ui-egui/src/import_screen.rs index b4cdb69163..ef1273d9dd 100644 --- a/crates/ui-egui/src/import_screen.rs +++ b/crates/ui-egui/src/import_screen.rs @@ -13,6 +13,7 @@ //! //! Own design. +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Id, Rect, Sense, Stroke, Vec2, pos2, vec2}; use serde_json::json; @@ -80,10 +81,7 @@ pub(crate) fn show(app: &mut LccApp, ctx: &egui::Context) { let screen = ctx.content_rect(); let mut cancel = false; let mut go = false; - if !egui::Popup::is_any_open(ctx) - && !ctx.egui_wants_keyboard_input() - && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) - { + if crate::dialog_frame::esc_closes(false, app.text_focus, ctx) { cancel = true; } let t = Tokens::get(ctx); @@ -569,7 +567,7 @@ pub(crate) fn options_for(app: &mut LccApp, ui: &mut egui::Ui, d: &mut ImportDia let cur = opts.iter().find(|o| o.0 == key).map_or(opts[0].1, |o| o.1); let combo = crate::widgets::combo_box("import-organize").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { for (k, label) in opts { - let r = ui.selectable_label(key == k, crate::i18n::tr(label)); + let r = ui.pick_label(key == k, crate::i18n::tr(label)); register(ui.ctx(), format!("button:importOrganize-{k}"), r.rect); if r.clicked() { d.organize = k.to_string(); @@ -626,6 +624,25 @@ pub(crate) fn options_for(app: &mut LccApp, ui: &mut egui::Ui, d: &mut ImportDia register(ui.ctx(), "check:importDng", r.rect); } } + // companions (issue #1692): JPEGs beside raws stay attached to their raw, one photo per pair. + // The library's setting is the starting point (once per session: the tab's options persist). + if !d.companions_touched { + d.companions = app.session.raw_jpeg_companions(); + d.companions_touched = true; + } + let comp = crate::dialog_frame::checkbox(ui, &mut d.companions, crate::i18n::tr("Treat JPEGs next to raw files as companions")); + register(ui.ctx(), "check:importCompanions", comp.rect); + if comp.changed() { + // only the companions' checks follow the switch: the rest of the selection stays + for (i, c) in d.candidates.iter().enumerate() { + if c.error.is_none() && c.duplicate.is_none() && c.companion_of.is_some() { + let importable = d.importable(i); + if let Some(on) = d.checked.get_mut(i) { + *on = !d.companions && importable; + } + } + } + } if tab { apply_rows(app, ui, d, tab); return; @@ -688,12 +705,12 @@ fn apply_rows(app: &mut LccApp, ui: &mut egui::Ui, d: &mut ImportDialog, tab: bo .width(ui.available_width()) .empty_text(empty) .show_with_choices(ui, |ui| { - let none = ui.selectable_label(d.album.is_none() && d.new_album.is_empty(), crate::i18n::tr("None")); + let none = ui.pick_label(d.album.is_none() && d.new_album.is_empty(), crate::i18n::tr("None")); register(ui.ctx(), "importAlbum:none", none.rect); if none.clicked() { extra = Some(false); } - let new = ui.selectable_label(d.album.is_none() && !d.new_album.is_empty(), crate::i18n::tr("New collection…")); + let new = ui.pick_label(d.album.is_none() && !d.new_album.is_empty(), crate::i18n::tr("New collection…")); register(ui.ctx(), "importAlbum:new", new.rect); if new.clicked() { extra = Some(true); diff --git a/crates/ui-egui/src/import_tab.rs b/crates/ui-egui/src/import_tab.rs index 07b1f92d58..05be25cb1c 100644 --- a/crates/ui-egui/src/import_tab.rs +++ b/crates/ui-egui/src/import_tab.rs @@ -17,6 +17,7 @@ //! db061a0a7, 437ed003f, 6e4fa44d0, 12d31e4fc. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Align2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -55,13 +56,13 @@ pub struct ImportSettings { impl Default for ImportSettings { fn default() -> Self { // add in place, as the review starts: copying is a choice the user makes - ImportSettings { take: "picks".into(), previews: "standard".into(), preset_name: String::new(), opts: Default::default() } + ImportSettings { take: "selected".into(), previews: "standard".into(), preset_name: String::new(), opts: Default::default() } } } impl ImportSettings { pub fn take(&self) -> Take { - Take::parse(&self.take).unwrap_or(Take::Picks) + Take::parse(&self.take).unwrap_or(Take::Selected) } /// These settings from an import preset's (unknown fields keep their defaults). @@ -69,7 +70,7 @@ impl ImportSettings { let mut opts: crate::import::ImportDialog = serde_json::from_value(v.clone()).unwrap_or_default(); opts.fold_preset(); let previews = v.get("previews").and_then(Value::as_str).filter(|p| matches!(*p, "none" | "standard" | "full")).unwrap_or("standard"); - ImportSettings { take: "picks".into(), previews: previews.to_string(), preset_name: name.to_string(), opts: settings_only(opts) } + ImportSettings { take: "selected".into(), previews: previews.to_string(), preset_name: name.to_string(), opts: settings_only(opts) } } /// What an import preset keeps of these settings (not what to take, nor any file). @@ -221,6 +222,15 @@ pub fn keep_in_step(app: &mut LccApp) { app.ui.import_was_browsing = browsing; } +/// Why an import with `take` would import zero photos from the browsed folder. +fn empty_take_reason(take: Take) -> &'static str { + match take { + Take::Picks => "No picks to import: flag the photos you want with P first", + Take::Selected => "No photos selected to import", + Take::All => "Every photo here is in the catalog already", + } +} + /// The big button: import what the settings take from the browsed folder, in the background, /// then show the Library tab as the photos come in (`import.start {what?}`). pub fn start(app: &mut LccApp, p: &Value) -> Result { @@ -242,12 +252,7 @@ pub fn start(app: &mut LccApp, p: &Value) -> Result { // a folder still being read: what is in so far is what there is let paths = app.session.import_paths(take); if paths.is_empty() { - return Err(crate::i18n::tr(match take { - Take::Picks => "No picks to import: flag the photos you want with P first", - Take::Selected => "No photos selected to import", - Take::All => "Every photo here is in the catalog already", - }) - .to_string()); + return Err(crate::i18n::tr(empty_take_reason(take)).to_string()); } let mut params = settings.opts.params()?; // a new album named in the settings is made with the first batch (a later batch joins it) @@ -780,9 +785,15 @@ fn bar(app: &mut LccApp, ui: &mut egui::Ui, wide: bool, pane: &mut Pane) { // where: the folder's name, all of it in a tooltip let folder = app.session.browse.as_ref().filter(|_| browsing).map(|b| b.path.clone()); let name = folder.as_ref().map(|f| std::path::Path::new(f).file_name().map_or_else(|| f.clone(), |n| n.to_string_lossy().to_string())); - // the button says what it does; how many and where to are in its tooltip + // the button says what it does; how many and where to (or why it is disabled) are in its tooltip let import_label = crate::i18n::tr("Import").to_string(); - let import_tip = crate::i18n::tr_format!("Import {n} into {library}", n = n, library = library_name(app)); + let import_tip = if !browsing { + crate::i18n::tr("Choose a folder or card to import from first").to_string() + } else if n == 0 { + crate::i18n::tr(empty_take_reason(take)).to_string() + } else { + crate::i18n::tr_format!("Import {n} into {library}", n = n, library = library_name(app)) + }; let layout = bar_layout(&row, &import_label, name.as_deref(), folder.as_deref(), wide); let mut room = layout.room.max(40.0); // the folders above it as a breadcrumb (OneSlips LR-IMP-WINDOW 6e4fa44d0): each opens, those that don't fit @@ -1019,7 +1030,7 @@ fn take_segments(app: &mut LccApp, ui: &mut egui::Ui) { Take::All => 2, }; if let Some(i) = crate::widgets::segments(ui, "importTake", &["Picks", "Selected", "All"], Some(chosen)) { - app.ui.settings.import_tab.take = ["picks", "selected", "all"].get(i).copied().unwrap_or("picks").to_string(); + app.ui.settings.import_tab.take = ["picks", "selected", "all"].get(i).copied().unwrap_or("selected").to_string(); } } @@ -1084,7 +1095,7 @@ fn settings(app: &mut LccApp, ui: &mut egui::Ui) { Take::All => 2, }; if let Some(i) = crate::widgets::segments(ui, "importTakeSettings", &["Picks", "Selected", "All"], Some(chosen)) { - s.take = ["picks", "selected", "all"].get(i).copied().unwrap_or("picks").to_string(); + s.take = ["picks", "selected", "all"].get(i).copied().unwrap_or("selected").to_string(); } }); crate::import_screen::options_for(app, ui, &mut s.opts, true); @@ -1122,7 +1133,7 @@ fn preset_row(app: &mut LccApp, ui: &mut egui::Ui, s: &mut ImportSettings) { let combo = crate::widgets::combo_box("import-tab-preset").selected_text(shown).width(ui.available_width().max(120.0)).show_ui(ui, |ui| { ui.set_min_width(list_w); for (i, n) in names.iter().enumerate() { - let r = ui.selectable_label(*n == s.preset_name, n); + let r = ui.pick_label(*n == s.preset_name, n); register(ui.ctx(), format!("button:importPreset-{i}"), r.rect); if r.clicked() { chosen = Some(n.clone()); diff --git a/crates/ui-egui/src/keyboard.rs b/crates/ui-egui/src/keyboard.rs index 8e49bd1ad6..9a9522dd9a 100644 --- a/crates/ui-egui/src/keyboard.rs +++ b/crates/ui-egui/src/keyboard.rs @@ -18,6 +18,10 @@ pub enum Owner { /// A dialog (Settings included), the shortcuts overlay or another window that waits over the /// app ([`modal_open`]): every key but [`PASS_THROUGH`] is its own, or nobody's. Modal, + /// A dropdown, a menu or another popup is open ([`egui::Popup::is_any_open`]): it takes the + /// keyboard, and what [`Owner::Modal`] lets through passes ([`PASS_THROUGH`]) too. A dropdown + /// inside a dialog is already the dialog's. + Popup, /// A widget with the keyboard focus keeps this frame's keys: a text field, a selected slider /// (↑ / ↓), a handle on the photo (arrows, Return, Space), a name being edited. Widget, @@ -159,6 +163,8 @@ pub fn owner(app: &LccApp, ctx: &egui::Context) -> Owner { Owner::Recorder } else if modal_open(app) { Owner::Modal + } else if egui::Popup::is_any_open(ctx) { + Owner::Popup } else if app.ui.name_edit.is_some() || crate::shortcuts::keyboard_owned(app, ctx) { Owner::Widget } else { @@ -184,7 +190,7 @@ pub fn menu_choice(owner: Owner, command: &str, shortcut: Option<&str>, text_foc return MenuChoice::TextField; } match owner { - Owner::Recorder | Owner::Modal if !PASS_THROUGH.contains(&command) => MenuChoice::Drop, + Owner::Recorder | Owner::Modal | Owner::Popup if !PASS_THROUGH.contains(&command) => MenuChoice::Drop, _ => MenuChoice::Run, } } @@ -194,8 +200,8 @@ mod tests { use super::*; #[test] - fn a_modal_drops_menu_shortcuts_but_quit_and_text_editing() { - for owner in [Owner::Modal, Owner::Recorder] { + fn a_modal_or_an_open_popup_drops_menu_shortcuts_but_quit_and_text_editing() { + for owner in [Owner::Modal, Owner::Recorder, Owner::Popup] { let choice = |command: &str, sc: Option<&str>, focus: bool| menu_choice(owner, command, sc, focus); for (command, sc) in [ ("view.zoomIn", "Cmd+="), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7423b76b26..678ead3cfb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -113,6 +113,7 @@ pub mod panels; pub mod pick; pub mod plate; mod pointer_repair; +pub mod popup_typeahead; pub mod print_ui; pub mod print_view; pub mod progress; @@ -252,6 +253,8 @@ mod tests_dialogs; #[cfg(test)] mod tests_drop_import; #[cfg(test)] +mod tests_dropdown_keys; +#[cfg(test)] mod tests_duplicates_ui; #[cfg(test)] mod tests_edit_layout; @@ -260,8 +263,12 @@ mod tests_empty_library; #[cfg(test)] mod tests_enhance_dialog; #[cfg(test)] +mod tests_enter_in_dialog_fields; +#[cfg(test)] mod tests_error_kinds; #[cfg(test)] +mod tests_esc_in_fields; +#[cfg(test)] mod tests_export_preview; #[cfg(test)] mod tests_filmstrip; @@ -569,6 +576,8 @@ pub type PngEncode = Box Vec>; pub type PickFolder = Box Option>; /// Reveal a file in the system file manager (Finder / Explorer / the folder on Linux). pub type RevealFn = Box Result<(), String>>; +/// Shows several files at once in the system file manager, selected in one window. +pub type RevealManyFn = Box Result<(), String>>; /// Open a URL in the user's browser. /// Starts listing (or copying) the device's camera roll; the channel answers with the photos' /// paths, or why there are none (permission denied, …). `Err` when it could not start (Android). @@ -600,6 +609,24 @@ pub type MidiReload = Box Result>; /// Whether an external editor can be started (its name as in [`Services::open_with`]); the /// error says why not and what to do (e.g. PhotoCraft isn't installed). pub type CheckEditorFn = Box Result<(), String>>; +/// Open dialog for an editor's program (Settings ▸ External Editing ▸ Browse…; desktop only). +pub type PickExecutable = Box Vec>; +/// One photo editor found on this machine (Settings ▸ External Editing's Application combo). +#[derive(Clone, Debug, PartialEq)] +pub struct DetectedEditor { + /// What it calls itself (`GIMP`, `Affinity Photo 2`). + pub name: String, + /// The application: a program path, or an application name on macOS. + pub app: String, +} +/// The photo editors installed on this machine, as [`DetectedEditor`]s. None: the host looks +/// nothing up (the web, tests) — the combo then offers Browse… only. +pub type DetectEditorsFn = Box Vec>; +/// Where an editor's application name starts a program, as the engine's launcher runs it +/// (`photocraft` → the installed copy's path; issue #1315). `None` = not a plain program: the +/// system default, a macOS `open -a` name is kept as is, the Flatpak or nothing found — the host +/// opener ([`Services::open_with`]) starts those itself. +pub type ResolveEditorFn = Box Option>; /// Something the host does with the session (web: back up or restore the library in browser /// storage); the work may finish asynchronously. pub type HostAction = Box Result>; @@ -729,6 +756,9 @@ pub struct Services { pub png: Option, /// Show a file in the system file manager (desktop only). pub reveal: Option, + /// Show several files selected in one file-manager window (Linux `FileManager1.ShowItems`); + /// None where the host reveals only one (macOS `open -R`, Windows `explorer /select`). + pub reveal_many: Option, /// The host's current log file (`/logs/.log`), which Help ▸ Open Log /// Folder reveals (#260). None where no log is kept: the web, `--memory`, `_NO_PREFS`. pub log_file: Option, @@ -759,6 +789,14 @@ pub struct Services { /// Checked before Edit In renders a copy, so a missing editor leaves no copy behind (none = /// assume it can). pub check_editor: Option, + /// Open dialog for an editor's program (Settings ▸ External Editing ▸ Browse…; desktop only). + pub pick_executable: Option, + /// The photo editors installed on this machine (Settings ▸ External Editing's Application + /// combo; none: the host looks nothing up). + pub detect_editors: Option, + /// Where an editor's application name starts a program (the installed PhotoCraft's path; + /// issue #1315). None with the name kept as it is: the host has no lookup (the web, tests). + pub resolve_editor: Option, /// File ▸ Back Up Library…: save the whole library (catalog and originals) as one file the /// user keeps (web only: there the library lives in browser storage, which the browser may /// clear; on the desktop it is a folder backed up like any other). @@ -3637,8 +3675,9 @@ pub struct Caches { pub last_move: f64, /// Name suggestions for the photo in the loupe: (photo, catalog revision, faces indexed, suggestions by region). pub face_hints: Option<(u64, u64, u64, std::sync::Arc)>, - /// The open person page: (name, catalog revision, faces indexed, when it was asked for, the page). - pub person_page: Option<(String, u64, u64, f64, std::sync::Arc)>, + /// The open person page: (name, catalog revision, faces indexed, when it was asked for, the sort it was asked + /// with, the page). + pub person_page: Option<(String, u64, u64, f64, crate::state::PersonSort, std::sync::Arc)>, /// The Advanced Search panel's lists of the library's cameras, lenses, formats, keywords and people, with the /// catalog revision they were read at. pub search_choices: Option<(u64, std::sync::Arc)>, @@ -4334,6 +4373,8 @@ mod tests_display_truth; #[cfg(test)] mod tests_docking_acceptance; #[cfg(test)] +mod tests_grid_empty_click; +#[cfg(test)] mod tests_modern; #[cfg(test)] mod tests_modern_gestures; diff --git a/crates/ui-egui/src/libtools.rs b/crates/ui-egui/src/libtools.rs index 55c84c4327..15879a62db 100644 --- a/crates/ui-egui/src/libtools.rs +++ b/crates/ui-egui/src/libtools.rs @@ -7,6 +7,7 @@ //! `metadata.panelPreset`); painting itself dispatches the engine's ordinary commands //! (`photo.setMeta`, `photo.label`, …), one undo step per photo. +use crate::popup_typeahead::PopupItems; use std::collections::HashSet; use lcc_catalog::{ColorLabel, Flag, Photo, PhotoId}; @@ -376,7 +377,7 @@ pub fn painter_bar(app: &mut LccApp, ui: &mut egui::Ui) { let mut next: Option<(PaintKind, String)> = None; let combo = egui::ComboBox::from_id_salt("painter-kind").selected_text(crate::i18n::tr(painter.kind.label())).show_ui(ui, |ui| { for k in PaintKind::ALL { - if ui.selectable_label(k == painter.kind, crate::i18n::tr(k.label())).clicked() && k != painter.kind { + if ui.pick_label(k == painter.kind, crate::i18n::tr(k.label())).clicked() && k != painter.kind { let v = match k { PaintKind::MetadataPreset => app.session.metadata_presets.first().map(|m| m.name.clone()).unwrap_or_default(), PaintKind::Settings => app.session.presets.first().map(|m| m.id.clone()).unwrap_or_default(), @@ -411,7 +412,7 @@ fn value_editor(app: &mut LccApp, ui: &mut egui::Ui, painter: &Painter, next: &m let current = items.iter().find(|(v, _)| *v == painter.value).map(|(_, l)| l.clone()).unwrap_or_else(|| painter.value.clone()); let r = egui::ComboBox::from_id_salt("painter-value").selected_text(current).show_ui(ui, |ui| { for (v, l) in items { - if ui.selectable_label(v == painter.value, l).clicked() { + if ui.pick_label(v == painter.value, l).clicked() { *next = Some((kind, v)); } } diff --git a/crates/ui-egui/src/map/side.rs b/crates/ui-egui/src/map/side.rs index 129f214c16..f83b6eeefc 100644 --- a/crates/ui-egui/src/map/side.rs +++ b/crates/ui-egui/src/map/side.rs @@ -2,6 +2,7 @@ //! geocoding, tile cache); the background jobs they start. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Rect, RichText}; use serde_json::{Value, json}; @@ -236,7 +237,7 @@ pub fn bar(app: &mut LccApp, ui: &mut egui::Ui, r: Rect) { let current = app.map.filter.clone(); for (key, label) in [("visible", "Visible on Map"), ("tagged", "Tagged"), ("untagged", "Untagged"), ("all", "None")] { let on = current.key() == key; - let b = ui.selectable_label(on, tr(label)); + let b = ui.pick_label(on, tr(label)); register(ui.ctx(), format!("map:filter:{key}"), b.rect); if b.clicked() { let _ = app.run("map.filter", json!({"filter": key})); @@ -249,7 +250,7 @@ pub fn bar(app: &mut LccApp, ui: &mut egui::Ui, r: Rect) { }; egui::ComboBox::from_id_salt("map-filter-location").selected_text(shown).width(130.0).show_ui(ui, |ui| { for n in &names { - if ui.selectable_label(current == LocationFilter::Location(n.clone()), n).clicked() { + if ui.pick_label(current == LocationFilter::Location(n.clone()), n).clicked() { let _ = app.run("map.filter", json!({"filter": format!("location:{n}")})); } } @@ -311,7 +312,7 @@ fn location_matches(app: &mut LccApp, ui: &mut egui::Ui, search: Rect) { egui::ScrollArea::vertical().min_scrolled_height(tall).max_height(tall).show(ui, |ui| { ui.with_layout(egui::Layout::top_down_justified(egui::Align::Min), |ui| { for name in &names { - let b = ui.selectable_label(false, name); + let b = ui.pick_label(false, name); register(ui.ctx(), format!("map:searchMatch:{name}"), b.rect); if b.clicked() { go_to_location(app, name); @@ -321,7 +322,7 @@ fn location_matches(app: &mut LccApp, ui: &mut egui::Ui, search: Rect) { if app.map.prefs.online_consent { ui.separator(); let q = app.map.search.trim().to_string(); - let b = ui.selectable_label(false, crate::i18n::tr_format!("Search online for “{q}”…", q = q)); + let b = ui.pick_label(false, crate::i18n::tr_format!("Search online for “{q}”…", q = q)); register(ui.ctx(), "map:searchOnline", b.rect); if b.clicked() && let Err(e) = search_online(app, &q) @@ -421,7 +422,7 @@ fn style_section(app: &mut LccApp, ui: &mut egui::Ui) { let cur = app.map.server(); egui::ComboBox::from_id_salt("map-style").selected_text(cur.name.clone()).width(240.0).show_ui(ui, |ui| { for s in &servers { - if ui.selectable_label(s.id == cur.id, &s.name).clicked() { + if ui.pick_label(s.id == cur.id, &s.name).clicked() { let _ = app.run("map.style", json!({"id": s.id})); } } diff --git a/crates/ui-egui/src/map/view.rs b/crates/ui-egui/src/map/view.rs index 1e0baaa3ee..dfde935c9e 100644 --- a/crates/ui-egui/src/map/view.rs +++ b/crates/ui-egui/src/map/view.rs @@ -1,6 +1,7 @@ //! The map canvas: tiles, tracks, saved-location circles, pins and clusters, attribution; pan, //! zoom, pin hover / click / drag, and drops of photos dragged from the filmstrip or grid. +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use serde_json::json; @@ -652,8 +653,8 @@ fn location_editor(app: &mut LccApp, ctx: &egui::Context, r: Rect) { } let unit_name = if ed.km { "km" } else { "m" }; let cb = egui::ComboBox::from_id_salt("map-location-unit").selected_text(unit_name).width(56.0).show_ui(ui, |ui| { - ui.selectable_value(&mut ed.km, false, "m"); - ui.selectable_value(&mut ed.km, true, "km"); + ui.pick_value(&mut ed.km, false, "m"); + ui.pick_value(&mut ed.km, true, "km"); }); register(ui.ctx(), "combo:mapLocationUnit", cb.response.rect); }); diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index af27e257db..a1cb782513 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -130,6 +130,9 @@ pub fn native_menu_structure(bar: &[(String, Vec)], keymap: &crate::sh s } +/// Hover text of Help ▸ Check for Updates… when `_DISABLE_UPDATES` turned it off. +const UPDATES_DISABLED_HINT: &str = "Updates are turned off ({env}_DISABLE_UPDATES is set); your package manager handles updates."; + /// The Library module's menus in order (the macOS app menu is added by the host); [`menus`] gives /// the module on screen's. pub const MENUS: &[&str] = &["File", "Edit", "Library", "Photo", "Metadata", "View", "Window", "Help"]; @@ -137,7 +140,7 @@ pub const MENUS: &[&str] = &["File", "Edit", "Library", "Photo", "Metadata", "Vi /// Order inside submenus whose items come from the registry: (menu, submenu, ids and `---`). /// Items not listed follow in registry order, dialogs (labels ending in `…`) last. const SUB_LAYOUT: &[(&str, &str, &[&str])] = &[ - ("Library", "Faces", &["faces.detect=Find Faces Again…", "faces.clearAndRescan", "---", "dialog.faceMaintenance"]), + ("Library", "Faces", &["faces.detect=Find Faces Again…", "faces.clearAndRescan", "people.buildThumbnails", "---", "dialog.faceMaintenance"]), ( "Photo", "Develop Settings", @@ -755,8 +758,8 @@ pub(crate) fn expanded(app: &LccApp, name: &str) -> Option> { .into_iter() .map(|(label, key, k)| item("library.sort", json!({"key": k}), label, None, true, Some(cur.key == key))) .collect(); - let in_album = crate::panels::grid::custom_order_album(app).is_some(); - v.push(item("library.sort", json!({"key": "custom"}), "Custom Order", None, in_album, Some(in_album && cur.key == Custom))); + let can_custom = crate::panels::grid::custom_order_source(app).is_some(); + v.push(item("library.sort", json!({"key": "custom"}), "Custom Order", None, can_custom, Some(can_custom && cur.key == Custom))); v.push(item("library.shuffle", json!({}), "Reshuffle", None, cur.key == Random, None)); v.push(MenuNode::Separator); // a shuffle has no direction worth choosing @@ -1605,6 +1608,10 @@ pub(crate) fn nodes_ui( if crate::lrc_menus::is_coming_soon(id) { r = r.on_disabled_hover_text(crate::i18n::tr(crate::lrc_menus::COMING_SOON_HINT)); } + // Check for Updates turned off by the environment says why (upstream #4663) + if id == "app.checkForUpdates" && crate::menus::updates_disabled_by_env() { + r = r.on_disabled_hover_text(crate::i18n::tr(UPDATES_DISABLED_HINT)); + } crate::widgets::register(ui.ctx(), format!("menuitem:{id}"), r.rect); if *checked == Some(true) { let t = crate::theme::Tokens::get(ui.ctx()); @@ -1674,7 +1681,7 @@ mod tests { else { panic!("Library ▸ Faces submenu") }; - let actions = ["faces.detect", "faces.clearAndRescan", "dialog.faceMaintenance"]; + let actions = ["faces.detect", "faces.clearAndRescan", "people.buildThumbnails", "dialog.faceMaintenance"]; for id in actions { assert!(find(children, id).is_some(), "{id} is in Library ▸ Faces"); } @@ -2222,6 +2229,50 @@ mod tests { assert_eq!(run_item(&mut app, "app.openLogFolder", Value::Null).unwrap_err(), "no file manager"); } + /// Upstream #4653: Show in Finder reveals the whole selection where the host selects several + /// files at once (`reveal_many`), and the active photo where it reveals one. + #[test] + fn show_in_finder_reveals_the_selection() { + let dir = lcc_testkit::TempDir::new("lc-ui-reveal"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let o = lcc_engine::export::ExportOptions { format: lcc_engine::export::ExportFormat::Png, ..Default::default() }; + for (name, base) in [("one.png", 0usize), ("two.png", 40)] { + let img = lcc_raster::Rgba8::from_fn(16, 12, |x, y| [(x * 7 + base) as u8, (y * 11) as u8, 50, 255]); + std::fs::write(dir.join(name), lcc_engine::export::encode_image(&img, &o).unwrap()).unwrap(); + } + let mut photos = LccApp::new(lcc_engine::Session::new().with_fs(), Default::default()); + photos.session.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let ids: Vec = photos.session.catalog.photos().map(|p| p.id.0).collect(); + assert_eq!(ids.len(), 2); + photos.session.execute("library.select", &json!({"ids": ids})).unwrap(); + // a demo scene has no file to reveal + let mut demo = app(); + assert!(run_item(&mut demo, "app.showInFinder", Value::Null).is_err()); + assert!(!crate::menus::ui_enabled(&demo, "app.showInFinder")); + // several files at once where the host supports it + let shown = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let captured = shown.clone(); + photos.services.reveal_many = Some(Box::new(move |paths: &[String]| { + captured.lock().unwrap().extend(paths.iter().cloned()); + Ok(()) + })); + assert!(crate::menus::ui_enabled(&photos, "app.showInFinder")); + let r = run_item(&mut photos, "app.showInFinder", Value::Null).unwrap(); + assert_eq!(shown.lock().unwrap().len(), 2, "{r}"); + assert_eq!(r["paths"].as_array().map(Vec::len), Some(2)); + // without it, one photo is revealed, as before + let single = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let one = single.clone(); + photos.services.reveal_many = None; + photos.services.reveal = Some(Box::new(move |p: &str| { + one.lock().unwrap().push(p.to_string()); + Ok(()) + })); + run_item(&mut photos, "app.showInFinder", Value::Null).unwrap(); + assert_eq!(single.lock().unwrap().len(), 1); + } + #[test] fn find_missing_and_locate() { let dir = lcc_testkit::TempDir::new("lc-ui-missing"); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index de28c120ac..05571fbbba 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -15,6 +15,7 @@ pub type UiCommand = (&'static str, &'static str, Option<&'static str>, &'static /// The fork's UI commands and their dispatch (fork-owned). #[path = "menus_fork.rs"] mod fork; +pub(crate) use fork::updates_disabled_by_env; /// The "Edit → Language" entries, one per language in [`crate::i18n::Locale::ALL`], so a language /// has a matching menu command (also listed through the control channel). Tests check coverage. @@ -113,6 +114,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.people", "People", None, "View"), ("view.person", "Show Person", None, ""), ("people.category", "Face Category", None, ""), + ("person.sort", "Person Sort", None, ""), + ("people.buildThumbnails", "Build Face Thumbnails", None, "Library>Faces"), ("view.faceBoxes", "Face Boxes", None, "View>Loupe Info"), ("view.focusPoint", "Show Focus Point", Some("Alt+F"), "View>Loupe Info"), ("view.zoomToFocus", "Zoom to Focus Point", None, "View>Loupe Info"), @@ -373,6 +376,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("dialog.contactSheet", "Contact Sheet PDF…", None, "File>More Exports"), ("app.contactSheet", "Export Contact Sheet PDF", None, ""), ("photo.editInPhotoCraft", "Edit in PhotoCraft", Some("Cmd+Shift+E"), "Photo>Edit In"), + ("photo.editInDefault", "Edit in Default Editor", None, "Photo>Edit In"), ("photo.editInExternal", "Edit in Other Editor", Some("Cmd+Alt+E"), "Photo>Edit In"), ("dialog.editInPresets", "Edit In Presets…", None, "Photo>Edit In"), // {preset, mode?, action?}: one item of a saved Edit In preset's menu (Photo ▸ Edit In ▸ the @@ -1004,7 +1008,7 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option { app.leave_fullscreen_preview(); if app.ui.module == crate::module::ModuleId::Library && app.ui.view == ViewMode::Detail { - app.ui.view = if app.ui.grid_style.is_grid() { app.ui.grid_style } else { ViewMode::PhotoGrid }; + app.ui.view = grid_to_return_to(app); Ok(Value::Null) } else { app.run("view.loupe", json!({})) @@ -1147,6 +1151,31 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option { + // {sort}: how a person's page orders their faces (issue #1691), for a control surface or a script + let Some(sort) = p.get("sort").and_then(Value::as_str).and_then(crate::state::PersonSort::parse) else { + return Some(Err("person.sort: `sort` must be photo, oldest, newest, folder or faceSize".into())); + }; + app.ui.person_sort = sort; + app.caches.person_page = None; + Ok(json!({"sort": sort.id()})) + } + "people.buildThumbnails" => { + // {edge?}: the People view's tiles (or, on the Confirmed category, the person cards') at + // their current size, so the run fills the cache keys that view asks for; else the + // engine's own default (256), when no window says what a point is + let ppp = app.tasks.repaint.as_ref().map_or(1.0, |ctx| ctx.pixels_per_point()); + let points = if app.ui.view == ViewMode::People + && app.ui.person_page.is_none() + && app.ui.people_category == crate::state::PeopleCategory::Confirmed + { + crate::panels::people::card_edge(app.ui.thumb_size) + } else { + crate::panels::people::tile_edge(app.ui.thumb_size) + }; + let edge = p.get("edge").and_then(Value::as_u64).unwrap_or_else(|| ((points * ppp).ceil() as u64).max(1)); + app.run("faces.buildThumbnails", json!({"edge": edge})) + } "view.survey" => { app.leave_fullscreen_preview(); app.ui.view = ViewMode::Survey; @@ -1576,6 +1605,22 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option { + // as in Lightroom: in a grid Cmd+= opens the active photo in the loupe at Fit, and Cmd+- does nothing. + // With no active photo Cmd+= keeps the loupe's zoom step, silently (below). + if id == "view.zoomOut" { + Ok(Value::Null) + } else { + // the grid this came from is the one a + / − in the loupe returns to + let grid = app.ui.view; + let opened = app.run("view.loupe", json!({})); + if opened.is_ok() { + app.ui.grid_style = grid; + app.ui.zoom = Zoom::Fit; + } + opened + } + } "view.zoomIn" | "view.zoomOut" => { // the fixed levels 1:4 … 11:1 (state::ZOOM_LEVELS); out of the first one is Fit let cur = match app.ui.zoom { @@ -1589,11 +1634,24 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option { - // the bottom-bar slider's range, one `THUMB_SIZE_STEP` per call; {} → {size} + // the grids step by column or by row change (`next_thumb_size`), People by `THUMB_SIZE_STEP`; {} → {size} if !thumb_size_view(app) { - return Some(Err(format!("{id}: only in Photo Grid, Square Grid or People"))); + return Some(Err(format!("{id}: only in Photo Grid, Square Grid, People or the Library loupe"))); + } + // from the loupe the keys first go back to the grid last shown, so the change is seen at once + if app.ui.view == ViewMode::Detail { + app.leave_fullscreen_preview(); + app.ui.view = grid_to_return_to(app); } - let step = if id == "view.thumbSizeUp" { crate::state::THUMB_SIZE_STEP } else { -crate::state::THUMB_SIZE_STEP }; + let up = id == "view.thumbSizeUp"; + if matches!(app.ui.view, ViewMode::PhotoGrid | ViewMode::SquareGrid) { + // a grid step: one column in Square Grid, the next rearrangement in Photo Grid (`next_thumb_size`) + if let Some(size) = crate::panels::grid::next_thumb_size(app, up) { + app.ui.thumb_size = size; + } + return Some(Ok(json!({"size": app.ui.thumb_size}))); + } + let step = if up { crate::state::THUMB_SIZE_STEP } else { -crate::state::THUMB_SIZE_STEP }; app.ui.thumb_size = (app.ui.thumb_size + step).clamp(crate::state::THUMB_SIZE_MIN, crate::state::THUMB_SIZE_MAX); Ok(json!({"size": app.ui.thumb_size})) } @@ -1962,7 +2020,7 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option { // a folder kept in Local's sidebar (saved with the UI state); nothing on disk changes let Some(path) = p.get("path").and_then(Value::as_str) else { return Some(Err("local.addRoot needs a path".into())) }; - let abs = std::path::absolute(path).map(|a| a.to_string_lossy().trim_end_matches(['/', '\\']).to_string()).unwrap_or(path.into()); + let abs = std::path::absolute(path).map(|a| lcc_engine::import::browse_folder_string(&a)).unwrap_or(path.into()); let abs = if abs.is_empty() { path.to_string() } else { abs }; if !std::path::Path::new(&abs).is_dir() { return Some(Err(format!("{path}: not a folder"))); @@ -2110,7 +2168,8 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option { // Return commits a tool panel (crop, remove, red eye, masking): back to Edit use RightPanel::*; - if app.ui.dialog.is_none() && matches!(app.ui.right, Crop | Remove | RedEye | Masking) { + let no_dialog = app.ui.dialog.is_none(); + if no_dialog && matches!(app.ui.right, Crop | Remove | RedEye | Masking) { app.end_midi_interaction(); let _ = app.session.end_interaction(); app.ui.tool.clear(); @@ -2119,6 +2178,12 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option Option edit_in_default(app, &ctx, p), "photo.openOriginalInExternal" => open_original_in(app, &ctx, p), "photo.editInPreset" => crate::edit_in::run_preset(app, &ctx, p), "dialog.qualityScan" => { @@ -3731,7 +3797,7 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option crate::control::export_active(app, p), "photo.renderToDng" => return crate::render_dng_task::start(app, p), "photo.updateDngPreview" => return crate::dng_update_task::start(app, p), - "app.showInFinder" => show_in_finder(app), + "app.showInFinder" => show_in_finder(app, p), "app.showInFolders" => show_in_folders(app, p.get("id").and_then(Value::as_u64).map(lcc_catalog::PhotoId)), "app.openLogFolder" => open_log_folder(app), "app.website" | "app.github" | "app.help" | "app.feedback" | "app.discord" => { @@ -3755,9 +3821,16 @@ fn chosen_library_folder(app: &LccApp) -> Result { } } -/// Views whose bottom bar has the thumbnail-size slider and that draw tiles of that size. +/// Views whose bottom bar has the thumbnail-size slider and that draw tiles of that size, and the +/// Library loupe, where the size keys switch to the grid first. fn thumb_size_view(app: &LccApp) -> bool { matches!(app.ui.view, ViewMode::PhotoGrid | ViewMode::SquareGrid | ViewMode::People) + || (app.ui.module == crate::module::ModuleId::Library && app.ui.view == ViewMode::Detail) +} + +/// The grid a loupe returns to: the grid shown last (View ▸ Grid, the loupe toggle), else Photo Grid. +fn grid_to_return_to(app: &LccApp) -> ViewMode { + if app.ui.grid_style.is_grid() { app.ui.grid_style } else { ViewMode::PhotoGrid } } pub fn ui_enabled(app: &LccApp, id: &str) -> bool { @@ -3797,7 +3870,7 @@ pub fn ui_enabled(app: &LccApp, id: &str) -> bool { app.session.active().is_some() } "photo.tagFromTracklog" => app.session.active().is_some() && app.services.pick_tracklog.is_some(), - "photo.editInPhotoCraft" | "photo.editInExternal" | "photo.editInPreset" => { + "photo.editInPhotoCraft" | "photo.editInExternal" | "photo.editInDefault" | "photo.editInPreset" => { app.session.active().is_some() && app.services.open_with.is_some() } "app.exportPrevious" => app.session.active().is_some() && app.session.last_export.is_some(), @@ -3820,12 +3893,12 @@ pub fn ui_enabled(app: &LccApp, id: &str) -> bool { }) } "app.showInFinder" => { - app.services.reveal.is_some() + (app.services.reveal.is_some() || app.services.reveal_many.is_some()) && app .session - .active() - .and_then(|id| app.session.catalog.photo(id)) - .is_some_and(|p| matches!(p.source, lcc_engine::catalog::Source::File { .. })) + .selected() + .iter() + .any(|id| app.session.catalog.photo(*id).is_some_and(|p| matches!(p.source, lcc_engine::catalog::Source::File { .. }))) } "app.showInFolders" => show_in_folders_enabled(app, None), "app.openSamModelFolder" => app.session.segmenter.dir.is_some() && app.services.open_with.is_some(), @@ -4008,13 +4081,33 @@ fn open_log_folder(app: &mut LccApp) -> Result { Ok(json!({"path": path})) } -/// Reveal the active photo's original in the system file manager. -fn show_in_finder(app: &mut LccApp) -> Result { - let id = app.session.active().ok_or("no photo selected")?; - let path = match app.session.catalog.photo(id).map(|p| p.source.clone()) { - Some(lcc_engine::catalog::Source::File { path }) => path, - _ => return Err("this photo has no file (demo scene)".into()), +/// Reveal the selected photos' originals (`ids`/`id`, or the selection) in the system file +/// manager. Where the host selects several files in one window (`reveal_many`, Linux) every file +/// is shown; otherwise the active photo, or the first with a file (adapted from upstream #4653). +fn show_in_finder(app: &mut LccApp, p: &Value) -> Result { + let ids = app.session.targets(p).map_err(|e| e.to_string())?; + if ids.is_empty() { + return Err("no photo selected".into()); + } + let file_of = |app: &LccApp, id: lcc_catalog::PhotoId| match app.session.catalog.photo(id).map(|photo| &photo.source) { + Some(lcc_engine::catalog::Source::File { path }) => Some(path.clone()), + _ => None, }; + let paths: Vec = ids.iter().filter_map(|id| file_of(app, *id)).collect(); + if paths.is_empty() { + return Err("this photo has no file (demo scene)".into()); + } + if let Some(reveal_many) = app.services.reveal_many.as_mut() { + reveal_many(&paths)?; + return Ok(json!({"path": paths.first(), "paths": paths})); + } + let path = app + .session + .active() + .and_then(|id| file_of(app, id)) + .filter(|active| paths.contains(active)) + .or_else(|| paths.into_iter().next()) + .ok_or("no photo selected")?; let reveal = app.services.reveal.as_mut().ok_or("not available here")?; reveal(&path)?; Ok(json!({"path": path})) @@ -4060,10 +4153,6 @@ fn show_in_folders(app: &mut LccApp, id: Option) -> Result /// is reported in the result's `failed` (and a toast), not as an error. pub(crate) fn edit_in(app: &mut LccApp, ctx: &egui::Context, p: &Value, photocraft: bool) -> Result { // every way in (menu, shortcut, context menu, the control channel) says why nothing opened - edit_in_inner(app, ctx, p, photocraft).inspect_err(|e| app.toast_error(ctx, crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e))) -} - -fn edit_in_inner(app: &mut LccApp, ctx: &egui::Context, p: &Value, photocraft: bool) -> Result { let settings = &app.ui.settings; let (file, configured) = if photocraft { let path = settings.photocraft_path.trim(); @@ -4071,6 +4160,20 @@ fn edit_in_inner(app: &mut LccApp, ctx: &egui::Context, p: &Value, photocraft: b } else { (settings.external_file, settings.external_editor.clone()) }; + edit_in_inner(app, ctx, p, configured, file) + .inspect_err(|e| app.toast_error(ctx, crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e))) +} + +/// Photo ▸ Edit In ▸ Edit in Default Editor: the rendered copy goes to the operating system's +/// application for its file type (no program named), as Settings ▸ External Editing ▸ Default +/// editor's file choices say. +fn edit_in_default(app: &mut LccApp, ctx: &egui::Context, p: &Value) -> Result { + let file = app.ui.settings.default_file; + edit_in_inner(app, ctx, p, String::new(), file) + .inspect_err(|e| app.toast_error(ctx, crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e))) +} + +fn edit_in_inner(app: &mut LccApp, ctx: &egui::Context, p: &Value, configured: String, file: crate::state::EditFile) -> Result { let editor = p.get("app").and_then(Value::as_str).map_or(configured, str::to_string); if let Some(check) = app.services.check_editor.as_ref() { check(&editor)?; diff --git a/crates/ui-egui/src/menus_fork.rs b/crates/ui-egui/src/menus_fork.rs index 88e8d139b2..e3cf1f4666 100644 --- a/crates/ui-egui/src/menus_fork.rs +++ b/crates/ui-egui/src/menus_fork.rs @@ -332,11 +332,27 @@ pub(super) fn run(app: &mut LccApp, id: &str, p: &Value) -> Option_DISABLE_UPDATES` turned the updater off; the web build has no updater, so never. +pub(crate) fn updates_disabled_by_env() -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + lcc_engine::update::disabled_by_env() + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + /// Enabled state of the fork's modules' commands. pub(super) fn enabled(app: &LccApp, id: &str) -> Option { if crate::lrc_menus::is_coming_soon(id) { return Some(false); } + // a distro package turned updates off (`_DISABLE_UPDATES`, upstream #4663) + if id == "app.checkForUpdates" && updates_disabled_by_env() { + return Some(false); + } crate::module::enabled(app, id) .or_else(|| crate::catalog_ui::enabled(app, id)) .or_else(|| crate::timelapse_ui::enabled(app, id)) diff --git a/crates/ui-egui/src/modern_sources.rs b/crates/ui-egui/src/modern_sources.rs index c116e80376..3cd7a8ca70 100644 --- a/crates/ui-egui/src/modern_sources.rs +++ b/crates/ui-egui/src/modern_sources.rs @@ -6,6 +6,7 @@ //! //! Own design. +use crate::popup_typeahead::PopupItems; use egui::{Id, Rect, RichText, Sense, pos2, vec2}; use lcc_catalog::{Album, AlbumId}; use lcc_engine::LibrarySource; @@ -164,7 +165,7 @@ fn picker(app: &mut LccApp, ctx: &egui::Context, at: egui::Pos2) { // full width, its text at the left (so the nesting shows) ui.with_layout(egui::Layout::top_down_justified(egui::Align::LEFT), |ui| { ui.spacing_mut().button_padding.y = 8.0; - ui.selectable_label(on, RichText::new(&it.label).size(15.0)) + ui.pick_label(on, RichText::new(&it.label).size(15.0)) }) .inner }) diff --git a/crates/ui-egui/src/onboarding.rs b/crates/ui-egui/src/onboarding.rs index 21d5770835..aa841830ea 100644 --- a/crates/ui-egui/src/onboarding.rs +++ b/crates/ui-egui/src/onboarding.rs @@ -25,6 +25,7 @@ //! only once; Help ▸ Getting Started… (`app.gettingStarted`) opens it again at any time. The tour's //! pictures are drawn in code from the app's own icons (original work). +use crate::popup_typeahead::PopupItems; use egui::{RichText, Ui}; use serde_json::{Value, json}; @@ -595,7 +596,7 @@ fn interface_page(app: &mut LccApp, ui: &mut Ui) -> bool { for k in crate::theme::ThemeKind::ALL { let s = &app.ui.settings; let on = if k.is_dark() { s.dark_theme.kind() == k } else { s.light_theme.kind() == k }; - let r = ui.selectable_label(on, tr(k.label())); + let r = ui.pick_label(on, tr(k.label())); register(ui.ctx(), format!("button:wizardTheme.{}", k.id()), r.rect); if r.clicked() { let _ = app.run("view.theme", json!({"theme": k.id()})); @@ -617,7 +618,7 @@ fn interface_page(app: &mut LccApp, ui: &mut Ui) -> bool { let combo = egui::ComboBox::from_id_salt("wizardLanguage").selected_text(current).width(220.0).height(320.0).show_ui(ui, |ui| { for (i, language) in crate::i18n::Locale::for_picker().into_iter().enumerate() { let label = crate::panels::settings::language_label(ui.ctx(), language); - let r = ui.selectable_value(&mut app.ui.language, language, label); + let r = ui.pick_value(&mut app.ui.language, language, label); register(ui.ctx(), format!("button:wizardLanguage-{i}"), r.rect); } }); diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index ba6f70dce9..81ec6da05b 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -1,5 +1,6 @@ //! The bottom bar: view modes, sort, rating/flags pill, copy/paste settings, zoom and view toggles. +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use lcc_catalog::Flag; use serde_json::json; @@ -98,7 +99,7 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { ); egui::Popup::menu(&more).show(|ui| { for &(id, _, mode, label) in VIEW_MODES { - if ui.selectable_label(app.ui.view == mode, crate::i18n::tr(label)).clicked() { + if ui.pick_label(app.ui.view == mode, crate::i18n::tr(label)).clicked() { let _ = app.run(&format!("view.{id}"), json!({})); ui.close(); } @@ -365,7 +366,7 @@ fn right_side(app: &mut LccApp, ui: &mut egui::Ui, full: Rect, compact_zoom: boo ("200%", Zoom::Percent(200.0)), ("400%", Zoom::Percent(400.0)), ] { - if ui.selectable_label(app.ui.zoom == z, crate::i18n::tr(label)).clicked() { + if ui.pick_label(app.ui.zoom == z, crate::i18n::tr(label)).clicked() { app.ui.zoom = z; app.ui.pan = (0.5, 0.5); } @@ -468,8 +469,11 @@ fn thumb_slider(app: &mut LccApp, child: &mut egui::Ui, t: &Tokens) { let p = child.painter(); let y = r.center().y; p.line_segment([pos2(r.left(), y), pos2(r.right(), y)], egui::Stroke::new(2.0, t.track)); - let (min, max) = (crate::state::THUMB_SIZE_MIN, crate::state::THUMB_SIZE_MAX); - let f = (app.ui.thumb_size - min) / (max - min); + // the top is the grid's own largest size (Photo Grid stops where only its last row would still grow) + let min = crate::state::THUMB_SIZE_MIN; + let max = crate::panels::grid::thumb_max(app).max(min); + // a grid that never changes with the size (top == bottom) has its knob at the top + let f = if max > min { ((app.ui.thumb_size - min) / (max - min)).clamp(0.0, 1.0) } else { 1.0 }; let x = r.left() + f * r.width(); p.rect_filled(Rect::from_center_size(pos2(x, y), vec2(3.0, 14.0)), 1.0, t.thumb_hover); if let Some(pp) = resp.interact_pointer_pos() @@ -482,7 +486,7 @@ fn thumb_slider(app: &mut LccApp, child: &mut egui::Ui, t: &Tokens) { fn click_zoom_menu(app: &mut LccApp, ui: &mut egui::Ui) { for pct in crate::state::CLICK_ZOOMS { - if ui.selectable_label(app.ui.click_zoom == pct, format!("{pct}%")).clicked() { + if ui.pick_label(app.ui.click_zoom == pct, format!("{pct}%")).clicked() { let _ = app.run("view.clickZoom", json!({"ratio": pct / 100})); } } @@ -503,14 +507,15 @@ fn sort_menu(app: &mut LccApp, ui: &mut egui::Ui) { ("Random", Random, "random"), ("Quality", Quality, "quality"), ] { - if ui.selectable_label(cur.key == key, crate::i18n::tr(label)).clicked() { + if ui.pick_label(cur.key == key, crate::i18n::tr(label)).clicked() { let _ = app.run("library.sort", json!({"key": k})); } } - // Custom Order: the order set by hand in a regular album (drag photos in the grid) - let in_album = crate::panels::grid::custom_order_album(app).is_some(); - ui.add_enabled_ui(in_album, |ui| { - if ui.selectable_label(cur.key == Custom && in_album, crate::i18n::tr("Custom Order")).clicked() { + // Custom Order: the order set by hand in a regular album or in a folder of the Folders panel shown on its + // own (drag photos in the grid) + let can_custom = crate::panels::grid::custom_order_source(app).is_some(); + ui.add_enabled_ui(can_custom, |ui| { + if ui.pick_label(cur.key == Custom && can_custom, crate::i18n::tr("Custom Order")).clicked() { let _ = app.run("library.sort", json!({"key": "custom"})); } }); @@ -528,10 +533,10 @@ fn sort_menu(app: &mut LccApp, ui: &mut egui::Ui) { ui.separator(); // a shuffle has no direction worth choosing ui.add_enabled_ui(cur.key != Random, |ui| { - if ui.selectable_label(cur.key != Random && cur.ascending, crate::i18n::tr("Ascending")).clicked() { + if ui.pick_label(cur.key != Random && cur.ascending, crate::i18n::tr("Ascending")).clicked() { let _ = app.run("library.sort", json!({"ascending": true})); } - if ui.selectable_label(cur.key != Random && !cur.ascending, crate::i18n::tr("Descending")).clicked() { + if ui.pick_label(cur.key != Random && !cur.ascending, crate::i18n::tr("Descending")).clicked() { let _ = app.run("library.sort", json!({"ascending": false})); } }); @@ -544,7 +549,7 @@ fn sort_menu(app: &mut LccApp, ui: &mut egui::Ui) { ("Year", GroupBy::Year, "year"), ("None", GroupBy::None, "none"), ] { - if ui.selectable_label(cur.group == g, crate::i18n::tr(label)).clicked() { + if ui.pick_label(cur.group == g, crate::i18n::tr(label)).clicked() { let _ = app.run("library.sort", json!({"group": k})); } } diff --git a/crates/ui-egui/src/panels/cells.rs b/crates/ui-egui/src/panels/cells.rs index c3f363f3e5..f3ec2993b4 100644 --- a/crates/ui-egui/src/panels/cells.rs +++ b/crates/ui-egui/src/panels/cells.rs @@ -95,6 +95,16 @@ pub fn extras(app: &mut LccApp, ui: &egui::Ui, id: PhotoId, r: Rect, square: boo if app.session.catalog.is_vignetting_reference(id) { badges.push(("vignettingReference", Icon::Radial, crate::i18n::tr("Vignetting reference").to_string(), Color32::WHITE)); } + // the companion JPEG kept beside this raw (issue #1692): one photo per pair; the Info + // panel names the file + if p.companion_jpeg.is_some() { + badges.push(( + "companion", + Icon::Photos, + crate::i18n::tr("Has a companion JPEG (click to open the Info panel)").to_string(), + Color32::WHITE, + )); + } } if app.session.source == lcc_engine::LibrarySource::Folder && p.in_library() { badges.push(("inLibrary", Icon::Check, crate::i18n::tr("In catalog").to_string(), Color32::WHITE)); @@ -135,6 +145,7 @@ pub fn extras(app: &mut LccApp, ui: &egui::Ui, id: PhotoId, r: Rect, square: boo let panel = match key { "keywords" => Some("panel.keywords"), "metadataConflict" => Some("panel.info"), + "companion" => Some("panel.info"), "cropped" => Some("panel.crop"), _ => None, }; diff --git a/crates/ui-egui/src/panels/classic_crop.rs b/crates/ui-egui/src/panels/classic_crop.rs index 69f155087d..3a83ed778e 100644 --- a/crates/ui-egui/src/panels/classic_crop.rs +++ b/crates/ui-egui/src/panels/classic_crop.rs @@ -170,10 +170,11 @@ pub(crate) fn transform_body(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId) { }); } -/// Upright's controls, shared by the Crop panel's Geometry and the Edit panel's Transform (#1274): -/// a status row that names the mode in use (no separate "Upright" heading: the panel says what it -/// is) with the Guided Upright tool's icon and Update at its right, then the six modes. The status -/// row keeps one height whatever the mode, so switching modes never moves the buttons under it. +/// Upright's controls of the Edit panel's Transform (#1274): a status row that names the mode in use (no +/// separate "Upright" heading: the panel says what it is) with the Guided Upright tool's icon and Update at +/// its right, then the six modes. The status row keeps one height whatever the mode, so switching modes never +/// moves the buttons under it. The icon and the Guided mode arm the tool where they are: the guides draw +/// over the Edit panel, without opening Crop & Straighten first (`detail::guided_tool`, issue #1684). pub(crate) fn upright_controls(app: &mut LccApp, ui: &mut egui::Ui, d: &lcc_develop::DevelopSettings) { use lcc_develop::Upright; let modes = [ diff --git a/crates/ui-egui/src/panels/connections.rs b/crates/ui-egui/src/panels/connections.rs index daee364cf2..6835287a07 100644 --- a/crates/ui-egui/src/panels/connections.rs +++ b/crates/ui-egui/src/panels/connections.rs @@ -9,6 +9,7 @@ //! Connect hands it to the secret store; it is never shown again, logged or saved in settings. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::{Arc, Mutex, PoisonError}; @@ -1963,7 +1964,7 @@ fn sync_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, i: usize, id: & ui, |ui| { for (k, l) in DIRECTIONS { - ui.selectable_value(&mut d2, k.to_string(), crate::i18n::tr(l)); + ui.pick_value(&mut d2, k.to_string(), crate::i18n::tr(l)); } }, ); @@ -1971,7 +1972,7 @@ fn sync_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, i: usize, id: & ui, |ui| { for (k, l) in POLICIES { - ui.selectable_value(&mut p2, k.to_string(), crate::i18n::tr(l)); + ui.pick_value(&mut p2, k.to_string(), crate::i18n::tr(l)); } }, ); @@ -1993,8 +1994,8 @@ fn sync_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, i: usize, id: & .width(90.0) .selected_text(crate::i18n::tr(if fav == "fiveStars" { "5 stars" } else { "Pick" })) .show_ui(ui, |ui| { - ui.selectable_value(&mut fav, "pick".to_string(), crate::i18n::tr("Pick")); - ui.selectable_value(&mut fav, "fiveStars".to_string(), crate::i18n::tr("5 stars")); + ui.pick_value(&mut fav, "pick".to_string(), crate::i18n::tr("Pick")); + ui.pick_value(&mut fav, "fiveStars".to_string(), crate::i18n::tr("5 stars")); }); if fav != before { cfg_patch.insert("favorite".into(), json!(fav)); diff --git a/crates/ui-egui/src/panels/controls.rs b/crates/ui-egui/src/panels/controls.rs index 97725cb170..deca9cd8e7 100644 --- a/crates/ui-egui/src/panels/controls.rs +++ b/crates/ui-egui/src/panels/controls.rs @@ -13,6 +13,7 @@ //! timing, OSD, plugin colours, tool contexts, Auto Sync, tool switching). use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Color32, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2}; use lcc_surface as ls; use ls::{Binding, PageGroup}; @@ -237,7 +238,7 @@ fn top_bar(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { let current = app.surface.settings().profile.clone(); let r = egui::ComboBox::from_id_salt("surfaceProfile").selected_text(¤t).width(140.0).show_ui(ui, |ui| { for n in &names { - if ui.selectable_label(*n == current, n).clicked() && *n != current { + if ui.pick_label(*n == current, n).clicked() && *n != current { let _ = app.run("surface.profile", json!({"profile": n})); app.surface.editor.page = None; } @@ -405,7 +406,7 @@ fn layout_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, max_h: f32) { }; let r = egui::ComboBox::from_id_salt("surfaceToolPage").selected_text(text).show_ui(ui, |ui| { for p in &tools { - if ui.selectable_label(p.name == page_key, when(&p.name)).clicked() { + if ui.pick_label(p.name == page_key, when(&p.name)).clicked() { app.surface.editor.page = Some(p.name.clone()); } } @@ -504,7 +505,7 @@ fn loupedeck_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, max_h: f32 .width(240.0) .show_ui(ui, |ui| { for (i, (name, path)) in found.iter().enumerate() { - if ui.selectable_label(i == pick, name).on_hover_text(path.to_string_lossy()).clicked() { + if ui.pick_label(i == pick, name).on_hover_text(path.to_string_lossy()).clicked() { pick = i; } } @@ -1080,7 +1081,7 @@ fn editor_panel(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, page: &str, max let r = crate::widgets::combo_box("surfacePreset").width(220.0).selected_text(text).show_ui(ui, |ui| { for p in &app.session.presets { let label = if p.group.is_empty() { p.name.clone() } else { format!("{} ▸ {}", p.group, p.name) }; - let item = ui.selectable_label(chosen.as_deref() == Some(p.id.as_str()), label); + let item = ui.pick_label(chosen.as_deref() == Some(p.id.as_str()), label); register(ui.ctx(), format!("button:surfacePreset-{}", p.id), item.rect); if item.clicked() { picked = Some(p.id.clone()); @@ -1357,14 +1358,14 @@ fn contexts(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { let r = egui::ComboBox::from_id_salt(format!("surfaceContext-{key}")) .selected_text(current.clone().unwrap_or_else(|| tr("None").to_string())) .show_ui(ui, |ui| { - if ui.selectable_label(current.is_none(), tr("None")).clicked() { + if ui.pick_label(current.is_none(), tr("None")).clicked() { let k = key.to_string(); edit_profile(app, |p| { p.contexts.remove(&k); }); } for pg in &profile.pages { - if ui.selectable_label(current.as_deref() == Some(&pg.name), &pg.name).clicked() { + if ui.pick_label(current.as_deref() == Some(&pg.name), &pg.name).clicked() { let (k, n) = (key.to_string(), pg.name.clone()); edit_profile(app, |p| { p.contexts.insert(k, vec![n]); @@ -1621,7 +1622,7 @@ fn feel(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, "Value", |ui| { let r = egui::ComboBox::from_id_salt("surfaceTuningTarget").selected_text(label).show_ui(ui, |ui| { for s in ls::targets::all_targets() { - if ui.selectable_label(s.id == target, format!("{}: {}", tr(s.group), tr(s.label))).clicked() { + if ui.pick_label(s.id == target, format!("{}: {}", tr(s.group), tr(s.label))).clicked() { app.surface.editor.tuning_target = s.id.clone(); } } diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index 149d51441a..87af9e7806 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -7,6 +7,7 @@ use crate::i18n::{tr, tr_format}; use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::RichText; use lcc_catalog::PhotoId; use lcc_engine::denoise::PhotoState; @@ -461,7 +462,7 @@ fn work_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, list: &Value) { let mut choice = current; crate::widgets::combo_box("denoise-cache-limit").selected_text(tr_format!("{size} GB", size = current)).show_ui(ui, |ui| { for gb in CACHE_LIMITS { - ui.selectable_value(&mut choice, gb, tr_format!("{size} GB", size = gb)); + ui.pick_value(&mut choice, gb, tr_format!("{size} GB", size = gb)); } }); if choice != current { diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index f30138fec1..ce18053ea8 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -1065,6 +1065,22 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { let browsing = crate::import_tab::showing(app); let right = if fullscreen || browsing { RightPanel::None } else { app.ui.right }; let crop_tool = right == RightPanel::Crop; + // Guided Upright armed from the Edit panel's Transform section (its Guided mode or its icon) draws over that + // panel, as it does over the Crop panel (issue #1684). The tool lasts as long as the section is drawn: a + // folded section, or a closed Modern card, puts it down rather than leaving a crosshair over the photo with + // no switch to click (`app.widgets` is the panel pass before, where the icon is registered). A clip has no + // Guided Upright. + let guided = right == RightPanel::Edit + && app.ui.tool == "guidedUpright" + && app.widgets.iter().any(|(w, _)| w == "icon:uprightGuidedTool") + && !crate::video_ui::photo_is_video(app, id); + if app.ui.tool == "guidedUpright" && right == RightPanel::Edit && !guided { + app.ui.tool.clear(); + app.ui.selected_guide = None; + if matches!(app.gesture, Some(Gesture::Guide { .. } | Gesture::GuideEndpoint { .. })) { + app.gesture = None; + } + } let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &d, !crop_tool, photo.embedded_lens.as_deref()); let aspect = frame.aspect() as f32; let ppp = ui.ctx().pixels_per_point(); @@ -1116,8 +1132,8 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { .map(|tex| tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32); // Follow the texture only where it really differs (an unsupported raw's embedded JPEG with // another crop): a texture's whole-pixel size is a little off the exact aspect, and the crop - // tool's overlays need the frame's own geometry. - let display_aspect = visible_texture_aspect.filter(|a| !crop_tool && (a / aspect - 1.0).abs() > 0.02).unwrap_or(aspect); + // tool's overlays (and the guides drawn over the Edit panel) need the frame's own geometry. + let display_aspect = visible_texture_aspect.filter(|a| !(crop_tool || guided) && (a / aspect - 1.0).abs() > 0.02).unwrap_or(aspect); let resp = ui.interact(canvas, egui::Id::new("loupe"), Sense::click_and_drag()); crate::widgets::announce(&resp, crate::i18n::tr("Photo")); let mut target_rect = fit_rect(main_area, display_aspect, app.ui.zoom, native, ppp, app.ui.pan); @@ -1932,12 +1948,16 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { } } // Cursor selection must also run on gesture frames, when tool input is suppressed. - if !matches!(right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye) { + if !guided && !matches!(right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye) { general_cursor(app, ui, &resp, img_rect, main_area); } if !navigating { match right { RightPanel::Crop => crop_overlay(app, ui, &resp, &map, &frame, &d, id), + // the Transform section's Guided Upright: the guides over the Edit panel, no crop box + RightPanel::Edit if guided => { + guided_tool(app, ui, &resp, &map, &frame, &d, id); + } RightPanel::Masking => mask_overlay(app, ui, &resp, &map, &d), RightPanel::Remove => { remove_overlay(app, ui, &resp, &map, &d); @@ -3615,13 +3635,7 @@ pub(crate) fn click_zoom_and_pan(app: &mut LccApp, resp: &egui::Response, img: R // ------------------------------------------------------------------------ crop fn crop_overlay(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, frame: &Frame, d: &DevelopSettings, id: PhotoId) { - // the selected guide belongs to this photo and to the Guided Upright tool, and to a guide - // that still exists (a Delete after the last one leaves the selection behind) - if app.ui.tool != "guidedUpright" || app.ui.selected_guide.is_some_and(|(photo, i)| photo != id.0 || i >= d.geometry.guides.len()) { - app.ui.selected_guide = None; - } - if app.ui.tool == "guidedUpright" { - guided_overlay(app, ui, resp, map, frame, d, id); + if guided_tool(app, ui, resp, map, frame, d, id) { return; } if app.ui.tool == "straighten" { @@ -4013,6 +4027,20 @@ fn angle_readout(ui: &egui::Ui, at: Pos2, angle: f64, bounds: Rect) { register(ui.ctx(), "cropAngleReadout", rect); } +/// Guided Upright while its tool is up, over the Crop panel or the Edit panel's Transform section +/// (issue #1684); false with the tool down. The selected guide belongs to this photo and to a guide +/// that still exists (a Delete after the last one leaves the selection behind). +fn guided_tool(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, frame: &Frame, d: &DevelopSettings, id: PhotoId) -> bool { + if app.ui.selected_guide.is_some_and(|(photo, i)| photo != id.0 || i >= d.geometry.guides.len()) { + app.ui.selected_guide = None; + } + if app.ui.tool != "guidedUpright" { + return false; + } + guided_overlay(app, ui, resp, map, frame, d, id); + true +} + /// Guided Upright: draw up to four guides along lines that should be vertical or horizontal. Guides are /// stored in lens-corrected (pre-perspective) coordinates, so they stay attached to the image as it warps. fn guided_overlay(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, frame: &Frame, d: &DevelopSettings, id: PhotoId) { @@ -4039,7 +4067,8 @@ fn guided_overlay(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, ma draw(sa, sb, selected == Some(i)); } ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); - // double-click on the photo finishes the tool, as in the crop tool (same as Return / Done); issue #297 + // double-click on the photo finishes the tool, as in the crop tool (same as Return / Done); issue #297. + // Over the Edit panel Done only puts the tool down (menus.rs `tool.done`) // A press starts a new guide right away (below), so the second click of a double-click has // already begun one: a guide that never left its press point is that click, not a drawn guide. let here = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).map(|q| map.norm(q)); @@ -4977,7 +5006,7 @@ fn mask_overlay(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, map: app.ui.tool.clear(); } if resp.drag_started() && d.masks.iter().find(|m| m.id == mid).and_then(|m| m.components.get(ci)).is_some() { - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + let _ = app.run("develop.beginInteraction", json!({"label": crate::region::SHARP_DRAG})); if let Some(original_shape) = current_shape(app, mid, ci) .or_else(|| d.masks.iter().find(|m| m.id == mid).and_then(|m| m.components.get(ci)).map(|c| c.shape.clone())) { @@ -5162,7 +5191,7 @@ fn mask_overlay(app: &mut LccApp, ui: &mut egui::Ui, resp: &egui::Response, map: let _ = app.run("mask.select", json!({"id": mask})); } app.ui.active_mask_component = Some(comp); - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + let _ = app.run("develop.beginInteraction", json!({"label": crate::region::SHARP_DRAG})); // (read after it begins: an old mask is on the photo from then on, in its coordinates) if let Some(original_shape) = current_shape(app, mask, comp) .or_else(|| d.masks.iter().find(|m| m.id == mask).and_then(|m| m.components.get(comp)).map(|c| c.shape.clone())) @@ -5421,7 +5450,7 @@ fn mask_keys(app: &mut LccApp, ui: &mut egui::Ui, map: &CanvasMap, d: &DevelopSe if app.session.active_mask != Some(mid) { let _ = app.run("mask.select", json!({"id": mid})); } - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + let _ = app.run("develop.beginInteraction", json!({"label": crate::region::SHARP_DRAG})); // (read after it begins: an old mask is on the photo from then on, in its coordinates) let (shape, map) = match (current_shape(app, mid, ci), current_on_photo(app, mid)) { (Some(s), Some(on)) => (s, map.for_mask(on)), @@ -6768,8 +6797,9 @@ fn filmstrip_strip(app: &mut LccApp, ui: &mut egui::Ui, r: Rect) { } // in the Map module photos are dragged from the strip onto the map to geotag them let map = app.ui.module == crate::module::ModuleId::Map; - // in a regular album they are dragged along the strip to put them in Custom Order - let reorder = !map && super::grid::custom_order_album(app).is_some(); + // in a regular album, or in a folder of the Folders panel shown on its own, they are dragged along + // the strip to put them in Custom Order + let reorder = !map && super::grid::custom_order_source(app).is_some(); // cells drawn ahead of the scroll (off view, under the side panels) take no clicks or // keyboard focus: Tab never lands on a thumbnail nobody can see let sense = if !local.intersects(vp) { diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index f8ab02db8f..47956236a7 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -1,6 +1,7 @@ //! Modal dialogs (new album, rename, create preset, choose settings to copy, export, about, shortcuts). use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use lcc_develop::{ControlSpec, Section, SettingsGroup, SettingsPick, Track}; use serde_json::json; @@ -638,7 +639,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { ("rescan", "Rescan and Merge"), ("reset", "Reset All Face Data"), ] { - let r = ui.selectable_value(mode, value.to_string(), crate::i18n::tr(label)); + let r = ui.pick_value(mode, value.to_string(), crate::i18n::tr(label)); crate::widgets::register(ui.ctx(), format!("faceMaintenance:mode:{value}"), r.rect); } }); @@ -968,8 +969,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { }); } Dialog::SmartRules { id, name, rules, .. } => { - let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Name")); - crate::widgets::register(ui.ctx(), "field:smartName", r.rect); + confirm_field(ui, crate::text_field::TextField::singleline("field:smartName", name).hint(crate::i18n::tr("Name")).width(f32::INFINITY)); ui.add_space(6.0); // the folder an album made from a folder view carries is not in the editor, but it counts let folder = id.and_then(|id| app.session.catalog.album(lcc_catalog::AlbumId(id))).and_then(|a| a.smart.as_deref().and_then(|f| f.library_folder.clone())); @@ -1022,8 +1022,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { let params = match mode.as_str() { "set" => { field(ui, "New time", |ui| { - let r = ui.add(egui::TextEdit::singleline(time).hint_text("2026-09-30 14:05:00 · 1983-04 · 1983").desired_width(f32::INFINITY)); - crate::widgets::register(ui.ctx(), "field:captureTime", r.rect); + confirm_field(ui, crate::text_field::TextField::singleline("field:captureTime", time).hint("2026-09-30 14:05:00 · 1983-04 · 1983").label(crate::i18n::tr("New time")).width(f32::INFINITY)); }); // several photos: give them all this time, rather than move them by the active photo's change if n > 1 { @@ -1128,13 +1127,12 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { field(ui, &colour, |ui| { let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); ui.painter().circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l)); - let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr(&colour)).desired_width(f32::INFINITY)), crate::i18n::tr(&colour)); - crate::widgets::register(ui.ctx(), format!("field:labelName-{}", colour.to_lowercase()), te.rect); + let widget = format!("field:labelName-{}", colour.to_lowercase()); + confirm_field(ui, crate::text_field::TextField::singleline(&widget, name).hint(crate::i18n::tr(&colour)).label(crate::i18n::tr(&colour)).width(f32::INFINITY)); }); } field(ui, "Save as set", |ui| { - let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(save_as).hint_text(crate::i18n::tr("Optional name")).desired_width(f32::INFINITY)), crate::i18n::tr("Save as set")); - crate::widgets::register(ui.ctx(), "field:labelSetName", te.rect); + confirm_field(ui, crate::text_field::TextField::singleline("field:labelSetName", save_as).hint(crate::i18n::tr("Optional name")).label(crate::i18n::tr("Save as set")).width(f32::INFINITY)); }); crate::dialog_frame::note(ui, egui::RichText::new(crate::i18n::tr("Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.")) @@ -1149,12 +1147,11 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { Dialog::Rename { template, start, texts } => { let n = app.session.selected().len(); crate::dialog_frame::note(ui, egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim)); - let template_id = egui::Id::new("rename-template"); + let template_id = crate::text_field::id("field:renameTemplate"); let tags_open = field(ui, "Template", |ui| { ui.spacing_mut().item_spacing.x = 4.0; let w = crate::import::tag_field_width(ui); - let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(template).id(template_id).hint_text("{name}").desired_width(w)), crate::i18n::tr("Template")); - crate::widgets::register(ui.ctx(), "field:renameTemplate", r.rect); + confirm_field(ui, crate::text_field::TextField::singleline("field:renameTemplate", template).hint("{name}").label(crate::i18n::tr("Template")).width(w)); crate::import::tag_toggle(ui, "renameTemplate") }); if tags_open { @@ -1280,7 +1277,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { } Dialog::CreatePreset { name, group, groups } => { field(ui, "Preset name", |ui| { - crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Preset name")).desired_width(f32::INFINITY)), crate::i18n::tr("Preset name")); + confirm_field(ui, crate::text_field::TextField::singleline("field:presetName", name).hint(crate::i18n::tr("Preset name")).width(f32::INFINITY)); }); // the user's groups in a list, and New Group… for a name typed in (LR-PRE-CREATE) let mut known_groups: Vec = @@ -1294,16 +1291,14 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { let typing = !known_groups.iter().any(|g| g == group.trim()); field(ui, "Group", |ui| { if typing { - let r = ui.add(egui::TextEdit::singleline(group).hint_text(crate::i18n::tr("New group name")).desired_width(f32::INFINITY)); - crate::widgets::register(ui.ctx(), "field:presetNewGroup", r.rect); - crate::widgets::named(r, crate::i18n::tr("Group")); + confirm_field(ui, crate::text_field::TextField::singleline("field:presetNewGroup", group).hint(crate::i18n::tr("New group name")).label(crate::i18n::tr("Group")).width(f32::INFINITY)); } else { let combo = egui::ComboBox::from_id_salt("presetGroupCombo").selected_text(group.as_str()).width(ui.available_width()).show_ui(ui, |ui| { for g in &known_groups { - ui.selectable_value(group, g.clone(), g.as_str()); + ui.pick_value(group, g.clone(), g.as_str()); } ui.separator(); - if ui.selectable_label(false, crate::i18n::tr("New Group…")).clicked() { + if ui.pick_label(false, crate::i18n::tr("New Group…")).clicked() { group.clear(); } }); @@ -1330,8 +1325,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { }); } field(ui, "Folder name", |ui| { - let r = ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Folder name")).desired_width(f32::INFINITY)); - crate::widgets::named(r, crate::i18n::tr("Folder name")); + confirm_field(ui, crate::text_field::TextField::singleline("field:presetFolderName", name).hint(crate::i18n::tr("Folder name")).width(f32::INFINITY)); }); } Dialog::CopySettings { groups, masks_off } => { @@ -1383,9 +1377,10 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { let n = app.session.selected().len(); ui.label(crate::i18n::tr_format!("{n} selected photos · {pages} pages", n = n, pages = n.div_ceil(options.columns * options.rows))); field(ui, "Paper", |ui| { - crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| { - ui.selectable_value(&mut options.paper, "a4".into(), "A4"); - ui.selectable_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter")); + let shown = if options.paper == "letter" { crate::i18n::tr("Letter") } else { "A4" }; + crate::widgets::combo_box("contactSheetPaper").selected_text(shown).show_ui(ui, |ui| { + ui.pick_value(&mut options.paper, "a4".into(), "A4"); + ui.pick_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter")); }); }); crate::dialog_frame::checkbox(ui, &mut options.landscape, crate::i18n::tr("Landscape")); @@ -1412,7 +1407,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { let shown = crate::timelapse_ui::SIZES.iter().find(|s| s.0 == size.as_str()).map_or(size.as_str(), |s| s.1).to_string(); let c = egui::ComboBox::from_id_salt("timelapseSize").selected_text(shown).show_ui(ui, |ui| { for (v, l) in crate::timelapse_ui::SIZES { - ui.selectable_value(size, v.to_string(), *l); + ui.pick_value(size, v.to_string(), *l); } }); crate::widgets::register(ui.ctx(), "combo:timelapseSize", c.response.rect); @@ -1784,7 +1779,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { for (p, b) in app.session.all_export_presets() { let o = lcc_engine::export::ExportOptions::from_json(&p.params); if let Some(w) = o.watermark - && ui.selectable_label(preset_name == &p.name, crate::i18n::builtin_label(&p.name, b)).clicked() + && ui.pick_label(preset_name == &p.name, crate::i18n::builtin_label(&p.name, b)).clicked() { chosen_wm = Some(w); chosen_name = Some(p.name); @@ -1818,7 +1813,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { { wm.image = f; } - crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut wm.image).hint_text("logo.png").desired_width(ui.available_width())), crate::i18n::tr("Image")); + confirm_field(ui, crate::text_field::TextField::singleline("field:watermarkImage", &mut wm.image).hint("logo.png").label(crate::i18n::tr("Image")).width(ui.available_width())); }); }); let mut width = wm.image_width as f64 * 100.0; @@ -1828,7 +1823,9 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { } else { choices(ui, app.ui.language.tr("Text direction"), "watermarkDialogOrientation", &[(false, app.ui.language.tr("Horizontal text")), (true, app.ui.language.tr("Vertical text"))], &mut wm.vertical); field(ui, "Text", |ui| { - crate::widgets::named(ui.add(egui::TextEdit::multiline(&mut wm.text).desired_rows(2).hint_text(crate::i18n::tr("© Your Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Text")) + let r = crate::widgets::named(ui.add(egui::TextEdit::multiline(&mut wm.text).desired_rows(2).hint_text(crate::i18n::tr("© Your Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Text")); + crate::widgets::register(ui.ctx(), "field:watermarkText", r.rect); + r }); } // a 3 × 3 grid laid out like the corners, edges and centre it picks (ids as before: @@ -2068,6 +2065,10 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { && !matches!(&dlg, Dialog::SmartRules { id, rules, .. } if !rules.check_for(&app.session.catalog, id.map(lcc_catalog::AlbumId)).is_empty()) // a camera profile waits for its chart photos and their corners && !matches!(&dlg, Dialog::ChartProfile { opts } if !crate::chart_profile::can_build(app, opts))); + // Return in a field of a dialog with several: the same as its button, when it's enabled + if !informational && can_confirm && field_returned(ctx) { + confirm = true; + } let primary = !informational && can_confirm && confirm_style(&dlg) == ConfirmStyle::Primary; use crate::button::{Button, Kind}; // (each kind of dialog its own buttons: the keyboard's place doesn't carry from a @@ -3480,9 +3481,7 @@ pub(crate) fn export_screen(app: &mut LccApp, ctx: &egui::Context) { let t = Tokens::get(ctx); let screen = ctx.content_rect(); let roomy = screen.width() >= crate::settings_screen::ROOMY; - let mut cancel = !egui::Popup::is_any_open(ctx) - && !ctx.egui_wants_keyboard_input() - && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); + let mut cancel = crate::dialog_frame::esc_closes(false, app.text_focus, ctx); let mut go = false; let n = export_targets(app).len().max(1); // last frame's section tops, for the rail's highlight @@ -3688,7 +3687,10 @@ pub(crate) fn export_screen(app: &mut LccApp, ctx: &egui::Context) { app.ui.dialog = None; return; } - if go && let Some(dlg) = now { + // Return in one of the settings' text fields presses Export too + if (go || field_returned(ctx)) + && let Some(dlg) = now + { match confirm_dialog(app, &dlg) { Ok(_) => { if app.ui.dialog.as_ref() == Some(&dlg) { @@ -3734,7 +3736,7 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm ui.separator(); } builtin = b; - if ui.selectable_label(cur_picked.eq_ignore_ascii_case(&p.name), crate::i18n::builtin_label(&p.name, b)).clicked() { + if ui.pick_label(cur_picked.eq_ignore_ascii_case(&p.name), crate::i18n::builtin_label(&p.name, b)).clicked() { chosen = Some(p.name); } } @@ -3774,7 +3776,7 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm .selected_text(label_of(&PLACES, opts.destination_mode)) .show_ui(ui, |ui| { for (m, l) in PLACES { - ui.selectable_value(&mut opts.destination_mode, m, crate::i18n::tr(l)); + ui.pick_value(&mut opts.destination_mode, m, crate::i18n::tr(l)); } }); crate::widgets::register(ui.ctx(), "combo:exportDestinationMode", c.response.rect); @@ -3799,7 +3801,12 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm *dir = d; } } - crate::widgets::named(ui.add(egui::TextEdit::singleline(dir).desired_width(ui.available_width())), crate::i18n::tr("Folder")); + confirm_field( + ui, + crate::text_field::TextField::singleline("field:exportFolder", dir) + .label(crate::i18n::tr("Folder")) + .width(ui.available_width()), + ); }); }); } @@ -3809,10 +3816,14 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm D::SameAsOriginal => {} } field(ui, "Subfolder", |ui| { - crate::widgets::named( - ui.add(egui::TextEdit::singleline(&mut opts.subfolder).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)), - crate::i18n::tr("Subfolder"), + confirm_field( + ui, + crate::text_field::TextField::singleline("field:exportSubfolder", &mut opts.subfolder) + .hint(crate::i18n::tr("none")) + .label(crate::i18n::tr("Subfolder")) + .width(f32::INFINITY), ) + .response }); choices( ui, @@ -3832,7 +3843,7 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm field(ui, "Template", |ui| { egui::ComboBox::from_id_salt("exportNamingTemplate").selected_text(crate::i18n::tr(current)).show_ui(ui, |ui| { for (t, l) in EXPORT_NAMING_TEMPLATES { - if ui.selectable_label(opts.naming == *t, crate::i18n::tr(l)).clicked() { + if ui.pick_label(opts.naming == *t, crate::i18n::tr(l)).clicked() { opts.naming = (*t).to_string(); } } @@ -3840,24 +3851,25 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm }); if opts.naming.contains("{custom}") { field(ui, "Custom text", |ui| { - crate::widgets::named( - ui.add(egui::TextEdit::singleline(&mut opts.custom_text).desired_width(f32::INFINITY)), - crate::i18n::tr("Custom text"), + confirm_field( + ui, + crate::text_field::TextField::singleline("field:exportCustomText", &mut opts.custom_text) + .label(crate::i18n::tr("Custom text")) + .width(f32::INFINITY), ) + .response }); } - let naming_id = egui::Id::new("export-naming"); + let naming_id = crate::text_field::id("field:exportNaming"); let tags_open = field(ui, "File name", |ui| { ui.spacing_mut().item_spacing.x = 4.0; let w = crate::import::tag_field_width(ui); - crate::widgets::named( - ui.add( - egui::TextEdit::singleline(&mut opts.naming) - .id(naming_id) - .hint_text("{name}-{seq} · {date} · {title} · {folder}") - .desired_width(w), - ), - crate::i18n::tr("File name"), + confirm_field( + ui, + crate::text_field::TextField::singleline("field:exportNaming", &mut opts.naming) + .hint("{name}-{seq} · {date} · {title} · {folder}") + .label(crate::i18n::tr("File name")) + .width(w), ); crate::import::tag_toggle(ui, "exportNaming") }); @@ -4257,9 +4269,12 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm { wm.image = f; } - crate::widgets::named( - ui.add(egui::TextEdit::singleline(&mut wm.image).hint_text("logo.png").desired_width(ui.available_width())), - crate::i18n::tr("Image"), + confirm_field( + ui, + crate::text_field::TextField::singleline("field:exportWatermarkImage", &mut wm.image) + .hint("logo.png") + .label(crate::i18n::tr("Image")) + .width(ui.available_width()), ); }); }); @@ -4345,12 +4360,14 @@ pub(crate) fn export_settings(app: &mut LccApp, ui: &mut egui::Ui, f: ExportForm crate::widgets::register(ui.ctx(), "exportAddToPhotos", r.rect); if opts.add_to_photos { field(ui, "Collection", |ui| { - crate::widgets::named( - ui.add( - egui::TextEdit::singleline(&mut opts.photos_album).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY), - ), - crate::i18n::tr("Collection"), + confirm_field( + ui, + crate::text_field::TextField::singleline("field:exportPhotosAlbum", &mut opts.photos_album) + .hint(crate::i18n::tr("none")) + .label(crate::i18n::tr("Collection")) + .width(f32::INFINITY), ) + .response }); crate::dialog_frame::note( ui, @@ -4671,7 +4688,7 @@ fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lcc_engine::export::R let before = r.mode; let c = crate::widgets::combo_box("exportResizeMode").width(150.0).selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { for (m, l) in MODES { - ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l)); + ui.pick_value(&mut r.mode, m, crate::i18n::tr(l)); } }); crate::widgets::register(ui.ctx(), "combo:exportResizeMode", c.response.rect); @@ -5056,6 +5073,25 @@ fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str) r.ending == Some(crate::text_field::Ending::Return) } +/// Draws a one-line field of a dialog that has other fields too, and notes a Return in it for +/// the dialog to confirm on (`field_returned`). The field keeps the focus, so a dialog that +/// refuses (rules that don't check, a time that isn't a date) leaves the typing where it was. +pub(crate) fn confirm_field(ui: &mut egui::Ui, field: crate::text_field::TextField<'_>) -> crate::text_field::TextFieldResponse { + let r = field.show(ui); + if r.ending == Some(crate::text_field::Ending::Return) { + let pass = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(egui::Id::new("dialog-field-returned"), pass)); + r.response.request_focus(); + } + r +} + +/// A `confirm_field` took Return on this pass. +pub(crate) fn field_returned(ctx: &egui::Context) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data(|d| d.get_temp::(egui::Id::new("dialog-field-returned"))) == Some(pass) +} + /// The dialog part `key` is drawn this frame but wasn't the frame before: the dialog has just /// opened (to give its first field the focus once). fn just_opened(ui: &egui::Ui, key: &str) -> bool { diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 4978af34fd..41c8dc29ab 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -2,6 +2,7 @@ //! sections, built from the engine's control specs. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::epaint::{Mesh, Vertex}; use egui::{Align2, Color32, Pos2, Rect, RichText, Sense, Stroke, pos2, vec2}; use lcc_catalog::PhotoId; @@ -463,7 +464,7 @@ pub fn show_controls(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId) { let r = crate::widgets::combo_box("sensor.highlightMode").selected_text(name(current)).show_ui(ui, |ui| { let mut chosen = None; for i in 0..modes.len() { - if ui.selectable_label(i == current, name(i)).clicked() && i != current { + if ui.pick_label(i == current, name(i)).clicked() && i != current { chosen = Some(i); } } @@ -689,7 +690,7 @@ fn tool_profile_row(app: &mut LccApp, ui: &mut egui::Ui) { let all: Vec<(String, String)> = app.ui.settings.tool_profiles.all().map(|p| (p.id.clone(), p.label())).collect(); let mut pick = None; for (pid, label) in &all { - let r = ui.selectable_label(*pid == active, label); + let r = ui.pick_label(*pid == active, label); register(ui.ctx(), format!("toolProfileMenu:{pid}"), r.rect); if r.clicked() { pick = Some(pid.clone()); @@ -939,7 +940,7 @@ fn base_curve_row(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId, d: &DevelopS } else { filter.clear(); } - if ui.selectable_label(current.is_empty(), crate::i18n::tr("Default")).clicked() { + if ui.pick_label(current.is_empty(), crate::i18n::tr("Default")).clicked() { picked = Some(String::new()); } let f = filter.to_lowercase(); @@ -952,7 +953,7 @@ fn base_curve_row(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId, d: &DevelopS if c.bundled { label = format!("{label} · {}", crate::i18n::tr("built in")); } - if ui.selectable_label(c.id == current, label).clicked() { + if ui.pick_label(c.id == current, label).clicked() { picked = Some(c.id.clone()); } } @@ -1630,12 +1631,12 @@ fn second_histogram_menu(app: &mut LccApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let cur = HistogramMode::parse(&app.ui.histogram_second); ui.label(RichText::new(crate::i18n::tr("Second Histogram")).color(t.text_label)); - if ui.selectable_label(cur.is_none(), crate::i18n::tr("None")).clicked() { + if ui.pick_label(cur.is_none(), crate::i18n::tr("None")).clicked() { let _ = app.run("view.histogram.second", json!({"mode": "off"})); ui.close(); } for m in HistogramMode::ALL { - if ui.selectable_label(cur == Some(m), crate::i18n::tr(m.label())).clicked() { + if ui.pick_label(cur == Some(m), crate::i18n::tr(m.label())).clicked() { let _ = app.run("view.histogram.second", json!({"mode": m.name()})); ui.close(); } @@ -1648,7 +1649,7 @@ fn histogram_display_menu(app: &mut LccApp, ui: &mut egui::Ui, mode: HistogramMo let t = Tokens::get(ui.ctx()); ui.label(RichText::new(crate::i18n::tr("Histogram Mode")).color(t.text_label)); for m in HistogramMode::ALL { - if ui.selectable_label(mode == m, crate::i18n::tr(m.label())).clicked() { + if ui.pick_label(mode == m, crate::i18n::tr(m.label())).clicked() { let _ = app.run("view.histogram.mode", json!({"mode": m.name()})); ui.close(); } @@ -1656,7 +1657,7 @@ fn histogram_display_menu(app: &mut LccApp, ui: &mut egui::Ui, mode: HistogramMo ui.separator(); ui.label(RichText::new(crate::i18n::tr("Scale")).color(t.text_label)); for s in HistogramScale::ALL { - if ui.selectable_label(scale == s, crate::i18n::tr(s.label())).clicked() { + if ui.pick_label(scale == s, crate::i18n::tr(s.label())).clicked() { let _ = app.run("view.histogram.scale", json!({"scale": s.name()})); ui.close(); } @@ -1696,14 +1697,14 @@ fn soft_proofing(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId) { let mut pick = false; crate::widgets::combo_box("proof-space").width(170.0).selected_text(shown).show_ui(ui, |ui| { for s in OutputSpace::ALL { - if ui.selectable_label(device.is_none() && cur == s, s.label()).clicked() { + if ui.pick_label(device.is_none() && cur == s, s.label()).clicked() { let _ = app.run("view.softProof", json!({"space": s})); } } if let Some(n) = &device { - let _ = ui.selectable_label(true, n); + let _ = ui.pick_label(true, n); } - if app.services.pick_display_profile.is_some() && ui.selectable_label(false, crate::i18n::tr("Other…")).clicked() { + if app.services.pick_display_profile.is_some() && ui.pick_label(false, crate::i18n::tr("Other…")).clicked() { pick = true; } }); @@ -1719,7 +1720,7 @@ fn soft_proofing(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId) { ui.label(RichText::new(crate::i18n::tr("Intent:")).color(t.text_label)); use lcc_engine::proof::ProofIntent; for (i, label) in [(ProofIntent::Perceptual, "Perceptual"), (ProofIntent::Relative, "Relative")] { - let r = ui.selectable_label(app.ui.proof_intent == i, crate::i18n::tr(label)); + let r = ui.pick_label(app.ui.proof_intent == i, crate::i18n::tr(label)); register(ui.ctx(), format!("button:proofIntent-{}", i.name()), r.rect); if r.clicked() && app.ui.proof_intent != i { let _ = app.run("view.softProof", json!({"intent": i.name()})); @@ -2394,7 +2395,7 @@ fn curve_footer(app: &mut LccApp, ui: &mut egui::Ui, d: &DevelopSettings, target user_seen = true; ui.separator(); } - let r = ui.selectable_label(current.as_deref() == Some(p.name.as_str()), crate::i18n::builtin_label(&p.name, p.builtin)); + let r = ui.pick_label(current.as_deref() == Some(p.name.as_str()), crate::i18n::builtin_label(&p.name, p.builtin)); register(ui.ctx(), target.widget(&format!("Preset:{}", p.name)), r.rect); if r.clicked() { let _ = app.run("curve.applyPreset", target.params(json!({"name": p.name}))); @@ -2843,7 +2844,7 @@ fn wb_rows(app: &mut LccApp, ui: &mut egui::Ui, d: &DevelopSettings, raw: bool) .on_hover_text(crate::i18n::tr("Sample size: the square of pixels the selector averages")); egui::Popup::menu(&r).show(|ui| { for s in crate::panels::detail::WB_SAMPLES { - if ui.selectable_label(n == s, format!("{s}×{s}")).clicked() { + if ui.pick_label(n == s, format!("{s}×{s}")).clicked() { app.ui.wb_sample = s; } } @@ -2862,7 +2863,7 @@ fn wb_rows(app: &mut LccApp, ui: &mut egui::Ui, d: &DevelopSettings, raw: bool) if m == WbMode::Custom { continue; } - if ui.selectable_label(d.wb.mode == m, crate::i18n::tr(m.label())).clicked() { + if ui.pick_label(d.wb.mode == m, crate::i18n::tr(m.label())).clicked() { let mode = serde_json::to_value(m).unwrap_or_default(); let _ = app.run("develop.wb", json!({"mode": mode})); } @@ -3884,7 +3885,7 @@ fn lens_picker(app: &mut LccApp, ui: &mut egui::Ui, id: lcc_catalog::PhotoId, d: egui::Grid::new("lens-picker").num_columns(2).spacing([6.0, 4.0]).show(ui, |ui| { ui.label(egui::RichText::new(tr("Make")).size(11.5).color(t.text_dim)); let r = crate::widgets::combo_box("lens-make").width(150.0).selected_text(make.clone().unwrap_or_else(|| auto.clone())).show_ui(ui, |ui| { - if ui.selectable_label(picked.is_none() && make.is_none(), &auto).clicked() { + if ui.pick_label(picked.is_none() && make.is_none(), &auto).clicked() { app.ui.lens_pick_make = None; action = Some(serde_json::Value::Null); } @@ -3892,7 +3893,7 @@ fn lens_picker(app: &mut LccApp, ui: &mut egui::Ui, id: lcc_catalog::PhotoId, d: makers.sort_unstable_by_key(|m| m.to_lowercase()); makers.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); for m in makers { - if ui.selectable_label(make.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(m)), m).clicked() { + if ui.pick_label(make.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(m)), m).clicked() { app.ui.lens_pick_make = Some(m.to_string()); } } @@ -3915,7 +3916,7 @@ fn lens_picker(app: &mut LccApp, ui: &mut egui::Ui, id: lcc_catalog::PhotoId, d: models.dedup(); for m in models { let on = picked.as_ref().is_some_and(|l| l.model.eq_ignore_ascii_case(m)); - if ui.selectable_label(on, m).clicked() { + if ui.pick_label(on, m).clicked() { let focal = picked.as_ref().and_then(|l| l.focal); action = Some(json!({"maker": mk, "model": m, "focal": focal})); } diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rs index 8aa16a75c5..91e88d4078 100644 --- a/crates/ui-egui/src/panels/faces.rs +++ b/crates/ui-egui/src/panels/faces.rs @@ -9,6 +9,7 @@ //! take a long time). "Open page" opens the model's own page in the browser for anything else. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::RichText; use serde_json::{Value, json}; @@ -255,16 +256,16 @@ fn gpu_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, gpu: &Value) { let mut selected_dev = dev_before.clone(); super::settings::row(ui, t, crate::i18n::tr("Face models device"), |ui| { let combo = crate::widgets::combo_box("settingsFacesDevice").selected_text(current_dev).width(260.0).show_ui(ui, |ui| { - let r = ui.selectable_value(&mut selected_dev, "auto".to_string(), auto.as_str()); + let r = ui.pick_value(&mut selected_dev, "auto".to_string(), auto.as_str()); register(ui.ctx(), "button:settingsFacesDevice-auto", r.rect); - let r = ui.selectable_value(&mut selected_dev, "cpu".to_string(), cpu.as_str()); + let r = ui.pick_value(&mut selected_dev, "cpu".to_string(), cpu.as_str()); register(ui.ctx(), "button:settingsFacesDevice-cpu", r.rect); for (i, d) in gpu_cards.iter().enumerate() { let id = d["id"].as_str().unwrap_or(""); let name = d["name"].as_str().unwrap_or(id); let usable = d["usable"].as_bool().unwrap_or(true); let why_not = d["whyNot"].as_str(); - let r = ui.add_enabled_ui(usable, |ui| ui.selectable_value(&mut selected_dev, id.to_string(), name)).inner; + let r = ui.add_enabled_ui(usable, |ui| ui.pick_value(&mut selected_dev, id.to_string(), name)).inner; let r = match why_not { Some(why) => r.on_disabled_hover_text(why), None => r, @@ -298,11 +299,11 @@ fn gpu_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, gpu: &Value) { super::settings::row(ui, t, crate::i18n::tr("GPU precision"), |ui| { ui.add_enabled_ui(dev_before != "cpu", |ui| { let combo = crate::widgets::combo_box("settingsFacesPrecision").selected_text(current_prec).width(260.0).show_ui(ui, |ui| { - let r = ui.selectable_value(&mut selected_prec, "auto".to_string(), prec_auto); + let r = ui.pick_value(&mut selected_prec, "auto".to_string(), prec_auto); register(ui.ctx(), "button:settingsFacesPrecision-auto", r.rect); - let r = ui.selectable_value(&mut selected_prec, "fp16".to_string(), prec_fp16); + let r = ui.pick_value(&mut selected_prec, "fp16".to_string(), prec_fp16); register(ui.ctx(), "button:settingsFacesPrecision-fp16", r.rect); - let r = ui.selectable_value(&mut selected_prec, "fp32".to_string(), prec_fp32); + let r = ui.pick_value(&mut selected_prec, "fp32".to_string(), prec_fp32); register(ui.ctx(), "button:settingsFacesPrecision-fp32", r.rect); }); register(ui.ctx(), "combo:settingsFacesPrecision", combo.response.rect); diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index de41fb4d10..9c524bf117 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -6,8 +6,9 @@ //! view with counts (`library.facets`); a click narrows the view (`library.facetPick`) and the columns cascade. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Color32, Rect, Sense, Stroke, StrokeKind, vec2}; -use lcc_catalog::{ColorLabel, Flag, MediaKind, RatingOp}; +use lcc_catalog::{ColorLabel, Flag, RatingOp}; use serde_json::{Value, json}; use crate::LccApp; @@ -77,13 +78,17 @@ fn picker(app: &mut LccApp, ui: &mut egui::Ui, id: &str, current: &str, active: let mut chosen = None; let searchable = matches!(id, "camera" | "lens" | "keyword"); // the metadata pickers take several values (issue #213): a click toggles one and the list stays open - let multi = searchable; + let multi = searchable || id == "kind"; // the search text of this picker alone; `None` until the dropdown opens, cleared when it closes let key = egui::Id::new(("filterSearch", id)); let close = if multi { egui::PopupCloseBehavior::CloseOnClickOutside } else { egui::PopupCloseBehavior::CloseOnClick }; // a stable id: the button's own comes from its place, which moves when the chips row appears after a pick let opened = egui::Popup::menu(&r).id(egui::Id::new(("filterPicker", id))).close_behavior(close).show(|ui| { let mut query = String::new(); + if multi { + // a pick toggles the value and the list stays open, with the mouse or Enter + crate::popup_typeahead::stays_open(ui); + } if searchable { let previous: Option = ui.data(|d| d.get_temp(key)); let just_opened = previous.is_none(); @@ -109,15 +114,20 @@ fn picker(app: &mut LccApp, ui: &mut egui::Ui, id: &str, current: &str, active: // the "Any …" row (a patch that only clears: nulls and empty lists) always stays, and so does the // column's operator toggle (a patch with an `…Op` key) // (its operator, if any, back to OR; a row that only sets the operator is not it) - let any = patch.as_object().is_none_or(|o| { - o.keys().any(|k| !k.ends_with("Op")) - && o.iter().all(|(k, v)| v.is_null() || v.as_array().is_some_and(Vec::is_empty) || (k.ends_with("Op") && v == "any")) + // a `library.facetPick` that replaces with no values ("All types") is one too + let pick_clears = patch.get("facetPick").is_some_and(|p| { + p.get("mode").is_some_and(|m| m == "replace") && p.get("values").and_then(Value::as_array).is_some_and(Vec::is_empty) }); + let any = pick_clears + || patch.as_object().is_none_or(|o| { + o.keys().any(|k| !k.ends_with("Op")) + && o.iter().all(|(k, v)| v.is_null() || v.as_array().is_some_and(Vec::is_empty) || (k.ends_with("Op") && v == "any")) + }); let op_row = !any && patch.as_object().is_some_and(|o| o.keys().any(|k| k.ends_with("Op"))); if searchable && !any && !op_row && !needle.is_empty() && !label.to_lowercase().contains(&needle) { continue; } - let resp = ui.selectable_label(*sel, if searchable && !any { label.as_str() } else { crate::i18n::tr(label) }); + let resp = ui.pick_label(*sel, if searchable && !any { label.as_str() } else { crate::i18n::tr(label) }); register(ui.ctx(), format!("filterItem:{id}:{n}"), resp.rect); if resp.clicked() { chosen = Some(patch.clone()); @@ -133,8 +143,26 @@ fn picker(app: &mut LccApp, ui: &mut egui::Ui, id: &str, current: &str, active: ui.data_mut(|d| d.remove::(key)); } if let Some(p) = chosen { - filter(app, p); + // a row that is a `library.facetPick` call (the Type menu) rather than a filter patch + match p.get("facetPick") { + Some(args) => { + let _ = app.run("library.facetPick", args.clone()); + } + None => filter(app, p), + } + } +} + +/// The Type choice as `library.facetPick` lists it: `image`, `raw`, `video`, `hdr`… (the single `kind` or `merged` +/// set elsewhere, or the list of a `kind` pick). +fn chosen_types(f: &lcc_catalog::Filter) -> Vec { + let mut out: Vec = f.kind.map(|k| lcc_catalog::facets::kind_name(k).to_string()).into_iter().chain(f.merged.clone()).collect(); + for v in f.facets.iter().filter(|p| p.field == "kind").flat_map(|p| p.values.iter()) { + if !out.iter().any(|o| o.eq_ignore_ascii_case(v)) { + out.push(v.clone()); + } } + out } /// The values a metadata picker has chosen: its multi-select list, and the single value (set from elsewhere) @@ -228,18 +256,21 @@ pub fn show(app: &mut LccApp, outer: &mut egui::Ui) { .collect() }); if let Some(r) = crate::rating::Rating::new("filter", f.rating).automation_ids("filter:star").show(ui) { - filter(app, json!({"rating": r})); + // the stars take over from a Rating column choice of several ratings + let others: Vec<&lcc_catalog::FacetPick> = f.facets.iter().filter(|p| p.field != "rating").collect(); + filter(app, json!({"rating": r, "facets": others})); } ui.add_space(14.0); - // flags (one at a time; click again to clear) + // flags: a click chooses one (again to clear it), ⌘/Ctrl-click adds or removes it, as in the Flag column caption(ui, "Flag"); + let lit = f.flags_shown().unwrap_or_default(); for (id, icon, flag, tip) in [ ("pick", Icon::FlagPick, Flag::Pick, "Picked"), - ("reject", Icon::FlagReject, Flag::Reject, "Rejected"), ("none", Icon::Circle, Flag::None, "Unflagged"), + ("reject", Icon::FlagReject, Flag::Reject, "Rejected"), ] { - let on = f.flag == Some(flag); + let on = lit.contains(&flag); let color = match flag { Flag::Pick if on => t.pick, Flag::Reject if on => t.reject, @@ -249,7 +280,14 @@ pub fn show(app: &mut LccApp, outer: &mut egui::Ui) { let resp = toggle(ui, id, on, tip, |p, r, c| paint(p, r, icon, if color == Color32::TRANSPARENT { c } else { color })); count(ui, &format!("filter:count:{id}"), tally.flag(flag)); if resp.clicked() { - filter(app, json!({"flag": if on { Value::Null } else { json!(id) }})); + let args = if ui.input(|i| i.modifiers.command) { + json!({"field": "flag", "mode": "toggle", "values": [id]}) + } else if on && lit.len() == 1 { + json!({"field": "flag", "mode": "replace", "values": []}) + } else { + json!({"field": "flag", "mode": "replace", "values": [id]}) + }; + let _ = app.run("library.facetPick", args); } } ui.add_space(14.0); @@ -289,36 +327,29 @@ pub fn show(app: &mut LccApp, outer: &mut egui::Ui) { } ui.add_space(14.0); - // kind + edited - let kind_label = match f.kind { - None => "All types", - Some(MediaKind::Image) => "Photos", - Some(MediaKind::Raw) => "Raw", - Some(MediaKind::Video) => "Videos", - }; - let kind_label = match f.merged.as_deref() { - Some("hdr") => "HDR", - Some("panorama") => "Panoramas", - Some("hdrPanorama") => "HDR Panoramas", - Some("focusStack") => "Focus Stacks", - Some(_) => "Merged", - None => kind_label, + // kind + edited: the Type menu takes several values, as the Camera menu does: a click toggles one, any of them matches + const TYPES: [(&str, &str); 7] = [ + ("Photos", "image"), + ("Raw", "raw"), + ("Videos", "video"), + ("HDR", "hdr"), + ("Panoramas", "panorama"), + ("HDR Panoramas", "hdrPanorama"), + ("Focus Stacks", "focusStack"), + ]; + let types = chosen_types(&f); + let type_names: Vec<&str> = types.iter().filter_map(|t| TYPES.iter().find(|(_, k)| k == t).map(|(l, _)| *l)).collect(); + let kind_label = match type_names.as_slice() { + [] => "All types".to_string(), + [one] => crate::i18n::tr(one).to_string(), + [first, rest @ ..] => format!("{} +{}", crate::i18n::tr(first), rest.len()), }; - picker(app, ui, "kind", kind_label, f.kind.is_some() || f.merged.is_some(), |_| { - [ - ("All types", Value::Null, None), - ("Photos", json!("image"), Some(MediaKind::Image)), - ("Raw", json!("raw"), Some(MediaKind::Raw)), - ("Videos", json!("video"), Some(MediaKind::Video)), - ] - .into_iter() - .map(|(l, v, k)| (l.to_string(), json!({"kind": v, "merged": null}), f.kind == k && f.merged.is_none())) - .chain( - [("HDR", "hdr"), ("Panoramas", "panorama"), ("HDR Panoramas", "hdrPanorama"), ("Focus Stacks", "focusStack")] - .into_iter() - .map(|(l, m)| (l.to_string(), json!({"kind": null, "merged": m}), f.merged.as_deref() == Some(m))), - ) - .collect() + picker(app, ui, "kind", &kind_label, !types.is_empty(), |_| { + std::iter::once(("All types".to_string(), json!({"facetPick": {"field": "kind", "mode": "replace", "values": []}}), types.is_empty())) + .chain(TYPES.iter().map(|(l, k)| { + (l.to_string(), json!({"facetPick": {"field": "kind", "mode": "toggle", "values": [k]}}), types.iter().any(|t| t == k)) + })) + .collect() }); let edited_label = match f.edited { None => "Edited or not", @@ -802,6 +833,44 @@ fn value_label(field: &str, value: &str) -> String { } } +/// The rows of a Metadata column, each `(value, count, label)`, in the order shown: numeric fields by value (as +/// `library.facets` lists them), every other field ascending by the label as shown, case aside, as Lightroom does. +fn column_rows<'a>(field: &str, values: &'a [Value]) -> Vec<(&'a str, u64, String)> { + let mut rows: Vec<_> = values + .iter() + .filter_map(|v| Some((v["value"].as_str()?, v["count"].as_u64()?))) + .map(|(value, count)| (value, count, value_label(field, value))) + .collect(); + if !lcc_catalog::facets::is_numeric(field) { + rows.sort_by(|a, b| a.2.to_lowercase().cmp(&b.2.to_lowercase()).then_with(|| a.2.cmp(&b.2))); + } + rows +} + +/// The `library.facetPick` a click on `value` in a Metadata column asks for, as Lightroom Classic reads the click: a plain +/// click chooses that value alone, ⌘/Ctrl-click adds it to the choice or takes it off, and ⇧-click chooses the run from +/// the last clicked value (else the first chosen one, else the top row) to it in `order`, the rows as listed. +fn pick_args(ui: &egui::Ui, col: usize, field: &str, value: &str, order: &[&str], chosen: &[&str]) -> Value { + let m = ui.input(|i| i.modifiers); + let anchor_id = egui::Id::new(("filterAnchor", col, field)); + let pos = |v: &str| order.iter().position(|o| o.eq_ignore_ascii_case(v)); + if m.shift + && let Some(to) = pos(value) + { + let stored: Option = ui.ctx().data(|d| d.get_temp(anchor_id)); + let from = stored.as_deref().and_then(pos).or_else(|| chosen.iter().find_map(|c| pos(c))).unwrap_or(0); + if let Some(run) = order.get(from.min(to)..=from.max(to)) { + return json!({"field": field, "mode": "replace", "values": run}); + } + } + ui.ctx().data_mut(|d| d.insert_temp(anchor_id, value.to_string())); + // A plain click on the one chosen value clears it, as it always has. + if !m.command && matches!(chosen, [only] if only.eq_ignore_ascii_case(value)) { + return json!({"field": field, "mode": "replace", "values": []}); + } + json!({"field": field, "mode": if m.command { "toggle" } else { "replace" }, "values": [value]}) +} + /// Whether what a Metadata column's search box holds lets `text` (a value as the column shows it) through. /// An empty box lets everything through; case is ignored. fn matches(query: &str, text: &str) -> bool { @@ -837,6 +906,172 @@ fn value_row(ui: &mut egui::Ui, widget: String, text: String, count: u64, on: bo clickable && resp.clicked() } +#[derive(Clone, Copy, PartialEq, Eq)] +enum DateRowOutcome { + None, + Pick, + Toggle, +} + +/// One row of the Date Metadata column (year, month, or day) with an optional disclosure chevron. +#[allow(clippy::too_many_arguments)] +fn date_tree_row( + ui: &mut egui::Ui, + col: usize, + row_idx: usize, + key: &str, + label: String, + count: u64, + indent: f32, + expandable: bool, + open: bool, + on: bool, +) -> DateRowOutcome { + let t = Tokens::get(ui.ctx()); + let (rr, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::click()); + register(ui.ctx(), format!("filterValue:{col}:{row_idx}"), rr); + register(ui.ctx(), format!("filterDate:{col}:{key}"), rr); + crate::widgets::announce_selected(&resp, label.clone(), on); + let tri_resp = if expandable { + let tri_rect = Rect::from_center_size(egui::pos2(rr.left() + 8.0 + indent, rr.center().y), vec2(14.0, 16.0)); + register(ui.ctx(), format!("filterDateToggle:{col}:{key}"), tri_rect); + Some((tri_rect, ui.interact(tri_rect, ui.id().with(("filterDateToggle", col, key)), Sense::click()))) + } else { + None + }; + let tri_hovered = tri_resp.as_ref().is_some_and(|(_, r)| r.hovered()); + let tri_clicked = tri_resp.as_ref().is_some_and(|(_, r)| r.clicked()); + if on { + ui.painter().rect_filled(rr, 3.0, t.tool_active); + } else if resp.hovered() || tri_hovered { + ui.painter().rect_filled(rr, 3.0, t.hover); + } + if let Some((tri_rect, _)) = tri_resp { + let icon = if open { Icon::ChevronDown } else { Icon::ChevronRight }; + let col = if tri_hovered { t.text } else { t.text_dim }; + paint(ui.painter(), Rect::from_center_size(tri_rect.center(), vec2(12.0, 12.0)), icon, col); + } + let color = if on { t.text } else { t.text_label }; + let text_left = rr.left() + 16.0 + indent; + let cg = ui.painter().layout_no_wrap(count.to_string(), t.font(11.5), t.text_dim); + let room = (rr.right() - 4.0 - cg.size().x - 6.0 - text_left).max(10.0); + let mut job = egui::text::LayoutJob::simple_singleline(label, t.font(12.0), color); + job.wrap = egui::text::TextWrapping::truncate_at_width(room); + let g = ui.painter().layout_job(job); + ui.painter().galley(egui::pos2(text_left, rr.center().y - g.size().y / 2.0), g, color); + ui.painter().galley(egui::pos2(rr.right() - 4.0 - cg.size().x, rr.center().y - cg.size().y / 2.0), cg, t.text_dim); + if tri_clicked { + DateRowOutcome::Toggle + } else if resp.clicked() { + DateRowOutcome::Pick + } else { + DateRowOutcome::None + } +} + +fn date_matches(query: &str, key: &str, label: &str) -> bool { + matches(query, label) || matches(query, key) +} + +/// Renders the Year → Month → Day hierarchy in the Date Metadata column. +/// Returns `(rows_shown, total_tree_rows, picked_value)`. +fn date_column_rows(ui: &mut egui::Ui, col: usize, tree: &[Value], query: &str, chosen: &[&str]) -> (usize, usize, Option) { + let searching = !query.trim().is_empty(); + let mut shown = 0usize; + let mut row_idx = 1usize; + let mut picked: Option = None; + // a ⇧-click runs over sibling rows only: the years, the months of one year, the days of one month + let sibling = |rows: &[Value], key: &str| -> Vec { rows.iter().filter_map(|r| r[key].as_str().map(str::to_string)).collect() }; + let years = sibling(tree, "year"); + let years: Vec<&str> = years.iter().map(String::as_str).collect(); + for y in tree { + let (Some(year), Some(y_count)) = (y["year"].as_str(), y["count"].as_u64()) else { continue }; + let y_label = crate::i18n::date_group_label(year, true); + let y_self = date_matches(query, year, &y_label); + let months = y["months"].as_array().map(Vec::as_slice).unwrap_or(&[]); + let has_matching_descendant = searching + && months.iter().any(|m| { + let Some(month) = m["month"].as_str() else { return false }; + let m_label = crate::i18n::date_group_label(month, true); + let days = m["days"].as_array().map(Vec::as_slice).unwrap_or(&[]); + date_matches(query, month, &m_label) + || days.iter().any(|d| d["day"].as_str().is_some_and(|day| date_matches(query, day, &crate::i18n::date_group_label(day, true)))) + }); + if searching && !y_self && !has_matching_descendant { + continue; + } + let y_open_id = egui::Id::new(("filterDateOpen", col, year)); + let y_stored: Option = ui.ctx().data(|d| d.get_temp(y_open_id)); + let y_open = if searching { + has_matching_descendant || y_stored.unwrap_or(tree.len() == 1) + } else { + y_stored.unwrap_or_else(|| tree.len() == 1 || chosen.iter().any(|c| c.len() > 4 && c.starts_with(year))) + }; + let y_on = chosen.iter().any(|c| c.eq_ignore_ascii_case(year)); + shown += 1; + match date_tree_row(ui, col, row_idx, year, y_label, y_count, 0.0, !months.is_empty(), y_open, y_on) { + DateRowOutcome::Pick => picked = Some(pick_args(ui, col, "year", year, &years, chosen)), + DateRowOutcome::Toggle => ui.ctx().data_mut(|d| { + d.insert_temp(y_open_id, !y_open); + }), + DateRowOutcome::None => {} + } + row_idx += 1; + if !y_open { + continue; + } + let month_keys = sibling(months, "month"); + let month_keys: Vec<&str> = month_keys.iter().map(String::as_str).collect(); + for m in months { + let (Some(month), Some(m_count)) = (m["month"].as_str(), m["count"].as_u64()) else { continue }; + let m_label = crate::i18n::date_group_label(month, true); + let m_self = date_matches(query, month, &m_label); + let days = m["days"].as_array().map(Vec::as_slice).unwrap_or(&[]); + let has_matching_day = searching + && days.iter().any(|d| d["day"].as_str().is_some_and(|day| date_matches(query, day, &crate::i18n::date_group_label(day, true)))); + if searching && !y_self && !m_self && !has_matching_day { + continue; + } + let m_open_id = egui::Id::new(("filterDateOpen", col, month)); + let m_stored: Option = ui.ctx().data(|d| d.get_temp(m_open_id)); + let m_open = if searching { + has_matching_day || m_stored.unwrap_or(months.len() == 1) + } else { + m_stored.unwrap_or_else(|| months.len() == 1 || chosen.iter().any(|c| c.len() > 7 && c.starts_with(month))) + }; + let m_on = chosen.iter().any(|c| c.eq_ignore_ascii_case(month)); + shown += 1; + match date_tree_row(ui, col, row_idx, month, m_label, m_count, 10.0, !days.is_empty(), m_open, m_on) { + DateRowOutcome::Pick => picked = Some(pick_args(ui, col, "year", month, &month_keys, chosen)), + DateRowOutcome::Toggle => ui.ctx().data_mut(|d| { + d.insert_temp(m_open_id, !m_open); + }), + DateRowOutcome::None => {} + } + row_idx += 1; + if !m_open { + continue; + } + let day_keys = sibling(days, "day"); + let day_keys: Vec<&str> = day_keys.iter().map(String::as_str).collect(); + for d in days { + let (Some(day), Some(d_count)) = (d["day"].as_str(), d["count"].as_u64()) else { continue }; + let d_label = crate::i18n::date_group_label(day, true); + if searching && !y_self && !m_self && !date_matches(query, day, &d_label) { + continue; + } + let d_on = chosen.iter().any(|c| c.eq_ignore_ascii_case(day)); + shown += 1; + if date_tree_row(ui, col, row_idx, day, d_label, d_count, 20.0, false, false, d_on) == DateRowOutcome::Pick { + picked = Some(pick_args(ui, col, "year", day, &day_keys, chosen)); + } + row_idx += 1; + } + } + } + (shown, row_idx - 1, picked) +} + /// The Metadata columns (issue #218): each lists one field's values among the photos in view with how many photos /// have each; a click narrows the view (`library.facetPick`), and the columns after it count only what is left. fn columns(app: &mut LccApp, ui: &mut egui::Ui, area: Rect) { @@ -872,7 +1107,7 @@ fn columns(app: &mut LccApp, ui: &mut egui::Ui, area: Rect) { crate::widgets::dropdown_within(&mut c, &format!("filterColumn{i}"), crate::i18n::tr(title), t.semibold(12.5), t.text, w - 8.0); egui::Popup::menu(&head).id(egui::Id::new(("filterColumnField", i))).show(|ui| { for (k, label) in COLUMN_FIELDS { - let resp = ui.selectable_label(k == field, crate::i18n::tr(label)); + let resp = ui.pick_label(k == field, crate::i18n::tr(label)); register(ui.ctx(), format!("filterColumnField:{i}:{k}"), resp.rect); if resp.clicked() { retitle = Some((i, k)); @@ -926,7 +1161,7 @@ fn columns(app: &mut LccApp, ui: &mut egui::Ui, area: Rect) { ("All", lcc_catalog::MatchOp::All, "Match all of the chosen values (AND)"), ]; for (label, want, tip) in buttons { - let resp = c.selectable_label(op == want, egui::RichText::new(crate::i18n::tr(label)).font(t.font(11.5))); + let resp = c.pick_label(op == want, egui::RichText::new(crate::i18n::tr(label)).font(t.font(11.5))); register(ui.ctx(), format!("filterColumnOp:{i}:{label}"), resp.rect); if resp.clicked() && op != want { op_pick = Some((op_key.clone(), json!(if want == lcc_catalog::MatchOp::All { "all" } else { "any" }))); @@ -949,30 +1184,42 @@ fn columns(app: &mut LccApp, ui: &mut egui::Ui, area: Rect) { } egui::ScrollArea::vertical().id_salt(("filterColumnRows", i)).auto_shrink([false, false]).show(&mut c, |ui| { let values = data["values"].as_array().map(Vec::as_slice).unwrap_or(&[]); - // the search box lets through only the rows whose text holds what is typed; a row keeps its place in - // the full list, so clicking one picks the same value whatever is typed - let mut shown = 0; - for (n, v) in values.iter().enumerate() { - let (Some(value), Some(count)) = (v["value"].as_str(), v["count"].as_u64()) else { continue }; - let label = value_label(field, value); - if !matches(&query, &label) { - continue; + let (shown, unknown_slot) = if field == "year" + && let Some(tree) = data["tree"].as_array() + { + let (shown, count, date_pick) = date_column_rows(ui, i, tree, &query, &chosen); + if let Some(pick) = date_pick { + picked = Some(pick); } - shown += 1; - let on = chosen.iter().any(|c| c.eq_ignore_ascii_case(value)); - if value_row(ui, format!("filterValue:{i}:{}", n + 1), label, count, on, true) { - picked = Some(json!({"field": field, "value": value})); + (shown, count + 1) + } else { + // the search box lets through only the rows whose text holds what is typed; a row keeps its place in + // the full list, so clicking one picks the same value whatever is typed + let mut shown = 0; + let rows: Vec<_> = column_rows(field, values).into_iter().filter(|r| matches(&query, &r.2)).collect(); + let unknown_slot = rows.len() + 1; + let order: Vec<&str> = rows.iter().map(|r| r.0).collect(); + for (n, (value, count, label)) in rows.iter().enumerate() { + shown += 1; + let on = chosen.iter().any(|c| c.eq_ignore_ascii_case(value)); + if value_row(ui, format!("filterValue:{i}:{}", n + 1), label.clone(), *count, on, true) { + picked = Some(pick_args(ui, i, field, value, &order, &chosen)); + } } - } + (shown, unknown_slot) + }; if shown == 0 && !query.trim().is_empty() { ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr("No matches")).font(t.font(12.0)).color(t.text_dim))); } let none = data["none"].as_u64().unwrap_or(0); // photos without a value (no keyword, no capture date, no title…) can be picked too (issue #777) if (none > 0 || none_on) - && value_row(ui, format!("filterValue:{i}:{}", values.len() + 1), crate::i18n::tr("Unknown").to_string(), none, none_on, true) + && value_row(ui, format!("filterValue:{i}:{unknown_slot}"), crate::i18n::tr("Unknown").to_string(), none, none_on, true) { - picked = Some(json!({"field": field, "none": true})); + let mode = if ui.input(|i| i.modifiers.command) { "toggle" } else { "replace" }; + // a plain click on "Unknown" when it is the whole choice clears it + let only = none_on && chosen.is_empty(); + picked = Some(json!({"field": field, "mode": mode, "values": [], "none": !(only && mode == "replace")})); } }); } @@ -990,3 +1237,27 @@ fn columns(app: &mut LccApp, ui: &mut egui::Ui, area: Rect) { let _ = app.run("view.filterColumns", json!({"column": column, "field": field})); } } + +#[cfg(test)] +mod column_order_tests { + use super::*; + + fn labels(field: &str, rows: &[(&str, u64)]) -> Vec { + let values: Vec = rows.iter().map(|(v, c)| json!({"value": v, "count": c})).collect(); + column_rows(field, &values).into_iter().map(|r| r.2).collect() + } + + #[test] + fn text_columns_list_ascending_by_the_label_shown_whatever_the_counts() { + // `library.facets` lists by count, most first: Unflagged, Rejected, Picked + assert_eq!(labels("flag", &[("none", 50), ("reject", 10), ("pick", 3)]), ["Picked", "Rejected", "Unflagged"]); + assert_eq!(labels("kind", &[("image", 9), ("video", 5), ("raw", 1)]), ["Photos", "Raw", "Videos"]); + assert_eq!(labels("camera", &[("canon", 9), ("Nikon", 5), ("Fuji", 1)]), ["canon", "Fuji", "Nikon"], "case aside"); + assert_eq!(labels("keyword", &[("2024", 1), ("10", 9), ("b", 5)]), ["10", "2024", "b"], "a keyword that looks like a number is text"); + } + + #[test] + fn numeric_columns_keep_their_order_by_value() { + assert_eq!(labels("iso", &[("100", 1), ("800", 9), ("1600", 5)]), ["100", "800", "1600"]); + } +} diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index c9926d600b..d594b3d5b3 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -22,6 +22,7 @@ pub(crate) fn exposure_line(m: &lcc_catalog::Meta) -> Option { mod header_tests; use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -115,6 +116,21 @@ pub struct GridCache { publish: Option<(u64, Option>>)>, /// What was read of each photo of the list last shown. read: Option, + /// The inputs of the layout the grid drew last, for a thumbnail-size key press ([`next_thumb_size`]). + pub(crate) step: Option, +} + +/// What the grid laid out last frame, apart from the thumbnail size: the width the photos fill, the strip +/// under each cell and the date runs. +#[derive(Clone)] +pub(crate) struct GridStep { + pub(crate) avail_w: f32, + pub(crate) footer: f32, + pub(crate) runs: Arc>, + /// Whether the frame was Square Grid, which has no cut-off to keep for the Photo Grid. + pub(crate) square: bool, + /// The Photo Grid's cut-off size ([`photo_cut`]); the largest size in Square Grid. + pub(crate) cut: f32, } /// Header keys of a published collection's sections, in the order the engine sorts them. @@ -257,6 +273,12 @@ impl ListRead { } impl GridCache { + /// The grid as last laid out, for the tests (None until the grid has been drawn). + #[cfg(test)] + pub(crate) fn laid_out(&self) -> Option<&GridLayout> { + self.layout.as_ref().map(|(_, lay)| lay.as_ref()) + } + /// The date runs of `ids`, reading what has to be read of them (`square`: the cells' shapes /// are not wanted). fn runs(&mut self, stats: &mut GridStats, cat: &Catalog, ids: &Arc<[PhotoId]>, key: RunsKey, square: bool) -> Arc> { @@ -305,7 +327,7 @@ impl GridCache { /// The shape of each cell of the list last shown (width / height), in list order; empty for /// the square grid. - fn shapes(&self) -> &[f32] { + pub(crate) fn shapes(&self) -> &[f32] { self.read.as_ref().and_then(|r| r.shapes.as_deref()).unwrap_or(&[]) } @@ -447,6 +469,7 @@ fn show_inner(app: &mut LccApp, ui: &mut egui::Ui) { let counted = super::chips::count_text(ids.len(), total, !chips.is_empty()); let cnt = if sel_n > 0 { crate::i18n::tr_format!("{sel_n} selected · {counted}", counted = counted, sel_n = sel_n) } else { counted }; match app.session.browse.clone().filter(|_| app.session.source == lcc_engine::LibrarySource::Folder) { + Some(_) if crate::import_tab::showing(app) => {} Some(b) => { let local = app.caches.grid.local(&app.session.catalog, &ids, generation); folder_header(app, ui, &b, &ids, local, &cnt); @@ -533,7 +556,7 @@ fn show_inner(app: &mut LccApp, ui: &mut egui::Ui) { } let ppp = ui.ctx().pixels_per_point(); let square = app.ui.view == ViewMode::SquareGrid; - let target = app.ui.thumb_size; + let target = app.ui.thumb_size.min(thumb_max(app)); let avail_w = ui.available_width() - 8.0; let by = resolve_group(app.session.sort.group, target); let group_key = match app.session.source { @@ -548,6 +571,12 @@ fn show_inner(app: &mut LccApp, ui: &mut egui::Ui) { // (read even for a published collection: the cell shapes the layout uses come with the runs) let date_runs = app.caches.grid.runs(stats, &app.session.catalog, &ids, runs_key, square); let runs = app.caches.grid.publish(&app.session, &ids, generation).unwrap_or(date_runs); + let cut = if square { + crate::state::THUMB_SIZE_MAX + } else { + photo_cut(app.caches.grid.step.as_ref(), app.caches.grid.shapes(), avail_w, footer, &runs) + }; + app.caches.grid.step = Some(GridStep { avail_w, footer, runs: runs.clone(), square, cut }); // the layout only changes with the photos (and their shapes), the grouping, the width and // the thumbnail size let lay_key = (runs_key, avail_w.to_bits(), target.to_bits(), footer.to_bits(), square); @@ -609,6 +638,8 @@ fn show_inner(app: &mut LccApp, ui: &mut egui::Ui) { egui::scroll_area::ScrollBarVisibility::AlwaysVisible }); let mut viewport_seen = Rect::NOTHING; + // a click on the grid's empty space (below the last row, or beside a photo) clears the selection + let mut empty_click = false; if scroll_to.is_none() && let Some(y) = handle_to.or_else(|| last.as_ref().and_then(|a| a.reflow_offset(lay_id, &ids, &lay))) { @@ -633,7 +664,12 @@ fn show_inner(app: &mut LccApp, ui: &mut egui::Ui) { }; ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none()); } - let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), total_h), Sense::hover()); + // the content's background comes before the cells and headers, which sit above it, so only a + // click on empty space reaches it + let (area, area_resp) = ui.allocate_exact_size(vec2(ui.available_width(), total_h), Sense::click()); + // named for screen readers (and the accessibility test): it is the grid itself + area_resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, crate::i18n::tr("Grid"))); + empty_click = area_resp.clicked(); let origin = area.min; app.grid_scroll = Some(viewport.top()); if let Some(r) = scroll_to { @@ -684,6 +720,10 @@ fn show_inner(app: &mut LccApp, ui: &mut egui::Ui) { group_header(app, ui, run, &ids, hr, true); } }); + if empty_click { + // no photo selected and no active photo (the active photo goes too, as B-C9D3 decides for Cmd+D) + let _ = app.run("library.select", json!({"ids": [], "mode": "replace"})); + } // where the view is in the shoot: "1,234 / 2,233" by the scroll bar while it is dragged or the view scrolls scroll_position_label(app, ui, scroll_rect, viewport_seen, total_h, &ids, &lay); // the Modern layout's fast-scroll handle: where the view is, how far it may go, how tall the shoot is @@ -836,6 +876,124 @@ pub fn layout(aspects: &[f32], groups: &[(usize, usize)], avail_w: f32, target: layout_with_footer(aspects, groups, avail_w, target, square, 0.0) } +/// The largest thumbnail size the grid takes: the slider's top, and the keys' limit. In Photo Grid that is the +/// cut-off ([`photo_cut`]), from the last drawn frame; Square Grid and the rest go to the slider's 480 px. +pub(crate) fn thumb_max(app: &LccApp) -> f32 { + match app.caches.grid.step.as_ref() { + Some(step) if app.ui.view == crate::state::ViewMode::PhotoGrid => step.cut, + _ => crate::state::THUMB_SIZE_MAX, + } +} + +/// The Photo Grid's cut-off: the smallest size from which its rows stay as they are up to the largest size, apart from +/// the last row of each group, which grows alone with the size. Above it only those rows would grow, so the keys and +/// the slider stop there. Kept from the last frame while the width, the strip and the photos are unchanged, since each layout is a pass over every photo. +fn photo_cut(prev: Option<&GridStep>, shapes: &[f32], avail_w: f32, footer: f32, runs: &Arc>) -> f32 { + if let Some(p) = prev + && !p.square + && p.avail_w == avail_w + && p.footer == footer + && Arc::ptr_eq(&p.runs, runs) + { + return p.cut; + } + let spans: Vec<(usize, usize)> = runs.iter().map(|r| (r.start, r.count)).collect(); + let full = |size: f32| row_geoms(&layout_with_footer(shapes, &spans, avail_w, size, false, footer), &spans); + let top = full(crate::state::THUMB_SIZE_MAX); + let room = (crate::state::THUMB_SIZE_MAX - crate::state::THUMB_SIZE_MIN).floor() as u32; + crate::state::THUMB_SIZE_MAX - last_true(room, |k| full(crate::state::THUMB_SIZE_MAX - k as f32) == top) as f32 +} + +/// The largest `k` in `0..=n` for which `holds(k)` is true, given that it holds at 0 and, once false, stays false: +/// a bisection, so the Photo Grid's size searches take about log2(n) layouts, not n. +/// Greedy row packing doesn't strictly guarantee that a layout which changed never changes back; if it did, the search +/// could land past the nearest change, never on a size that is no change (the tests compare it with a 1 px scan). +fn last_true(n: u32, holds: impl Fn(u32) -> bool) -> u32 { + let (mut lo, mut hi) = (0, n); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + if holds(mid) { + lo = mid; + } else { + hi = mid - 1; + } + } + lo +} + +/// The thumbnail size one grid key press moves to. `up` makes the grid bigger. Square Grid: the next size that +/// gives one column fewer (up) or one more (down), so every press changes the column count by one. Photo Grid: the +/// next size at which a full row changes, its photos or its height (the last row grows alone, and doesn't count). +/// `None` at a limit: 90 or 480 px, or one column. +pub(crate) fn next_thumb_size(app: &LccApp, up: bool) -> Option { + let step = app.caches.grid.step.as_ref()?; + let current = app.ui.thumb_size; + let min = crate::state::THUMB_SIZE_MIN; + let max = thumb_max(app); + let current = current.min(max); + if app.ui.view == crate::state::ViewMode::SquareGrid { + // the square layout's gap between cells is 1 px; the half pixels keep each size on its own column count + const GAP: f32 = 1.0; + let w = step.avail_w + GAP; + let cols = (w / (current + GAP)).floor().max(1.0); + let size = if up { + if cols <= 1.0 { + return None; + } + w / cols - GAP + 0.5 + } else { + w / (cols + 1.0) - GAP - 0.5 + }; + return (min..=max).contains(&size).then_some(size); + } + photo_step(|size| rows_at(app, size), current, min, max, up) +} + +/// The next size from `current`, 1 px at a time up (or down) to `max` (`min`), at which `rows` differs from the +/// layout at `current` (see [`row_geoms`]); `None` when it never does. +pub(crate) fn photo_step(rows: impl Fn(f32) -> Option>, current: f32, min: f32, max: f32, up: bool) -> Option { + let here = rows(current)?; + let sign = if up { 1.0 } else { -1.0 }; + let room = (if up { max - current } else { current - min }).floor() as u32; + // the layout stays as it is for a run of sizes; the first one past the run is the step + let same = |k: u32| rows(current + sign * k as f32).is_some_and(|r| here == r); + let k = last_true(room, same) + 1; + (k <= room).then_some(current + sign * k as f32) +} + +/// One row of the Photo Grid's layout: its photos (start, end) and its height (as bits, so equal rows compare +/// equal); see [`row_geoms`]. +pub(crate) type RowGeom = (usize, usize, u32); + +/// The rows the Photo Grid lays out at `size`, from the layout inputs of the last drawn frame (`None` before the +/// grid has drawn). For the thumbnail-size key steps and their tests. +pub(crate) fn rows_at(app: &LccApp, size: f32) -> Option> { + let step = app.caches.grid.step.as_ref()?; + let spans: Vec<(usize, usize)> = step.runs.iter().map(|r| (r.start, r.count)).collect(); + let layout = layout_with_footer(app.caches.grid.shapes(), &spans, step.avail_w, size, false, step.footer); + Some(row_geoms(&layout, &spans)) +} + +/// The rows of a Photo Grid layout as what the eye sees of them: the photos in each and its height. Where a row sits +/// is left out, since a growing row above moves every row below it. The last row of a group is the one that grows +/// with the size when it is not full, so its height is left out too (its photos still count). +pub(crate) fn row_geoms(layout: &GridLayout, groups: &[(usize, usize)]) -> Vec { + // no groups means one group of every photo + let mut ends: std::collections::HashSet = + groups.iter().map(|&(start, count)| start.saturating_add(count).min(layout.cells.len())).collect(); + if groups.is_empty() { + ends.extend(layout.rows.last().map(|r| r.end)); + } + layout + .rows + .iter() + .map(|r| { + let height = if ends.contains(&r.end) { 0 } else { (r.bottom - r.top).to_bits() }; + (r.start, r.end, height) + }) + .collect() +} + /// [`layout`] with a `footer` strip (points) under every cell's picture: the ratings, flags and /// labels the Compact layout shows under the thumbnails rather than over them. The pictures keep /// their sizes; each cell grows by the footer. @@ -1609,19 +1767,17 @@ pub fn open_photo(app: &mut LccApp, id: PhotoId) { let _ = app.run(cmd, json!({})); } -/// The regular album the library shows: the one whose photos can be put in Custom Order. -pub fn custom_order_album(app: &LccApp) -> Option { - match app.session.source { - lcc_engine::LibrarySource::Album(a) if app.session.catalog.has_custom_order(a) => Some(a), - _ => None, - } +/// What the library shows whose photos can be put in Custom Order: a regular album, or a folder +/// of the Folders panel shown on its own (see [`lcc_engine::CustomOrderSource`]). +pub fn custom_order_source(app: &LccApp) -> Option { + app.session.custom_order_source() } -/// Photos dragged over a thumbnail of a regular album: a line on the side they would land -/// (before this photo, or after it), and on release they move there in Custom Order (switching the -/// sort to it, as Lightroom Classic does). +/// Photos dragged over a thumbnail of a regular album, or of a folder shown on its own: a line on +/// the side they would land (before this photo, or after it), and on release they move there in +/// Custom Order (switching the sort to it, as Lightroom Classic does). pub(crate) fn reorder_drop(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, dragged: &[u64]) { - let Some(album) = custom_order_album(app).filter(|_| !dragged.contains(&id.0)) else { return }; + let Some(source) = custom_order_source(app).filter(|_| !dragged.contains(&id.0)) else { return }; let (pos, released) = ui.input(|i| (i.pointer.latest_pos(), i.pointer.any_released())); let Some(pos) = pos.filter(|p| r.contains(*p) && ui.clip_rect().contains(*p)) else { return }; let t = Tokens::get(ui.ctx()); @@ -1639,7 +1795,12 @@ pub(crate) fn reorder_drop(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId, r: vis.iter().position(|v| *v == id).and_then(|i| vis.get(i + 1).copied()) }; app.ui.dragging_photos = None; - if let Err(e) = app.run("album.orderPhotos", json!({"album": album.0, "ids": dragged, "before": before.map(|b| b.0)})) { + // an album's photos are moved with album.orderPhotos, a folder's own with folder.orderPhotos + let (cmd, params) = match &source { + lcc_engine::CustomOrderSource::Album(a) => ("album.orderPhotos", json!({"album": a.0, "ids": dragged, "before": before.map(|b| b.0)})), + lcc_engine::CustomOrderSource::Folder(path) => ("folder.orderPhotos", json!({"folder": path, "ids": dragged, "before": before.map(|b| b.0)})), + }; + if let Err(e) = app.run(cmd, params) { app.toast_error(ui.ctx(), e); } } @@ -1852,14 +2013,14 @@ pub fn label_items(app: &mut LccApp, ui: &mut egui::Ui, current: Option ui.separator(); } for s in app.ui.sidebar.sections().iter().filter(|s| s.id.available()) { - let shown = ui.selectable_label(!s.hidden, crate::i18n::tr(s.id.title())); + let shown = ui.pick_label(!s.hidden, crate::i18n::tr(s.id.title())); register(ui.ctx(), format!("sidebarMenu:section:{}", s.id.id()), shown.rect); if shown.clicked() { run = Some(("view.sidebarSection", json!({"section": s.id.id(), "show": s.hidden}))); diff --git a/crates/ui-egui/src/panels/mask_pickers.rs b/crates/ui-egui/src/panels/mask_pickers.rs index 0a6f402d3b..3bd8b33ce8 100644 --- a/crates/ui-egui/src/panels/mask_pickers.rs +++ b/crates/ui-egui/src/panels/mask_pickers.rs @@ -4,6 +4,7 @@ //! //! Behaviour ported from OneSlips' fork (`smart_people.rs`), drawn in the app's own widgets. +use crate::popup_typeahead::PopupItems; use lcc_catalog::PhotoId; use serde_json::json; @@ -56,7 +57,7 @@ pub fn people_picker(app: &mut LccApp, ui: &mut egui::Ui, photo: PhotoId) { }; let mut names: Vec> = Vec::new(); ui.horizontal_wrapped(|ui| { - let r = ui.selectable_label(person == 0, tr("Everyone")); + let r = ui.pick_label(person == 0, tr("Everyone")); register(ui.ctx(), "maskPeople:person:0", r.rect); if r.clicked() { person = 0; @@ -76,7 +77,7 @@ pub fn people_picker(app: &mut LccApp, ui: &mut egui::Ui, photo: PhotoId) { Some(name) => name, None => crate::i18n::tr_format!("Person {n}", n = n), }; - let r = ui.selectable_label(person == k, label); + let r = ui.pick_label(person == k, label); register(ui.ctx(), format!("maskPeople:person:{n}"), r.rect); if r.clicked() { person = k; diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index 534c62cb5f..47a55ff38a 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -1,5 +1,6 @@ //! The Masking panel: create masks, list them, edit components and local adjustments. +use crate::popup_typeahead::PopupItems; use egui::{Align2, Rect, Sense, Stroke, pos2, vec2}; use lcc_catalog::PhotoId; use lcc_develop::{ControlSpec, LocalAdjustments, MaskShape, Section, Track}; @@ -1695,12 +1696,12 @@ fn who_picker(app: &mut LccApp, ui: &mut egui::Ui, photo: PhotoId, comp: usize, ui.add_space(if crate::theme::compact(ui.ctx()) { 4.0 } else { 20.0 }); ui.label(tr("Who")); let r = egui::ComboBox::from_id_salt(("maskWho", comp)).selected_text(current).show_ui(ui, |ui| { - if ui.selectable_label(who.is_none() && *person == 0, tr("Everyone")).clicked() { + if ui.pick_label(who.is_none() && *person == 0, tr("Everyone")).clicked() { chosen = Some(None); } for n in &names { let on = matches!(who, Some(lcc_develop::recipe::Who::Name(x)) if x.eq_ignore_ascii_case(n)); - if ui.selectable_label(on, n).clicked() { + if ui.pick_label(on, n).clicked() { chosen = Some(Some(lcc_develop::recipe::Who::Name(n.clone()))); } } @@ -1709,7 +1710,7 @@ fn who_picker(app: &mut LccApp, ui: &mut egui::Ui, photo: PhotoId, comp: usize, } for r in &roles { let on = matches!(who, Some(lcc_develop::recipe::Who::Role(x)) if x.eq_ignore_ascii_case(r)); - if ui.selectable_label(on, r).clicked() { + if ui.pick_label(on, r).clicked() { chosen = Some(Some(lcc_develop::recipe::Who::Role(r.clone()))); } } diff --git a/crates/ui-egui/src/panels/metadata.rs b/crates/ui-egui/src/panels/metadata.rs index de39aaa48e..93b180bbe9 100644 --- a/crates/ui-egui/src/panels/metadata.rs +++ b/crates/ui-egui/src/panels/metadata.rs @@ -3,6 +3,7 @@ //! and editing many photos at once — a field whose value differs across the selection shows //! `` and typing into it sets every selected photo. +use crate::popup_typeahead::PopupItems; use std::sync::Arc; use egui::{Sense, vec2}; @@ -371,7 +372,7 @@ fn toolbar(app: &mut LccApp, ui: &mut egui::Ui, ids: &[u64]) { let current = PRESETS.iter().find(|(k, _)| *k == app.ui.lib.metadata_preset).map_or("Default", |(_, l)| *l); let r = egui::ComboBox::from_id_salt("metadata-panel-preset").selected_text(crate::i18n::tr(current)).show_ui(ui, |ui| { for (k, l) in PRESETS { - if ui.selectable_label(k == app.ui.lib.metadata_preset, crate::i18n::tr(l)).clicked() { + if ui.pick_label(k == app.ui.lib.metadata_preset, crate::i18n::tr(l)).clicked() { let _ = app.run("metadata.panelPreset", json!({"preset": k})); } } @@ -520,7 +521,7 @@ fn copyright_status(app: &mut LccApp, ui: &mut egui::Ui, photos: &[Arc]) let text = if mixed { MIXED.to_string() } else { crate::i18n::tr(current.label()).to_string() }; let r = egui::ComboBox::from_id_salt("info-copyright-status").selected_text(text).show_ui(ui, |ui| { for st in lcc_catalog::CopyrightStatus::ALL { - if ui.selectable_label(!mixed && st == current, crate::i18n::tr(st.label())).clicked() && (mixed || st != current) { + if ui.pick_label(!mixed && st == current, crate::i18n::tr(st.label())).clicked() && (mixed || st != current) { let _ = app.run("photo.setMeta", json!({"copyrightStatus": st.id()})); } } @@ -546,6 +547,28 @@ fn file_name(app: &mut LccApp, ui: &mut egui::Ui, photos: &[Arc]) { { ui.label(egui::RichText::new(format!("{} {n}", crate::i18n::tr("Copy Name:"))).size(11.5).color(t.text_label)); } + // the companion JPEG beside this raw (issue #1692): named, and shown where it lives + if let [p] = photos + && let Some(c) = &p.companion_jpeg + { + ui.horizontal(|ui| { + let name = std::path::Path::new(c).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| c.clone()); + let r = ui + .label(egui::RichText::new(format!("{} {name}", crate::i18n::tr("Companion JPEG:"))).size(11.5).color(t.text_label)) + .on_hover_text(crate::i18n::tr("The JPEG beside this raw's file, kept with it: not a photo of its own.")); + if app.services.reveal.is_some() { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::icon_button(ui, "infoCompanion", Icon::Folder, vec2(20.0, 20.0), false, true, crate::menus::reveal_label()) + .clicked() + && let Some(reveal) = app.services.reveal.as_mut() + { + let _ = reveal(c); + } + }); + } + r + }); + } ui.add_space(4.0); } diff --git a/crates/ui-egui/src/panels/ml_models.rs b/crates/ui-egui/src/panels/ml_models.rs index ccad6f03f8..555af47093 100644 --- a/crates/ui-egui/src/panels/ml_models.rs +++ b/crates/ui-egui/src/panels/ml_models.rs @@ -2,6 +2,7 @@ use crate::i18n::{tr, tr_format}; use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::RichText; use serde_json::{Value, json}; @@ -174,16 +175,16 @@ pub fn ml_device_selector(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, statu let mut selected = normalized_before.clone(); super::settings::row(ui, t, crate::i18n::tr("AI embedding device"), |ui| { let combo = crate::widgets::combo_box("settingsMlDevice").selected_text(current).width(260.0).show_ui(ui, |ui| { - let r = ui.selectable_value(&mut selected, String::new(), auto.as_str()); + let r = ui.pick_value(&mut selected, String::new(), auto.as_str()); register(ui.ctx(), "button:settingsMlDevice-auto", r.rect); - let r = ui.selectable_value(&mut selected, "cpu".to_string(), cpu.as_str()); + let r = ui.pick_value(&mut selected, "cpu".to_string(), cpu.as_str()); register(ui.ctx(), "button:settingsMlDevice-cpu", r.rect); for (i, d) in gpu_cards.iter().enumerate() { let id = d["id"].as_str().unwrap_or(""); let name = d["name"].as_str().unwrap_or(id); let usable = d["usable"].as_bool().unwrap_or(true); let why_not = d["whyNot"].as_str(); - let r = ui.add_enabled_ui(usable, |ui| ui.selectable_value(&mut selected, id.to_string(), name)).inner; + let r = ui.add_enabled_ui(usable, |ui| ui.pick_value(&mut selected, id.to_string(), name)).inner; let r = match why_not { Some(why) => r.on_disabled_hover_text(why), None => r, diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 0d97bb2b81..2bfd659b80 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -71,6 +71,7 @@ pub mod rules_move; pub mod second; pub mod settings; pub mod settings_develop; +pub mod settings_external; pub mod settings_folders; pub mod settings_profiles; pub mod slide_layout; diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 5a231bd0d4..cf37ffadf7 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -3,6 +3,7 @@ //! its triangle picks it). //! A click or drag pans the loupe (and opens it from the grids), like Lightroom Classic. +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use serde_json::json; @@ -116,7 +117,7 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { triangle(ui.painter(), pos2(r.right() - 6.0, r.center().y), true, col); egui::Popup::menu(ar).show(|ui| { for (i, (name, _)) in ZOOM_LEVELS.iter().enumerate() { - if ui.selectable_label(*name == custom, level_label(name)).clicked() { + if ui.pick_label(*name == custom, level_label(name)).clicked() { ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("navigator-custom"), i)); if app.ui.view != ViewMode::Detail { let _ = app.run("view.loupe", json!({})); diff --git a/crates/ui-egui/src/panels/peer_sync.rs b/crates/ui-egui/src/panels/peer_sync.rs index de0ce655ac..bffff31e0c 100644 --- a/crates/ui-egui/src/panels/peer_sync.rs +++ b/crates/ui-egui/src/panels/peer_sync.rs @@ -10,6 +10,7 @@ //! syncs, and [`waiting`] counts what needs an answer (the top bar's cloud shows it). use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::collections::{BTreeMap, BTreeSet}; use egui::RichText; @@ -877,7 +878,7 @@ fn picker(ui: &mut egui::Ui, r: &Row) -> Option<(Value, &'static str)> { }; if r.mine { for (g, label, why) in GRANTS { - if ui.selectable_label(g == r.grant, tr(label)).clicked() && g != r.grant { + if ui.pick_label(g == r.grant, tr(label)).clicked() && g != r.grant { out = Some((json!(g.id()), "sync.allow")); } small(ui, why); @@ -889,7 +890,7 @@ fn picker(ui: &mut egui::Ui, r: &Row) -> Option<(Value, &'static str)> { (true, Take::FullQuality) => "The originals come from Immich; edits go to your other devices.", _ => why, }; - if ui.selectable_label(*k == r.take, tr(label)).clicked() && *k != r.take { + if ui.pick_label(*k == r.take, tr(label)).clicked() && *k != r.take { out = Some((json!(k.id()), "sync.take")); } small(ui, why); diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 00bef58840..ffaa5704ac 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -6,6 +6,7 @@ //! //! The engine does the looking (`faces.person`); this draws it. Only the rows on screen ask for a face render. +use crate::popup_typeahead::PopupItems; use std::sync::Arc; use egui::{Align2, Color32, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2}; @@ -78,21 +79,22 @@ pub(crate) fn follow_filter(app: &mut LccApp) { } } -/// The page for `name`, asked for again only when the catalog changed, or (while the scan runs) at most once a second -/// as it learns more faces. +/// The page for `name`, asked for again only when the catalog or the sort changed, or (while the scan runs) at most +/// once a second as it learns more faces. fn page_for(app: &mut LccApp, name: &str, now: f64) -> Arc { follow_filter(app); - let (rev, indexed) = (app.session.catalog.revision, app.caches.faces_indexed); - if let Some((n, r, i, at, page)) = &app.caches.person_page + let (rev, indexed, sort) = (app.session.catalog.revision, app.caches.faces_indexed, app.ui.person_sort); + if let Some((n, r, i, at, cached_sort, page)) = &app.caches.person_page && n == name && *r == rev + && *cached_sort == sort && (*i == indexed || now - *at < 1.0) { return page.clone(); } - let v = app.session.execute("faces.person", &json!({"name": name, "scope": "filter"})).unwrap_or(Value::Null); + let v = app.session.execute("faces.person", &json!({"name": name, "scope": "filter", "sort": sort.id()})).unwrap_or(Value::Null); let page = Arc::new(parse(&v)); - app.caches.person_page = Some((name.to_string(), rev, indexed, now, page.clone())); + app.caches.person_page = Some((name.to_string(), rev, indexed, now, sort, page.clone())); page } @@ -269,7 +271,7 @@ pub(crate) fn handle_bulk_key(app: &mut LccApp, ctx: &egui::Context) -> bool { if !ctx.input(|i| i.modifiers == egui::Modifiers::NONE && i.key_pressed(egui::Key::A)) { return false; } - let Some((cached_name, cached_revision, _, _, page)) = &app.caches.person_page else { return false }; + let Some((cached_name, cached_revision, _, _, _, page)) = &app.caches.person_page else { return false }; if *cached_name != name || *cached_revision != app.session.catalog.revision { return false; } @@ -325,6 +327,15 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui, name: &str) { let _ = app.run("library.filter", json!({"person": shown_name})); let _ = app.run("view.photoGrid", json!({})); } + // the faces' order (issue #1691): picking one asks for the page again with `faces.person`'s `sort` + let combo = + crate::widgets::combo_box("person:sort").selected_text(crate::i18n::tr(app.ui.person_sort.title())).width(130.0).show_ui(ui, |ui| { + for s in crate::state::PersonSort::ALL { + let r = ui.pick_value(&mut app.ui.person_sort, s, crate::i18n::tr(s.title())); + register(ui.ctx(), format!("person:sort:{}", s.id()), r.rect); + } + }); + register(ui.ctx(), "combo:personSort", combo.response.rect); }); }); ui.add_space(6.0); diff --git a/crates/ui-egui/src/panels/plugin_filters.rs b/crates/ui-egui/src/panels/plugin_filters.rs index 0265a74631..3ae0d18645 100644 --- a/crates/ui-egui/src/panels/plugin_filters.rs +++ b/crates/ui-egui/src/panels/plugin_filters.rs @@ -3,6 +3,7 @@ //! manifest parameters. Every edit goes through the `develop.pluginFilter.*` commands; a slider drag //! is wrapped in `develop.beginInteraction` / `endInteraction`, so it is one History step. +use crate::popup_typeahead::PopupItems; use egui::{Color32, RichText}; use lcc_develop::controls::{ControlSpec, Section, Track}; use lcc_develop::{DevelopSettings, FilterStage, PLUGIN_FILTERS_SECTION, PluginFilter}; @@ -396,7 +397,7 @@ fn row(ui: &mut egui::Ui, f: &PluginFilter, i: usize, n: usize, st: &RowState, o let width = (ui.available_width() - 4.0).max(60.0); let r = egui::ComboBox::from_id_salt("stage").width(width).selected_text(name(f.stage)).show_ui(ui, |ui| { for (s, key) in [(FilterStage::Source, "source"), (FilterStage::Display, "display")] { - if ui.selectable_label(f.stage == s, name(s)).clicked() && f.stage != s { + if ui.pick_label(f.stage == s, name(s)).clicked() && f.stage != s { out.push(Action::Run("develop.pluginFilter.set", json!({"uid": uid, "stage": key}))); } } @@ -418,12 +419,12 @@ fn row(ui: &mut egui::Ui, f: &PluginFilter, i: usize, n: usize, st: &RowState, o let width = (ui.available_width() - 70.0).max(60.0); let now = f.mask.map_or_else(|| tr("Whole Photo").to_string(), |m| mask_name(m.id)); let r = egui::ComboBox::from_id_salt("mask").width(width).selected_text(now).show_ui(ui, |ui| { - if ui.selectable_label(f.mask.is_none(), tr("Whole Photo")).clicked() && f.mask.is_some() { + if ui.pick_label(f.mask.is_none(), tr("Whole Photo")).clicked() && f.mask.is_some() { out.push(Action::Run("develop.pluginFilter.set", json!({"uid": uid, "mask": null}))); } for (id, _) in &st.masks { let on = f.mask.is_some_and(|m| m.id == *id); - if ui.selectable_label(on, mask_name(*id)).clicked() && !on { + if ui.pick_label(on, mask_name(*id)).clicked() && !on { let invert = f.mask.is_some_and(|m| m.invert); out.push(Action::Run("develop.pluginFilter.set", json!({"uid": uid, "mask": {"id": id, "invert": invert}}))); } @@ -639,7 +640,7 @@ fn param(ui: &mut egui::Ui, uid: u32, name: &str, key: &str, s: &Value, cur: Opt let width = (ui.available_width() - 4.0).max(60.0); let r = egui::ComboBox::from_id_salt(("choice", key)).width(width).selected_text(now).show_ui(ui, |ui| { let mut pick = |ui: &mut egui::Ui, o: &str| { - if ui.selectable_label(o == now, o).clicked() && o != now { + if ui.pick_label(o == now, o).clicked() && o != now { out.push(set(json!(o))); } }; diff --git a/crates/ui-egui/src/panels/plugins.rs b/crates/ui-egui/src/panels/plugins.rs index 8f39b23120..0ab34505b5 100644 --- a/crates/ui-egui/src/panels/plugins.rs +++ b/crates/ui-egui/src/panels/plugins.rs @@ -43,6 +43,7 @@ //! [`take_drop`]. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; @@ -791,12 +792,12 @@ pub fn export_destination_ui(ui: &mut egui::Ui) { ui.horizontal(|ui| { ui.label(tr("Then send to")); let r = egui::ComboBox::from_id_salt("export-plugin-destination").selected_text(text).show_ui(ui, |ui| { - if ui.selectable_label(current.is_none(), tr("None")).clicked() { + if ui.pick_label(current.is_none(), tr("None")).clicked() { chosen = None; } for (plugin, d) in &offered { let on = current.is_some_and(|(p, cd)| p == plugin && cd.id == d.id); - if ui.selectable_label(on, &d.name).clicked() && !on { + if ui.pick_label(on, &d.name).clicked() && !on { // the values it last ran with let values = lcc_engine::cmd::plugins::manager().as_ref().map(|m| m.destination_values(plugin, &d.id)).unwrap_or_default(); chosen = Some((plugin.clone(), d.id.clone(), Value::Object(values))); @@ -916,11 +917,11 @@ fn metadata_field_ui(ui: &mut egui::Ui, plugin: &str, photo: u64, f: &Value, mix &cur }; let r = egui::ComboBox::from_id_salt(("plugin-meta", plugin, key)).selected_text(shown).show_ui(ui, |ui| { - if ui.selectable_label(cur.is_empty() && !mixed, crate::i18n::tr("None")).clicked() && (mixed || !cur.is_empty()) { + if ui.pick_label(cur.is_empty() && !mixed, crate::i18n::tr("None")).clicked() && (mixed || !cur.is_empty()) { out = Some(Value::Null); } for o in f["options"].as_array().into_iter().flatten().filter_map(Value::as_str) { - if ui.selectable_label(cur == o && !mixed, o).clicked() && (mixed || cur != o) { + if ui.pick_label(cur == o && !mixed, o).clicked() && (mixed || cur != o) { out = Some(json!(o)); } } @@ -2492,7 +2493,7 @@ fn field_ui(ui: &mut egui::Ui, scope: &str, f: &Value, values: &mut Value) -> bo let mut cur = was.clone(); let r = egui::ComboBox::from_id_salt(("plugin-field", scope, k)).selected_text(cur.clone()).show_ui(ui, |ui| { for o in f["options"].as_array().into_iter().flatten().filter_map(Value::as_str) { - ui.selectable_value(&mut cur, o.to_string(), o); + ui.pick_value(&mut cur, o.to_string(), o); } }); crate::widgets::register(ui.ctx(), format!("pluginChoice:{scope}:{k}"), r.response.rect); diff --git a/crates/ui-egui/src/panels/presets_manager.rs b/crates/ui-egui/src/panels/presets_manager.rs index 46f583dfc5..5536e8a5e4 100644 --- a/crates/ui-egui/src/panels/presets_manager.rs +++ b/crates/ui-egui/src/panels/presets_manager.rs @@ -18,6 +18,7 @@ //! window opens at a size that fits the screen, never grows from its content, and keeps the size //! the user drags it to (see [`window_size`]). +use crate::popup_typeahead::PopupItems; use std::collections::HashSet; use std::sync::Arc; @@ -474,7 +475,7 @@ fn confirm_group_delete( let r = crate::widgets::combo_box(("presetsManagerMoveTo", g)).width(200.0).selected_text(label).height(300.0).show_ui(ui, |ui| { for o in others { - if ui.selectable_label(move_to.as_deref() == Some(o.as_str()), o.as_str()).clicked() { + if ui.pick_label(move_to.as_deref() == Some(o.as_str()), o.as_str()).clicked() { *move_to = Some(o.clone()); } } @@ -627,7 +628,7 @@ fn preset_row( ui.set_min_width(200.0); egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { for g in groups { - if ui.selectable_label(*g == p.group, g.as_str()).clicked() { + if ui.pick_label(*g == p.group, g.as_str()).clicked() { actions.push(("preset.move", json!({"id": id, "group": g}))); ui.close(); } diff --git a/crates/ui-egui/src/panels/profile_manager.rs b/crates/ui-egui/src/panels/profile_manager.rs index ea8dd49ebb..caa379aae0 100644 --- a/crates/ui-egui/src/panels/profile_manager.rs +++ b/crates/ui-egui/src/panels/profile_manager.rs @@ -20,6 +20,7 @@ //! ([`super::presets_manager::window_size`]). use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -651,7 +652,7 @@ fn item_row( ui.set_min_width(200.0); egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { for other in look_groups { - if ui.selectable_label(*other == g.name, other.as_str()).clicked() { + if ui.pick_label(*other == g.name, other.as_str()).clicked() { actions.push(("profile.setGroup", json!({"id": id, "group": other}))); ui.close(); } diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index 3177529bc7..16b9508f84 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -2,6 +2,7 @@ //! profile as a live thumbnail of the current photo, grouped (Favorites first), with a favourite //! star, the applied profile's amount, a temporary loupe preview while hovering and apply on click. +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2}; use lcc_catalog::PhotoId; use lcc_develop::DevelopSettings; @@ -54,7 +55,7 @@ fn camera_profile_row(app: &mut LccApp, ui: &mut egui::Ui, d: &DevelopSettings, ui.label(egui::RichText::new(crate::i18n::tr("Camera Profile")).color(t.text_dim).font(t.font(13.0))); let r = crate::widgets::combo_box("cameraProfile").width((ui.available_width() - 24.0).max(80.0)).selected_text(shown).show_ui(ui, |ui| { for (o, n) in &options { - ui.selectable_value(&mut choice, o.clone(), n); + ui.pick_value(&mut choice, o.clone(), n); } }); register(ui.ctx(), "cameraProfile", r.response.rect); diff --git a/crates/ui-egui/src/panels/publish.rs b/crates/ui-egui/src/panels/publish.rs index a39105226d..c29c3600eb 100644 --- a/crates/ui-egui/src/panels/publish.rs +++ b/crates/ui-egui/src/panels/publish.rs @@ -7,6 +7,7 @@ //! sends on a worker thread. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Align2, Sense, pos2, vec2}; use serde_json::{Value, json}; @@ -369,7 +370,7 @@ fn setup_form(app: &mut LccApp, ui: &mut egui::Ui, form: &mut Form) { let r = egui::ComboBox::from_id_salt("publishSetUpKind").selected_text(kind_label(&form.kind, &form.plugins)).show_ui(ui, |ui| { for k in &kinds { let label = kind_label(k, &form.plugins); - ui.selectable_value(&mut form.kind, k.clone(), label); + ui.pick_value(&mut form.kind, k.clone(), label); } }); register(ui.ctx(), "publishSetUpKind", r.response.rect); @@ -391,9 +392,9 @@ fn setup_form(app: &mut LccApp, ui: &mut egui::Ui, form: &mut Form) { let shown = if form.sftp_saved.is_empty() { other.clone() } else { form.sftp_saved.clone() }; let r = egui::ComboBox::from_id_salt("publishSetUpServer").selected_text(shown).show_ui(ui, |ui| { for s in &form.servers { - ui.selectable_value(&mut form.sftp_saved, s.clone(), s); + ui.pick_value(&mut form.sftp_saved, s.clone(), s); } - ui.selectable_value(&mut form.sftp_saved, String::new(), other); + ui.pick_value(&mut form.sftp_saved, String::new(), other); }); register(ui.ctx(), "publishSetUpServer", r.response.rect); if form.sftp_saved.is_empty() { @@ -432,7 +433,7 @@ fn setup_form(app: &mut LccApp, ui: &mut egui::Ui, form: &mut Form) { let shown = form.accounts.iter().find(|(id, _)| *id == form.immich_account).map(|(_, l)| l.clone()).unwrap_or_default(); let r = egui::ComboBox::from_id_salt("publishSetUpAccount").selected_text(shown).show_ui(ui, |ui| { for (id, label) in &form.accounts { - ui.selectable_value(&mut form.immich_account, id.clone(), label); + ui.pick_value(&mut form.immich_account, id.clone(), label); } }); register(ui.ctx(), "publishSetUpAccount", r.response.rect); @@ -441,7 +442,7 @@ fn setup_form(app: &mut LccApp, ui: &mut egui::Ui, form: &mut Form) { let shown = sends.iter().find(|(k, _)| *k == form.immich_send).map(|(_, l)| crate::i18n::tr(l)).unwrap_or_default(); let r = egui::ComboBox::from_id_salt("publishSetUpSend").selected_text(shown).show_ui(ui, |ui| { for (k, l) in sends { - ui.selectable_value(&mut form.immich_send, k.to_string(), crate::i18n::tr(l)); + ui.pick_value(&mut form.immich_send, k.to_string(), crate::i18n::tr(l)); } }); register(ui.ctx(), "publishSetUpSend", r.response.rect); diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index d306bfa9bf..43ee447a21 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -2,6 +2,7 @@ //! Keywords, Versions, Activity. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Align2, Rect, Sense, pos2, vec2}; use lcc_catalog::PhotoId; use serde_json::json; @@ -1062,7 +1063,7 @@ pub(crate) fn tool_overlay_options(app: &mut LccApp, ui: &mut egui::Ui) { .on_hover_text(crate::i18n::tr("When pins show on the photo (Shift+H cycles)")); egui::Popup::menu(&r).show(|ui| { for m in ToolOverlay::ALL { - let item = ui.selectable_label(m == current, crate::i18n::tr(m.label())); + let item = ui.pick_label(m == current, crate::i18n::tr(m.label())); register(ui.ctx(), format!("toolOverlay:{}", m.name()), item.rect); if item.clicked() { let _ = app.run("view.toolOverlay", json!({"mode": m.name()})); @@ -1417,7 +1418,7 @@ fn keyword_set(app: &mut LccApp, ui: &mut egui::Ui) { .show_ui(ui, |ui| { for set in sets.field("sets").as_array().into_iter().flatten() { let name = set["name"].as_str().unwrap_or_default(); - if ui.selectable_label(name == current, crate::i18n::builtin_label(name, name == lcc_engine::cmd::keywords::RECENT)).clicked() { + if ui.pick_label(name == current, crate::i18n::builtin_label(name, name == lcc_engine::cmd::keywords::RECENT)).clicked() { let _ = app.run("keyword.useSet", json!({"name": name})); } } diff --git a/crates/ui-egui/src/panels/rules_editor.rs b/crates/ui-egui/src/panels/rules_editor.rs index 82acf7c12f..bfa572a17b 100644 --- a/crates/ui-egui/src/panels/rules_editor.rs +++ b/crates/ui-egui/src/panels/rules_editor.rs @@ -1,6 +1,7 @@ //! The smart-album rule editor: match all / any / none of a list of rules (field, operator, //! value), with nested groups. Field and operator lists come from `lcc_catalog::rules`. +use crate::popup_typeahead::PopupItems; use egui::RichText; use lcc_catalog::rules::{FIELD_GROUPS, Kind, Problem, TOP_LEVEL_FIELDS, bool_value, field_kind, field_label, ops_for, takes_value}; use lcc_catalog::{Match, Rule, RuleSet}; @@ -53,7 +54,7 @@ fn match_combo(ui: &mut egui::Ui, salt: &str, m: &mut Match) { }; crate::widgets::combo_box(format!("{salt}-match")).width(64.0).selected_text(crate::i18n::tr(label(*m))).show_ui(ui, |ui| { for x in [Match::All, Match::Any, Match::None] { - ui.selectable_value(m, x, crate::i18n::tr(label(x))); + ui.pick_value(m, x, crate::i18n::tr(label(x))); } }); } @@ -64,8 +65,10 @@ fn text_value(ui: &mut egui::Ui, v: &mut Value, width: f32, hint: &str, salt: &s Value::Null => String::new(), other => other.to_string(), }; - let r = ui.add(egui::TextEdit::singleline(&mut s).hint_text(crate::i18n::tr(hint)).desired_width(width)); - register(ui.ctx(), format!("field:{salt}"), r.rect); + let widget = format!("field:{salt}"); + let r = + crate::panels::dialogs::confirm_field(ui, crate::text_field::TextField::singleline(&widget, &mut s).hint(crate::i18n::tr(hint)).width(width)) + .response; if r.changed() { *v = json!(s); } @@ -152,7 +155,7 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: & ui.add(egui::DragValue::new(&mut n).range(1.0..=10_000.0).clamp_existing_to_range(false).speed(0.2).fixed_decimals(0)).changed(); crate::widgets::combo_box(format!("{salt}-unit")).width(70.0).selected_text(crate::i18n::tr(&unit)).show_ui(ui, |ui| { for u in ["hours", "days", "weeks", "months", "years"] { - if ui.selectable_label(unit.trim_end_matches('s') == u.trim_end_matches('s'), crate::i18n::tr(u)).clicked() { + if ui.pick_label(unit.trim_end_matches('s') == u.trim_end_matches('s'), crate::i18n::tr(u)).clicked() { unit = u.to_string(); changed = true; } @@ -201,7 +204,7 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: & let cur = v.as_str().unwrap_or("").to_string(); crate::widgets::combo_box(format!("{salt}-choice")).width(120.0).selected_text(crate::i18n::choice_text(field, &cur)).show_ui(ui, |ui| { for (id, _) in c.iter() { - if ui.selectable_label(cur == *id, crate::i18n::choice_text(field, id)).clicked() { + if ui.pick_label(cur == *id, crate::i18n::choice_text(field, id)).clicked() { *v = json!(id); } } @@ -214,7 +217,7 @@ fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: & let text = cur.map_or_else(|| v.to_string(), |b| crate::i18n::bool_text(b).to_string()); crate::widgets::combo_box(format!("{salt}-bool")).width(60.0).selected_text(text).show_ui(ui, |ui| { for b in [true, false] { - if ui.selectable_label(cur == Some(b), crate::i18n::bool_text(b)).clicked() { + if ui.pick_label(cur == Some(b), crate::i18n::bool_text(b)).clicked() { *v = json!(b); } } @@ -245,7 +248,7 @@ fn field_menu(ui: &mut egui::Ui, salt: &str, field: &mut String, op: &mut String let r = crate::widgets::combo_box(format!("{salt}-field")).width(150.0).height(400.0).selected_text(crate::i18n::tr(&label)).show_ui(ui, |ui| { let mut pick = None; let mut item = |ui: &mut egui::Ui, id: &'static str| { - let r = ui.selectable_label(current == id, crate::i18n::tr(field_label(id).unwrap_or(id))); + let r = ui.pick_label(current == id, crate::i18n::tr(field_label(id).unwrap_or(id))); register(ui.ctx(), format!("ruleFieldItem:{id}:{salt}"), r.rect); if r.clicked() { pick = Some(id); @@ -275,7 +278,7 @@ fn field_menu(ui: &mut egui::Ui, salt: &str, field: &mut String, op: &mut String let text = if lcc_catalog::rules::plugin_field(¤t).is_some() { text.strong() } else { text }; let r = crate::widgets::menu_button(ui, text, |ui| { for (id, name) in &plugin_fields { - let r = ui.selectable_label(current == *id, name); + let r = ui.pick_label(current == *id, name); register(ui.ctx(), format!("ruleFieldItem:{id}:{salt}"), r.rect); if r.clicked() { plugin_pick = Some(id.clone()); @@ -409,7 +412,7 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: let op_label = ops_for(kind).iter().find(|o| o.0 == op.as_str()).map_or(op.as_str(), |o| o.1).to_string(); crate::widgets::combo_box(format!("{rsalt}-op")).width(110.0).selected_text(crate::i18n::tr(&op_label)).show_ui(ui, |ui| { for (id, l) in ops_for(kind) { - if ui.selectable_label(op == id, crate::i18n::tr(l)).clicked() && op != id { + if ui.pick_label(op == id, crate::i18n::tr(l)).clicked() && op != id { let was_special = matches!(op.as_str(), "between" | "inLast" | "notInLast") || !takes_value(op); *op = id.to_string(); if was_special || matches!(*id, "between" | "inLast" | "notInLast") || !takes_value(id) { diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index 4e832246c5..d15dfca7b2 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -15,6 +15,7 @@ //! so they travel with the library. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::RichText; use serde_json::{Value, json}; @@ -32,6 +33,7 @@ pub const SECTIONS: &[(&str, &str)] = &[("lensProfiles", "import"), ("autoImport /// under More at the end of the row. pub const TABS: &[(&str, &str)] = &[ ("general", "General"), + ("external", "External Editing"), ("import", "Import"), ("folders", "Folders"), ("performance", "Performance"), @@ -359,6 +361,7 @@ pub(crate) fn tab_body(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, tab: &st fn tab_body_page(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, tab: &str) { match tab { + "external" => super::settings_external::settings_tab(app, ui, t), "import" => import_tab(app, ui, t), "folders" => super::settings_folders::settings_tab(app, ui, t), "performance" => performance_tab(app, ui, t), @@ -627,7 +630,7 @@ fn general_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { let combo = egui::ComboBox::from_id_salt("settingsLanguage").selected_text(current).width(220.0).height(420.0).show_ui(ui, |ui| { // English first, then by each language's own name (as Edit ▸ Language lists them) for (i, language) in crate::i18n::Locale::for_picker().into_iter().enumerate() { - let r = ui.selectable_value(&mut app.ui.language, language, language_label(ui.ctx(), language)); + let r = ui.pick_value(&mut app.ui.language, language, language_label(ui.ctx(), language)); register(ui.ctx(), format!("button:settingsLanguage-{i}"), r.rect); } }); @@ -714,52 +717,6 @@ fn general_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { check(ui, "settings.askBeforeMove", &mut app.ui.settings.ask_before_move, "Confirm before moving photos to another folder on disk"); heading(ui, t, crate::i18n::tr("Dialogs")); check(ui, "settings.closeDialogsOutside", &mut app.ui.settings.close_dialogs_outside, "Close a dialog by clicking outside it"); - heading_help(ui, t, crate::i18n::tr("External Editing"), "externalEditing"); - // Photo ▸ Edit In (#616): the window that asks which file to edit, or the remembered choice - row(ui, t, crate::i18n::tr("Edit In"), |ui| { - use crate::state::EditInMode; - choices( - ui, - "settingsEditInMode", - &[ - (EditInMode::Ask, "Ask"), - (EditInMode::CopyWithAdjustments, "Edit a Copy with Adjustments"), - (EditInMode::Copy, "Edit a Copy"), - (EditInMode::Original, "Edit Original"), - ], - &mut app.ui.settings.edit_in_mode, - ); - }); - row(ui, t, crate::i18n::tr("PhotoCraft"), |ui| { - crate::text_field::TextField::singleline("field:photocraftPath", &mut app.ui.settings.photocraft_path) - .hint(crate::i18n::tr("Found automatically")) - .width(220.0) - .show(ui); - }); - edit_file_rows(ui, t, "photocraftFile", &mut app.ui.settings.photocraft_file); - hint( - ui, - t, - crate::i18n::tr( - "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.", - ), - ); - row(ui, t, crate::i18n::tr("Other editor"), |ui| { - crate::text_field::TextField::singleline("field:externalEditor", &mut app.ui.settings.external_editor) - .hint(crate::i18n::tr("System default")) - .width(220.0) - .show(ui); - }); - edit_file_rows(ui, t, "externalFile", &mut app.ui.settings.external_file); - hint(ui, t, crate::i18n::tr("Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).")); - hint( - ui, - t, - crate::i18n::tr( - "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).", - ), - ); - hint(ui, t, crate::i18n::tr("For more editors, each with its own items in Photo → Edit In, use Photo → Edit In → Edit In Presets….")); } /// A language's name as the picker shows it: its own name (`Deutsch`), or, when no loaded font @@ -790,24 +747,6 @@ pub(crate) fn language_label(ctx: &egui::Context, language: crate::i18n::Locale) english.to_string() } -/// The file Edit In hands an editor: format, colour space and bit depth (`button:{id}Format-…`). -fn edit_file_rows(ui: &mut egui::Ui, t: &Tokens, id: &str, file: &mut crate::state::EditFile) { - use crate::state::{EditFormat, EditSpace}; - row(ui, t, "", |ui| { - choices(ui, &format!("{id}Format"), &[(EditFormat::Psd, "PSD"), (EditFormat::Tiff, "TIFF")], &mut file.format); - ui.separator(); - choices(ui, &format!("{id}Depth"), &[(16u8, "16-bit"), (8, "8-bit")], &mut file.bit_depth); - }); - row(ui, t, "", |ui| { - choices( - ui, - &format!("{id}Space"), - &[(EditSpace::AdobeRgb, "Adobe RGB"), (EditSpace::ProPhoto, "ProPhoto"), (EditSpace::DisplayP3, "P3"), (EditSpace::Srgb, "sRGB")], - &mut file.color_space, - ); - }); -} - // -------------------------------------------------------------------------------------- Import /// A preset picker: `None` = `none_label`. Returns the new choice when it changed. @@ -825,7 +764,7 @@ fn preset_combo(app: &LccApp, ui: &mut egui::Ui, id: &str, current: Option<&str> let r = crate::widgets::combo_box(id).width(240.0).selected_text(text).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show_ui( ui, |ui| { - if ui.selectable_label(current.is_none(), crate::i18n::tr(none_label)).clicked() { + if ui.pick_label(current.is_none(), crate::i18n::tr(none_label)).clicked() { out = Some(None); ui.close(); } @@ -1015,11 +954,11 @@ fn import_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { .selected_text(label) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show_ui(ui, |ui| { - if ui.selectable_label(current == Some(RAW_DEFAULT), crate::i18n::tr("Same as raw default")).clicked() { + if ui.pick_label(current == Some(RAW_DEFAULT), crate::i18n::tr("Same as raw default")).clicked() { pick = Some(json!({"camera": cam, "remove": true})); ui.close(); } - if ui.selectable_label(current.is_none(), crate::i18n::tr("{app} Default")).clicked() { + if ui.pick_label(current.is_none(), crate::i18n::tr("{app} Default")).clicked() { pick = Some(json!({"camera": cam, "preset": null})); ui.close(); } @@ -1068,11 +1007,11 @@ fn import_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { }; let mut pick: Option> = None; let r = crate::widgets::combo_box(&id).width(240.0).selected_text(shown).show_ui(ui, |ui| { - if ui.selectable_label(current.is_none(), &none_label).clicked() { + if ui.pick_label(current.is_none(), &none_label).clicked() { pick = Some(None); } for (pid, name) in profile_options(&camera) { - if ui.selectable_label(current == Some(&pid), &name).clicked() { + if ui.pick_label(current == Some(&pid), &name).clicked() { pick = Some(Some(pid)); } } @@ -1133,11 +1072,11 @@ fn import_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { .width(240.0) .selected_text(cur.clone().unwrap_or_else(|| crate::i18n::tr("None").into())) .show_ui(ui, |ui| { - if ui.selectable_label(cur.is_none(), crate::i18n::tr("None")).clicked() { + if ui.pick_label(cur.is_none(), crate::i18n::tr("None")).clicked() { pick = Some(String::new()); } for m in &app.session.metadata_presets { - if ui.selectable_label(cur.as_deref() == Some(m.name.as_str()), &m.name).clicked() { + if ui.pick_label(cur.as_deref() == Some(m.name.as_str()), &m.name).clicked() { pick = Some(m.name.clone()); } } @@ -1301,11 +1240,11 @@ fn import_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { .width(240.0) .selected_text(cur.clone().unwrap_or_else(|| crate::i18n::tr("None").into())) .show_ui(ui, |ui| { - if ui.selectable_label(cur.is_none(), crate::i18n::tr("None")).clicked() { + if ui.pick_label(cur.is_none(), crate::i18n::tr("None")).clicked() { pick = Some(String::new()); } for m in &app.session.metadata_presets { - if ui.selectable_label(cur.as_deref() == Some(m.name.as_str()), &m.name).clicked() { + if ui.pick_label(cur.as_deref() == Some(m.name.as_str()), &m.name).clicked() { pick = Some(m.name.clone()); } } @@ -1513,10 +1452,10 @@ fn gpu_card_rows(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, crate::i18n::tr("Graphics card for editing"), |ui| { let current = name_of(&app.ui.settings.gpu_card).unwrap_or_else(|| auto.clone()); let combo = crate::widgets::combo_box("settingsGpuCard").selected_text(current).width(260.0).show_ui(ui, |ui| { - let r = ui.selectable_value(&mut app.ui.settings.gpu_card, String::new(), auto.as_str()); + let r = ui.pick_value(&mut app.ui.settings.gpu_card, String::new(), auto.as_str()); register(ui.ctx(), "button:settingsGpuCard-auto", r.rect); for (i, e) in cards.iter().enumerate() { - let r = ui.add_enabled_ui(e.usable, |ui| ui.selectable_value(&mut app.ui.settings.gpu_card, e.key.to_string(), label(e))).inner; + let r = ui.add_enabled_ui(e.usable, |ui| ui.pick_value(&mut app.ui.settings.gpu_card, e.key.to_string(), label(e))).inner; let r = match &e.why_not { Some(why) => r.on_disabled_hover_text(why), None => r, @@ -1549,12 +1488,12 @@ fn gpu_card_rows(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { k => name_of(k).unwrap_or_else(|| auto.clone()), }; let combo = crate::widgets::combo_box("settingsGpuHelper").selected_text(current).width(260.0).show_ui(ui, |ui| { - let r = ui.selectable_value(&mut app.ui.settings.gpu_helper, String::new(), auto_now.as_str()); + let r = ui.pick_value(&mut app.ui.settings.gpu_helper, String::new(), auto_now.as_str()); register(ui.ctx(), "button:settingsGpuHelper-auto", r.rect); - let r = ui.selectable_value(&mut app.ui.settings.gpu_helper, "off".to_string(), off.as_str()); + let r = ui.pick_value(&mut app.ui.settings.gpu_helper, "off".to_string(), off.as_str()); register(ui.ctx(), "button:settingsGpuHelper-off", r.rect); for (i, e) in &others { - let r = ui.selectable_value(&mut app.ui.settings.gpu_helper, e.key.to_string(), label(e)); + let r = ui.pick_value(&mut app.ui.settings.gpu_helper, e.key.to_string(), label(e)); register(ui.ctx(), format!("button:settingsGpuHelper-{i}"), r.rect); } }); @@ -2235,7 +2174,7 @@ pub(super) fn view_options(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { let r = crate::widgets::combo_box(&id).width(220.0).selected_text(crate::i18n::tr(line.label())).show_ui(ui, |ui| { for f in F::ALL { let key = serde_json::to_value(f).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); - let r = ui.selectable_label(line == f, crate::i18n::tr(f.label())); + let r = ui.pick_label(line == f, crate::i18n::tr(f.label())); register(ui.ctx(), format!("button:{id}-{key}"), r.rect); if r.clicked() { *line = *f; diff --git a/crates/ui-egui/src/panels/settings_develop.rs b/crates/ui-egui/src/panels/settings_develop.rs index 6a5e69b3aa..09f122ae7f 100644 --- a/crates/ui-egui/src/panels/settings_develop.rs +++ b/crates/ui-egui/src/panels/settings_develop.rs @@ -4,6 +4,7 @@ //! profiles (Default, Witchcraft) show what they hold but can't be changed. Every change runs //! `view.toolProfile` / `view.toolProfileEdit`, so agents and the CLI can do the same. +use crate::popup_typeahead::PopupItems; use serde_json::{Value, json}; use super::settings::{check, heading, hint, row}; @@ -34,7 +35,7 @@ pub fn settings_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { let mut chosen = profile.id.clone(); let combo = crate::widgets::combo_box("toolProfileSettings").width(220.0).selected_text(profile.label()).show_ui(ui, |ui| { for (id, label) in &all { - let r = ui.selectable_value(&mut chosen, id.clone(), label); + let r = ui.pick_value(&mut chosen, id.clone(), label); register(ui.ctx(), format!("toolProfileSettings:{id}"), r.rect); } }); @@ -152,7 +153,7 @@ fn custom_group(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, profile: &crate } ui.label(egui::RichText::new(crate::i18n::tr(title)).small().weak()); for s in sliders { - let r = ui.selectable_label(false, crate::i18n::tr(s.label)); + let r = ui.pick_label(false, crate::i18n::tr(s.label)); register(ui.ctx(), format!("toolCustomAdd:{}", s.id), r.rect); if r.clicked() { add = Some(s.id.to_string()); diff --git a/crates/ui-egui/src/panels/settings_external.rs b/crates/ui-egui/src/panels/settings_external.rs new file mode 100644 index 0000000000..079c14b20a --- /dev/null +++ b/crates/ui-egui/src/panels/settings_external.rs @@ -0,0 +1,460 @@ +//! Settings ▸ External Editing (its own page): the editors Photo ▸ Edit In offers — the default +//! (the operating system's application for the file), PhotoCraft, and as many saved editors as +//! the user adds, each with the file it hands over — and the question Edit In asks. The saved +//! editors are the engine's Edit In presets (`editors.json`), the same list the Photo ▸ Edit In +//! menu shows, so the page and the menu never disagree. + +use egui::RichText; +use serde_json::json; + +use super::settings::{choices, heading_help, hint, row}; +use crate::LccApp; +use crate::edit_in::Draft; +use crate::i18n::tr; +use crate::state::{EditFormat, EditInMode, EditSpace}; +use crate::theme::Tokens; + +/// The page's local state: which editor row is open for editing, what it is being edited to, and +/// the photo editors the host found (asked for once, when a form first opens its application). +#[derive(Default)] +struct Page { + open: Option, + draft: Option, + detected: Option>, +} + +thread_local! { + static PAGE: std::cell::RefCell = std::cell::RefCell::new(Page::default()); +} + +fn page(f: impl FnOnce(&mut Page) -> R) -> R { + PAGE.with_borrow_mut(f) +} + +/// The format choices the form shows. `original` is not a file format: the editor gets the +/// photo's own file (or its copy) plus an XMP sidecar, whatever the format is. +const FORMATS: &[(&str, &str)] = + &[("tiff", "TIFF"), ("psd", "PSD (layered)"), ("png", "PNG"), ("exr", "OpenEXR"), ("dng", "DNG (+XMP)"), ("original", "Original (+XMP)")]; + +/// The colour spaces a rendered copy takes ([`lcc_engine::cmd::edit_in::space`] parses them). +const SPACES: &[(&str, &str)] = + &[("proPhoto", "ProPhoto RGB"), ("adobeRgb", "Adobe RGB"), ("displayP3", "DisplayP3"), ("srgb", "sRGB"), ("rec2020", "Rec. 2020")]; + +/// The bit-depth label a format's depth shows. +fn depth_label(format: &str, depth: u8) -> &'static str { + match (format, depth) { + ("exr", 16) => "16-bit half float", + (_, 32) => "32-bit float", + (_, 16) => "16-bit", + _ => "8-bit", + } +} + +/// The colour space's name as the summary shows it (the same keys the engine accepts). +fn space_label(s: &str) -> &'static str { + match s { + "srgb" | "sRGB" => "sRGB", + "adobeRgb" => "Adobe RGB", + "displayP3" => "DisplayP3", + "proPhoto" | "prophoto" => "ProPhoto RGB", + _ => "Rec. 2020", + } +} + +/// What a saved editor shows on its row when it is closed: the file it hands over. +fn summary(p: &lcc_engine::cmd::edit_in::EditorPreset) -> String { + use lcc_engine::cmd::edit_in::{Format, Mode}; + match p.mode { + Mode::Original => return tr("the original, with an XMP sidecar").to_string(), + Mode::Copy => return tr("a copy of the original, with an XMP sidecar").to_string(), + _ => (), + } + let f = match p.format { + Format::Tiff => "TIFF", + Format::Psd => "PSD", + Format::Png => "PNG", + Format::Exr => "OpenEXR", + Format::Dng => "DNG", + }; + let depth = match (p.format, p.bit_depth) { + (Format::Exr, 16) => "16-bit half", + (_, 32) => "32-bit float", + (_, 16) => "16-bit", + _ => "8-bit", + }; + match p.format { + Format::Exr | Format::Dng => format!("{f} · {depth}"), + _ => format!("{f} · {depth} · {}", space_label(&p.color_space)), + } +} + +pub(crate) fn settings_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { + // Photo ▸ Edit In (#616): the window that asks which file to edit, or the remembered choice + heading_help(ui, t, "Edit In", "externalEditing"); + row(ui, t, "Edit In", |ui| { + choices( + ui, + "settingsEditInMode", + &[ + (EditInMode::Ask, "Ask"), + (EditInMode::CopyWithAdjustments, "Edit a Copy with Adjustments"), + (EditInMode::Copy, "Edit a Copy"), + (EditInMode::Original, "Edit Original"), + ], + &mut app.ui.settings.edit_in_mode, + ); + }); + + heading_help(ui, t, "Editors", "externalEditing"); + hint( + ui, + t, + "Photo ▸ Edit In lists every editor here. The first two are built in; add as many as you like, and click a row to change what it hands over.", + ); + editor_row(app, ui, t, "default", "Default editor", |app, ui, t| { + hint(ui, t, "the operating system's application for the file type: Edit in Default Editor renders the copy and hands it over"); + file_rows(ui, t, "defaultFile", &mut app.ui.settings.default_file); + }); + editor_row(app, ui, t, "photocraft", "PhotoCraft", |app, ui, t| { + row(ui, t, "Location", |ui| { + crate::text_field::TextField::singleline("field:photocraftPath", &mut app.ui.settings.photocraft_path) + .hint(tr("Found automatically")) + .width(220.0) + .show(ui); + }); + file_rows(ui, t, "photocraftFile", &mut app.ui.settings.photocraft_file); + hint( + ui, + t, + "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.", + ); + }); + + // the saved editors: the engine's Edit In presets, the Photo ▸ Edit In menu's list + let presets = lcc_engine::cmd::edit_in::presets_of(&app.session).unwrap_or_default(); + for p in &presets { + if p.name.is_empty() { + continue; + } + let name = p.name.clone(); + let row_name = name.clone(); + let line = summary(p); + let open = page(|pg| pg.open.as_deref() == Some(name.as_str())); + let draft = open.then(|| page(|pg| pg.draft.take())).flatten(); + row(ui, t, "", |ui| { + let mut text = format!("{} {name}", if open { "▾" } else { "▸" }); + if !line.is_empty() { + text.push_str(&format!(" · {line}")); + } + let r = ui.add(egui::Button::new(RichText::new(text).strong()).frame(false)); + crate::widgets::register(ui.ctx(), format!("button:editorRow-{row_name}"), r.rect); + if r.clicked() { + page(|pg| { + if pg.open.as_deref() == Some(row_name.as_str()) { + pg.open = None; + pg.draft = None; + } else { + pg.open = Some(row_name.clone()); + pg.detected = None; + } + }); + } + }); + if open { + let mut draft = draft.unwrap_or_else(|| { + Draft::from_preset(&serde_json::to_value(presets.iter().find(|x| x.name == name).unwrap_or(p)).unwrap_or_default()) + }); + form(app, ui, t, &name, &mut draft); + page(|pg| pg.draft = Some(draft)); + ui.add_space(4.0); + } + } + + row(ui, t, "", |ui| { + let r = ui.button(tr("Add Editor")); + crate::widgets::register(ui.ctx(), "button:editorAdd", r.rect); + if r.clicked() { + let presets = lcc_engine::cmd::edit_in::presets_of(&app.session).unwrap_or_default(); + let mut name = tr("New editor").to_string(); + let mut n = 2; + while presets.iter().any(|p| p.name == name) { + name = format!("{name} {n}"); + n += 1; + } + let draft = Draft { name: name.clone(), ..Draft::default() }; + match app.session.execute("editIn.savePreset", &draft.to_params()) { + Ok(_) => page(|pg| { + pg.open = Some(name); + pg.draft = Some(draft); + pg.detected = None; + }), + Err(e) => app.toast_error(ui.ctx(), e.to_string()), + } + } + }); + hint(ui, t, "adds an editor; click its row to name it and choose its program and file"); + + heading_help(ui, t, "Other editor", "externalEditing"); + row(ui, t, "Application", |ui| { + crate::text_field::TextField::singleline("field:externalEditor", &mut app.ui.settings.external_editor) + .hint(tr("System default")) + .width(220.0) + .show(ui); + }); + file_rows(ui, t, "externalFile", &mut app.ui.settings.external_file); + hint( + ui, + t, + "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere). With the location empty the system's default application opens it.", + ); + hint( + ui, + t, + "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).", + ); +} + +/// One row of the editors list: a name that opens its form below (`add` draws the form). +fn editor_row(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, key: &str, label: &str, add: impl FnOnce(&mut LccApp, &mut egui::Ui, &Tokens)) { + let open = page(|pg| pg.open.as_deref() == Some(key)); + row(ui, t, "", |ui| { + let text = RichText::new(format!("{} {label}", if open { "▾" } else { "▸" })).strong(); + let r = ui.add(egui::Button::new(text).frame(false)); + crate::widgets::register(ui.ctx(), format!("button:editorRow-{key}"), r.rect); + if r.clicked() { + page(|pg| { + if pg.open.as_deref() == Some(key) { + pg.open = None; + pg.draft = None; + } else { + pg.open = Some(key.to_string()); + pg.detected = None; + } + }); + } + }); + if open { + add(app, ui, t); + ui.add_space(4.0); + } +} + +/// The file a built-in editor hands over: format, bit depth and colour space. The saved editors' +/// richer form is [`form`]; these rows are the built-ins', which the menu commands read +/// (`defaultFile` backs Edit in Default Editor, `photocraftFile` Edit in PhotoCraft, +/// `externalFile` Edit in Other Editor). +fn file_rows(ui: &mut egui::Ui, t: &Tokens, id: &str, file: &mut crate::state::EditFile) { + row(ui, t, "", |ui| { + choices(ui, &format!("{id}Format"), &[(EditFormat::Psd, "PSD"), (EditFormat::Tiff, "TIFF")], &mut file.format); + ui.separator(); + choices(ui, &format!("{id}Depth"), &[(16u8, "16-bit"), (8, "8-bit")], &mut file.bit_depth); + }); + row(ui, t, "", |ui| { + choices( + ui, + &format!("{id}Space"), + &[ + (EditSpace::AdobeRgb, "Adobe RGB"), + (EditSpace::ProPhoto, "ProPhoto RGB"), + (EditSpace::DisplayP3, "DisplayP3"), + (EditSpace::Srgb, "sRGB"), + ], + &mut file.color_space, + ); + }); +} + +/// The form of a saved editor: its name, application, launch options and the file it hands over. +fn form(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, old_name: &str, draft: &mut Draft) { + row(ui, t, "Name", |ui| { + crate::text_field::TextField::singleline("field:editorName", &mut draft.name).width(220.0).show(ui); + }); + row(ui, t, "Application", |ui| { + crate::text_field::TextField::singleline("field:editorApp", &mut draft.app).hint(tr("System default")).width(220.0).show(ui); + application_combo(ui, draft, app); + if app.services.pick_executable.is_some() { + let r = ui.button(tr("Browse…")); + crate::widgets::register(ui.ctx(), "button:editorBrowse", r.rect); + if r.clicked() + && let Some(path) = app.services.pick_executable.as_mut().and_then(|pick| pick().into_iter().next()) + { + draft.app = path; + } + } + }); + row(ui, t, "Launch Options", |ui| { + crate::text_field::TextField::singleline("field:editorArgs", &mut draft.args).hint("{file}").width(220.0).show(ui); + }); + hint(ui, t, "the arguments before the file; `{file}` places the file's path where it stands"); + format_row(ui, t, draft); + depth_row(ui, t, draft); + space_row(ui, t, draft); + xmp_row(ui, t, draft); + row(ui, t, "", |ui| { + let save = ui.button(tr("Save")); + crate::widgets::register(ui.ctx(), "button:editorSave", save.rect); + if save.clicked() + && let Err(e) = save_preset(app, old_name, draft) + { + app.toast_error(ui.ctx(), e.to_string()); + } + let delete = ui.button(tr("Delete")); + crate::widgets::register(ui.ctx(), "button:editorDelete", delete.rect); + if delete.clicked() { + match app.session.execute("editIn.deletePreset", &json!({"name": old_name})) { + Ok(_) => page(|pg| { + pg.open = None; + pg.draft = None; + }), + Err(e) => app.toast_error(ui.ctx(), e.to_string()), + } + } + let cancel = ui.button(tr("Cancel")); + crate::widgets::register(ui.ctx(), "button:editorCancel", cancel.rect); + if cancel.clicked() { + page(|pg| { + pg.open = None; + pg.draft = None; + }); + } + }); + ui.add_space(4.0); +} + +/// Save the draft under its (possibly new) name; a rename removes the row it was edited from. +fn save_preset(app: &mut LccApp, old_name: &str, draft: &Draft) -> Result<(), String> { + let params = draft.to_params(); + app.session.execute("editIn.savePreset", ¶ms).map_err(|e| e.to_string())?; + if params.get("name").and_then(|v| v.as_str()).is_some_and(|n| n != old_name) { + app.session.execute("editIn.deletePreset", &json!({"name": old_name})).map_err(|e| e.to_string())?; + } + page(|pg| { + pg.open = params.get("name").and_then(|v| v.as_str()).map(str::to_string); + pg.draft = Some(draft.clone()); + }); + Ok(()) +} + +/// The photo editors the host found on this machine, asked for once and kept for the page. +fn detected(app: &mut LccApp) -> Vec { + page(|pg| pg.detected.clone()).unwrap_or_else(|| { + let found = app.services.detect_editors.as_ref().map(|f| f()).unwrap_or_default(); + page(|pg| pg.detected = Some(found.clone())); + found + }) +} + +/// The application combo: the editors found on this machine, one click instead of a browse. +fn application_combo(ui: &mut egui::Ui, draft: &mut Draft, app: &mut LccApp) { + let detected = detected(app); + if detected.is_empty() { + return; + } + let current = detected.iter().find(|d| d.app == draft.app).map(|d| d.name.clone()).unwrap_or_else(|| tr("Installed editors…").to_string()); + egui::ComboBox::from_id_salt("combo:editorApp").selected_text(RichText::new(current).weak()).show_ui(ui, |ui| { + for d in &detected { + if ui.selectable_label(d.app == draft.app, tr(&d.name)).clicked() { + draft.app = d.app.clone(); + } + } + }); +} + +/// The file the editor hands over: a rendered copy's format, or the original itself (+XMP). +fn format_row(ui: &mut egui::Ui, t: &Tokens, draft: &mut Draft) { + row(ui, t, "Format Options", |ui| { + let hand_over = matches!(draft.mode.as_str(), "copy" | "original"); + let shown = if draft.mode == "original" { + tr("Original (+XMP)").to_string() + } else if hand_over { + tr("a copy of the original").to_string() + } else { + draft.format.clone() + }; + egui::ComboBox::from_id_salt("combo:editorFormat").selected_text(shown).show_ui(ui, |ui| { + if hand_over { + // picking a rendered format moves the preset back to a rendered copy + for (v, l) in FORMATS.iter().filter(|(v, _)| *v != "original") { + if ui.selectable_label(draft.format == *v, tr(l)).clicked() { + draft.mode = "copyWithAdjustments".into(); + draft.format = (*v).to_string(); + } + } + if ui.selectable_label(draft.mode == "original", tr("Original (+XMP)")).clicked() { + draft.mode = "original".into(); + draft.xmp = true; + } + } else { + for (v, l) in FORMATS { + let current = if *v == "original" { draft.mode == "original" } else { draft.format == *v }; + if ui.selectable_label(current, tr(l)).clicked() { + if *v == "original" { + draft.mode = "original".into(); + draft.xmp = true; + } else { + draft.mode = "copyWithAdjustments".into(); + draft.format = (*v).to_string(); + } + } + } + } + }); + }); +} + +/// The bit level the copy is written with, as its format offers. +fn depth_row(ui: &mut egui::Ui, t: &Tokens, draft: &mut Draft) { + row(ui, t, "Bit Level", |ui| { + let depths = lcc_engine::cmd::edit_in::Format::bit_depths(lcc_engine::cmd::edit_in::Format::parse(&draft.format).unwrap_or_default()); + if matches!(draft.mode.as_str(), "copy" | "original") { + ui.label(RichText::new(tr("the file's own")).weak()); + } else if depths.is_empty() { + ui.label(RichText::new(tr("the raw data's own")).weak()); + } else { + if !depths.contains(&draft.bit_depth) { + draft.bit_depth = depths.first().copied().unwrap_or(16); + } + egui::ComboBox::from_id_salt("combo:editorDepth").selected_text(tr(depth_label(&draft.format, draft.bit_depth))).show_ui(ui, |ui| { + for d in depths { + ui.selectable_value(&mut draft.bit_depth, *d, tr(depth_label(&draft.format, *d))); + } + }); + } + }); +} + +/// The colour space of a rendered copy (a DNG and the original have no choice to make). +fn space_row(ui: &mut egui::Ui, t: &Tokens, draft: &mut Draft) { + row(ui, t, "Colour Space", |ui| match draft.format.as_str() { + "exr" if !matches!(draft.mode.as_str(), "copy" | "original") => { + ui.label(RichText::new(tr("scene-linear Rec. 2020")).weak()); + } + "dng" if !matches!(draft.mode.as_str(), "copy" | "original") => { + ui.label(RichText::new(tr("the raw data's own")).weak()); + } + _ if matches!(draft.mode.as_str(), "copy" | "original") => { + ui.label(RichText::new(tr("the file's own")).weak()); + } + _ => { + egui::ComboBox::from_id_salt("combo:editorSpace") + .selected_text( + SPACES.iter().find(|(v, _)| *v == draft.color_space).map(|(_, l)| tr(l).to_string()).unwrap_or_else(|| draft.color_space.clone()), + ) + .show_ui(ui, |ui| { + for (v, l) in SPACES { + ui.selectable_value(&mut draft.color_space, (*v).to_string(), tr(l)); + } + }); + } + }); +} + +/// A copy of, or the, original file can also carry an XMP sidecar (a raw developer that reads +/// Lightroom-style sidecars). +fn xmp_row(ui: &mut egui::Ui, t: &Tokens, draft: &mut Draft) { + if matches!(draft.mode.as_str(), "copy" | "original") { + row(ui, t, "XMP Sidecar", |ui| { + ui.checkbox(&mut draft.xmp, tr("write the edits beside the file")); + }); + } +} diff --git a/crates/ui-egui/src/panels/settings_profiles.rs b/crates/ui-egui/src/panels/settings_profiles.rs index af15b19686..45cdf94ff0 100644 --- a/crates/ui-egui/src/panels/settings_profiles.rs +++ b/crates/ui-egui/src/panels/settings_profiles.rs @@ -2,6 +2,7 @@ //! camera profile, and the way to the Profile Manager (`panels::profile_manager`). use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use serde_json::{Value, json}; use super::settings::{heading, hint, row}; @@ -43,7 +44,7 @@ pub fn settings_tab(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { let mut chosen = current.clone(); let combo = crate::widgets::combo_box(format!("bodyProfile{i}")).width(240.0).selected_text(shown).show_ui(ui, |ui| { for (id, name) in &options { - ui.selectable_value(&mut chosen, id.clone(), name); + ui.pick_value(&mut chosen, id.clone(), name); } }); register(ui.ctx(), format!("combo:bodyProfile:{key}"), combo.response.rect); diff --git a/crates/ui-egui/src/panels/tether_bar.rs b/crates/ui-egui/src/panels/tether_bar.rs index 6c1f8158a5..91b0cf23b8 100644 --- a/crates/ui-egui/src/panels/tether_bar.rs +++ b/crates/ui-egui/src/panels/tether_bar.rs @@ -9,6 +9,7 @@ //! supports it. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use serde_json::{Value, json}; use crate::LccApp; @@ -145,7 +146,7 @@ fn camera_controls(app: &mut LccApp, ui: &mut egui::Ui, cam: &Value, st: &Value) let mut picked = None; let resp = egui::ComboBox::from_id_salt(("tether-readout", name.as_str())).selected_text(label.clone()).width(72.0).show_ui(ui, |ui| { for c in &choices { - if ui.selectable_label(*c == label, c).clicked() { + if ui.pick_label(*c == label, c).clicked() { picked = Some(c.clone()); } } @@ -344,9 +345,9 @@ fn settings_window(app: &mut LccApp, ctx: &egui::Context) { let none = crate::i18n::tr("None (studio capture: watch a folder)").to_string(); let shown = list.iter().find(|(id, _)| *id == form.device).map(|(_, n)| n.clone()).unwrap_or_else(|| none.clone()); let r = egui::ComboBox::from_id_salt("tether-device").selected_text(shown).width(260.0).show_ui(ui, |ui| { - ui.selectable_value(&mut form.device, String::new(), none.clone()); + ui.pick_value(&mut form.device, String::new(), none.clone()); for (id, name) in &list { - ui.selectable_value(&mut form.device, id.clone(), name); + ui.pick_value(&mut form.device, id.clone(), name); } }); register(ui.ctx(), "tetherDevice", r.response.rect); @@ -402,7 +403,7 @@ fn settings_window(app: &mut LccApp, ctx: &egui::Context) { .width(260.0) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show_ui(ui, |ui| { - if ui.selectable_value(&mut form.preset, String::new(), crate::i18n::tr("None")).clicked() { + if ui.pick_value(&mut form.preset, String::new(), crate::i18n::tr("None")).clicked() { ui.close(); } if let Some(id) = crate::panels::presets::picker_rows(ui, "tether-preset", &app.session, Some(&form.preset)) { @@ -414,9 +415,9 @@ fn settings_window(app: &mut LccApp, ctx: &egui::Context) { let metas: Vec = app.session.metadata_presets.iter().map(|m| m.name.clone()).collect(); let shown = if form.metadata_preset.is_empty() { crate::i18n::tr("None").to_string() } else { form.metadata_preset.clone() }; egui::ComboBox::from_id_salt("tether-meta").selected_text(shown).width(260.0).show_ui(ui, |ui| { - ui.selectable_value(&mut form.metadata_preset, String::new(), crate::i18n::tr("None")); + ui.pick_value(&mut form.metadata_preset, String::new(), crate::i18n::tr("None")); for name in &metas { - ui.selectable_value(&mut form.metadata_preset, name.clone(), name); + ui.pick_value(&mut form.metadata_preset, name.clone(), name); } }); ui.end_row(); diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index a250a2fbcd..9758cdff03 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -1,5 +1,6 @@ //! The top bar: sidebar toggle, back/forward, search, filter, and the right-hand icons. +use crate::popup_typeahead::PopupItems; use egui::{Align2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use serde_json::json; @@ -371,7 +372,7 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { ui.separator(); } for kind in group { - let r = ui.selectable_label(app.ui.settings.theme(app.system_theme(ui.ctx())) == *kind, crate::i18n::tr(kind.label())); + let r = ui.pick_label(app.ui.settings.theme(app.system_theme(ui.ctx())) == *kind, crate::i18n::tr(kind.label())); register(ui.ctx(), format!("menu:themeFavorite-{}", kind.id()), r.rect); if r.clicked() { let _ = app.run("view.theme", json!({"theme": kind.id()})); diff --git a/crates/ui-egui/src/plate.rs b/crates/ui-egui/src/plate.rs index 1bade64909..0f0cf04464 100644 --- a/crates/ui-egui/src/plate.rs +++ b/crates/ui-egui/src/plate.rs @@ -2,6 +2,7 @@ //! fitted to the module bar's height. Loaded once per path and kept as a texture; a file that //! can't be read or decoded is an error the command reports, never a panic. +use crate::popup_typeahead::PopupItems; /// The largest plate file read (a logo is kilobytes; this bounds a hostile choice). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] const MAX_FILE: u64 = 8 << 20; @@ -184,10 +185,10 @@ pub fn show_setup(app: &mut crate::LccApp, ctx: &egui::Context) { ui.label(crate::i18n::tr("Identity Plate:")); let current = if setup.personalized { crate::i18n::tr("Personalized").to_string() } else { lcc_brand::DISPLAY_NAME.to_string() }; let r = egui::ComboBox::from_id_salt("identityPlateKind").selected_text(current).width(180.0).show_ui(ui, |ui| { - if ui.selectable_label(!setup.personalized, lcc_brand::DISPLAY_NAME).clicked() { + if ui.pick_label(!setup.personalized, lcc_brand::DISPLAY_NAME).clicked() { actions.push(("dialog.identityPlateSetup", json!({"personalized": false}))); } - if ui.selectable_label(setup.personalized, crate::i18n::tr("Personalized")).clicked() { + if ui.pick_label(setup.personalized, crate::i18n::tr("Personalized")).clicked() { actions.push(("dialog.identityPlateSetup", json!({"personalized": true}))); } }); diff --git a/crates/ui-egui/src/popup_typeahead.rs b/crates/ui-egui/src/popup_typeahead.rs new file mode 100644 index 0000000000..d2f888deeb --- /dev/null +++ b/crates/ui-egui/src/popup_typeahead.rs @@ -0,0 +1,174 @@ +//! Typing a name in an open dropdown moves to the first item whose name starts with it. +//! +//! egui's menus don't do this on their own. The list items of a popup are drawn through +//! [`PopupItems`] (`pick_label`, `pick_value`: `selectable_label` and `selectable_value` with the +//! typeahead built in), which hands each item's name to [`feed`]. Text typed while the popup is +//! open builds up one search; a pause of [`RESET_AFTER`] seconds starts a new one. The item found +//! takes the keyboard focus (the highlight: Enter chooses it, the arrows move on from it) and is +//! scrolled into view. A text field with the focus, such as a menu's Search… box, keeps its typing. + +use egui::{Context, Event, Id, Order, Response, Ui, WidgetText}; + +/// A pause this long (seconds) between two letters ends the search. +const RESET_AFTER: f64 = 1.0; + +#[derive(Clone, Default)] +struct Search { + /// What has been typed, lower-cased. + text: String, + /// Time of the last letter. + last: f64, + /// The pass this was last worked out for. + pass: u64, + /// The frame of that pass: a frame with no popup items drawn between two calls means the + /// popup closed, and its search goes with it. + frame: u64, + /// The pass of a ↓ press that has yet to take the focus to the first item; 0 for none. + arrowed: u64, + /// Letters came in this pass, so the first matching item takes the focus. + fresh: bool, +} + +/// What this pass's input types: text, not a shortcut. +fn typed(ctx: &Context) -> String { + ctx.input(|i| { + if i.modifiers.command || i.modifiers.ctrl || i.modifiers.alt { + return String::new(); + } + i.events + .iter() + .filter_map(|e| match e { + Event::Text(t) => Some(t.chars().filter(|c| !c.is_control()).collect::()), + _ => None, + }) + .collect() + }) +} + +/// Take this pass's letters into the search, once per pass. +fn update(ctx: &Context) -> Search { + let id = Id::new("popup-typeahead"); + let mut search: Search = ctx.data(|d| d.get_temp(id)).unwrap_or_default(); + let pass = ctx.cumulative_pass_nr(); + if search.pass != pass { + search.pass = pass; + let frame = ctx.cumulative_frame_nr(); + if frame > search.frame.saturating_add(1) { + search.text.clear(); + search.arrowed = 0; + } + search.frame = frame; + let letters = typed(ctx); + let now = ctx.input(|i| i.time); + search.fresh = !letters.is_empty(); + if search.fresh { + if now - search.last > RESET_AFTER { + search.text.clear(); + } + search.text.push_str(&letters.to_lowercase()); + search.last = now; + } + ctx.data_mut(|d| d.insert_temp(id, search.clone())); + } + search +} + +/// Whether `label` is the item the typed text asks for, and none before it was. +fn hit(ctx: &Context, label: &str) -> bool { + let search = update(ctx); + if !search.fresh || !label.trim_start().to_lowercase().starts_with(&search.text) { + return false; + } + // the first match takes it: the rest of the list sees a search that is used up + let id = Id::new("popup-typeahead"); + ctx.data_mut(|d| d.get_temp_mut_or_default::(id).fresh = false); + true +} + +/// ↓ with nothing focused in the popup, or in its Search… field, takes the highlight to the first +/// item (egui's arrows only move on from an item that has it already). The item takes the focus a +/// frame after the key: in the frame of the press egui's own navigation would move on from it. +fn arrow_claims(ctx: &Context) -> bool { + let id = Id::new("popup-typeahead"); + let pass = ctx.cumulative_pass_nr(); + let search = update(ctx); + if search.arrowed != 0 && search.arrowed < pass { + ctx.data_mut(|d| d.get_temp_mut_or_default::(id).arrowed = 0); + return true; + } + if search.arrowed == 0 + && (!ctx.memory(|m| m.focused().is_some()) || ctx.text_edit_focused()) + && ctx.input(|i| i.key_pressed(egui::Key::ArrowDown)) + { + ctx.data_mut(|d| d.get_temp_mut_or_default::(id).arrowed = pass); + ctx.request_repaint(); + } + false +} + +/// Called with each item of a popup's list as it is drawn: when the typed text names it, it takes +/// the focus. Does nothing outside a popup, or while a text field has the focus. +pub fn feed(ui: &Ui, response: &Response, label: &str) { + let ctx = ui.ctx(); + if ui.layer_id().order != Order::Foreground || !egui::Popup::is_any_open(ctx) { + return; + } + if arrow_claims(ctx) { + response.request_focus(); + response.scroll_to_me(None); + return; + } + if ctx.text_edit_focused() { + return; + } + if hit(ctx, label) { + response.request_focus(); + response.scroll_to_me(None); + } +} + +/// An item chosen with Enter or Space closes its popup, as a click does (egui closes a popup on a +/// pointer click only). A popup whose items toggle in place (they stay open on a mouse click too, +/// as with `PopupCloseBehavior::CloseOnClickOutside`) calls this first, inside its contents. +pub fn stays_open(ui: &Ui) { + let ctx = ui.ctx(); + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(Id::new("popup-stays-open"), pass)); +} + +fn stays_open_now(ctx: &Context) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data(|d| d.get_temp::(Id::new("popup-stays-open"))) == Some(pass) +} + +/// `selectable_label` and `selectable_value` for the items of a dropdown list. +pub trait PopupItems { + /// [`Ui::selectable_label`], and the item answers to typed names. + fn pick_label(&mut self, selected: bool, text: impl Into) -> Response; + /// [`Ui::selectable_value`], and the item answers to typed names. + fn pick_value(&mut self, current: &mut V, alternative: V, text: impl Into) -> Response; +} + +impl PopupItems for Ui { + fn pick_label(&mut self, selected: bool, text: impl Into) -> Response { + let text = text.into(); + let label = text.text().to_string(); + let response = self.selectable_label(selected, text); + feed(self, &response, &label); + let ctx = self.ctx(); + let popup = self.layer_id().order == Order::Foreground && egui::Popup::is_any_open(ctx); + if popup && response.clicked() && !ctx.input(|i| i.pointer.any_click()) && !stays_open_now(ctx) { + self.close(); + } + response + } + + fn pick_value(&mut self, current: &mut V, alternative: V, text: impl Into) -> Response { + let mut response = self.pick_label(*current == alternative, text); + if response.clicked() && *current != alternative { + *current = alternative; + response.mark_changed(); + } + response + } +} diff --git a/crates/ui-egui/src/print_ui.rs b/crates/ui-egui/src/print_ui.rs index 23b75f67f5..a24fd2ce19 100644 --- a/crates/ui-egui/src/print_ui.rs +++ b/crates/ui-egui/src/print_ui.rs @@ -19,6 +19,7 @@ //! and `printui.trustOnFirstUse {on}`. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use lcc_catalog::PhotoId; use lcc_engine::print::layout::Unit; @@ -1311,7 +1312,7 @@ fn template_browser(ui: &mut egui::Ui, app: &mut LccApp) { heading(ui, "Saved Prints"); let open = app.print.creation; for c in lcc_engine::creations::creations_of(&app.session, Some(lcc_layout::CreationKind::Print)) { - let r = ui.selectable_label(open == Some(c.id.0), format!("{} ({})", c.name, c.photos.len())); + let r = ui.pick_label(open == Some(c.id.0), format!("{} ({})", c.name, c.photos.len())); register(&ctx, format!("print:creation:{}", c.id.0), r.rect); if r.clicked() { cmd(app, &ctx, "creation.open", json!({"id": c.id.0})); @@ -1347,7 +1348,7 @@ fn template_browser(ui: &mut egui::Ui, app: &mut LccApp) { ui.horizontal(|ui| { ui.label(crate::i18n::tr("Units")); for u in [Unit::Inches, Unit::Centimeters, Unit::Millimeters] { - let r = ui.selectable_label(g.units == u, u.label()); + let r = ui.pick_label(g.units == u, u.label()); register(&ctx, format!("print:units:{}", u.label()), r.rect); if r.clicked() { g.units = u; @@ -1563,7 +1564,7 @@ fn settings_panels(ui: &mut egui::Ui, app: &mut LccApp) { if let Some(tpl) = &mut o.photo_info { egui::ComboBox::from_id_salt("print-photo-info").selected_text(tpl.as_str()).show_ui(ui, |ui| { for tok in ["{Filename}", "{Title}", "{Caption}", "{Date}", "{Exposure}", "{Camera}", "{Filename} · {Exposure}"] { - ui.selectable_value(tpl, tok.to_string(), tok); + ui.pick_value(tpl, tok.to_string(), tok); } }); } @@ -1572,7 +1573,7 @@ fn settings_panels(ui: &mut egui::Ui, app: &mut LccApp) { ui.horizontal(|ui| { ui.label(crate::i18n::tr("Print to:")); for (d, label) in [(Destination::Printer, "Printer"), (Destination::Pdf, "PDF File"), (Destination::Jpeg, "JPEG File")] { - let r = ui.selectable_label(s.destination == d, crate::i18n::tr(label)); + let r = ui.pick_label(s.destination == d, crate::i18n::tr(label)); register(&ctx, format!("print:dest:{label}"), r.rect); if r.clicked() { s.destination = d; @@ -1594,7 +1595,7 @@ fn settings_panels(ui: &mut egui::Ui, app: &mut LccApp) { let cur = levels.iter().find(|l| l.0 == s.job.sharpening).map_or("Standard", |l| l.1); egui::ComboBox::from_id_salt("print-sharpen-amount").selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { for (v, label) in levels { - ui.selectable_value(&mut s.job.sharpening, v, crate::i18n::tr(label)); + ui.pick_value(&mut s.job.sharpening, v, crate::i18n::tr(label)); } }); } @@ -1604,7 +1605,7 @@ fn settings_panels(ui: &mut egui::Ui, app: &mut LccApp) { use lcc_print::PrintMedia; ui.label(crate::i18n::tr("Media Type")); for (v, label) in [(PrintMedia::Glossy, "Glossy"), (PrintMedia::Matte, "Matte")] { - let r = ui.selectable_label(s.job.media == v, crate::i18n::tr(label)); + let r = ui.pick_label(s.job.media == v, crate::i18n::tr(label)); if r.clicked() { s.job.media = v; } @@ -1630,7 +1631,7 @@ fn settings_panels(ui: &mut egui::Ui, app: &mut LccApp) { }); let printers = app.print.printers.clone(); for pr in printers { - if ui.selectable_label(app.print.printer_uri == pr.uri, format!("{} {}", pr.name, pr.info)).clicked() { + if ui.pick_label(app.print.printer_uri == pr.uri, format!("{} {}", pr.name, pr.info)).clicked() { app.print.printer_uri = pr.uri.clone(); // offer its paper sizes in Page Setup cmd(app, &ctx, "printui.media", json!({"uri": pr.uri})); @@ -1715,11 +1716,11 @@ fn printer_options(ui: &mut egui::Ui, app: &mut LccApp, ctx: &egui::Context) { ui.label(crate::i18n::tr(label)); let shown = cur.map(|c| pretty(c)).unwrap_or_else(|| default_label(def.map(|v| pretty(v)))); let r = egui::ComboBox::from_id_salt(("print-driver", key)).selected_text(shown).show_ui(ui, |ui| { - if ui.selectable_label(cur.is_none(), default_label(def.map(|v| pretty(v)))).clicked() { + if ui.pick_label(cur.is_none(), default_label(def.map(|v| pretty(v)))).clicked() { cmd(app, ctx, "printui.driver", json!({key: null})); } for v in list { - if ui.selectable_label(cur == Some(v), pretty(v)).clicked() { + if ui.pick_label(cur == Some(v), pretty(v)).clicked() { cmd(app, ctx, "printui.driver", json!({key: v})); } } @@ -1738,11 +1739,11 @@ fn printer_options(ui: &mut egui::Ui, app: &mut LccApp, ctx: &egui::Context) { let def = default_label(o.quality_default.map(name)); let shown = d.print_quality.map(name).unwrap_or_else(|| def.clone()); let r = egui::ComboBox::from_id_salt(("print-driver", "printQuality")).selected_text(shown).show_ui(ui, |ui| { - if ui.selectable_label(d.print_quality.is_none(), def.clone()).clicked() { + if ui.pick_label(d.print_quality.is_none(), def.clone()).clicked() { cmd(app, ctx, "printui.driver", json!({"printQuality": null})); } for q in &o.qualities { - if ui.selectable_label(d.print_quality == Some(*q), name(*q)).clicked() { + if ui.pick_label(d.print_quality == Some(*q), name(*q)).clicked() { cmd(app, ctx, "printui.driver", json!({"printQuality": q})); } } @@ -1786,15 +1787,15 @@ fn color_management(ui: &mut egui::Ui, app: &mut LccApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.label(crate::i18n::tr("Profile:")); let r = egui::ComboBox::from_id_salt("print-profile").selected_text(current).show_ui(ui, |ui| { - if ui.selectable_label(managed, crate::i18n::tr("Managed by Printer")).clicked() { + if ui.pick_label(managed, crate::i18n::tr("Managed by Printer")).clicked() { choose = Some(json!({"path": null})); } if let Some((path, name)) = app.ui.proof_profile.clone() - && ui.selectable_label(app.print.settings.job.color.profile.as_deref() == Some(path.as_str()), name).clicked() + && ui.pick_label(app.print.settings.job.color.profile.as_deref() == Some(path.as_str()), name).clicked() { choose = Some(json!({"path": path})); } - if ui.selectable_label(false, crate::i18n::tr("Other…")).clicked() { + if ui.pick_label(false, crate::i18n::tr("Other…")).clicked() { choose = Some(json!({})); } }); @@ -1808,7 +1809,7 @@ fn color_management(ui: &mut egui::Ui, app: &mut LccApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.label(crate::i18n::tr("Intent:")); for (v, label) in [(PrintIntent::Perceptual, "Perceptual"), (PrintIntent::Relative, "Relative")] { - let r = ui.selectable_label(c.intent == v, crate::i18n::tr(label)); + let r = ui.pick_label(c.intent == v, crate::i18n::tr(label)); register(ctx, format!("print:intent:{label}"), r.rect); if r.clicked() { c.intent = v; @@ -1841,7 +1842,7 @@ fn page_setup_bar(ui: &mut egui::Ui, app: &mut LccApp, r: Rect) { child.label(crate::i18n::tr("Page Setup:")); let resp = egui::ComboBox::from_id_salt("print-paper").selected_text(cur).width(200.0).show_ui(&mut child, |ui| { for p in PAPERS { - if ui.selectable_label(false, crate::i18n::tr(p.label)).clicked() { + if ui.pick_label(false, crate::i18n::tr(p.label)).clicked() { cmd(app, &ctx, "printui.pageSetup", json!({"paper": p.key, "landscape": landscape})); } } @@ -1850,7 +1851,7 @@ fn page_setup_bar(ui: &mut egui::Ui, app: &mut LccApp, r: Rect) { ui.label(egui::RichText::new(crate::i18n::tr("Printer paper")).small().weak()); for m in app.print.media.clone() { let label = format!("{} ({:.2} × {:.2} in)", m.name, m.size.w / 72.0, m.size.h / 72.0); - if ui.selectable_label(false, label).clicked() { + if ui.pick_label(false, label).clicked() { cmd(app, &ctx, "printui.pageSetup", json!({"media": m.name, "landscape": landscape})); } } @@ -1863,7 +1864,7 @@ fn page_setup_bar(ui: &mut egui::Ui, app: &mut LccApp, r: Rect) { ctx.request_repaint(); } for (label, land) in [("Portrait", false), ("Landscape", true)] { - let r = child.selectable_label(landscape == land, crate::i18n::tr(label)); + let r = child.pick_label(landscape == land, crate::i18n::tr(label)); register(&ctx, format!("print:{}", label.to_lowercase()), r.rect); if r.clicked() && landscape != land { cmd(app, &ctx, "printui.pageSetup", json!({"landscape": land})); diff --git a/crates/ui-egui/src/print_view.rs b/crates/ui-egui/src/print_view.rs index 8a77cab535..37487c1946 100644 --- a/crates/ui-egui/src/print_view.rs +++ b/crates/ui-egui/src/print_view.rs @@ -6,6 +6,7 @@ //! the guides' snapping done by the command. Widgets register under `print:*`, `button:print*` //! and `drag:print*` ids for the control channel and the headless tests. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use lcc_catalog::PhotoId; use lcc_engine::export::ExportOptions; @@ -240,11 +241,11 @@ fn settings(app: &mut LccApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, st: &Pr let shown = pu.folder.clone().unwrap_or_else(|| crate::i18n::tr(default_folder).to_string()); let c = egui::ComboBox::from_id_salt("printTemplateFolder").width(140.0).selected_text(shown).show_ui(ui, |ui| { let picked = pu.folder.clone(); - if ui.selectable_label(picked.as_deref() == Some(default_folder), crate::i18n::tr(default_folder)).clicked() { + if ui.pick_label(picked.as_deref() == Some(default_folder), crate::i18n::tr(default_folder)).clicked() { pu.folder = Some(default_folder.to_string()); } for f in &folders { - if ui.selectable_label(picked.as_deref() == Some(f.as_str()), f.as_str()).clicked() { + if ui.pick_label(picked.as_deref() == Some(f.as_str()), f.as_str()).clicked() { pu.folder = Some(f.clone()); } } @@ -300,7 +301,7 @@ fn settings(app: &mut LccApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, st: &Pr let targets = std::iter::once((None, crate::i18n::tr(default_folder).to_string())) .chain(folders.iter().map(|f| (Some(f.clone()), f.clone()))); for (target, label) in targets { - if ui.selectable_label(*folder == target, label.as_str()).clicked() && *folder != target { + if ui.pick_label(*folder == target, label.as_str()).clicked() && *folder != target { let to = target.unwrap_or_else(|| default_folder.to_string()); if run(app, &ctx, "print.template.move", json!({"name": name, "folder": to})).is_some() { app.toast(&ctx, crate::i18n::tr_format!("Moved {name} to {folder}", name = name, folder = to)); @@ -476,7 +477,7 @@ fn settings(app: &mut LccApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, st: &Pr let current = current_paper(&l.page.paper); let c = egui::ComboBox::from_id_salt("printPaper").selected_text(paper_label(current)).show_ui(ui, |ui| { for name in layout::paper_names().chain(std::iter::once("custom")) { - if ui.selectable_label(current == name, paper_label(name)).clicked() { + if ui.pick_label(current == name, paper_label(name)).clicked() { patch(app, &ctx, json!({"layout": {"page": {"paper": name}}})); } } @@ -570,17 +571,17 @@ fn print_job_color(app: &mut LccApp, ui: &mut Ui, t: &Tokens, color: &PrintColor row(ui, t, "Profile", |ui| { let c = egui::ComboBox::from_id_salt("print-profile").width(190.0).selected_text(shown.clone()).show_ui(ui, |ui| { for (space, label) in [(ManagedSpace::Srgb, "Managed by Printer (sRGB)"), (ManagedSpace::AdobeRgb, "Managed by Printer (Adobe RGB)")] { - let r = ui.selectable_label(color.profile == managed(space), crate::i18n::tr(label)); + let r = ui.pick_label(color.profile == managed(space), crate::i18n::tr(label)); register(ui.ctx(), format!("item:printProfile-{}", to_value(space).as_str().unwrap_or_default()), r.rect); if r.clicked() && color.profile != managed(space) { patch_color(app, &ctx, "profile", to_value(managed(space))); } } if let PrintProfile::Icc { .. } = &color.profile { - let _ = ui.selectable_label(true, shown.as_str()); + let _ = ui.pick_label(true, shown.as_str()); } if app.services.pick_display_profile.is_some() { - let r = ui.selectable_label(false, crate::i18n::tr("Other…")); + let r = ui.pick_label(false, crate::i18n::tr("Other…")); register(ui.ctx(), "item:printProfile-other", r.rect); pick |= r.clicked(); } diff --git a/crates/ui-egui/src/region.rs b/crates/ui-egui/src/region.rs index 1d25618e49..49744953b2 100644 --- a/crates/ui-egui/src/region.rs +++ b/crates/ui-egui/src/region.rs @@ -100,6 +100,12 @@ pub struct LoupePlan { /// it, or full-size drafts of this drag went over [`DRAFT_BUDGET_MS`]), against the render at rest. pub const CPU_DRAFT_SCALE: f32 = 0.6; +/// The interaction label of a mask edit on the photo (moving, resizing or turning a gradient or +/// pin). Its drafts are always full size, on the CPU too, and never drop to [`CPU_DRAFT_SCALE`]: +/// the edit changes part of the photo, and a smaller draft blurred the whole photo for it +/// (adapted from upstream #4444). A slow machine shows fewer drafts instead. +pub const SHARP_DRAG: &str = "Edit Mask"; + /// The slider budget (ms): a drag whose full-size drafts take longer gets smaller drafts next time. /// A draft's time is its render plus the frame that shows it (the texture upload is part of it). pub const DRAFT_BUDGET_MS: f64 = 16.0; @@ -187,7 +193,7 @@ impl DragScale { } let key = (photo, control.to_string()); let small = matches!(self.verdict(&key), Some(Verdict::Slow { until, .. }) if now < until); - let s = if gpu && !small { 1.0 } else { CPU_DRAFT_SCALE }; + let s = if control == SHARP_DRAG || (gpu && !small) { 1.0 } else { CPU_DRAFT_SCALE }; self.current = Some((key, s)); self.seen = shown; Some(s) @@ -211,7 +217,8 @@ impl DragScale { } if self.samples.len() > GIVE_UP_AFTER && median_after_first(&self.samples).is_some_and(|m| m > DRAFT_BUDGET_MS * GIVE_UP_FACTOR) - && let Some((_, s)) = self.current.as_mut() + && let Some(((_, control), s)) = self.current.as_mut() + && control != SHARP_DRAG { *s = CPU_DRAFT_SCALE; return; @@ -1102,6 +1109,28 @@ mod tests { assert_eq!(d.scale(drag, false, None, 0.0), Some(1.0)); } + // Given a mask edit on the photo (a gradient's handle or pin dragged), its drafts are full size + // even on the CPU, after slow drags, and when they are far over budget: the photo stays sharp + // (upstream #4444) + #[test] + fn a_mask_edit_always_drafts_at_full_size() { + use lcc_catalog::PhotoId; + let mut d = DragScale::default(); + let mask = Some((PhotoId(1), SHARP_DRAG)); + assert_eq!(d.scale(mask, false, None, 0.0), Some(1.0), "on the CPU too"); + d.scale(None, false, None, 0.0); + for i in 0..3 { + assert_eq!(timed_drag(&mut d, mask, 400.0, f64::from(i)), Some(1.0), "drag {i}: slow drags don't shrink the next"); + } + assert_eq!(d.scale(mask, true, None, 10.0), Some(1.0)); + for key in 100..110 { + d.observe(key, 400.0, None); + } + assert_eq!(d.scale(mask, true, None, 10.0), Some(1.0)); + d.scale(None, true, None, 10.0); + assert_eq!(d.scale(Some((PhotoId(1), "Exposure")), false, None, 10.0), Some(CPU_DRAFT_SCALE)); + } + /// One whole drag of `drag` at full size whose drafts all take `ms` to show, ending at `now`. fn timed_drag(d: &mut DragScale, drag: Option<(lcc_catalog::PhotoId, &str)>, ms: f64, now: f64) -> Option { let scale = d.scale(drag, true, None, now); diff --git a/crates/ui-egui/src/settings_screen.rs b/crates/ui-egui/src/settings_screen.rs index 4a2b7a17da..3897be53d6 100644 --- a/crates/ui-egui/src/settings_screen.rs +++ b/crates/ui-egui/src/settings_screen.rs @@ -59,6 +59,7 @@ struct Section { const SECTIONS: &[Section] = &[ Section { key: "general", label: "General", icon: Icon::Gear, tabs: &["general"] }, + Section { key: "external", label: "External Editing", icon: Icon::Pencil, tabs: &["external"] }, Section { key: "import", label: "Import", icon: Icon::Plus, tabs: &["import"] }, Section { key: "folders", label: "Folders", icon: Icon::Folder, tabs: &["folders"] }, Section { key: "performance", label: "Performance", icon: Icon::Activity, tabs: &["performance"] }, @@ -236,10 +237,7 @@ pub(crate) fn show(app: &mut LccApp, ctx: &egui::Context) { let wide = roomy || app.modern_sheets.settings.wide; let mut go_back = false; // Esc: Back (a popup or a text field being edited takes it first) - if !egui::Popup::is_any_open(ctx) - && !ctx.egui_wants_keyboard_input() - && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) - { + if crate::dialog_frame::esc_closes(false, app.text_focus, ctx) { go_back = true; } let t = Tokens::get(ctx); @@ -351,9 +349,7 @@ fn window(app: &mut LccApp, ctx: &egui::Context, asked: &str, left: bool) { let screen = ctx.content_rect(); let mut tab = crate::panels::settings::window_tab(asked).to_string(); // Esc: Close (a popup or a text field being edited takes it first) - let mut closing = !egui::Popup::is_any_open(ctx) - && !ctx.egui_wants_keyboard_input() - && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); + let mut closing = crate::dialog_frame::esc_closes(false, app.text_focus, ctx); // the backdrop: an area below the window egui::Area::new(Id::new("settings-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| { ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(140)); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 5f118c2f3b..17626eab7b 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -390,6 +390,29 @@ const DIGIT_COMMANDS: [(Key, &str); 10] = [ (Key::Num9, "photo.labelBlue"), ]; +/// Shift+← / Shift+→ in a grid: the neighbour of the active photo joins the selection and becomes the +/// active one. At either end of the view the key does nothing. +fn extend_by_step(app: &mut LccApp, step: i64) { + let vis = app.session.visible_cloned(); + let neighbour = app + .session + .active() + .and_then(|active| vis.iter().position(|p| *p == active)) + .and_then(|pos| i64::try_from(pos).ok()) + .and_then(|pos| pos.checked_add(step)) + .and_then(|pos| usize::try_from(pos).ok()) + .and_then(|pos| vis.get(pos)); + if let Some(id) = neighbour { + let _ = app.run("library.select", json!({"ids": [id.0], "mode": "add"})); + } +} + +/// Shift+↑ / Shift+↓ in a grid's top or bottom row: the grid is laid out and no cell lies above or below +/// the active photo (`row_distance` is 0 there; None while the grid isn't laid out). +fn grid_extend_sideways(app: &mut LccApp, f: &str) -> bool { + matches!(f, "grid:extend:up" | "grid:extend:down") && crate::panels::grid::row_distance(app, f == "grid:extend:down") == Some(0) +} + /// The id the culling path takes for a rating or label command (`rate:3:0`, `label:red`). fn culling_id(id: &str) -> Option { if let Some(n) = id.strip_prefix("photo.rate").filter(|n| n.len() == 1) { @@ -580,7 +603,8 @@ pub fn handle(app: &mut LccApp, ctx: &egui::Context) { let owner = crate::keyboard::owner(app, ctx); // A modal (a dialog, Settings, the shortcuts overlay) owns its keys, Esc and text editing // included, and so does the keymap editor recording a shortcut: background photo actions wait. - if matches!(owner, Owner::Recorder | Owner::Modal) { + // An open dropdown or menu takes the keys the same way, until it closes. + if matches!(owner, Owner::Recorder | Owner::Modal | Owner::Popup) { return; } if app.ui.name_edit.is_none() && crate::panels::person::handle_bulk_key(app, ctx) { @@ -817,11 +841,15 @@ pub fn handle(app: &mut LccApp, ctx: &egui::Context) { if let Some(id) = edge { let _ = app.run("library.select", json!({"ids": [id.0], "active": id.0})); } + } else if grid_extend_sideways(app, &f) { + // Shift+↑ / Shift+↓ in the top / bottom row: no cell lies above / below, so the key steps + // sideways like Shift+← / Shift+→, toward the end of the view + extend_by_step(app, if f == "grid:extend:down" { 1 } else { -1 }); } else if f == "grid:extend:up" || f == "grid:extend:down" { // Shift+↑ / Shift+↓ in a grid: every photo from the active one to the cell above / below it // (the layout's nearest cell, as plain ↑ / ↓ move to) joins the selection; the cell reached - // becomes the active photo. In the top / bottom row, or while the grid isn't laid out for the - // photos in view, the key does nothing. + // becomes the active photo. While the grid isn't laid out for the photos in view, the key + // does nothing. let down = f == "grid:extend:down"; let reach = crate::panels::grid::row_distance(app, down).and_then(|d| usize::try_from(d).ok()).unwrap_or(0); let vis = app.session.visible_cloned(); @@ -844,21 +872,7 @@ pub fn handle(app: &mut LccApp, ctx: &egui::Context) { let _ = app.run("library.select", json!({"ids": run, "mode": "add"})); } } else if let Some(step) = f.strip_prefix("grid:extend:") { - // Shift+← / Shift+→ in a grid: the neighbour of the active photo joins the selection and - // becomes the active one. At either end of the view the key does nothing. - let step = step.parse::().unwrap_or(0); - let vis = app.session.visible_cloned(); - let neighbour = app - .session - .active() - .and_then(|active| vis.iter().position(|p| *p == active)) - .and_then(|pos| i64::try_from(pos).ok()) - .and_then(|pos| pos.checked_add(step)) - .and_then(|pos| usize::try_from(pos).ok()) - .and_then(|pos| vis.get(pos)); - if let Some(id) = neighbour { - let _ = app.run("library.select", json!({"ids": [id.0], "mode": "add"})); - } + extend_by_step(app, step.parse::().unwrap_or(0)); } else if compare::culling(app) && matches!(f.as_str(), "library.next" | "library.previous" | "library.down" | "library.up") { // ↑ / ↓ step like → / ←: run as the grid's Photo Below / Above, they would leave one photo // of the survey (or the pair) selected (upstream #3640) @@ -893,9 +907,10 @@ pub fn handle(app: &mut LccApp, ctx: &egui::Context) { } continue; } - R::Crop if app.ui.tool == "guidedUpright" => { + R::Crop | R::Edit if app.ui.tool == "guidedUpright" => { // Delete removes the selected guide alone; with none selected it removes - // nothing (the photo itself is never deleted while the tool is open) + // nothing (the photo itself is never deleted while the tool is open, over the + // Crop panel or the Edit panel's Transform section, issue #1684) if let (Some((photo, i)), Some(active)) = (app.ui.selected_guide, app.session.active()) { if photo == active.0 && let Some(d) = app.session.develop_of(active) @@ -1231,7 +1246,7 @@ mod tests { #[test] fn select_only_active_without_active_photo_does_not_change_selection() { let mut h = library(); - // Deselect All keeps the active photo selected, so clear the whole selection state instead. + // a fresh state with no selection and no active photo (Cmd+D leaves the same one) h.app.session.selection = Default::default(); assert!(!crate::menus::ui_enabled(&h.app, "library.selectOnlyActive")); assert!(h.app.run("library.selectOnlyActive", json!({})).is_err()); @@ -1239,6 +1254,98 @@ mod tests { assert!(h.app.session.selection.ids.is_empty()); } + /// Press the Select None chord (Cmd+D, the secondary binding; see `ALIASES`). + fn select_none_chord(h: &mut crate::headless::Headless) { + let r = h.request("ui.key", json!({"key": "D", "cmd": true}), std::time::Duration::from_secs(20)); + assert_eq!(r["ok"], true, "{r}"); + } + + #[test] + fn select_none_clears_every_selected_photo_and_the_active_photo() { + use lcc_catalog::PhotoId; + let mut h = library(); + h.app.session.execute("library.select", &json!({"ids": [1, 2, 3], "active": 2})).unwrap(); + select_none_chord(&mut h); + assert!(h.app.session.selection.ids.is_empty(), "no photo stays selected: {:?}", h.app.session.selection.ids); + assert_eq!(h.app.session.active(), None, "no photo is active afterwards"); + assert!(!h.app.session.selection.contains(PhotoId(2))); + } + + #[test] + fn select_none_with_one_photo_selected_leaves_nothing_selected() { + let mut h = library(); + h.app.session.execute("library.select", &json!({"ids": [3]})).unwrap(); + select_none_chord(&mut h); + assert!(h.app.session.selection.ids.is_empty(), "{:?}", h.app.session.selection); + assert_eq!(h.app.session.active(), None); + } + + #[test] + fn select_none_with_nothing_selected_does_nothing_and_raises_no_error() { + let mut h = library(); + h.app.session.selection = Default::default(); + select_none_chord(&mut h); + assert!(h.app.session.selection.ids.is_empty()); + assert_eq!(h.app.session.active(), None); + } + + #[test] + fn select_only_active_still_keeps_only_the_active_photo() { + use lcc_catalog::PhotoId; + let mut h = library(); + h.app.session.execute("library.select", &json!({"ids": [1, 2, 3], "active": 2})).unwrap(); + select_only_active_chord(&mut h); + assert_eq!(h.app.session.selection.ids, vec![PhotoId(2)]); + assert_eq!(h.app.session.active(), Some(PhotoId(2))); + } + + #[test] + fn select_none_stays_cleared_across_settled_frames() { + let mut h = library(); + h.app.session.execute("library.select", &json!({"ids": [1, 2], "active": 2})).unwrap(); + select_none_chord(&mut h); + // a few frames later the grid and filmstrip still draw nothing selected + for _ in 0..3 { + h.settle(std::time::Duration::from_secs(5)); + } + assert!(h.app.session.selection.ids.is_empty(), "{:?}", h.app.session.selection); + assert_eq!(h.app.session.active(), None); + } + + #[test] + fn after_select_none_the_down_arrow_takes_the_last_photo_of_the_view() { + let mut h = library(); + h.app.session.execute("library.select", &json!({"ids": [1, 2], "active": 2})).unwrap(); + select_none_chord(&mut h); + let last = *h.app.session.visible_cloned().last().expect("the view has photos"); + let r = h.request("ui.key", json!({"key": "down"}), std::time::Duration::from_secs(20)); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(h.app.session.active(), Some(last), "↓ after Cmd+D starts from the last photo (F-66C0)"); + assert_eq!(h.app.session.selection.ids, vec![last]); + } + + #[test] + fn after_select_none_the_up_arrow_takes_the_first_photo_of_the_view() { + let mut h = library(); + // a photo well down the view, so a step up from it (the old behaviour) would not land on the first + let vis = h.app.session.visible_cloned(); + let (first, active) = (vis[0], vis[vis.len() - 1]); + h.app.session.execute("library.select", &json!({"ids": [active.0], "active": active.0})).unwrap(); + select_none_chord(&mut h); + let r = h.request("ui.key", json!({"key": "up"}), std::time::Duration::from_secs(20)); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(h.app.session.active(), Some(first), "↑ after Cmd+D starts from the first photo (F-66C0)"); + assert_eq!(h.app.session.selection.ids, vec![first]); + } + + #[test] + fn select_none_is_listed_as_cmd_d_in_the_classic_set() { + super::set_active(super::KeymapSet::Classic); + let h = library(); + // the Edit menu's "Select None" item shows the key that works: Cmd+D, not the engine's declared Cmd+Shift+A + assert_eq!(super::shortcut_of(&h.app.ui.settings.keymap, "library.selectNone"), Some("Cmd+D")); + } + #[test] fn library_rating_labels_flags_and_undo() { use lcc_catalog::{ColorLabel, Flag, PhotoId}; diff --git a/crates/ui-egui/src/slideshow_ui.rs b/crates/ui-egui/src/slideshow_ui.rs index e1c4a91243..699479d9d0 100644 --- a/crates/ui-egui/src/slideshow_ui.rs +++ b/crates/ui-egui/src/slideshow_ui.rs @@ -7,6 +7,7 @@ //! Every action is a `slideshow.*` command (listed in `module::SHELL_COMMANDS`). View ▸ Slideshow //! (the impromptu slideshow) is unchanged. +use crate::popup_typeahead::PopupItems; use std::cell::RefCell; use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, pos2, vec2}; @@ -850,7 +851,7 @@ pub fn toolbar(app: &mut LccApp, ui: &mut egui::Ui) { }; egui::ComboBox::from_id_salt("slideshow-use").selected_text(crate::i18n::tr(label(cur))).show_ui(ui, |ui| { for u in [UsePhotos::All, UsePhotos::Selected, UsePhotos::Flagged] { - if ui.selectable_label(cur == u, crate::i18n::tr(label(u))).clicked() { + if ui.pick_label(cur == u, crate::i18n::tr(label(u))).clicked() { let _ = app.run("slideshow.set", json!({"usePhotos": u})); } } @@ -1028,7 +1029,7 @@ fn left_column(app: &mut LccApp, ui: &mut egui::Ui) { let count = saved.len(); let open = app.ui.slides.open_id; for (id, name, n) in saved { - let r = ui.selectable_label(open == Some(id), format!("{name} ({n})")); + let r = ui.pick_label(open == Some(id), format!("{name} ({n})")); if r.clicked() { let _ = app.run("slideshow.openSaved", json!({"id": id})); } @@ -1085,7 +1086,7 @@ fn anchor_combo(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, a let mut changed = false; egui::ComboBox::from_id_salt(id).selected_text(name(*a)).show_ui(ui, |ui| { for x in ALL { - if ui.selectable_label(*a == x, name(x)).clicked() { + if ui.pick_label(*a == x, name(x)).clicked() { *a = x; changed = true; } @@ -1141,7 +1142,7 @@ fn right_column(app: &mut LccApp, ui: &mut egui::Ui) { }; egui::ComboBox::from_id_salt("slideshow-aspect").selected_text(aspect(s.layout.aspect)).show_ui(ui, |ui| { for a in [Aspect::Screen, Aspect::Wide16x9, Aspect::Classic4x3] { - if ui.selectable_label(s.layout.aspect == a, aspect(a)).clicked() { + if ui.pick_label(s.layout.aspect == a, aspect(a)).clicked() { s.layout.aspect = a; ch = true; } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index bb8873d2ab..94935870ba 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -60,6 +60,51 @@ impl PeopleCategory { } } +/// How a person's page orders their faces (`faces.person`'s `sort`, issue #1691): the order the +/// photos came into the library, their capture time oldest or newest first (to see someone grow up +/// or age), by folder, or the largest face first (to pick a portrait). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PersonSort { + #[default] + Photo, + Oldest, + Newest, + Folder, + FaceSize, +} + +impl PersonSort { + /// What the control channel and the picker's widget id use. + pub const fn id(self) -> &'static str { + match self { + PersonSort::Photo => "photo", + PersonSort::Oldest => "oldest", + PersonSort::Newest => "newest", + PersonSort::Folder => "folder", + PersonSort::FaceSize => "faceSize", + } + } + + /// The sort `id` names, if it names one. + pub fn parse(id: &str) -> Option { + [PersonSort::Photo, PersonSort::Oldest, PersonSort::Newest, PersonSort::Folder, PersonSort::FaceSize].into_iter().find(|s| s.id() == id) + } + + /// The picker's labels, in order, in English (translated where they are shown). + pub const fn title(self) -> &'static str { + match self { + PersonSort::Photo => "Import Order", + PersonSort::Oldest => "Oldest First", + PersonSort::Newest => "Newest First", + PersonSort::Folder => "Folder", + PersonSort::FaceSize => "Largest Face", + } + } + + /// Every sort, in the picker's order. + pub const ALL: [PersonSort; 5] = [PersonSort::Photo, PersonSort::Oldest, PersonSort::Newest, PersonSort::Folder, PersonSort::FaceSize]; +} + impl ViewMode { /// The two Library grids ([`Self::PhotoGrid`], [`Self::SquareGrid`]). pub fn is_grid(self) -> bool { @@ -617,6 +662,9 @@ pub struct AppSettings { pub photocraft_path: String, /// The file Edit in PhotoCraft hands over. pub photocraft_file: EditFile, + /// Edit in Default Editor: the file handed to the operating system's application for its + /// file type (Photo ▸ Edit In ▸ Edit in Default Editor). + pub default_file: EditFile, /// Memory the caches may hold together, in MB (0 = automatic; `app.memoryBudget`). pub memory_mb: u32, /// Photos an export renders side by side (0 = automatic; `app.exportTuning`, "Test my machine"). @@ -871,6 +919,7 @@ impl Default for AppSettings { external_file: EditFile::default(), photocraft_path: String::new(), photocraft_file: EditFile { format: EditFormat::Psd, ..EditFile::default() }, + default_file: EditFile::default(), memory_mb: 0, export_lanes: 0, export_cpu_only: false, @@ -1606,6 +1655,9 @@ pub struct UiState { /// The person whose page the People view shows (their faces and the faces that look like them); `None`: everyone. #[serde(skip)] pub person_page: Option, + /// How the person's page orders their faces (issue #1691). + #[serde(default)] + pub person_sort: PersonSort, /// The person page a photo in the loupe was opened from (`None`: the People view's unnamed faces), and that photo: /// Escape goes back there (not to the grid). #[serde(skip)] @@ -2899,6 +2951,7 @@ impl Default for UiState { name_edit: None, face_focus: None, person_page: None, + person_sort: PersonSort::default(), person_from: None, last_person: None, cull_burst: None, diff --git a/crates/ui-egui/src/template_browser.rs b/crates/ui-egui/src/template_browser.rs index afe00d1616..31085b018c 100644 --- a/crates/ui-egui/src/template_browser.rs +++ b/crates/ui-egui/src/template_browser.rs @@ -8,6 +8,7 @@ //! `*.moveTemplate` commands are one-liners over it. use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::RichText; use lcc_engine::template_folders::{self as folders, DEFAULT_FOLDER, Foldered}; use serde_json::{Value, json}; @@ -61,7 +62,7 @@ fn dim(ui: &egui::Ui, text: &str) -> RichText { } fn row_ui(ui: &mut egui::Ui, ids: &Ids, r: &Row, current: Option<&str>, listed: &[String], out: &mut Vec) { - let resp = ui.selectable_label(current == Some(r.name.as_str()), r.shown.as_str()); + let resp = ui.pick_label(current == Some(r.name.as_str()), r.shown.as_str()); register(ui.ctx(), format!("{}{}", ids.template, r.name), resp.rect); if resp.clicked() { out.push(Action::Apply(r.name.clone())); diff --git a/crates/ui-egui/src/tests_dropdown_keys.rs b/crates/ui-egui/src/tests_dropdown_keys.rs new file mode 100644 index 0000000000..9b64ab4d9b --- /dev/null +++ b/crates/ui-egui/src/tests_dropdown_keys.rs @@ -0,0 +1,140 @@ +//! An open dropdown takes the keyboard: typing a name moves to the matching item, and no key +//! reaches the Library behind it. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::keyboard::{Owner, owner}; +use crate::{LccApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn ask(h: &mut Headless, method: &str, params: serde_json::Value) { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{method}: {r}"); + h.step(); + h.step(); +} + +/// The demo library's grid with the filter bar over it. +fn filter_bar() -> Headless { + let app = LccApp::new(lcc_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1600.0, 1000.0], 1.0); + h.app.ui.view = crate::state::ViewMode::PhotoGrid; + h.app.ui.filter_bar = true; + h.settle(SETTLE); + h +} + +fn open(h: &mut Headless, picker: &str) { + ask(h, "ui.clickWidget", json!({"id": format!("dropdown:filter-{picker}")})); +} + +fn faces(h: &Headless) -> Option { + h.app.session.filter.faces.clone() +} + +#[test] +fn an_open_dropdown_owns_the_keyboard_and_no_key_reaches_the_library() { + let mut h = filter_bar(); + let active = h.app.session.active().expect("the demo opens on a photo"); + h.app.session.execute("photo.rate", &json!({"ids": [active.0], "rating": 0})).unwrap(); + let rating = |h: &Headless| h.app.session.catalog.photo(active).map(|p| p.rating); + assert_eq!(owner(&h.app, &h.view.ctx), Owner::Window, "nothing has the keyboard before the test"); + open(&mut h, "faces"); + assert_eq!(owner(&h.app, &h.view.ctx), Owner::Popup, "an open dropdown takes the keys"); + ask(&mut h, "ui.key", json!({"key": "5"})); + assert_eq!(rating(&h), Some(0), "a key doesn't rate the photo behind the menu"); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + assert_eq!(owner(&h.app, &h.view.ctx), Owner::Window, "Esc closes the menu and gives the keys back"); + assert_eq!(faces(&h), None, "and chose nothing"); + ask(&mut h, "ui.key", json!({"key": "5"})); + assert_eq!(rating(&h), Some(5), "with the menu closed, 5 rates the photo again"); +} + +#[test] +fn typing_a_name_moves_to_the_item_that_starts_with_it_and_enter_chooses_it() { + let mut h = filter_bar(); + open(&mut h, "faces"); + ask(&mut h, "ui.text", json!({"text": "3"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(faces(&h).as_deref(), Some("3+"), "typing `3` moves to `3+ faces`, and Enter chooses it"); +} + +#[test] +fn a_search_field_in_the_menu_keeps_the_typing() { + let mut h = filter_bar(); + open(&mut h, "camera"); + let cameras = h.app.caches.filter_values(&h.app.session.catalog).cameras.clone(); + assert!(cameras.iter().any(|c| c.to_lowercase().starts_with('s')), "the demo's cameras start with `s`: {cameras:?}"); + // letter by letter, with a camera that starts with the first letter under the field + ask(&mut h, "ui.text", json!({"text": "s"})); + ask(&mut h, "ui.text", json!({"text": "y"})); + assert!(h.view.ctx.text_edit_focused(), "the focus stays in the Search… field"); + let typed: Option = h.view.ctx.data(|d| d.get_temp(egui::Id::new(("filterSearch", "camera")))); + assert_eq!(typed.as_deref(), Some("sy"), "the letters go into the Search… field"); +} + +#[test] +fn letters_typed_close_together_build_one_search_and_a_pause_starts_a_new_one() { + let mut h = filter_bar(); + open(&mut h, "faces"); + // `1`, then `0` a moment later: `10`, which only `10+ faces` starts with + ask(&mut h, "ui.text", json!({"text": "1"})); + h.time += 0.3; + ask(&mut h, "ui.text", json!({"text": "0"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(faces(&h).as_deref(), Some("10+"), "`1` and `0` typed together search for `10`"); + // after a pause the search starts over: `1`, a pause, `3` is `3`, not `13` + h.settle(SETTLE); + open(&mut h, "faces"); + assert_eq!(owner(&h.app, &h.view.ctx), Owner::Popup, "the menu opens again"); + ask(&mut h, "ui.text", json!({"text": "1"})); + h.time += 3.0; + ask(&mut h, "ui.text", json!({"text": "3"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(faces(&h).as_deref(), Some("3+"), "a pause ends the search"); +} + +#[test] +fn arrows_move_the_highlight_enter_chooses_it_and_a_cmd_shortcut_waits() { + let mut h = filter_bar(); + open(&mut h, "faces"); + // ⌘, would open Settings from the Library + ask(&mut h, "ui.key", json!({"key": ",", "cmd": true})); + assert!(h.app.ui.dialog.is_none(), "a Cmd shortcut doesn't reach the Library behind the menu"); + assert_eq!(owner(&h.app, &h.view.ctx), Owner::Popup, "and the menu stays open"); + // ↓ takes the highlight to the first item ("Any faces"), and ↓ again to the second ("No faces") + for _ in 0..2 { + ask(&mut h, "ui.key", json!({"key": "down"})); + } + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(faces(&h).as_deref(), Some("0"), "the arrows moved the highlight and Enter chose it"); + assert_eq!(owner(&h.app, &h.view.ctx), Owner::Window, "choosing closes the menu"); +} + +#[test] +fn down_from_the_search_field_moves_into_the_list() { + let mut h = filter_bar(); + open(&mut h, "keyword"); + ask(&mut h, "ui.text", json!({"text": "t"})); + assert!(h.view.ctx.text_edit_focused(), "the Search… field has the typing"); + ask(&mut h, "ui.key", json!({"key": "down"})); + ask(&mut h, "ui.key", json!({"key": "down"})); + assert!(!h.view.ctx.text_edit_focused(), "↓ leaves the field for the list"); + assert!(h.view.ctx.memory(|m| m.focused().is_some()), "and an item has the highlight"); +} + +#[test] +fn typing_matches_the_start_of_a_name_only() { + let mut h = filter_bar(); + open(&mut h, "faces"); + // "Any faces", "No faces" and "3+ faces" all contain `f`, and none starts with it + ask(&mut h, "ui.text", json!({"text": "f"})); + assert!(h.view.ctx.memory(|m| m.focused().is_none()), "no item takes the highlight for a letter in the middle of names"); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(faces(&h), None, "so Enter chooses nothing"); +} diff --git a/crates/ui-egui/src/tests_enter_in_dialog_fields.rs b/crates/ui-egui/src/tests_enter_in_dialog_fields.rs new file mode 100644 index 0000000000..7ca7aa754b --- /dev/null +++ b/crates/ui-egui/src/tests_enter_in_dialog_fields.rs @@ -0,0 +1,193 @@ +//! Return in a text field of a dialog with several fields does what its confirm button does: the +//! Smart Collection dialog (name and rule values), Edit Capture Time, Color Label Names, Rename +//! Photos, New Preset and its folder, and the Export screen. Where the button is off (rules that +//! don't check) Return does nothing. + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LccApp, Services}; +use serde_json::json; +use std::time::Duration; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LccApp::new(lcc_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(Duration::from_secs(120)); + h +} + +fn req(h: &mut Headless, method: &str, params: serde_json::Value) { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{method}: {r}"); + h.step(); +} + +fn dialog(command: &str, params: serde_json::Value) -> Headless { + let mut h = demo(); + req(&mut h, "command", json!({"command": command, "params": params})); + h.settle(T); + assert!(h.app.ui.dialog.is_some(), "{command} opened a dialog"); + h +} + +fn smart(rules: serde_json::Value) -> Headless { + let mut h = dialog("dialog.smartAlbum", json!({"name": "Keepers"})); + let Some(Dialog::SmartRules { rules: r, .. }) = &mut h.app.ui.dialog else { panic!("no rule editor") }; + *r = serde_json::from_value(json!({"rules": rules})).unwrap(); + h.settle(T); + h +} + +fn smart_albums(h: &Headless) -> usize { + h.app.session.catalog.albums().filter(|a| a.smart.is_some() && a.name == "Keepers").count() +} + +fn capture_time() -> Headless { + let mut h = dialog("dialog.captureTime", json!({"mode": "set"})); + if let Some(Dialog::CaptureTime { time, .. }) = &mut h.app.ui.dialog { + *time = "2026-09-30 14:05:00".into(); + } + h +} + +fn export_screen() -> Headless { + let mut h = dialog("dialog.export", json!({})); + let folder = std::env::temp_dir().join(format!("enter-in-export-{}", std::process::id())); + if let Some(Dialog::Export { opts, dir, .. }) = &mut h.app.ui.dialog { + opts.destination_mode = lcc_engine::export::DestinationMode::SpecificFolder; + *dir = folder.to_string_lossy().into_owned(); + } + h.settle(T); + h +} + +fn rename() -> Headless { + let mut h = demo(); + h.app.ui.dialog = Some(Dialog::Rename { template: "{name}".into(), start: 1, texts: Default::default() }); + h.settle(T); + h +} + +fn preset_folder() -> Headless { + let mut h = demo(); + h.app.ui.dialog = Some(Dialog::CreatePresetFolder { name: "Looks".into(), parent: None }); + h.settle(T); + h +} + +/// Click the field, type nothing more, press Return. +fn enter_in(h: &mut Headless, field: &str) { + req(h, "ui.clickWidget", json!({"id": field})); + assert!(h.view.ctx.egui_wants_keyboard_input(), "{field} has the keys"); + req(h, "ui.key", json!({"key": "Enter"})); + h.settle(T); +} + +/// One row per field: Return in it does what the dialog's button does. Most dialogs close; the +/// Export screen starts the export, which a headless run has no writer for: it says so (the +/// toast), where without Return it stays quiet. +#[test] +fn return_in_a_field_of_each_dialog_confirms_it() { + type Row = (&'static str, fn() -> Headless, &'static str, bool); + let rows: [Row; 9] = [ + ("Smart Collection name", || smart(json!([{"field": "rating", "op": "gte", "value": 3}])), "field:smartName", false), + ("Smart Collection rule value", || smart(json!([{"field": "title", "op": "contains", "value": "x"}])), "field:rules-0", false), + ("Edit Capture Time", capture_time, "field:captureTime", false), + ("Color Label Names", || dialog("dialog.labelNames", json!({})), "field:labelName-red", false), + ("Rename Photos template", rename, "field:renameTemplate", false), + ("New Preset name", || dialog("dialog.createPreset", json!({})), "field:presetName", false), + ("New Preset folder name", preset_folder, "field:presetFolderName", false), + ("Export: folder", export_screen, "field:exportFolder", true), + ("Export: subfolder", export_screen, "field:exportSubfolder", true), + ]; + let mut wrong = Vec::new(); + for (what, make, field, starts_export) in rows { + let mut h = make(); + assert!(h.app.ui.toast().is_none(), "{what}: nothing said yet"); + enter_in(&mut h, field); + let confirmed = if starts_export { h.app.ui.toast().is_some() } else { h.app.ui.dialog.is_none() }; + if !confirmed { + wrong.push(format!("{what}: Return did not confirm")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn return_in_the_smart_collection_name_saves_the_collection() { + let mut h = smart(json!([{"field": "rating", "op": "gte", "value": 3}])); + enter_in(&mut h, "field:smartName"); + assert_eq!(smart_albums(&h), 1, "the Smart Collection was created"); +} + +/// Rules that don't check leave the button off, and Return does nothing: no collection, the +/// dialog open with its marked problems, the field still holding the keys. +#[test] +fn return_with_rules_that_dont_check_does_nothing() { + let mut h = smart(json!([{"field": "album", "op": "isNot", "value": null}])); + enter_in(&mut h, "field:smartName"); + assert!(matches!(h.app.ui.dialog, Some(Dialog::SmartRules { .. })), "the dialog stays open"); + assert_eq!(smart_albums(&h), 0, "nothing was created"); + assert!(h.view.ctx.egui_wants_keyboard_input(), "the field keeps the keys"); +} + +/// Return in the rule's value ends its edit and then saves, when the rules check. +#[test] +fn return_in_a_rule_value_ends_the_edit_and_saves() { + let mut h = smart(json!([{"field": "title", "op": "contains", "value": ""}])); + req(&mut h, "ui.clickWidget", json!({"id": "field:rules-0"})); + req(&mut h, "ui.text", json!({"text": "sunset"})); + req(&mut h, "ui.key", json!({"key": "Enter"})); + h.settle(T); + assert!(h.app.ui.dialog.is_none(), "the dialog closed"); + assert_eq!(smart_albums(&h), 1, "the collection was saved"); + let saved = h.app.session.catalog.albums().find(|a| a.name == "Keepers").and_then(|a| a.smart.as_ref().map(|s| format!("{s:?}"))); + assert!(saved.is_some_and(|s| s.contains("sunset")), "with the typed value"); +} + +/// The multi-line watermark text still takes a new line on Return. +#[test] +fn return_in_the_multiline_watermark_text_still_starts_a_line() { + let mut h = dialog("dialog.watermark", json!({})); + req(&mut h, "ui.clickWidget", json!({"id": "field:watermarkText"})); + req(&mut h, "ui.text", json!({"text": "a"})); + req(&mut h, "ui.key", json!({"key": "Enter"})); + req(&mut h, "ui.text", json!({"text": "b"})); + h.settle(T); + let Some(Dialog::Watermark { wm, .. }) = &h.app.ui.dialog else { panic!("the Watermark dialog closed") }; + assert!(wm.text.contains("a\nb"), "the text is {:?}", wm.text); +} + +/// Esc closes each of these dialogs as it did. +#[test] +fn esc_in_a_field_still_closes_each_dialog() { + for (what, make, field) in [ + ("Smart Collection", (|| smart(json!([{"field": "rating", "op": "gte", "value": 3}]))) as fn() -> Headless, "field:smartName"), + ("Edit Capture Time", capture_time, "field:captureTime"), + ("New Preset", || dialog("dialog.createPreset", json!({})), "field:presetName"), + ] { + let mut h = make(); + req(&mut h, "ui.clickWidget", json!({"id": field})); + req(&mut h, "ui.key", json!({"key": "Escape"})); + h.settle(T); + assert!(h.app.ui.dialog.is_none(), "{what}: Esc closed the dialog"); + } +} + +/// The Export module (the settings column beside the preview) starts the export on Return in a +/// settings field, as its button does. A headless run has no writer, so it says so in the status +/// line, where without Return it stays quiet. +#[test] +fn return_in_a_field_of_the_export_module_starts_the_export() { + let mut h = demo(); + req(&mut h, "engine.execute", json!({"command": "module.export", "params": {}})); + h.settle(T); + assert!(h.app.ui.status.is_empty(), "nothing said yet: {:?}", h.app.ui.status); + enter_in(&mut h, "field:exportSubfolder"); + assert!(!h.app.ui.status.is_empty(), "Return started the export, which the headless run could not write"); +} diff --git a/crates/ui-egui/src/tests_esc_in_fields.rs b/crates/ui-egui/src/tests_esc_in_fields.rs new file mode 100644 index 0000000000..a502ed9637 --- /dev/null +++ b/crates/ui-egui/src/tests_esc_in_fields.rs @@ -0,0 +1,191 @@ +//! Esc in a text field of a full-window screen (Settings, Import, Export) leaves the field first; the +//! next Esc closes the screen. A dialog form keeps closing on Esc from a field (issue #1388). + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LccApp, Services}; +use serde_json::json; +use std::time::Duration; + +const T: Duration = Duration::from_secs(20); + +fn demo(size: [f32; 2], ui: serde_json::Value) -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LccApp::new(lcc_engine::Session::with_demo(), services); + let mut h = Headless::new(app, size, 1.0); + let r = h.request("ui.set", ui, T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(Duration::from_secs(120)); + h +} + +fn req(h: &mut Headless, method: &str, params: serde_json::Value) { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{method}: {r}"); + h.step(); +} + +fn esc(h: &mut Headless) { + req(h, "ui.key", json!({"key": "Escape"})); + h.step(); + h.step(); +} + +fn open(h: &mut Headless) -> bool { + h.app.ui.dialog.is_some() +} + +fn settings(modern: bool) -> Headless { + settings_tab(modern, "general") +} + +fn settings_tab(modern: bool, page: &str) -> Headless { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + if modern { + req(&mut h, "engine.execute", json!({"command": "view.modernLayout", "params": {"on": true}})); + } + req(&mut h, "engine.execute", json!({"command": "app.settings", "params": {"tab": page}})); + h.settle(T); + assert!(matches!(h.app.ui.dialog, Some(Dialog::Settings { .. })), "Settings is open"); + h +} + +/// What the first Esc does in a field of a container. +#[derive(Clone, Copy, Debug, PartialEq)] +enum First { + /// It leaves the field; the container stays, and the next Esc closes it. + LeavesTheField, + /// A dialog form keeps closing on Esc from a field (issue #1388). + ClosesTheDialog, +} + +type Row = (&'static str, fn() -> Headless, &'static str, First); + +fn import_review() -> Headless { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + let file = lcc_engine::import::ImportCandidate { path: "/photos/new.jpg".into(), ..Default::default() }; + h.app.ui.dialog = Some(Dialog::Import { opts: Box::new(crate::import::ImportDialog::new(vec![file])) }); + h.settle(T); + h +} + +fn export_screen() -> Headless { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + req(&mut h, "command", json!({"command": "dialog.export"})); + if let Some(Dialog::Export { opts, .. }) = &mut h.app.ui.dialog { + opts.destination_mode = lcc_engine::export::DestinationMode::SpecificFolder; + } + h.settle(T); + h +} + +fn new_collection() -> Headless { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + req(&mut h, "command", json!({"command": "dialog.newAlbum"})); + h.settle(T); + h +} + +/// One row per container that can show a text field in a headless run: Esc in a field, then Esc again. +#[test] +fn the_first_esc_in_a_field_of_each_container() { + let rows: [Row; 6] = [ + ("Settings window: search", || settings(false), "settingsSearch", First::LeavesTheField), + ("Settings sheet: search", || settings(true), "settingsSearch", First::LeavesTheField), + ("Settings page: an External Editing field", || settings_tab(false, "external"), "field:externalEditor", First::LeavesTheField), + ("Import: keywords", import_review, "field:importKeywords", First::LeavesTheField), + ("Export: folder", export_screen, "field:exportFolder", First::LeavesTheField), + ("New Collection (a dialog form)", new_collection, "field:albumName", First::ClosesTheDialog), + ]; + let mut wrong = Vec::new(); + for (what, make, field, first) in rows { + let mut h = make(); + req(&mut h, "ui.clickWidget", json!({"id": field})); + req(&mut h, "ui.text", json!({"text": "x"})); + if !h.view.ctx.egui_wants_keyboard_input() { + wrong.push(format!("{what}: the field never had the keys")); + continue; + } + esc(&mut h); + match first { + First::LeavesTheField => { + if !open(&mut h) { + wrong.push(format!("{what}: the first Esc closed the screen")); + continue; + } + if h.view.ctx.egui_wants_keyboard_input() { + wrong.push(format!("{what}: the first Esc left the field with the keys")); + } + esc(&mut h); + if open(&mut h) { + wrong.push(format!("{what}: the next Esc did not close the screen")); + } + } + First::ClosesTheDialog => { + if open(&mut h) { + wrong.push(format!("{what}: the dialog stayed open on Esc")); + } + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// With no field focused one Esc still closes Settings. +#[test] +fn esc_with_no_field_focused_closes_settings() { + let mut h = settings(false); + esc(&mut h); + assert!(!open(&mut h), "Esc closed Settings"); +} + +/// A popup open over Settings takes the first Esc, with the search field not involved. +#[test] +fn esc_with_a_dropdown_open_in_settings_closes_only_the_dropdown() { + let mut h = settings(false); + req(&mut h, "ui.clickWidget", json!({"id": "combo:settingsLanguage"})); + assert!(egui::Popup::is_any_open(&h.view.ctx), "the language list is open"); + esc(&mut h); + assert!(!egui::Popup::is_any_open(&h.view.ctx), "the first Esc closes the list"); + assert!(open(&mut h), "Settings stays open"); + esc(&mut h); + assert!(!open(&mut h), "the next Esc closes Settings"); +} + +/// While Settings takes Esc for its field, nothing behind it moves: the loupe stays and so does the selection. +#[test] +fn esc_in_a_settings_field_leaves_the_photos_behind_alone() { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + h.app.ui.view = crate::state::ViewMode::Detail; + let selected = h.app.session.selected(); + req(&mut h, "engine.execute", json!({"command": "app.settings", "params": {"tab": "general"}})); + h.settle(T); + req(&mut h, "ui.clickWidget", json!({"id": "settingsSearch"})); + req(&mut h, "ui.text", json!({"text": "x"})); + for step in ["leaves the field", "closes Settings"] { + esc(&mut h); + assert_eq!(h.app.ui.view, crate::state::ViewMode::Detail, "Esc that {step} keeps the loupe"); + assert_eq!(h.app.session.selected(), selected, "Esc that {step} keeps the selection"); + } + assert!(!open(&mut h), "Settings closed"); +} + +/// Modern Back (the Android key) with the cursor in a Settings field leaves the field first, then closes Settings. +#[test] +fn back_in_a_settings_field_leaves_the_field_first() { + let mut h = settings(true); + req(&mut h, "ui.clickWidget", json!({"id": "settingsSearch"})); + req(&mut h, "ui.text", json!({"text": "x"})); + let view = h.app.ui.view; + req(&mut h, "ui.key", json!({"key": "BrowserBack"})); + h.step(); + h.step(); + assert!(open(&mut h), "the first Back only leaves the field"); + assert!(!h.view.ctx.egui_wants_keyboard_input(), "the field let go of the keys"); + h.settle(T); + req(&mut h, "ui.key", json!({"key": "BrowserBack"})); + h.step(); + h.step(); + assert!(!open(&mut h), "the next Back closes Settings"); + assert_eq!(h.app.ui.view, view, "the screen behind is unchanged"); +} diff --git a/crates/ui-egui/src/tests_filter_search.rs b/crates/ui-egui/src/tests_filter_search.rs index 63d4bd1bbf..cb253ad14f 100644 --- a/crates/ui-egui/src/tests_filter_search.rs +++ b/crates/ui-egui/src/tests_filter_search.rs @@ -442,3 +442,211 @@ fn switching_semantic_search_off_takes_the_ai_button_away() { h.step(); assert!(has_ai(&h), "the button is back"); } + +/// Issue #1708: the Metadata Date column expands Year -> Month -> Day, filters by day, month, or +/// year, toggles without picking, and searches across months and days. +#[test] +fn metadata_date_column_filters_by_year_month_and_day() { + let mut h = filter_bar(); + let all_ids = h.app.session.visible_cloned(); + assert!(all_ids.len() >= 4); + for (id, date) in [ + (all_ids[0], "2028-03-14T09:00:00"), + (all_ids[1], "2028-03-15T11:00:00"), + (all_ids[2], "2028-04-02T14:00:00"), + (all_ids[3], "2027-07-19T16:00:00"), + ] { + h.app.session.catalog.apply(lcc_catalog::Op::SetCaptured { id, captured: Some(date.into()) }).unwrap(); + } + h.app.session.refresh_view(); + let total = h.app.session.visible_cloned().len(); + + ok(&mut h, "ui.clickWidget", json!({"id": "button:filterColumns"})); + assert_eq!(h.app.ui.filter_columns[0], "year"); + assert!(h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2028")); + assert!(h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2027")); + + // Expanding 2028 reveals its months; expanding 2028-03 reveals its individual days. + assert!(!h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2028-03"), "multi-year starts collapsed"); + ok(&mut h, "ui.clickWidget", json!({"id": "filterDateToggle:0:2028"})); + assert!(h.app.session.filter.date.is_none(), "clicking the toggle does not pick the year"); + assert!(h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2028-03")); + ok(&mut h, "ui.clickWidget", json!({"id": "filterDateToggle:0:2028-03"})); + assert!(h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2028-03-14")); + assert!(h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2028-03-15")); + + // Clicking a day filters to that day only; clicking it again clears the filter. + ok(&mut h, "ui.clickWidget", json!({"id": "filterDate:0:2028-03-14"})); + assert_eq!(h.app.session.filter.date.as_deref(), Some("2028-03-14")); + assert_eq!(h.app.session.visible_cloned(), vec![all_ids[0]]); + ok(&mut h, "ui.clickWidget", json!({"id": "filterDate:0:2028-03-14"})); + assert_eq!(h.app.session.visible_cloned().len(), total); + + // Clicking a month filters to that month. + ok(&mut h, "ui.clickWidget", json!({"id": "filterDate:0:2028-03"})); + assert_eq!(h.app.session.filter.date.as_deref(), Some("2028-03")); + let mut vis = h.app.session.visible_cloned(); + vis.sort(); + let mut want = vec![all_ids[0], all_ids[1]]; + want.sort(); + assert_eq!(vis, want); + + // Searching in the Date column expands matching months/days across collapsed years. + ok(&mut h, "ui.clickWidget", json!({"id": "filterValue:0:0"})); + ok(&mut h, "ui.clickWidget", json!({"id": "field:filterColumnSearch:0"})); + ok(&mut h, "ui.text", json!({"text": "2027-07-19"})); + assert!(h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2027-07-19"), "search expands matching day"); + assert!(!h.app.widgets.iter().any(|(w, _)| w == "filterDate:0:2028")); +} + +/// The Flag column lists its statuses ascending by the label shown (Picked, Rejected, Unflagged), not by count. +#[test] +fn the_flag_column_lists_picked_rejected_unflagged_whatever_the_counts() { + use lcc_catalog::Flag; + let mut h = filter_bar(); + // the demo library holds all three; make Unflagged the most numerous and Picked the fewest, the order the engine lists + let ids: Vec<_> = h.app.session.visible_cloned(); + for (n, id) in ids.iter().enumerate() { + let flag = match n { + 0 => "pick", + 1 | 2 => "reject", + _ => "none", + }; + ok(&mut h, "engine.execute", json!({"command": "photo.flag", "params": {"ids": [id.0], "flag": flag}})); + } + ok(&mut h, "ui.clickWidget", json!({"id": "button:filterColumns"})); + ok(&mut h, "engine.execute", json!({"command": "view.filterColumns", "params": {"column": 1, "field": "flag"}})); + for (row, want) in [(1, Flag::Pick), (2, Flag::Reject), (3, Flag::None)] { + ok(&mut h, "ui.clickWidget", json!({"id": format!("filterValue:1:{row}")})); + assert_eq!(h.app.session.filter.flag, Some(want), "row {row} of the Flag column"); + } +} + +/// A click on a widget with the modifiers held (`cmd` is ⌘ on a Mac and Ctrl elsewhere). +fn click_with(h: &mut Headless, id: &str, cmd: bool, shift: bool) { + ok(h, "ui.clickWidget", json!({"id": id, "cmd": cmd, "shift": shift})); +} + +/// The demo library with capture dates in 1995 to 1997 and a flag and rating of every kind, the Metadata columns +/// shown, and column 1 listing `field`. +fn multi_choice_bar(field: &str) -> (Headless, Vec) { + let mut h = filter_bar(); + let ids: Vec<_> = h.app.session.catalog.photos().filter(|p| p.in_library()).take(6).map(|p| p.id).collect(); + for (n, id) in ids.iter().enumerate() { + let date = ["1995-06-01", "1995-06-02", "1996-03-10", "1996-07-05", "1997-01-01", "1997-02-02"][n]; + h.app.session.catalog.apply(lcc_catalog::Op::SetCaptured { id: *id, captured: Some(format!("{date}T10:00:00")) }).unwrap(); + let flag = ["pick", "none", "reject"][n % 3]; + ok(&mut h, "engine.execute", json!({"command": "photo.flag", "params": {"ids": [id.0], "flag": flag}})); + let rating = [1, 2][n % 2]; + ok(&mut h, "engine.execute", json!({"command": "photo.rate", "params": {"ids": [id.0], "rating": rating}})); + } + ok(&mut h, "ui.clickWidget", json!({"id": "button:filterColumns"})); + ok(&mut h, "engine.execute", json!({"command": "view.filterColumns", "params": {"column": 1, "field": field}})); + (h, ids) +} + +/// The widget id of the row of `value` in column 1, as the column lists it. +fn row_of(h: &mut Headless, field: &str, value: &str) -> String { + let rows: Vec = h.app.session.execute("library.facets", &json!({"fields": [field]})).unwrap()[field]["values"] + .as_array() + .unwrap() + .iter() + .map(|v| v["value"].as_str().unwrap().to_string()) + .collect(); + format!("filterValue:1:{}", rows.iter().position(|v| v == value).unwrap() + 1) +} + +/// The values of the column's `facets` entry. +fn picked(h: &Headless, field: &str) -> Vec { + h.app.session.filter.facets.iter().find(|p| p.field == field).map(|p| p.values.clone()).unwrap_or_default() +} + +#[test] +fn cmd_click_adds_a_date_and_shift_click_runs_over_sibling_rows() { + let (mut h, _) = multi_choice_bar("year"); + click_with(&mut h, "filterDate:1:1995", false, false); + assert_eq!(h.app.session.filter.date.as_deref(), Some("1995"), "a plain click chooses it alone"); + click_with(&mut h, "filterDate:1:1997", true, false); + assert_eq!(picked(&h, "year"), ["1995", "1997"], "⌘-click adds"); + assert_eq!(h.app.session.visible().len(), 4, "photos from 1995 or 1997"); + click_with(&mut h, "filterDate:1:1995", true, false); + assert_eq!(h.app.session.filter.date.as_deref(), Some("1997"), "⌘-click on a chosen value takes it off"); + click_with(&mut h, "filterDate:1:1996", false, false); + assert_eq!(h.app.session.filter.date.as_deref(), Some("1996"), "a plain click replaces the choice"); + click_with(&mut h, "filterDate:1:1997", false, true); + assert_eq!(picked(&h, "year"), ["1996", "1997"], "⇧-click runs from the last clicked row"); + click_with(&mut h, "filterDate:1:1995", false, true); + assert_eq!(picked(&h, "year"), ["1995", "1996"], "and replaces the earlier choice, keeping its anchor"); +} + +#[test] +fn clicks_with_modifiers_choose_several_flags_in_the_column_and_the_icons_alike() { + let (mut h, ids) = multi_choice_bar("flag"); + // the column lists Picked, Rejected, Unflagged + click_with(&mut h, "filterValue:1:3", false, false); + assert_eq!(h.app.session.filter.flags_shown(), Some(vec![lcc_catalog::Flag::None])); + click_with(&mut h, "filterValue:1:1", true, false); + assert_eq!(h.app.session.filter.flags_shown(), Some(vec![lcc_catalog::Flag::Pick, lcc_catalog::Flag::None])); + // the icons show the same choice, and ⌘-click on one takes it off + click_with(&mut h, "filter:pick", true, false); + assert_eq!(h.app.session.filter.flags_shown(), Some(vec![lcc_catalog::Flag::None])); + click_with(&mut h, "filter:reject", true, false); + assert_eq!(h.app.session.filter.flags_shown(), Some(vec![lcc_catalog::Flag::None, lcc_catalog::Flag::Reject])); + let shown = h.app.session.visible_cloned(); + assert!(shown.iter().all(|id| h.app.session.catalog.photo(*id).unwrap().flag != lcc_catalog::Flag::Pick), "{ids:?}"); + // a plain click on an icon chooses it alone, and again clears it + click_with(&mut h, "filter:pick", false, false); + assert_eq!(h.app.session.filter.flags_shown(), Some(vec![lcc_catalog::Flag::Pick])); + click_with(&mut h, "filter:pick", false, false); + assert_eq!(h.app.session.filter.flags_shown(), None); + // ⇧-click runs in the column's order: Picked, Rejected + click_with(&mut h, "filterValue:1:1", false, false); + click_with(&mut h, "filterValue:1:2", false, true); + assert_eq!(h.app.session.filter.flags_shown(), Some(vec![lcc_catalog::Flag::Pick, lcc_catalog::Flag::Reject])); +} + +#[test] +fn cmd_click_adds_a_rating_and_the_stars_take_over_again() { + let (mut h, _) = multi_choice_bar("rating"); + let (one, two) = (row_of(&mut h, "rating", "1"), row_of(&mut h, "rating", "2")); + click_with(&mut h, &one, false, false); + click_with(&mut h, &two, true, false); + assert_eq!(picked(&h, "rating"), ["1", "2"]); + let shown = h.app.session.visible_cloned(); + assert!(!shown.is_empty() && shown.iter().all(|id| [1, 2].contains(&h.app.session.catalog.photo(*id).unwrap().rating))); + ok(&mut h, "ui.clickWidget", json!({"id": "filter:star4"})); + assert!(picked(&h, "rating").is_empty(), "a star click ends the column's several-rating choice"); + assert_eq!(h.app.session.filter.rating, 4); +} + +#[test] +fn the_type_menu_takes_several_types_and_all_types_clears_them() { + let mut h = filter_bar(); + ok(&mut h, "ui.clickWidget", json!({"id": "dropdown:filter-kind"})); + // rows: All types, Photos, Raw, Videos, HDR, Panoramas, HDR Panoramas, Focus Stacks + ok(&mut h, "ui.clickWidget", json!({"id": "filterItem:kind:1"})); + assert_eq!(h.app.session.filter.kind, Some(lcc_catalog::MediaKind::Image), "one type is the single field"); + ok(&mut h, "ui.clickWidget", json!({"id": "filterItem:kind:2"})); + assert_eq!(picked(&h, "kind"), ["image", "raw"], "the menu stays open and a second pick adds"); + ok(&mut h, "ui.clickWidget", json!({"id": "filterItem:kind:4"})); + assert_eq!(picked(&h, "kind"), ["image", "raw", "hdr"], "the merged kinds join the choice"); + ok(&mut h, "ui.clickWidget", json!({"id": "filterItem:kind:1"})); + assert_eq!(picked(&h, "kind"), ["raw", "hdr"], "a chosen type is taken off"); + ok(&mut h, "ui.clickWidget", json!({"id": "filterItem:kind:0"})); + assert_eq!(h.app.session.filter, lcc_catalog::Filter::default(), "All types clears the choice"); +} + +#[test] +fn a_plain_click_replaces_a_camera_choice_and_cmd_click_adds() { + let (mut h, _) = multi_choice_bar("camera"); + click_with(&mut h, "filterValue:1:1", false, false); + click_with(&mut h, "filterValue:1:2", false, false); + assert_eq!(picked_cameras(&h).len(), 1, "a plain click replaces the camera"); + click_with(&mut h, "filterValue:1:1", true, false); + assert_eq!(picked_cameras(&h).len(), 2, "⌘-click adds one"); +} + +fn picked_cameras(h: &Headless) -> Vec { + let f = &h.app.session.filter; + f.cameras.iter().cloned().chain(f.camera.clone()).collect() +} diff --git a/crates/ui-egui/src/tests_grid.rs b/crates/ui-egui/src/tests_grid.rs index 7fc2accf7c..b838390e0b 100644 --- a/crates/ui-egui/src/tests_grid.rs +++ b/crates/ui-egui/src/tests_grid.rs @@ -10,6 +10,7 @@ use lcc_engine::Session; use serde_json::json; use crate::headless::Headless; +use crate::panels::grid::vertical_neighbor; use crate::state::ViewMode; use crate::{LccApp, Services}; @@ -642,3 +643,129 @@ fn panel_resizes_and_filter_toggles_keep_the_selected_photo_in_place() { assert!((now - before).abs() < 2.0, "filter bar: moved from {before} to {now}"); } } + +/// Shift+↑ / Shift+↓ in the top or bottom row extend the selection toward the ends of the view, the way +/// Shift+← / Shift+→ do; away from those rows they still run to the cell above / below (B-F3A3). +#[test] +fn shift_arrows_in_the_top_or_bottom_row_extend_toward_the_ends_of_the_view() { + let mut h = grid(ViewMode::PhotoGrid); + let vis = h.app.session.visible().to_vec(); + let lay = h.app.caches.grid.laid_out().expect("grid laid out").clone(); + let rows = lay.rows.clone(); + assert!(rows.len() >= 3, "a grid of {N} photos has more than two rows, got {}", rows.len()); + let top = rows[0].end - 1; // the last photo of the top row + let bottom = rows[rows.len() - 1].start; // the first photo of the bottom row + assert!(top >= 1 && bottom + 1 < vis.len(), "the top row has a photo before {top}, the bottom row one after {bottom}"); + let shift = |h: &mut Headless, k: &str, cmd: bool| { + let r = h.request("ui.key", json!({"key": k, "shift": true, "cmd": cmd}), T); + assert_eq!(r["ok"], true, "{k}: {r}"); + h.settle(SETTLE); + }; + // the selected photos and the active one, as a set + let sel = |h: &Headless| (h.app.session.selection.ids.clone(), h.app.session.selection.active); + + // AC-1 (and AC-5 with Cmd): the top row, not the first photo: Shift+↑ adds the previous photo and makes it active + for cmd in [false, true] { + select(&mut h, vis[top]); + shift(&mut h, "ArrowUp", cmd); + let (ids, active) = sel(&h); + assert_eq!(active, Some(vis[top - 1]), "Shift+↑ in the top row (cmd {cmd}): the previous photo is active"); + assert!(ids.len() == 2 && ids.contains(&vis[top]) && ids.contains(&vis[top - 1]), "Shift+↑ adds it (cmd {cmd}): {ids:?}"); + } + + // AC-2 (and AC-5 with Cmd): the bottom row, not the last photo: Shift+↓ adds the next photo and makes it active + for cmd in [false, true] { + select(&mut h, vis[bottom]); + shift(&mut h, "ArrowDown", cmd); + let (ids, active) = sel(&h); + assert_eq!(active, Some(vis[bottom + 1]), "Shift+↓ in the bottom row (cmd {cmd}): the next photo is active"); + assert!(ids.len() == 2 && ids.contains(&vis[bottom]) && ids.contains(&vis[bottom + 1]), "Shift+↓ adds it (cmd {cmd}): {ids:?}"); + } + + // AC-5, Ctrl: the binding is Cmd+Shift on macOS and Ctrl+Shift elsewhere (egui's `command`), so Ctrl+Shift+↑ + // extends the selection off macOS and does nothing on it + let mac = cfg!(target_os = "macos"); + select(&mut h, vis[top]); + let r = h.request("ui.key", json!({"key": "ArrowUp", "shift": true, "ctrl": true, "cmd": !mac}), T); + assert_eq!(r["ok"], true, "Ctrl+Shift+↑: {r}"); + h.settle(SETTLE); + if mac { + assert_eq!(sel(&h), (vec![vis[top]], Some(vis[top])), "Ctrl+Shift+↑ is not bound on macOS"); + } else { + assert_eq!(sel(&h).1, Some(vis[top - 1]), "Ctrl+Shift+↑ in the top row extends like Cmd+Shift+↑"); + } + select(&mut h, vis[bottom]); + let r = h.request("ui.key", json!({"key": "ArrowDown", "shift": true, "ctrl": true, "cmd": !mac}), T); + assert_eq!(r["ok"], true, "Ctrl+Shift+↓: {r}"); + h.settle(SETTLE); + if mac { + assert_eq!(sel(&h), (vec![vis[bottom]], Some(vis[bottom])), "Ctrl+Shift+↓ is not bound on macOS"); + } else { + assert_eq!(sel(&h).1, Some(vis[bottom + 1]), "Ctrl+Shift+↓ in the bottom row extends like Cmd+Shift+↓"); + } + + // AC-3: at the first photo Shift+↑ does nothing, and at the last photo Shift+↓ does nothing + select(&mut h, vis[0]); + shift(&mut h, "ArrowUp", false); + assert_eq!(sel(&h), (vec![vis[0]], Some(vis[0])), "Shift+↑ at the first photo of the view"); + select(&mut h, *vis.last().expect("photos")); + shift(&mut h, "ArrowDown", false); + assert_eq!(sel(&h), (vec![*vis.last().expect("photos")], vis.last().copied()), "Shift+↓ at the last photo of the view"); + + // AC-4: away from the top and bottom rows, every photo up to the cell above / below joins the selection + let mid = rows[1].start; + let below = vertical_neighbor(&lay, mid, true).expect("a row below"); + select(&mut h, vis[mid]); + shift(&mut h, "ArrowDown", false); + let (ids, active) = sel(&h); + assert_eq!(active, Some(vis[below]), "Shift+↓ from the second row reaches the cell below"); + assert_eq!(ids.len(), below - mid + 1, "Shift+↓ selects every photo down to the cell below: {ids:?}"); + let above = vertical_neighbor(&lay, mid, false).expect("a row above"); + select(&mut h, vis[mid]); + shift(&mut h, "ArrowUp", false); + let (ids, active) = sel(&h); + assert_eq!(active, Some(vis[above]), "Shift+↑ from the second row reaches the cell above"); + assert_eq!(ids.len(), mid - above + 1, "Shift+↑ selects every photo up to the cell above: {ids:?}"); +} + +/// F-66C0 (AC-1 to AC-5): with no photo active, ↑ selects the view's first photo and ↓ its last, each made active; +/// with a photo selected the arrows step from it. Cmd+D leaves no active photo (B-C9D3), so that state is set here. +#[test] +fn arrows_with_no_photo_active_take_the_first_or_last_of_the_view() { + let mut h = grid(ViewMode::PhotoGrid); + let vis = h.app.session.visible().to_vec(); + let (first, last) = (vis[0], *vis.last().unwrap()); + let nothing = |h: &mut Headless| h.app.session.selection = lcc_engine::Selection { ids: vec![], active: None }; + let key = |h: &mut Headless, k: &str| { + let r = h.request("ui.key", json!({"key": k}), T); + assert_eq!(r["ok"], true, "{k}: {r}"); + h.settle(SETTLE); + }; + + // AC-1: nothing selected, ↑ selects the first photo of the view and makes it active + nothing(&mut h); + key(&mut h, "ArrowUp"); + assert_eq!(h.app.session.selection.active, Some(first), "↑ with no photo: the first"); + assert_eq!(h.app.session.selection.ids, vec![first]); + + // AC-2: nothing selected, ↓ selects the last photo of the view and makes it active + nothing(&mut h); + key(&mut h, "ArrowDown"); + assert_eq!(h.app.session.selection.active, Some(last), "↓ with no photo: the last"); + assert_eq!(h.app.session.selection.ids, vec![last]); + + // AC-4: several photos selected but none active (the state Cmd+D leaves) acts the same + h.app.session.selection = lcc_engine::Selection { ids: vec![vis[5], vis[6]], active: None }; + key(&mut h, "ArrowDown"); + assert_eq!(h.app.session.selection.active, Some(last), "↓ with no active photo: the last"); + h.app.session.selection = lcc_engine::Selection { ids: vec![vis[5], vis[6]], active: None }; + key(&mut h, "ArrowUp"); + assert_eq!(h.app.session.selection.active, Some(first), "↑ with no active photo: the first"); + + // AC-3: with a photo selected, ↓ moves from it to the cell below, not to an edge + select(&mut h, vis[10]); + key(&mut h, "ArrowDown"); + let below = h.app.session.selection.active.expect("active"); + assert!(below != vis[10] && below != first && below != last, "↓ steps from the active photo: {below:?}"); + assert_eq!(h.app.session.selection.ids, vec![below]); +} diff --git a/crates/ui-egui/src/tests_grid_empty_click.rs b/crates/ui-egui/src/tests_grid_empty_click.rs new file mode 100644 index 0000000000..692358a66c --- /dev/null +++ b/crates/ui-egui/src/tests_grid_empty_click.rs @@ -0,0 +1,156 @@ +//! Headless tests of a click on the grid's empty space (B-8125): below the last row, or in the gap +//! beside a photo. It clears the selection and the active photo, with or without a modifier; a click +//! on a photo or a date header keeps its own behaviour; a press that becomes a drag clears nothing. + +use std::time::Duration; + +use egui::{Pos2, Rect, pos2}; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::{LccApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn exec(h: &mut Headless, command: &str, params: Value) -> Value { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + h.settle(SETTLE); + r +} + +fn rect(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// The demo library in the grid, with nothing selected yet. +fn library() -> Headless { + let app = LccApp::new(lcc_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 1400.0], 1.0); + let first = h.app.session.visible_cloned()[0].0; + exec(&mut h, "library.select", json!({"ids": [first]})); + exec(&mut h, "module.library", json!({})); + exec(&mut h, "view.photoGrid", json!({})); + // by capture day, so that the grid draws its date headers + exec(&mut h, "library.sort", json!({"key": "captureDate", "group": "day"})); + assert!(rect(&h, "grid:scroll").is_some(), "the grid is on screen"); + h +} + +/// A spot in the grid's visible part that no photo or date header covers: a gap between the photos. +fn empty_spot(h: &Headless) -> Pos2 { + let grid = rect(h, "grid:scroll").expect("the grid"); + let taken: Vec = h.app.widgets.iter().filter(|(w, _)| w.starts_with("thumb:") || w.starts_with("group:")).map(|(_, r)| *r).collect(); + // below the pinned date header at the top + let mut y = grid.top() + 60.0; + while y < grid.bottom() - 2.0 { + let mut x = grid.left() + 2.0; + while x < grid.right() - 20.0 { + let p = pos2(x, y); + if !taken.iter().any(|r| r.contains(p)) { + return p; + } + x += 3.0; + } + y += 3.0; + } + panic!("no empty spot in the grid"); +} + +fn click(h: &mut Headless, at: Pos2, modifiers: Value) { + let mut p = json!({"x": at.x, "y": at.y}); + for (k, v) in modifiers.as_object().into_iter().flatten() { + p[k] = v.clone(); + } + let r = h.request("ui.click", p, T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); +} + +fn select(h: &mut Headless, ids: &[u64], active: u64) { + let r = exec(h, "library.select", json!({"ids": ids, "active": active})); + assert_eq!(r["ok"], true, "{r}"); +} + +#[test] +fn a_click_on_empty_space_clears_the_selection_and_the_active_photo_with_any_modifier() { + let mut h = library(); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + for modifiers in [json!({}), json!({"cmd": true}), json!({"shift": true}), json!({"ctrl": true}), json!({"alt": true})] { + select(&mut h, &ids[..2], ids[1]); + assert_eq!(h.app.session.selection.ids.len(), 2, "two photos selected before the click"); + let spot = empty_spot(&h); + click(&mut h, spot, modifiers.clone()); + assert!(h.app.session.selection.ids.is_empty(), "a click on empty space ({modifiers}) clears the selection"); + assert_eq!(h.app.session.selection.active, None, "and the active photo ({modifiers})"); + } +} + +#[test] +fn a_click_on_a_photo_still_selects_that_photo_alone() { + let mut h = library(); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + select(&mut h, &ids[..2], ids[0]); + // a photo that isn't selected, clear of the pinned date header at the top of the grid + let grid = rect(&h, "grid:scroll").expect("the grid"); + let (cell, id) = h + .app + .widgets + .iter() + .filter_map(|(w, r)| w.strip_prefix("thumb:").map(|id| (*r, id.parse::().unwrap()))) + .find(|(r, id)| !ids[..2].contains(id) && r.center().y > grid.top() + crate::panels::grid::HEADER_H && r.bottom() < grid.bottom()) + .expect("a photo below the header on screen"); + click(&mut h, cell.center(), json!({})); + assert_eq!(h.app.session.selection.ids, [lcc_catalog::PhotoId(id)], "the click selects that photo alone"); + assert_eq!(h.app.session.selection.active.map(|p| p.0), Some(id)); +} + +#[test] +fn a_click_on_a_date_header_keeps_its_behaviour() { + let mut h = library(); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + select(&mut h, &ids[..1], ids[0]); + let header = h.app.widgets.iter().find(|(w, _)| w.starts_with("group:")).map(|(w, r)| (w.clone(), *r)).expect("a date header on screen"); + click(&mut h, header.1.center(), json!({})); + // the first date group is the first photo of the list (its only photo here): the click selects it + let selected: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); + assert_eq!(selected, [ids[0]], "a click on the date header ({}) selects its group", header.0); +} + +/// Below the last row, in the strip the content adds under the photos: the scroll area's background +/// takes the click there too, and clears the selection. +#[test] +fn a_click_below_the_last_row_clears_the_selection() { + let mut h = library(); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + select(&mut h, &ids[..2], ids[0]); + // scroll to the bottom of the shoot, a notch at a time, with the pointer over the grid + let over = rect(&h, "grid:scroll").expect("the grid").center(); + let r = h.request("ui.move", json!({"x": over.x, "y": over.y}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..60 { + let r = h.request("ui.scroll", json!({"dy": -400.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + } + let grid = rect(&h, "grid:scroll").expect("the grid"); + let last_row = + h.app.widgets.iter().filter(|(w, r)| w.starts_with("thumb:") && r.intersects(grid)).map(|(_, r)| r.bottom()).fold(f32::MIN, f32::max); + let spot = pos2(grid.center().x, last_row + 4.0); + assert!(grid.contains(spot) && spot.y < grid.bottom(), "a spot below the last row is in the grid: {spot:?} in {grid:?}"); + click(&mut h, spot, json!({})); + assert!(h.app.session.selection.ids.is_empty(), "a click below the last row clears the selection"); +} + +#[test] +fn a_press_that_becomes_a_drag_on_empty_space_clears_nothing() { + let mut h = library(); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + select(&mut h, &ids[..2], ids[1]); + let before = h.app.session.selection.ids.clone(); + let spot = empty_spot(&h); + let r = h.request("ui.drag", json!({"x": spot.x, "y": spot.y, "toX": spot.x + 40.0, "toY": spot.y + 10.0, "steps": 8}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.session.selection.ids, before, "a drag from empty space leaves the selection"); +} diff --git a/crates/ui-egui/src/tests_import_tab.rs b/crates/ui-egui/src/tests_import_tab.rs index 2cfd6cc98c..2960850da0 100644 --- a/crates/ui-egui/src/tests_import_tab.rs +++ b/crates/ui-egui/src/tests_import_tab.rs @@ -910,3 +910,60 @@ fn export_from_a_browsed_photo_writes_a_file() { assert!(h.app.session.catalog.photos().all(|p| !p.in_library()), "nothing was imported"); let _ = std::fs::remove_dir_all(&dir); } + +/// Issue #1730: the Import tab defaults to taking Selected (so selecting photos enables the +/// Import button immediately without needing to flag them with P first), and hides the grid's +/// duplicate Local folder header (`Add N to My Photos`). +#[test] +fn default_take_is_selected_and_hides_duplicate_folder_header() { + let mut h = app([1400.0, 900.0], "classic"); + assert_eq!(h.app.ui.settings.import_tab.take(), crate::import_tab::Take::Selected); + let dir = folder("default-selected", 3); + exec(&mut h, "library.browse", json!({"path": dir.to_string_lossy()})); + assert_eq!(h.app.ui.tab, Tab::Import); + assert!(has_widget(&mut h, "importGo")); + assert!(!has_widget(&mut h, "grid:folderHeader"), "no duplicate grid folder header in Import tab"); + assert!(!has_widget(&mut h, "button:addToLibrary"), "no competing Add to My Photos button in Import tab"); + + let ids = h.app.session.visible_cloned(); + assert_eq!(ids.len(), 3); + exec(&mut h, "library.select", json!({"ids": [ids[1].0]})); + assert_eq!(h.request("ui.clickWidget", json!({"id": "importGo"}), T)["ok"], true); + h.step_until(SETTLE, |h| h.app.import.is_none()); + assert_eq!(h.app.ui.tab, Tab::Library); + assert!(!h.app.session.catalog.photo(ids[1]).unwrap().local, "selected photo was imported"); + assert!(h.app.session.catalog.photo(ids[0]).unwrap().local, "unselected photo stayed local"); + assert!(h.app.session.catalog.photo(ids[2]).unwrap().local, "unselected photo stayed local"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// When the active Take mode matches zero photos (e.g. Picks with 0 picks, or Selected with an +/// empty selection), the Import button stays disabled and `import.start` returns the reason, +/// while switching to a matching mode enables importing. +#[test] +fn empty_take_disables_import_button_until_matching_mode_selected() { + let mut h = app([1400.0, 900.0], "classic"); + let dir = folder("empty-take", 2); + exec(&mut h, "library.browse", json!({"path": dir.to_string_lossy()})); + + exec(&mut h, "import.configure", json!({"take": "picks", "previews": "none"})); + let r = try_exec(&mut h, "import.start", json!({})); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap_or("").contains("picks"), "{r}"); + assert_eq!(h.request("ui.clickWidget", json!({"id": "importGo"}), T)["ok"], true); + h.settle(SETTLE); + assert_eq!(h.app.ui.tab, Tab::Import, "disabled Import button did not start an import"); + + exec(&mut h, "import.configure", json!({"take": "selected"})); + exec(&mut h, "library.select", json!({"ids": []})); + let r = try_exec(&mut h, "import.start", json!({})); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap_or("").contains("selected"), "{r}"); + + exec(&mut h, "import.configure", json!({"take": "all"})); + let r = exec(&mut h, "import.start", json!({})); + assert_eq!(r["importing"], 2, "{r}"); + h.step_until(SETTLE, |h| h.app.import.is_none()); + assert_eq!(h.app.session.catalog.photos().filter(|p| p.in_library()).count(), 2); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/tests_lrc_menus.rs b/crates/ui-egui/src/tests_lrc_menus.rs index 7bc850a975..874f04dcfe 100644 --- a/crates/ui-egui/src/tests_lrc_menus.rs +++ b/crates/ui-egui/src/tests_lrc_menus.rs @@ -202,13 +202,14 @@ fn classic_keys_reach_classic_commands() { let mut h = headless(); key(&mut h, "E", json!({"cmd": true, "shift": true})); assert!(h.app.ui.module == ModuleId::Export || h.app.ui.dialog.is_some(), "⇧⌘E opens Export"); - // ⌘D: Select None (the photo on screen stays the active one) + // ⌘D: Select None (nothing stays selected, and no photo is active) let mut h = headless(); let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); h.app.run("library.select", json!({"ids": ids, "active": ids[0]})).unwrap(); assert_eq!(h.app.session.selection.ids.len(), 3); key(&mut h, "D", json!({"cmd": true})); - assert_eq!(h.app.session.selection.ids.len(), 1, "⌘D selects none but the active photo"); + assert!(h.app.session.selection.ids.is_empty(), "⌘D selects none"); + assert_eq!(h.app.session.active(), None, "⌘D leaves no active photo"); } // ---- Library / Edit / View / File items that used to be "Coming soon" diff --git a/crates/ui-egui/src/tests_print.rs b/crates/ui-egui/src/tests_print.rs index 4c8ac6ae80..5a2a761a41 100644 --- a/crates/ui-egui/src/tests_print.rs +++ b/crates/ui-egui/src/tests_print.rs @@ -569,3 +569,18 @@ fn print_module_follows_the_filmstrip_selection() { cmd(&mut h, "library.select", json!({"ids": []})); assert!(crate::print_ui::job_photos(&mut h.app, false).len() >= ids.len()); } + +// upstream #4484: the contact sheet's Paper box shows the label (A4 / Letter), not the stored id +#[test] +fn contact_sheet_paper_box_shows_the_label() { + let mut h = demo(Services::default()); + h.app.ui.language = crate::i18n::Locale::En; + for (paper, label) in [("a4", "A4"), ("letter", "Letter")] { + let options = lcc_engine::contact_sheet::Options { paper: paper.into(), ..Default::default() }; + h.app.ui.dialog = Some(Dialog::ContactSheet { options }); + h.settle(T); + let text = h.painted_text(); + assert!(text.iter().any(|t| t == label), "{paper} not shown as {label}"); + assert!(!text.iter().any(|t| t == paper), "{paper} shown raw"); + } +} diff --git a/crates/ui-egui/src/tests_sync.rs b/crates/ui-egui/src/tests_sync.rs index 8182616388..4236dde8dc 100644 --- a/crates/ui-egui/src/tests_sync.rs +++ b/crates/ui-egui/src/tests_sync.rs @@ -492,7 +492,9 @@ fn the_folders_scan_shows_a_row_and_its_cross_closes_the_dialog() { let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let g = gate.clone(); h.app.session.media.file_probe = Some(std::sync::Arc::new(move |_: &str| { - while !g.load(std::sync::atomic::Ordering::Relaxed) { + // bounded, so a test that fails before opening the gate doesn't leave the scan spinning + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !g.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < end { std::thread::sleep(Duration::from_millis(5)); } Ok(lcc_engine::media::ProbeInfo { format: "PNG".into(), ..Default::default() }) diff --git a/crates/ui-egui/src/tests_upright_panel.rs b/crates/ui-egui/src/tests_upright_panel.rs index 7e1d42bb15..9e24aa92c1 100644 --- a/crates/ui-egui/src/tests_upright_panel.rs +++ b/crates/ui-egui/src/tests_upright_panel.rs @@ -1,12 +1,15 @@ //! Headless tests of Upright's controls in the Transform section (issue #1274): the Guided Upright //! tool has its own icon, the redundant "Upright" heading is gone and the active mode is named //! instead, and switching modes never moves the mode buttons (what read as "Upright" flashing). +//! Issue #1684: the tool armed there draws over the Edit panel at once, and the six modes sit in a +//! grid with one even gap. use std::time::Duration; use serde_json::json; use crate::headless::Headless; +use crate::state::RightPanel; use crate::{LccApp, Services}; const T: Duration = Duration::from_secs(20); @@ -71,3 +74,181 @@ fn switching_modes_never_moves_the_mode_buttons() { assert!((now.top() - before.top()).abs() < 0.5, "after {mode} the modes moved: {before:?} → {now:?}"); } } + +/// Develop with the Edit panel's Transform section open and in view (a tall window: the section sits +/// under the closed ones): the panel the Guided Upright tool is armed from (issue #1684). +fn transform_section() -> Headless { + let app = LccApp::new(lcc_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1280.0, 1900.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.right = RightPanel::Edit; + h.app.ui.open_sections = vec!["geometry".to_string()]; + h.settle(SETTLE); + assert!(rect(&h, "icon:uprightGuidedTool").is_some(), "Transform's Upright row is on screen"); + h +} + +fn guides_len(h: &Headless) -> usize { + let id = h.app.session.active().expect("a photo"); + h.app.session.catalog.photo(id).expect("the photo").develop.geometry.guides.len() +} + +/// A drag on the photo from `(x0, y0)` to `(x1, y1)`, each a share of the way across it. +fn drag_photo(h: &mut Headless, from: (f64, f64), to: (f64, f64)) { + let ((x0, y0), (x1, y1)) = (from, to); + let r = h.request( + "ui.pointer", + json!({"events": [{"kind": "down", "x": x0, "y": y0}, {"kind": "drag", "x": x1, "y": y1}, {"kind": "up", "x": x1, "y": y1}]}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); +} + +/// The tool's path from the Transform section, for each of the two controls that arm it: the +/// guides draw over the Edit panel at once (no Crop & Straighten first), Delete removes the selected +/// guide and never asks about the photo, and Esc puts the tool down, leaving Transform where it is. +fn guides_draw_from_the_transform_section(h: &mut Headless, arm: &str) { + let id = h.app.session.active().expect("a photo"); + let before = guides_len(h); + click(h, arm); + assert_eq!(upright(h), lcc_develop::Upright::Guided, "{arm} switches Upright to Guided"); + assert_eq!(h.app.ui.tool, "guidedUpright", "{arm} arms the tool"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "over the Edit panel: no Crop & Straighten needed"); + + // a drag along what should be a horizontal line draws a guide, and it is on screen + drag_photo(h, (0.3, 0.3), (0.7, 0.3)); + assert_eq!(guides_len(h), before + 1, "the drag on the photo drew a guide"); + let guide = rect(h, "uprightGuide:0").unwrap_or_else(|| panic!("the guide is drawn over the photo")); + assert_eq!(h.app.ui.right, RightPanel::Edit, "and the Transform section stays up"); + + // a click on the guide selects it; Delete removes that guide alone: no dialog, the photo stays + h.time += 1.0; + let r = h.request("ui.click", json!({"x": guide.center().x, "y": guide.center().y}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.ui.selected_guide, Some((id.0, 0)), "the guide is selected"); + let r = h.request("ui.key", json!({"key": "Delete"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(guides_len(h), before, "Delete removed the selected guide"); + assert!(h.app.ui.dialog.is_none(), "and asked nothing about deleting the photo"); + assert!(h.app.session.active().is_some(), "the photo is still there"); + + // Esc puts the tool down where it stands; a drag on the photo is the loupe's again + let r = h.request("ui.key", json!({"key": "Escape"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.tool.is_empty(), "Esc puts the tool down"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "leaving the Transform section up"); + drag_photo(h, (0.3, 0.6), (0.7, 0.6)); + assert_eq!(guides_len(h), before, "with the tool down, a drag draws nothing"); +} + +/// Issue #1684: the Guided icon and the Guided mode arm the tool where they are, and the guides +/// draw over the Edit panel; Done and a double-click on the photo put it down as in the Crop panel. +#[test] +fn the_guided_icon_and_the_guided_mode_draw_guides_over_the_transform_section() { + let mut h = transform_section(); + assert!(h.app.ui.tool.is_empty(), "nothing is armed to begin with"); + guides_draw_from_the_transform_section(&mut h, "icon:uprightGuidedTool"); + guides_draw_from_the_transform_section(&mut h, "button:upright-guided"); + + // Done (Return) puts the tool down too, without leaving the Transform section + click(&mut h, "icon:uprightGuidedTool"); + assert_eq!(h.app.ui.tool, "guidedUpright"); + let r = h.request("engine.execute", json!({"command": "tool.done"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.tool.is_empty(), "Done puts the tool down"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "without leaving the Transform section"); + assert_eq!(upright(&h), lcc_develop::Upright::Guided, "and keeps the mode"); + + // a double-click on the photo finishes the tool (issue #297), over the Edit panel too + click(&mut h, "button:upright-guided"); + assert_eq!(h.app.ui.tool, "guidedUpright"); + // (not a triple-click with the click on the mode before) + h.time += 1.0; + let click = json!({"kind": "down", "x": 0.5, "y": 0.5}); + let up = json!({"kind": "up", "x": 0.5, "y": 0.5}); + let r = h.request("ui.pointer", json!({"events": [click, up, click, up]}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.tool.is_empty(), "the double-click puts the tool down"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "and stays over the Edit panel"); +} + +/// A tool armed in the Transform section ends when that section is folded: nothing stays armed +/// over the photo that the user cannot see or click. +#[test] +fn folding_transform_puts_an_armed_guided_tool_down() { + let mut h = transform_section(); + click(&mut h, "button:upright-guided"); + assert_eq!(h.app.ui.tool, "guidedUpright"); + let r = h.request("engine.execute", json!({"command": "section.geometry"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(rect(&h, "icon:uprightGuidedTool").is_none(), "the section is folded"); + drag_photo(&mut h, (0.3, 0.5), (0.7, 0.5)); + assert!(h.app.ui.tool.is_empty(), "the tool went down with its section"); + assert_eq!(guides_len(&h), 0, "and the drag drew nothing"); +} + +/// Shift+T's route works beside it: the tool command opens Crop & Straighten with the tool up. +#[test] +fn the_tool_command_still_opens_crop_and_straighten() { + let mut h = transform_section(); + let r = h.request("engine.execute", json!({"command": "tool.guidedUpright"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.ui.right, RightPanel::Crop); + assert_eq!(h.app.ui.tool, "guidedUpright"); +} + +/// The six modes are a grid with one even gap: as much between two columns as between the two rows +/// (issue #1684; the rows used to touch while the columns were 4 apart), and the columns share the +/// width. +#[test] +fn the_mode_grid_has_one_even_gap() { + let h = transform_section(); + let g = |k: &str| rect(&h, &format!("button:upright-{k}")).unwrap_or_else(|| panic!("{k} is on screen")); + let (off, auto, guided, level, vertical, full) = (g("off"), g("auto"), g("guided"), g("level"), g("vertical"), g("full")); + let even = |a: f32, b: f32, what: &str| assert!((a - b).abs() < 0.5, "{what}: {a} vs {b}"); + let (col, row) = (auto.left() - off.right(), level.top() - off.bottom()); + even(col, row, "the gap between columns and the gap between the rows"); + even(guided.left() - auto.right(), col, "the first and second gaps between columns"); + even(vertical.top() - auto.bottom(), row, "the gap under each column"); + even(level.top(), vertical.top(), "the second row's top"); + for (a, b) in [(&off, &auto), (&auto, &guided), (&level, &vertical), (&vertical, &full)] { + even(a.width(), b.width(), "the columns share the width"); + } + even(off.height(), level.height(), "the rows are one height"); +} + +/// The Modern layout's Optics ▸ Transform card arms the tool the same way, and putting the card +/// away puts the tool down with it. +#[test] +fn the_modern_transform_card_draws_guides_too() { + let mut h = transform_section(); + for (method, params) in [ + ("engine.execute", json!({"command": "view.modernLayout", "params": {"on": true}})), + ("ui.clickWidget", json!({"id": "modern:group:optics"})), + ("ui.clickWidget", json!({"id": "modern:more:geometry"})), + ] { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{method}: {r}"); + h.settle(SETTLE); + } + click(&mut h, "icon:uprightGuidedTool"); + assert_eq!(h.app.ui.tool, "guidedUpright"); + drag_photo(&mut h, (0.3, 0.3), (0.7, 0.3)); + assert_eq!(guides_len(&h), 1, "the drag over the Modern layout drew a guide"); + + // back to the group's sliders: the card with the tool's icon is gone, and the tool with it + let r = h.request("ui.clickWidget", json!({"id": "modern:moreBack"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(rect(&h, "icon:uprightGuidedTool").is_none(), "the card is gone"); + assert!(h.app.ui.tool.is_empty(), "and the tool went down with it"); +} diff --git a/crates/ui-egui/src/tests_zoom_keys.rs b/crates/ui-egui/src/tests_zoom_keys.rs index 4626abf599..8ccf3d8ae1 100644 --- a/crates/ui-egui/src/tests_zoom_keys.rs +++ b/crates/ui-egui/src/tests_zoom_keys.rs @@ -113,7 +113,8 @@ fn press(h: &mut Headless, k: &str, shift: bool, cmd: bool) { #[test] fn equals_and_minus_step_the_grid_thumbnail_size_and_clamp() { use crate::state::{THUMB_SIZE_MAX, THUMB_SIZE_MIN, THUMB_SIZE_STEP, ViewMode}; - for view in [ViewMode::PhotoGrid, ViewMode::People] { + // People steps by the slider's 30 px; the grids step by column or rearrangement (the tests below) + for view in [ViewMode::People] { let mut h = grid_view(view); h.app.ui.thumb_size = 220.0; press(&mut h, "=", false, false); @@ -146,10 +147,123 @@ fn equals_and_minus_step_the_grid_thumbnail_size_and_clamp() { } } +#[test] +fn cmd_equals_in_a_grid_opens_the_active_photo_at_fit() { + use crate::state::{ViewMode, Zoom}; + for view in [ViewMode::PhotoGrid, ViewMode::SquareGrid] { + let mut h = grid_view(view); + h.app.ui.module = crate::module::ModuleId::Library; + let active = h.app.session.active(); + assert!(active.is_some(), "{view:?}: the demo session has no active photo"); + h.app.ui.zoom = Zoom::Percent(100.0); + key(&mut h, "="); + assert_eq!(h.app.ui.view, ViewMode::Detail, "{view:?}: Cmd+= did not open the loupe"); + assert_eq!(h.app.ui.zoom, Zoom::Fit, "{view:?}: the loupe did not open at Fit"); + assert_eq!(h.app.session.active(), active, "{view:?}: Cmd+= changed the active photo"); + } + // View ▸ Zoom In does the same as its key + let mut h = grid_view(ViewMode::PhotoGrid); + h.app.ui.module = crate::module::ModuleId::Library; + let r = h.request("ui.menu.invoke", json!({"id": "view.zoomIn"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(h.app.ui.view, ViewMode::Detail, "View ▸ Zoom In did not open the loupe"); + assert_eq!(h.app.ui.zoom, Zoom::Fit); +} + +#[test] +fn cmd_equals_in_a_grid_without_an_active_photo_steps_the_zoom_silently() { + use crate::state::{ViewMode, Zoom}; + let mut h = grid_view(ViewMode::PhotoGrid); + h.app.session.selection.active = None; + h.app.ui.zoom = Zoom::Fit; + let r = h.request("ui.menu.invoke", json!({"id": "view.zoomIn"}), T); + assert_eq!(r["ok"], true, "no active photo: {r}"); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid, "no active photo: Cmd+= left the grid"); + assert_eq!(h.app.ui.zoom, Zoom::Percent(100.0 / 3.0), "no active photo: Cmd+= did not step the zoom"); +} + +#[test] +fn cmd_minus_in_a_grid_changes_nothing() { + use crate::state::{ViewMode, Zoom}; + for view in [ViewMode::PhotoGrid, ViewMode::SquareGrid] { + let mut h = grid_view(view); + h.app.ui.module = crate::module::ModuleId::Library; + let active = h.app.session.active(); + h.app.ui.zoom = Zoom::Percent(100.0); + key(&mut h, "-"); + assert_eq!(h.app.ui.view, view, "{view:?}: Cmd+- changed the view"); + assert_eq!(h.app.ui.zoom, Zoom::Percent(100.0), "{view:?}: Cmd+- changed the zoom"); + assert_eq!(h.app.session.active(), active, "{view:?}: Cmd+- changed the active photo"); + let r = h.request("ui.menu.invoke", json!({"id": "view.zoomOut"}), T); + assert_eq!(r["ok"], true, "{view:?}: View ▸ Zoom Out reported a message: {r}"); + assert_eq!(h.app.ui.view, view, "{view:?}: View ▸ Zoom Out changed the view"); + } +} + +/// A grid with the loupe open on its active photo, entered as View ▸ Loupe does (`view.loupe`). +fn loupe_from(view: crate::state::ViewMode) -> Headless { + let mut h = grid_view(view); + h.app.run("view.loupe", json!({})).unwrap(); + h.step(); + h.step(); + h +} + +#[test] +fn cmd_equals_and_minus_in_the_loupe_still_zoom_the_photo() { + use crate::state::{ViewMode, Zoom}; + let mut h = loupe_from(ViewMode::PhotoGrid); + assert_eq!(h.app.ui.module, crate::module::ModuleId::Library); + h.app.ui.zoom = Zoom::Fit; + key(&mut h, "="); + assert_eq!(h.app.ui.zoom, Zoom::Percent(100.0 / 3.0), "{:?}", h.app.ui.zoom); + assert_eq!(h.app.ui.view, ViewMode::Detail, "Cmd+= left the loupe"); + key(&mut h, "-"); + assert_eq!(h.app.ui.zoom, Zoom::Percent(25.0), "{:?}", h.app.ui.zoom); + assert_eq!(h.app.ui.view, ViewMode::Detail, "Cmd+- left the loupe"); +} + +#[test] +fn plus_and_minus_in_the_loupe_switch_to_the_last_grid_and_resize_it() { + use crate::state::ViewMode; + for grid in [ViewMode::PhotoGrid, ViewMode::SquareGrid] { + let mut h = loupe_from(grid); + // the grid last shown is the one the loupe came from (View ▸ Grid sets it; a loupe entered from a grid keeps it) + h.app.ui.grid_style = grid; + h.app.ui.thumb_size = 220.0; + press(&mut h, "Plus", false, false); + assert_eq!(h.app.ui.view, grid, "{grid:?}: + did not switch to the grid"); + let larger = h.app.ui.thumb_size; + assert!(larger > 220.0, "{grid:?}: + did not enlarge the grid ({larger} px)"); + h.app.run("view.loupe", json!({})).unwrap(); + press(&mut h, "-", false, false); + assert_eq!(h.app.ui.view, grid, "{grid:?}: - did not switch to the grid"); + let smaller = h.app.ui.thumb_size; + assert!(smaller < larger, "{grid:?}: - did not shrink the grid ({smaller} px after {larger} px)"); + // the plain = is the same increase key as Plus (Classic's Library key) + h.app.run("view.loupe", json!({})).unwrap(); + press(&mut h, "=", false, false); + assert_eq!(h.app.ui.view, grid, "{grid:?}: = did not switch to the grid"); + assert!(h.app.ui.thumb_size > smaller, "{grid:?}: = did not enlarge the grid ({} px)", h.app.ui.thumb_size); + } +} + +#[test] +fn plus_and_minus_in_the_develop_loupe_do_nothing() { + use crate::state::ViewMode; + let mut h = grid_view(ViewMode::Detail); + h.app.ui.module = crate::module::ModuleId::Develop; + h.app.ui.thumb_size = 220.0; + press(&mut h, "Plus", false, false); + press(&mut h, "-", false, false); + assert_eq!(h.app.ui.view, ViewMode::Detail, "a size key left the Develop loupe"); + assert_eq!(h.app.ui.thumb_size, 220.0, "a size key resized the grid from Develop"); +} + #[test] fn thumbnail_size_keys_do_nothing_outside_the_grids() { use crate::state::ViewMode; - for view in [ViewMode::Detail, ViewMode::Survey] { + for view in [ViewMode::Survey, ViewMode::Compare, ViewMode::Reference] { let mut h = grid_view(view); h.app.ui.thumb_size = 220.0; let zoom = h.app.ui.zoom; @@ -187,7 +301,7 @@ fn search_field_keeps_equals_and_minus() { #[test] fn thumbnail_size_commands_persist_and_ui_set_clamps_like_a_settings_file() { - let mut h = grid_view(crate::state::ViewMode::SquareGrid); + let mut h = grid_view(crate::state::ViewMode::People); h.app.ui.thumb_size = 120.0; let r = h.request("ui.menu.invoke", json!({"id": "view.thumbSizeUp"}), T); assert_eq!(r["ok"], true, "{r}"); @@ -218,3 +332,181 @@ fn thumbnail_size_commands_persist_and_ui_set_clamps_like_a_settings_file() { assert_eq!(r["ok"], true, "{r}"); assert_eq!(h.app.ui.settings.preview_limit, 0); } + +#[test] +fn square_grid_keys_take_or_add_one_column_per_press_up_to_the_limits() { + use crate::state::{THUMB_SIZE_MAX, THUMB_SIZE_MIN, ViewMode}; + let mut h = grid_view(ViewMode::SquareGrid); + h.app.ui.thumb_size = THUMB_SIZE_MIN; + h.step(); + h.step(); + let avail = h.app.caches.grid.step.as_ref().map_or(0.0, |s| s.avail_w); + assert!(avail > 0.0, "the square grid drew its width"); + // the columns the grid really lays out at a size: the photos in its fullest row + let cols_at = |h: &Headless, size: f32| { + let layout = crate::panels::grid::layout_with_footer(h.app.caches.grid.shapes(), &[], avail, size, true, 0.0); + layout.rows.iter().map(|r| r.end - r.start).max().unwrap_or(0) + }; + let cols = |h: &Headless| cols_at(h, h.app.ui.thumb_size); + let mut c = cols(&h); + while c > 1 { + let before = h.app.ui.thumb_size; + press(&mut h, "=", false, false); + if h.app.ui.thumb_size == before { + // the limit: even the largest size gives no column fewer + assert_eq!(cols_at(&h, THUMB_SIZE_MAX), c, "{before} px: a column fewer is within the limit"); + break; + } + assert_eq!(cols(&h), c - 1, "= at {before} px takes one column away"); + c = cols(&h); + } + while h.app.ui.thumb_size > THUMB_SIZE_MIN { + let before = h.app.ui.thumb_size; + press(&mut h, "-", false, false); + if h.app.ui.thumb_size == before { + assert_eq!(cols_at(&h, THUMB_SIZE_MIN), c, "{before} px: a column more is within the limit"); + break; + } + assert_eq!(cols(&h), c + 1, "- at {before} px adds one column"); + c = cols(&h); + } +} + +fn full_rows(h: &Headless, size: f32) -> Vec { + crate::panels::grid::rows_at(&h.app, size).expect("the photo grid drew its rows") +} + +#[test] +fn photo_grid_key_lands_on_the_next_size_where_a_full_row_changes() { + use crate::state::ViewMode; + let mut h = grid_view(ViewMode::PhotoGrid); + h.app.ui.thumb_size = 220.0; + h.step(); + h.step(); + let old = h.app.ui.thumb_size; + let before = crate::panels::grid::rows_at(&h.app, old).expect("the photo grid drew its rows"); + press(&mut h, "=", false, false); + let new = h.app.ui.thumb_size; + assert!(new > old, "= makes the grid bigger"); + let after = crate::panels::grid::rows_at(&h.app, new).expect("the photo grid drew its rows"); + assert!(after != before, "the new size changes a full row"); + for t in (old as i32 + 1)..(new as i32) { + let rows = crate::panels::grid::rows_at(&h.app, t as f32).expect("the photo grid drew its rows"); + assert!(rows == before, "{t} px is inside the step"); + } +} + +#[test] +fn photo_grid_keys_stop_where_only_the_last_row_would_still_grow() { + use crate::state::{THUMB_SIZE_MAX, THUMB_SIZE_MIN, ViewMode}; + let mut h = grid_view(ViewMode::PhotoGrid); + h.app.ui.thumb_size = 220.0; + h.step(); + h.step(); + for _ in 0..400 { + let before = h.app.ui.thumb_size; + press(&mut h, "=", false, false); + if h.app.ui.thumb_size == before { + break; + } + } + let stop = h.app.ui.thumb_size; + // the cut-off: the smallest size from which the full rows stay as they are up to the largest size + let top = full_rows(&h, THUMB_SIZE_MAX); + let mut cut = THUMB_SIZE_MAX as i32; + while cut > THUMB_SIZE_MIN as i32 && full_rows(&h, (cut - 1) as f32) == top { + cut -= 1; + } + assert_eq!(stop, cut as f32, "the grid stopped at {stop} px; its full rows stop changing at {cut} px"); + // the slider's top is the same size, so the slider and the keys agree + assert_eq!(crate::panels::grid::thumb_max(&h.app), stop, "the slider goes past where the keys stop"); + // the opposite key works at once from the stop + let before = h.app.ui.thumb_size; + press(&mut h, "-", false, false); + assert!(h.app.ui.thumb_size < before, "- at the stop ({before} px) shrinks the grid at once"); +} + +/// Photo Grid layouts of `n` photos with varied shapes, as the key step sees them. +fn synthetic_rows(n: usize, width: f32, seed: u64) -> impl Fn(f32) -> Option> { + let mut x = seed; + let aspects: Vec = (0..n) + .map(|_| { + x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + 0.5 + ((x >> 33) % 1000) as f32 / 1000.0 * 1.5 + }) + .collect(); + let runs: Vec<(usize, usize)> = (0..n).step_by(40).map(|s| (s, 40.min(n - s))).collect(); + move |size| { + let layout = crate::panels::grid::layout_with_footer(&aspects, &runs, width, size, false, 0.0); + Some(crate::panels::grid::row_geoms(&layout, &runs)) + } +} + +#[test] +fn the_photo_grid_step_search_finds_the_same_size_as_trying_each_pixel() { + use crate::state::{THUMB_SIZE_MAX, THUMB_SIZE_MIN}; + for seed in 0..6u64 { + for (width, n) in [(700.0, 60), (1180.0, 200), (1900.0, 900)] { + let rows = synthetic_rows(n, width, seed); + for start in (THUMB_SIZE_MIN as i32..=THUMB_SIZE_MAX as i32).step_by(23) { + let current = start as f32; + for up in [true, false] { + let here = rows(current).expect("rows"); + let sign = if up { 1.0 } else { -1.0 }; + let mut want = None; + let mut size = current + sign; + while (THUMB_SIZE_MIN..=THUMB_SIZE_MAX).contains(&size) { + if here != rows(size).expect("rows") { + want = Some(size); + break; + } + size += sign; + } + let got = crate::panels::grid::photo_step(&rows, current, THUMB_SIZE_MIN, THUMB_SIZE_MAX, up); + assert_eq!(got, want, "seed {seed}, {n} photos, {width} wide, from {current} px, up={up}"); + } + } + } + } +} + +#[test] +fn the_photo_grid_step_search_on_a_large_library_takes_a_few_layouts() { + use crate::state::{THUMB_SIZE_MAX, THUMB_SIZE_MIN}; + let rows = synthetic_rows(200_000, 1500.0, 7); + let calls = std::cell::Cell::new(0u32); + let counted = |s: f32| { + calls.set(calls.get() + 1); + rows(s) + }; + let t = std::time::Instant::now(); + let _ = crate::panels::grid::photo_step(counted, THUMB_SIZE_MIN, THUMB_SIZE_MIN, THUMB_SIZE_MAX, true); + eprintln!("200k photos: one press = {} layouts, {:?}", calls.get(), t.elapsed()); + assert!(calls.get() <= 12, "a press lays the grid out {} times", calls.get()); +} + +#[test] +fn a_photo_grid_row_that_ends_a_group_and_only_grows_is_not_a_step() { + use crate::panels::grid::{layout_with_footer, photo_step, row_geoms}; + // two groups of three square photos in 1000 px: each group is one row, shorter than the width asks for, so it + // keeps the target height and grows with it (and moves the second group down); nothing else changes + let aspects = [1.0f32; 6]; + let groups = [(0, 3), (3, 3)]; + let rows = |size: f32| Some(row_geoms(&layout_with_footer(&aspects, &groups, 1000.0, size, false, 0.0), &groups)); + assert_eq!(photo_step(rows, 150.0, 90.0, 300.0, true), None, "growing group-end rows are steps"); + assert_eq!(photo_step(rows, 300.0, 90.0, 300.0, false), None, "growing group-end rows are steps going down"); + // a break that really moves is a step: three photos stop fitting one row once each would be under 329 px + let wide = [(0, 6)]; + let rows = |size: f32| Some(row_geoms(&layout_with_footer(&aspects, &wide, 1000.0, size, false, 0.0), &wide)); + assert!(photo_step(rows, 150.0, 90.0, 480.0, true).is_some(), "the row that splits is a step"); +} + +#[test] +fn a_group_running_past_the_last_photo_still_ends_on_its_last_row() { + use crate::panels::grid::{layout_with_footer, photo_step, row_geoms}; + // the layout stops a group at the last photo; the rows must be read the same way + let aspects = [1.0f32; 6]; + let groups = [(0, 3), (3, 50)]; + let rows = |size: f32| Some(row_geoms(&layout_with_footer(&aspects, &groups, 1000.0, size, false, 0.0), &groups)); + assert_eq!(photo_step(rows, 150.0, 90.0, 300.0, true), None, "a growing group-end row is no step"); +} diff --git a/crates/ui-egui/src/web_module.rs b/crates/ui-egui/src/web_module.rs index 915ebdc976..e365fc6d71 100644 --- a/crates/ui-egui/src/web_module.rs +++ b/crates/ui-egui/src/web_module.rs @@ -9,6 +9,7 @@ //! Export, upload and Share via Immich run on a worker thread ([`run`]: `webui.*`). use crate::json_ext::JsonExt as _; +use crate::popup_typeahead::PopupItems; use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2}; use lcc_webgallery::Server; use lcc_webgallery::{GallerySettings, MetadataMode, Template}; @@ -384,8 +385,8 @@ fn settings_column(ui: &mut egui::Ui, app: &mut LccApp, st: &mut WebUi) { ui.add(egui::Slider::new(&mut s.output.quality, 1..=100).text(crate::i18n::tr("Quality"))); ui.horizontal(|ui| { ui.label(crate::i18n::tr("Metadata")); - ui.selectable_value(&mut s.output.metadata, MetadataMode::All, crate::i18n::tr("All")); - ui.selectable_value(&mut s.output.metadata, MetadataMode::CopyrightOnly, crate::i18n::tr("Copyright only")); + ui.pick_value(&mut s.output.metadata, MetadataMode::All, crate::i18n::tr("All")); + ui.pick_value(&mut s.output.metadata, MetadataMode::CopyrightOnly, crate::i18n::tr("Copyright only")); }); field(ui, "watermark", "Watermark text", &mut s.output.watermark); ui.checkbox(&mut s.output.sharpen, crate::i18n::tr("Sharpen for screen")); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 67254fd4bf..d6891839af 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1699,8 +1699,9 @@ pub fn shared_width(room: f32, n: usize, gap: f32) -> f32 { ((room - gap * (n - 1.0)) / n).floor().max(0.0) } -/// A segmented control: `labels` share the available width equally, `per_row` per row. Each segment is -/// addressable as `button:{id}-{key}` (keys parallel to labels). Returns the clicked index. +/// A segmented control: `labels` share the available width equally, `per_row` per row, the rows `gap` +/// apart as the segments in a row are (one even gap over a grid of several rows, issue #1684). Each +/// segment is addressable as `button:{id}-{key}` (keys parallel to labels). Returns the clicked index. pub fn segmented(ui: &mut Ui, id: &str, items: &[(&str, &str)], active: Option, per_row: usize) -> Option { let t = Tokens::get(ui.ctx()); let finger = crate::dialog_frame::finger_sized(ui); @@ -1713,7 +1714,12 @@ pub fn segmented(ui: &mut Ui, id: &str, items: &[(&str, &str)], active: Option---…`): the MSI on Windows, the DMG on macOS, the AppImage on Linux + (`chromaforge---…`): the MSI on Windows, the DMG on macOS, the AppImage on Linux x86_64/aarch64, and a tarball (or the portable zip) as a manual install anywhere else. An installer always wins over an archive; the `SHA256SUMS.txt` asset is never installed. - **Signed checksums** (`signature`). Before a download starts, the release's `SHA256SUMS.txt` and @@ -48,7 +48,7 @@ if let Some(update) = lcc_updater::check(&opts, None, None)? { version as a whole `---` token (`signature::names_version`: an older release's signed list and file served under a newer tag) stops the update (`UpdateError::Signature`) and deletes whatever was staged under that name. Keys are made and releases signed with - `cargo xtask update-key` (docs/releasing.md → Update signing key). + `cargo xtask update-key` (docs/release-process.md → Update signing key). - **Downloads** resume from a `.part` file, are capped, and must match the size the feed states and the SHA-256 the signed list records before they are renamed into place. A file that fails its check is deleted. A file already there is re-hashed, not trusted by name; a hostile asset name (`../../…`) @@ -121,7 +121,7 @@ UPDATER_TEST_DMG="$(ls "$S"/b/*.dmg)" UPDATER_TEST_BUNDLE="$S/old/$APP" \ The ignored test refuses to run unless `$S/cfg/updates.json` turns the start-up check off. It then installs, and starts the new bundle on the scratch settings and library: unlike the app's own relaunch (a plain `open -n` of the bundle once the app has quit), it passes them with -`open --env _CONFIG_DIR=… --args --library …`, because an app started by `open` doesn't +`open --env CHROMAFORGE_CONFIG_DIR=… --args --library …`, because an app started by `open` doesn't inherit the shell's environment. Afterwards the scratch bundle's `Info.plist` names `$V`, no `.partial` or `.old` is left beside diff --git a/crates/updater/src/target.rs b/crates/updater/src/target.rs index 8531c33dbc..61693ee570 100644 --- a/crates/updater/src/target.rs +++ b/crates/updater/src/target.rs @@ -1,7 +1,7 @@ //! Which release artifact belongs to this machine. //! //! The release pipeline names every artifact `---[-portable]` -//! (see `docs/releasing.md` and `packaging/`). This module turns the running platform into that +//! (see `docs/release-process.md` and `packaging/`). This module turns the running platform into that //! shape and classifies the assets a release offers, so the update check can pick the one file //! that applies — and say so in words first ([`Target::describe`]). diff --git a/crates/video-export/Cargo.toml b/crates/video-export/Cargo.toml index 1b7e4155d7..ac8b433a32 100644 --- a/crates/video-export/Cargo.toml +++ b/crates/video-export/Cargo.toml @@ -12,15 +12,15 @@ workspace = true lcc-brand = { workspace = true } lcc-raster = { workspace = true } lcc-video = { workspace = true } -filmcraft-color = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-aac = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-prores = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-color = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-aac = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-prores = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } thiserror = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] -filmcraft-matroska = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-matroska = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } lcc-testkit = { workspace = true } # Never `filmcraft-codecs` / `-media` / `-export`: they pull symphonia (MPL-2.0). diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index df5c42ed62..33e0cf2cc6 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -18,36 +18,36 @@ thiserror = { workspace = true } # std-only, MIT OR Apache-2.0, no unsafe). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] chrono = { workspace = true, features = ["clock"] } -filmcraft-color = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-frame = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-time = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-h264 = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-hevc = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-bitstream = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-matroska = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-mpegts = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-mxf = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-vp9 = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-av1 = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-prores = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-mpeg2v = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-apv = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-dnx = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-color = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-frame = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-time = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-isobmff = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-h264 = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-hevc = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-bitstream = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-matroska = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-mpegts = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-mxf = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-vp9 = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-av1 = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-prores = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-mpeg2v = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-apv = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-dnx = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } # audio (std-only, MIT OR Apache-2.0; puremp3 is MIT OR CC0-1.0, no unsafe) -filmcraft-aac = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-opus = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } -filmcraft-ac3 = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-aac = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-opus = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } +filmcraft-ac3 = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } puremp3 = "0.1" # Dev-only `test_util::write_clip` (synthetic H.264 MP4s for other crates' tests); never on in a product build. -filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4", optional = true } +filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c", optional = true } [features] test-util = ["dep:filmcraft-h264enc"] [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] -filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "3f0cb5f2a906087e5fdc1cd0bb685527da717ba4" } +filmcraft-h264enc = { git = "https://github.com/emmertex/filmcraft", rev = "4b82c5a1337dfad846a4a50e868c57ae4502f06c" } [dev-dependencies] lcc-testkit = { workspace = true } diff --git a/crates/video/src/source.rs b/crates/video/src/source.rs index 162b046677..1721592b89 100644 --- a/crates/video/src/source.rs +++ b/crates/video/src/source.rs @@ -33,7 +33,7 @@ impl FileSource { } } -/// Every FilmCraft demuxer has its own (identical) byte-source trait. +/// The FilmCraft demuxers' byte-source traits (Matroska shares the ISO-BMFF one). macro_rules! byte_source { ($($t:path),*) => {$( impl $t for FileSource { @@ -47,4 +47,4 @@ macro_rules! byte_source { )*}; } -byte_source!(filmcraft_isobmff::ByteSource, filmcraft_matroska::ByteSource, filmcraft_mpegts::ByteSource, filmcraft_mxf::ByteSource); +byte_source!(filmcraft_isobmff::ByteSource, filmcraft_mpegts::ByteSource, filmcraft_mxf::ByteSource); diff --git a/deny.toml b/deny.toml index c287b787cb..01970ffe28 100644 --- a/deny.toml +++ b/deny.toml @@ -1,19 +1,22 @@ # `cargo deny check licenses` (run by `cargo xtask ci` and the CI workflow): only licences the project accepts may # reach the build (licence policy in AGENTS.md, maintainer decisions 2026-11-05 and 2026-11-10): anything that allows # derivatives, redistribution and commercial use — permissive licences and GPL/LGPL/AGPL share-alike alike. MPL and -# CC BY-NC/ND ("non-commercial", "no derivatives") stay out. The workspace crates are MIT OR GPL-3.0-or-later; -# crates/segment and crates/fetch are Apache-2.0 OR GPL-3.0-or-later (all allowed below). +# CC BY-NC/ND ("non-commercial", "no derivatives") stay out. Project-only lcc-* crates are +# GPL-3.0-or-later; crates holding adopted code also carry the original option (all allowed below). [graph] all-features = true [licenses] version = 2 +# This is a policy allow-list, not a list of licences currently in the graph: a licence the project accepts stays +# listed when no dependency uses it (AGENTS.md, "Third-party sources"). Unused entries are therefore not warnings. +unused-allowed-license = "allow" # Everything not listed here is denied, GPL, LGPL, AGPL and MPL included. allow = [ "MIT", "MIT-0", - # Share-alike with commercial use (licence policy 2026-11-05; workspace crates dual-licensed 2026-11-10): + # Share-alike with commercial use (licence policy 2026-11-05; lcc crates GPL-only since 2026-11-30): "GPL-2.0-only", "GPL-2.0-or-later", "GPL-3.0-only", diff --git a/docs/ai-masks.md b/docs/ai-masks.md index 508dea791e..ea01cd1500 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -1,8 +1,5 @@ # AI masks (Object and Describe) -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - The app selects objects with **SAM 3** (Segment Anything with Concepts, Meta 2025), run in pure Rust by `crates/segment` on [candle](https://github.com/huggingface/candle): on the GPU through Metal on macOS, on the CPU elsewhere (for now). If the Mac's GPU can't run it, it runs on @@ -99,8 +96,8 @@ same blue as the sky (0.60–0.67). Real photos need a CC0 set with hand-made re `ZhengPeng7/BiRefNet_lite`) in pure Rust on candle. Like SAM 3 it is optional and downloaded only on request: `segment.subject.download {"acknowledged": true}` fetches `model.safetensors` (177,634,392 bytes, SHA-256 `4417d897…0815`, from the author's Hugging Face repository at a pinned -revision; `_BIREFNET_MIRRORS` adds mirrors) into `/models/birefnet` -(`_BIREFNET_DIR` overrides it); `segment.subject.status` reports it and puts a finished +revision; `CHROMAFORGE_BIREFNET_MIRRORS` adds mirrors) into `Chromaforge/models/birefnet` +(`CHROMAFORGE_BIREFNET_DIR` overrides it); `segment.subject.status` reports it and puts a finished download to use. The weights are never committed or shipped. Once installed, the engine registers it as the pipeline's subject model @@ -156,7 +153,7 @@ still open, and the analysis above runs. ### SAM 3 mirror -The mirror mechanism is finished in code: `_SAM3_MIRRORS`, the `sam3-mirrors.txt` +The mirror mechanism is finished in code: `CHROMAFORGE_SAM3_MIRRORS`, the `sam3-mirrors.txt` file, and the built-in `DEFAULT_MIRRORS`, with size + SHA-256 pinning of all three files (checked against the official checkpoint on 2026-10-13). What's missing isn't code but a host. Someone has to redistribute Meta's SAM Materials under the SAM License (with the licence @@ -176,12 +173,12 @@ path is unchanged) and its own multi-threaded CPU kernels (`sam2_kernels.rs`). I model with its size and licence and a Download button each; `ai.models.download {"id": "sam2", "acknowledged": true}` does the same. The files (`config.json`, `model.safetensors`, 156 MB) come from `facebook/sam2.1-hiera-tiny` on Hugging Face at a pinned commit, each checked against its size - and SHA-256, into `/models/sam2.1-hiera-tiny`. `_SAM2_MIRRORS` or + and SHA-256, into `Chromaforge/models/sam2.1-hiera-tiny`. `CHROMAFORGE_SAM2_MIRRORS` or `sam2.1-hiera-tiny-mirrors.txt` add mirrors. - **Which model clicks use:** `ai.models.setObjectModel {"model": "auto" | "sam3" | "sam2"}`, or the segmented control in the AI Models dialog. **Automatic** (the default) keeps SAM 3 when it is installed, as before, and otherwise uses SAM 2.1 when that is installed. The choice is saved in - `/models/ai-models.json`. **Describe** (text) always needs SAM 3. + `Chromaforge/models/ai-models.json`. **Describe** (text) always needs SAM 3. - With SAM 2.1 chosen and not installed, an Object mask fails with `ModelMissing(Sam2)` and the app opens the AI Models dialog. A damaged download is an error, not a crash. - **Depth Anything V2 Small** (Apache-2.0, `depth-anything/Depth-Anything-V2-Small-hf`, 99 MB) is in @@ -193,7 +190,7 @@ path is unchanged) and its own multi-threaded CPU kernels (`sam2_kernels.rs`). I BlazeFace full range, 1 MB, fetched with it from its own address) are Google's Apache-2.0 models from `storage.googleapis.com/mediapipe-models` / `mediapipe-assets`, pinned by size and SHA-256 (`lcc_tflite::models`) and run on the pure-Rust TFLite interpreter (`crates/tflite`, `lcc_segment::people`). The dialog offers both - (`ai.models.download {"id": "people" | "face"}`, mirrors via `_PEOPLE_MIRRORS` / `_FACE_MIRRORS`); they + (`ai.models.download {"id": "people" | "face"}`, mirrors via `CHROMAFORGE_PEOPLE_MIRRORS` / `CHROMAFORGE_FACE_MIRRORS`); they back Retouch (Smooth Skin, Find Blemishes) and Detect Faces ([faces.md](faces.md)). Without them those fail with `ModelMissing(People)` / `ModelMissing(FaceDetector)` and the app opens the AI Models dialog; nothing is downloaded without the person's go-ahead. @@ -202,7 +199,7 @@ path is unchanged) and its own multi-threaded CPU kernels (`sam2_kernels.rs`). I selections instead of the photo analysis. It is the person's choice: the AI Models dialog's "Sky, Landscape and People masks use" control, or `ai.models.setSceneModel {"model": "analysis" | "eomt"}` (saved in `ai-models.json`). The default stays the photo analysis; EoMT is used only once it is chosen - and installed (`ai.models.download {"id": "scene"}`, mirrors via `_SCENE_MIRRORS`). It runs + and installed (`ai.models.download {"id": "scene"}`, mirrors via `CHROMAFORGE_SCENE_MIRRORS`). It runs once per photo at 640 px, with an activity row; a failure falls back to the analysis. Embedded sky mattes (HEIC) still win over it. The model was trained on COCO, whose annotations are CC BY 4.0: the dialog and `NOTICE` credit it (maintainer decision 2026-11-03). Switching @@ -218,9 +215,9 @@ path is unchanged) and its own multi-threaded CPU kernels (`sam2_kernels.rs`). I Tests: `cargo test -p lcc-segment` (kernels against candle, preprocessing, the registry); `tests/sam2_reference.rs` compares against Hugging Face `transformers` stage by stage when -`_SAM2_DIR` and `_SAM2_REF` are set (skipped otherwise). `tests/scene_reference.rs` -runs the real EoMT weights (`_SCENE_DIR`): sky above a drawn meadow, and damaged copies of -the checkpoint as errors, not panics; with `_SCENE_REF` also the stage-by-stage comparison. +`CHROMAFORGE_SAM2_DIR` and `CHROMAFORGE_SAM2_REF` are set (skipped otherwise). `tests/scene_reference.rs` +runs the real EoMT weights (`CHROMAFORGE_SCENE_DIR`): sky above a drawn meadow, and damaged copies of +the checkpoint as errors, not panics; with `CHROMAFORGE_SCENE_REF` also the stage-by-stage comparison. ## Remote Metal inference @@ -230,17 +227,17 @@ as described below, then run: ```sh cargo build --release --locked -p lcc-segment --bin sam3-worker -export _SAM3_WORKER_TOKEN="$(openssl rand -hex 16)" # or any secret of 16+ characters -target/release/sam3-worker "$HOME/Library/Application Support//models/sam3" 127.0.0.1:8793 +export CHROMAFORGE_SAM3_WORKER_TOKEN="$(openssl rand -hex 16)" # or any secret of 16+ characters +target/release/sam3-worker "$HOME/Library/Application Support/Chromaforge/models/sam3" 127.0.0.1:8793 ``` -Without `_SAM3_WORKER_TOKEN` the worker makes up a token for the run and prints it. On the +Without `CHROMAFORGE_SAM3_WORKER_TOKEN` the worker makes up a token for the run and prints it. On the editing computer, start an SSH tunnel in one terminal and the app in another, with the same token: ```sh ssh -N -T -o ExitOnForwardFailure=yes -L 127.0.0.1:8793:127.0.0.1:8793 user@your-mac -_SAM3_WORKER_TOKEN= _SAM3_REMOTE=127.0.0.1:8793 +CHROMAFORGE_SAM3_WORKER_TOKEN= CHROMAFORGE_SAM3_REMOTE=127.0.0.1:8793 chromaforge ``` Object clicks, Describe prompts, and detail refinement use the remote worker. Only the @@ -260,7 +257,7 @@ the token as private as an SSH key; don't expose the worker through a public pro No local weights are required in remote mode. An unavailable worker produces an explicit error, not a silent CPU fallback. Restore the tunnel and retry. Unset -`_SAM3_REMOTE` to use the local model again. This offloads segmentation only, +`CHROMAFORGE_SAM3_REMOTE` to use the local model again. This offloads segmentation only, not RAW development, denoising, or upscaling. The model licence below still applies. ## Getting the model @@ -282,7 +279,7 @@ when complete and verified — `model.safetensors` must have the exact size and official checkpoint; a file that doesn't match is deleted, never used. If no location works, the dialog says why and the app carries on without the model. -Agents and scripts use the same commands (control channel, ` mcp --connect`): +Agents and scripts use the same commands (control channel, `chromaforge-cli mcp --connect`): `segment.model.status`, `segment.model.download {"acknowledged": true}` (refused without the explicit `acknowledged`: pass it only after the user agreed to the download and the licence), `segment.model.cancel`. @@ -292,14 +289,14 @@ explicit `acknowledged`: pass it only after the user agreed to the download and The model is fetched from an ordered list of mirrors: base URLs where `/model.safetensors`, `/vocab.json` and `/merges.txt` live. The list is, in order: -1. `_SAM3_MIRRORS` (environment variable; URLs separated by commas or spaces); +1. `CHROMAFORGE_SAM3_MIRRORS` (environment variable; URLs separated by commas or spaces); 2. the file `models/sam3-mirrors.txt` in the app's settings folder (one URL per line, `#` - comments) — `~/Library/Application Support//` (macOS), `%APPDATA%\\` - (Windows), `~/.config//` (Linux); + comments) — `~/Library/Application Support/Chromaforge/` (macOS), `%APPDATA%\Chromaforge\` + (Windows), `~/.config/Chromaforge/` (Linux); 3. the built-in list, `DEFAULT_MIRRORS` in `crates/segment/src/fetch/mod.rs`. A mirror can also be a **local folder** holding the three files: an absolute path or a -`file://` URL (`_SAM3_MIRRORS=/data/sam3` or `file:///data/sam3`; on Windows +`file://` URL (`CHROMAFORGE_SAM3_MIRRORS=/data/sam3` or `file:///data/sam3`; on Windows `file:///C:/data/sam3`). The files are copied into the model folder with the same checks as a download (exact size and SHA-256, `.part` file, progress in the activity stack, cancellable); a copy that doesn't match is deleted. Use this when you already have the checkpoint (for example @@ -316,11 +313,11 @@ licence there, wait for approval and download with their own token). Someone wit use it as their mirror: ```sh -_SAM3_MIRRORS=https://huggingface.co/facebook/sam3/resolve/main \ -_SAM3_TOKEN=hf_... +CHROMAFORGE_SAM3_MIRRORS=https://huggingface.co/facebook/sam3/resolve/main \ +CHROMAFORGE_SAM3_TOKEN=hf_... chromaforge ``` -(`_SAM3_TOKEN` is sent as a bearer token only over https, and only to the mirror's own +(`CHROMAFORGE_SAM3_TOKEN` is sent as a bearer token only over https, and only to the mirror's own host — not to the storage host it redirects to.) The download is plain HTTP/1.1 over TLS in pure Rust (rustls with the RustCrypto provider and @@ -330,7 +327,7 @@ the Mozilla root certificates; no OpenSSL, `ring` or `aws-lc`, nothing compiled ### By hand Put `model.safetensors`, `vocab.json` and `merges.txt` from `facebook/sam3` in the model folder: -`models/sam3/` in the settings folder above, or the folder `_SAM3_DIR` names. It must be +`models/sam3/` in the settings folder above, or the folder `CHROMAFORGE_SAM3_DIR` names. It must be the Hugging Face format (3,439,938,512 bytes): `sam3.safetensors` from community mirrors, renamed, is Meta's original checkpoint, and the app says so instead of loading it. Developers can use the installer scripts, which download from Hugging Face with your token and verify the @@ -347,8 +344,8 @@ $env:HF_TOKEN = "hf_..."; .\tools\install-sam3.ps1 # Windows ## Licence of the model -The app's code is MIT; `crates/segment` (a port of Apache-2.0 code) is -Apache-2.0. **The SAM 3 weights are neither**: they are Meta's, released under the **SAM +The app's own code is GPL-3.0-or-later; `crates/segment` is licensed under GPL-3.0-or-later OR +Apache-2.0, not MIT. **The SAM 3 weights are neither**: they are Meta's, released under the **SAM License** (), a custom licence that is not an OSI open-source licence. It grants a non-exclusive, worldwide, non-transferable, royalty-free licence to use, reproduce, distribute, copy, modify and create derivative works of @@ -405,7 +402,7 @@ the mask is made without the model. Without the model, the AI kinds fail with an In the desktop app the commands don't wait for the model: `mask.objectPoint` returns `{pending: true}` and the selection is applied when it's computed (one undo step per settled selection); `mask.add {kind: "prompt"}` returns `{pending: true}` and the mask appears when -something is found (or a message says nothing was). `` and the headless MCP server +something is found (or a message says nothing was). `chromaforge-cli` and the headless MCP server wait and return the result (when built with the `sam` feature; the default CLI has no AI masks). ## Implementation notes @@ -427,10 +424,10 @@ wait and return the result (when built with the `sam` feature; the default CLI h error and the model is reloaded on the next request; busy counters are reset by drop guards. - GPU fallback (issue #1974): a job that fails on the GPU (a panic or a candle error, e.g. an AMD GPU in an Intel Mac whose Metal compiler crashes on a matmul kernel) frees the model and runs - once more on the CPU. If that works, the model stays on the CPU until restarts and + once more on the CPU. If that works, the model stays on the CPU until Chromaforge restarts and the user is told once ("The GPU couldn't run the AI mask model…"); if the CPU fails too, the error is reported and the next job tries the GPU again. Missing or damaged model files and - remote-worker errors are not retried. `_GPU=0` or `_GPU_BACKEND=off` keep + remote-worker errors are not retried. `CHROMAFORGE_GPU=0` or `CHROMAFORGE_GPU_BACKEND=off` keep the model on the CPU from the start. - Hostile documents: a selection keeps at most 4 detail patches (when read and when rendered), each at most 1024² logits; more than 64 clicks are never sent to the model. @@ -458,5 +455,5 @@ wait and return the result (when built with the `sam` feature; the default CLI h ```sh python3 -m venv .venv-sam3 && .venv-sam3/bin/pip install -r tools/requirements-sam3-reference.txt .venv-sam3/bin/python tools/sam3_reference.py photo.jpg ref.safetensors -_SAM3_DIR= _SAM3_REF=ref.safetensors cargo test -p lcc-segment --release -- --nocapture +CHROMAFORGE_SAM3_DIR= CHROMAFORGE_SAM3_REF=ref.safetensors cargo test -p lcc-segment --release -- --nocapture ``` diff --git a/docs/android.md b/docs/android.md index 9cf21c3cf0..947b64023f 100644 --- a/docs/android.md +++ b/docs/android.md @@ -163,7 +163,7 @@ Android is `unix`. Code meant for Linux and the BSDs names them (`target_os = "l .github/scripts/install-android-sdk.sh # JDK 17+ and SDK platform 36 / build-tools 36 (prints JAVA_HOME, ANDROID_HOME) rustup target add aarch64-linux-android # and x86_64-linux-android for the emulator cargo xtask android package [--abi arm64] [--abi x86_64] [--split] [--aab] [--store github|play] [--version-code N] -adb install -r target/android/--android-arm64-v8a.apk +adb install -r target/android/chromaforge--android-arm64-v8a.apk ``` There is no Gradle. The activity is one Java file on the platform's `NativeActivity` (no AndroidX), so xtask diff --git a/docs/apple-photos.md b/docs/apple-photos.md index a794d4470b..c3088a8bc0 100644 --- a/docs/apple-photos.md +++ b/docs/apple-photos.md @@ -109,7 +109,7 @@ or the control port as giving it this too, and turn the control port on only whe | What you see | Why, and what to do | |---|---| -| " isn't allowed to control Photos…" | Permission refused (`-1743`). Turn on Photos under the app (or your terminal app) in System Settings ▸ Privacy & Security ▸ Automation, then try again. | +| "Chromaforge isn't allowed to control Photos…" | Permission refused (`-1743`). Turn on Photos under the app (or your terminal app) in System Settings ▸ Privacy & Security ▸ Automation, then try again. | | "Apple Photos couldn't be found…" | Photos isn't installed or couldn't be opened (`-600`, `-10810`, `-10814`, or no `/System/Applications/Photos.app`). | | "The import was cancelled in Photos." | Someone pressed Cancel in a Photos dialog (`-128`). | | "More than one album at the top level of Photos is named …" | Several top-level albums have that name; nothing was added. Rename one in Photos, or use another name. | @@ -125,13 +125,13 @@ new empty library first: hold ⌥ while opening Photos ▸ Create New). 1. Package the app (ad-hoc signed unless `MACOS_SIGN_IDENTITY` is set): `packaging/macos/package.sh --arch arm64` (or `x64` on an Intel Mac). Check its entitlement: `codesign -d --entitlements - - target/macos-package/.app` lists `com.apple.security.automation.apple-events`. With a Developer ID + target/macos-package/Chromaforge.app` lists `com.apple.security.automation.apple-events`. With a Developer ID build, also run the notarized DMG from `dist/release/`. -2. Open it from the Finder, or with `open target/macos-package/.app --args --demo` (not by running +2. Open it from the Finder, or with `open target/macos-package/Chromaforge.app --args --demo` (not by running the binary in a terminal, which makes the terminal the app macOS asks about). -3. Select three photos, choose File ▸ Export…, set a folder (e.g. `~/Pictures/ Exports`), tick **Add +3. Select three photos, choose File ▸ Export…, set a folder (e.g. `~/Pictures/Chromaforge Exports`), tick **Add to Apple Photos**, type the album `Trip test "1"` and press OK. -4. macOS asks whether **** may control Photos, showing the usage text from `Info.plist`: allow it. +4. macOS asks whether **Chromaforge** may control Photos, showing the usage text from `Info.plist`: allow it. Expected: the toast reads "Exported 3 of 3 photos · 3 added to Apple Photos album “Trip test "1"”", and a top-level album of that name holds the three images. 5. Export the same photos again with the same settings. Expected: Photos asks about duplicates or imports them @@ -147,7 +147,7 @@ new empty library first: hold ⌥ while opening Photos ▸ Create New). 9. Hostile names: album `-e`, then `a\b`, and an export folder whose name contains `"` and `'`; a name with a line break through the CLI: `lcc-cli run --demo app.export dir=/tmp/lc-photos addToPhotos=true "photosAlbum=$(printf 'two\nlines')"`. Expected: albums named exactly so; nothing else happens. -10. The window stays responsive: start the app with `open target/macos-package/.app --args --demo +10. The window stays responsive: start the app with `open target/macos-package/Chromaforge.app --args --demo --control 18999`, then send `{"method": "engine.execute", "params": {"command": "export.addToPhotos", "params": {"paths": ["/tmp/lc-photos/.jpg"]}}}` to port 18999 (`docs/control-protocol.md`). Expected: an immediate `{"job": …, "running": true}`; the app keeps responding; a toast when Photos is done; diff --git a/docs/architecture.md b/docs/architecture.md index 536f9d411d..f5d24a60db 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -77,11 +77,11 @@ build is one `cargo check --target wasm32-unknown-unknown --keep-going` over the `gpu_probe` test of `lcc-gpu`, run after the workspace tests so it reuses their build; xtask has no wgpu), the corpus and `CRAFT_FONTS_DIR`. Tests that need what is missing call `lcc_testkit::skip!(need, reason)`, which appends a JSON line to -the file `_SKIP_LOG` names. The run ends with the machine and the skips by need and reason, +the file `CHROMAFORGE_SKIP_LOG` names. The run ends with the machine and the skips by need and reason, and writes `target/ci/report.json` (commit, dirty flag, machine, capabilities, each step's result and time, skips) and `target/ci/summary.md` (Markdown for a PR; `--summary-md` prints it). The report holds no host name, user name or absolute path, and nothing is uploaded. `--hardware` adds a step that runs -the `lcc-gpu` tests once per backend with a hardware adapter (`_GPU_BACKEND`). +the `lcc-gpu` tests once per backend with a hardware adapter (`CHROMAFORGE_GPU_BACKEND`). ## Revision history diff --git a/docs/base-curve-format.md b/docs/base-curve-format.md index 780401f7a2..ccc966d117 100644 --- a/docs/base-curve-format.md +++ b/docs/base-curve-format.md @@ -10,8 +10,8 @@ base curve is the base tone itself. ## Where the files go -- The folder `base-curves` inside the settings folder (`%APPDATA%\\base-curves` on Windows; - `\Data\base-curves` in a portable install), or the folder named by `_BASE_CURVES`. +- The folder `base-curves` inside the settings folder (`%APPDATA%\Chromaforge\base-curves` on Windows; + `\ChromaforgeData\base-curves` in a portable install), or the folder named by `CHROMAFORGE_BASE_CURVES`. - One curve per file, `.json`. The photo stores the id `base:` (the file name without `.json`). - Files over 1 MB, files that are not valid, and files with a newer format version are ignored with a warning. A photo whose selected curve is not in the folder keeps the id, renders with the default base tone and shows a diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 72e2ab0d98..5fd90af0eb 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -1,8 +1,5 @@ # Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3/CR2, Pentax PEF, Samsung SRW, Olympus ORF, Epson ERF, Canon CRW and Minolta MRW starting look -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - ARW, NEF, RW2, RAF, CR3, CR2, PEF, SRW, ORF, ERF, CRW and MRW decoding supply sensor data and camera white-balance multipliers, but currently no measured camera colour matrix. Treating camera RGB as linear sRGB produces a dark, muted default rendering. The loader now estimates a file-local starting look from that file's embedded camera JPEG, only when a usable camera matrix is absent. All output pixels still come from the RAW sensor data; there is no JPEG replacement or uniform saturation boost. ## Colour and tone are separate @@ -91,7 +88,7 @@ On one sample, Exposure +1 EV, Saturation +100, Contrast +50, warm/cool WB, tint The same fit, gates and relative WB apply to Panasonic RW2, Leica RWL and the older Panasonic RAW files (all decode as `RawFormat::Rw2`; white balance from tags `0x0024`–`0x0026`). Their embedded JPEG (`JpgFromRaw`, 1920 px wide) always shows the whole active area, while the default crop is the aspect ratio set in the camera (4:3 on the 3:2 sensors, 1:1, 16:9, 2.71 on the S1R II…); when the preview matches the active area rather than the crop, the reference is cropped to the default crop before fitting. -Public CC0 samples from raw.pixls.us (178 files from 118 Panasonic and Leica bodies; the four from 2005–2007 carry no preview), rendered at 1200 px and compared with each file's embedded JPEG (mean CIE76 ΔE at 200 px): 140 of 174 fits accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 (1.2–21.3) with matching mean lightness (median |ΔL*| 0.4); 124 of them use a hue/saturation table. (Fitted with the matrix and tone curve alone, 137 were accepted at median ΔE 6.1; every one of those is as close or closer with the table and chroma curve, by 0.75 on average.) On the 14 corpus files with a preview the neutral fallback scored ΔE 9.6–27 and rendered up to 16 L* too dark; 13 fits were accepted, ΔE 2.8–8.9, lightness within 2 L*. Of the 34 files left on the neutral fallback, 21 fail the gates, almost all compacts and kit zooms (TZ/ZS, FZ2500, D-Lux, V-Lux, GF2, GX80 with its 12–32 mm): their camera JPEG is distortion-corrected, the pixel pairs no longer line up and the held-out RMS stays above 0.10 (GX80: 0.138 → 0.107); two S1 II shots just miss it (0.103, 0.107). The other 13 never reach the gates, mostly nearly colourless scenes (grey walls, concrete: under 5% coloured pixels) or dark ones (a night sky, a near-black frame). Panasonic's embedded distortion data (tag `0x0119`) now corrects the render under Enable Profile Corrections (issue #256) but does not yet align the pairs of this fit, and ` calibrate` doesn't collect RW2 files: the misaligned pairs of distortion-corrected JPEGs would distort a pooled profile. +Public CC0 samples from raw.pixls.us (178 files from 118 Panasonic and Leica bodies; the four from 2005–2007 carry no preview), rendered at 1200 px and compared with each file's embedded JPEG (mean CIE76 ΔE at 200 px): 140 of 174 fits accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 (1.2–21.3) with matching mean lightness (median |ΔL*| 0.4); 124 of them use a hue/saturation table. (Fitted with the matrix and tone curve alone, 137 were accepted at median ΔE 6.1; every one of those is as close or closer with the table and chroma curve, by 0.75 on average.) On the 14 corpus files with a preview the neutral fallback scored ΔE 9.6–27 and rendered up to 16 L* too dark; 13 fits were accepted, ΔE 2.8–8.9, lightness within 2 L*. Of the 34 files left on the neutral fallback, 21 fail the gates, almost all compacts and kit zooms (TZ/ZS, FZ2500, D-Lux, V-Lux, GF2, GX80 with its 12–32 mm): their camera JPEG is distortion-corrected, the pixel pairs no longer line up and the held-out RMS stays above 0.10 (GX80: 0.138 → 0.107); two S1 II shots just miss it (0.103, 0.107). The other 13 never reach the gates, mostly nearly colourless scenes (grey walls, concrete: under 5% coloured pixels) or dark ones (a night sky, a near-black frame). Panasonic's embedded distortion data (tag `0x0119`) now corrects the render under Enable Profile Corrections (issue #256) but does not yet align the pairs of this fit, and `chromaforge-cli calibrate` doesn't collect RW2 files: the misaligned pairs of distortion-corrected JPEGs would distort a pooled profile. ### Fujifilm RAF @@ -105,7 +102,7 @@ For validation, every fifth usable photo of each model in sorted path order was The three original dark X-H2S wrench files have too little colour variation to learn a matrix, but now use the known profile to fit tone: ΔE 8.74 → 2.25, all accepted. The four original X-T4 files and two public X-T4 files remain accepted with the final bundled profile; they regress slightly against their own per-file fits (six-file mean 4.72 → 4.94), while remaining much closer than the neutral fallback (13.47). The public X-T20 reference fails the gates on all pixels (held-out RMS 0.114) and passes on the second attempt away from edges (0.056, from 0.185 uncorrected), so it is fitted too. -RAF inputs also work with ` calibrate`. Tests cover real X-Trans/16-bit Bayer fits, profile use on dull scenes, per-file fitting after profile rejection, monochrome rejection, resolution independence, header/decoded relative WB, old-catalog WB transitions and invalid RAF calibration inputs. A full-size 6240×4160 X-T4 JPEG export also succeeded. +RAF inputs also work with `chromaforge-cli calibrate`. Tests cover real X-Trans/16-bit Bayer fits, profile use on dull scenes, per-file fitting after profile rejection, monochrome rejection, resolution independence, header/decoded relative WB, old-catalog WB transitions and invalid RAF calibration inputs. A full-size 6240×4160 X-T4 JPEG export also succeeded. These are camera-JPEG look estimates, **not measured spectral calibration or Lightroom parity**. Camera local tone, picture styles, noise reduction and lens warps cannot all be reproduced by a global matrix/curve; same-aspect crops may evade the aspect check. Skin, mixed-light scenes and saturated highlights can still differ from a supplied JPEG. Broader Sony, Nikon, Panasonic and Fujifilm model/lighting coverage, chart-based calibration, absolute WB and other manufacturers remain unverified. Rejected fits and other RAW formats retain their existing behaviour. @@ -175,14 +172,14 @@ with a calibration file (R5 C, Z 6III, G9) and the Z 8 (no vignetting data) rend ## Camera profiles (pooled per model) -One photo can show too little of a colour for its own fit to learn it: in a second shot of the lime shirt only a few dozen proxy pixels show it, next to a hillside of foliage at the same hue that the camera renders differently, and the shirt stayed yellow (hue 68° against the JPEG's 82°; a 192-pixel proxy only reached 74°). ` calibrate [--max N] [--out DIR] FOLDERS…` therefore pools the colour pairs of many ARWs, NEFs or RAFs per camera model — each against its own embedded JPEG, at a 192-pixel proxy, at most 4000 pairs per photo, files spread evenly over the folders — and fits one matrix (from white-balanced camera RGB, so no single photo's white point is baked in) and one hue/saturation/value table. Models need at least 5 usable photos. +One photo can show too little of a colour for its own fit to learn it: in a second shot of the lime shirt only a few dozen proxy pixels show it, next to a hillside of foliage at the same hue that the camera renders differently, and the shirt stayed yellow (hue 68° against the JPEG's 82°; a 192-pixel proxy only reached 74°). `chromaforge-cli calibrate [--max N] [--out DIR] FOLDERS…` therefore pools the colour pairs of many ARWs, NEFs or RAFs per camera model — each against its own embedded JPEG, at a 192-pixel proxy, at most 4000 pairs per photo, files spread evenly over the folders — and fits one matrix (from white-balanced camera RGB, so no single photo's white point is baked in) and one hue/saturation/value table. Models need at least 5 usable photos. -Profiles are JSON files `.json` in `$_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support//camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos, NIKON D780, 255 photos, NIKON D750, 276 photos, NIKON D90, 289 photos (all below); NIKON D700, 394 photos; NIKON D70, 379 photos; and the Fujifilm X-T1, 217 photos, X100T, 32 photos, and X20, 396 photos, all shot with the PROVIA film simulation. They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit; when no look fits at all, the photo keeps the profile's colour (below). Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. +Profiles are JSON files `.json` in `$CHROMAFORGE_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/Chromaforge/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos, NIKON D780, 255 photos, NIKON D750, 276 photos, NIKON D90, 289 photos (all below); NIKON D700, 394 photos; NIKON D70, 379 photos; and the Fujifilm X-T1, 217 photos, X100T, 32 photos, and X20, 396 photos, all shot with the PROVIA film simulation. They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit; when no look fits at all, the photo keeps the profile's colour (below). Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. ### Sony ILCE-7CR -Fitted from 125 usable photos of 131 ILCE-7CR ARWs (one photographer, September 2025 to September 2026, Standard creative style with DRO off, Lv3 or Auto; 127 uncompressed, 2 compressed, 2 lossless compressed), 448,230 colour pairs. Measured as above: rendered at 1200 px with ` render`, mean CIE76 ΔE against each file's embedded JPEG at 200 px. +Fitted from 125 usable photos of 131 ILCE-7CR ARWs (one photographer, September 2025 to September 2026, Standard creative style with DRO off, Lv3 or Auto; 127 uncompressed, 2 compressed, 2 lossless compressed), 448,230 colour pairs. Measured as above: rendered at 1200 px with `chromaforge-cli render`, mean CIE76 ΔE against each file's embedded JPEG at 200 px. Without a profile, 123 of the 131 photos accept their own fit; the other 8 open with the neutral fallback at ΔE 6–26. For validation every fifth photo in sorted name order (26) was withheld and a profile fitted to the other 105 (100 usable). On the withheld photos mean ΔE went from 4.07 with per-file fitting to 3.29 with the profile. Both withheld photos whose own fit is rejected are accepted (ΔE 26.0 → 6.1 on a night scene, 6.2 → 5.5). Withheld photos whose own fit was accepted are about unchanged and move both ways: 12 of 24 improve, mean ΔE 3.06 → 3.08, largest regression 1.8. On that photo (gold tinsel bokeh) the profile turns a blue light blue again where the per-file fit had made it teal, but renders the gold slightly more saturated than the camera. With the final profile all 131 photos are accepted, and the 8 previously rejected ones land at ΔE 1.3–5.7; that comparison is in-sample. @@ -274,11 +271,11 @@ When no look fits a photo of a profiled model (steps 3 and 4 both fail: a black- Before this, such a photo fell to 5 or 6 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. ` calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a photo no look fits takes the pooled curve whole instead of the default one. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `chromaforge-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a photo no look fits takes the pooled curve whole instead of the default one. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). -`photo.sourceReport {ids}` (a read-only command; agents and `` scripts can run it) says which step a photo's +`photo.sourceReport {ids}` (a read-only command; agents and `chromaforge-cli` scripts can run it) says which step a photo's original took: `colour.kind` is `file` (1), `measuredDatabase` (2), `cameraJpeg` (3 or 4: `cameraProfile` says a profile for the model was offered to the fit, not whether its colour was kept), `cameraProfile` (the profile's colour kept when no look fits, above), `database` (5, with the entry's provenance), `spectralStandIn` (an ARW of a Sony body @@ -329,11 +326,11 @@ matrix reads tungsten-lit multipliers less exactly than a two-illuminant pair wo Data rules: what ships must be legal to redistribute, with its source named. No Adobe DCP/LCP files, no matrices harvested from Adobe-converted DNGs, no Adobe-rendered pixels, and no tables from GPL or other copyleft projects -(darktable, RawTherapee, LibRaw's updated copies of dcraw's table). ` camdb extract NATIVE.dng…` prints entries from DNGs +(darktable, RawTherapee, LibRaw's updated copies of dcraw's table). `chromaforge-cli camdb extract NATIVE.dng…` prints entries from DNGs a camera wrote itself and refuses DNGs whose `Software` tag names Adobe software (DNG Converter, Lightroom, Camera Raw, -Photoshop), the app's own DNG export, or is missing. ` camdb show MAKE MODEL` prints the entry a camera resolves +Photoshop), the app's own DNG export, or is missing. `chromaforge-cli camdb show MAKE MODEL` prints the entry a camera resolves to. A native DNG's matrices help that model's other raw format (a Pentax body's PEF files, say), whose files carry -none. ` calibrate-chart` measures entries with `chart` provenance from raw shots of a ColorChecker Classic ([chart-calibration](chart-calibration.md)). Besides dcraw's table, the database has no TOML entries yet. +none. `chromaforge-cli calibrate-chart` measures entries with `chart` provenance from raw shots of a ColorChecker Classic ([chart-calibration](chart-calibration.md)). Besides dcraw's table, the database has no TOML entries yet. Calibrations matched to Lightroom (`crates/camdb/data/calibrations/`, maintainer decision 2026-10-25) are the one place Lightroom informs the numbers: black-box fits to Lightroom's *output images* of a contributor's own photos, diff --git a/docs/catalog.md b/docs/catalog.md index 1059265dfb..407898d097 100644 --- a/docs/catalog.md +++ b/docs/catalog.md @@ -1,7 +1,5 @@ # Catalog storage and scale -> Names in angle brackets (``, ``, …) are the values set in [`brand.toml`](../brand.toml). - ## Benchmark `cargo xtask bench-catalog --photos 250000,1000000 [--backend v3|v4]` builds a synthetic library (camera, lens, @@ -159,7 +157,7 @@ A catalog is a folder (`crates/catalog/src/library.rs`): ```text My Catalog/ - My Catalog. entry point (JSON: magic, version, store) + My Catalog.chromacat entry point (JSON: magic, version, store) catalog.redb the store catalog.log the op log catalog.snap stub that makes builds before v4 refuse the folder untouched @@ -238,8 +236,8 @@ both). Photos match by file path and virtual-copy name, so a photo whose origina twice). Its startup default (`default`) is not carried over: At launch decides. A file it can't parse is skipped with a log line and set aside; one it can't read is logged and kept for the next start. - **First start** (`catalog.welcome`): when there is no catalog of this app to open (no `--library` / - `_LIBRARY`, nothing remembered, no catalog at the default location) the welcome dialog asks: create a - library (name, location — default `~/Pictures/` — and sample photos only if ticked; `catalog.new + `CHROMAFORGE_LIBRARY`, nothing remembered, no catalog at the default location) the welcome dialog asks: create a + library (name, location — default `~/Pictures/Chromaforge Library` — and sample photos only if ticked; `catalog.new {parent, name, demo}`) or open one. Its "Check for updates when the app starts" box (unticked at first) travels with the action as `checkAtStartup: true` when ticked (`catalog.new`, `catalog.open`, `catalog.openRecent`), and turns the start-up check on through `update.prefs` only once that action has opened a library; while Open Catalog…'s folder diff --git a/docs/changelog/unreleased/2026-11-29-capture-one-import-tones-and-curves.md b/docs/changelog/unreleased/2026-11-29-capture-one-import-tones-and-curves.md new file mode 100644 index 0000000000..d5d1f55f10 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-29-capture-one-import-tones-and-curves.md @@ -0,0 +1,3 @@ +## Import + +- **Capture One import:** a raw's film curve comes across as its base curve with the Built-in colour (the curve files are the user's), Highlight (below zero), Shadow and Saturation are converted by mappings measured on Capture One's exports and marked approximate in the result window, and contrast, white, black, clarity and structure are named as not imported. A virtual copy starts from the camera defaults instead of its master's settings, and a Capture One import reads no XMP sidecar. diff --git a/docs/changelog/unreleased/2026-11-29-custom-order-in-folders.md b/docs/changelog/unreleased/2026-11-29-custom-order-in-folders.md new file mode 100644 index 0000000000..a9b8c76ee9 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-29-custom-order-in-folders.md @@ -0,0 +1,3 @@ +## Library + +- **Custom Order in folders:** a folder of the Folders panel shown as its own photos can be put in the order you set by hand, as a collection can: pick Custom Order in the sort menu and drag photos in the grid or along the filmstrip. The order is saved with the folder and follows it when the folder is renamed or moved (#1583). diff --git a/docs/changelog/unreleased/2026-11-29-dropdown-menus-take-the-keyboard.md b/docs/changelog/unreleased/2026-11-29-dropdown-menus-take-the-keyboard.md new file mode 100644 index 0000000000..5cbbd68ccd --- /dev/null +++ b/docs/changelog/unreleased/2026-11-29-dropdown-menus-take-the-keyboard.md @@ -0,0 +1,3 @@ +## Fixes + +- Open dropdown menus no longer let keys act on the photos behind them, and typing a name selects the matching item. diff --git a/docs/changelog/unreleased/2026-11-29-edit-in-checks-the-editor-first.md b/docs/changelog/unreleased/2026-11-29-edit-in-checks-the-editor-first.md new file mode 100644 index 0000000000..dc4e548cb7 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-29-edit-in-checks-the-editor-first.md @@ -0,0 +1,3 @@ +## Library + +- **Edit In keeps no useless copy on a failed launch.** Edit a Copy and Edit Original check the editor before the command makes its file, so a missing editor reports why instead of leaving an unopened copy stacked in the library (#1315). The launch itself finds PhotoCraft where its installer put it (registry, App Paths, desktop entry, AppImage, Flatpak) for every mode, not only for a rendered copy. diff --git a/docs/changelog/unreleased/2026-11-29-macos-open-from-finder.md b/docs/changelog/unreleased/2026-11-29-macos-open-from-finder.md new file mode 100644 index 0000000000..3f030dcc30 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-29-macos-open-from-finder.md @@ -0,0 +1,3 @@ +## Library + +- macOS: photos opened from Finder (Open With, the Dock icon) or another app are imported; before, macOS said the app could not open them. diff --git a/docs/changelog/unreleased/2026-11-30-cmd-d-select-none.md b/docs/changelog/unreleased/2026-11-30-cmd-d-select-none.md new file mode 100644 index 0000000000..384602313b --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-cmd-d-select-none.md @@ -0,0 +1,4 @@ +## Library +- **Select None (⌘D) deselects every photo:** it used to keep the active photo selected, so it did the same as Select Only Active Photo. Now nothing stays selected and no photo is active; Cmd+Shift+D still keeps only the active photo. +- **Deselect Unflagged Photos deselects the active photo too:** with no flagged photo in the selection, nothing stays selected. +- **Loupedeck "Select Only Active Photo" is no longer mapped to Select None:** an imported profile that used it now lists that action as dropped. diff --git a/docs/changelog/unreleased/2026-11-30-date-filter-year-month-day.md b/docs/changelog/unreleased/2026-11-30-date-filter-year-month-day.md new file mode 100644 index 0000000000..501d5b8c57 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-date-filter-year-month-day.md @@ -0,0 +1,3 @@ +## Library + +- **Metadata Date filter by year, month, and day:** the Metadata filter bar's **Date** column now expands into a Year, Month, and Day tree so multi-day events can be filtered down to individual days or months (#1708). diff --git a/docs/changelog/unreleased/2026-11-30-enter-in-dialog-fields.md b/docs/changelog/unreleased/2026-11-30-enter-in-dialog-fields.md new file mode 100644 index 0000000000..1f53c96425 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-enter-in-dialog-fields.md @@ -0,0 +1,3 @@ +## Fixes + +- **Enter in dialog text boxes:** Enter in a text box of the Smart Collection, Edit Capture Time, Color Label Names, Rename Photos, New Preset and Export dialogs, and in the Export module's settings, confirms the dialog or starts the export, as it already did in New Collection and Rename. With Smart Collection rules that don't check, Enter does nothing. diff --git a/docs/changelog/unreleased/2026-11-30-esc-in-settings-fields.md b/docs/changelog/unreleased/2026-11-30-esc-in-settings-fields.md new file mode 100644 index 0000000000..140ed762e1 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-esc-in-settings-fields.md @@ -0,0 +1,3 @@ +## Fixes + +- **Esc in Settings, Import and Export:** Esc in a text field of these screens (or Back in the Modern layout) leaves the field first instead of closing the screen; the next Esc closes it. diff --git a/docs/changelog/unreleased/2026-11-30-external-editing-settings.md b/docs/changelog/unreleased/2026-11-30-external-editing-settings.md new file mode 100644 index 0000000000..8f0576e5d2 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-external-editing-settings.md @@ -0,0 +1,3 @@ +## Settings + +- **External Editing gets its own settings page.** Every editor Photo ▸ Edit In offers is listed there: the operating system's default application (new menu command Edit in Default Editor), PhotoCraft, and as many saved editors as you add. Adding one makes a row; clicking it opens its fields (name, application with the editors found on this machine or Browse…, launch options, and the file it hands over: format, bit level, colour space, or the original with an XMP sidecar) (#1315). Copy formats gain PNG (8/16-bit), scene-linear OpenEXR (16/32-bit half/float, Rec. 2020; its link rides in a `.xmp` sidecar) and a raw's DNG with the edits in its XMP; TIFF copies take 32-bit float, colour spaces gain Rec. 2020, and every editor can write the edits beside an Edit a Copy / Edit Original file as an XMP sidecar. diff --git a/docs/changelog/unreleased/2026-11-30-faces-aligned-in-maintenance.md b/docs/changelog/unreleased/2026-11-30-faces-aligned-in-maintenance.md new file mode 100644 index 0000000000..c3369885c9 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-faces-aligned-in-maintenance.md @@ -0,0 +1,3 @@ +## Library + +- **Face suggestions after Face Maintenance:** since 26.48.1, Recognize Existing Faces, Rebuild All Embeddings and Rebuild Named Faces cut every face by its box instead of aligning it with the face model's landmarks, which made name suggestions far less reliable, above all with SFace (#1616). They align again, as the background scan does, and faces embedded in the meantime are embedded once more. diff --git a/docs/changelog/unreleased/2026-11-30-faster-lightroom-recovery-archive.md b/docs/changelog/unreleased/2026-11-30-faster-lightroom-recovery-archive.md new file mode 100644 index 0000000000..4c4d4fd144 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-faster-lightroom-recovery-archive.md @@ -0,0 +1,3 @@ +## Performance + +- **Faster Lightroom recovery archive:** the archive written while importing a Lightroom catalog is compressed in 1 MiB blocks instead of one compressor call per JSON token, each of which cleared a 16 KiB buffer; importing a 680,000-photo catalog took 594 s instead of 860 s on an M1 Max, with the same archive (#1742). Thanks @blwfish. diff --git a/docs/changelog/unreleased/2026-11-30-filter-bar-several-values-of-one-type.md b/docs/changelog/unreleased/2026-11-30-filter-bar-several-values-of-one-type.md new file mode 100644 index 0000000000..5de0957c34 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-filter-bar-several-values-of-one-type.md @@ -0,0 +1,3 @@ +## Library + +- **Several values of one filter type:** Metadata column clicks work as in Lightroom Classic: a plain click chooses one value, ⌘/Ctrl-click adds or removes one, ⇧-click chooses a run. Date (year, month, day), Flag, Rating and File Type take several values, as do the Flag icons and the Type menu; any chosen value matches and different types still combine. A plain click in Camera, Lens, Keyword, People and Label now replaces the choice instead of adding to it. `library.facetPick` takes `values` and a `mode` (`replace` or `toggle`). diff --git a/docs/changelog/unreleased/2026-11-30-fits-astrophotography.md b/docs/changelog/unreleased/2026-11-30-fits-astrophotography.md new file mode 100644 index 0000000000..68d074a5d0 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-fits-astrophotography.md @@ -0,0 +1,3 @@ +## Import, export and formats + +- **FITS (astrophotography):** `.fits`, `.fit` and `.fts` files from astro cameras and stacking software import as raw photos: 8-, 16- and 32-bit integer and 32- and 64-bit floating-point samples, a monochrome frame, a colour-filter-array frame (demosaiced from the file's `BAYERPAT`, with `XBAYOFF` / `YBAYOFF`) or red, green and blue planes; the header's `DATE-OBS`, `EXPTIME`, `INSTRUME`, `OBJECT` and `FOCALLEN` fill the photo's metadata (#1604). Read by the app's own decoder on every platform. Suggested by @Under-The-Moonlight-Stars. diff --git a/docs/changelog/unreleased/2026-11-30-grid-size-keys-every-press.md b/docs/changelog/unreleased/2026-11-30-grid-size-keys-every-press.md new file mode 100644 index 0000000000..4e2f385aa0 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-grid-size-keys-every-press.md @@ -0,0 +1,3 @@ +## Fixes + +- **Grid size keys change the grid on every press:** `=` and `-` now move Square Grid by one column and Photo Grid to the next size at which a row changes, so no press is lost near the largest size. Photo Grid's size slider and keys end at the same size. diff --git a/docs/changelog/unreleased/2026-11-30-import-tab-default-selected.md b/docs/changelog/unreleased/2026-11-30-import-tab-default-selected.md new file mode 100644 index 0000000000..d97e9ced2e --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-import-tab-default-selected.md @@ -0,0 +1,3 @@ +## Import + +- **Import tab defaults to Selected:** choosing photos in the Browse / Import tab now enables the **Import** button immediately without needing to flag them as Picks first, shows the reason in the tooltip when 0 photos match, and removes the duplicate grid folder header (#1730). diff --git a/docs/changelog/unreleased/2026-11-30-people-sort-thumbnails.md b/docs/changelog/unreleased/2026-11-30-people-sort-thumbnails.md new file mode 100644 index 0000000000..e1152751fe --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-people-sort-thumbnails.md @@ -0,0 +1,4 @@ +## Library + +- **People view, sorting:** a person's page sorts their faces by import order (as before), capture time oldest or newest first, folder, or largest face first; the choice persists (`person.sort`, `faces.person`'s `sort`). +- **Build Face Thumbnails:** Library ▸ Faces ▸ Build Face Thumbnails renders a tile of every face in the library into the thumbnail cache ahead of the People view (background, cancellable, `faces.buildThumbnails` with `status`/`cancel`), so scrolling People no longer renders tiles one by one. diff --git a/docs/changelog/unreleased/2026-11-30-raw-jpeg-companions.md b/docs/changelog/unreleased/2026-11-30-raw-jpeg-companions.md new file mode 100644 index 0000000000..8b55f684f2 --- /dev/null +++ b/docs/changelog/unreleased/2026-11-30-raw-jpeg-companions.md @@ -0,0 +1,3 @@ +## Library + +- **RAW + JPEG companions:** at import, a JPEG with a raw's name beside it (same folder) is not a photo of its own any more but the raw's companion — one thumbnail, one face scan, one set of metadata — and travels with the raw through Copy / Move and Rename (#1692). The grid badge marks the pair and the Info panel names the companion JPEG; a raw the library already has is pointed at the JPEG when it arrives later. The behaviour is the library setting Treat JPEGs next to raw files as companions (Catalog Settings, on by default, as Lightroom Classic) and the same option in the import options; unchecked, JPEGs import as separate photos as before. diff --git a/docs/chart-calibration.md b/docs/chart-calibration.md index c7b11aa966..aafcc36dd1 100644 --- a/docs/chart-calibration.md +++ b/docs/chart-calibration.md @@ -1,6 +1,6 @@ # Calibrating a camera with a colour chart -` calibrate-chart` measures a camera's colour from raw photos of an **X-Rite ColorChecker Classic** (the 24-patch +`chromaforge-cli calibrate-chart` measures a camera's colour from raw photos of an **X-Rite ColorChecker Classic** (the 24-patch chart, also sold as Calibrite ColorChecker Classic). The result is measured colour for that camera model. The app then uses it before any estimate: the camera-JPEG fit, the spectral table and dcraw's matrices. @@ -21,7 +21,7 @@ the picture's width and height. For example, a corner patch 1200 px from the lef `0.2`. Give them in any order round the chart; the tool works out which corner is which. ``` - calibrate-chart \ +chromaforge-cli calibrate-chart \ --shot DSC_0001.NEF --corners "0.21,0.30 0.78,0.29 0.79,0.70 0.20,0.71" --light daylight \ --shot DSC_0002.NEF --corners "0.22,0.31 0.77,0.30 0.78,0.69 0.21,0.70" --light tungsten \ --preview chart-check --dcp my-camera.dcp diff --git a/docs/ci.md b/docs/ci.md index 0911b99630..b9c3167935 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -1,6 +1,6 @@ # CI and landing changes -> **Last updated:** 2026-11-29 · **Change:** major (`main`, `staging` and `release` are permanent: rulesets name them, fixes go to `main` and come back to `staging` through a `sync/` branch, a PR to `release` must carry `main`'s tree); major (PRs to `staging` run the fast gate only, no tests; the full suite gates the batch PR `staging` → `main`; Brand on batch PRs only; Windows ARM64 weekly + dispatch; Immich and Print nightly only); patch (the nightly Report job also runs on dispatches on `main`, so a green dispatch closes the failure issue); minor (2026-11-24: `cargo xtask bench` runs the probes and gates on budgets); patch (dependency updates: the hand-held `windows` 0.62.2 lockfile pin); minor (PRs run the tests of the changed crates and their dependents; the nightly full run covers macOS and Windows, files an issue when red, and a red nightly blocks `release.yml`); minor (nightly `Fuzz` runs all targets in parallel in one job); minor (nightly `Fuzz` workflow: every pure-Rust fuzz target for 30 minutes, crash inputs as artifacts); minor (nightly workflow: corpus + fonts full run with a skip gate, GPU equivalence on lavapipe and WARP); minor (timing probes and benchmarks run with `_PROBES=1` and otherwise record a `probe` skip); minor (generated demo photos are kept on disk across test processes); minor (the fast gate checks that the fork catalogs are sorted); minor (the full run also checks the x86_64 Android target); major (no repeated runs: a push to main skips a tree its PR run tested, no CI on pushes to `release`, Brand only on PRs and built in the runner cache, Windows ARM64 only when packaging inputs change, sccache, one cargo run per target for the fast gate's wasm/Android checks); minor (release jobs upload straight to the draft release, not via Actions artifacts); major (every workflow on self-hosted runners, containers on gpu0, fork PRs approved after review); minor (test retries, flaky reports and the test quarantine for the full run); major (fast PR gate; full test runs only before a release); major (created: PR-only main, self-hosted runner, local status) +> **Last updated:** 2026-11-29 · **Change:** major (`main`, `staging` and `release` are permanent: rulesets name them, fixes go to `main` and come back to `staging` through a `sync/` branch, a PR to `release` must carry `main`'s tree); major (PRs to `staging` run the fast gate only, no tests; the full suite gates the batch PR `staging` → `main`; Brand on batch PRs only; Windows ARM64 weekly + dispatch; Immich and Print nightly only); patch (the nightly Report job also runs on dispatches on `main`, so a green dispatch closes the failure issue); minor (2026-11-24: `cargo xtask bench` runs the probes and gates on budgets); patch (dependency updates: the hand-held `windows` 0.62.2 lockfile pin); minor (PRs run the tests of the changed crates and their dependents; the nightly full run covers macOS and Windows, files an issue when red, and a red nightly blocks `release.yml`); minor (nightly `Fuzz` runs all targets in parallel in one job); minor (nightly `Fuzz` workflow: every pure-Rust fuzz target for 30 minutes, crash inputs as artifacts); minor (nightly workflow: corpus + fonts full run with a skip gate, GPU equivalence on lavapipe and WARP); minor (timing probes and benchmarks run with `CHROMAFORGE_PROBES=1` and otherwise record a `probe` skip); minor (generated demo photos are kept on disk across test processes); minor (the fast gate checks that the fork catalogs are sorted); minor (the full run also checks the x86_64 Android target); major (no repeated runs: a push to main skips a tree its PR run tested, no CI on pushes to `release`, Brand only on PRs and built in the runner cache, Windows ARM64 only when packaging inputs change, sccache, one cargo run per target for the fast gate's wasm/Android checks); minor (release jobs upload straight to the draft release, not via Actions artifacts); major (every workflow on self-hosted runners, containers on gpu0, fork PRs approved after review); minor (test retries, flaky reports and the test quarantine for the full run); major (fast PR gate; full test runs only before a release); major (created: PR-only main, self-hosted runner, local status) ## How changes land: `staging`, then batched into `main` @@ -137,7 +137,7 @@ Release platform jobs upload their files straight to the draft GitHub release wi Actions artifacts: from these runners `actions/download-artifact` ran at about 0.3 MB/s (the 0.8.2 release job spent over an hour downloading), `gh release` at about 11 MB/s. Only a few-byte checksum file per platform (and, on a dry run, the Linux tarball for the Flatpak job) still goes through artifacts. See -[releasing.md](releasing.md). +[release-process.md](release-process.md). Jobs run at low priority, since the machines are also used interactively: Linux steps run under `nice -n 19` (job `defaults.run.shell`), macOS steps under `nice -n 19` (not `taskpolicy -b`: background QoS confines builds to the efficiency cores), and Windows @@ -156,7 +156,7 @@ before. `sccache --show-stats` on the runner shows the hit rate; `rm -rf ~/.cach Test runs keep generated demo photos on disk. A procedural demo photo costs up to a minute of CPU time to generate, and nextest starts one process per test, so every UI test used to generate its own (over 90 % of the suite's time). Unit tests of the UI and engine now store them in `tmp/demo-scenes` of the target directory, and -`cargo xtask ci`, `quarantine` and `sil` set `_DEMO_SCENE_CACHE` to the same folder for integration tests +`cargo xtask ci`, `quarantine` and `sil` set `CHROMAFORGE_DEMO_SCENE_CACHE` to the same folder for integration tests and the CLI processes they start (`crates/engine/src/scene_disk.rs`). A file is named after a fingerprint of the scene's pixels, so a change to a scene makes new files; the folder stops growing at 16 GB and can be deleted at any time. The app itself never uses it unless the variable is set. @@ -295,10 +295,10 @@ allows none since the job has craft-fonts); after a green nightly, tighten them why in the commit. **Software adapters.** The app never renders on a software adapter (the CPU pipeline is faster). -`_GPU_SOFTWARE=1` (CI and tests only) makes the compute device wgpu's fallback adapter instead: lavapipe on +`CHROMAFORGE_GPU_SOFTWARE=1` (CI and tests only) makes the compute device wgpu's fallback adapter instead: lavapipe on Vulkan, WARP on DX12. On it the equivalence tests allow mean |Δ| < 1.0 and max |Δ| ≤ 6 8-bit steps (hardware: 0.5 and 3), since software rasterizers round transcendentals and fused multiply-adds differently; a wrong kernel still -moves far more. Locally: `_GPU_SOFTWARE=1 _GPU_BACKEND=dx12 cargo test -p lcc-gpu --release --test it +moves far more. Locally: `CHROMAFORGE_GPU_SOFTWARE=1 CHROMAFORGE_GPU_BACKEND=dx12 cargo test -p lcc-gpu --release --test it -- equivalence` (Windows; `vulkan` with Mesa's `mesa-vulkan-drivers` on Linux). ## Model references @@ -314,8 +314,8 @@ compares, per output, element count, mean, standard deviation, min, max and the min / max within `rtol` of the output's range, the share within `share_tol`; both stored per model). The job fails if any model is skipped. These are regression references for our ports, generated by our own code (no images, no upstream outputs); the stage-by-stage comparisons with the upstream implementations (`*_reference.rs`) stay manual. -Locally: `_MODEL_REF_DIR= cargo test -p lcc-segment --release --test model_reference -- --nocapture`; -after a deliberate change to a model's outputs, regenerate with `_MODEL_REF_WRITE=1` and review the diff. +Locally: `CHROMAFORGE_MODEL_REF_DIR= cargo test -p lcc-segment --release --test model_reference -- --nocapture`; +after a deliberate change to a model's outputs, regenerate with `CHROMAFORGE_MODEL_REF_WRITE=1` and review the diff. | Model | Licence of the weights | In the job | |---|---|---| @@ -382,8 +382,8 @@ status is only as trustworthy as the run behind it: post it only from a real, co A test that can't run here calls `lcc_testkit::skip!(Need, "why")`; `cargo xtask ci` collects the skips in `target/ci/report.json` and `summary.md`. Timing probes and benchmarks are not `#[ignore]`d: they start with -`if !lcc_testkit::probe("what") { return; }`, which records a `probe` skip unless `_PROBES=1` is set. Run them -in release, for example `_PROBES=1 cargo test --release -p lcc-pipeline --lib bench_ -- --nocapture`. +`if !lcc_testkit::probe("what") { return; }`, which records a `probe` skip unless `CHROMAFORGE_PROBES=1` is set. Run them +in release, for example `CHROMAFORGE_PROBES=1 cargo test --release -p lcc-pipeline --lib bench_ -- --nocapture`. The nightly skip gate (`cargo xtask skips check`) does not count `probe` skips: they are opt-in by design, not a missing corpus, font or GPU. `cargo xtask bench` runs the main ones and checks their budgets (`--strict` fails on a breach or a > 20 % regression vs this machine's baseline; [`perf.md`](perf.md#budget-gate-cargo-xtask-bench---strict)). diff --git a/docs/contributors.md b/docs/contributors.md deleted file mode 100644 index 242550e3ef..0000000000 --- a/docs/contributors.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor credits - -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - -The contributor records credit everyone who contributed to the app, and the AI models named in -`Co-Authored-By` trailers. This page is the decision. - -## Decision - -- Two files in [`contributors/`](../contributors/): - - [`contributors/contributors.json`](../contributors/contributors.json): commit stats per GitHub - username. **Generated** by `contributors/fork-contributors.py`; never hand-edit. - - [`contributors/people.toml`](../contributors/people.toml): the names people chose for - themselves. **Each contributor adds only their own entry**, in their own PR. -- Each contributor gets one record: GitHub username (always), display name (opt-in, or their synced - GitHub profile name), real name (only if they told us), merged PRs, commits, lines added, lines - deleted, binary assets added, binary assets removed, first and last commit date. - -## In the app - -- Since 2026-11-15 the app no longer shows these lists: Help ▸ About shows only the app's - name, version, licences and links. The files are kept up to date for the repository's own - credits. - -## Credit yourself - -Add your entry to `contributors/people.toml` in a PR you commit yourself (every field optional): - -```toml -[people.your-github-username] -real_name = "Your Name" -display_name = "Nickname" -sync_github_name = true # use the name on your public GitHub profile as display name -``` - -Names show after the next refresh: the script checks that each entry was committed by its own -user (or by a maintainer with a `consent_source`). Delete your entry to remove your names. - -## Refreshing (maintainers) - -```sh -python3 contributors/fork-contributors.py # regenerate contributors.json; needs `gh` signed in and the `upstream` remote fetched -``` - -Commit the updated `contributors/contributors.json`. Git author names and emails are never recorded. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 08dc8eb070..de6846be03 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,9 +1,6 @@ # Control protocol -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - -` --control 7980` (or `_CONTROL_PORT=7980`) starts a JSON-lines server on +`chromaforge --control 7980` (or `CHROMAFORGE_CONTROL_PORT=7980`) starts a JSON-lines server on `127.0.0.1:7980` (loopback only). One request per line, one reply per line, in order. The first request on every connection authenticates (see [Authentication](#authentication)). The example assumes exactly one photo is selected: @@ -25,15 +22,15 @@ or wrong token, or a line that isn't a request gets one error reply (`authentica `wrong control token`; it never contains the token) and is closed. - **The token:** 64 hex digits (32 random bytes). The app makes a fresh one each run, or uses - `--control-token HEX` / `_CONTROL_TOKEN=HEX` when given (handy for scripts that start the + `--control-token HEX` / `CHROMAFORGE_CONTROL_TOKEN=HEX` when given (handy for scripts that start the app themselves). - **Where clients find it:** the app writes it to `control-token-` in its settings folder - (`` in the platform's settings location, beside the program in portable mode, or - `_CONFIG_DIR`); on Unix only you can read it. A page in + (`Chromaforge` in the platform's settings location, beside the program in portable mode, or + `CHROMAFORGE_CONFIG_DIR`); on Unix only you can read it. A page in a browser can't read files, and the HTTP request line it must send first is refused anyway. - Without a settings folder (`_CONFIG_DIR` set empty) a fresh token is printed on stderr. -- **Clients:** ` run --connect` and ` mcp --connect` send - `_CONTROL_TOKEN` if set, else the token in that file for the port they connect to, and + Without a settings folder (`CHROMAFORGE_CONFIG_DIR` set empty) a fresh token is printed on stderr. +- **Clients:** `chromaforge-cli run --connect` and `chromaforge-cli mcp --connect` send + `CHROMAFORGE_CONTROL_TOKEN` if set, else the token in that file for the port they connect to, and report a refused token as such. [`docs/showcase/run.py`](showcase/run.py) does the same. Implementation: `crates/engine/src/control_auth.rs`. @@ -82,13 +79,13 @@ mode ([mcp.md](mcp.md)) is a thin layer over this channel. Implementation: ## Isolated automation profiles -Set `_CONFIG_DIR` to a fresh directory to isolate UI preferences, app logs, the emergency +Set `CHROMAFORGE_CONFIG_DIR` to a fresh directory to isolate UI preferences, app logs, the emergency panic log, the GPU initialization marker, camera profiles and default model folders. The nonempty value is used as the complete settings directory. Unset retains the normal platform paths; an explicit empty value disables the settings directory, while the emergency panic log retains its system-temp path. Explicit model-directory environment variables still take precedence over their defaults. Also pass `--library DIR` with a separate scratch library: the configuration override does not change -the default photo-library location. Do not use `--memory` or `_NO_PREFS` when testing persistence. +the default photo-library location. Do not use `--memory` or `CHROMAFORGE_NO_PREFS` when testing persistence. A native acceptance run must reject the stderr message `rendering headlessly`: `ui.screenshot` automatically uses the CPU fallback after two seconds without a presented frame. That fallback is useful @@ -120,7 +117,7 @@ filmstrip is visible. | `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `frameGaps: {hostFrameMs, gapMs, maxGapMs, maxGapHostMs}` = wall time between frames while the window had work to show (renders on their way, input), the longest since start and the host's frame time before it — a long gap with a short host frame waited outside the UI thread, e.g. presenting behind GPU work, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `adjustQuality` = what a slider drag renders with high quality adjustment previews on: `idle` (no drag, or the setting is off), `full`, `draft` (too slow at full quality and the slider is moving) or `settled` (too slow, but the slider holds still) — see `docs/high-quality-adjustment-previews.md`; `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `last` / `draft` / `cached` or `render`), and with the app's own render; `dwellMs` is how long it stayed, the latest 256 steps), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack shows it, same shape as `activity.list`; a task shows once it is 0.5 s old. Classic: in the module bar in the identity plate's place, `activity:plate`, with ✕ = `activity:cancel:` for a single task and thin bars `activity:bar:` for several; a click there or `view.activityList` opens the list `activity:list` with rows `activity:row:` and their ✕. Modern: a floating card of rows `activity:row:`, `activity:more` expands past 3. Compact: as Classic; see `docs/background-tasks.md`), `activityList` (Classic and Compact: the list of tasks is open), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied), `toasts` (the messages at the bottom centre still showing, oldest first: `{text, kind, secsLeft}`; `kind` is `message`, `error`, `action` or `sticky`; a sticky one has a `key` and no `secsLeft`), `toastAction` (the message with a button: `{text, button, command, secsLeft}`, else `null`), `osd` (the on-screen overlay pill, as `osd.state` returns it: `settings`, `shown` = `{title, value, caption, icon, ageS}` or `null`, `held`)) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks) / `{id, toX?, toY?, dx?, dy?, steps?}` / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews) | -| `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points. In every pointer and scroll gesture (also `ui.clickWidget`, `ui.dragWidget`, `ui.hoverWidget`, `ui.pointer`, `ui.scroll`) a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | +| `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points. In every pointer and scroll gesture (also `ui.clickWidget`, `ui.dragWidget`, `ui.hoverWidget`, `ui.pointer`, `ui.scroll`) a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing. At most 4096 synthetic events (pointer, key, text, scroll, zoom) wait for the frames that take them; a request that would queue past that is refused (wait and retry), except one lone release (`ui.pointer` `up`, `ui.key` `up`) so a held button or key is never left down | | `ui.pointer` | `{events: [{kind: down\|drag\|up, x, y}], alt?, shift?, cmd?}` | Gesture in normalized image coordinates (Detail view) | | `ui.key` | `{key, action?: press\|down\|repeat\|up, cmd?, shift?, alt?, ctrl?}` | Key press (default), or the key going `down` and staying held until an `up` (Space held over a `ui.pointer` drag); `repeat` is an auto-repeat while held (Space's are ignored: it is a modifier) | | `ui.text` | `{text}` | Text input | @@ -134,9 +131,9 @@ filmstrip is visible. | `ui.dialog.confirm` / `ui.dialog.cancel` | — | Close the open dialog (confirm runs its action; also Read / Save Metadata's overwrite question, which those commands answer with `{confirm: "dialog", affected}`; Synchronize Folder on a folder that is up to date answers `{"upToDate": true}` and starts nothing) | | `ui.resize` | `{width?, height?}` | Resize the window in current egui points. Omitted `width` defaults to 1600 and omitted `height` to 1000; see [size limits below](#headless-rendering-no-window-no-gpu) | | `ui.dropFiles` | `{paths: [..], hover?}` | Files dragged from the file manager. `hover: true` makes every following frame report `paths` as hovered over the window (the drop card appears, `ui.widgets` lists `dropOverlay`) until another `ui.dropFiles` replaces them; `{paths: [], hover: true}` ends the hover. Without `hover` the files are dropped: the hover ends and the next frame receives them as dropped files, exactly as an OS drop arrives (photos and folders open the import review, or import at once with Settings ▸ Import ▸ Import dropped files without review). An empty path stands for a file whose path the platform doesn't tell | -| `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | +| `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off; in the loupe Cmd+= / Cmd+- zoom the photo, and in a grid Cmd+= opens it) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | -| `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir`; `destinationMode: "chooseLater"` without `dir` opens the folder dialog and exports once a folder is chosen (nothing when it is cancelled; an error where there is no folder dialog) | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md` — and `quality`, the JPEG quality a `limitKb` file-size limit settled on, when a limit was set); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | +| `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir`; `destinationMode: "chooseLater"` without `dir` opens the folder dialog and exports once a folder is chosen (nothing when it is cancelled; an error where there is no folder dialog) | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md` — and `quality`, the JPEG quality a `limitKb` file-size limit settled on, when a limit was set). A headless batch continues after a failed photo and lists it as `{photo, file, error}` in `files`; a failed single-photo export is an error. With `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | | `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?, inline?}` | Render a photo (PNG to `path`), `{width, height}`; `inline: true` without `path` puts the PNG in the reply as base64 `png` (for a client on another machine) | @@ -160,7 +157,7 @@ raws with colour matrices — in the file (DNG) or measured for the camera model reads the file's as-shot white; rendered files and raws without matrices use a relative scale whose 6500 K / 0 is the as-shot look (the Edit panel shows it as −100..+100). The stored `wb` of such a Kelvin raw says `"scale": "kelvin"`; a partial settings JSON given to `develop.merge`, to a preset's `wb`, or to -` render --settings` and which sets `temp` / `tint` **without** `scale` keeps the relative meaning it +`chromaforge-cli render --settings` and which sets `temp` / `tint` **without** `scale` keeps the relative meaning it always had (6500 = as shot) on every raw, so agents that mean Kelvin on a Kelvin raw pass `"scale": "kelvin"` or use `develop.set` / `develop.wb`. A partial that names only one of `temp` / `tint` is resolved against the photo (issue #2910): the photo's white balance is first brought onto the partial's scale with the photo's own as-shot @@ -238,8 +235,8 @@ after an update; `done`/`total` are bytes in its `backup` phase and photos in `w With Settings ▸ General ▸ At launch set to Ask me (`ui.set {"settings": {"atLaunch": "ask"}}`; `"last"`, the default, opens the last library), or Alt/Option held during the first 2 s after the window appears, the desktop app -shows a window listing the recent libraries (issue #1290). `--library` and `_LIBRARY` skip it, and so does -`--memory`; `` never shows it. `ui.inspect` → `libraryProblem.chooser` is `{libraries: [{path, +shows a window listing the recent libraries (issue #1290). `--library` and `CHROMAFORGE_LIBRARY` skip it, and so does +`--memory`; `chromaforge-cli` never shows it. `ui.inspect` → `libraryProblem.chooser` is `{libraries: [{path, lastOpened, available, checking, reason}], selected, libraryOpen}` (else `null`; `libraryOpen: true` when it was opened over the last library with Alt). Each library is checked read-only on a worker thread of its own, never on the UI thread (the folder and its catalog file are looked at, never locked or written, so a library another program has @@ -364,8 +361,8 @@ lcc-cli run --connect 127.0.0.1:7980 develop.adjust control=light.exposure delta For MCP, use `lcc-cli mcp --connect 127.0.0.1:7980`: `run_command` reaches the commands above, `list_controls` / `set_develop` provide slider helpers, and `resources/read` polls -`://library`, `://photo/active`, `://develop/active` and -`://controls` ([mcp.md](mcp.md#resources)). Headless CLI/MCP mode owns a separate engine +`chromaforge://library`, `chromaforge://photo/active`, `chromaforge://develop/active` and +`chromaforge://controls` ([mcp.md](mcp.md#resources)). Headless CLI/MCP mode owns a separate engine session; use connect mode for feedback from edits in the desktop app. ## Headless rendering (no window, no GPU) @@ -377,22 +374,22 @@ scissor clipping as egui's GPU backends, so the image matches the window (minus - **In the running app:** `{"method": "ui.screenshot", "params": {"path": "a.png", "headless": true}}`. The UI is drawn into an offscreen context from the app's logic tick, which keeps running when the window is occluded or the display sleeps/locks. Windowed screenshots fall back to this after 2 s. -- **Without any app window:** ` snapshot` runs a whole app session headlessly. +- **Without any app window:** `chromaforge-cli snapshot` runs a whole app session headlessly. Photo development also defaults to the CPU, so the initial frames do not discover a GPU adapter - or load a graphics driver. `_GPU=1` does not opt snapshots back into GPU rendering. + or load a graphics driver. `CHROMAFORGE_GPU=1` does not opt snapshots back into GPU rendering. This applies only to the snapshot session: even `--library DIR` leaves the desktop app's saved `ui.json` preferences untouched. It answers the same control requests (same handler) from a JSON-lines script: ```text - snapshot --demo -o grid.png --size 1600x1000 [--scale 2] - snapshot --library DIR --script tour.jsonl -o shot.png +chromaforge-cli snapshot --demo -o grid.png --size 1600x1000 [--scale 2] +chromaforge-cli snapshot --library DIR --script tour.jsonl -o shot.png ``` Headless screenshot dimensions must be finite and at least one logical point, with a finite, positive scale. Rounded output must be at least one pixel per edge, at most 16,384 pixels per edge and 64 million pixels in total. `snapshot` and `ui.resize` reject requests outside these limits before layout or rasterization; supplied resize dimensions must be numbers. -An interface zoom (egui's zoom factor; the keyboard never changes it — ⌘= / ⌘− / ⌘0 zoom the +An interface zoom (egui's zoom factor; the keyboard never changes it — in the loupe ⌘= / ⌘− / ⌘0 zoom the photo, issue #566) changes text and control sizes while preserving the snapshot viewport's requested physical pixel dimensions. Later `ui.resize` requests use current egui points; validation and rasterization both convert them to native viewport points before rounding the output diff --git a/docs/control-surfaces.md b/docs/control-surfaces.md index c2314b1d91..2e96ce6a23 100644 --- a/docs/control-surfaces.md +++ b/docs/control-surfaces.md @@ -126,7 +126,7 @@ same. **No setup:** a control nothing binds does what its label says (Loupedeck's own default layout: the Exposure knob moves Exposure, P1–P8 the colour mixer, Undo undoes, the rating keys rate …). **Import:** Settings ▸ Controls ▸ Loupedeck+ lists the profiles Loupedeck's software keeps for the console on this computer -(`%LOCALAPPDATA%\Loupedeck\Applications\Loupedeck15\\Profiles\\ProfileInfo.json`, read only) with an +(`%LOCALAPPDATA%\Loupedeck\Applications\Loupedeck15\Chromaforge\Profiles\\ProfileInfo.json`, read only) with an **Import** button each, and **Import a Loupedeck profile…** takes a `ProfileInfo.json` or an exported `.lp5`; `cmd:surface.import` takes either too. The editor mode's layout (Loupedeck's `loupe` mode: its first workspace, then the Fn workspace for what that leaves empty) goes into every Chromaforge profile (the console has no pages), replacing @@ -136,21 +136,21 @@ Hue / Sat / Lum mode buttons). Code: `crates/surface/src/loupedeck.rs`. ### Installing the Logi plugin -The plugin is built in its own repository (`logi-plugin`: `scripts/package.ps1` → `dist/.lplug4`, a +The plugin is built in its own repository (`logi-plugin`: `scripts/package.ps1` → `dist/Chromaforge.lplug4`, a ZIP of the plugin DLL, its `metadata/` and its default profiles `profiles/DefaultProfile70.lp5` / `…71.lp5`). -Chromaforge looks for **`.lplug4` next to its executable** (or in `plugins/` beside it), or at -`_LOGI_PLUGIN`. *Install the plugin* (`cmd:surface.installPlugin`) writes the plugin's +Chromaforge looks for **`Chromaforge.lplug4` next to its executable** (or in `plugins/` beside it), or at +`CHROMAFORGE_LOGI_PLUGIN`. *Install the plugin* (`cmd:surface.installPlugin`) writes the plugin's `%LOCALAPPDATA%\Logi\LogiPluginService\PluginData\Chromaforge\config.json` (the port Chromaforge listens on) and -runs `%ProgramFiles%\Logi\LogiPluginService\LogiPluginServiceTool.exe install-plugin .lplug4` — what +runs `%ProgramFiles%\Logi\LogiPluginService\LogiPluginServiceTool.exe install-plugin Chromaforge.lplug4` — what double-clicking a `.lplug4` does. Logi Options+ then asks the user to confirm, installs the plugin into `…\LogiPluginService\Plugins\Chromaforge` and its profiles, and reloads its plugin service (Logi restarts it; the devices pause for a few seconds). *Remove the plugin* (`cmd:surface.uninstallPlugin`) runs `uninstall-plugin` the same way. `cmd:surface.plugin` reports `{status: {host, installed, package, packagePath}, busy, message}`. Nothing else in Logi Options+ is touched: other plugins, their profiles and the user's Options+ settings stay as they are. Windows -only for now; elsewhere the page says to open `.lplug4` by hand. +only for now; elsewhere the page says to open `Chromaforge.lplug4` by hand. -**Releases (maintainer decision).** A release that ships the plugin builds `.lplug4` from a pinned -`logi-plugin` commit (a .NET build on Windows) and puts it next to `.exe` in the Windows package (and +**Releases (maintainer decision).** A release that ships the plugin builds `Chromaforge.lplug4` from a pinned +`logi-plugin` commit (a .NET build on Windows) and puts it next to `chromaforge.exe` in the Windows package (and the macOS app's `Contents/MacOS` once the macOS path is verified). Without it Chromaforge runs as before and the page says no package came with it. Publishing the plugin on the Logi Marketplace instead is the other option; then Chromaforge would only link to it. @@ -163,10 +163,10 @@ Every action of the editor is also a command (`cmd:surface.profile`, `cmd:surfac ## Settings file -`control-surfaces.json` in Chromaforge's settings folder (next to `ui.json`; `_CONFIG_DIR` moves it). Written +`control-surfaces.json` in Chromaforge's settings folder (next to `ui.json`; `CHROMAFORGE_CONFIG_DIR` moves it). Written atomically half a second after a change. When the settings folder has none on start, the file is copied (never moved) from the first of the previous name's settings folders that has one (`[legacy] settings_dirs` in `brand.toml`); an -existing file is never overwritten, and a `_CONFIG_DIR` or portable folder is left alone. A damaged file, or +existing file is never overwritten, and a `CHROMAFORGE_CONFIG_DIR` or portable folder is left alone. A damaged file, or one from a newer Chromaforge, is reported (Settings ▸ Controls and a notice), kept as it is, and Chromaforge runs on the defaults until you change something. Every number is clamped into range on reading. diff --git a/docs/denoise.md b/docs/denoise.md index 22880ccd32..642fa36cf6 100644 --- a/docs/denoise.md +++ b/docs/denoise.md @@ -1,8 +1,5 @@ # AI Denoise -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - Edit ▸ Detail ▸ **AI Denoise** is a per-photo switch above **Amount** (0–100). Turning it on starts at 50, or preserves an already positive Amount. Turning it off preserves Amount and mixes none of the cleaned picture. Like the sliders, it follows @@ -147,7 +144,7 @@ ISO 6400 up. ## Models and terms (optional) **No model weights are bundled** (the built-in denoiser needs none). Models live in the per-user `denoise-models` folder -(override with `_DENOISE_MODELS`). Settings provides **Install from file…** +(override with `CHROMAFORGE_DENOISE_MODELS`). Settings provides **Install from file…** for a user-supplied ONNX file with a `denoise-model.json` beside it. The default library build offers no model downloads (see the upstream project's own model below). The separate `rawnind-model` Cargo feature enables the pinned RawNIND offer only when a release's model policy permits it. @@ -173,10 +170,10 @@ It is downloaded from two sources, tried in order: A source that can't be reached, refuses, or sends a file of another size or SHA-256 is passed over for the next; a wrong file is never kept, whichever source sent it, and with both failing the message names each. The pinned size (31,091,398 bytes) and SHA-256 (`abd3c4cd…3247dea9`) are checked wherever the file comes from. There is no third -source: `_DENOISE_MODEL_URL` (an `https://` address) replaces both with that one address, for maintainers who +source: `CHROMAFORGE_DENOISE_MODEL_URL` (an `https://` address) replaces both with that one address, for maintainers who host the same file themselves. -With the file at hand, `_TEST_OWN_DENOISE_MODEL= cargo test --release -p lcc-engine --features denoise +With the file at hand, `CHROMAFORGE_TEST_OWN_DENOISE_MODEL= cargo test --release -p lcc-engine --features denoise tests_denoise_own -- --nocapture` runs it for real: a noisy raw developed with it against the best manual Noise Reduction (the Rust form of `tools/denoise-train/eval_app.py`), the graphics card against the processor, a damaged copy (an error, never a panic), and with `--ignored` a 24 MP timing against the built-in denoiser. @@ -317,15 +314,15 @@ A laptop can hand tiles to a desktop with a bigger graphics card over a LAN or a selected model the way the app does (the card when it can run it, checked against the CPU first; else the CPU): ```text -export _DENOISE_TOKEN='a long random string, at least 16 characters' +export CHROMAFORGE_DENOISE_TOKEN='a long random string, at least 16 characters' lcc-cli denoise-serve --listen 100.101.102.103:7990 # e.g. the machine's Tailscale address ``` On the laptop, before the app starts: ```text -export _DENOISE_URL=100.101.102.103:7990 -export _DENOISE_TOKEN='…the same token…' +export CHROMAFORGE_DENOISE_URL=100.101.102.103:7990 +export CHROMAFORGE_DENOISE_TOKEN='…the same token…' ``` When the laptop first uses the model it greets the server and times a check tile there and back. If that is faster @@ -370,7 +367,18 @@ Native apps enable inference through their `denoise` feature. A build without it the web build report inference unavailable. Manifest/cache primitives still compile for WASM. Settings and models remain opt-in; nothing is downloaded on launch. -This implementation supports **Bayer RAW only**. X-Trans, Foveon, demosaiced DNG and -non-RAW images remain unsupported by this model contract. No measured quality parity -with Lightroom is claimed. Apple/Metal and wider hardware verification, model policy, +The model contract itself is **Bayer only**. A non-Bayer colour filter array — Fujifilm's +X-Trans, and any other pattern laid out in red, green and blue — reaches it through a +re-mosaic: the sensor is interpolated and read back as an RGGB mosaic of the same size +(`remosaic_rggb`, `crates/raw/src/demosaic`), so the picture keeps its resolution and every +step after the model is unchanged. It interpolates only the colour each site needs, without +the full RGB picture in between: on a 26 MP X-Trans frame it takes ~65 ms (a full demosaic +~80 ms) and holds three planes at once, the mosaic, its green and the RGGB copy, under its +own share of the working-memory gate. 39 % of the frame's sites already carry the colour +RGGB wants there and keep the sensor's own sample, and reading the result back as RGB comes +within 42 dB (PSNR) of demosaicing the X-Trans mosaic directly. The rest reach the model +already interpolated, so it sees noise that varies from site to site: this is an +approximation of an X-Trans sensor, not a model trained on one, and its quality is +unmeasured. Foveon, demosaiced DNG and non-RAW +images remain unsupported. No measured quality parity with Lightroom is claimed. Apple/Metal and wider hardware verification, model policy, a linear-RGB contract and a side-by-side fidelity suite remain future work. diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 1930652686..cf6ebfc3d3 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -1,15 +1,15 @@ # Diagnostics recorder `crates/diag` (`lcc-diag`, layer L0) answers one question: *what was this process doing when it hung, was killed, -ran out of memory or panicked?* It is off unless `_DIAG` is set, writes only to a local folder, and sends +ran out of memory or panicked?* It is off unless `CHROMAFORGE_DIAG` is set, writes only to a local folder, and sends nothing anywhere (issue #1363). ## Turning it on | Variable | Meaning | |---|---| -| `_DIAG` | Levels to record. A bare level sets every subsystem, `name=level` overrides one; order doesn't matter and the last entry for a subsystem wins. Words are not case-sensitive. `1`, `on`, `true` and `yes` mean `normal`; `0`, `off`, `false` and `no` mean off; unset, empty, or a list that records nothing (`off`, `off,probe=0`) leaves the recorder off. | -| `_DIAG_DIR` | Where the files go. Default: `diag/` in the settings folder (the one `_CONFIG_DIR` and portable mode choose). Set but empty: no folder. | +| `CHROMAFORGE_DIAG` | Levels to record. A bare level sets every subsystem, `name=level` overrides one; order doesn't matter and the last entry for a subsystem wins. Words are not case-sensitive. `1`, `on`, `true` and `yes` mean `normal`; `0`, `off`, `false` and `no` mean off; unset, empty, or a list that records nothing (`off`, `off,probe=0`) leaves the recorder off. | +| `CHROMAFORGE_DIAG_DIR` | Where the files go. Default: `diag/` in the settings folder (the one `CHROMAFORGE_CONFIG_DIR` and portable mode choose). Set but empty: no folder. | Levels, least verbose first: `critical` (a step that runs once per user action and matters after a kill, and panics: written to disk at once), `normal` (stages and per-batch steps), `detail` (work that runs after every command), @@ -21,7 +21,7 @@ Subsystems: `app` (the recorder itself: start, panics, configuration), `import` `probe` (reading files before an import, a reload, a recheck or reading originals), `commit` (a Lightroom catalog import's commit and its stages), `catalog` (writing the library after a command). -A run that keeps no settings (`--memory`, `--demo`, `_NO_PREFS`) records only when `_DIAG_DIR` names a +A run that keeps no settings (`--memory`, `--demo`, `CHROMAFORGE_NO_PREFS`) records only when `CHROMAFORGE_DIAG_DIR` names a folder. `--version` and `--help` record nothing. The app and the CLI log where they record, or why they don't (no folder, a folder that can't be created). diff --git a/docs/duplicates.md b/docs/duplicates.md index 999470fae1..18fd2f0909 100644 --- a/docs/duplicates.md +++ b/docs/duplicates.md @@ -1,7 +1,5 @@ # Duplicate Finder -> Names in angle brackets (``, ``, …) are the values set in [`brand.toml`](../brand.toml). - Library ▸ Find Duplicates… (issue #1107) finds the photos that are copies of one another across the whole library, so the re-imported, resized or renamed copies can be cleaned out while the best copy of each stays. What it finds, and what the window's buttons do: @@ -36,7 +34,7 @@ of each stays. What it finds, and what the window's buttons do: The same scan is the `library.findDuplicates` command (`{similar?: true}`), which returns the groups with each photo's id, name, path, resolution, file size and import date for the control channel and -MCP; the CLI renders it through ` mcp` or a control script like any other command. Not in the +MCP; the CLI renders it through `chromaforge-cli mcp` or a control script like any other command. Not in the web build: the similar scan reads the photos' files. ## What is deliberately not there diff --git a/docs/faces.md b/docs/faces.md index 8d2ac96a31..10708ecaaf 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -1,8 +1,5 @@ # Faces -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - The app reads the face names other apps (Lightroom, digiKam…) write into your photos, shows them in the loupe (boxes you can switch off, resize and remove) and groups photos by person in the People view. This page is about the *models* that find and recognise faces by themselves. @@ -78,7 +75,8 @@ The actions are: - **Detect and Recognize**: search unsearched photos that have no face regions, then embed existing and newly found boxes that do not yet have embeddings. -- **Recognize Existing Faces**: embed existing face boxes that do not yet have an embedding; does not run the detector. +- **Recognize Existing Faces**: embed existing face boxes that do not yet have an embedding. No faces are looked for and + none are added; the face model still runs, so each face is aligned by its landmarks as the background scan does. - **Scan New Items**: process only photos not yet marked as searched: detect faces where a photo has no face region and embed any existing face boxes that still need it. Already-searched photos are skipped. - **Rebuild All Embeddings** / **Rebuild Named Faces**: forget and recompute the selected model's embeddings for all @@ -88,15 +86,17 @@ The actions are: regions, are preserved in either mode. A recognition model is needed for every scan action; reset does not require a model. Detection actions also need the face -detector model. The progress is a cancellable activity task. `faces.scanStatus` reports the scoped pass, +detector model, and every action that embeds faces uses it, when it is installed, to align them (without it they are cut +by their boxes; see [How much the alignment matters](#how-much-the-alignment-matters)). The progress is a cancellable +activity task. `faces.scanStatus` reports the scoped pass, `activity.cancel {id: taskId}` stops queued work, and `faces.pause` / `faces.resume` stop or restart new photos from being queued; photos already in flight are allowed to finish. The same saved pause setting controls the continuous face scan. A cancel may let a small number of already-running photos finish. The CLI and MCP use the same engine commands. For example: ```sh - run --library DIR faces.maintain mode=detect folder=/Photos/Trip includeSubfolders=true - run --library DIR faces.scanStatus +chromaforge-cli run --library DIR faces.maintain mode=detect folder=/Photos/Trip includeSubfolders=true +chromaforge-cli run --library DIR faces.scanStatus ``` MCP clients can use `cmd_faces_maintain`, `cmd_faces_scanStatus`, `cmd_faces_reset`, or `command_run`. @@ -173,8 +173,8 @@ vector per face. A bad entry is reported in Settings ▸ Faces and skipped; the (Add a model file…) is recognised by its hash and gets the terms you wrote. Models you cannot or do not want to list can still be added by file; non-commercial models are never offered by the built-in list. -The models folder is `/models` (`%APPDATA%\\models` on Windows, `~/Library/Application Support//models` -on macOS, `~/.config//models` on Linux), or `$_FACE_MODELS`. The desktop app, the CLI and the MCP +The models folder is `/models` (`%APPDATA%\Chromaforge\models` on Windows, `~/Library/Application Support/Chromaforge/models` +on macOS, `~/.config/Chromaforge/models` on Linux), or `$CHROMAFORGE_FACE_MODELS`. The desktop app, the CLI and the MCP server share it. ## What is known about the models the app recognises @@ -236,7 +236,7 @@ The CPU interpreter remains the reference. After a model loads, a background che the GPU for faces") runs a 1-probe output check against the CPU (`1e-3` relative tolerance in FP32, `1e-2` in FP16) and, when not yet cached for `(driver/adapter, program fingerprint, precision)` in the on-disk plan cache (`face-models/.gpu-cache/plan-*.bin`), benchmarks an 8-face batch against the CPU. Until the check succeeds, and -whenever the GPU is switched off (`_GPU=0`, `_GPU_BACKEND=off`, the GPU preference, or **Settings ▸ +whenever the GPU is switched off (`CHROMAFORGE_GPU=0`, `CHROMAFORGE_GPU_BACKEND=off`, the GPU preference, or **Settings ▸ Faces ▸ Face models device: CPU**), missing, wrong or slower, the model runs on the CPU. The first GPU error, or a result of the wrong size or with non-finite values, drops it for that model. Settings ▸ Faces shows which device and precision each model runs on (`faces.gpu`, with `card`: `second` or `editing`). When a multi-GPU card stops working, @@ -333,7 +333,7 @@ suggest names for the ones you have not: Naming a face also makes it one of the faces the others are compared with, so the suggestions improve as you go. - Faces come from the names other apps wrote into your photos (read from XMP), from Library ▸ Detect Faces, or both. A face is aligned using the detector's five landmarks (eyes, nose, mouth corners) when it finds the same face, and cut out by its box - otherwise. Each face goes through the model twice, as it is and mirrored left to right, and the two results are averaged + otherwise, in every scan (the background one and Face Maintenance alike). Each face goes through the model twice, as it is and mirrored left to right, and the two results are averaged (issue #1920): the same person then matches more often. On 1,800 LFW pairs with AuraFace v1, at its match bar of 0.40, 94.3 % of a person's pairs matched instead of 93.1 % (92.9 % instead of 89.3 % for faces 37 pixels wide, 82.4 % instead of 76.8 % at 24 pixels), and no pair of two different people matched either way. It doubles the time the model takes per @@ -371,10 +371,10 @@ Turning recognition on starts a scan of the whole library, once, in the backgrou when light (2 threads). - **Memory** limits the number of photos at once as much as the processor does: a photo in progress holds about 180 MB (peak memory grew by that much per extra worker), so at most half of the memory budget (a quarter of the RAM, at most - 16 GiB, unless `_MEMORY_MB` says otherwise; a container's or cgroup's memory limit counts as the RAM when + 16 GiB, unless `CHROMAFORGE_MEMORY_MB` says otherwise; a container's or cgroup's memory limit counts as the RAM when smaller) is given to them: about four photos per 1.5 GiB of budget, whatever the core count. Eight at once was not much faster and needed about twice the memory (a 2.0 GB peak against - 1.1 GB). `_FACE_THREADS` replaces these limits with a number of your own. A couple more photos wait behind + 1.1 GB). `CHROMAFORGE_FACE_THREADS` replaces these limits with a number of your own. A couple more photos wait behind the running ones, so a worker that finishes has its next photo at once. - **Earlier scan speed (a different runner).** A mixed raw and JPEG library of 184 photos (the raws read through their embedded previews, 73 photos searched for faces) took about 29 seconds on that machine at full pace: roughly 6 photos a second, so the first scan of 10,000 photos @@ -405,6 +405,12 @@ The unnamed faces follow the sidebar: pick a year, a folder or an album and only same goes for their faces and the **More** suggestions (`faces.person {scope: "filter"}`), so you can go through one year at a time; their faces anywhere still teach the match, and the face count in the header stays the whole library's. +A person's page has a **sort picker** next to its title (kept across restarts, `person.sort` for scripts): **Import +Order**, the order the photos came into the library; **Oldest First** and **Newest First**, by capture time (to see +someone grow up or age; photos without a capture time come last either way); **Folder**, path and then file name; and +**Largest Face**, the biggest close-up first, to pick a good portrait (`faces.person {sort}` orders the faces the same +ways). + Right-click a person's card, or use **Rename Person…** on their page, to rename every face of that person in the library at once (`faces.renamePerson`). The name is matched the way the cards are grouped (trimmed, ignoring capitalization) and every matching face is stored with the exact new spelling, so a change of capitalization alone updates them all. The @@ -497,6 +503,24 @@ shot), so check a model on your own photos before trusting it: (ignoring shots taken within a few seconds of it, which would make it too easy) and reports, for each threshold, how many suggestions it would make and how many were right. +### How much the alignment matters + +Recognition models are trained on faces aligned to their landmarks, and some take a face cut by its box much worse than +others. Measured with the app's own detector, crops and models on 3,360 public photographs (LFW) of 1,680 people, each +face cut three ways, mirror averaging off, on the CPU. "Stray" pairs are pairs of two different people that pass the +model's own bar, out of 5,641,440: + +| How the face was cut | SFace: a person's own pairs at 0.55 | SFace: stray pairs | AuraFace v1: a person's own pairs at 0.40 | AuraFace v1: stray pairs | +| --- | ---: | ---: | ---: | ---: | +| by the detector's landmarks | 91.5 % | 5 | 93.9 % | 146 | +| by the detector's own box, 1.5× padded | 63.0 % | 77,472 | 91.0 % | 361 | +| by a box 1.9× the detector's, 1.5× padded | 88.8 % | 2,847,334 | 72.1 % | 1,005,680 | + +The second row is what every scan that only embeds faces did from 26.48.1 to 26.48.2 (issue #1616: the detector was only +attached when faces were looked for). The third is still what a region gets when no detection overlaps it by 0.3, which a +box from another tool or one drawn by hand can easily be: such faces look alike to the model, so they match whoever else +was cut that way, while a person's own aligned faces score low against them. + ## Face pictures in the People view Each face on a person card, in Unnamed faces and on a person's page is a square around the face, about 1.7 times the @@ -528,11 +552,19 @@ profiles, so an edit, another square or a new renderer makes a new picture, and without reading the originals. Tile sizes are rounded up to a multiple of 16 px, so moving the thumbnail slider reuses the pictures of its step instead of rendering every face again. +**Library ▸ Faces ▸ Build Face Thumbnails** (`faces.buildThumbnails`) renders a tile of every face in the library +(the ignored ones aside) at one tile edge ahead of the scrolling that would otherwise build them one by one — on a +library with hundreds of people, the slow part of People. `edge` is the size the tiles are asked for now (the app +passes what the People view is showing; the CLI's default is 256); tiles in the cache already cost a lookup. It runs +in the background on two lanes (a cancellable row in the activity stack), `wait: true` runs it where the call is, +`status` reports the last run (`{active, done, total, built, failed, cancelled, edge}`) and `cancel` stops it; +`lanes` 1..8 chooses how many build side by side with `wait`. + ## Commands All of this is reachable from the control channel, the CLI and MCP: `faces.models.list`, `faces.models.inspect {path}`, `faces.models.install {path, acknowledged: true, activate?}`, `faces.models.download {id, acknowledged: true}` (then `faces.models.downloads`, which also installs what has arrived, and `faces.models.downloadCancel {id}`), `faces.models.remove {id}`, `faces.models.select {id}`, -`faces.enable {enabled?}`, `faces.detect {ids?, apply?}`, `faces.index {budgetMs?, ids?}`, `faces.maintain {mode?, scope?, ids?, folder?, folders?, album?, albums?, includeSubfolders?, minScore?, behavior?}`, `faces.scanStatus`, `faces.reset {confirmed: true}`, `faces.pump` (what the app calls every frame), `faces.suggest {ids?, threshold?, margin?}`, `faces.person {name, more?}` (a person's faces and the unnamed faces that look like them), `faces.unnamed {limit?, bySuggestion?, budgetMs?}` (every unnamed face, look-alikes together, with suggested names found across the whole library; `scan` says how far that comparison is), `faces.setName {id?, index, name}`, `faces.nameFaces {faces: [{photo, index}], name}` (name many at once, one undo step), `faces.renamePerson {from, to, merge?}` (rename every in-library face of one person, or merge two when `merge` is true, one undo step), `faces.confirmSuggestions {faces}` and `faces.rejectSuggestions {faces}` (the Suggested category's decisions: name the faces what is suggested for them now, one undo step; or keep them unknown and suggest that person no more), `faces.undoSuggestionDecision {faces}` (forget a decision, so the suggestion is back) and `faces.suggestionDecisions {photo?}` (what was decided, a page at a time), and `faces.evaluate`. `faces.unnamed {bySuggestion: true}` also answers `groups`: the suggested faces under the person suggested, the most faces first. Neither a confirmation nor a rejection writes to a photo's sidecar: a confirmation is a name on a face region (catalog only, undoable), a rejection is a line in `people.json`. `acknowledged` must be `true`: the caller has shown the user the terms and the user agreed. Installing makes the model the one in use and switches recognition on unless `activate` is `false`. +`faces.enable {enabled?}`, `faces.detect {ids?, apply?}`, `faces.index {budgetMs?, ids?}`, `faces.maintain {mode?, scope?, ids?, folder?, folders?, album?, albums?, includeSubfolders?, minScore?, behavior?}`, `faces.scanStatus`, `faces.reset {confirmed: true}`, `faces.pump` (what the app calls every frame), `faces.suggest {ids?, threshold?, margin?}`, `faces.person {name, more?, sort?, scope?}` (a person's faces and the unnamed faces that look like them; `sort` orders the faces shown: `photo` (import order, the default), `oldest`/`newest` (capture time), `folder` or `faceSize`), `faces.unnamed {limit?, bySuggestion?, budgetMs?}` (every unnamed face, look-alikes together, with suggested names found across the whole library; `scan` says how far that comparison is), `faces.setName {id?, index, name}`, `faces.nameFaces {faces: [{photo, index}], name}` (name many at once, one undo step), `faces.renamePerson {from, to, merge?}` (rename every in-library face of one person, or merge two when `merge` is true, one undo step), `faces.confirmSuggestions {faces}` and `faces.rejectSuggestions {faces}` (the Suggested category's decisions: name the faces what is suggested for them now, one undo step; or keep them unknown and suggest that person no more), `faces.undoSuggestionDecision {faces}` (forget a decision, so the suggestion is back) and `faces.suggestionDecisions {photo?}` (what was decided, a page at a time), and `faces.evaluate`, and `faces.buildThumbnails {edge?, lanes?, wait?, status?, cancel?}` (build every face tile into the thumbnail cache ahead of People, see above). `faces.unnamed {bySuggestion: true}` also answers `groups`: the suggested faces under the person suggested, the most faces first. Neither a confirmation nor a rejection writes to a photo's sidecar: a confirmation is a name on a face region (catalog only, undoable), a rejection is a line in `people.json`. `acknowledged` must be `true`: the caller has shown the user the terms and the user agreed. Installing makes the model the one in use and switches recognition on unless `activate` is `false`. ## Find Blemishes diff --git a/docs/focus-points.md b/docs/focus-points.md index c9ca6aee51..3697cf6313 100644 --- a/docs/focus-points.md +++ b/docs/focus-points.md @@ -17,7 +17,7 @@ zooms to it, so checking whether the subject is sharp takes one key while cullin centres on the active photo's point; per-pane focus zoom is a follow-up. - **Info panel**: a *Focus* row says how the camera focused, e.g. `AF-C · Wide · Animal Eye Tracking` (focus mode, the AF area set on the camera, and what it tracked when the camera says). -- **Agents**: `photo.inspect` (and the MCP `://photo/active` resource) returns it as `meta.focus`: +- **Agents**: `photo.inspect` (and the MCP `chromaforge://photo/active` resource) returns it as `meta.focus`: `{rect: {x0, y0, x1, y1}, mode?, area?, tracking?}`, the box normalized to the upright (EXIF-oriented) photo, y down. Photos without one have no `focus` key. `view.zoomToggle` replies `{focus: [x, y]}` (the pan it centred on) when it zoomed to one. @@ -129,11 +129,11 @@ DMF (AF, then manual touch-up) keeps its point. ## Code - `crates/meta/src/focus.rs`: the decoder (bounded; hostile values give no point, never a panic) and its tests, - including an opt-in test over real files (`_FOCUS_SAMPLES=`). + including an opt-in test over real files (`CHROMAFORGE_FOCUS_SAMPLES=`). - `crates/meta/src/focus_read.rs`: the header-only read; its tests check it against the whole-file read on intact, truncated and corrupted files and count what it reads. - `crates/engine/src/focus_scan.rs`: the background job (`photo.readFocusPoints`, `focus.pump`) and `crates/engine/src/tests_focus_scan.rs`, with an opt-in comparison over real files - (`_FOCUS_FILES=`); `crates/ui-egui/src/focus_scan.rs` drives it from the frame loop. + (`CHROMAFORGE_FOCUS_FILES=`); `crates/ui-egui/src/focus_scan.rs` drives it from the frame loop. - `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `focus_pan`, `draw_focus_point`): mapping through the user's rotation and crop, the overlay, and the zoom target; `crates/ui-egui/src/tests_focus_point.rs`. diff --git a/docs/fuji-lens-corrections.md b/docs/fuji-lens-corrections.md index a303b9728f..a6b0690f9b 100644 --- a/docs/fuji-lens-corrections.md +++ b/docs/fuji-lens-corrections.md @@ -162,4 +162,4 @@ before demosaicing would be needed. - `crates/raw/src/vendor/raf.rs`: a synthetic RAF through header and full decode, only for validated models, and a DNG round trip. - `crates/raw/tests/it/corpus.rs` `fuji_embedded_lens_tables_follow_the_validated_models`: the corpus' `raf-fuji-*` files, - or any folder of RAFs in `_FUJI` (the pixls set: 129 decoded, 88 warps, 98 vignette gains). + or any folder of RAFs in `CHROMAFORGE_FUJI` (the pixls set: 129 decoded, 88 warps, 98 vignette gains). diff --git a/docs/gaps.md b/docs/gaps.md index 9ffda1d8a6..99b14b101e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ - 2026-10-12: Print colour management (G15): printer ICC profile, Perceptual / Relative with black point compensation, Print Adjustment, 16-bit PDF output. -> **Last updated:** 2026-11-29 · **Change:** patch (gap 36 narrows: the file-name templates shared by Export, Rename Photos and import take every stored metadata field as a token — caption, headline, category, keywords, copyright, job title, location fields, camera serial, alt text, long description, caption writer, shutter, aperture, focal — #1584); patch (gap 41 narrows: a Lightroom import is committed and saved in parts, #1361); patch (gap 41 narrows: a large step is saved as many small log records, #1361); imported photos' metadata status compares their sidecars with the catalog, in step or a conflict, #1312); patch (gap 41 narrows: no row cap on Lightroom import tables, a memory budget from the computer instead, #1361); patch (gaps 13 and 41 narrow: cached-XMP records over 64 MiB and packets over 16 MiB are read without their camera-profile tables, #1311); patch (gap 39: ONNX Runtime on the GPU exists, #491; the aesthetic model is what is left); patch (gap 41 narrows: the recovery archive and the history settings budget follow the drive, the catalog and the memory, newest steps first, #1312); patch (feature-freeze parity pass: CF-PROCESS-RECIPES row restored, gap 43 cites the skin-uniformity row; no ranked gap closes); patch (#1360: scoped, cancellable face maintenance and confirmed reset; no ranked gap closes); patch (gap 42 narrows: OpenEXR scene-linear export, plan 7.5); minor (gap 11: Lens Blur renders from the depth model or the subject, focus picker and bokeh shapes, plan 7.1); patch (gap 16: plug-in publish services get the account, collection, photo metadata and remote comments, plan 7.14); patch (gap 43 narrows: skin-tone uniformity on Point Color, plan 7.9); patch (gap 43: Match Look, Capture One's Smart Adjustments, plan 7.6); minor (gap 18 narrows: lens corrections, Upright and Transform on video frames, poster frame picked, plan 7.11); patch (gap 43 narrows: process recipes, several export presets in one run with one decode per photo, plan 7.4); minor (gap 42 narrows: Tone Equalizer ported from darktable, plan 7.10); minor (gap 42 narrows: inpaint opposed and guided Laplacian highlight reconstruction, ported from darktable, plan 7.2); minor (adaptive presets, plan 7.8; no gap change: P2 rows without a gap entry; adaptive profiles left); patch (the Export screen previews the first photo as its file will be, with an SDR / HDR choice; minor (HDR export: gain map files for AVIF and JPEG XL with `hdrMode: gainMap`, LR-HDR-EXPORT; no ranked gap closes); patch (gap 37: OS folder notifications, single-instance hand-off, URL scheme on Windows and Linux, plan 5.9); patch (gap 43 narrows: speed-edit keys, hold a key and drag or scroll to move a Develop slider, plan 5.10); patch (gap 23: the brush by keyboard; Library and Develop core widgets checked in the AccessKit tree, plan 5.8); patch (gap 26: 100k wheel-scroll frame timed frame by frame, 3–5 ms median, within budget, plan 4.8); minor (gap 2 narrows: CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`, synthetic tests only); patch (gap 1: LibRaw matrices for about 400 newer bodies; every body with a pinned sample has colour matrices; SIL ΔE cross-check; no chart shots yet); patch (gap 8: lensfun's database fetched on first run, picked lens written to XMP, plan 3.9); minor (gap 10: SRF and S200 EXR RAF decode, 47 Olympus / OM bodies verified: 645 verified, 89% on a verified body; target not met); minor (gap 19: the plug-in marketplace — search, install, update, remove and opt-in automatic updates from an index of each plug-in's newest release, vetted and community tiers); patch (gap 9: weekly model-reference job for SAM 2.1, BiRefNet, EoMT and MediaPipe); patch (gap 1: LibRaw matrices for six newer bodies that used the neutral matrix, #451; no chart shots yet); patch (gap 3: render-fidelity reference suite with ΔE2000 / SSIM tolerances and a synthetic ColorChecker check, plan 3.5); patch (gap 3: process V10 applies the Tone Curve in a wide working space, #1142); patch (gap 1: one ranked colour-source order, a Lightroom calibration that loses to the per-photo JPEG fit serves converted DNGs only, #1119; Adobe Standard DNGs without a tone curve get their BaselineExposure once more, #1174); minor (gaps 41–43: Lightroom migration limits left from #1311 / #1312, darktable raw-processing depth, Capture One workflow features); patch (gap 9: PRs run changed-crate tests; the nightly full run covers macOS and Windows, files an issue when red, and blocks releases); patch (gap 40 closed: `apps/android` denies `indexing_slicing`, clippy runs on it in the Android check); patch (never-crash tooling: pure-Rust fuzz targets with a nightly long run; no gap change); patch (gap 40: `apps/cli` and the chart-profile dialog converted); patch (tests only: loopback mock servers for generative fill errors, publish uploads while the server is down and misbehaving IPP printers; slideshow export in SIL; no gap changes); patch (gap 9: nightly corpus + fonts run with a skip gate, GPU equivalence on software adapters); patch (gap 37: folder polling notices new dated folders in a photo tree); minor (gap 38 closed: mixed metadata across a selection, `photo.sharedMeta`); patch (gap 9: timing probes and benchmarks are opt-in `probe` skips, not `#[ignore]`); patch (gap 9: engine import → export → re-import SIL scenario); minor (gap 40 added: checked indexing in the UI; unconverted modules carry a tracked allow); patch (gap 31: the sync merge rules are property-tested in the SIL run); patch (gap 13: required-table record losses always warned; remaining Lightroom size limits listed, #1311); patch (gap 13: the Lightroom import index is no longer capped at 16 MiB, #1312); patch (gap 13: one bad Lightroom record costs only itself; keyword assignments streamed, #1311); minor (gap 19: signed plug-ins find updates in their author's feed, checked when the Plug-in Manager opens and installed by the user); minor (gap 19: plug-in author signatures pin a plug-in's signer, #1271); minor (People: the People view sorts faces into Unknown, Suggested and Confirmed, and reviews the suggested ones a person at a time, #1050); minor (gap 20: Nikon NEFX, NX Studio's merged pixel-shift images, decodes; ARQ pixel shift is what is left of pixel shift); minor (gap 13: Capture One develop settings — exposure, orientation, crop, flips, white balance); minor (gap 13: saved prints in Lightroom catalogs import as Saved Prints with their layout); minor (gap 33 closed: the translation coverage check reads `trf!` and the helpers that translate; gap 21 re-measured: every language has every interface message); minor (gap 19: plug-ins look at a photo's pixels, set its crop and make virtual copies, #891); minor (gap 5: AI mask edges follow the photo's, no outline under a raised Exposure, upstream #3298); minor (gap 11 narrows: AI Super Resolution and AI Sharpen with an opt-in upscaler, upstream #3493); minor (gap 11 narrows: AI Denoise for finished pictures, upstream #3279); patch (gap 36: the ISO country code is carried over in preset save and import, #784); minor (gap 5: AI masks as recipes computed on the AI worker, Update AI Mask, masks under geometry, a Color Mixer per mask); patch (gap 26: smoother edits and lasting previews); minor (gap 5: Object masks can run on SAM 2.1, an open model, ported from OneSlips); minor (gap 12: generative remove through cloud providers with your own key, from OneSlips); minor (gap 36: the IPTC Content fields — headline, description writer, category, supplemental categories, subject codes — are stored, so Lightroom metadata presets carry them); minor (gap 19: plug-ins add a tool's files to the library, stacked or in the source album); minor (gap 19: plug-ins start installed programs; plug-in work no longer on hold); minor (gap 11: AI Denoise works out of the box with a built-in BM3D denoiser, upstream #2982); minor (gap 1: colour-chart calibration); patch (gap 1: calibrations matched to other editors); minor (gap 11 shrinks: the upstream project's own AI Denoise model is a download in the desktop app); patch (gap 3: probe DNGs and slider sweeps); minor (gap 1: dcraw's colour matrices replace the neutral fallback for about 550 models); patch (gap 3: `calibrate-lightroom verify`, edited raws against edited exports); patch (gap 3: ` compare`, ΔE00 between renders from any editor); minor (gaps 1 and 3: Lightroom-matched calibration tool, 0 cameras calibrated yet); minor (upstream merge: gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: grid-cycle key shown in View, #2500; gap 21: Thai glyphs in export text, #2052; gap 15: Japanese photo and postcard paper sizes); patch (HDR zoom: recent windows kept, encoded off the UI thread); patch (HDR adjustment previews: review follow-up); minor (upstream merge: gap 38 added: multi-select metadata editing UI, upstream's gap 30; XMP foreign namespaces and PSD/PSB embedded metadata, no gap change); patch (HDR adjustment previews keep float HDR output during slider drags); minor (opt-in Windows VRR compositor workaround); minor (gap 37 added: folder watching leftovers after issue #123's polling); minor (gap 36 added: what preset import doesn't carry over); minor (M15 decisions: CMYK won't do; Flickr / SmugMug and tethering blocked); minor (gap 11: the Enhance dialog); minor (gap 14 closed: HDR renders on the GPU; X11 SDR is a platform limit); minor (gap 14 narrows: zoomed, Before/After, Compare and second window show HDR, HDR Preview toggle); minor (gap 11 narrows: Raw Details and Super Resolution; gap 18: M14 closed, interlaced H.264 and faster AV1); minor (full audit 2026-10-20: rows refreshed against code; gaps 8 and 2 no longer beta blockers; gaps 34–35 added: Android camera roll and built-in camera; gap 34 narrows: picked folders rescanned); minor (gap 29 narrows: JPEG response curves and half-float frames) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last updated:** 2026-11-30 · **Change:** minor (People: a person's page sorts their faces — import order, capture time oldest or newest first, folder, largest face — and Library ▸ Faces ▸ Build Face Thumbnails builds every face tile into the thumbnail cache ahead of the view, #1691; no ranked gap closes); patch (gap 41 narrows: a Lightroom import is committed and saved in parts, #1361); patch (gap 41 narrows: a large step is saved as many small log records, #1361); imported photos' metadata status compares their sidecars with the catalog, in step or a conflict, #1312); patch (gap 41 narrows: no row cap on Lightroom import tables, a memory budget from the computer instead, #1361); patch (gaps 13 and 41 narrow: cached-XMP records over 64 MiB and packets over 16 MiB are read without their camera-profile tables, #1311); patch (gap 39: ONNX Runtime on the GPU exists, #491; the aesthetic model is what is left); patch (gap 41 narrows: the recovery archive and the history settings budget follow the drive, the catalog and the memory, newest steps first, #1312); patch (feature-freeze parity pass: CF-PROCESS-RECIPES row restored, gap 43 cites the skin-uniformity row; no ranked gap closes); patch (#1360: scoped, cancellable face maintenance and confirmed reset; no ranked gap closes); patch (gap 42 narrows: OpenEXR scene-linear export, plan 7.5); minor (gap 11: Lens Blur renders from the depth model or the subject, focus picker and bokeh shapes, plan 7.1); patch (gap 16: plug-in publish services get the account, collection, photo metadata and remote comments, plan 7.14); patch (gap 43 narrows: skin-tone uniformity on Point Color, plan 7.9); patch (gap 43: Match Look, Capture One's Smart Adjustments, plan 7.6); minor (gap 18 narrows: lens corrections, Upright and Transform on video frames, poster frame picked, plan 7.11); patch (gap 43 narrows: process recipes, several export presets in one run with one decode per photo, plan 7.4); minor (gap 42 narrows: Tone Equalizer ported from darktable, plan 7.10); minor (gap 42 narrows: inpaint opposed and guided Laplacian highlight reconstruction, ported from darktable, plan 7.2); minor (adaptive presets, plan 7.8; no gap change: P2 rows without a gap entry; adaptive profiles left); patch (the Export screen previews the first photo as its file will be, with an SDR / HDR choice; minor (HDR export: gain map files for AVIF and JPEG XL with `hdrMode: gainMap`, LR-HDR-EXPORT; no ranked gap closes); patch (gap 37: OS folder notifications, single-instance hand-off, URL scheme on Windows and Linux, plan 5.9); patch (gap 43 narrows: speed-edit keys, hold a key and drag or scroll to move a Develop slider, plan 5.10); patch (gap 23: the brush by keyboard; Library and Develop core widgets checked in the AccessKit tree, plan 5.8); patch (gap 26: 100k wheel-scroll frame timed frame by frame, 3–5 ms median, within budget, plan 4.8); minor (gap 2 narrows: CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`, synthetic tests only); patch (gap 1: LibRaw matrices for about 400 newer bodies; every body with a pinned sample has colour matrices; SIL ΔE cross-check; no chart shots yet); patch (gap 8: lensfun's database fetched on first run, picked lens written to XMP, plan 3.9); minor (gap 10: SRF and S200 EXR RAF decode, 47 Olympus / OM bodies verified: 645 verified, 89% on a verified body; target not met); minor (gap 19: the plug-in marketplace — search, install, update, remove and opt-in automatic updates from an index of each plug-in's newest release, vetted and community tiers); patch (gap 9: weekly model-reference job for SAM 2.1, BiRefNet, EoMT and MediaPipe); patch (gap 1: LibRaw matrices for six newer bodies that used the neutral matrix, #451; no chart shots yet); patch (gap 3: render-fidelity reference suite with ΔE2000 / SSIM tolerances and a synthetic ColorChecker check, plan 3.5); patch (gap 3: process V10 applies the Tone Curve in a wide working space, #1142); patch (gap 1: one ranked colour-source order, a Lightroom calibration that loses to the per-photo JPEG fit serves converted DNGs only, #1119; Adobe Standard DNGs without a tone curve get their BaselineExposure once more, #1174); minor (gaps 41–43: Lightroom migration limits left from #1311 / #1312, darktable raw-processing depth, Capture One workflow features); patch (gap 9: PRs run changed-crate tests; the nightly full run covers macOS and Windows, files an issue when red, and blocks releases); patch (gap 40 closed: `apps/android` denies `indexing_slicing`, clippy runs on it in the Android check); patch (never-crash tooling: pure-Rust fuzz targets with a nightly long run; no gap change); patch (gap 40: `apps/cli` and the chart-profile dialog converted); patch (tests only: loopback mock servers for generative fill errors, publish uploads while the server is down and misbehaving IPP printers; slideshow export in SIL; no gap changes); patch (gap 9: nightly corpus + fonts run with a skip gate, GPU equivalence on software adapters); patch (gap 37: folder polling notices new dated folders in a photo tree); minor (gap 38 closed: mixed metadata across a selection, `photo.sharedMeta`); patch (gap 9: timing probes and benchmarks are opt-in `probe` skips, not `#[ignore]`); patch (gap 9: engine import → export → re-import SIL scenario); minor (gap 40 added: checked indexing in the UI; unconverted modules carry a tracked allow); patch (gap 31: the sync merge rules are property-tested in the SIL run); patch (gap 13: required-table record losses always warned; remaining Lightroom size limits listed, #1311); patch (gap 13: the Lightroom import index is no longer capped at 16 MiB, #1312); patch (gap 13: one bad Lightroom record costs only itself; keyword assignments streamed, #1311); minor (gap 19: signed plug-ins find updates in their author's feed, checked when the Plug-in Manager opens and installed by the user); minor (gap 19: plug-in author signatures pin a plug-in's signer, #1271); minor (People: the People view sorts faces into Unknown, Suggested and Confirmed, and reviews the suggested ones a person at a time, #1050); minor (gap 20: Nikon NEFX, NX Studio's merged pixel-shift images, decodes; ARQ pixel shift is what is left of pixel shift); minor (gap 13: Capture One develop settings — exposure, orientation, crop, flips, white balance); minor (gap 13: saved prints in Lightroom catalogs import as Saved Prints with their layout); minor (gap 33 closed: the translation coverage check reads `trf!` and the helpers that translate; gap 21 re-measured: every language has every interface message); minor (gap 19: plug-ins look at a photo's pixels, set its crop and make virtual copies, #891); minor (gap 5: AI mask edges follow the photo's, no outline under a raised Exposure, upstream #3298); minor (gap 11 narrows: AI Super Resolution and AI Sharpen with an opt-in upscaler, upstream #3493); minor (gap 11 narrows: AI Denoise for finished pictures, upstream #3279); patch (gap 36: the ISO country code is carried over in preset save and import, #784); minor (gap 5: AI masks as recipes computed on the AI worker, Update AI Mask, masks under geometry, a Color Mixer per mask); patch (gap 26: smoother edits and lasting previews); minor (gap 5: Object masks can run on SAM 2.1, an open model, ported from OneSlips); minor (gap 12: generative remove through cloud providers with your own key, from OneSlips); minor (gap 36: the IPTC Content fields — headline, description writer, category, supplemental categories, subject codes — are stored, so Lightroom metadata presets carry them); minor (gap 19: plug-ins add a tool's files to the library, stacked or in the source album); minor (gap 19: plug-ins start installed programs; plug-in work no longer on hold); minor (gap 11: AI Denoise works out of the box with a built-in BM3D denoiser, upstream #2982); minor (gap 1: colour-chart calibration); patch (gap 1: calibrations matched to other editors); minor (gap 11 shrinks: the upstream project's own AI Denoise model is a download in the desktop app); patch (gap 3: probe DNGs and slider sweeps); minor (gap 1: dcraw's colour matrices replace the neutral fallback for about 550 models); patch (gap 3: `calibrate-lightroom verify`, edited raws against edited exports); patch (gap 3: ` compare`, ΔE00 between renders from any editor); minor (gaps 1 and 3: Lightroom-matched calibration tool, 0 cameras calibrated yet); minor (upstream merge: gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: grid-cycle key shown in View, #2500; gap 21: Thai glyphs in export text, #2052; gap 15: Japanese photo and postcard paper sizes); patch (HDR zoom: recent windows kept, encoded off the UI thread); patch (HDR adjustment previews: review follow-up); minor (upstream merge: gap 38 added: multi-select metadata editing UI, upstream's gap 30; XMP foreign namespaces and PSD/PSB embedded metadata, no gap change); patch (HDR adjustment previews keep float HDR output during slider drags); minor (opt-in Windows VRR compositor workaround); minor (gap 37 added: folder watching leftovers after issue #123's polling); minor (gap 36 added: what preset import doesn't carry over); minor (M15 decisions: CMYK won't do; Flickr / SmugMug and tethering blocked); minor (gap 11: the Enhance dialog); minor (gap 14 closed: HDR renders on the GPU; X11 SDR is a platform limit); minor (gap 14 narrows: zoomed, Before/After, Compare and second window show HDR, HDR Preview toggle); minor (gap 11 narrows: Raw Details and Super Resolution; gap 18: M14 closed, interlaced H.264 and faster AV1); minor (full audit 2026-10-20: rows refreshed against code; gaps 8 and 2 no longer beta blockers; gaps 34–35 added: Android camera roll and built-in camera; gap 34 narrows: picked folders rescanned); minor (gap 29 narrows: JPEG response curves and half-float frames) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 patch (gap 36 narrows: the file-name templates shared by Export, Rename Photos and import take every stored metadata field as a token — caption, headline, category, keywords, copyright, job title, location fields, camera serial, alt text, long description, caption writer, shutter, aperture, focal — #1584); patch (gap 41 narrows: a Lightroom import is committed and saved in parts, #1361); patch (gap 41 narrows: a large step is saved as many small log records, #1361); imported photos' metadata status compares their sidecars with the catalog, in step or a conflict, #1312); patch (gap 41 narrows: no row cap on Lightroom import tables, a memory budget from the computer instead, #1361); patch (gaps 13 and 41 narrow: cached-XMP records over 64 MiB and packets over 16 MiB are read without their camera-profile tables, #1311); patch (gap 39: ONNX Runtime on the GPU exists, #491; the aesthetic model is what is left); patch (gap 41 narrows: the recovery archive and the history settings budget follow the drive, the catalog and the memory, newest steps first, #1312); patch (feature-freeze parity pass: CF-PROCESS-RECIPES row restored, gap 43 cites the skin-uniformity row; no ranked gap closes); patch (#1360: scoped, cancellable face maintenance and confirmed reset; no ranked gap closes); patch (gap 42 narrows: OpenEXR scene-linear export, plan 7.5); minor (gap 11: Lens Blur renders from the depth model or the subject, focus picker and bokeh shapes, plan 7.1); patch (gap 16: plug-in publish services get the account, collection, photo metadata and remote comments, plan 7.14); patch (gap 43 narrows: skin-tone uniformity on Point Color, plan 7.9); patch (gap 43: Match Look, Capture One's Smart Adjustments, plan 7.6); minor (gap 18 narrows: lens corrections, Upright and Transform on video frames, poster frame picked, plan 7.11); patch (gap 43 narrows: process recipes, several export presets in one run with one decode per photo, plan 7.4); minor (gap 42 narrows: Tone Equalizer ported from darktable, plan 7.10); minor (gap 42 narrows: inpaint opposed and guided Laplacian highlight reconstruction, ported from darktable, plan 7.2); minor (adaptive presets, plan 7.8; no gap change: P2 rows without a gap entry; adaptive profiles left); patch (the Export screen previews the first photo as its file will be, with an SDR / HDR choice; minor (HDR export: gain map files for AVIF and JPEG XL with `hdrMode: gainMap`, LR-HDR-EXPORT; no ranked gap closes); patch (gap 37: OS folder notifications, single-instance hand-off, URL scheme on Windows and Linux, plan 5.9); patch (gap 43 narrows: speed-edit keys, hold a key and drag or scroll to move a Develop slider, plan 5.10); patch (gap 23: the brush by keyboard; Library and Develop core widgets checked in the AccessKit tree, plan 5.8); patch (gap 26: 100k wheel-scroll frame timed frame by frame, 3–5 ms median, within budget, plan 4.8); minor (gap 2 narrows: CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`, synthetic tests only); patch (gap 1: LibRaw matrices for about 400 newer bodies; every body with a pinned sample has colour matrices; SIL ΔE cross-check; no chart shots yet); patch (gap 8: lensfun's database fetched on first run, picked lens written to XMP, plan 3.9); minor (gap 10: SRF and S200 EXR RAF decode, 47 Olympus / OM bodies verified: 645 verified, 89% on a verified body; target not met); minor (gap 19: the plug-in marketplace — search, install, update, remove and opt-in automatic updates from an index of each plug-in's newest release, vetted and community tiers); patch (gap 9: weekly model-reference job for SAM 2.1, BiRefNet, EoMT and MediaPipe); patch (gap 1: LibRaw matrices for six newer bodies that used the neutral matrix, #451; no chart shots yet); patch (gap 3: render-fidelity reference suite with ΔE2000 / SSIM tolerances and a synthetic ColorChecker check, plan 3.5); patch (gap 3: process V10 applies the Tone Curve in a wide working space, #1142); patch (gap 1: one ranked colour-source order, a Lightroom calibration that loses to the per-photo JPEG fit serves converted DNGs only, #1119; Adobe Standard DNGs without a tone curve get their BaselineExposure once more, #1174); minor (gaps 41–43: Lightroom migration limits left from #1311 / #1312, darktable raw-processing depth, Capture One workflow features); patch (gap 9: PRs run changed-crate tests; the nightly full run covers macOS and Windows, files an issue when red, and blocks releases); patch (gap 40 closed: `apps/android` denies `indexing_slicing`, clippy runs on it in the Android check); patch (never-crash tooling: pure-Rust fuzz targets with a nightly long run; no gap change); patch (gap 40: `apps/cli` and the chart-profile dialog converted); patch (tests only: loopback mock servers for generative fill errors, publish uploads while the server is down and misbehaving IPP printers; slideshow export in SIL; no gap changes); patch (gap 9: nightly corpus + fonts run with a skip gate, GPU equivalence on software adapters); patch (gap 37: folder polling notices new dated folders in a photo tree); minor (gap 38 closed: mixed metadata across a selection, `photo.sharedMeta`); patch (gap 9: timing probes and benchmarks are opt-in `probe` skips, not `#[ignore]`); patch (gap 9: engine import → export → re-import SIL scenario); minor (gap 40 added: checked indexing in the UI; unconverted modules carry a tracked allow); patch (gap 31: the sync merge rules are property-tested in the SIL run); patch (gap 13: required-table record losses always warned; remaining Lightroom size limits listed, #1311); patch (gap 13: the Lightroom import index is no longer capped at 16 MiB, #1312); patch (gap 13: one bad Lightroom record costs only itself; keyword assignments streamed, #1311); minor (gap 19: signed plug-ins find updates in their author's feed, checked when the Plug-in Manager opens and installed by the user); minor (gap 19: plug-in author signatures pin a plug-in's signer, #1271); minor (People: the People view sorts faces into Unknown, Suggested and Confirmed, and reviews the suggested ones a person at a time, #1050); minor (gap 20: Nikon NEFX, NX Studio's merged pixel-shift images, decodes; ARQ pixel shift is what is left of pixel shift); minor (gap 13: Capture One develop settings — exposure, orientation, crop, flips, white balance); minor (gap 13: saved prints in Lightroom catalogs import as Saved Prints with their layout); minor (gap 33 closed: the translation coverage check reads `trf!` and the helpers that translate; gap 21 re-measured: every language has every interface message); minor (gap 19: plug-ins look at a photo's pixels, set its crop and make virtual copies, #891); minor (gap 5: AI mask edges follow the photo's, no outline under a raised Exposure, upstream #3298); minor (gap 11 narrows: AI Super Resolution and AI Sharpen with an opt-in upscaler, upstream #3493); minor (gap 11 narrows: AI Denoise for finished pictures, upstream #3279); patch (gap 36: the ISO country code is carried over in preset save and import, #784); minor (gap 5: AI masks as recipes computed on the AI worker, Update AI Mask, masks under geometry, a Color Mixer per mask); patch (gap 26: smoother edits and lasting previews); minor (gap 5: Object masks can run on SAM 2.1, an open model, ported from OneSlips); minor (gap 12: generative remove through cloud providers with your own key, from OneSlips); minor (gap 36: the IPTC Content fields — headline, description writer, category, supplemental categories, subject codes — are stored, so Lightroom metadata presets carry them); minor (gap 19: plug-ins add a tool's files to the library, stacked or in the source album); minor (gap 19: plug-ins start installed programs; plug-in work no longer on hold); minor (gap 11: AI Denoise works out of the box with a built-in BM3D denoiser, upstream #2982); minor (gap 1: colour-chart calibration); patch (gap 1: calibrations matched to other editors); minor (gap 11 shrinks: the upstream project's own AI Denoise model is a download in the desktop app); patch (gap 3: probe DNGs and slider sweeps); minor (gap 1: dcraw's colour matrices replace the neutral fallback for about 550 models); patch (gap 3: `calibrate-lightroom verify`, edited raws against edited exports); patch (gap 3: ` compare`, ΔE00 between renders from any editor); minor (gaps 1 and 3: Lightroom-matched calibration tool, 0 cameras calibrated yet); minor (upstream merge: gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: grid-cycle key shown in View, #2500; gap 21: Thai glyphs in export text, #2052; gap 15: Japanese photo and postcard paper sizes); patch (HDR zoom: recent windows kept, encoded off the UI thread); patch (HDR adjustment previews: review follow-up); minor (upstream merge: gap 38 added: multi-select metadata editing UI, upstream's gap 30; XMP foreign namespaces and PSD/PSB embedded metadata, no gap change); patch (HDR adjustment previews keep float HDR output during slider drags); minor (opt-in Windows VRR compositor workaround); minor (gap 37 added: folder watching leftovers after issue #123's polling); minor (gap 36 added: what preset import doesn't carry over); minor (M15 decisions: CMYK won't do; Flickr / SmugMug and tethering blocked); minor (gap 11: the Enhance dialog); minor (gap 14 closed: HDR renders on the GPU; X11 SDR is a platform limit); minor (gap 14 narrows: zoomed, Before/After, Compare and second window show HDR, HDR Preview toggle); minor (gap 11 narrows: Raw Details and Super Resolution; gap 18: M14 closed, interlaced H.264 and faster AV1); minor (full audit 2026-10-20: rows refreshed against code; gaps 8 and 2 no longer beta blockers; gaps 34–35 added: Android camera roll and built-in camera; gap 34 narrows: picked folders rescanned); minor (gap 29 narrows: JPEG response curves and half-float frames) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 patch (FITS, astrophotography, decodes: no gap, Lightroom has no FITS, #1604); patch (gap 36 narrows: the file-name templates shared by Export, Rename Photos and import take every stored metadata field as a token — caption, headline, category, keywords, copyright, job title, location fields, camera serial, alt text, long description, caption writer, shutter, aperture, focal — #1584); patch (gap 41 narrows: a Lightroom import is committed and saved in parts, #1361); patch (gap 41 narrows: a large step is saved as many small log records, #1361); imported photos' metadata status compares their sidecars with the catalog, in step or a conflict, #1312); patch (gap 41 narrows: no row cap on Lightroom import tables, a memory budget from the computer instead, #1361); patch (gaps 13 and 41 narrow: cached-XMP records over 64 MiB and packets over 16 MiB are read without their camera-profile tables, #1311); patch (gap 39: ONNX Runtime on the GPU exists, #491; the aesthetic model is what is left); patch (gap 41 narrows: the recovery archive and the history settings budget follow the drive, the catalog and the memory, newest steps first, #1312); patch (feature-freeze parity pass: CF-PROCESS-RECIPES row restored, gap 43 cites the skin-uniformity row; no ranked gap closes); patch (#1360: scoped, cancellable face maintenance and confirmed reset; no ranked gap closes); patch (gap 42 narrows: OpenEXR scene-linear export, plan 7.5); minor (gap 11: Lens Blur renders from the depth model or the subject, focus picker and bokeh shapes, plan 7.1); patch (gap 16: plug-in publish services get the account, collection, photo metadata and remote comments, plan 7.14); patch (gap 43 narrows: skin-tone uniformity on Point Color, plan 7.9); patch (gap 43: Match Look, Capture One's Smart Adjustments, plan 7.6); minor (gap 18 narrows: lens corrections, Upright and Transform on video frames, poster frame picked, plan 7.11); patch (gap 43 narrows: process recipes, several export presets in one run with one decode per photo, plan 7.4); minor (gap 42 narrows: Tone Equalizer ported from darktable, plan 7.10); minor (gap 42 narrows: inpaint opposed and guided Laplacian highlight reconstruction, ported from darktable, plan 7.2); minor (adaptive presets, plan 7.8; no gap change: P2 rows without a gap entry; adaptive profiles left); patch (the Export screen previews the first photo as its file will be, with an SDR / HDR choice; minor (HDR export: gain map files for AVIF and JPEG XL with `hdrMode: gainMap`, LR-HDR-EXPORT; no ranked gap closes); patch (gap 37: OS folder notifications, single-instance hand-off, URL scheme on Windows and Linux, plan 5.9); patch (gap 43 narrows: speed-edit keys, hold a key and drag or scroll to move a Develop slider, plan 5.10); patch (gap 23: the brush by keyboard; Library and Develop core widgets checked in the AccessKit tree, plan 5.8); patch (gap 26: 100k wheel-scroll frame timed frame by frame, 3–5 ms median, within budget, plan 4.8); minor (gap 2 narrows: CRX partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode, ported from LibRaw `crx.cpp`, synthetic tests only); patch (gap 1: LibRaw matrices for about 400 newer bodies; every body with a pinned sample has colour matrices; SIL ΔE cross-check; no chart shots yet); patch (gap 8: lensfun's database fetched on first run, picked lens written to XMP, plan 3.9); minor (gap 10: SRF and S200 EXR RAF decode, 47 Olympus / OM bodies verified: 645 verified, 89% on a verified body; target not met); minor (gap 19: the plug-in marketplace — search, install, update, remove and opt-in automatic updates from an index of each plug-in's newest release, vetted and community tiers); patch (gap 9: weekly model-reference job for SAM 2.1, BiRefNet, EoMT and MediaPipe); patch (gap 1: LibRaw matrices for six newer bodies that used the neutral matrix, #451; no chart shots yet); patch (gap 3: render-fidelity reference suite with ΔE2000 / SSIM tolerances and a synthetic ColorChecker check, plan 3.5); patch (gap 3: process V10 applies the Tone Curve in a wide working space, #1142); patch (gap 1: one ranked colour-source order, a Lightroom calibration that loses to the per-photo JPEG fit serves converted DNGs only, #1119; Adobe Standard DNGs without a tone curve get their BaselineExposure once more, #1174); minor (gaps 41–43: Lightroom migration limits left from #1311 / #1312, darktable raw-processing depth, Capture One workflow features); patch (gap 9: PRs run changed-crate tests; the nightly full run covers macOS and Windows, files an issue when red, and blocks releases); patch (gap 40 closed: `apps/android` denies `indexing_slicing`, clippy runs on it in the Android check); patch (never-crash tooling: pure-Rust fuzz targets with a nightly long run; no gap change); patch (gap 40: `apps/cli` and the chart-profile dialog converted); patch (tests only: loopback mock servers for generative fill errors, publish uploads while the server is down and misbehaving IPP printers; slideshow export in SIL; no gap changes); patch (gap 9: nightly corpus + fonts run with a skip gate, GPU equivalence on software adapters); patch (gap 37: folder polling notices new dated folders in a photo tree); minor (gap 38 closed: mixed metadata across a selection, `photo.sharedMeta`); patch (gap 9: timing probes and benchmarks are opt-in `probe` skips, not `#[ignore]`); patch (gap 9: engine import → export → re-import SIL scenario); minor (gap 40 added: checked indexing in the UI; unconverted modules carry a tracked allow); patch (gap 31: the sync merge rules are property-tested in the SIL run); patch (gap 13: required-table record losses always warned; remaining Lightroom size limits listed, #1311); patch (gap 13: the Lightroom import index is no longer capped at 16 MiB, #1312); patch (gap 13: one bad Lightroom record costs only itself; keyword assignments streamed, #1311); minor (gap 19: signed plug-ins find updates in their author's feed, checked when the Plug-in Manager opens and installed by the user); minor (gap 19: plug-in author signatures pin a plug-in's signer, #1271); minor (People: the People view sorts faces into Unknown, Suggested and Confirmed, and reviews the suggested ones a person at a time, #1050); minor (gap 20: Nikon NEFX, NX Studio's merged pixel-shift images, decodes; ARQ pixel shift is what is left of pixel shift); minor (gap 13: Capture One develop settings — exposure, orientation, crop, flips, white balance); minor (gap 13: saved prints in Lightroom catalogs import as Saved Prints with their layout); minor (gap 33 closed: the translation coverage check reads `trf!` and the helpers that translate; gap 21 re-measured: every language has every interface message); minor (gap 19: plug-ins look at a photo's pixels, set its crop and make virtual copies, #891); minor (gap 5: AI mask edges follow the photo's, no outline under a raised Exposure, upstream #3298); minor (gap 11 narrows: AI Super Resolution and AI Sharpen with an opt-in upscaler, upstream #3493); minor (gap 11 narrows: AI Denoise for finished pictures, upstream #3279); patch (gap 36: the ISO country code is carried over in preset save and import, #784); minor (gap 5: AI masks as recipes computed on the AI worker, Update AI Mask, masks under geometry, a Color Mixer per mask); patch (gap 26: smoother edits and lasting previews); minor (gap 5: Object masks can run on SAM 2.1, an open model, ported from OneSlips); minor (gap 12: generative remove through cloud providers with your own key, from OneSlips); minor (gap 36: the IPTC Content fields — headline, description writer, category, supplemental categories, subject codes — are stored, so Lightroom metadata presets carry them); minor (gap 19: plug-ins add a tool's files to the library, stacked or in the source album); minor (gap 19: plug-ins start installed programs; plug-in work no longer on hold); minor (gap 11: AI Denoise works out of the box with a built-in BM3D denoiser, upstream #2982); minor (gap 1: colour-chart calibration); patch (gap 1: calibrations matched to other editors); minor (gap 11 shrinks: the upstream project's own AI Denoise model is a download in the desktop app); patch (gap 3: probe DNGs and slider sweeps); minor (gap 1: dcraw's colour matrices replace the neutral fallback for about 550 models); patch (gap 3: `calibrate-lightroom verify`, edited raws against edited exports); patch (gap 3: ` compare`, ΔE00 between renders from any editor); minor (gaps 1 and 3: Lightroom-matched calibration tool, 0 cameras calibrated yet); minor (upstream merge: gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: grid-cycle key shown in View, #2500; gap 21: Thai glyphs in export text, #2052; gap 15: Japanese photo and postcard paper sizes); patch (HDR zoom: recent windows kept, encoded off the UI thread); patch (HDR adjustment previews: review follow-up); minor (upstream merge: gap 38 added: multi-select metadata editing UI, upstream's gap 30; XMP foreign namespaces and PSD/PSB embedded metadata, no gap change); patch (HDR adjustment previews keep float HDR output during slider drags); minor (opt-in Windows VRR compositor workaround); minor (gap 37 added: folder watching leftovers after issue #123's polling); minor (gap 36 added: what preset import doesn't carry over); minor (M15 decisions: CMYK won't do; Flickr / SmugMug and tethering blocked); minor (gap 11: the Enhance dialog); minor (gap 14 closed: HDR renders on the GPU; X11 SDR is a platform limit); minor (gap 14 narrows: zoomed, Before/After, Compare and second window show HDR, HDR Preview toggle); minor (gap 11 narrows: Raw Details and Super Resolution; gap 18: M14 closed, interlaced H.264 and faster AV1); minor (full audit 2026-10-20: rows refreshed against code; gaps 8 and 2 no longer beta blockers; gaps 34–35 added: Android camera roll and built-in camera; gap 34 narrows: picked folders rescanned); minor (gap 29 narrows: JPEG response curves and half-float frames) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -17,9 +17,9 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | # | Gap | Evidence | User impact | Hours | Doc | |---:|---|---|---|---:|---| -| 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG (and a person's own raw + JPEG pairs fit a reusable Camera Matching look, `profile.fitCameraLook`, 2026-11-25; LR-PROF-CAMERA / LR-PROF-LEGACY 🟡), 11 bundled profiles or 52 spectral matrices, then dcraw's D65 matrices for about 550 models up to 2018 (2026-10-26) and LibRaw's for about 400 newer bodies (2026-11-24, `tools/libraw_adobe_coeff.py`; tests keep the 20 top bodies and every body with a pinned sample off the neutral matrix, 4 bodies with no allowed source listed; a SIL check compares table matrices with measured spectral data, median mean ΔE2000 about 4, #451); ` calibrate-chart` measures a camera from ColorChecker Classic shots into a `chart` camera-database entry ([chart-calibration](chart-calibration.md), 2026-10-26; no camera measured yet); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307); a photo can switch to Calibrated (spectral) colour (96ce78d8) or use the person's own imported DCP (344a04f7, 2026-10-18); bundled profiles now include D780 / D750 / D90; ` calibrate-lightroom` ([calibrate-lightroom](calibrate-lightroom.md), 2026-10-25) fits calibrations matched to Lightroom from contributors' raws and exports, and with `--editor` to Capture One, darktable, RawTherapee or DxO PhotoLab (2026-10-26); 0 cameras calibrated yet | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 0 chart-calibrated models vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | +| 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG (and a person's own raw + JPEG pairs fit a reusable Camera Matching look, `profile.fitCameraLook`, 2026-11-25; LR-PROF-CAMERA / LR-PROF-LEGACY 🟡), 11 bundled profiles or 52 spectral matrices, then dcraw's D65 matrices for about 550 models up to 2018 (2026-10-26) and LibRaw's for about 400 newer bodies (2026-11-24, `tools/libraw_adobe_coeff.py`; tests keep the 20 top bodies and every body with a pinned sample off the neutral matrix, 4 bodies with no allowed source listed; a SIL check compares table matrices with measured spectral data, median mean ΔE2000 about 4, #451); `chromaforge-cli calibrate-chart` measures a camera from ColorChecker Classic shots into a `chart` camera-database entry ([chart-calibration](chart-calibration.md), 2026-10-26; no camera measured yet); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307); a photo can switch to Calibrated (spectral) colour (96ce78d8) or use the person's own imported DCP (344a04f7, 2026-10-18); bundled profiles now include D780 / D750 / D90; `chromaforge-cli calibrate-lightroom` ([calibrate-lightroom](calibrate-lightroom.md), 2026-10-25) fits calibrations matched to Lightroom from contributors' raws and exports, and with `--editor` to Capture One, darktable, RawTherapee or DxO PhotoLab (2026-10-26); 0 cameras calibrated yet | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 0 chart-calibrated models vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | | 2 | **CR3 variants no public file uses** (LR-IMP-FORMATS): partial subbands, multi-tile 0x200 and adaptive low-frequency gains decode since 2026-11-24 (ported from LibRaw `crx.cpp`, synthetic tests only; vertical-tile 0x100 C-RAW since 2026-10-13, also synthetic only); `crates/raw/src/vendor/crx.rs` still refuses rounded / non-partial plane coding and the median-bit-depth header, and those files fall back to the preview. All 110 CC0 CR3s on raw.pixls.us (31 folders) decode from sensor data, so none of these variants has a public sample; 26 CR3 bodies are verified (M50 / R100 / R8 exact, R5 Mark II pinned, 22 more pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each); the R6 also on five private files). HEIF stills are `.HIF` files, not CR3; no CR3 sRAW / mRAW sample exists | measured: Canon's share whose camera fully works 73% → 98% (raw-parity.md, re-measured 2026-10-15); 18 of 22 popular Canon bodies write CR3, all 18 now verified | +0.3 points of photographers; the variants surface only as user files that open as a preview | 10–25 | [raw-parity](raw-parity.md#remaining-work-ranked-by-photographers-unlocked-per-hour) | -| 3 B | **Render fidelity unmeasured** (LR-BEHAV-RENDER-FIDELITY): tone, highlights, texture / clarity / dehaze, NR and sharpening are tuned by eye | no Lightroom reference renders measured yet; the render-fidelity reference suite (`cargo xtask fidelity`, [testing-sil](testing-sil.md#render-fidelity-reference-suite)) renders 15 tools × every process × procedural scenes and CC0 corpus photos against local references with committed ΔE2000 / SSIM tolerances, gates process-version retunes (in CI through a committed per-process baseline of aggregate numbers, `cargo xtask fidelity --baseline`), and checks the unedited pipeline on a synthetic ColorChecker (mean ΔE2000 ≈ 0.3); process versions V1–V4 (V2 Highlights / Shadows detail #632, V3 Dehaze #1237, V4 sharpening #757 / #762, [process-versions](process-versions.md)); retunes ship as new versions; camera colour and looks can now be fitted to Lightroom exports (` calibrate-lightroom`, 0 cameras so far), which also measures held-out ΔE00 per look; ` compare` measures any render against any other editor's (ΔE00 by tone and hue), and ` calibrate-lightroom verify` measures edited raws against their edited exports per group of controls (the migration check; no results recorded yet); `calibrate-lightroom probe` / `probe-check` write synthetic probe DNGs and slider sweeps and measure, per Lightroom slider value, the app value that matches it (no Lightroom run recorded yet) | edits imported from Lightroom look different; the look "isn't Lightroom's" | 30–60 | [raw-parity](raw-parity.md), [process-versions](process-versions.md) | +| 3 B | **Render fidelity unmeasured** (LR-BEHAV-RENDER-FIDELITY): tone, highlights, texture / clarity / dehaze, NR and sharpening are tuned by eye | no Lightroom reference renders measured yet; the render-fidelity reference suite (`cargo xtask fidelity`, [testing-sil](testing-sil.md#render-fidelity-reference-suite)) renders 15 tools × every process × procedural scenes and CC0 corpus photos against local references with committed ΔE2000 / SSIM tolerances, gates process-version retunes (in CI through a committed per-process baseline of aggregate numbers, `cargo xtask fidelity --baseline`), and checks the unedited pipeline on a synthetic ColorChecker (mean ΔE2000 ≈ 0.3); process versions V1–V4 (V2 Highlights / Shadows detail #632, V3 Dehaze #1237, V4 sharpening #757 / #762, [process-versions](process-versions.md)); retunes ship as new versions; camera colour and looks can now be fitted to Lightroom exports (`chromaforge-cli calibrate-lightroom`, 0 cameras so far), which also measures held-out ΔE00 per look; `chromaforge-cli compare` measures any render against any other editor's (ΔE00 by tone and hue), and `chromaforge-cli calibrate-lightroom verify` measures edited raws against their edited exports per group of controls (the migration check; no results recorded yet); `calibrate-lightroom probe` / `probe-check` write synthetic probe DNGs and slider sweeps and measure, per Lightroom slider value, the app value that matches it (no Lightroom run recorded yet) | edits imported from Lightroom look different; the look "isn't Lightroom's" | 30–60 | [raw-parity](raw-parity.md), [process-versions](process-versions.md) | | 4 | ~~**Original-pixel detail at 100%**~~ (LR-VIEW-ZOOM, P0) — **closed 2026-10-13**: the loupe, Before/After, mask overlays, soft proofing, Compare and Reference are all tiled zoom windows at 1:1–8:1 (#323); overlays and the proof are part of each tile's look | `tests_preview_limit::in_the_loupe::a_mask_overlay_at_one_to_one_is_a_window_and_keeps_zoom_and_pan`, `…::soft_proofing_at_one_to_one_is_tiled`; headless 1:1 on a 6000 × 4000 photo: 2048 px window of the 6000 px frame, canvas-sized whole-frame render | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape**: Subject and Background use **BiRefNet_lite** (MIT, maintainer decision 2026-10-13; pure-Rust port matching the reference to 2·10⁻⁵, downloaded on request, `segment.subject.*`, ~5.7 s per photo on a loaded 32-core CPU; demo-scene IoU 0.44, below the analysis' 0.88 because the synthetic bokeh discs are sharp — needs a real-photo set) when installed; otherwise, and for Sky, People, Landscape, they run a whole-photo analysis (`auto_mask.rs`: sky colour model + per-column split, boundary-prior saliency, water / vegetation), measured on the labelled demo scenes (soft IoU: Sky 0.65 → 0.79, Subject 0.40 → 0.88, water 0 → 0.32); People parts, Landscape mountains / architecture / ground select nothing without mattes. Object clicks can also run on SAM 2.1 Hiera-Tiny (Apache-2.0, downloadable from Meta's Hugging Face repository at a pinned commit, `ai.models.*`; not yet verified with the real checkpoint here), so Object no longer needs a SAM 3 mirror; Object / Describe run SAM 3, verified end to end with the real checkpoint on CPU (first Describe ~90 s incl. load + encode, then 0.2–3 s per prompt/click, peak RSS 4.7 GB); a local copy installs through a `file://` / folder mirror, all three files SHA-256 pinned; the default download location still needs a maintainer-hosted mirror (code is done: env var, mirrors file, `DEFAULT_MIRRORS`) Masks as recipes (2026-11-02, ported from OneSlips): presets, paste and sync carry People by name or role and anchored gradients, completed per photo; Object / Describe selections compute on the AI worker as one cancellable activity row (`masks.recompute`, Update AI Mask, a stale badge), masks stay on the photo under lens corrections / Upright / Transform / Rotate, and each mask carries its own Color Mixer and Point Color. Still open here: the per-person body box is estimated from the face, mask thumbnails of Subject / Sky / People use the analysis, not the mattes | `crates/pipeline/src/auto_mask.rs`, `tests_mask_eval.rs`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 30–60 + model decision | [target-app-parity](target-app-parity.md#ai) | | 6 | ~~**Compressed ORF**~~ closed 2026-10-13: `decode_compressed` in `orf.rs` decodes every Olympus / OM body since ~2008 that writes it | measured: E-M1 and E-M10 Mark III corpus files decode and render correctly; 73 of 78 Olympus / OM models now unverified rather than preview-only; OM bucket 3% → 80% fully working | +2.6 points (use-weighted 85% → 87%) | 0 (left: verify OM-1 / OM-5 / E-M1 II–III files) | [raw-parity](raw-parity.md#compressed-orf-a-clean-room-starting-point) | @@ -27,7 +27,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 8 | **No lens profile database of our own** (LR-EDIT-OPTICS-PROFILE): DNG opcodes, RW2 in-file distortion and Sony ILCE-7RM4A, ILCE-7RM6 and ZV-E10 distortion (`docs/sony-ilce7rm6-lens-corrections.md`), Nikon Z 6II / Z 8 / Z f in-file distortion (`docs/nikon-lens-corrections.md`), plus lensfun's database, fetched once on the desktop app's first run (activity stack) or set up / downloaded from Settings ▸ Lens profiles (CC-BY-SA, not bundled in the binary; a picked lens is written to XMP as `optics.lens`; profiles unverified against Lightroom) | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | | 9 B | **Full tests in CI not yet green on macOS, Windows and Linux x64**: pushes to main run fmt / clippy / build on all three OSes (green); full tests run only on `release` or a manual dispatch. The manual full run was green 2026-10-18 (run 39114677868); release 0.9.5 (run 39371069655) failed on macOS, Windows and Linux in four deterministic test groups: lcc-publish full-disk publish, ui-egui i18n catalog coverage (2 tests), empty-library icon layout, engine Immich album publish. Also left: real-disk sidecar-repair fixtures skip on case-insensitive volumes (FakeFs models them); CPU/GPU equivalence runs nightly on software adapters (lavapipe, WARP; `nightly.yml`, wider bounds), and a nightly corpus + fonts run fails when skips exceed `ci/skip-allowlist.toml`, both not yet seen green on CI (#1050); a weekly model-reference job (`models.yml`) runs SAM 2.1, BiRefNet, EoMT and the MediaPipe TFLite models from their pinned, sha256-checked downloads against stored numeric summaries of our own outputs; SAM 3 (SAM License, gated) and YuNet (retired, CC BY-NC-ND training data) are left out (docs/ci.md → Model references) | `.github/workflows/ci.yml`, runs 39114677868 / 39371069655 | regressions reach users on the main platforms until the full suite is green | 2–6 | [target-app-parity](target-app-parity.md#by-dimension) | | 10 B | **Per-model verification still partial**: 645 of 1,446 Adobe models verified (45%, measured 2026-11-24), ~89% of photographers on a verified body (plan target: 60% of models or 95% of photographers — not met); per maker in raw-parity.md. The cheap per-body fixes landed (Z 6II packed NEF #769, ARW version 1 for the A100 and A200…A390, A850, Z 8 and Z 9 lossless verified, pre-X FinePix SuperCCD RAF decoded); S200 EXR upright RAF and SRF decode, Olympus / OM bulk-checked (2026-11-24); left: phones (DNG, few public samples), the older / niche tail per maker, a four-colour path for the F828, and samples for the 90D, 250D, X-H2S, Z 6III, OM-1, OM-5 (none on raw.pixls.us) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 15–30 | [raw-parity](raw-parity.md#by-maker-measured) | -| 11 | **Enhance: AI denoise without shippable weights or X-Trans; Raw Details and Super Resolution are classical** (Photo ▸ Enhance ▸ Raw Details / Super Resolution landed 2026-10-20: edge-aware residual demosaic and 2× iterative back-projection, each a new linear DNG stacked with the source, in the activity stack; no learned model, Raw Details Bayer only; the Enhance Preview dialog, Photo ▸ Enhance…, landed 2026-10-21) | ENH rows 🟡; denoise: Bayer raws, and finished pictures (JPEG / PNG / TIFF) once a model for them is installed (own model slot; opt-in NIND U-Net, GPL-3.0 weights, upstream #3279); a built-in classical denoiser (block-matching collaborative filtering, GPU-accelerated) works out of the box; the upstream project's own model (MIT OR Apache-2.0, CC0 training data, 0.1.0; [denoise.md](denoise.md#the-upstream-projects-own-model)) is a download in the desktop app, from the upstream release asset, else radfilms.com.au (same SHA-256); RawNIND weights dual-licensed GPL-3.0 and CC BY 4.0, offered under CC BY 4.0, and opt-in (#1760) (Lens Blur renders since 2026-11-25 from the depth model, else from the Subject selection: LR-EDIT-LENSBLUR 🟡, no depth refine brushes) | Fujifilm users get no AI denoise; classical Super Resolution recovers less texture than an AI model, and AI Super Resolution / AI Sharpen (an installed upscaler, upstream #3493) bake the photo's edits into an sRGB TIFF (Lightroom keeps an editable raw) | 20–45 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | +| 11 | **Enhance: AI denoise without shippable weights (X-Trans only through an RGGB re-mosaic, 2026-11-29); Raw Details and Super Resolution are classical** (Photo ▸ Enhance ▸ Raw Details / Super Resolution landed 2026-10-20: edge-aware residual demosaic and 2× iterative back-projection, each a new linear DNG stacked with the source, in the activity stack; no learned model, Raw Details Bayer only; the Enhance Preview dialog, Photo ▸ Enhance…, landed 2026-10-21) | ENH rows 🟡; denoise: Bayer raws, X-Trans through an RGGB re-mosaic (`remosaic_rggb`, upstream #1828; unmeasured with a model trained on Bayer sensors), and finished pictures (JPEG / PNG / TIFF) once a model for them is installed (own model slot; opt-in NIND U-Net, GPL-3.0 weights, upstream #3279); a built-in classical denoiser (block-matching collaborative filtering, GPU-accelerated) works out of the box; the upstream project's own model (MIT OR Apache-2.0, CC0 training data, 0.1.0; [denoise.md](denoise.md#the-upstream-projects-own-model)) is a download in the desktop app, from the upstream release asset, else radfilms.com.au (same SHA-256); RawNIND weights dual-licensed GPL-3.0 and CC BY 4.0, offered under CC BY 4.0, and opt-in (#1760) (Lens Blur renders since 2026-11-25 from the depth model, else from the Subject selection: LR-EDIT-LENSBLUR 🟡, no depth refine brushes) | Fujifilm users get AI denoise only through a re-mosaic the model was not trained on; classical Super Resolution recovers less texture than an AI model, and AI Super Resolution / AI Sharpen (an installed upscaler, upstream #3493) bake the photo's edits into an sRGB TIFF (Lightroom keeps an editable raw) | 20–45 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | | 12 | **Generative remove, detect distractions, reflections removal** (content-aware Remove exists: PatchMatch Fill spots, LR-REM-CONTENTAWARE 🟡) | REM rows 75%; generative remove works through cloud providers with the user's own key (LR-REM-GEN 🟡, ported from OneSlips; no on-device model), remove people stays out of scope (LR-REM-PEOPLE 🚫); open work is detect distractions and reflections | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) | | 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived; smart collections with unmappable rules (metadata status) stay static; 6 of 113 public flat `crs:` fields have no equivalent (Upright tool options, lens profile setup…) (most smart rules (rule mapping still being finished, 8296786e), stacks, develop history as History, snapshots as Versions, collection / capture / edit date rules incl. today / this week / month / year now import, G13); offline record counts and destination are shown in a lasting import result; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672); video records classified, records without files skipped, large catalogs read in bounded pages; one oversized or damaged record is left out and counted instead of its table, keyword assignments are streamed past a million (#1311, #1312) — oversized cached-XMP records and packets are read without their camera-profile tables (#1311); imported photos start in step with their sidecars, or as a conflict where a sidecar disagrees (#1312); the recovery archive and the history budget grow with the catalog, the drive and the memory (#1312); the import index grows past 16 MiB so large re-imports add nothing twice; saved prints import as Saved Prints with their layout; Capture One catalogs (`.cocatalogdb`) import through the same path (photos, variants as virtual copies, ratings, colour tags but orange / pink, IPTC fields, keywords, albums in their projects and groups, capture time and camera of offline originals; develop settings: exposure, contrast, brightness, saturation, High Dynamic Range, clarity and structure, levels, the RGB / red / green / blue curves, orientation and straighten, crop, flips and white balance, every other setting named in the result window; not yet the colour editor, layers (as masks), the luma curve or smart albums, C1-IMPORT, C1-DEVELOP) | lightroom-catalog-import.md | switching users lose some looks | 6–10 | [file-format-parity](file-format-parity.md) | | 14 | ~~**HDR display leftovers**~~ — **closed 2026-10-21**: HDR display output (EDR / scRGB surface through a vendored egui-wgpu patch, UI at paper white, HDR edits above SDR white in every view, View ▸ HDR Preview `view.hdrPreview`), and HDR renders run on the GPU (float HDR tone map and output in `finish.wgsl`, CPU as oracle; HDR views, HDR exports and gain maps). X11 has no HDR surface (no colour-management protocol carries headroom or HDR metadata there; a platform limit, not planned): on Linux the app runs native Wayland whenever an output reports HDR headroom, else XWayland / X11 in SDR; slider drags show live HDR drafts too, zoomed in as well (2026-10-22); zoomed panes keep their recent HDR windows (2026-10-24) | HDR rows 85%; LR-HDR-EDIT ✅; LR-VIEW-HDR-DISPLAY 🟡 only for X11 (platform limit); `hdr_renders_match` in `crates/gpu/tests/it/equivalence.rs` | 6 MP HDR render CPU ~200 ms → GPU ~50–70 ms | 0 | [hardware-parity](hardware-parity.md) | @@ -57,9 +57,9 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 38 | ~~**Multi-select metadata editing in the UI**~~ — **closed 2026-11-21**: the Classic Metadata panel and the Modern Info card show `< mixed >` for a field whose values differ across the selection and write only the field the user edits (`photo.setMeta` with that one key; a mixed field left empty changes nothing); `photo.sharedMeta` gives the same shared/mixed view to scripts, MCP and plug-ins. All Metadata stays a one-photo, read-only view of the file, as in Lightroom Classic | `crates/ui-egui/src/panels/metadata.rs` `common`, `crates/ui-egui/src/modern_library.rs` `field`, `crates/engine/src/cmd/library.rs` `shared_meta`, test `shared_meta_marks_mixed_fields_and_edits_keep_them` | — | 0 | [ui-parity](ui-parity.md) | | 39 | **Image Quality Scanner: no learned aesthetic engine** (LR-LIB-QUALITY, issue #1313): the scanner's score is a weighted mean of four classical technical measures (sharpness, noise, exposure, JPEG blockiness, `crates/pipeline/src/quality.rs`), which is honest but blind to subject and intent — a sharp, clean photo of a dull subject scores high. The issue also asks for a Deep Learning aesthetic engine (NIMA / MUSIQ ONNX, GPU with CPU fallback, a model download prompt). It is not built: `crates/ml`'s CLIP is the only learned model, with `Role::AestheticHead` unimplemented, so there is no aesthetic head to run. A runtime for one exists since #491: desktop builds run ONNX models on the GPU through ONNX Runtime (`crates/onnxrt`, docs/onnxruntime.md). What stands in for it: Assisted Culling's Aesthetic score and Suggested Stars (classical, stored as `Analysis.aesthetic` / `Analysis.suggested`). Closing it: an aesthetic head with weights that ships and a licence to redistribute them, then a `Role::AestheticHead` score folded into the scanner's verdict (the four factors' weights and `QualityVerdict` are already per-photo data). What is built (#1362) is the auto-assigned metadata: star ratings and Pick / Reject from configurable thresholds, with the user's own ratings and flags protected unless "Overwrite existing". The pixels are measured on the multi-threaded CPU only; the issue's GPU path is not built. So what this gap leaves is the learned aesthetic judgement and the graphics-card passes alone | gap 11 (AI) | a scan cannot tell a good photograph from a sharp one | small (a head wired into the scanner: 4–8 h) once the model exists; the model is the work | [quality-scanner](manual-site/src/content/docs/library/quality-scanner.mdx) | | 40 | ~~**Checked indexing on Android**~~ — **closed 2026-11-22**: `clippy::indexing_slicing` is denied in `crates/ui-egui`, `apps/app`, `apps/cli`, `apps/web` and `apps/android` with no module-level `allow` left; `apps/android` had no indexing outside tests, and `cargo xtask android check` now runs clippy on `lcc-android` for its Android target so its crate-root denies are enforced | `apps/android/src/lib.rs` deny, `xtask/src/android.rs` `check` | — | 0 | [ci](ci.md) | -| 41 B | **Lightroom catalog migration still drops data at fixed limits** (issues #1311, #1312; gap 13): one oversized record no longer drops its table (skipped and counted since 2026-11-22), keyword assignments stream and the import index holds 1 GiB; the recovery archive may take a quarter of the drive's free space and the history settings budget follows the catalog's size and the memory, spent on every photo's newest steps first (2026-11-27). A cached-XMP record over 64 MiB is read as a stream and a packet over 16 MiB without its `crs:Table_` attributes (2026-11-27); a packet still over 16 MiB without them is dropped. Each photo's metadata status compares its sidecar with the catalog after the import (in step, or a conflict the result counts) instead of "changed in the catalog" for all (2026-11-27). Left: the result doesn't say which fields came from the files instead; no table has a row cap since 2026-11-27 (#1361: the read keeps within a memory budget taken from the computer, `_LIGHTROOM_IMPORT_MEMORY` to change it, and keeps half what it did), and its one log step is written as records of about 4 MiB each, never one string of gigabytes (a crash keeps the records before it). the import is committed and saved 20,000 changes at a time, still one undo step, so the session no longer holds a copy of the whole import until it is saved (2026-11-27). Left: the peak is still about 37 KB a photo on a synthetic 200,000-photo catalog (the catalog itself, the undo step and the read), past a small computer for a multi-million-photo catalog; an import stopped by a crash keeps the parts already saved, and importing again adds the rest but may add their virtual copies twice (the import index is written at the end) | a 679,930-photo professional catalog loses rights metadata, history and archives while the import reports success | large-catalog migrants (the users most likely to switch) | 12–24 h | [lightroom-catalog-import](lightroom-catalog-import.md) | +| 41 B | **Lightroom catalog migration still drops data at fixed limits** (issues #1311, #1312; gap 13): one oversized record no longer drops its table (skipped and counted since 2026-11-22), keyword assignments stream and the import index holds 1 GiB; the recovery archive may take a quarter of the drive's free space and the history settings budget follows the catalog's size and the memory, spent on every photo's newest steps first (2026-11-27). A cached-XMP record over 64 MiB is read as a stream and a packet over 16 MiB without its `crs:Table_` attributes (2026-11-27); a packet still over 16 MiB without them is dropped. Each photo's metadata status compares its sidecar with the catalog after the import (in step, or a conflict the result counts) instead of "changed in the catalog" for all (2026-11-27). Left: the result doesn't say which fields came from the files instead; no table has a row cap since 2026-11-27 (#1361: the read keeps within a memory budget taken from the computer, `CHROMAFORGE_LIGHTROOM_IMPORT_MEMORY` to change it, and keeps half what it did), and its one log step is written as records of about 4 MiB each, never one string of gigabytes (a crash keeps the records before it). the import is committed and saved 20,000 changes at a time, still one undo step, so the session no longer holds a copy of the whole import until it is saved (2026-11-27). Left: the peak is still about 37 KB a photo on a synthetic 200,000-photo catalog (the catalog itself, the undo step and the read), past a small computer for a multi-million-photo catalog; an import stopped by a crash keeps the parts already saved, and importing again adds the rest but may add their virtual copies twice (the import index is written at the end) | a 679,930-photo professional catalog loses rights metadata, history and archives while the import reports success | large-catalog migrants (the users most likely to switch) | 12–24 h | [lightroom-catalog-import](lightroom-catalog-import.md) | | 42 | **darktable raw-processing depth not matched** (competitor matrix, completion plan §4): demosaic offers Bilinear / PPG / AHD / Detail / RCD (RCD translated from RawTherapee 2026-11-25: +1.1 dB over AHD on 12 real raws, ~6× slower, so not the default) but not AMaZE or LMMSE (`crates/raw/src/demosaic/mod.rs`); highlight reconstruction offers Rebuild, inpaint opposed and guided Laplacian (`sensor.highlightMode`, `crates/raw/src/highlight.rs`, the last two ported from darktable) but not segmentation-based; a tone equalizer since 2026-11-25 (`crates/pipeline/src/tone_eq.rs`, without a band picker, curve graph or per-mask use); a fixed tone curve instead of a scene-referred mapper (sigmoid / AgX / filmic); OpenEXR scene-linear export since 2026-11-25 (`exr` crate, half / float, Rec. 2020 or ACEScg); no liquify. darktable / RawTherapee sources are GPL and may be ported with provenance. Module reordering and multiple instances are left out on purpose | not in the parity checklist (beyond Lightroom) | users comparing against darktable; highlight and demosaic quality also shows in Lightroom-parity renders | 60–120 h | [raw-parity](raw-parity.md) | -| 43 | **Capture One workflow features missing** (competitor matrix, completion plan §4): layers with opacity and blend modes (masks have an amount only), annotations, sessions without a catalog (browse mode is partial), Live-style client review; Capture One develop import reads basics only, not curves, levels, colour editor, clarity, layers or smart albums (`crates/engine/src/capture_one_develop.rs`). Style brushes are partial. Process recipes landed (CF-PROCESS-RECIPES, `export.runPresets`). Skin-tone uniformity on Point Color landed (plan 7.9, LR-EDIT-COLOR-POINTCOLOR-UNIFORMITY). Smart Adjustments-style Match Look landed (`develop.matchLook`, CF-MATCH-LOOK) | not in the parity checklist (beyond Lightroom) | Capture One migrants and studio / tethered shooters | 80–160 h | [target-app-parity](target-app-parity.md) | +| 43 | **Capture One workflow features missing** (competitor matrix, completion plan §4): layers with opacity and blend modes (masks have an amount only), annotations, sessions without a catalog (browse mode is partial), Live-style client review; Capture One develop import reads exposure, brightness, levels, curves, crop, flips, white balance, a raw's film curve and measured Highlight, Shadow and Saturation mappings, but not contrast, white, black, clarity, structure, the colour editor, layers or smart albums (`crates/engine/src/capture_one_develop.rs`, `docs/lightroom-catalog-import.md`). Style brushes are partial. Process recipes landed (CF-PROCESS-RECIPES, `export.runPresets`). Skin-tone uniformity on Point Color landed (plan 7.9, LR-EDIT-COLOR-POINTCOLOR-UNIFORMITY). Smart Adjustments-style Match Look landed (`develop.matchLook`, CF-MATCH-LOOK) | not in the parity checklist (beyond Lightroom) | Capture One migrants and studio / tethered shooters | 80–160 h | [target-app-parity](target-app-parity.md) | Beta-blocking gaps (B) total **~170–310 h**; with the stability and platform work they need around them, **~280–480 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -114,6 +114,8 @@ Beta-blocking gaps (B) total **~170–310 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-30 | patch | FITS, the format of astrophotography cameras and software, decodes (8-, 16-, 32-bit integers, 32-, 64-bit floats; monochrome, colour filter array, red / green / blue planes; `crates/raw/src/vendor/fits.rs`, `crates/meta/src/fits.rs`): closes no gap, Lightroom has no FITS (#1604) | +| 2026-11-29 | patch | Gaps 13 and 43: the Capture One catalog import reads a raw's film curve as its base curve with Built-in colour, and Highlight, Shadow and Saturation by mappings measured on Capture One's exports (approximate, each with a result-window line); a virtual copy starts from the camera defaults, no XMP sidecar is read and no edit-time warning is made; contrast, white, black, clarity and structure are named as not imported (the 2026-11-25 row's contrast, clarity and structure no longer apply); hours unchanged | | 2026-11-25 | patch | Gap 16: plug-in publish services (host feature `publishServices`) get the user's service and settings, the collection and each photo's title / caption / keywords, and answer remote comments, so Flickr / SmugMug can come as third-party plug-ins; first-party keys still the maintainer's call; hours unchanged | | 2026-11-25 | minor | Gap 42 narrows: the Tone Equalizer (exposure per luminance band through a guided-filter mask), translated from darktable `toneequal.c` (GPL, NOTICE), plan 7.10; CPU code on both renderers, no WGSL kernel | | 2026-11-25 | minor | Adaptive presets (plan 7.8): presets carry mask recipes computed per photo, a built-in Smart Masks: Adaptive group, version 2 preset files with hostile-input tests, and a build without the AI model applies the rest and names the skipped masks; LR-PRE-ADAPTIVE / LR-MASK-ADAPTIVE ✅; LR-PROF-ADAPTIVE (an AI tone profile) stays ⬜; no gap entry changes | @@ -127,6 +129,7 @@ Beta-blocking gaps (B) total **~170–310 h**; with the stability and platform w | 2026-11-22 | patch | Gap 40 closed: `apps/android` denies `clippy::indexing_slicing`; the Android check runs clippy on `lcc-android`. | | 2026-11-23 | patch | Gap 9: PRs run the tests of the changed crates and their dependents; the nightly full run covers macOS and Windows, opens or updates an issue when red, and a red nightly blocks the release workflow; gap not closed | | 2026-11-22 | patch | Never-crash tooling: pure-Rust fuzz targets, `cargo xtask fuzz` and a nightly long run; no gap change. | +| 2026-11-30 | minor | People (issue #1691): a person's page sorts their faces — import order, capture time oldest or newest first, folder, or largest face first (kept across restarts; `faces.person {sort}`, the UI's `person.sort`) — and Library ▸ Faces ▸ Build Face Thumbnails (`faces.buildThumbnails`) renders a tile of every face into the thumbnail cache ahead of the scrolling that would build them one by one, background, cancellable; no ranked gap closes | | 2026-11-22 | patch | Gap 9: a nightly workflow runs the full suite with the corpus, craft-fonts and photocraft-corpus and fails when skips exceed `ci/skip-allowlist.toml`; CPU ↔ GPU equivalence runs nightly on lavapipe and WARP with wider bounds; gap not closed | | 2026-11-21 | minor | Gap 39 added: the Image Quality Scanner (LR-LIB-QUALITY, issue #1313) — background scans of a selection, folder or catalog for sharpness, noise, exposure and JPEG blockiness, per-factor weights, scores kept on the photo (catalog format 20) with Quality sort and filters, and Pick / Reject by two cutoffs; no aesthetic engine (pure Rust: no ONNX runtime), so the score stays technical | | 2026-11-15 | minor | The People view's faces are sorted into Unknown, Suggested and Confirmed, and the faces recognition matched to someone are reviewed a person at a time — Confirm names a person's whole group in one undo step, Reject keeps them unknown and stops that person being suggested for them again (issue #1050); the 22 new messages and formats are in all 17 languages, so gap 21's count is unchanged | @@ -144,7 +147,7 @@ Beta-blocking gaps (B) total **~170–310 h**; with the stability and platform w | 2026-10-28 | minor | Gap 19: plug-ins add the files a tool made to the library (`libraryAdd` permission, `library.add`: from the source photo's folder, stacked on it or in an album that holds it, re-read when the tool wrote over it), and commands learn the Library source they ran from (`source`); hours unchanged | | 2026-10-26 | minor | Gap 19: plug-ins start programs installed on the computer (a `programs` permission only the user grants, `program.list`, `program.start` with a run folder, `program.end`, a row in the activity stack); plug-in work is no longer on hold (the maintainer reopened it 2026-10-24); hours unchanged | | 2026-10-26 | minor | Gap 11: AI Denoise works out of the box with a built-in BM3D denoiser (upstream #2982); the gap stays open (no trained weights shipped, X-Trans) | -| 2026-10-25 | minor | Gap 11 shrinks: the upstream project's own AI Denoise model (MIT OR Apache-2.0, CC0 training data; upstream PR 2929) is offered in the desktop app, from the upstream release asset, else radfilms.com.au (same file, same SHA-256; `_DENOISE_MODEL_URL` replaces both); X-Trans remains | +| 2026-10-25 | minor | Gap 11 shrinks: the upstream project's own AI Denoise model (MIT OR Apache-2.0, CC0 training data; upstream PR 2929) is offered in the desktop app, from the upstream release asset, else radfilms.com.au (same file, same SHA-256; `CHROMAFORGE_DENOISE_MODEL_URL` replaces both); X-Trans remains | | 2026-10-24 | patch | HDR zoom and drags: zoomed panes keep their last few HDR windows (pan back and zoom back in at once), HDR frames are encoded on the render worker, and no 8-bit tiles render under an HDR pane (gap 14 / LR-VIEW-HDR-DISPLAY, status unchanged) | | 2026-10-24 | patch | HDR adjustment previews, review follow-up: only the edited photo's views draft, a drag showing HDR frames renders no 8-bit drafts beside them, zoomed panes show their HDR window, the whole frame's HDR while it comes, or their tiles when not HDR, and a failed or reshaped (crop, rotation) HDR frame is dropped (gap 14 / LR-VIEW-HDR-DISPLAY, status unchanged) | | 2026-10-23 | minor | Gap 13: before a Lightroom catalog import the app asks whether it merges into the open library or goes into a new one (opt-out in Settings, #2672); hours unchanged | diff --git a/docs/generative-fill.md b/docs/generative-fill.md index b9f2b3b566..cb04d7bc32 100644 --- a/docs/generative-fill.md +++ b/docs/generative-fill.md @@ -111,7 +111,7 @@ comparison of the services needs the user's keys and test crops. 1. Create an API key in your account with the provider (Settings ▸ Generative Fill ▸ *Get an API key*). 2. Paste it in Settings ▸ Generative Fill and click **Save Key**. Or set - `_GENFILL__KEY` (e.g. `_GENFILL_OPENAI_KEY`) before starting Chromaforge. + `CHROMAFORGE_GENFILL__KEY` (e.g. `CHROMAFORGE_GENFILL_OPENAI_KEY`) before starting Chromaforge. 3. The first Generate with a provider opens a short dialog: the crop that will be uploaded (the area to fill lightly tinted), its size and the cost ("About $0.20, billed to your OpenAI account"), with **Generate** and **Cancel**. What the provider does with uploads, its @@ -162,7 +162,7 @@ part of its data, so a slow upload could repeat bytes inside an encrypted record The sockets are non-blocking now (a send that can't go out sends nothing), tested against a local TLS server that reads slowly. -Keys are kept in `genfill-keys.json` in Chromaforge's settings folder (`` (per OS) on +Keys are kept in `genfill-keys.json` in Chromaforge's settings folder (`Chromaforge` (per OS) on Windows, macOS and Linux), written with owner-only permissions on macOS and Linux. They are never in the catalog, XMP, exports or logs, never returned by a command (`genfill.providers` shows where a key comes from and its last @@ -261,9 +261,9 @@ genfill_check` with `GENFILL_REAL=1` repeats such a test (each run is a paid req ### Trying it without an account -` genfill-mock --port 18510` serves the four providers' request and response shapes on +`chromaforge-cli genfill-mock --port 18510` serves the four providers' request and response shapes on 127.0.0.1 and fills holes with Chromaforge's own content-aware fill. Start Chromaforge with -`_GENFILL_MOCK=http://127.0.0.1:18510`, save any key, and Generate goes to the mock. Only +`CHROMAFORGE_GENFILL_MOCK=http://127.0.0.1:18510`, save any key, and Generate goes to the mock. Only loopback addresses are accepted there, so a key can't be sent elsewhere by mistake. ## Commands diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index ec1bd55559..9fc86e5cc2 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -1,8 +1,5 @@ # GPU develop pipeline (M5.2) -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - The CPU pipeline (`crates/pipeline`) is the reference ("oracle"). `lcc-gpu` (`crates/gpu`, L3) evaluates the same stages with wgpu compute shaders (WGSL) on Metal / Vulkan / DX12. Everything is pure Rust (wgpu, naga); the drivers are the system's. No GL backend is compiled in. @@ -43,14 +40,14 @@ means to use (`lcc_gpu::backend`), for its compute device *and* for the desktop | Linux / BSD | Vulkan (the window also lists GL, eframe's default; no GL backend is compiled in) | Overrides (read once at launch): -- `_GPU_BACKEND=dx12 | vulkan | metal | gl | auto | off` (comma lists allowed, e.g. +- `CHROMAFORGE_GPU_BACKEND=dx12 | vulkan | metal | gl | auto | off` (comma lists allowed, e.g. `vulkan,dx12`): the backends for both the window and GPU rendering; `off` turns GPU rendering off (CPU pipeline) — the window still needs a backend and keeps the platform default. A backend this build doesn't contain (`gl`) is ignored with a warning. - else `WGPU_BACKEND` (wgpu's own variable, same names) — before #136 only the window honoured it, the compute device always used Vulkan + DX12 (+ Metal). -- `_GPU=0`: GPU rendering off for the process (the window is unaffected). -- `_GPU_ADAPTER=` (any case, e.g. `4070`, `radeon`, `"rtx 4070 super"`): +- `CHROMAFORGE_GPU=0`: GPU rendering off for the process (the window is unaffected). +- `CHROMAFORGE_GPU_ADAPTER=` (any case, e.g. `4070`, `radeon`, `"rtx 4070 super"`): the graphics card for GPU rendering, AI Denoise and the face models, on a machine with more than one (`backend::pick_adapter`). The first hardware card whose name contains it wins, in wgpu's order; software adapters (WARP, llvmpipe) never. A name that matches no card is logged @@ -58,9 +55,9 @@ Overrides (read once at launch): high-performance card is used. The window stays on the card that drives the screen. The log's `gpu: GPU_ADAPTER=…: using …` line names the card used. Handy to keep test runs or a long export off the card the screens hang on. -- Both `_GPU=0` and `_GPU_BACKEND=off` also keep AI Denoise, the face models +- Both `CHROMAFORGE_GPU=0` and `CHROMAFORGE_GPU_BACKEND=off` also keep AI Denoise, the face models and the AI mask model (SAM 3 on Metal) on the CPU. -- `_GPU_INIT_TIMEOUT=` (whole seconds, 1–3600; default 30): how long creating a +- `CHROMAFORGE_GPU_INIT_TIMEOUT=` (whole seconds, 1–3600; default 30): how long creating a compute device (rendering, AI Denoise, faces) and compiling its kernels may go without building a kernel (ten times that in all). See *Device creation time limit* below. @@ -71,7 +68,7 @@ none, so that copy belongs to another program (a Windows SDK, a folder on `PATH` `dxil.dll` beside it (e.g. DXC 1.7) warns that the DXIL is unsigned, wgpu treats the warning as a compile error, its indirect-validation pipelines fail, the device is lost, and the window never opened (`WGPU error: Parent device is lost`). `WGPU_DX12_COMPILER=dxc | auto | fxc` (wgpu's variable) still -chooses; with `dxc`, put `dxcompiler.dll` *and* `dxil.dll` (DXC ≥ 1.8.2502) next to `.exe`. +chooses; with `dxc`, put `dxcompiler.dll` *and* `dxil.dll` (DXC ≥ 1.8.2502) next to `chromaforge.exe`. FXC builds the compute kernels somewhat slower than DXC (≈ 9 s vs 7.5 s for the GPU test suite on an RTX 4080), off the startup path. @@ -93,7 +90,7 @@ skip when the device cannot build the kernels hides this, so read the skip note **Off the startup path.** The compute device is created on a background thread once the window is up (`gpu::warm_up` from the first frame's settings), and never while GPU rendering is off: with Settings ▸ Performance ▸ *Use the GPU for rendering* unchecked (applied before the window opens), -`_GPU=0` or `_GPU_BACKEND=off`, no GPU driver is loaded for rendering at all. +`CHROMAFORGE_GPU=0` or `CHROMAFORGE_GPU_BACKEND=off`, no GPU driver is loaded for rendering at all. **Device creation time limit (issue #3068).** Creating the wgpu instance, adapter and device calls into the driver, which on Linux may first talk to the display server; with one that accepts the @@ -101,14 +98,14 @@ connection and never answers (a crash-looping WSLg compositor, a stale `WAYLAND_ calls never returned, and every render waiting for the device, and every test that creates one, hung for good. wgpu's native calls are synchronous, so each compute device (rendering, denoise, faces) is now created, kernels included, on a thread of its own (`lc-gpu-device`, `crates/gpu/src/init.rs`), and -the caller waits until `_GPU_INIT_TIMEOUT` seconds (default 30) pass with no progress. Each +the caller waits until `CHROMAFORGE_GPU_INIT_TIMEOUT` seconds (default 30) pass with no progress. Each module prepared and each kernel built is progress (`init::Progress`, ticked by `ctx::build_kernels`), so a first start after an install or a driver update, when the driver's shader cache is empty and compiling every kernel takes 30 s on an RTX 4070 SUPER and an RTX 5070 under DX12, still ends on the GPU instead of falling back to the CPU; a creation is given up on at ten times the limit in all (`did not finish in 300 s (10 times …)`), or a limit after its last kernel (`stopped making progress for 30 s … after N kernels`). Past it that device is unavailable for the process, with the -reason `GPU device creation did not finish in 30 s (_GPU_INIT_TIMEOUT): …` reported like any +reason `GPU device creation did not finish in 30 s (CHROMAFORGE_GPU_INIT_TIMEOUT): …` reported like any other creation failure (`perf.gpuReason`, the no-GPU notice, the log), and the blocked thread is left behind. That thread, not the caller, holds what must last as long as the driver work does: its share of the GPU work in flight, so a quit meanwhile finds the GPU busy (`gpu::wait_idle` returns `false` at @@ -130,18 +127,18 @@ deadline of 2 s covers it all; past it the app quits anyway. A job pool that is hosts, tests) waits for its running jobs the same way (`JobPool::shutdown`, `crates/preview/src/pool.rs`). **Crash sentinel.** The desktop app writes `gpu-init.marker` into its settings folder (next to -`ui.json`: `%APPDATA%\`, `~/Library/Application Support/`, -`~/.config/`) just before the compute device is created and its kernels are compiled (and, on the first +`ui.json`: `%APPDATA%\Chromaforge`, `~/Library/Application Support/Chromaforge`, +`~/.config/Chromaforge`) just before the compute device is created and its kernels are compiled (and, on the first AI denoise, before that network's kernels are) and removes it as soon as that returns, successfully or not (issue #250: Apple's Metal compiler, `MTLCompilerService`, aborting on a kernel on an older Intel Mac). A kernel the driver refuses without crashing is caught by wgpu error scopes: the log says why -(`gpu: rendering on the CPU: …`) and renders stay on the CPU. `_GPU=0` (or Settings ▸ +(`gpu: rendering on the CPU: …`) and renders stay on the CPU. `CHROMAFORGE_GPU=0` (or Settings ▸ uncheck *Use the GPU for rendering*) forces the CPU path from the start. If the marker is still there at the next launch, the process died inside the driver: the app starts with GPU rendering off (the preference is saved unchecked), removes the marker and says so in a notice. The same happens after a quit while a device creation that passed its time limit was still inside the driver (above): the driver hung rather than crashed, but it would likely hang again, so the next launch starts on the CPU too. Checking *Use the GPU for rendering* again tries the GPU once more -(and re-arms the sentinel). Not with `_NO_PREFS` (tests, scripts), and not in a `--memory` session, +(and re-arms the sentinel). Not with `CHROMAFORGE_NO_PREFS` (tests, scripts), and not in a `--memory` session, which writes nothing: it neither arms the sentinel nor removes a marker it finds (it still starts with GPU rendering off when one is there, and the next ordinary launch reports and clears it). Quitting the app normally removes the marker even when device creation has not returned yet (a launch closed a few @@ -150,7 +147,7 @@ inside the driver (`backend::release_init_marker_on_quit`, called in `App::on_ex the ~0.3 s of device creation, or two instances starting at the same moment, can trip it falsely — harmless: rendering is then on the CPU until the box is checked again. The sentinel covers the compute device and every kernel build; a crash while the window's renderer starts is avoided by the backend defaults above -or worked around with `_GPU_BACKEND`. +or worked around with `CHROMAFORGE_GPU_BACKEND`. **The window's renderer and its fallback (Windows).** Before the window opens, each renderer is probed in order: Vulkan, DX12, GL, then eframe's OpenGL renderer (glow). A broken Vulkan driver can crash the process before @@ -167,7 +164,7 @@ as a failed start (no "could not start with its … renderer last time" notice, weaker renderer because of it). That second copy writes no marker while the first holds it, so if its own start dies it is not relaunched. A crash or kill releases the lock, so a marker with no live owner (also one an older version left) still counts as a failed start; a copy that hangs inside the driver without dying keeps the lock -until it is ended. An empty or unreadable marker names no failed start. `_GPU_BACKEND=dx12 | vulkan | gl | glow` (or `WGPU_BACKEND`) forces one; DX12 stays +until it is ended. An empty or unreadable marker names no failed start. `CHROMAFORGE_GPU_BACKEND=dx12 | vulkan | gl | glow` (or `WGPU_BACKEND`) forces one; DX12 stays first because a broken Vulkan driver can crash the process uncatchably (#136). Compute keeps its own device and falls back to the CPU as before. @@ -178,7 +175,7 @@ egui-wgpu hook, `on_frame_acquired`, reports each frame that got its texture): a frames — 30 over at least 2 s after the GPU reported a lost device, 600 over 20 s otherwise — means the device is gone. A single skipped frame, a hidden or resizing window never counts. The renderer is then written to `window-lost` in the settings folder (at once, so it survives the process being killed) and dropped from -`window-renderer-2`; every later start tries it last (unless `_GPU_BACKEND` forces it). The library and +`window-renderer-2`; every later start tries it last (unless `CHROMAFORGE_GPU_BACKEND` forces it). The library and settings are saved, a native message box says what happened, and the app ends. **The window's surface: one frame in flight.** The window's wgpu options start from eframe's defaults @@ -191,7 +188,7 @@ texture uploads; renders run on the compute device), which is what `LOW_LATENCY` During a live window resize egui-wgpu still uses three drawables on macOS. **Troubleshooting a crash at startup (Windows).** Start the app from a `.cmd` file or a terminal -with `set _GPU_BACKEND=dx12` (the default since #136), or `=off` to keep the GPU out of +with `set CHROMAFORGE_GPU_BACKEND=dx12` (the default since #136), or `=off` to keep the GPU out of rendering; `set VK_LOADER_DRIVERS_DISABLE=*igvk64*` (Vulkan loader) hides a specific Vulkan driver from every program started with it. Help ▸ System Info and `app.gpu` show the adapter and backend in use (e.g. `Intel(R) UHD Graphics 630 (Dx12)`). @@ -199,7 +196,7 @@ use (e.g. `Intel(R) UHD Graphics 630 (Dx12)`). **The app stops during an export or a render; the log says "device lost" (Windows, issue #1337).** When the graphics driver resets the GPU (the Windows watchdog, a driver hang: DXGI `0x887A0005`, "GPU device instance has been suspended"), renders fall back to the CPU, but the window's renderer (egui-wgpu) -panics on the lost device and the app stops. It says so (" stopped unexpectedly", not "could +panics on the lost device and the app stops. It says so ("Chromaforge stopped unexpectedly", not "could not open its window") and records it in `gpu-lost.marker` in the settings folder: the next start turns *Use the GPU for rendering* off and says why once. Turn it back on in Settings ▸ Performance after a driver update. @@ -219,7 +216,7 @@ walks the drive. `render_now` (CLI, MCP, control channel renders) and exports render on the GPU when one is available; grid/filmstrip thumbnails (many small jobs in parallel) stay on the CPU. - Anything the GPU path cannot do returns `None` and the CPU renders instead: no adapter (CI - machines, software-only adapters), `_GPU=0` or `_GPU_BACKEND=off` (whole + machines, software-only adapters), `CHROMAFORGE_GPU=0` or `CHROMAFORGE_GPU_BACKEND=off` (whole process; see [Backends](#backends-environment-variables-and-troubleshooting-issue-136)), the `app.gpu {enabled}` command (runtime preference; `ui.inspect` → `perf.gpu` shows the adapter), a buffer larger than the device's storage-buffer limit, or a render the device did not complete correctly (see @@ -278,12 +275,12 @@ walks the drive. the dark channel is recomputed). Dropped buffers are recycled (exact size, ≤ 2 GB pool) once the thread that dropped them has submitted — allocating and zero-filling fresh 100–300 MB buffers per pass cost as much as the passes. -- `_PROFILE=1` prints GPU stage timings (each stage is then submitted and waited for). +- `CHROMAFORGE_PROFILE=1` prints GPU stage timings (each stage is then submitted and waited for). ## Limits, failures and the CPU fallback Issue #78: on an Intel UHD (ICL GT1) iGPU with Mesa/Vulkan, exports from the desktop app came out -as valid JPEGs that were entirely black, while previews, ` render` and -`_GPU=0` were fine — and the GPU export took ~15 s against ~3 s on the CPU. The readback +as valid JPEGs that were entirely black, while previews, `chromaforge-cli render` and +`CHROMAFORGE_GPU=0` were fine — and the GPU export took ~15 s against ~3 s on the CPU. The readback returned a buffer the per-pixel stage had never written, with no error. The likeliest cause: the whole export was recorded as one command submission lasting seconds on that GPU, and the driver reset it (GPU hang check / preemption timeout — the app's own window keeps the GPU busy, the CLI @@ -322,19 +319,19 @@ cannot vouch for: | validation / internal error, device lost, readback failure or timeout, incomplete image, panic | CPU | CPU (whole process) | **Diagnosing.** `ui.inspect` → `perf.gpu` (adapter in use), `perf.gpuReason` (why renders don't use -the GPU, e.g. `"disabled by _GPU=0"`, `"software adapter (llvmpipe (LLVM 21.1.8, 256 bits)) +the GPU, e.g. `"disabled by CHROMAFORGE_GPU=0"`, `"software adapter (llvmpipe (LLVM 21.1.8, 256 bits)) skipped: …"`, `"stopped after a GPU failure: device lost …"`), `perf.gpuFallback` (the latest render redone on the CPU and why, e.g. `"6000×4000: the GPU returned an incomplete image (24000000 of 24000000 pixels unwritten); the GPU is not used again"`). The same in `app.gpu` (`reason`, -`lastFallback`), Help ▸ System Info and Settings ▸ Performance. `_PROFILE=1` prints the +`lastFallback`), Help ▸ System Info and Settings ▸ Performance. `CHROMAFORGE_PROFILE=1` prints the fallback with the stage timings; `RUST_LOG=warn` logs it. `perf.gpuFallback` is one value for the whole process, overwritten by the latest render on any thread. A render's *own* reason comes from `lcc_gpu::try_render` (`Err(Fallback::Failed(why))`; `Fallback::NotTried` when the GPU was not used at all), which `lcc_engine::media::develop_reporting` passes on as `RenderResult::gpu_fallback`; an export carries it as `Exported::gpu_fallback`, and each file of an `app.export` batch result has `gpuFallback` when its render fell back (issue #675). -**Reproducing a smaller GPU:** `_GPU_LIMITS=webgpu` (or `downlevel`) creates the device -with 128 MiB storage bindings / 256 MiB buffers, `_GPU_LIMITS=` with n MiB / 2n MiB. +**Reproducing a smaller GPU:** `CHROMAFORGE_GPU_LIMITS=webgpu` (or `downlevel`) creates the device +with 128 MiB storage bindings / 256 MiB buffers, `CHROMAFORGE_GPU_LIMITS=` with n MiB / 2n MiB. Tests inject failures with `lcc_gpu::inject_fault` (`crates/gpu/tests/it/fallback.rs`, `export_falls_back_to_the_cpu_when_gpu_work_is_lost`). The fault is thread-local, and so are its consequences: a simulated fatal failure stops GPU use on the injecting thread only (`available()` @@ -383,7 +380,7 @@ Remaining differences come from f32 vs f64 coordinate math, fast-math transcende Metal and summation order in the box filters — all far below one 8-bit step. ## Measurements -**In the app:** Help ▸ Debug ▸ Frame Rate (`view.frameRate`, `{show?}`; `_FPS=1` +**In the app:** Help ▸ Debug ▸ Frame Rate (`view.frameRate`, `{show?}`; `CHROMAFORGE_FPS=1` starts with it on, never saved) draws frames per second, each frame's UI CPU time against its time spent waiting (for vsync, or for the GPU), the latest whole-frame and zoom-window render times, the render queue, renders thrown away as superseded, the GPU adapter and its memory, and a @@ -392,8 +389,8 @@ numbers (`fps-hud:`), so a scripted drag (`ui.dragWidget`) can be measured from **Present mode** (issue #633): the window presents with FIFO (vsync), except with HDR output on Wayland with an NVIDIA GPU, where it uses Mailbox when the surface offers it (FIFO there missed -vblank at idle clocks: ~95 instead of 144 fps). `_PRESENT=fifo` forces FIFO, -`_PRESENT=mailbox` asks for Mailbox anywhere it is offered; a mode the surface doesn't +vblank at idle clocks: ~95 instead of 144 fps). `CHROMAFORGE_PRESENT=fifo` forces FIFO, +`CHROMAFORGE_PRESENT=mailbox` asks for Mailbox anywhere it is offered; a mode the surface doesn't offer always falls back to FIFO. `render_bench` on `corpus/raw/arw-sony-a7m3-compressed.arw` (24 MP; loupe = 2560 px preview → @@ -416,7 +413,7 @@ On Windows (Radeon 780M iGPU, DX12), a full-size JPEG export of the same raw wit 1.9–2.0 s on the CPU: the horizontal box pass had each thread slide a running sum over 16 pixels, so the threads of a workgroup read pixels 16 apart, and it took 9–15× as long as the vertical pass. Summing each pixel's window instead (adjacent threads, adjacent pixels): 1.9–2.0 s, with the GPU's -NR stage 1.5 → 0.4 s and spatial planes 0.89 → 0.29 s (`_PROFILE`). Per-pass timings come from `_PROFILE` on +NR stage 1.5 → 0.4 s and spatial planes 0.89 → 0.29 s (`CHROMAFORGE_PROFILE`). Per-pass timings come from `CHROMAFORGE_PROFILE` on `cargo xtask bench` (24 MP source). GPU timings include the readback of the 8-bit result and the histogram. The histogram (channels, chroma, vectorscope and waveform grids) is binned on the GPU by `hist_k` (`wgsl/hist.wgsl`: workgroup-local atomics for the 1D bins, global atomics for the grids) over the same ~1 MP sample grid as `Histogram::of_srgb8_covered`, the CPU oracle, and read back with the image in one transfer; `gpu_histogram_matches_the_cpu_oracle` checks they agree exactly. At 24 MP it takes the ~7 ms CPU pass off each render (75 → 68 ms on this machine's GPU). Device creation + kernel @@ -455,7 +452,7 @@ and build time. 512 rows padded by mirror reflection as the CPU pads its tiles, so seams can't show. The CPU's stays the reference: `the_gpu_demosaic_matches_the_cpu` holds every Bayer phase to the CPU's picture but for rounding (under 0.5 % of pixels take the other direction's candidate where rounding tips a homogeneity count). No GPU, - a device failure or `_GPU_DEMOSAIC=0` demosaics on the CPU; X-Trans and other patterns always do. + a device failure or `CHROMAFORGE_GPU_DEMOSAIC=0` demosaics on the CPU; X-Trans and other patterns always do. - The next and previous photos in filmstrip order are prepared in the background once the current one is rendered (decoded source kept, view render cached): stepping through photos shows the developed image in ~50 ms. @@ -466,17 +463,17 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source sources, rendered previews) and the GPU renderer's device buffers (allocated, of which pooled and retired); `ui.inspect` → `memory` adds the loupe's stage caches (CPU images, GPU buffers) and the textures. -- Heap profile: build `` with `--features dhat-heap`; `library.memory` then also - reports live/peak heap bytes and the run writes `dhat-heap.json` (`_DHAT_FILE`), whose +- Heap profile: build `chromaforge-cli` with `--features dhat-heap`; `library.memory` then also + reports live/peak heap bytes and the run writes `dhat-heap.json` (`CHROMAFORGE_DHAT_FILE`), whose allocation sites at the peak (`t-gmax`) show who holds the memory. - Measuring the scenario (import 14 raws from `corpus/raw`, open the loupe, step 12 times): - `/usr/bin/time -l snapshot --script steps.jsonl -o out.png` → "maximum + `/usr/bin/time -l chromaforge-cli snapshot --script steps.jsonl -o out.png` → "maximum resident set size" and "peak memory footprint". Run it several times: the high-water mark is noisy (allocator caching, scheduling). On Apple silicon GPU buffers count in the footprint. - Imports read raw headers only (`lcc_raw::probe_info`): no pixel data is decompressed, except the first rows a few vendor formats need for facts their headers lack (Nikon NEF: the first 128 rows for the masked trailing columns, issue #708). -- One budget (`memory::budget`, default min(25 % of RAM, 16 GiB); by hand at most 75 % of RAM; `_MEMORY_MB` or +- One budget (`memory::budget`, default min(25 % of RAM, 16 GiB); by hand at most 75 % of RAM; `CHROMAFORGE_MEMORY_MB` or `app.memoryBudget {mb}`): half for the engine caches (decoded thumbnail / preview / full sources and rendered previews, evicted least recently used *across* them; the photo on screen stays), a quarter for decodes in flight (`memory::work_gate`: grid thumbnails, neighbour @@ -514,10 +511,10 @@ always its own. A headless `ui.screenshot` reads a GPU-drawn view back (`lcc_gpu - Not offered on an HDR window for now: with the renderer on the window's device, turning an edit's HDR on stopped the Wayland window drawing (Radeon 8060S / RADV, 2026-11-03; no error - logged; fine with a device of its own). `_GPU_WINDOW=1` offers it anyway. -- `_GPU_WINDOW=0`: never offer the window's device (a device of its own, renders read + logged; fine with a device of its own). `CHROMAFORGE_GPU_WINDOW=1` offers it anyway. +- `CHROMAFORGE_GPU_WINDOW=0`: never offer the window's device (a device of its own, renders read back): to compare, or for a driver that misbehaves with compute and drawing on one device. - `_GPU_LIMITS` caps the adopted device as it caps one of its own. + `CHROMAFORGE_GPU_LIMITS` caps the adopted device as it caps one of its own. - `ui.inspect` → `perf.gpuWindowDevice` (renders run on the window's device), `perf.screenTextures` (the UI can draw GPU-resident renders), `perf.mainOnGpu` (the loupe shows one now). - With the renderer on the window's device, errors the device raises outside a render (the window's @@ -534,7 +531,7 @@ on the processor, with no wgpu device.) ## Two graphics cards: who renders batch work -Settings ▸ Performance ▸ Second graphics card (`app.gpu {helper}`; `_GPU_HELPER` wins) sets +Settings ▸ Performance ▸ Second graphics card (`app.gpu {helper}`; `CHROMAFORGE_GPU_HELPER` wins) sets up a device on another card (`helper.rs`). Thumbnails sent there (`lcc_gpu::prefer_helper`) and AI models (`ai_adapter`) use it whenever it is ready. Batch photos (exports, Build Previews, the background preparation, the import's previews) take a **turn per photo** on either card @@ -554,7 +551,7 @@ background preparation, the import's previews) take a **turn per photo** on eith (55 % on the editing card). - 1:1 Build Previews runs two photos per card (`batch_lanes_hint(2)`); exports' automatic lanes grow by the second card's jobs, and a lanes setting made on one card is raised to both cards' - turns plus one (`_EXPORT_LANES` still means exactly that many). The CLI, MCP and tests + turns plus one (`CHROMAFORGE_EXPORT_LANES` still means exactly that many). The CLI, MCP and tests don't track the interface: there both cards simply share photos by speed. - `app.gpu` → `batch.cards`, `batch.rate {editing, helper}`, `batch.renders` (GPU renders so far by card and kind of work) and `batch.interfaceBusy` show it working. diff --git a/docs/grain.md b/docs/grain.md index 9680864552..e69b3faeae 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -113,7 +113,7 @@ Roughness 100 is coarser (1.45× the radius), irregular and 1.37× stronger. Seven settings exported from Lightroom Classic 15.1.1 (process version 15.4) as full-size JPEGs of a 6000 × 4000 chart of flat grey steps (39, 63, 118, 179, 231 of 255), measured on the luminance of each step (900 × 3400 px): the standard deviation in 8-bit levels, and the lag (px) at which the -autocorrelation (mean of horizontal and vertical) falls to ½. "Ours" is ` render` of +autocorrelation (mean of horizontal and vertical) falls to ½. "Ours" is `chromaforge-cli render` of the same chart (CPU), measured the same way; "before" is the grain before this calibration. | Amount / Size / Roughness | Lightroom Classic: sd at 39 · 63 · 118 · 179 · 231; width | Ours | Before | @@ -170,7 +170,7 @@ own settings; Camera Raw has no equivalents. ## Performance -- **GPU** (Chromaforge, 2026-11-03, 6000 × 4000 grey ramp, `_PROFILE=1`, `gpu finish + readback`; +- **GPU** (Chromaforge, 2026-11-03, 6000 × 4000 grey ramp, `CHROMAFORGE_PROFILE=1`, `gpu finish + readback`; the same machine's CPU finish in brackets): no grain 28 ms; Amount 50 at defaults 397 ms (CPU 1312 ms); Size 0 165 ms; Roughness 0 619 ms; Size 100 323 ms; Color 50 1774 ms. At 1900 px (the loupe): defaults 11 ms (CPU 99 ms), Size 0 48 ms, Roughness 0 38 ms, Size 100 83 ms, Color 50 34 ms. Whole renders at @@ -178,7 +178,7 @@ own settings; Camera Raw has no equivalents. 100 in the loupe (≈ 105 ms) and Color 50 on a 24 MP export (≈ 1.8 s) are over them. - **CPU:** works on bands of 8 output rows. Each clump is generated once per band and its grains are splatted onto the pixels they reach (`band_matches_per_pixel` checks the result equals the - per-pixel evaluation). The finish stage (`_PROFILE=1`) of a ` render` + per-pixel evaluation). The finish stage (`CHROMAFORGE_PROFILE=1`) of a `chromaforge-cli render` of the 24 MP chart on 32 threads, fastest of three, the same build settings, before the Lightroom Classic calibration (`765142bac`) and after: diff --git a/docs/guided-filter-memory.md b/docs/guided-filter-memory.md index a8a30f0540..cd31dc103f 100644 --- a/docs/guided-filter-memory.md +++ b/docs/guided-filter-memory.md @@ -29,7 +29,7 @@ Arguments are mode, width, height, integer sigma and timing iterations. The exam before measurement; `--heap` counts one filter call with the source allocated beforehand. Time the runs without `--heap`: allocation profiling significantly changes timings. It reports the minimum wall time; on a shared machine repeat when other builds/renders have stopped. -Use `_PROFILE=1` and `cargo xtask bench` for broader pipeline measurements. +Use `CHROMAFORGE_PROFILE=1` and `cargo xtask bench` for broader pipeline measurements. ## Observed allocation and time diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index fa9707d334..1a4de8ae24 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -34,7 +34,7 @@ correctness is proven on Apple GPUs; other vendors rely on user reports. | Work | Hours | Needs | |---|---:|---| -| HDR display (EDR on macOS, Windows HDR, Linux where possible) | done (2026-10-14, #47) | the vendored egui-wgpu (`vendor/egui-wgpu`, see `vendor/README.md`) configures an `Rgba16Float` surface in extended linear sRGB (scRGB / EDR) where offered, reads the display's headroom and SDR white (`wgpu::DisplayHdrInfo`), and draws the UI at paper white; the loupe shows HDR edits from a float render up to the headroom (whole-frame render; zoomed tiles stay SDR; the float HDR render runs on the GPU when there is one, 2026-10-21). X11 / XWayland stays SDR: X11 has no HDR surface or headroom protocol, a platform limit. On Wayland the headroom comes from the compositor's colour-management protocol (output image description: target max ÷ reference; `apps/app/src/wayland_hdr.rs`), the app then runs native Wayland instead of XWayland, and `crates/hdrmeta` sets Vulkan HDR metadata (peak = headroom × 80 cd/m² × paper white) so KWin shows the range; where the compositor lacks `extended_target_volume` (GNOME's Mutter: Mesa then offers no extended-linear colour space) the window uses an `Rgba16Float` BT.2100 PQ surface instead (the shader converts to BT.2020 and PQ-encodes; SDR white is `_HDR_PAPER_WHITE`, else the compositor's reference white, else 203 cd/m²), checked by eye on GNOME 50.1 / Mesa 26.2.6 (RX 7900 XTX, 700 cd/m² OLED); overrides `_HDR_HEADROOM` / `_HDR_PAPER_WHITE`. ` --hdr-probe` reports what a machine offers. Verified on Windows 11 / RTX 4090 (DX12, `Rgba16Float` scRGB, headroom ≈ 12.9×); Linux: the loupe in HDR confirmed on a laptop panel with KWin 6.7.5 EDR (AMD RADV, headroom 1.4× from the compositor); macOS EDR confirmed on an Apple M1 Max built-in XDR display (2026-10-15); results per machine: PR body | +| HDR display (EDR on macOS, Windows HDR, Linux where possible) | done (2026-10-14, #47) | the vendored egui-wgpu (`vendor/egui-wgpu`, see `vendor/README.md`) configures an `Rgba16Float` surface in extended linear sRGB (scRGB / EDR) where offered, reads the display's headroom and SDR white (`wgpu::DisplayHdrInfo`), and draws the UI at paper white; the loupe shows HDR edits from a float render up to the headroom (whole-frame render; zoomed tiles stay SDR; the float HDR render runs on the GPU when there is one, 2026-10-21). X11 / XWayland stays SDR: X11 has no HDR surface or headroom protocol, a platform limit. On Wayland the headroom comes from the compositor's colour-management protocol (output image description: target max ÷ reference; `apps/app/src/wayland_hdr.rs`), the app then runs native Wayland instead of XWayland, and `crates/hdrmeta` sets Vulkan HDR metadata (peak = headroom × 80 cd/m² × paper white) so KWin shows the range; where the compositor lacks `extended_target_volume` (GNOME's Mutter: Mesa then offers no extended-linear colour space) the window uses an `Rgba16Float` BT.2100 PQ surface instead (the shader converts to BT.2020 and PQ-encodes; SDR white is `CHROMAFORGE_HDR_PAPER_WHITE`, else the compositor's reference white, else 203 cd/m²), checked by eye on GNOME 50.1 / Mesa 26.2.6 (RX 7900 XTX, 700 cd/m² OLED); overrides `CHROMAFORGE_HDR_HEADROOM` / `CHROMAFORGE_HDR_PAPER_WHITE`. `chromaforge --hdr-probe` reports what a machine offers. Verified on Windows 11 / RTX 4090 (DX12, `Rgba16Float` scRGB, headroom ≈ 12.9×); Linux: the loupe in HDR confirmed on a laptop panel with KWin 6.7.5 EDR (AMD RADV, headroom 1.4× from the compositor); macOS EDR confirmed on an Apple M1 Max built-in XDR display (2026-10-15); results per machine: PR body | | Per-monitor profile on Windows and Wayland | 2–4 | multi-monitor setup | | Pen pressure for brush masks: done where winit reports a touch force; macOS and Linux tablets need winit tablet events (or a pure-Rust tablet layer) | 3–8 | a tablet | | Remaining stages on GPU (defringe, spot removal, masks) | 10–20 | | diff --git a/docs/immich.md b/docs/immich.md index 6a48483346..a64110e834 100644 --- a/docs/immich.md +++ b/docs/immich.md @@ -16,7 +16,7 @@ can't use; **Connect** stores the key and starts a link pass. Several servers an (macOS and Windows until a safe backend exists, or a Linux session without a Secret Service), connecting reports it; a passphrase-protected key file is not wired into the UI yet. - Accounts (URL, user, version, permissions, a confirmed certificate fingerprint, path mappings, link progress) live in - `/connections.json`. + `Chromaforge/connections.json`. - Servers older than 3.0 are refused with an upgrade message. - A self-signed certificate (common on home servers) is shown with its SHA-256 fingerprint; *Trust This Certificate* pins it for that account (trust on first use). A changed certificate is refused again. diff --git a/docs/lcc-design-notes.md b/docs/lcc-design-notes.md deleted file mode 100644 index de7e6370f8..0000000000 --- a/docs/lcc-design-notes.md +++ /dev/null @@ -1,820 +0,0 @@ -# LCC "Uniform Light" (flat-field) — design notes - -> Status: exploration only, no code yet (2026-11-05). The maintainer has approved an LCC feature. Scope: a -> flat-field correction like Capture One's LCC "Uniform Light" with an Amount slider. A reference shot through a -> diffuser gives a smoothed **luminance** gain map; the same gain multiplies R, G and B, so there is **no colour-cast -> correction**. Dust removal is out of scope. - -**Naming gotcha before anything else:** every crate in Chromaforge is `lcc-*` / `lcc_*` (the legacy brand prefix, -[`AGENTS.md`](../AGENTS.md) "The name lives in `brand.toml` only"; e.g. `lcc_develop`, `lcc_raw`, `lcc_brand`). A -grep for "lcc" finds the brand, not lens cast calibration, and code named `lcc_*` would read as a crate. The code -should call the feature **flat field** (`vignetting_calibration`, `optics.vignettingCalibration…`); "LCC" stays a UI/docs word. - -## 1. How the Optics vignetting correction works today - -**What it computes.** `Warp` in [`crates/pipeline/src/optics.rs`](../crates/pipeline/src/optics.rs) carries two -vignetting terms: - -- Manual Vignetting: `gain = 2^(vig_stops · r^vig_power)` with `vig_stops = 1.5 · optics.vignetting / 100` and - `vig_power = 1 + 6 · midpoint/100`, `r` = distance from the image centre over the half diagonal, capped at 1.5 - (`Warp::from_settings`, optics.rs:74–92; `Warp::gain`, optics.rs:237–251; `VIGNETTE_STOPS`, optics.rs:30). -- Profile vignetting: DNG `FixVignetteRadial` (`1 + k0 r² + … + k4 r¹⁰`) from the file or the lens database, - scaled by `optics.profile_vignetting / 100` (`embedded_vignette_gain`, optics.rs:396–409; struct - `EmbeddedVignette`, [`crates/develop/src/settings.rs`](../crates/develop/src/settings.rs):1162–1170). It is applied - only when `optics.lens_profile` is on (optics.rs:84–90). - -Both are one scalar per pixel, multiplied into R, G and B alike — exactly the shape a "Uniform Light" gain has. - -**Where in the pipeline.** Stage 1, *geometry*, inside the single resample -([`crates/pipeline/src/lib.rs`](../crates/pipeline/src/lib.rs):7–14 lists the stage order). `sample_warped` -([`crates/pipeline/src/geometry.rs`](../crates/pipeline/src/geometry.rs):502–528) finds each output pixel's source -position `g`, samples it bilinearly and multiplies by `wp.gain(g)` (geometry.rs:521–524). The same gain is used by -generative-fill patches (`crates/pipeline/src/genpatch.rs`:75). The GPU renderer duplicates it: the warp's -parameters are packed into 65 floats (`crates/gpu/src/render.rs`:565–587, `debug_assert_eq!(p.len(), 65)`) and -`warp_gain` in `crates/gpu/src/wgsl/geom.wgsl`:137 is applied at geom.wgsl:194. CPU/GPU agreement is tested in -`crates/gpu/tests/it/equivalence.rs` (33 vignetting references). - -A frame whose warp is the identity has no warp at all (`warp: (!warp.is_identity()).then_some(warp)`, -geometry.rs:94; `is_identity = !moves_pixels() && !has_gain()`, optics.rs:129–131), so a new gain must be part of -`has_gain()` (optics.rs:125–127) or it would be skipped on the Copy/Affine sampling paths. - -Not to be confused with **Effects ▸ Vignette** (post-crop, creative): that runs in stage 5 on display-linear values -after the tone map (`crates/pipeline/src/finish.rs`:109–125, 861–880; GPU `finish.wgsl`:951). - -**Is the data linear there?** Yes. The pipeline's input is "scene-referred, linear Rec.2020 … already EXIF-oriented" -(lib.rs:3–5). For a raw, `load_bytes_now` ([`crates/engine/src/files.rs`](../crates/engine/src/files.rs):715–903) -builds it as: decode → pixel repair on the mosaic (files.rs:738) → optional outlier suppression (740–746) → -`RawImage::develop` / `develop_binned_masked` (normalise, demosaic, `OpcodeList3`, default crop; files.rs:787–802) → -`finish` closure (files.rs:822–841): highlight rebuild → `CameraColourModel::apply` (white balance, camera matrix or -fitted look, DNG profile tables, baseline-exposure gain; files.rs:408–440) → fit to `max_edge` → orient. Exposure is -applied later, in stage 2 (lib.rs:19–21). So at the vignetting stage the values are linear Rec.2020 but already white -balanced, matrixed and scaled by baseline exposure, and not clipped (floats above 1.0 survive). - -**Before or after highlight clipping/recovery?** After. Highlight reconstruction runs in the source load -(`rebuild_highlights` / `rebuild_highlights_masked`, files.rs:420–433, called at 826–829) on camera RGB with the -sensor clip `HIGHLIGHT_CLIP = 0.99` (files.rs:406), before white balance; the algorithm is in -`crates/raw/src/highlight.rs` (header 1–22, `clip_neutral` 28–31). The vignetting gain then multiplies the -reconstructed values. Process versions do not reach the source load ([`process-versions.md`](process-versions.md), -"Changes to how a file is decoded … the process doesn't reach that stage today"). - -**Coordinates.** Neither sensor nor output coordinates: the gain is evaluated at the **source position in the -user-oriented, EXIF-oriented, default-cropped source**, in pixels, normalised by its half diagonal (optics.rs:237–243; -the warp's `w × h` are the oriented source, optics.rs:34–38). So crop, straighten, Upright/Transform and flips don't -move it (the warp maps output → transformed → lens-corrected → source, optics.rs:3–11), and preview/export sizes -agree (resolution independence, AGENTS.md "Non-negotiables"). But it is not sensor-aligned: - -- the active-area crop happens in `RawImage::normalized` and the default crop in `finish_demosaiced` - (`crates/raw/src/lib.rs`:859–929), and non-square pixels are stretched (`stretched_height`, lib.rs:925–928); -- the source is EXIF-oriented at load (`img.into_oriented(raw.orientation)`, files.rs:837) and user orientation is - applied in `Frame::with_lens` (geometry.rs:70–75). - -File-embedded lens data is converted for this: `EmbeddedLens` is stored "converted to the oriented, -default-cropped image" (settings.rs:1112–1116) and re-expressed for the user orientation by `reorient_lens` -(optics.rs:411–446). A flat-field map recorded in sensor coordinates needs the same treatment. - -## 2. Where linear, black-subtracted raw data exists, and could a gain map go there? - -**Where.** `RawImage::normalized` (`crates/raw/src/lib.rs`:859–901) applies `OpcodeList1` on raw values, subtracts -each site's black, scales each site's white to 1.0, crops to the active area, then applies **`OpcodeList2` on the -normalised CFA data** (lib.rs:899). That is the earliest linear, black-subtracted point, still a mosaic and not white -balanced. After demosaic, `develop` gives camera RGB with white = 1.0, not white balanced (lib.rs:903–914), which is -what highlight reconstruction reads. - -**There is already a gain-map mechanism here.** `crates/raw/src/opcodes.rs` parses, writes and applies DNG -`GainMap` (opcodes.rs:88, parse 404, `gain_at` 550, applied in `apply_list` 609–635), including binning/cropping of -its area (opcodes.rs:135–177). A DNG flat field is exactly a `GainMap` in `OpcodeList2`. (Not to be confused with -`crates/raw/src/gaintable.rs`, ProRAW's tone-mapping `ProfileGainTableMap`.) - -**Could ours go there?** It could, but it costs more than it gains for an achromatic map: - -- **Amount would re-decode the raw.** Develop settings that change the source go through `LoadOptions::of` - (`crates/engine/src/media.rs`:179–188) and `DecodedSource::serves` (media.rs:277–285), as `sensor.pixelFix` and - `detail.nr_outliers` do; any change drops the decoded source. A slider drag would then mean a full decode per step, - far past the 16 ms slider budget (AGENTS.md "Testing & performance"). -- **Previews lose the fast path.** `develop_binned` falls back to a full `normalized()` whenever `OpcodeList1/2` are - non-empty (`crates/raw/src/binned.rs`:70), so injecting a map there slows every thumbnail and preview unless the - binned path learns the map. -- **Denoise and highlights must follow.** The AI-denoised twin is made from `raw.normalized()` - (`crates/engine/src/denoise.rs`:1245) and read back as a cached product (files.rs:697–713), so its key would need - the map; highlight reconstruction's clip test (0.99) would need dividing by the gain, or brightened corners read as - clipped. -- **It buys nothing for a uniform gain.** Everything between the mosaic and stage 1 is linear and per-pixel except - highlight reconstruction and the colour tables (`CameraColourModel::apply`, files.rs:436–440). A scalar gain - commutes with white balance and the 3×3 matrix; the hue/sat tables are indexed by hue and saturation, which a - scalar gain leaves alone (a DNG `LookTable` with a value axis is the exception). Raw-stage placement matters for a - **colour-cast** LCC (per-channel gains, which the sensor's colour crosstalk produces); that is out of scope here. - -So the current stage is not "too late" for Uniform Light. The open question is only highlights (see §7). - -## 3. How develop settings are stored and versioned - -**Schema.** `DevelopSettings` (settings.rs:271–347) is one serde struct, `#[serde(default)]` everywhere: missing -fields take defaults, unknown ones are ignored (settings.rs:1–4); `SCHEMA_VERSION = 1` (settings.rs:9). Field names -are snake_case in JSON (`optics.profile_vignetting`); control ids are camelCase (`optics.profileVignetting`). -Optics fields: settings.rs:1050–1107. Fields added later avoid changing old settings' JSON with -`skip_serializing_if = "…::is_default"` (`hdr`, `skin`, `retouch`, `sensor`; settings.rs:286–336), because -`DevelopSettings::hash64` hashes the JSON (`crates/develop/src/lib.rs`:99–106) and that hash keys preview caches and -the catalog's content-addressed `develop_settings` table ([`catalog.md`](catalog.md) "develop settings are -content-addressed"). - -**Process versions.** `ProcessVersion` / `Process` (settings.rs:146–270), now V1…V7, LATEST = V7 -(settings.rs:216–269); rules and table in [`process-versions.md`](process-versions.md): a change to how *existing* -settings render needs a new process; a new setting that is neutral by default does not. A flat field at Amount 0 / no -reference is neutral, so it needs no process. - -**Catalog format.** The catalog format is **16** now, not 13: `VERSION = 16` in -`crates/catalog/src/journal.rs`:91, table at journal.rs:43–60 (13 was `Meta.gps_removed`; [`catalog.md`](catalog.md) -line 112 still says 13 and is stale). The rule (journal.rs:62–66): bump `VERSION` when adding a serialized field "to … -develop settings that an older build would misread or silently drop". In practice recent develop fields (`sensor`, -`hdr`, `skin`) shipped without a row; see open questions. - -**XMP sidecars.** `lc:settings` holds the complete `DevelopSettings` JSON (exact round trip; -[`xmp-interop.md`](xmp-interop.md):32, `crates/engine/src/sidecar.rs`:6, 29, 244), so a new field travels -automatically. `crs:` fields are mapped approximately in `crates/engine/src/crs.rs` (`VignetteAmount` → -`optics.vignetting`, crs.rs:479–480); Adobe has no flat-field equivalent to map. Pixel-filter stacks are the one -thing written under their own namespace instead (sidecar.rs:749). - -**Copy / paste / sync / presets.** `SettingsGroup` in `crates/develop/src/presets.rs`: the Optics group copies the -whole `optics` object (presets.rs:131–134), and `OPTICS_ITEMS` lists sub-items that can be ticked one by one -(presets.rs:228–245). The process is in no group (presets.rs:9–11; process-versions.md "Copy, paste, sync and -presets"). - -**What a new setting needs** (following `sensor.pixelFix` and `optics.vignetting`): - -1. The field with a neutral `Default`, ideally skipped while default, in `Optics` (settings.rs:1050–1107). -2. A control spec for the numeric Amount in `crates/develop/src/controls.rs` (the table at ~295–347; e.g. - `"optics.vignetting" => optics.vignetting, "Vignetting", Optics, -100, 100, 0, 1, 0, Centered;` at 320). Every - slider is a control spec (AGENTS.md "Everything is a command"); clamping of hostile values is tested in - `crates/develop/src/lib.rs`:544–546. -3. A sub-item in `OPTICS_ITEMS` (presets.rs:228–245) so it can be copied without the other optics settings. -4. The reference itself (not a number) set through `develop.merge` like the lens picker's `optics.lens` - (`ChosenLens`, settings.rs:1072–1090) — plus commands for making and listing references (engine command registry, - `crates/engine/src/cmd/`), so UI, CLI, control channel and MCP share them. -5. The renderer: CPU (`Warp`, optics.rs) and GPU (`render.rs` warp params, `geom.wgsl`), with the equivalence test. -6. Catalog `VERSION` bump if the maintainer applies journal.rs's rule to develop fields; `RENDER_CACHE_VERSION` - (`crates/engine/src/media.rs`:65, now 77) only if existing renders change (they shouldn't). - -## 4. The Optics panel in each layout, and locale strings - -- **Desktop (Lightroom-style right panel):** `panels/right.rs`:91 calls `edit::show_controls`, which draws the - section `section(app, ui, &d, "optics", "Lens Corrections", …)` in - [`crates/ui-egui/src/panels/edit.rs`](../crates/ui-egui/src/panels/edit.rs):418–498: Remove CA and Enable Lens - Corrections checkboxes (`develop.merge`), lens note and picker, profile sliders when enabled (435–437), the "New - photos start from" default (442–468), then **Manual**: `optics.distortion`, `optics.vignetting`, - `optics.vignettingMidpoint` (470–474), and the Defringe flyout (476–496). Sliders are `control()` / `control_as()` - (edit.rs:41–50), built from the control specs. Menu entry `section.optics` = Cmd+6 (`crates/ui-egui/src/menus.rs`:199). -- **Modern (touch) layout:** [`crates/ui-egui/src/modern_dock.rs`](../crates/ui-egui/src/modern_dock.rs) — the - Optics dock group's pill sliders are a fixed list `&["optics.distortion", "optics.vignetting", "optics.caRed", - "optics.caBlue"]` (modern_dock.rs:130); its "more" button opens the same Edit-panel sections, `("optics", "Lens - Corrections")` and `("geometry", "Transform")` (modern_dock.rs:108), via `edit::show_section` (modern_dock.rs:472); - a long press on any `optics.*` slider opens the `optics` section (modern_dock.rs:139–148). Docs: - [`android.md`](android.md):15. -- There are two layouts, Desktop and Touch/Modern (Settings ▸ General ▸ Layout; [`android.md`](android.md):15). - `panels/classic.rs` is not a third one: it is the Lightroom Classic–style panel stack of the Library side - (Navigator, Folders, Quick Develop…; classic.rs:1–5), and the Desktop Develop column (`panels/right.rs`:54–93, with - Classic's Previous / Sync… bar from `classic_tools.rs`) shows the same `edit::show_controls`. So there is one Optics - section to change (edit.rs) plus the Modern pill list (modern_dock.rs:130), if the Amount should be a pill too. -- UI tests touching Optics: `tests_develop_panels.rs`, `tests_panels.rs`, `tests_compact_layout.rs`, - `tests_solo_sections.rs`, `tests_lens_db.rs` in `crates/ui-egui/src/`. - -**Locale strings.** Text goes through `crate::i18n::tr("…")`; keys are the English strings -([`localization.md`](localization.md) "How a message is found"). Upstream's catalogs are -`crates/ui-egui/locales/.json`; **Chromaforge's own strings go in `crates/ui-egui/locales/fork/.json`**, -merged over upstream's (`crates/ui-egui/src/i18n_fork.rs`:1–3). `tests_i18n_coverage.rs` fails when a fork string is -missing from a complete language (every language except the `PARTIAL` list: pl, cs, it, ka, sv, fi, id, vi; -tests_i18n_coverage.rs:23–28); the fast gate also checks the fork catalogs are sorted ([`ci.md`](ci.md)). Control -labels ("Vignetting") are translated the same way (e.g. `locales/de.json`:1589). - -## 5. Capture One catalog import - -`crates/engine/src/capture_one_catalog.rs` (1001 lines) reads library data only: "Develop settings are not read yet" -(capture_one_catalog.rs:9–11). `read_with_progress` (279–) loads `ZENTITIES`, `ZIMAGE`, `ZPATHLOCATION`, -`ZVARIANT`, `ZVARIANTMETADATA`, `ZKEYWORD`, collections and `ZDOCUMENTCONTENT` (291–303). The only per-variant -layer lookup is metadata: rating, colour tag, IPTC from the `ZVARIANTMETADATA` rows of the variant's -`ZCOMBINEDSETTINGS`, `ZADJUSTMENTLAYER` and `ZDEFAULTLAYER` (362–366). **Nothing in the importer reads -`ZVARIANTLAYER` or anything LCC-like**; a grep for `ZSTYLESOURCE`, `ZVARIANTLAYER`, `.lcc` or flat field in `crates/` -finds nothing. - -Outside the code (from inspecting a Capture One catalog, read-only): - -- In `ZVARIANTLAYER`, LCC is applied as a *style* layer (entity 19 `VariantStyleLayer`, `ZSTYLESOURCE = 'LCC'`). -- The catalog's `Adjustments/LCC/` folder holds the profiles as `<32-hex>.lcc` files (12–520 KB each). Their header - is a tagged binary container naming "CaptureOne LCC", a version, camera make, model and **body serial**, a raw hash - and a "Chroma" block. The format is undocumented; reading it would be black-box analysis of a user's own files - (allowed for data, AGENTS.md "Clean-room sources"), and is a separate task. - -A Capture One develop import would wait for this tool, so it can bring LCC across in one pass. - -## 6. Tests, CI and PR / changelog conventions - -- **Tests** ([`AGENTS.md`](../AGENTS.md) "Testing & performance"): unit/property tests next to the code (crates use - `tests*.rs` siblings, e.g. `crates/pipeline/src/tests_geometry.rs`, `tests_window.rs`); behaviour and invariants, - no change-detector or golden-image tests; procedural images from `lcc-scenes`, never committed media; hostile-input - no-panic checks for anything parsed (an imported reference or `.lcc`). CPU/GPU parity in - `crates/gpu/tests/it/equivalence.rs`. Process rules have `crates/develop/src/tests_process.rs`. End-to-end: - `apps/cli/tests/`, `crates/mcp/tests/it/e2e.rs`; SIL harness `apps/cli/tests/sil.rs`, `cargo xtask sil` - ([`testing-sil.md`](testing-sil.md)). Tests that can't run here use `lcc_testkit::skip!`. -- **Never crash:** no `unwrap`/`expect`/`panic!`/indexing on input-derived numbers in non-test code, enforced by - clippy (AGENTS.md "Never crash"). A gain map from a file needs `get()`, checked sizes and capped allocations. -- **CI** ([`ci.md`](ci.md)): PRs run `cargo xtask ci --fast` (fmt, brand, docs, notes, i18n sort, clippy - `-D warnings`, parity refs, layers, assets, deny, wasm and Android checks) plus SIL; the full `cargo xtask ci` - runs before releases. One `ci` per machine (`xtask/src/ci_lock.rs`). Per commit: `--fast` + `cargo test -p` of the - touched crates. Perf: `cargo xtask bench`, `_PROFILE=1`. -- **Commits / PRs:** one task id per commit (`M2.3: …`); PR title starts with the checklist id or `Issue #n:` - ([`CONTRIBUTING.md`](../CONTRIBUTING.md) "Open a pull request"); template `.github/PULL_REQUEST_TEMPLATE.md` (Problem, - Change, How it was checked, "Existing edits and libraries", "Shared numbers taken" — catalog `VERSION`, - `RENDER_CACHE_VERSION`, `LOOK_VERSION`, process). A **Sources:** line for every algorithm (here: "own design" / the - DNG spec's GainMap). Branch from latest `main`, merge (not rebase) `origin/main` before pushing. -- **Parity docs in the same commit:** the row for this belongs next to `LR-EDIT-OPTICS-MANUAL` - ([`parity-checklist.md`](parity-checklist.md):299) — a new beyond-Lightroom row; `docs/gaps.md` if listed; - `cargo xtask parity` checks cited ids and paths. -- **Release notes:** `docs/whats-new/-.md` (one `### Title` + bullets; `docs/whats-new/README.md`) - and `docs/changelog/unreleased/-.md` (one `## Develop` section + bullets; - `docs/changelog/unreleased/README.md`). Never edit `docs/whats-new.md` or a released changelog; - `cargo xtask notes --check` enforces it. -- **Docs** name the fork "Chromaforge" and never write binary names or the env prefix outside `.md.in` templates - (AGENTS.md "The name lives in `brand.toml` only"; `cargo xtask brand check`). - -## 7. Open questions - -1. **Highlights in dark corners.** With the gain after highlight reconstruction, a corner that clipped on the sensor - is rebuilt, then brightened past the rest of the frame's clip level. Is that acceptable (it matches today's - vignetting slider), or should reconstruction see the gain? Needs a test on a real flat-field + clipped-corner raw. -2. **Where reference profiles live.** Options: in the settings JSON (a coarse grid, e.g. 64 × 43 f32 ≈ 11 KB, bloats - every edited photo and preset; travels in `lc:settings`), or a per-body store referenced by id, like - `crates/engine/src/sensor_maps.rs` (`/sensor-maps`, per body serial) and camera profiles - (`crates/engine/src/camera_profiles.rs`, `dcp:`). A store keeps settings small but a sidecar or copied - library then carries a dangling id. What happens on the web build, which has no config folder? -3. **Grid and smoothing.** Grid size, smoothing radius, and how the reference is normalised (centre = 1.0, or - brightest = 1.0 so the map only brightens?). Amount: 0–100 linear in stops (`gain^(amount/100)`) or in gain? -4. **Coordinates of the map.** Store it relative to the active area (sensor), then convert per photo for default - crop, pixel aspect, EXIF and user orientation, as `reorient_lens` does; and refuse a reference whose raw size - doesn't match (sensor maps refuse other models/sizes the same way). -5. **Interaction with lens-profile vignetting.** A flat field already removes lens fall-off; should applying one - switch Profile Vignetting off (C1 does not touch its own lens correction), or multiply both? -6. **Catalog format bump.** journal.rs's rule says a new develop field older builds would drop needs a `VERSION` - bump (17), but `sensor`, `hdr` and `skin` shipped without one. Which does the maintainer want here? -7. **Making a reference.** A command on a selected raw (`vignettingCalibration.create`?), batch per lens/aperture, and how the - C1 importer maps an `.lcc` (decode its grid, or ask the user to re-shoot)? -8. **Copy semantics.** Should the reference be in the Optics copy group (so syncing a shoot copies it) — C1's own - workflow copies LCC across the shots of one lens and aperture. - -## 8. Recommendation: where the flat-field stage goes - -**Put the gain in stage 1, inside `Warp::gain`** (`crates/pipeline/src/optics.rs`:237), as a third factor next to -manual and profile vignetting, sampled bilinearly from a smoothed grid at the source position: - -- it is where Chromaforge already applies achromatic fall-off corrections, linear and before every spatial and - tonal stage (noise reduction, local tone, masks), so masks and Auto see the evened-out picture; -- the Amount slider stays cheap: the decoded source is reused and only the geometry resample reruns, like dragging - Vignetting today (no re-decode, no lost binning fast path, no denoise-product key); -- resolution independence, crops, Upright and windowed renders come for free from the existing framing - (geometry.rs:502–528), and generative fill picks it up through the same `gain()` (genpatch.rs:75); -- for a same-gain-on-all-channels map the result equals a raw-stage gain except for highlight reconstruction - (open question 1). - -What it requires: extend `has_gain()` so the warp isn't dropped as identity (optics.rs:125–131); carry the grid on -`SourceInfo` / `Frame` already converted to the oriented, default-cropped frame (like `EmbeddedLens`); add it to the -GPU path (a small storage buffer or texture beside the 65-float params in `render.rs`:565–587, sampled in -`geom.wgsl` `warp_gain`) with an equivalence test; and keep the settings field neutral and skipped while default so -no existing photo's JSON, hash or render changes (no new process). - -Revisit the raw stage (`OpcodeList2`-style `GainMap` in `RawImage::normalized`, `crates/raw/src/lib.rs`:899) only -if colour-cast correction comes into scope later; the GainMap opcode code in `crates/raw/src/opcodes.rs` is the -starting point then. - -## 9. Phase 1: measuring maps (2026-11-05) - -**Amount and what we validate against.** Recent Capture One versions overcorrect at LCC amount 100 (users set -about 43 to look right), while older versions were correct at 100. Chromaforge does not emulate either: - -- The map is measured on linear data and applied on linear data, so amount 1.0 is the physically correct full - correction. `DEFAULT_VIGNETTING_CALIBRATION_AMOUNT = 1.0`, and the range is 0 to 1.2 (Capture One's slider). -- The amount scales the correction in EV: `gain^amount`. -- A map is checked against a second reference of the same setup (`--check` below), not against Capture One's - output. - -**A map is valid only for an identical active area.** It is a grid over the sensor's active area, unrotated -(`VignettingMeasurement::sensor`). Phase 2 must refuse a photo whose active area differs. This includes the same body in -another image area: a Z 7 shot in 5:4 records 6912 × 5520 px instead of 8288 × 5520. It also includes another body -of the same lens, even a near-identical sensor: Z 7 is 8288 px wide, Z 8 is 8280. `--check` always refuses a size -mismatch. - -**What landed** (`crates/raw/src/vignetting_calibration.rs`, CLI `apps/cli/src/vignetting_calibration.rs`): - -- `VignettingMeasurement` (serde, grid of gains ≥ 1, never pre-scaled) and `VignettingCalibrationSource` (camera, serial, lens, focal - length, aperture, SHA-1). -- `build`: - - Takes the green samples of `RawImage::normalized`, which already has any DNG `OpcodeList2` GainMap applied, so - the map measures the fall-off that remains. - - Per-cell trimmed mean; any cell with more than 1 % clipped green samples refuses the reference (`Clipped`, - with the cell and percentage). - - log2, 3 × 3 median and Gaussian, both with odd-reflection padding; normalised to the brightest cell. -- Sampling (`gain_at`, `ev_at`) is bilinear in log space, with linear extrapolation over the last half cell to the - frame edge. -- `SensorFrame` maps between `Warp::gain`'s coordinates (EXIF and user orientation, default crop, pixel aspect, any - fitted size) and the sensor. -- `fit_centre` fits `a + b·d² + c·d⁴` with a coarse-to-fine centre search and reports the offset and RMS. -- `check` reports the residual against the median corrected cell. It passes at max |residual| < 0.05 EV and - peak-to-peak < 0.1 EV. -- ` flat-field REF.raw [--check B.raw [--force]] [--save MAP.json] [--json]` prints corners, the radial table, - the optical centre, and the lens database's vignetting evaluated as `Warp::gain` does. - -Nothing is in the pipeline, the settings or the UI yet. - -**First real references** (17 NEFs, Z 7 and Z 8): - -- All measure without clipping. Corner fall-off ranges from 0.8 EV (500 mm f/5.6) to 3.6 EV (24 mm f/1.8). -- The only same-setup pair with an identical active area (28 mm f/2.8 on the Z 7) fails `--check`: 0.5 EV - peak-to-peak, with centres 4 % apart and fit RMS around 0.05 EV. One of the two shots has uneven light (a sky - gradient or the diffuser). -- The other same-setup pairs differ in image area (5:4 vs 3:2), and the Z 7 / Z 8 pairs differ in width, so they - can't be compared under the identical-area rule. -- Better references are needed: two diffuser shots per setup at the same image area. - -### Phase 1 follow-up: image areas, centre fit, lens database (uncommitted) - -**Image areas of one sensor.** Nikon records where the stored frame sits on the sensor in maker-note tag `0x001b` -(CropHiSpeed: mode, sensor width and height, crop width and height, crop x and y): - -| Camera and image area | CropHiSpeed | -|---|---| -| Z 7, 3:2 | `11, 8288, 5520, 8288, 5520, 0, 0` | -| Z 7, 5:4 | `3, 8288, 5520, 6912, 5520, 688, 0` (centred) | -| Z 8, 3:2 | `11, 8280, 5520, 8280, 5520, 0, 0` | - -- `lcc_raw::sensor_window(bytes, active)` reads it (`crates/raw/src/sensor_window.rs`, `vendor/nef.rs`; it came in with the lens-profile crop-mode fix, PR #856). It returns a window only when the - window's size equals the active area of `normalized()`. -- A map keeps its reference's window. -- `VignettingMeasurement::placement` lets a map serve a smaller image area of the same sensor: offset = origin difference. - Another sensor, an unknown position, or an area the map doesn't cover are refused. -- `relative_offset` is the comparison-only version: a 5:4 map can be checked against a 3:2 shot over the area they - share. -- `find_offset` searches ±64 px (steps of 4, then 1) for the placement with the smallest spread of corrected cells. - -Z 7 results: - -| Pair | Direction | Result | Offset from the file | Best fit | -|---|---|---|---|---| -| 85 mm f/1.8 | 3:2 map → 5:4 shot | PASS (max 0.024 EV, p2p 0.047) | +688, 0 | +648, −13 | -| 85 mm f/1.8 | 5:4 map → 3:2 shot | PASS (max 0.027, p2p 0.047) | −688, 0 | −648, +13 | -| 50 mm f/1.8 | 3:2 map → 5:4 shot | FAIL (max 0.097, p2p 0.128) | +688, 0 | +663, −2 | -| 50 mm f/1.8 | 5:4 map → 3:2 shot | FAIL (max 0.091, p2p 0.119) | −688, 0 | −665, +1 | - -- The 85 mm best fit is about 40 px off the file's offset, consistently in both directions. That is the same as the - difference between the two shots' fitted optical centres (−0.5 % of 8288 vs 0.0 % of 6912 ≈ 41 px). The lens's - centre moved between the shots (in-body stabilisation recentres the sensor between frames), not the crop. The - crop offset itself holds: with no offset the spread is 0.17 EV instead of 0.011. -- The 50 mm pair fails at any offset (the minimum is shallow, 0.021 vs 0.022 EV). Its two shots simply had different - fall-off: different light, or focus distance. - -**Centre fit:** `a + b·d² + c·d⁴ + e·d⁶`, solved with partial pivoting (`None` when nearly singular). "Uneven" -means RMS > max(0.03 EV, 2 % of the mean corner fall-off). With this rule only the 28 mm pair still disagrees; the -known sky shot (a Z 7 300 mm f/2.8 reference) is marked as such. - -**Lens database:** a folder of lensfun XML files. -- Set it in Settings ▸ Import ▸ Lens profiles: Download fetches lensfun's `data/db` into `/lensfun/db`, or - Choose Folder… points at an existing copy. -- The choice is stored in `/lens-profiles.json` (`{"dir": …}`); `_LENSFUN_DIR` overrides it - (`docs/lens-profiles.md`). -- Where a profile has vignetting, the measured corner fall-off is 1.10–1.28× the profile's on full-frame shots. - -**Found on the way, fixed separately (PR #856, `fix/lens-profile-crop-modes`):** the lens-profile lookup scaled the -profile by the developed frame's half diagonal and the camera's crop factor. A 5:4 frame of a full-frame body -therefore got the profile's full-frame corner fall-off at its own, nearer corners: the same 1.912 EV for the 50 mm -at 3:2 and at 5:4. That over-corrected 5:4 by 0.46 EV at the corners (1.447 EV is right) and 16:9 by 0.20 EV. -`lookup_framed` now evaluates the profile for the camera's normal frame and re-expresses it for the image area -exactly. The `flat-field` diagnostic uses it too: after the fix the 85 mm's measured/profile ratio is 1.28 in both -3:2 and 5:4 (it was 1.02 in 5:4). - -Image-area evidence from three Z 8 diffuser shots (50 mm f/1.8; 1:1, DX, 16:9): every cross-check between them -passes (max |residual| 0.005–0.011 EV, peak-to-peak 0.008–0.022 EV), and the offset search finds the CropHiSpeed -offsets within 1–10 px. Ignoring the offset makes the spread 0.18–0.36 EV. An older 3:2 Z 8 shot fails against all -three (peak-to-peak 0.23–0.54 EV), with its centre 1–2 % off theirs: it was lit differently. - -## 10. Phase 2 plan: applying a map in the pipeline, and the UI - -Written 2026-11-05; revised 2026-11-10 against `main` a974417dc, after PR #856 (the crop-mode lens-profile fix) was -merged. Phase 2 makes a measured map part of an edit. It builds on `lcc_raw::SensorWindow`, `lookup_framed` and -`ImageArea` from #856. - -### Name and UI (2026-11-11, later): Vignetting Calibration, Create and Apply - -- **Name:** "Vignetting Calibration" in the UI; in code `vignetting_calibration` (modules, settings - `optics.vignetting_calibration` / `_amount`, commands `vignettingCalibration.*`, library folder - `/vignetting-calibration`, CLI `vignetting-calibration`) and `VignettingMap…` for the stored map - (`VignettingMapId`, `EmbeddedVignettingMap`, `Op::AddVignettingMap`, catalog table `vignetting_maps`). It works like - Capture One's LCC "Uniform Light". Upstream's Library ▸ Flat-Field Correction… (PR #1079, `lcc_raw::flatfield`, - `photo.flatField`) is a separate tool that writes corrected DNG copies; the names keep the two apart. Earlier names in - this section (flat field, LCC, `lens_cast`) are the same feature. -- **Panel:** two buttons. **Create** measures this raw (on a worker thread) and reports its exposure. **Apply** gives - each photo of the selection (or this one) the reference that fits it, picked by `vignettingCalibration.apply` - without a map: same camera model and lens named on both, a zoom within 5 % (at least 2 mm) of the focal length, the - same aperture (since 2026-11-13: the same one only, any body; see *One reference per combination* below). It is off, with a - tooltip, when no reference fits; photos without one are skipped and counted. With a calibration the panel shows its - reference (Show Reference), what differs in one quiet line, the Amount and Remove. Choosing a map by hand is for - commands, the CLI and MCP only (`map` / `key`, `vignettingCalibration.list`). -- **Shooting a reference** (What's New): an OLED screen or a real diffuser, not LCD/IPS (it darkens off-axis and - makes the map too strong); histogram peak at 2/3 to 3/4; 1/30 s or slower on a screen; infinity, tripod, the photos' - lens, focal length and aperture. - -### Withdrawn references, filter and marker (2026-11-12) - -- **Why:** Apply prefers the newest reference, so a bad new one took over silently, and without a list there was no - way back. -- **Withdrawn:** `VignettingMapRecord.withdrawn` (serde default, left out while false) and - `Op::SetVignettingMapState { id, withdrawn }`, whose inverse restores the state before (format 18 still: 18 hasn't - shipped). The table stays append-only. Apply's automatic pick skips withdrawn maps; photos that use one keep it. - Create's batch adds the map withdrawn and then puts it in use, so undoing a Create withdraws its map instead of - leaving it to be picked as the newest; a Create that measures a map the catalog holds puts it back in use. -- **Store:** the v4 store compared vignetting-map rows by id only; it now keeps the records and rewrites one whose - `Arc` changed (an op replaces the record it changes), so a withdraw reaches the next checkpoint. -- **Library:** each library file has `withdrawn` too. Within a catalog the catalog's state wins; a library-only map - uses its file's flag. Every step that sets a state (commit, undo, redo, take-back) rewrites that map's library file, - best effort (`Session::vignetting_after`); a map the library doesn't hold isn't added to it. -- **Derived reference index:** `Catalog::vignetting_reference_states()` (photo → Reference | Withdrawn), built from the - table through `reference_photo` on first use and dropped by every op kind that can change it (the table, files, - SHA-1s, deletion). It feeds the panel's reference block, the Library filter `vignettingReference` - (`reference | none`), the smart-collection field `vignettingReference` (Develop group; Reference / Not a Reference) - and the grid/filmstrip marker, so none of them can be stale. Both map ops touch the reference photo, so - smart-collection tallies follow. -- **The UI shows only references in use** (simplified the same day): the panel offers Stop Using as Reference on an - active reference; a withdrawn one is a normal photo to the panel, the filter, the rule (it counts as "not a - reference") and the marker. Create on it measures the same map (the same id) and puts it back in use, through the - plausibility check. The state itself stays (undo, library files, other catalogs). -- **Commands:** `vignettingCalibration.withdraw` / `.restore` (`map` or the photo's own maps; one undo step; a - library-only map changes its file) and `vignettingCalibration.references` (catalog and library, with state). - -### One reference per combination, the same aperture only (2026-11-13) - -- **Matching:** the aperture must be the same (within `SAME_STOPS` = 1/6 stop); the nearest-aperture order, the - "another body" note and the own-body and newest rules are gone. Apply's automatic pick is the reference in use that - fits; with none, the reason says whether only the aperture is missing (`noReferenceAtAperture`, the panel's - "No reference at f/13 for this lens yet"). -- **One in use per combination** (`same_combination`): camera model, lens (or both unnamed), aperture, a zoom's focal - length within `same_zoom_focal`, and for now the same image area (sensor size and window). Create finds the ones in - use in the catalog and the library (`conflicts`) and replaces them only when asked (the panel's Replace question, - the command's `replace: true`): they are withdrawn in the Create's own undo step (one only in the library joins the - catalog first, in use, so undo restores it there and in its file). Photos that use the old one keep it. Among - references from before this rule that overlap, the one shot last is picked. -- **Image areas** (approved and built the same day): an FX reference serves DX and other crops on the same sensor - (`sensor_at`), not the other way round. Within a setup (`same_setup`: camera model, lens, aperture, zoom focal - length) one reference is in use per image area (`coverage`: the window on the full sensor). Create replaces those - its new reference covers (`covers`: the same area or one inside it), asking first, and adding to the question that - the new one covers the old one's area too; nothing is lost. Those it doesn't cover (a new DX reference beside an FX - one, or partly overlapping areas) stay in use without a question, and the report says so (`keptForOtherAreas`). - Apply uses the tightest image area that covers a photo (`sort_for`). -- **Tests and the reference library:** the app's tests give their sessions no reference library - (`vignetting_calibration_dir_override`) or a temporary one, so they never read or write the settings folder's. -- **VR:** `lcc_meta::Metadata::stabilization` reads the Nikon maker note's VRInfo (`0x001F`, byte 4: 1 on, 2 off). - Every Z 7 / Z 8 raw of a 331-raw sample had it, and it matched ExifTool on all 22 test references (6 on). Create still - creates the reference; its report adds "VR was on: turn it off for references for the most precise result". Three - of the four references with the "unevenly lit" note were shot with VR on. - -### Plausibility check in Create (2026-11-12) - -- `lcc_raw::vignetting_plausibility::check(&Normalized)`: on a 96-cell grid of per-cell trimmed means, the largest - and 99th-percentile deviation of log2 green from its smoothed grid (3 × 3 median, Gaussian σ 1, odd-reflection - padding), the colour structure (robust RMS of log2 R/G, B/G less their smoothed grids), the brightest area's offset, - rings brighter than the ring inside them, `fit_centre`'s RMS, the fall-off, the level and the clipped share. -- **Limits** (borderline / fail): detail max 0.05 / 0.12 EV, detail p99 0.008 / 0.015, colour 0.004 / 0.010, peak - offset 0.10 / 0.25 half-diagonals, rising rings any / 10 %, fit RMS 0.08 / 0.15, clipped 0.1 % / 1 %; fail below a - level of 0.02 or a fall-off of 0.05 EV; a clean pass with fit RMS above 0.03 gets the "unevenly lit" note. -- **Tuning data:** 22 references (20 + two screen shots) and 2 astro flats against 553 ordinary raws: 318 at - random and 235 chosen as hard (fog, snow, dawn, dusk, sunsets, the moon, deep sky, sky, clouds, walls). All flat - fields pass (4 with the note); every photo fails, all on detail. Flat fields reach at most 0.035 EV of detail (a dust - spot), the closest photo 0.159 EV (an 800 mm sky); the worst reference is at 0.7 of the borderline limits. -- **Create:** `measure` runs the check before the map is made and refuses a Fail (`MeasureError::Implausible`, the - reasons and the detail measurement in the message); `commit_measured(…, force)` keeps a Borderline one only with - `force` (the command's `force`, the panel's Create Anyway dialog, which keeps the map measured on the worker thread - so confirming doesn't measure again). The result carries `plausibility: {verdict, reasons, metrics}`. - -### As built (2026-11-11): one PR, maps by reference - -Implemented on `flat-field-render` (rebased on `main` b1d04be13). Where this differs from the plan below, this -section wins. - -- **One PR, not three.** Steps 1–6 (settings, placement, render, library, commands, UI) are one PR; the stabilisation - shift (step 7) stays a later one. -- **Maps by reference, not inline** (replacing decision 1). A catalog stores each map once, in a `vignetting_maps` table - keyed by the map's id (the SHA-256 of its canonical JSON), linked to the reference photo it was measured from - (`lcc_catalog::vignetting_maps`, `Op::AddVignettingMap`). A photo's settings hold only the id and the amount, so History - steps, Versions, copy, paste and sync inside a catalog carry the reference. - - **Append-only.** No op removes a map: removing the reference photo, deleting its file, clearing History and undo - all keep it, and a map is self-contained (nothing reads the reference raw again). A later "clean up unused maps" - would be one op that refuses any id still reachable from a photo's settings, History, Versions or Before view. - - **The reference link is trusted only within one catalog.** Photo ids are unique per catalog only, so the portable - form never carries one; Export / Import as Catalog remaps it or drops it; and `reference_photo` uses a stored id - only when that photo's file has the map's reference SHA-1, else finds the photo by the SHA-1. - - **Portability.** Settings that leave the catalog (XMP sidecars, presets, the clipboard, the control channel and - MCP, `--save-settings`, peer sync) carry the map at `optics.vignetting_calibration_map`; settings that come in store it with - the edit that uses them (`vignetting_calibration_io`). Peer sync leaves photos with a map out of an exchange with a device that - doesn't announce `vignettingCalibration` (an older build would drop the map). - - **Catalog format 18** (17 is upstream's Export status) covers the table, the op and the settings field. -- **The per-body library** (`/flat-fields`) is the cross-catalog store: every map made, under the same id as - in a catalog. Choose from Library lists the library's and the catalog's maps merged by id. -- **Grid: 96 cells along the long side** by default (was 48). On the Z 7 85 mm reference corrected with its own map, - the residual against the centre is a step inside the inner 15 % of the radius, flat outside it: 0.019 EV at 48 - cells, 0.013 EV at 48 without smoothing, 0.007 EV at 96, 0.005 EV at 96 without smoothing. Cell averaging and linear - interpolation flatten the peak at the optical centre; smoothing adds about a third. -- **Several photos at once:** Apply to Selected Photos (`vignettingCalibration.apply` on the selection), Copy / Paste and Sync - Settings (the "Lens Cast Calibration (LCC)" item). -- **No menu item:** Library ▸ Flat-Field Correction… is upstream's separate DNG-copy tool (PR #1079), so LCC is - reached from Develop ▸ Lens Corrections. The names (`vignetting_calibration` in code, Lens Cast Calibration in the UI) keep the - two apart. - -### Where the map multiplies in - -- **CPU:** `Warp::gain` (`crates/pipeline/src/optics.rs`, the `gain` method). It gains a third factor next to - manual vignetting (`vig_stops`) and profile / embedded vignetting (`lens_vig`). - - `Warp` carries an `Option>`: the map already re-expressed in `Warp`'s own frame (the - user-oriented, EXIF-oriented, default-cropped source, at full size) as a small EV grid, plus the amount. - - Doing the coordinate work once, when the frame is built, keeps `gain()` cheap: bilinear in log space, then - `2^(amount · ev)`. It also lets the CPU and the GPU sample the very same numbers. - - The grid is 64 × 64 nodes resampled from the sensor map. It's exact under orientation changes (nodes map to - nodes) and loses nothing visible for a smooth field. -- **`has_gain()`** (optics.rs, next to `is_identity`) must include the flat field. Otherwise a photo with no other - warp takes the Copy / Affine sampling path and the map is silently skipped (`geometry.rs`, the - `(!warp.is_identity()).then_some(warp)` in `Frame::with_lens`). `genpatch.rs` already multiplies by `wp.gain(g)`, - so generative-fill patches follow. -- **Windowed renders:** `Frame::sample_windows` (new on `main`, `f4ae084e8` / `0a99b96be`) renders several windows of - one frame through the same `sample_base` → `sample_warped` → `wp.gain()`. The windows share the frame's `Warp`, so - the field needs nothing extra, but the tests cover that path too. -- **GPU:** - - `warp_params` (`crates/gpu/src/render.rs`) packs the warp into 65 values, guarded by a - `debug_assert_eq!(p.len(), 65)`. It grows by the grid's size, origin and spacing and the amount (in a new - parameter range documented in `geom.wgsl`'s layout comment). - - The `sample_warp` kernel gets a fourth buffer next to `base`, `out` and `coverage`: the EV grid as `f32`. - - `warp_gain` in `crates/gpu/src/wgsl/geom.wgsl` multiplies by `exp2(amount · bilinear(grid, s))`. `pu(64u)` - ("gain?") becomes true when a map is active. -- **Parity tests** (`crates/gpu/tests/it/equivalence.rs`, which already has ~35 vignetting cases), CPU against GPU - within the file's existing tolerance: - - a synthetic map on a rotated, 5:4-windowed source; - - the map plus manual vignetting; - - a `sample_windows` render against the same windows rendered one by one. - -### Coordinates: `SourcePlacement`, extended with the sensor window - -The map is in sensor coordinates (the active area, unrotated). Chromaforge already places a sensor-space map on the -developed source: Apple ProRAW's gain table. It uses `lcc_raw::gaintable::SourcePlacement`, applied per output pixel -in `crates/pipeline/src/local_tone.rs` (`apply_frame`). The flat field reuses that type instead of a parallel path. - -- **What `SourcePlacement` already carries:** `rect`, the developed default crop relative to the active area, and - `orientation`, the EXIF orientation. `active(u, v)` maps normalised source coordinates to the active area. -- **What it handles without changes:** - - **User orientation:** the caller undoes it first, as `local_tone::apply_frame` does - (`frame.orient.inverse()`). - - **Pixel aspect:** everything is in normalised coordinates, where a row stretch is a uniform scale. -- **What it can't carry, and is therefore added:** the **sensor window**. An optional field - `window: Option` (serde-default, skipped when `None`) says where the active area sits on the - full sensor. Without it, `rect` alone can't turn active-area coordinates into a position on a map measured in - another image area of the same sensor (a 3:2 map on a 5:4 photo). The window's `size` also gives the active area - in pixels, so nothing else is needed. -- **The chain:** output pixel → `Warp` source position → undo user orientation → `SourcePlacement::active` → - × active size, + `window.origin` (sensor) → − the map's `window.origin` (`VignettingMeasurement::placement`) → - `VignettingMeasurement::ev_at`. -- **Phase 1's `SensorFrame`** (`crates/raw/src/vignetting_calibration.rs`) becomes a thin wrapper over `SourcePlacement`, kept for - the `flat-field` diagnostic, so there is one mapping. -- **Requirements:** - - Phase 1's orientation round-trip test (8 EXIF × 8 user orientations, a crop offset, pixel aspect 2.0) and the - window tests run through the `SourcePlacement` path. - - With `window` unset, ProRAW gain tables behave exactly as before: the existing `local_tone` / gain-table tests - unchanged, and a byte-identical render of the corpus ProRAW sample (`raw/dng-apple-iphone12pro-proraw.dng`, - CC0, raw.pixls.us) before and after. -- The decode path (`crates/engine/src/files.rs`, `load_bytes_now`) builds a `SourcePlacement` with the window for - every raw, the way `local_tone()` builds one for ProRAW today, and keeps it in `SourceInfo`, next to the new - `lens_from_file` (upstream #3781). The raw is still oriented at decode (`img.into_oriented(raw.orientation)`), so - the chain above holds. - -### Interaction with other vignetting - -- **The flat field is independent of "Enable Lens Corrections".** A map applies whenever the photo has one, whether - profile corrections are on or off. Since `92ddacfe3` ("LENS-OFF", 2026-11-10), new photos start with lens - corrections off except DNG, RW2 / RWL and RAF built-in corrections, so the flat field alone is the common case. -- **When both are on**, profile and embedded vignetting are off (`lens_vig` = 0 whatever - `optics.profile_vignetting` says): the map is the measured truth for this lens and aperture, and both would correct - twice. Profile **distortion and lateral CA stay**, since the map is luminance only. -- **Manual lens vignetting** (`optics.vignetting`, `vig_stops`) stays as a fine-tune on top. Post-crop vignette - (Effects) is unaffected. -- The Optics section says so: "Profile vignetting is replaced by the flat field" under the profile sliders, which - are disabled for vignetting only. -- **The camera-look fit:** since upstream #3402 (5bc88f079), the per-file camera look - (`camera_preview::correct_vignetting`) is fitted on a sensor proxy corrected with the lens-profile vignetting the - render applies. On `main` that's `LOOK_VERSION` 22, and `7f470722a` (DCP-KEEPS-TONE) passes the same correction - into its new `tone_without_profile` path. - - That fit runs at decode, before any develop setting is known. - - **Proposal for Phase 2:** keep it on the lens profile, so the fitted look doesn't depend on a develop setting - (switching the flat field on or off must not refit the look or change the decoded source). - - The cost: a photo whose profile vignetting is off because of a flat field gets a look fitted with a slightly - different correction than the one rendered. - - **Maintainer question:** is that acceptable, or should the fit take the flat field when the photo has one? - -### Storage - -- **In the develop settings.** - - Fields: `optics.vignetting_calibration: Option` (the map) and `optics.vignetting_calibration_amount: f64` (0–120, - default 100). Both are serde-skipped while there is no map, so every existing photo keeps its JSON and - `hash64`. - - The map is stored compactly: grid size, sensor, window, source (body model and serial, lens, focal length, - aperture, SHA-1), and the gains as log2 in 1/4096-EV `u16`, base64. A 48 × 32 grid is 3 KB of JSON. - - Copy, paste, sync and presets carry it through the Optics group (a new `OPTICS_ITEMS` entry), and XMP sidecars - through `lc:settings` (the full settings JSON). - - **Cost:** the catalog stores each distinct settings value once (`develop_settings` table, content-addressed). - But every History step and Version of an edited photo is a distinct value, each with its own 3 KB copy. On a - photo with 50 steps that's ~150 KB. Acceptable: maps are inline (decision 1 below), not referenced by hash. -- **Partial presets** (upstream #2207: "a preset changes only the settings it names"). The rule, explicitly: - - A preset that names only `optics.vignetting_calibration_amount` sets the amount. On a photo with a map that changes the - correction. On a photo without one it changes the stored amount and has no visible effect, and no map is - created. - - A preset that names `optics.vignetting_calibration` sets the map and the amount together. If it doesn't name the amount, - the amount becomes the default (100 %), so a map is never applied at a stale amount from an earlier map. - - A preset that names `optics.vignetting_calibration` as `null` removes the map and leaves the amount alone. - - Applying a preset never refuses a map: a map that doesn't fit the photo (see *Matching*) is stored and shown as - not applied. -- **A per-body library of maps to pick from**, like the hot-pixel maps (`crates/engine/src/sensor_maps.rs`: one JSON - file per body in `/sensor-maps`, keyed by `body_key`, damaged files set aside as `.bad`). - - New `/flat-fields//___.json`, each a `VignettingMeasurement`, validated on - read. - - "Create from this photo" adds the map there and to the photo. "Choose from library" lists the body's maps, - best match first. - - The library is a convenience; a photo's own copy in its settings is what renders. -- **Web build:** `config::config_dir()` gives no settings folder there, so there is no per-body library on disk. - - The settings copy works unchanged (it lives in the catalog and in exported sidecars). - - "Choose from library" there lists the maps of photos already in the library (the distinct `optics.vignetting_calibration` - values). - - "Create from this photo" works if the source raw is available (the web build decodes raws). - -### Matching a map to a photo - -| Check | Result | -|---|---| -| Active area not the map's, and no window that places it (`VignettingMeasurement::placement` → `Mismatch`) | **refused**: not applied, with a notice in Optics | -| Another sensor (window's sensor size differs, e.g. Z 7 8288 vs Z 8 8280), or camera model differs | **refused** | -| Same model, another body serial | not checked (2026-11-13): any body of the model serves | -| Lens differs (both named) | **refused** | -| Focal length differs (zoom) | within 5 % (at least 2 mm) a note with the difference, further **refused** | -| Aperture differs (2026-11-13) | **refused** beyond a sixth of a stop (every third-stop step stays apart): the fall-off changes with the aperture, so a reference serves only its own aperture. Recorded on one side only: **refused**; on neither (adapted or manual lenses): applies, with "can't be checked" | -| Focus distance | not checked: NEFs don't give a usable one yet (see *Focus distance* below) | - -A refused map is kept on the photo (so a later fix or another photo can use it) but has no effect. "Choose from -library" shows only maps that can be placed. - -### Focus distance - -Fall-off depends on focus distance as well as aperture, so matching could use it. What the 20 Z 7 / Z 8 NEFs -record: - -- **EXIF SubjectDistance (`0x9206`):** absent in every file. -- **Nikon maker note `0x0098` LensData:** present in every file, 108 bytes, version `0800` / `0801` (Z 7) and `0802` - (Z 8). - - Per ExifTool's Nikon tag-name documentation, LensData from version 0201 on is enciphered with the body serial - (`0x001d`) and the shutter count (`0x00a7`), both of which these files record. - - Earlier versions carry a one-byte, log-scale focus distance. Whether 0800–0802 do, and at what resolution, can't - be checked without deciphering. -- **Deciphering, under the licence policy of 2026-11-10** (AGENTS.md, "Third-party sources"): - - Both sources are now usable: dcraw's Nikon decipher (its `xlat` tables; all of dcraw is allowed), and ExifTool's - code and tables (ExifTool is distributed under Perl's terms, Artistic or GPL). - - Either needs provenance: a `Sources:` line, module docs saying "translated from", and a `NOTICE` credit with the - licence text. - - A port from a share-alike source stays Chromaforge-only (never offered upstream), and a binary that ships it is - under the GPL's terms. -- **Reliability**, even once decoded: Nikon reports the lens's focus position, quantised. It is typically coarse at - long distances, "infinity" past a few tens of metres, and meaningless or absent with manual and adapted lenses - (four of the 20 files name no lens at all). -- **Proposed experiment** before relying on it: shoot one lens at known distances (0.5 m, 1 m, 3 m, infinity), several - frames each. Decipher LensData and check the value is monotone in distance and repeatable at each one. -- Until then matching ignores focus distance, as the lens-profile lookup does (`Shot::distance` is `None`). - -### Z 8 in-body stabilisation centre (NEFInfo `0x0008`) - -- `crates/raw/src/vendor/nef_lens.rs` already reads the optical centre's offset from the image-area centre (entry - `0x0008`, "where the in-body stabilization left the sensor"). It's validated for the Z 6II, Z 8 and Z f, and is up - to ~100 px with Z lenses (−90.1, +18.6 in one file). -- Vignetting is centred on the lens axis, so between a reference and a photo shot with different sensor positions - the map should move by the difference of their offsets. -- **How big:** a 50 mm f/1.8 corner fall-off of 1.9 EV has a slope of about 4.8 EV per half diagonal at the corner, - ~0.001 EV per px on a 45 MP sensor. 100 px of shift is about ±0.1 EV at opposite corners, 40 px about ±0.04 EV. - That matches the ~40 px seen between the two Z 7 85 mm shots, which left 0.011 EV of spread against 0.002 at the - best placement. -- **Proposal:** - - Shift by `photo offset − reference offset` where both files record it (Z 6II / Z 8 / Z f), as an extra - placement offset; otherwise no shift. - - Validate with two Z 8 references shot handheld (IBIS on) against one on a tripod (IBIS off): the `--check` - residual with the shift should drop to the tripod pair's. - - The Z 7 isn't validated for `0x0008` yet (it isn't in `VALIDATED`); check its files first. - -### UI - -- **Desktop, Lens Corrections section** (`crates/ui-egui/src/panels/edit.rs`, the `section(app, ui, &d, "optics", - …)` block): a "Flat Field (LCC)" sub-section under the profile controls, shown whether or not Enable Lens - Corrections is on. - - With no map: **Create from This Photo**, and **Choose from Library…** (a list: body, lens, focal length, - aperture, date, match warnings). - - With a map: its source line (lens, focal length, aperture, body, any warning), the **Amount** slider (control - `optics.vignettingCalibrationAmount`, 0–120, default 100, step 1), and **Remove**. - - The compact layout's short-label map (`edit.rs`, the match from control id to short name, e.g. - `"optics.profileVignetting" => "Vignetting"`) gains `"optics.vignettingCalibrationAmount" => "Amount"`. - - Create on a clipped or too-dark photo shows the builder's error (`Clipped` names the cell and the percentage). -- **Modern dock:** the Optics group (`crates/ui-egui/src/modern_dock.rs`, `Group::Optics` in `control_ids`) gains the - `optics.vignettingCalibrationAmount` pill while the photo has a map. The rest is in the Lens Corrections section the group - already opens. -- **Library menu:** `main` already lists a placeholder, `soon.flatField`, "Flat-Field Correction…" - (`crates/ui-egui/src/lrc_menus.rs`, the `COMING_SOON` table; issue #983). - - PR B wires it to Create from This Photo for the selected raw, and opens the Lens Corrections section on it. - - Its tooltip changes, because the current one ("Correct lens cast and vignetting from a flat-field reference - frame") promises colour-cast correction, which this feature doesn't do. New text: "Even out lens fall-off from a - flat-field reference shot." -- **Commands** (everything is a command; UI, CLI, control channel and MCP share them): - - `vignettingCalibration.create {id?}` (from the photo's raw; adds to the library and applies); - - `vignettingCalibration.list {body?}`; - - `vignettingCalibration.apply {map, ids}`; - - `vignettingCalibration.remove {ids}`; - - the amount through `develop.set` / `develop.merge`. -- **Copy and sync:** `OPTICS_ITEMS` (`crates/develop/src/presets.rs`) gains `item("optics.vignettingCalibration", "Flat Field - (LCC)", &["optics.vignetting_calibration", "optics.vignetting_calibration_amount"])`. Syncing across a shoot then carries the map to - every photo of that lens and aperture, as Capture One users expect. -- **Locale strings:** every new label and message goes into all 17 fork overlays - (`crates/ui-egui/locales/fork/.json`). - - #946 holds every language to the coverage tests (the old partial-language list is gone), and #935 scans every - source file for text shown without `tr`. - - No em dash (U+2014) in UI copy: `ui_text_has_no_em_dashes` (`62b588ade`) fails on one. Use a comma, colon, - full stop or parentheses. - - Labels: "Flat Field (LCC)", "Create from This Photo", "Choose from Library…", "Remove", "Amount". - - Notices: "Profile vignetting is replaced by the flat field", "Made with another lens", "Made at another aperture - ({diff} stops)", "Made on another camera body", "This flat field doesn't fit this photo's image area". - -### Process version, catalog version - -- **No process version:** the fields are new and off by default, so no existing photo renders differently - (`docs/process-versions.md`; V8 is the latest process on `main`). -- **Catalog `VERSION`** (`crates/catalog/src/journal.rs`, still 16 on `main`): bump to 17. An older build would - silently drop `optics.vignetting_calibration` when it saves the photo, which loses the user's map, which is the case the rule - ("a serialized field … an older build would misread or silently drop") is for. Earlier develop fields (`sensor`, - `hdr`, `skin`) shipped without a bump, but dropping them cost a setting, not measured data. -- **`RENDER_CACHE_VERSION`:** no bump; photos with a map have a new `hash64`. - -### Phase 2 steps, each separately testable - -1. **Schema:** `EmbeddedVignettingMap` (compact encoding, serde round trip, hostile input), the two Optics fields, the - control spec, the `OPTICS_ITEMS` entry, the partial-preset rule, the catalog `VERSION` bump. Tests: settings - without a map keep their JSON and hash; copy/paste carries it; damaged maps load as "no map". -2. **Placement:** `SourcePlacement` gains `window`; `SourceInfo` carries one for every raw from the decode path; - the field grid is built from it and `placement`. Tests: all 8 × 8 orientations and the 5:4 / 1:1 / 16:9 / DX - windows give each sensor position its map value, through `SourcePlacement`; ProRAW unchanged; a refused map gives - no field. -3. **CPU render:** `Warp::gain` and `has_gain`, profile vignetting off while a map is active, independent of Enable - Lens Corrections. Tests: a synthetic fall-off source corrected flat to < 0.01 EV; amount 0 / 100 / 120; manual - vignetting still applies; `sample_windows`; no map → byte-identical renders. -4. **GPU render:** the extra buffer and parameters, `warp_gain`; the equivalence tests. -5. **Library and commands:** `/flat-fields`, `vignettingCalibration.create/list/apply/remove`, MCP schema, the activity - stack for Create (a full decode). Tests: hostile files set aside; a matching table for the warnings; the web - build without a folder. -6. **UI:** the Optics sub-section, the short label, the Modern pill, the Library menu item and its tooltip, locale - strings in all 17 overlays, What's New. Verify by running the app and taking screenshots; a SIL step that creates, - applies and removes a map. -7. **IBIS shift** (Z 6II / Z 8 / Z f): the placement offset from NEFInfo `0x0008`, after the tripod / handheld - validation above. -8. **Later:** importing Capture One's LCC from the catalog (the paused develop import), and writing the map into - DNG export as an `OpcodeList2` GainMap. - -Every commit passes `cargo xtask ci --fast`, the targeted `cargo test -p` and `cargo xtask sil` before it is pushed -(AGENTS.md, quality gates of 2026-11-10). - -### Decisions (2026-11-06, extended 2026-11-10) - -1. **Maps are inline** in the develop settings, about 3 KB each, not referenced by hash. Inline travels by itself - through XMP, copy, sync and presets, and needs no catalog table or import path. -2. **The field in `Warp`'s frame is a 64 × 64 `f32` grid**, on the CPU and in the GPU buffer alike (16 KB; no - `f16`). -3. **Nearest aperture only in Phase 2.** With references at several apertures, a photo gets the one nearest in - stops, with the aperture warning. Interpolating between two references (a log-space blend by stops) comes later. -4. **Uneven references warn, they don't refuse.** A reference the centre fit flags (`CentreFit::uneven`), or one - whose centre is far off, is accepted with a notice in Optics. Clipped and too-dark references are still refused - by the builder. -5. **The Z 7's stabilisation offset** (NEFInfo `0x0008`) is checked in step 7, together with the shift. -6. **Amount range 0–120 %**, default 100 %. -7. **The camera-look fit stays on the lens profile**, pending the maintainer (see *Interaction with other - vignetting*). -8. **The flat field doesn't depend on Enable Lens Corrections.** When both are on, profile vignetting is off; profile - distortion and lateral CA stay. -9. **Placement reuses `SourcePlacement`**, extended with an optional sensor window, instead of a parallel type. -10. **Partial presets** follow the rule under *Storage*: the amount alone never creates or applies a map; a map - without an amount comes with 100 %. - -### PR split - -- **PR A: steps 1–4.** Schema, placement, CPU and GPU render, so a map in the settings renders, and renders the same - on both paths. Reviewable on its own with synthetic maps; nothing visible in the UI yet. -- **PR B: steps 5–6.** Library, commands and UI: creating, choosing and removing maps, the Amount slider, the Library - menu item, locale strings and What's New. This is what users see. -- **PR C: step 7.** The stabilisation shift, after the tripod / handheld validation. It changes renders of photos - that already have a map, so it lands on its own with its measurements. -- Step 8 stays later. - -### Questions for the maintainer (issue #857) - -1. **Catalog `VERSION`:** bump it for `optics.vignetting_calibration`, since an older build would drop the user's map when it - saves? (`sensor`, `hdr` and `skin` shipped without a bump.) -2. **Camera-look fit:** keep the per-file look fitted with the lens-profile vignetting even when a flat field - replaces it in the render, so decoding doesn't depend on a develop setting? Or fit with the flat field? -3. **PR split:** A (render path) → B (library, commands, UI) → C (stabilisation shift), as above? diff --git a/docs/lens-profiles.md b/docs/lens-profiles.md index cf987cfc19..8d5575f843 100644 --- a/docs/lens-profiles.md +++ b/docs/lens-profiles.md @@ -23,7 +23,7 @@ files were last updated) and offers: The folder is an app setting (`lens-profiles.json` in the settings folder), shared by every library, the CLI and the MCP server. A change takes effect at once, without a restart: the database is reloaded and the photo open in Develop is looked up again (other photos when they are next opened in Develop, or with `lens.db.refresh`). -`_LENSFUN_DIR` still works and overrides the folder chosen in Settings (the section says so). +`CHROMAFORGE_LENSFUN_DIR` still works and overrides the folder chosen in Settings (the section says so). Develop ▸ Optics says why **Enable Lens Corrections** has nothing to apply to a raw without its own correction: no lens database (a link to the Settings section), no lens named in the photo's metadata, or no profile for its lens. @@ -31,7 +31,7 @@ lens database (a link to the Settings section), no lens named in the photo's met Commands: `lens.db.status`, `lens.db.setDir {dir}`, `lens.db.download {wait?}`, `lens.db.downloadCancel`, `lens.db.remove`, `lens.db.refresh {ids}`, `lens.db.photo {id, lens?}`, `lens.db.list {mount?, crop?, query?, limit?, offset?}`; `app.settings {section: "lensProfiles"}` opens the section. Invalid files are skipped with a warning in the -log. Each read logs the folder, whether it is the Settings folder or `_LENSFUN_DIR`, and how many lenses and +log. Each read logs the folder, whether it is the Settings folder or `CHROMAFORGE_LENSFUN_DIR`, and how many lenses and cameras it holds; a folder that is missing or holds no lenses is logged as a warning. ## Which correction applies diff --git a/docs/library-shortcuts.md b/docs/library-shortcuts.md index 2c74fb962c..956841a2ac 100644 --- a/docs/library-shortcuts.md +++ b/docs/library-shortcuts.md @@ -88,10 +88,15 @@ on 2026-10-08; this work extends its fix with library culling bindings and tests ## Grid thumbnail size `=` makes the grid thumbnails larger and `-` smaller (`+` also enlarges), as in Lightroom Classic. Each -press moves the bottom-bar slider by 30 pt within its 90–480 pt range and stops at either end. The keys -work in Photo Grid, Square Grid and People (the views with the slider), do nothing in Detail, Compare, -Survey and Reference, and leave text fields alone, so the search box still types `-` and `=`. `⌘=` / -`⌘−` remain Zoom In / Out. The same steps are the View ▸ Increase / Decrease Grid Thumbnail Size +press moves the bottom-bar slider within the range it shows (90–480 pt) and stops at either end. In Square Grid a +press adds or takes away one column; in Photo Grid it goes to the next size at which a row changes (the last +row of each group grows alone with the size and is not a step, so the keys and the slider end where only +those rows would still grow); People moves 30 pt. The keys +work in Photo Grid, Square Grid and People (the views with the slider), and in the loupe, where they first +switch to the grid last shown and resize it (as in Lightroom). They do nothing in Compare, Survey and +Reference, and leave text fields alone, so the search box still types `-` and `=`. `⌘=` / `⌘−` are Zoom In / Out +in the loupe; in a grid `⌘=` opens the active photo in the loupe at Fit and `⌘−` does nothing (View ▸ Zoom In / +Out follow the same rules). The same steps are the View ▸ Increase / Decrease Grid Thumbnail Size commands (`view.thumbSizeUp`, `view.thumbSizeDown`, reachable from the control channel and MCP, which return `{"size"}`); the size is saved with the other interface settings. diff --git a/docs/licence-conversion.md b/docs/licence-conversion.md new file mode 100644 index 0000000000..91525e3188 --- /dev/null +++ b/docs/licence-conversion.md @@ -0,0 +1,60 @@ +# Converting contributed code to GPL-3.0-or-later + +Core Chromaforge code is `GPL-3.0-or-later` only (2026-11-30). Code that predates +that change may still be offered under the terms it was contributed under, +usually `MIT OR Apache-2.0`. The copyright holder can convert their own work; +nobody else can. This page is for that pull request. It is not legal advice. + +## Who can convert what + +- Only the copyright holder (or someone with their written permission) may + relicense a contribution. The contributor is normally the holder, unless an + employer owns the work. +- Convert only the contributor's own original code, data and assets. +- Leave adopted third-party code, vendored dependencies and anything owned by + another copyright holder untouched. They keep their original licence and + `NOTICE` / `assets/ATTRIBUTION.md` entry. +- If ownership is unclear, stop and ask. Do not guess. + +## What the PR changes + +1. Confirm that the contributor asked for the conversion and owns the code. + Link the issue or comment in the PR's **Permission** section. +2. Find the work: `git log --author`, SPDX/file headers, `Cargo.toml` `license` + fields, `NOTICE`, `assets/ATTRIBUTION.md`, and translation rows. +3. Set the licence to `GPL-3.0-or-later` (or the crate's existing GPL-compatible + expression) everywhere that names it for the converted work: crate manifest, + SPDX/file header, `NOTICE`, `assets/ATTRIBUTION.md`, README or licence + statement, translation table. +4. Leave every other copyright holder's notice in place. +5. Update [`docs/license-status.md`](license-status.md) in the same PR: the + inventory row, any ambiguity the conversion clears, and the "Next" list. A + conversion PR is not finished while that page still describes the old + licence. +6. Check: + - `git grep -n -i 'MIT\|Apache-2.0' -- `; every remaining hit + must be adopted code that correctly keeps its licence. + - `cargo xtask brand check`, `cargo xtask docs --check`, `cargo xtask assets`. + - `cargo deny check licenses` when a manifest changed. +7. Open the PR with [the licence-conversion + template](../.github/PULL_REQUEST_TEMPLATE/licence-conversion.md) (add + `?template=licence-conversion.md` to the compare URL), or copy it by hand. + +## If you are an agent + +The person you are working with is the author. Before editing: + +- Ask once whether the code is theirs and whether they want it converted to + `GPL-3.0-or-later`. If they are not the copyright holder, stop. +- Do not convert adopted third-party code, and do not remove its notices. +- Do not invent permission, and do not give legal advice. +- Update `docs/license-status.md` in the same PR; the conversion is incomplete + without it. +- Put the person's own words for the permission in the PR, and commit as them. + +## Notes + +- The MIT text stays in `LICENSE` for adopted MIT modules even after a + contributor's own code is GPL-only. Do not delete it. +- A crate that also carries adopted Apache-2.0 code keeps its dual expression + until that code is separated. See `docs/license-status.md` → "Ambiguities". diff --git a/docs/license-status.md b/docs/license-status.md new file mode 100644 index 0000000000..26ade33fc9 --- /dev/null +++ b/docs/license-status.md @@ -0,0 +1,161 @@ +# Licence status + +Snapshot: 2026-11-30, after the GPL conversion. Source of truth: each crate's +`Cargo.toml`, `NOTICE`, `LICENSE*`, and the per-file notices named below. This +document is an inventory, not legal advice. + +## Rules this inventory applies + +- **Core Chromaforge code is `GPL-3.0-or-later` only.** It is not MIT. +- **Adopted code must be GPL-3.0-compatible or Apache-2.0.** MIT is allowed only + as a complete, isolated module/library or a plugin, with provenance in `NOTICE`. +- **No upstream code is taken, whatever the licence.** Upstream is ideas-only; + see [`docs/upstream-pr-intake.md`](upstream-pr-intake.md). +- New contributions are accepted under `GPL-3.0-or-later` only. +- **A contributor converting their own code follows [`docs/licence-conversion.md`](licence-conversion.md)** and + updates this page in the same PR. +- A crate's manifest licence is **package-level**. An adopted file can still be + under its original licence, named in `NOTICE` or its file header. That is why + some entries below are marked **ambiguous**. + +## Workspace crates + +All workspace crates below are `GPL-3.0-or-later` unless the next table says +otherwise. + +### Apps + +`lcc-android`, `lcc-app`, `lcc-cli`, `lcc-cli-launcher`, `lcc-web` — core +application code, GPL-only. + +### Tooling + +`xtask` — core tooling, GPL-only. + +### Core crates + +`lcc-actions`, `lcc-android-host`, `lcc-audio-out`, `lcc-book`, `lcc-brand`, +`lcc-camdb`, `lcc-catalog`, `lcc-classic-slideshow`, `lcc-codecs`, `lcc-color`, +`lcc-colourfit`, `lcc-credentials`, `lcc-denoise`, `lcc-denoise-core`, +`lcc-develop`, `lcc-diag`, `lcc-engine`, `lcc-faces`, `lcc-fidelity`, +`lcc-filters`, `lcc-firstclick`, `lcc-fuzzkit`, `lcc-genfill`, `lcc-geo`, +`lcc-geocode`, `lcc-geom`, `lcc-gpu`, `lcc-gpumem`, `lcc-hash`, `lcc-hdrmeta`, +`lcc-heif`, `lcc-immich`, `lcc-inpaint`, `lcc-layout`, `lcc-lensdb`, `lcc-mcp`, +`lcc-merge`, `lcc-meta`, `lcc-ml`, `lcc-net`, `lcc-notes`, `lcc-onnxrt`, +`lcc-opendocs`, `lcc-pdf`, `lcc-peer`, `lcc-pipeline`, `lcc-plugins`, +`lcc-preview`, `lcc-print`, `lcc-psd`, `lcc-publish`, `lcc-raster`, `lcc-raw`, +`lcc-scenes`, `lcc-slideshow`, `lcc-surface`, `lcc-sync`, `lcc-sysmem`, +`lcc-testkit`, `lcc-tether`, `lcc-text`, `lcc-tiff`, `lcc-ui-egui`, `lcc-updater`, +`lcc-video`, `lcc-video-export`, `lcc-webgallery`, `lcc-winjob`, `lcc-winmsi`, +`lcc-winspool` — GPL-only at package level. + +Several of these contain adopted permissive modules; see +[Modules with file-level licences](#modules-with-file-level-licences). + +### Crates that also carry an adopted option + +| Crate | Manifest licence | Adopted material | Status | +|---|---|---|---| +| `lcc-camprof` | `GPL-3.0-or-later OR MIT OR Apache-2.0` | RADcamProfiles engine, MIT/Apache | Package tri-license; whole crate is also available under MIT/Apache | +| `lcc-fetch` | `GPL-3.0-or-later OR Apache-2.0` | Apache-2.0 model-download code | Package dual-license | +| `lcc-segment` | `GPL-3.0-or-later OR Apache-2.0` | SAM 2/3, DINOv2, OWLv2, Depth Anything, EoMT ports, Apache-2.0 | Package dual-license | +| `lcc-tflite` | `GPL-3.0-or-later OR Apache-2.0` | TensorFlow Lite schema/behaviour and MediaPipe data, Apache-2.0 | Package dual-license | +| `lcc-libraw` | `GPL-3.0-or-later` | LibRaw itself is LGPL-2.1 (or CDDL-1.0), linked opt-in | GPL-only wrapper; LGPL notice stays | + +## Modules with file-level licences + +These are the main adopted modules inside the repository. Unless noted, the +crate package stays GPL-only and the file/header carries the original licence. + +| Module | Original licence | Crate package | Note | +|---|---|---|---| +| `crates/camprof/src/*` | MIT or Apache-2.0 (RADcamProfiles) | `lcc-camprof` GPL/MIT/Apache | Package already carries both options | +| `crates/segment/src/*` | Apache-2.0 (Hugging Face/Meta, OneSlips ports) | `lcc-segment` GPL/Apache | Package already carries Apache | +| `crates/tflite/src/*` | Apache-2.0 (TensorFlow/MediaPipe-derived) | `lcc-tflite` GPL/Apache | Package already carries Apache | +| `crates/fetch` | Apache-2.0 | `lcc-fetch` GPL/Apache | Package already carries Apache | +| `crates/inpaint/src/*` | MIT or Apache-2.0 (PhotoCraft port) | `lcc-inpaint` GPL-only | **Ambiguous:** file-level MIT/Apache is in `NOTICE` but the package does not advertise it | +| `crates/surface/src/tactilebridge.rs` | MIT (RAD Films / TactileBridge) | `lcc-surface` GPL-only | **Ambiguous:** same package/file mismatch | +| `crates/raw/src/vc5.rs` | Apache-2.0 or MIT (GoPro GPR SDK) | `lcc-raw` GPL-only | **Ambiguous:** package/file mismatch | +| `crates/raw/src/spectral_table.rs` | Apache-2.0 (rawtoaces-data) + CC-BY-4.0 CIE data | `lcc-raw` GPL-only | **Ambiguous:** package/file mismatch; attribution required | +| `crates/raw/src/vendor/crx.rs` | LGPL-2.1 (LibRaw) | `lcc-raw` GPL-only | Compatible; LGPL notice must stay | +| `crates/raw/src/highlight/opposed.rs`, `laplacian.rs` | GPL-3.0-or-later (darktable) | `lcc-raw` GPL-only | Compatible | +| `crates/raw/src/demosaic/rcd.rs` | GPL-3.0-or-later (RawTherapee) | `lcc-raw` GPL-only | Compatible | +| `crates/pipeline/src/tone_eq.rs` | GPL-3.0-or-later (darktable) | `lcc-pipeline` GPL-only | Compatible | +| `crates/ui-egui/locales/*` | MIT or Apache-2.0 (contributor translations) | `lcc-ui-egui` GPL-only | **Ambiguous:** package/file mismatch, listed in `assets/ATTRIBUTION.md` | +| `crates/ui-egui/src/icons.rs` (Lucide subset) | ISC (Lucide; portions Feather/MIT) | `lcc-ui-egui` GPL-only | **Ambiguous:** package/file mismatch | +| `crates/ui-egui/src/eyedropper.rs` | MIT (OneSlips) | `lcc-ui-egui` GPL-only | **Ambiguous:** package/file mismatch | +| `crates/camdb/src/calibration.rs` | Data constant `MIT OR Apache-2.0` | `lcc-camdb` GPL-only | **Ambiguous:** code says MIT/Apache, package says GPL-only | +| `crates/camdb/data/cameras/libraw.toml` | LGPL-2.1 (LibRaw) | `lcc-camdb` GPL-only | Compatible; LGPL notice stays | +| `crates/camdb/data/cameras/dcraw.toml` | dcraw's own "free for all uses" statement, Foveon block excluded | `lcc-camdb` GPL-only | **Ambiguous:** not an SPDX licence | +| `crates/denoise-core/src/known.rs` | Model weights MIT/Apache-2.0 or CC BY 4.0, download only | `lcc-denoise-core` GPL-only | Weights are not shipped; metadata only | +| `crates/scenes` (generated demo images) | Entries say MIT/Apache-2.0 for the upstream contributors | `lcc-scenes` GPL-only | **Ambiguous:** asset entries and package licence differ | + +## Outside the workspace + +| Area | Licence | Status | +|---|---|---| +| `sdk/plugin`, `sdk/stamp`, `sdk/examples/*` | MIT | Separate libraries/plugins; allowed as complete modules, not core | +| `tools/denoise-train/rawdump` | MIT OR Apache-2.0 | Development tool, not product core | +| `vendor/candle-core`, `vendor/egui-wgpu`, `vendor/naga` | MIT OR Apache-2.0 | Vendored third-party dependencies | +| `assets/ATTRIBUTION.md` rows | Many MIT/Apache/CC/OFL entries | Assets are not core code; per-entry licences still apply | +| `LICENSE` | MIT text | Deliberately kept for adopted MIT modules; core GPL text is `LICENSE-GPL-3.0.txt` | +| `LICENSE-APACHE` in `crates/segment` / `crates/fetch` | Apache-2.0 | Adopted-module notices | +| `LICENSE-LibRaw-LGPL-2.1.txt` | LGPL-2.1 | LibRaw notice | +| craft-fonts (external build input) | OFL | Fetched by packaging scripts; not MIT core code | + +## Ambiguities + +1. **Package-level dual licences also cover project-authored changes.** The four + adopted-code crates (`lcc-camprof`, `lcc-fetch`, `lcc-segment`, `lcc-tflite`) + are licensed as whole crates under the original option. Strict GPL-only core + inside those crates would need per-file headers or splitting the adopted code + into separate crates. +2. **Several GPL-only crates contain MIT/Apache modules.** `lcc-inpaint`, + `lcc-surface`, `lcc-raw`, `lcc-ui-egui` and `lcc-camdb` have file-level + notices that are not reflected in the package manifest. The file licence + survives, but a scanner reading only `Cargo.toml` will report the crate as + GPL-only. +3. **`LICENSE` is MIT while the project is GPL.** That is intentional for adopted + modules, but it is easy to misread. `LICENSE-GPL-3.0.txt` is the core licence. +4. **dcraw data is not under an SPDX licence.** `dcraw.toml` relies on dcraw's + "free for all uses" statement; the GPL RESTRICTED (Foveon) block is excluded. +5. **CIE data is CC-BY-4.0.** `spectral_table.rs` carries attribution obligations + separate from the crate's GPL licence. +6. **Translation data and icons are permissive inside a GPL crate.** See + `assets/ATTRIBUTION.md`; the package manifest does not show this. +7. **`sdk/*` is MIT by design.** It is a separate library/plugin surface, not + core, and is allowed by the current rule. It is still part of any future MIT + inventory because it ships in the repository. +8. **`assets/ATTRIBUTION.md` still has MIT/Apache entries for original assets.** + Those are not core code, but they remain shipped material. + +## Next: MIT / storytold inventory + +This is the candidate list for the rewrite/isolation pass, not a conclusion: + +- The MIT/Apache modules in the table above, especially those marked + **ambiguous**. +- `sdk/*`, `tools/denoise-train/rawdump`, `vendor/*` and `assets/ATTRIBUTION.md` + entries (allowed, but to be listed and consciously kept or replaced). +- Storytold references: `NOTICE` (upstream project attribution), `README` + fork statement, `docs/upstream-*`, `assets/ATTRIBUTION.md` links, + `packaging/fonts.sh` / `packaging/windows/fonts.ps1` craft-fonts checkout, and + the `storytold/photocraft-corpus` test data reference. +- Cargo dependencies under MIT/Apache/BSD/ISC do not make core code MIT; they are + separate modules/libraries. They still belong in the dependency inventory. + +## Updating this page + +Change this page in the same PR that changes a licence, adds adopted code, or +converts a contributor's code. Update the crate or module row, the +**Ambiguities** it clears, and the **Next** list; move the snapshot date in the +header. A licence change that leaves this page stale is an incomplete change. + +## Summary + +- **Core/project-only crates:** GPL-3.0-or-later only. +- **Adopted-code crates:** GPL plus their original option, at package level. +- **GPL-only crates with adopted permissive modules:** compatible, but the + package/file split is the main ambiguity to clean up. +- **MIT outside core:** `sdk/*`, tools, vendor, assets, and the adopted modules + listed above. diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 1ad133f278..1e6c9afb95 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -1,8 +1,5 @@ # Lightroom Classic catalog import -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - File → Import Lightroom or Capture One Catalog… opens `.lrcat` directly. Lightroom, Python, DNG conversion and a C SQLite runtime are not required. The source database is read-only, including committed `-wal` pages; a catalog that changes during the read is rejected when the change is @@ -17,7 +14,7 @@ File → Open Catalog… given a Lightroom catalog folder (or an `.lrdata` / `.l doesn't make a library of the app there: it offers this import instead, with the catalog found (`crates/engine/src/lightroom_folder.rs`, issue #891), and then asks where the catalog goes as described next (unless the question is turned off, below). -` --library` refuses those places too. +`chromaforge-cli --library` refuses those places too. **Where the catalog goes.** Before the import starts, the desktop app asks where the catalog goes (issue #2672), unless Settings says to always merge (*Turning the question off*, below): @@ -44,7 +41,7 @@ A session with no library on disk (in memory, e.g. after Continue Without Saving next to: the catalog merges into it without asking, as before. **Scripts and agents.** The app command `file.importLightroom {path?, into?, name?, location?}` (control channel, -` mcp --connect`) chooses without the window: `into: "open"` merges, `into: "new"` creates the library +`chromaforge-cli mcp --connect`) chooses without the window: `into: "open"` merges, `into: "new"` creates the library `name` (default: the catalog's name) in the folder `location` (default: the open library's parent folder; a full path), opens it and imports. Without `into` it shows the window (and returns `{asking: true, path, into}`, `into` being the choice the window opens with) or merges when the setting says so. A catalog path that doesn't exist is @@ -54,11 +51,11 @@ open now. Equivalent commands: ```text - run --library " Library" library.inspectLightroom path="Lightroom Catalog.lrcat" - run --library " Library" library.importLightroom path="Lightroom Catalog.lrcat" +chromaforge-cli run --library "Chromaforge Library" library.inspectLightroom path="Lightroom Catalog.lrcat" +chromaforge-cli run --library "Chromaforge Library" library.importLightroom path="Lightroom Catalog.lrcat" ``` -The import itself (`library.importLightroom`, ` run`) adds records to the currently open +The import itself (`library.importLightroom`, `chromaforge-cli run`) adds records to the currently open library; only the desktop window above can make a new library for it first. The desktop result stays open until dismissed and shows the destination library, the number of records added, missing originals and warnings. **Show in Library** opens All Photos, clears filters and selects an imported record. Errors stay @@ -104,7 +101,9 @@ image id with its reason, `missingFile`, `missingFolder`, `missingRoot`, `incomp `masterSkipped`), also in `library.inspectLightroom`, and the desktop result window says how many in the UI language. Virtual copies count as added records too; reimport reports zero additions when all records already exist. Existing -edits are preserved by default; `updateExisting=true` explicitly replaces them. Settings read from an +edits are preserved by default; `updateExisting=true` explicitly replaces them. Ratings, flags and colour labels are +not edits in this sense: importing a catalog again takes them from the catalog again, replacing changes made in +Chromaforge since the first import. Settings read from an original's own XMP (embedded or a sidecar) while the import adds it, or while it was browsed, are not existing edits: a photo the import adds, or a Local one unchanged since browsing, takes the catalog's settings, history and snapshots, and a setting the catalog leaves out (Lightroom omits @@ -174,7 +173,7 @@ charged as it is kept against one memory budget for the whole read, three quarte free when the import starts (half the computer's memory when that can't be told, never less than 1 GiB). A catalog that needs more stops with an error saying how much was read and what the limit was, and nothing is imported; it is never skipped table by table, so no photo comes in without what -a table holds. `_LIGHTROOM_IMPORT_MEMORY=` sets the budget instead (more on a computer +a table holds. `CHROMAFORGE_LIGHTROOM_IMPORT_MEMORY=` sets the budget instead (more on a computer whose other apps can wait, less to keep room for them). Of each `AgLibraryFile` row only its folder and file name are kept, and of `Adobe_AdditionalMetadata` only the XMP packet, which each photo then takes over rather than copies. The import is committed and saved 20,000 changes at a time and the parts fold into one undo step, so the session never holds a second copy of the whole import waiting to be saved; a failure takes every part back. If the app stops partway (a crash, power loss), the parts already saved stay in the library and importing the catalog again adds the rest, though virtual copies saved before the stop may come in twice, because the import index is written when the import ends. These bounds limit work and decoded data: a catalog within the @@ -332,7 +331,8 @@ Capture One 16.9.0 on Windows (catalog format 160906). camera's clock, no offset), camera make, model and lens from the catalog; a file that is there keeps its own. Capture One's stand-ins for a file without a camera ("Tiff File", "Jpeg File") are no camera. - **Ratings and colour tags** (`ZVARIANTMETADATA`): red, yellow, green, blue and purple become labels; orange and - pink have no label here and come in without one, with a warning. + pink have no label here and come in without one, with a warning. Importing the catalog again takes ratings, flags and + colour labels from the catalog again, replacing changes made in Chromaforge since the first import. - **Keywords:** `ZCONTENT_KEYWORDS` lists each keyword as its full path with an order suffix (`Animals|Birds|Owls||4`) and the parents of an assigned keyword as entries of their own; the parents are dropped, as the path implies them. @@ -345,7 +345,13 @@ Capture One 16.9.0 on Windows (catalog format 160906). *style* layers what applied styles set, the *default* layer the camera's defaults. A setting is the variant's when the adjustment layer (else a style) sets it to something other than the default. Imported so far, on top of the photo's camera defaults: - - **Exposure** (`ZEXPOSURE`, EV). + - **Exposure** (`ZEXPOSURE`, EV): the variant's effective value (the adjustment layer's, else a style's, else the + camera default layer's), written when it differs from 0 by more than 0.001 EV (finer than the slider's step, so + float noise left by a reset doesn't count as an edit). A raw's exposure is taken as it is. On a rendered file (TIFF, + JPEG, …) Capture One's exposure acts on the file's encoded values, so it is multiplied by 1.17 (measured against + Capture One's exports; the best factor was 1.14 to 1.21 over the range) and held to the app's range of ±5 EV. Above + +0.5 EV Capture One's highlight shoulder is not reproduced, so the result is approximate: the result window counts + those rendered files. (On a raw the remaining difference is small and not reported.) - **Orientation and straighten** (`ZROTATION`): the whole turn in degrees, clockwise as shown, including the camera's own orientation (the default layer's value, which the file's orientation already shows). The quarter turns beyond the camera's become the photo's orientation, the rest (±45°) the straighten angle. @@ -358,22 +364,83 @@ Capture One 16.9.0 on Windows (catalog format 160906). relative scale (no matrices for its camera) gets the same change through that scale, which on those cameras only approximates Capture One's (the result window says so, with the photo count); a rendered file's white balance is not imported. - - **Tone and clarity**: `ZCONTRAST`, `ZBRIGHTNESS`, `ZSATURATION` (Capture One's ±50, doubled onto the app's - sliders), High Dynamic Range (`ZHIGHLIGHTRECOVERY` / `ZWHITERECOVERY` pull Highlights / Whites down, - `ZSHADOWRECOVERY` / `ZBLACKRECOVERY` lift Shadows / Blacks), `ZCLARITY` → Clarity, `ZCLARITYSTRUCTURE` → Texture - (the clarity method has no equivalent and is reported). + - **Brightness** (`ZBRIGHTNESS`, −50..50, often fractional) → Brightness doubled, not rounded: the app's slider has + Capture One's effect on twice the range (checked against Capture One's exports to 0.2 of an 8-bit level). + - **Highlight, Shadow** (`ZHIGHLIGHTRECOVERY`, `ZSHADOWRECOVERY`, −100..100, the sliders' own numbers; the variant's + effective value, as for Brightness). A *negative* Highlight → Highlights one to one; the result window counts these + photos as approximate (strong values stay lighter than in Capture One in very bright areas). A *negative* Shadow → + Shadows times 1.2, held to −100, with no warning. A *positive* Shadow → Shadows times 2, held to 100: Capture One's + reaches about twice as far as the app's slider, so strong lifts (from +50 up) are held at the app's limit and stay + darker than in Capture One; the result window counts these photos as approximate. A positive Highlight is not + imported (Capture One's reaches further than the app's slider can follow); the window names it ("Highlight + (positive values)") with its photo count. + - **Saturation** (`ZSATURATION`, −100..100). A *negative* value → Saturation one to one (a rendered file is counted as + approximate: the most saturated colours don't darken as much as in Capture One). A *positive* value on a raw → + Vibrance, because Capture One's positive Saturation leaves strongly saturated colours alone and lifts the rest, as + Vibrance does and Saturation does not: +25 → 45, +50 → 80, +100 → 100, linear between these and from 0 at 0. That is + approximate (the result window counts the photos): skin tones stay less saturated than in Capture One, and strongly + saturated colours are boosted a little less. A positive value on a rendered file is not imported and is named with + its photo count. Capture One and the app both apply Saturation before Brightness, Levels and the curve, so + combinations keep Capture One's order. + - Not imported yet, named in the result window: Contrast (Capture One's curve pivots around a much darker level than + the app's, so no factor reproduces it), White and Black (they act locally in Capture One, per pixel in the app), + Clarity and Structure, and the settings listed at the end of this section. - **Curves** (`ZGRADATIONCURVE`, `…RED`, `…GREEN`, `…BLUE`, `x,y;x,y;…` in 0..1 or 0..255) → the Tone Curve's point curves; the luma curve (`…Y`) is reported. - - **Levels** (`ZLEVELSSHADOW`, `ZLEVELSHIGHLIGHT`, `ZLEVELSTARGETSHADOW`, `ZLEVELSTARGETHIGHLIGHT`, `ZMIDTONE`; one - value or `rgb;r;g;b`, 0..1 or 0..255, the midtone as the marker's place between the points) → Levels per channel. + - **Levels** (`ZLEVELSSHADOW` and `ZLEVELSHIGHLIGHT`: the black and white points; `ZLEVELSTARGETSHADOW` and + `ZLEVELSTARGETHIGHLIGHT`: the output levels; `ZMIDTONE`): each is four numbers, `red;green;blue;master`, the points + in 0..1 of the 0..255 scale and the midtone as the tool's own signed value (−1..1, 0 neutral). They become the + Levels of the red, green and blue channels and of the master. The values are stored to three decimals and + Capture One renders a reopened catalog from them, so they are read as stored, not rounded to whole levels; a + black point above the white point (an inverted channel) is kept. Output levels count while `ZLEVELSTARGETENABLE` + isn't 0. Brightness and Levels are the variant's *effective* value (the adjustment layer's, else a style's, else the + camera default layer's, since Capture One can save them as camera defaults) and are written when they differ from + neutral by more than float noise (under 0.001 for Brightness, 0.0001 for each Levels value). Levels on a local + adjustment layer are named in the result window ("Levels (local adjustments)"); the Levels tool keeps its black and + white points at least 2 levels apart, and the window says how many photos had them closer. - A value that doesn't read as described (wrong count, out of range, not a number) is reported, never guessed. - - The ICC profile choice is left out on purpose: photos get the app's camera colour. + - **Film curve** (`ZFILMCURVE`, the variant's effective value, raw files only): the catalog holds a file name + (`-Auto.fcrv`); the import uses only that name. Its stem names a base curve file in the app's own format: + `-Auto.fcrv` becomes the base curve `base:-Auto`. Curve files are user-provided, in the base curve + folder; nothing is bundled, and no file of Capture One's is read. A photo that gets a curve is also set to the + app's own colour (Built-in), and its white balance is converted for that colour, through the camera database alone + (a camera profile of the user's, which would otherwise be that camera's default, is not used for these photos). + The import checks that the curve + file is installed (it scans the folder once more when a missing curve's file is there): a curve whose file isn't + installed sets no id, the photo keeps the default base tone and colour, and the result window names the missing + curves with the photo count. After adding the file, import the catalog again: photos with nothing else imported + (only the camera's own curve) pick the curve up; photos that got other Capture One settings count as edited and keep + theirs. To give them the curve, import into a new library with the file in place. + The camera's own curve is what Capture One gives an unedited raw, so it is not an edit: the curve, the app's colour + and the as-shot white balance are the photo's baseline (Reset returns to them), and a photo with nothing else + imported stays unedited. A curve the variant chose itself goes on top of that baseline (the camera's own curve, when + it is installed) as an edit, and so does any other imported setting (a non-as-shot white balance, Exposure, + Brightness, Levels, …). A rendered file has no base tone, so its film curve is not imported. A record made from the + catalog alone counts as a raw when the variant has a camera model and a film curve that is not a rendered format's, + whatever its extension; a photo with a film curve that the app does not develop as a raw (a file it cannot develop + yet, or one that could not be read) gets no curve or colour and is counted on its own line of the result window. A + value that is not a file name is reported ("base curve: values could not be read") and sets no curve. + - **Variants:** an image's first variant is its photo, each further variant a virtual copy ("Variant N") of it. Every + variant has settings, rating, colour label and keywords of its own, and a copy starts from the camera's defaults + (with the camera's own curve and the app's colour as its baseline, like any photo), never from its master's edits, + edit date, history or keywords; only its own variant's settings go on top. Catalog images that point to the same + original file share that file's one record: the record keeps the settings of the last of them, and the result window + counts the others. + - **XMP sidecars and embedded XMP are not read** by a Capture One import, in the window or by any other way of + importing (script, CLI, MCP): the catalog is the only source of the photo's settings, rating, flag, label, keywords + and metadata, so nothing a sidecar says, another editor's settings included, reaches an imported photo. (A Lightroom + import reads them first and puts the catalog's values over them.) + - The rest of the ICC profile choice is left out on purpose: photos get the app's camera colour. Every other setting a photo uses is named in the result window, by Capture One tool (Color Editor, Dehaze, Luma curve, LCC, Local adjustment layers, …, with how many photos use it), and per photo in the report's - `unmapped`. A photo is dated at Capture One's last settings change (`ZSETTINGSMODIFICATIONDATE`). + `unmapped`. **Edit date:** a Capture One catalog keeps no edit date per variant that the catalogs checked fill in + (`ZSETTINGSMODIFICATIONDATE` and the variant's metadata dates are empty; the image's import date is not an edit date), + so a photo that gets settings from the catalog is dated at the import, one without keeps any edit date it already had, + and the result window says nothing about it (a date the column does hold is used). Lightroom keeps a touch time for + every image, and its catalogs report the images where it is missing or not a date. - Checked against Capture One's own exports of the same raws (` compare`, aligned, 1000 px renders; 12 photos + Checked against Capture One's own exports of the same raws (`chromaforge-cli compare`, aligned, 1000 px renders; 12 photos for geometry, 8 for white balance): straightened and turned photos (−18.9° to +2.4°, camera portraits at +2° and +13.9°, user quarter and half turns) aligned at 0.968–1.003 scale, 10 of 12 with no shift and 2 within 6 px of 512. White balance is an approximation. With the app's standard colour (no camera profile installed) it lowered @@ -383,6 +450,24 @@ Capture One 16.9.0 on Windows (catalog format 160906). photos went from 5.6–10.4 to 1.9–5.0. The rest of the difference includes settings not imported yet and the camera colour. A camera that gets an entry in the camera database moves to the Kelvin scale; the import reads the same database, so it follows. + - **How the tone mappings were decided, and what is left.** Each slider was measured on Capture One's own exports of + raws, one slider per export from a fresh variant, against what the app renders with exactly what the import gives + the photo plus that one slider, as a change from each image's own baseline (so the two renderers' baseline colour + gap drops out), on luminance masks. A rule fixed in advance decided each slider and sign: a mapping that stays + within 4 levels (rms, 8-bit) and ΔE00 3 on every measured raw imports without a warning; one that fails that but + halves the "not imported" error on every raw and is never worse on any mask imports as approximate with a + result-window line; anything else is reported only. Two outcomes are decisions that depart from the rule: a + positive Saturation on a raw is imported as Vibrance by a table (it halves the error on the real scenes but not on + the colour chart, where skin tones are worst, because the app's Vibrance protects them and Capture One's + Saturation does not), and a positive Shadow is imported at twice its value held to 100 (at +100 it misses the + halving). Contrast stays not imported by decision: Capture One's curve pivots near sRGB 87, the app's near 118. + - **Known limits and follow-ups.** Raw Exposure has no highlight shoulder like Capture One's (above about +1 EV the + highlights differ; the value itself is carried over). Positive Highlight, White, Black, Clarity and Structure are + not imported (not reproducible or not measured). Possible later: skin protection in Vibrance as an option; a + negative Saturation that darkens the most saturated colours; a second positive-Shadow point below +50. A re-import + cannot give a curve added later to photos that got other settings, because the import cannot tell its own earlier + settings from the user's; storing a fingerprint of what the import wrote on the photo (a catalog format change) + would allow a safe rebuild. - The import's activity row, messages, result window, destination window and undo step say Capture One. ## Historical local validation diff --git a/docs/localization-cs.md b/docs/localization-cs.md index f3fb102cf2..bc10e88a6d 100644 --- a/docs/localization-cs.md +++ b/docs/localization-cs.md @@ -3,7 +3,7 @@ Češtinu (`cs`, English name **Czech**, native name **Čeština**) zapnete přes **Úpravy → Jazyk → Čeština** nebo **Nastavení → Obecné → Jazyk**. Změna platí ihned a ukládá se pro další spuštění. Příkaz je `app.language.czech`; řídicí kanál přijímá `ui.set {"language":"cs"}` i značky -`cs-CZ` a `cs_CZ.UTF-8`. Pro běh bez okna lze nastavit `_LANGUAGE=cs`. +`cs-CZ` a `cs_CZ.UTF-8`. Pro běh bez okna lze nastavit `CHROMAFORGE_LANGUAGE=cs`. Katalogy `crates/ui-egui/locales/cs.json` a `cs-formats.json` vznikly s pomocí AI pro @Losminek, po celých frázích podle významu anglických zdrojových řetězců. Výchozí seznam klíčů vycházel diff --git a/docs/localization-de.md b/docs/localization-de.md index 082d6424b3..1b8f7cf23b 100644 --- a/docs/localization-de.md +++ b/docs/localization-de.md @@ -1,6 +1,6 @@ # Deutsche Oberfläche -> ``, ``, ``: [`brand.toml`](../brand.toml). +> `CHROMAFORGE`, `chromaforge-cli`, `chromaforge`: [`brand.toml`](../brand.toml). Wähle **Bearbeiten → Sprache → Deutsch** oder **Einstellungen → Allgemein → Sprache**. Die Auswahl gilt sofort und wird für den nächsten Start gespeichert (`language: "de"` in `ui.json`). @@ -57,7 +57,7 @@ Formulierungen. Das Datum erscheint beispielsweise als `Sonntag, 20.09.2026`. ```sh cargo test -p lcc-ui-egui i18n::tests -_LANGUAGE=de snapshot --demo -o deutsch.png --size 1600x1000 +CHROMAFORGE_LANGUAGE=de chromaforge-cli snapshot --demo -o deutsch.png --size 1600x1000 ``` Die Tests prüfen Platzhalter, Sprachwechsel per Menü und Steuerkanal, Speicherung, diff --git a/docs/localization-es.md b/docs/localization-es.md index 30d8d48ac3..86b5934aaf 100644 --- a/docs/localization-es.md +++ b/docs/localization-es.md @@ -1,9 +1,9 @@ # Interfaz en español -> ``, ``, ``: [`brand.toml`](../brand.toml). +> `CHROMAFORGE`, `chromaforge-cli`, `chromaforge`: [`brand.toml`](../brand.toml). Elegir **Editar → Idioma → Español** o **Ajustes → General → Idioma**. El cambio se aplica al -momento y se conserva para el próximo inicio (`language: "es"` en `ui.json`). `_LANGUAGE` +momento y se conserva para el próximo inicio (`language: "es"` en `ui.json`). `CHROMAFORGE_LANGUAGE` acepta cualquier variante del español (`es`, `es-ES`, `es_MX.UTF-8`, `es-419`…). El catálogo en español cubre los menús, los métodos abreviados de teclado, la biblioteca, el @@ -47,5 +47,5 @@ comprueba los marcadores al compilar. Las terminaciones de plural del inglés se ```sh cargo test -p lcc-ui-egui i18n::tests -- --nocapture -_LANGUAGE=es snapshot --demo -o espanol.png --size 1600x1000 +CHROMAFORGE_LANGUAGE=es chromaforge-cli snapshot --demo -o espanol.png --size 1600x1000 ``` diff --git a/docs/localization-fi.md b/docs/localization-fi.md index 61d5928122..ca5bdc8f83 100644 --- a/docs/localization-fi.md +++ b/docs/localization-fi.md @@ -4,7 +4,7 @@ Suomen (`fi`, englanniksi **Finnish**, omakielinen nimi **Suomi**) saa käyttö **Muokkaa → Kieli → Suomi** tai **Asetukset → Yleiset → Kieli**. Muutos tulee voimaan heti ja tallentuu seuraavaa käynnistystä varten. Komento on `app.language.finnish`; ohjauskanava hyväksyy `ui.set {"language":"fi"}` sekä tunnisteet `fi-FI` ja `fi_FI.UTF-8`. Ikkunattomassa -ajossa voi käyttää `_LANGUAGE=fi`. +ajossa voi käyttää `CHROMAFORGE_LANGUAGE=fi`. Luettelot `crates/ui-egui/locales/fi.json` ja `fi-formats.json` on laadittu tekoälyavusteisesti (Claude) englanninkielisten lähdemerkkijonojen merkityksestä, kokonaisina fraaseina. Avainlista diff --git a/docs/localization-id.md b/docs/localization-id.md index 31186ce6b5..194e017026 100644 --- a/docs/localization-id.md +++ b/docs/localization-id.md @@ -1,9 +1,9 @@ -# in Indonesian +# Chromaforge in Indonesian Choose **Edit → Language → Bahasa Indonesia** or **Settings → General → Language**. The choice applies at once and is saved for the next launch (`language: "id"` in `ui.json`); the control command is -`app.language.indonesian`. `_LANGUAGE` selects it for headless runs and accepts `id`, `id-ID` -and `id_ID.UTF-8`; the saved value is always `id`. does not follow the system language, for +`app.language.indonesian`. `CHROMAFORGE_LANGUAGE` selects it for headless runs and accepts `id`, `id-ID` +and `id_ID.UTF-8`; the saved value is always `id`. Chromaforge does not follow the system language, for Indonesian as for every other language. The Indonesian catalogs cover every plain and formats message the other catalogs have (2,258 + 297), diff --git a/docs/localization-ja.md b/docs/localization-ja.md index 47267d7553..6268676949 100644 --- a/docs/localization-ja.md +++ b/docs/localization-ja.md @@ -1,6 +1,6 @@ # 日本語表示 -> ``, ``, ``: [`brand.toml`](../brand.toml). +> `CHROMAFORGE`, `chromaforge-cli`, `chromaforge`: [`brand.toml`](../brand.toml). 本アプリは日本語・簡体字中国語・英語(English)の表示に対応しています。 言語設定は `ui.json` の `language` に保存します。 @@ -26,7 +26,7 @@ 可変文言の訳文はすべてビルド時にRustの `format!` 検査を受けます。値は名前(`{n}`)または 位置(`{0}`、`{1}`)で参照し、`{:.1}` などの書式指定は英文と同じものを使います。 英語の単複数語尾を日本語で省略する場合、対応する文字列引数は `{:.0}` で空にします。 -`_LANGUAGE=ja snapshot ...` で日本語の画面を描画できます。 +`CHROMAFORGE_LANGUAGE=ja chromaforge-cli snapshot ...` で日本語の画面を描画できます。 スマートアルバムの「はい/いいえ」で答える条件(編集、切り抜きなど)の値は、文脈付きキー `"smart album value|Yes"`・`"smart album value|No"` で「あり/なし」と表示します。共有の diff --git a/docs/localization-ka.md b/docs/localization-ka.md index f2dee7784e..34f62b331a 100644 --- a/docs/localization-ka.md +++ b/docs/localization-ka.md @@ -2,7 +2,7 @@ Choose **Edit → Language → ქართული** or **Settings → General → Language**. The choice applies at once and is saved for the next launch (`language: "ka"` in `ui.json`); the control command is -`app.language.georgian`. `_LANGUAGE` selects it for headless runs and accepts `ka`, `ka-GE` +`app.language.georgian`. `CHROMAFORGE_LANGUAGE` selects it for headless runs and accepts `ka`, `ka-GE` and `ka_GE.UTF-8`; the saved value is always `ka`. The app does not follow the system language, for Georgian as for every other language. @@ -70,7 +70,7 @@ the placeholders at build time. Strings not yet in the plain catalog show in Eng ```sh cargo test -p lcc-ui-egui i18n::tests -- --nocapture -_LANGUAGE=ka snapshot --demo -o georgian.png --size 1600x1000 +CHROMAFORGE_LANGUAGE=ka chromaforge-cli snapshot --demo -o georgian.png --size 1600x1000 ``` The tests check placeholders, switching language by menu and control channel, saving, the `ka` diff --git a/docs/localization-pl.md b/docs/localization-pl.md index f4fbca9135..e8832bd94d 100644 --- a/docs/localization-pl.md +++ b/docs/localization-pl.md @@ -3,7 +3,7 @@ Język polski (`pl`, English name **Polish**, nazwa natywna **Polski**) włącza się przez **Edytuj → Język → Polski** albo **Ustawienia → Ogólne → Język**. Zmiana działa od razu i jest zapamiętywana przy kolejnym uruchomieniu. Polecenie to `app.language.polish`; kanał sterowania przyjmuje `ui.set {"language":"pl"}` -oraz znaczniki `pl-PL` i `pl_PL.UTF-8`. Bez okna można ustawić `_LANGUAGE=pl`. +oraz znaczniki `pl-PL` i `pl_PL.UTF-8`. Bez okna można ustawić `CHROMAFORGE_LANGUAGE=pl`. Katalogi `crates/ui-egui/locales/pl.json` i `pl-formats.json` dodał #1100 (tłumaczenie przygotowane z pomocą AI). Uzupełnienie opisane niżej również przygotowano z pomocą AI; przygotował je rodzimy diff --git a/docs/localization-pt-br.md b/docs/localization-pt-br.md index 9691187951..7d4c51d9ca 100644 --- a/docs/localization-pt-br.md +++ b/docs/localization-pt-br.md @@ -1,6 +1,6 @@ # Interface em português do Brasil -> ``, ``, ``: [`brand.toml`](../brand.toml). +> `CHROMAFORGE`, `chromaforge-cli`, `chromaforge`: [`brand.toml`](../brand.toml). O aplicativo pode ser exibido em inglês, chinês simplificado, chinês tradicional (Taiwan), japonês e português do Brasil. A preferência de idioma é gravada em `language` no `ui.json`. @@ -37,5 +37,5 @@ verificadas por `cargo test -p lcc-ui-egui i18n::tests` (a checagem de glifos s `CRAFT_FONTS_DIR`). Para visualizar o idioma, renderize sem interface gráfica: ```sh -_LANGUAGE=pt-br snapshot --demo --script tour.jsonl -o out.png --size 1600x1000 +CHROMAFORGE_LANGUAGE=pt-br chromaforge-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000 ``` diff --git a/docs/localization-ru.md b/docs/localization-ru.md index ff7592dc8e..f61124cab6 100644 --- a/docs/localization-ru.md +++ b/docs/localization-ru.md @@ -1,6 +1,6 @@ # Русский интерфейс -> ``, ``, ``: [`brand.toml`](../brand.toml). +> `CHROMAFORGE`, `chromaforge-cli`, `chromaforge`: [`brand.toml`](../brand.toml). Выберите **Правка → Язык → Русский** или **Настройки → Общие → Язык**. Выбор применяется сразу и сохраняется для следующего запуска (`language: "ru"` в `ui.json`). @@ -24,5 +24,5 @@ ```sh cargo test -p lcc-ui-egui i18n::tests -- --nocapture -_LANGUAGE=ru snapshot --demo -o russian.png --size 1600x1000 +CHROMAFORGE_LANGUAGE=ru chromaforge-cli snapshot --demo -o russian.png --size 1600x1000 ``` diff --git a/docs/localization-vi.md b/docs/localization-vi.md index 7d62b5f3e2..8896d4e1b3 100644 --- a/docs/localization-vi.md +++ b/docs/localization-vi.md @@ -1,4 +1,4 @@ -# bằng tiếng Việt +# Chromaforge bằng tiếng Việt Chọn **Chỉnh sửa → Ngôn ngữ → Tiếng Việt** hoặc **Cài đặt → Chung → Ngôn ngữ**. Lựa chọn áp dụng ngay và được lưu cho lần mở sau (`language: "vi"` trong `ui.json`). @@ -7,7 +7,7 @@ Các tag locale hệ thống sau cũng chọn tiếng Việt: `vi`, `vi-VN`, `vi ## Phạm vi -Catalog tiếng Việt phủ **toàn bộ** bề mặt localization hiện tại của +Catalog tiếng Việt phủ **toàn bộ** bề mặt localization hiện tại của Chromaforge (đo 2026-10-13: union plain **2 222** + formats **249** = **2 471** thông điệp): - `crates/ui-egui/locales/vi.json` — thông điệp plain / nhãn hiển thị (2 222 khóa) @@ -40,7 +40,7 @@ các ngôn ngữ khác. | Shutter Speed | Tốc độ màn trập | | Smart Previews | Xem trước thông minh | -Tên sản phẩm và chuẩn giữ nguyên khi là định danh: , GitHub, Discord, +Tên sản phẩm và chuẩn giữ nguyên khi là định danh: Chromaforge, GitHub, Discord, JPEG, PNG, TIFF, WebP, AVIF, HEIF, HEIC, RAW, DNG, RGB, HDR, ICC, EXIF, XMP, GPU, MCP, SAM, ISO, OK. Tên album / preset / profile do người dùng tạo, tên tệp, command ID và metadata nhập tay @@ -62,8 +62,8 @@ Tiếng Việt dùng Inter (Latin + dấu). Không cần craft-fonts CJK. Kiểm ```sh cargo test -p lcc-ui-egui i18n::tests -- --nocapture -_LANGUAGE=vi lcc-cli snapshot --demo -o vi.png --size 1600x1000 -_LANGUAGE=vi lcc-cli snapshot --demo -o vi-narrow.png --size 1280x800 +CHROMAFORGE_LANGUAGE=vi chromaforge-cli snapshot --demo -o vi.png --size 1600x1000 +CHROMAFORGE_LANGUAGE=vi chromaforge-cli snapshot --demo -o vi-narrow.png --size 1280x800 ``` Các test tiếng Việt kiểm tra đổi ngôn ngữ, lưu `vi`, formats, ngày, dữ liệu người dùng và glyph @@ -72,6 +72,6 @@ không test nào thất bại vì thiếu bản dịch. ## Nguồn dịch (clean-room) -Dịch từ chuỗi tiếng Anh nguồn của . PhotoCraft / VectorCraft / PDFCraft chỉ dùng +Dịch từ chuỗi tiếng Anh nguồn của Chromaforge. PhotoCraft / VectorCraft / PDFCraft chỉ dùng làm bộ nhớ thuật ngữ khi cùng nguồn tiếng Anh và cùng ngữ cảnh UI. Không dùng gói ngôn ngữ Adobe Lightroom hay tài nguyên độc quyền. diff --git a/docs/localization-zh-hans.md b/docs/localization-zh-hans.md index 47101c9546..608e580829 100644 --- a/docs/localization-zh-hans.md +++ b/docs/localization-zh-hans.md @@ -1,6 +1,6 @@ # 简体中文界面 -> ``, ``, ``: [`brand.toml`](../brand.toml). +> `CHROMAFORGE`, `chromaforge-cli`, `chromaforge`: [`brand.toml`](../brand.toml). 本应用的界面支持英语、简体中文、繁体中文(台湾)和日语。语言设置保存在 `ui.json` 的 `language` 字段中。 @@ -14,7 +14,7 @@ `cargo::warning` 提示这一点。 - 翻译只发生在显示层:命令 ID、照片文件名、用户输入的元数据都不做改动。 - 尚未翻译的技术性错误、补充说明和发行说明仍以英文显示。 -- 网页版将 Noto Sans CJK SC 作为独立的 `_zh_hans.otf` 文件随站点分发,页面启动时加载; +- 网页版将 Noto Sans CJK SC 作为独立的 `app_zh_hans.otf` 文件随站点分发,页面启动时加载; 这样可显示简体中文,也避免把约 16 MB 字体放进受单文件大小限制的 WASM。部署时需上传整个 `target/web-site/` 目录。未指定 `CRAFT_FONTS_DIR` 的开发构建仍缺少中文字体。 - 日期分组标题与拍摄时间按中文格式显示(如 `2026年9月20日 星期日`)。 @@ -36,7 +36,7 @@ - `format!` 不允许未使用的参数:英文用来表示单复数的那个参数(`"s"` / `""`)在中文里写成 `{:.0}`(精度为 0 的字符串不输出任何内容)。 -`_LANGUAGE=zh-hans snapshot ...` 可以渲染中文界面用于检查。 +`CHROMAFORGE_LANGUAGE=zh-hans chromaforge-cli snapshot ...` 可以渲染中文界面用于检查。 两种目录的占位符是否一致、字形是否齐全,由 `cargo test -p lcc-ui-egui i18n::tests` 验证(字形检查只在指定 `CRAFT_FONTS_DIR` 时实际执行)。 diff --git a/docs/localization-zh-hant.md b/docs/localization-zh-hant.md index a49d308fbe..61fbe76106 100644 --- a/docs/localization-zh-hant.md +++ b/docs/localization-zh-hant.md @@ -1,6 +1,6 @@ # 繁體中文(台灣)介面 -> ``, ``, ``: [`brand.toml`](../brand.toml). +> `CHROMAFORGE`, `chromaforge-cli`, `chromaforge`: [`brand.toml`](../brand.toml). 從「編輯 → 語言 → 繁體中文(台灣)」切換,或開啟「設定 → 一般 → 語言」選擇。 macOS 的設定也可由「應用程式選單 → 設定…」或 `⌘,` 開啟。 @@ -28,7 +28,7 @@ Web 建置在 WASM 中嵌入 BIZ UDPGothic Regular,並另外載入 Noto Sans C ## 自動化與維護 -`_LANGUAGE=zh-hant snapshot --demo -o zh-hant.png` 可繪製繁中畫面。 +`CHROMAFORGE_LANGUAGE=zh-hant chromaforge-cli snapshot --demo -o zh-hant.png` 可繪製繁中畫面。 接受 `zh-hant`、`zh-Hant`、`zh-TW`、`zh_TW.UTF-8` 與 `zh-HK`;儲存時統一使用 `zh-hant`。 控制通道可切換語言: diff --git a/docs/localization.md b/docs/localization.md index 1404982c37..65a6ae2d84 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,8 +1,5 @@ # Localization -> Names in angle brackets (``, ``, ``, ``, ``, …) are the values set in -> [`brand.toml`](../brand.toml); see the README. - The interface ships in the language it is written in (English) plus every language in the table in `crates/ui-egui/src/i18n.rs`. Today that is English, Simplified Chinese (`zh-hans`), Traditional Chinese (`zh-hant`, Taiwan), Japanese (`ja`), Brazilian Portuguese (`pt-br`), Spanish (`es`), German (`de`), Russian (`ru`), French (`fr`), Ukrainian (`uk`), Czech (`cs`), Italian (`it`), Georgian (`ka`), Swedish (`sv`), Finnish (`fi`), Indonesian (`id`), Vietnamese (`vi`) and Polish (`pl`). This file is the reference for **adding or maintaining a language**; the per-language notes @@ -183,7 +180,7 @@ to them. The glyph tests are skipped without `CRAFT_FONTS_DIR` (there are no CJK To look at a language, render it headless: ```sh -_LANGUAGE=zh-hans snapshot --demo --script tour.jsonl -o out.png --size 1600x1000 +CHROMAFORGE_LANGUAGE=zh-hans chromaforge-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000 ``` or, with the app running (`--control 7980`), run the language command @@ -192,7 +189,7 @@ or, with the app running (`--control 7980`), run the language command ## Language codes and settings The settings file stores the BCP-47 code, never the Rust variant name, so a language can be renamed -in code without invalidating anyone's saved preference. `_LANGUAGE` accepts what a system +in code without invalidating anyone's saved preference. `CHROMAFORGE_LANGUAGE` accepts what a system locale looks like (`zh_Hans`, `zh-CN`, `en_US`, `ja_JP.UTF-8`) and falls back to the base language when a region has no dedicated entry. diff --git a/docs/manual-site/scripts/fixtures/capture-one/Example.cocatalogdb b/docs/manual-site/scripts/fixtures/capture-one/Example.cocatalogdb index 90edac4b54..9dc897ed96 100644 Binary files a/docs/manual-site/scripts/fixtures/capture-one/Example.cocatalogdb and b/docs/manual-site/scripts/fixtures/capture-one/Example.cocatalogdb differ diff --git a/docs/manual-site/scripts/shots.d/develop.json b/docs/manual-site/scripts/shots.d/develop.json index 1171936b2e..cd6fd25470 100644 --- a/docs/manual-site/scripts/shots.d/develop.json +++ b/docs/manual-site/scripts/shots.d/develop.json @@ -188,12 +188,32 @@ "method": "ui.scroll", "params": { "dx": 0, - "dy": -900 + "dy": -6000 }, "only": [ "classic", "compact" ] + }, + { + "method": "ui.scroll", + "params": { + "dx": 0, + "dy": 330 + }, + "only": [ + "classic" + ] + }, + { + "method": "ui.scroll", + "params": { + "dx": 0, + "dy": 390 + }, + "only": [ + "compact" + ] } ], "layouts": [ diff --git a/docs/manual-site/scripts/shots.d/library.json b/docs/manual-site/scripts/shots.d/library.json index 49da7e4262..09f77bb6d4 100644 --- a/docs/manual-site/scripts/shots.d/library.json +++ b/docs/manual-site/scripts/shots.d/library.json @@ -366,6 +366,13 @@ "only": [ "modern" ] + }, + { + "method": "ui.scroll", + "params": { + "dx": 0, + "dy": -600 + } } ] }, diff --git a/docs/manual-site/src/assets/shots/classic/capture-one-import-result.jpg b/docs/manual-site/src/assets/shots/classic/capture-one-import-result.jpg index edcaf26bda..070e6e7df2 100644 Binary files a/docs/manual-site/src/assets/shots/classic/capture-one-import-result.jpg and b/docs/manual-site/src/assets/shots/classic/capture-one-import-result.jpg differ diff --git a/docs/manual-site/src/assets/shots/classic/transform.jpg b/docs/manual-site/src/assets/shots/classic/transform.jpg index 0aebf07ca9..876d095d93 100644 Binary files a/docs/manual-site/src/assets/shots/classic/transform.jpg and b/docs/manual-site/src/assets/shots/classic/transform.jpg differ diff --git a/docs/manual-site/src/assets/shots/compact/capture-one-import-result.jpg b/docs/manual-site/src/assets/shots/compact/capture-one-import-result.jpg index bf65afd20a..e70212c14f 100644 Binary files a/docs/manual-site/src/assets/shots/compact/capture-one-import-result.jpg and b/docs/manual-site/src/assets/shots/compact/capture-one-import-result.jpg differ diff --git a/docs/manual-site/src/assets/shots/compact/transform.jpg b/docs/manual-site/src/assets/shots/compact/transform.jpg index 7e32ee5f39..856e00259c 100644 Binary files a/docs/manual-site/src/assets/shots/compact/transform.jpg and b/docs/manual-site/src/assets/shots/compact/transform.jpg differ diff --git a/docs/manual-site/src/assets/shots/modern/capture-one-import-result.jpg b/docs/manual-site/src/assets/shots/modern/capture-one-import-result.jpg index b9bbcb2bb8..e9aad7de2f 100644 Binary files a/docs/manual-site/src/assets/shots/modern/capture-one-import-result.jpg and b/docs/manual-site/src/assets/shots/modern/capture-one-import-result.jpg differ diff --git a/docs/manual-site/src/content/docs/ai/denoise.mdx b/docs/manual-site/src/content/docs/ai/denoise.mdx index 2b3848a467..b49b22bc42 100644 --- a/docs/manual-site/src/content/docs/ai/denoise.mdx +++ b/docs/manual-site/src/content/docs/ai/denoise.mdx @@ -13,7 +13,7 @@ import { Aside } from '@astrojs/starlight/components'; - **Where**: Edit ▸ **Detail** ▸ under **AI Denoise**, the **Enable** switch and **Amount** (0 to 100). Turning it on starts at 50. - **Works out of the box**: a built-in denoiser (block matching and collaborative filtering after measuring the photo's noise). No download and no weights. It is a classical filter, not a trained network. -- **Raw only by default**: Bayer raw files. A JPEG, PNG or TIFF is denoised only with a model for finished pictures. X-Trans, Foveon and demosaiced DNG are not supported. The panel says so on photos it cannot handle. +- **Raw only by default**: raw files with a colour filter array. Bayer raws go to the model as they are; X-Trans (and other red/green/blue patterns) are first rebuilt as a Bayer mosaic, an approximation the model was not trained on. A JPEG, PNG or TIFF is denoised only with a model for finished pictures. Foveon, monochrome and demosaiced DNG are not supported. The panel says so on photos it cannot handle. - **Non-destructive**: the cleaned picture is cached data, made in the background and shown in previews and exports. Your file is never changed. Exports make it if it is missing. - **Manual noise reduction** (Luminance, Color) stays separate and works on every photo. diff --git a/docs/manual-site/src/content/docs/ai/faces.mdx b/docs/manual-site/src/content/docs/ai/faces.mdx index 1dde5cee48..7dbc364dda 100644 --- a/docs/manual-site/src/content/docs/ai/faces.mdx +++ b/docs/manual-site/src/content/docs/ai/faces.mdx @@ -16,7 +16,9 @@ import { Aside } from '@astrojs/starlight/components'; - **Detect Faces**: Library ▸ **Detect Faces** finds faces in the selected photos with the MediaPipe Face Landmarker and adds unnamed boxes in one undo step. It offers the small one-time download the first time. Boxes from XMP or that you named are never touched. Finds faces down to about 60 pixels; tiny faces in big group photos can be missed. - **Recognise faces (experimental)**: Settings ▸ **Faces**. Off until you switch it on, even after a model is downloaded: scanning a big library takes a long time. With a recognition model chosen, a background scan works out what each face looks like and suggests names from faces you have already named. A suggestion is only a label such as "Jane Doe?" until you confirm it; nothing is named for you. - **Face scan controls**: Settings ▸ Faces ▸ **Face scan** shows where the scan is (not started, indexing, paused, complete, and how many photos are done) with **Pause** / **Resume**, **Clear…** (deletes what the scan learned and leaves it paused; named faces stay) and **Restart…** (deletes it and scans every photo again). Both ask first. While the scan runs, its "Finding faces" row in the activity stack has a pause button (resume while paused; a pause is kept across restarts) and a gear that opens Settings ▸ Faces. -- **Face Maintenance…**: run a cancellable detect-and-recognise, recognise-existing, new-items, embedding rebuild, or rescan-and-merge pass over visible photos, the selection, one or more folders, or one or more regular or smart collections. Right-click a folder to prefill **Scan Folder for Faces…**; filesystem folders include subfolders by default and can be limited to direct children. Collection sets always include nested collections. Rescan can merge old automatic detections or replace them while preserving named, ignored, manual, and non-face regions. Reset All Face Data is a separate confirmed action; it leaves the continuous scan paused so the reset data is not immediately recreated. Scripts use `faces.maintain` and `faces.scanStatus`; `faces.reset` requires `{ confirmed: true }`. MCP clients also get `cmd_faces_maintain`, `cmd_faces_scanStatus` and `cmd_faces_reset`. +- **Face Maintenance…**: run a cancellable detect-and-recognise, recognise-existing, new-items, embedding rebuild, or rescan-and-merge pass over visible photos, the selection, one or more folders, or one or more regular or smart collections. Right-click a folder to prefill **Scan Folder for Faces…**; filesystem folders include subfolders by default and can be limited to direct children. Collection sets always include nested collections. Rescan can merge old automatic detections or replace them while preserving named, ignored, manual, and non-face regions. Reset All Face Data is a separate confirmed action; it leaves the continuous scan paused so the reset data is not immediately recreated. Recognize Existing Faces, Rebuild All Embeddings and Rebuild Named Faces find no new faces; with the face model installed they align each face as the background scan does, since a recognition model matches a face cut by its box much less well. Scripts use `faces.maintain` and `faces.scanStatus`; `faces.reset` requires `{ confirmed: true }`. MCP clients also get `cmd_faces_maintain`, `cmd_faces_scanStatus` and `cmd_faces_reset`. +- **Build Face Thumbnails**: Library ▸ Faces ▸ **Build Face Thumbnails** renders a tile of every face in the library at the size the People view shows now, ahead of the scrolling that would otherwise build them one by one — on a library with hundreds of people that is the slow part of People. It runs in the background (a cancellable row in the activity stack) and keeps the tiles in the thumbnail cache, so People scrolls without rendering afterwards, also after a restart. Scripts use `faces.buildThumbnails` (`status` reports the last run, `cancel` stops it). +- **Sorting a person's faces**: a person's page in the People view has a sort picker next to its title — import order, capture time oldest or newest first, folder, or largest face first. Scripts use `person.sort`. - **Everything stays local**: face data is cached beside the library, not in the catalog or XMP. diff --git a/docs/manual-site/src/content/docs/ai/models.mdx b/docs/manual-site/src/content/docs/ai/models.mdx index fd06e11e6c..422184228d 100644 --- a/docs/manual-site/src/content/docs/ai/models.mdx +++ b/docs/manual-site/src/content/docs/ai/models.mdx @@ -52,11 +52,11 @@ Meta releases the weights under the custom, non-OSI [SAM License](https://github The model files belong in `models/sam3/` inside the per-user settings directory: -- **Linux**: `~/.config//models/sam3` +- **Linux**: `~/.config/Chromaforge/models/sam3` - **macOS**: `~/Library/Application Support/Chromaforge/models/sam3` - **Windows**: `%APPDATA%\Chromaforge\models\sam3` -You can also point Chromaforge at any other folder in Settings ▸ **AI Models** ▸ **SAM 3 model folder**, or override it with the `_SAM3_DIR` environment variable. +You can also point Chromaforge at any other folder in Settings ▸ **AI Models** ▸ **SAM 3 model folder**, or override it with the `CHROMAFORGE_SAM3_DIR` environment variable. ### 3. Install scripts diff --git a/docs/manual-site/src/content/docs/ai/orientation.mdx b/docs/manual-site/src/content/docs/ai/orientation.mdx index ff635c6a70..c9cdd88e90 100644 --- a/docs/manual-site/src/content/docs/ai/orientation.mdx +++ b/docs/manual-site/src/content/docs/ai/orientation.mdx @@ -23,7 +23,7 @@ import { Aside } from '@astrojs/starlight/components'; Auto orient puts a small classifier (a few thousand numbers) on top of the CLIP model. You can fit one for your own photos: 1. Open a library whose photos all stand the right way up (several hundred photos or more works best). -2. Run `ml.orientation.fit` from the command line or a script: ` run --library ml.orientation.fit '{}'`. Each photo is rendered, turned four ways and looked at; one photo in five is held out to measure the result and choose how sure an answer must be. Only the numbers are kept, never the photos. +2. Run `ml.orientation.fit` from the command line or a script: `chromaforge-cli run --library ml.orientation.fit '{}'`. Each photo is rendered, turned four ways and looked at; one photo in five is held out to measure the result and choose how sure an answer must be. Only the numbers are kept, never the photos. 3. The classifier is saved next to the models (`orientation-clip-vit-b32-laion2b.json`) and Auto orient uses it from then on. `ml.orientation.status` shows which classifier is in use and how accurate it measured. ## Limits diff --git a/docs/manual-site/src/content/docs/automate/actions.mdx b/docs/manual-site/src/content/docs/automate/actions.mdx index 6206ba0447..2baa2b102a 100644 --- a/docs/manual-site/src/content/docs/automate/actions.mdx +++ b/docs/manual-site/src/content/docs/automate/actions.mdx @@ -12,7 +12,7 @@ import { Aside } from '@astrojs/starlight/components'; - **Parameters**: a step value written `{{name}}` becomes a parameter asked for when the action plays. - **Play**: runs once per selected photo (the default), then restores your selection. It stops at the first failing step. - **Shortcut**: give a saved action a key in the panel; the desktop app plays it on that key. -- **From scripts**: ` run-action NAME [param=value…] [ids=[…]]`, or the `actions.*` commands (`list`, `get`, `play`, `delete`) through MCP. +- **From scripts**: `chromaforge-cli run-action NAME [param=value…] [ids=[…]]`, or the `actions.*` commands (`list`, `get`, `play`, `delete`) through MCP. diff --git a/docs/manual-site/src/content/docs/automate/cli-and-mcp.md b/docs/manual-site/src/content/docs/automate/cli-and-mcp.md index 330def5f57..d4e9e0b68f 100644 --- a/docs/manual-site/src/content/docs/automate/cli-and-mcp.md +++ b/docs/manual-site/src/content/docs/automate/cli-and-mcp.md @@ -6,7 +6,7 @@ sidebar: --- - Every action is a **command** with an id. The menus, keys, CLI, control channel, MCP and plug-ins all run the same ones. See [Commands](../commands/). -- **CLI** (``): run commands, render and export without a window. See [Command line](../cli/). +- **CLI** (`chromaforge-cli`): run commands, render and export without a window. See [Command line](../cli/). - **Headless render and snapshots**: no window, no GPU. See [Headless](../headless/). - **Control channel**: JSON lines over a local port; drive the running app. See [Control channel](../control-channel/). - **MCP server**: let an AI agent work on your library. See [MCP server](../mcp/). diff --git a/docs/manual-site/src/content/docs/automate/cli.md b/docs/manual-site/src/content/docs/automate/cli.md index 5c94a101b9..55c9b442ca 100644 --- a/docs/manual-site/src/content/docs/automate/cli.md +++ b/docs/manual-site/src/content/docs/automate/cli.md @@ -1,28 +1,28 @@ --- title: Command line -description: The program runs commands, renders and exports without a window. +description: The chromaforge-cli program runs commands, renders and exports without a window. sidebar: order: 2 --- -- **Start**: ` --help` lists everything; ` --version` prints the version. -- **` run`**: run a chain of commands and print one JSON line per command. A word without `=` starts the next command; `key=value` values are JSON when they parse. -- **` render`**: develop one file and export it (see [Headless](../headless/)). -- **` run-action NAME`**: play a saved [action](../actions/) on the selection or on `ids`. -- **` sync-folder FOLDER`** and **`open-url URL`**: synchronise a library folder, or follow a `` link. Opening the link itself (Windows, Linux) starts the app, or hands it to the copy already running, which opens Synchronize Folder for the folder. -- **` mcp`**: the [MCP server](../mcp/). -- **` merge hdr|panorama|hdr-panorama|hdr-batch|focus FILES…`**: Photo Merge without a window. -- **` quality-scan [FOLDER]`**: the [Image Quality Scanner](../../library/quality-scanner/) without a window: scores the library (or a folder) and prints the summary as JSON. `--accepted`, `--rejected`, `--apply-flags` (`--auto-flag`), `--rescan`, `--weights`, `--auto-rate`, `--overwrite-metadata` and `--star-breaks` (five scores) set what the dialog sets; `--connect` scans in the running app. `run photo.qualityScan …` does the same from a script. -- **` commands` / `controls`**: the command and Develop-control registries (`--json` for scripts). -- **` compare REFERENCE TEST`**: how far two renders of one photo are apart (CIEDE2000 by tone band and hue). +- **Start**: `chromaforge-cli --help` lists everything; `chromaforge-cli --version` prints the version. +- **`chromaforge-cli run`**: run a chain of commands and print one JSON line per command. A word without `=` starts the next command; `key=value` values are JSON when they parse. +- **`chromaforge-cli render`**: develop one file and export it (see [Headless](../headless/)). +- **`chromaforge-cli run-action NAME`**: play a saved [action](../actions/) on the selection or on `ids`. +- **`chromaforge-cli sync-folder FOLDER`** and **`open-url URL`**: synchronise a library folder, or follow a `Chromaforge` link. Opening the link itself (Windows, Linux) starts the app, or hands it to the copy already running, which opens Synchronize Folder for the folder. +- **`chromaforge-cli mcp`**: the [MCP server](../mcp/). +- **`chromaforge-cli merge hdr|panorama|hdr-panorama|hdr-batch|focus FILES…`**: Photo Merge without a window. +- **`chromaforge-cli quality-scan [FOLDER]`**: the [Image Quality Scanner](../../library/quality-scanner/) without a window: scores the library (or a folder) and prints the summary as JSON. `--accepted`, `--rejected`, `--apply-flags` (`--auto-flag`), `--rescan`, `--weights`, `--auto-rate`, `--overwrite-metadata` and `--star-breaks` (five scores) set what the dialog sets; `--connect` scans in the running app. `run photo.qualityScan …` does the same from a script. +- **`chromaforge-cli commands` / `controls`**: the command and Develop-control registries (`--json` for scripts). +- **`chromaforge-cli compare REFERENCE TEST`**: how far two renders of one photo are apart (CIEDE2000 by tone band and hue). - **Library choice**: `--demo` (procedural demo photos), `--library DIR` (a saved library; `@app` is the one the desktop app opens), `--import PATH`, or `--connect` to drive the running app. - **Calibration tools** for contributors: `calibrate`, `calibrate-chart`, `calibrate-lightroom`, `camdb`; `denoise-serve` runs AI Denoise tiles for other computers. ```sh - run --import ~/Photos/a.dng develop.set control=light.exposure value=0.7 \ +chromaforge-cli run --import ~/Photos/a.dng develop.set control=light.exposure value=0.7 \ develop.auto app.export path=/tmp/a.jpg longEdge=1600 - run --library ~/lib --import ~/Photos/shoot library.info - run --demo --script steps.jsonl --keep-going +chromaforge-cli run --library ~/lib --import ~/Photos/shoot library.info +chromaforge-cli run --demo --script steps.jsonl --keep-going ``` - Exit status is non-zero when a command fails; `--keep-going` continues after a failure. diff --git a/docs/manual-site/src/content/docs/automate/commands.mdx b/docs/manual-site/src/content/docs/automate/commands.mdx index ad9a75ba67..fcf256dc05 100644 --- a/docs/manual-site/src/content/docs/automate/commands.mdx +++ b/docs/manual-site/src/content/docs/automate/commands.mdx @@ -10,13 +10,13 @@ import { Aside } from "@astrojs/starlight/components"; - **Command**: one named action (`photo.rate`, `develop.set`, `app.export`). Each has an id, a label, a menu path, an optional shortcut and parameters. - **Same everywhere**: menus, keys, CLI, control channel, MCP, plug-ins, actions and control surfaces all dispatch by id. - **Develop controls** are commands too: every slider is a control id such as `light.exposure`, set with `develop.set`. -- **List them**: ` commands` (add `--json` for scripts); ` controls` for the Develop control ids and ranges. +- **List them**: `chromaforge-cli commands` (add `--json` for scripts); `chromaforge-cli controls` for the Develop control ids and ranges. - **In the app**: **Edit ▸ Settings ▸ Shortcuts** lists every command with its key and id, and a search box. **Help ▸ Keyboard Shortcuts** opens the same list. - There is no command palette yet; **Find…** (⌘F / Ctrl+F) searches photos, not commands. ```sh - commands | grep develop - controls +chromaforge-cli commands | grep develop +chromaforge-cli controls ```