Merge storytold/main into issue-3404-unused-egui-patches

Main uses egui_extras since #3726, so its patch stays; the three still unused (egui_demo_lib, egui_inspection, egui_system_font_provider) are removed.
This commit is contained in:
Antonio Sokic committed 2026-11-06 22:02:58 +01:00
commit 7e6a861dd7
669 files changed
+77891 -4773

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
name: CI (Windows)
# The Windows leg of the gate: clippy and the tests of the crates with Windows-only code, on pull
# requests and pushes to main that touch that code, and on pull requests labelled `full-ci`.
# The Linux gate (ci.yml) still runs everything else on every pull request.
#
# Not the full `cargo xtask ci`: on a cold windows-latest runner that is well over an hour, and
# its wasm, layers, assets and parity steps don't differ by platform. What does is the
# `cfg(windows)` code (title bar theme, monitor profiles, file handling) and its tests.
on:
push:
branches: [main]
pull_request:
# `labeled`: adding `full-ci` starts it. Other labels skip (see concurrency and the scope job).
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# Its own group, so the Windows leg never cancels the Linux gate. A newer push to a PR branch
# cancels its older run; a label other than `full-ci` gets a group of its own, so it cancels nothing.
concurrency:
group: ci-windows-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ github.event.action == 'labeled' && github.event.label.name != 'full-ci' && format('-label-{0}', github.run_id) || '' }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
windows-scope:
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
uses: storytold/craft-common-actions/.github/workflows/changed-paths.yml@main
with:
label: full-ci
# The crates and files with `cfg(windows)` code, and what decides how they build: their
# manifests and the lockfile (a dependency bump can break only Windows).
paths: |
.github/workflows/ci-windows.yml
apps/lightcraft/*
apps/lightcraft-cli/src/bench_cull.rs
apps/lightcraft-cli/tests/it/cli.rs
apps/lightcraft-cli/Cargo.toml
crates/wincolor/*
crates/ui-egui/src/theme.rs
crates/ui-egui/src/panels/left/local.rs
crates/ui-egui/src/menus/files.rs
crates/ui-egui/src/dialogs/settings/performance.rs
crates/catalog/src/safe_file.rs
crates/catalog/Cargo.toml
crates/engine/src/originals.rs
crates/engine/src/import/scan.rs
crates/engine/src/walk.rs
crates/engine/src/doc_path.rs
crates/engine/src/rename/*
crates/engine/src/cmd/geocode.rs
crates/engine/src/tests/sync.rs
crates/engine/src/tests/import.rs
crates/engine/Cargo.toml
crates/ui-egui/Cargo.toml
Cargo.toml
Cargo.lock
rust-toolchain.toml
.cargo/*
gate-windows:
needs: windows-scope
if: needs.windows-scope.outputs.matched == 'true'
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-latest"]'
# Same craft-fonts commit as ci.yml and release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
targets: ""
tools: ""
timeout-minutes: 90
windows-command: |
pkgs=(-p lightcraft-wincolor -p lightcraft-catalog -p lightcraft-engine -p lightcraft-ui-egui -p lightcraft -p lightcraft-cli)
cargo clippy "${pkgs[@]}" --all-targets --keep-going -- -D warnings
cargo test "${pkgs[@]}" --lib --bins --tests --no-fail-fast
+3
View File
@@ -24,6 +24,9 @@ jobs:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
timeout-minutes: 90
# A green run takes about 40 min. A hung test is stopped at 80 min, so the log lists the
# processes still running and the leg fails as timed out instead of being cancelled at 90.
gate-timeout-minutes: 80
# xtask ci runs cargo test: the demo scene cache is per process, so nextest is slower here.
tools: ""
packages: >-
+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+2
View File
@@ -14,6 +14,7 @@ on:
permissions:
contents: write
packages: write
concurrency:
group: release-${{ github.ref }}
@@ -84,3 +85,4 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
+3
View File
@@ -14,3 +14,6 @@ plan/
# model weights are never committed (SAM 3: docs/ai-masks.md)
*.safetensors
*.safetensors.part
# Python tools import their public operator family.
__pycache__/
+103 -35
View File
@@ -1,25 +1,75 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# LightCraft — instructions for agents
LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructive raw developer targeting Adobe Lightroom parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../pdfcraft` (Acrobat), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator) and `../filmcraft` (Premiere), with the same conventions.
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next unchecked task, blockers).
2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README/docs of the crate you touch. Behaviour/visual reference: `plan/lightroom/` (incl. `10-observed-ui.md` + screenshots).
3. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for
`plan/` is an optional gitignored notebook (status, execution notes, `plan/lightroom/`). Do not ask for it and do not stop when it is absent.
1. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for
method and evidence, [`docs/target-app-parity.md`](docs/target-app-parity.md). The checklist counts features that
*exist*; the real gaps are quality and coverage: camera colour calibration, CR3 / compressed raws, per-model
verification, render fidelity against Lightroom, AI models, HDR / video / Classic modules (raw detail:
[`docs/raw-parity.md`](docs/raw-parity.md)). A ✅ row is not proof of parity — if you find a ✅ feature that is
wrong or incomplete, downgrade it to 🟡 with a note.
4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
2. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut).
When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` /
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history, per
craftrules `standards/progress-docs.md`); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
path the tracker cites still exists, and `cargo xtask parity --write` refreshes its summary.
5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local-only).
`docs/target-app-parity.md` when a listed gap closes (add a row to each doc's revision history; the header line keeps only `Last reviewed`, `Target` and the `Changes` link, never a `Last updated` date or a change note, which every PR would edit and conflict on); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
path the tracker cites still exists and that `docs/gaps.md` lists each gap once, and `cargo xtask parity --write`
refreshes its summary.
`plan/` stays optional. Do not stop to ask except for the house-rule list.
**Merging agent branches:** merge one branch, run `cargo xtask ci`, fix, commit — then the next. Two individually green
branches can still break each other (e.g. a new struct field vs. a new constructor).
@@ -32,17 +82,17 @@ and often so a crash loses minutes, not hours.
People trust LightCraft with their photo libraries and edits; a crash loses their work. A malformed raw/JPEG/XMP, a bad
command, control or MCP argument, a corrupt catalog or settings file, or a full disk must produce an error the user (or
agent) can act on, never a panic. Don't ship a feature by adding a panic path, and fix a crash before building on top
of it. Full standard: `../craftrules/standards/never-crash.md`
([storytold/craftrules](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md)).
of it.
- **Non-test code never panics:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`, and
no `unsafe`. Return the crate's error type through `Result` and `?`; use `ok_or(..)?`, `let … else`, `if let`, or a
fallback (`unwrap_or…`) only where it can't silently corrupt a document. An unfinished feature returns an
"unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]`
+ `.expect("why it can't fail")`.
- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed
allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
fallback where possible, and a line here naming it.
allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile
Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every
other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper
crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it.
- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or
arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative
casts to `usize`; cap allocations sized by input; slice strings only at char boundaries.
@@ -51,20 +101,31 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
- **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped
panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native.
- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix.
- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic in tests only; indexing is not denied. Every production crate
root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Not `[workspace.lints]`: those would also hit
integration tests, examples and benches. New crates start with the attribute.
- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace
denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with
`workspace = true` under a `[lints]` table, and `sysmem` repeats those denies in its local lint table. Every production crate root
(`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include
`workspace = true` under a `[lints]` table in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include
the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots`
(part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib`
web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception).
## Non-negotiables
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…).
- **Pure Rust** in the product. No C/C++ dependencies.
- **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd.
- **Layering** (enforced by `cargo xtask layers`; `plan/architecture.md` §3 is optional background): nothing below L5 depends on egui/eframe/winit/rfd.
- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec.
- **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything
that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind,
label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses
`Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row.
- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm).
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm).
For iteration, `cargo xtask ci --quick` runs fmt, clippy, changed packages' tests, layers, assets, roots,
and heif / parity / wasm when touched; it does not replace the full gate before merging branches.
One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`).
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states.
## Assets: icons, images, fonts (ABSOLUTE RULE — never violate)
- **Never use any iconography, image, artwork, font, sound or other asset from Adobe products** (no Lightroom/Creative Cloud icons, no screenshots, no presets/profiles/LUTs, no UI bitmaps — not even as a temporary placeholder or "reference copy"). Observing Adobe's UI to imitate *layout and behaviour* is allowed; copying or tracing its assets is not.
@@ -83,11 +144,10 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
then `CRAFT_FONTS_DIR=../craft-fonts cargo run -p lightcraft` (or any cargo/xtask command). `crates/engine/build.rs`
embeds the manifest's fonts as `lightcraft_engine::CRAFT_FONTS` (wasm32: BIZ UDPGothic Regular only); `cargo xtask web`
ships Noto Sans CJK SC Regular as a separate asset loaded by the UI before startup. The UI
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter. Unset,
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter; the UI also falls back on the faces of other scripts (Thai, Arabic, …). Unset,
`CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build
with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip
without it; the FreeBSD CI job runs them with it. Rules: craftrules
[`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md).
without it; the FreeBSD CI job runs them with it.
- Icons drawn in code (e.g. `crates/ui-egui/src/icons.rs`) are original work and are recorded in `assets/ATTRIBUTION.md` as such; do not trace them from Adobe icons.
- Demo/test images: generated procedurally by `lightcraft-scenes`, or CC0 downloads kept in the gitignored `corpus/` with their source recorded. Screenshots of Adobe apps live only in the gitignored `plan/` and are never committed or published.
- **Enforced:** `cargo xtask assets` (in `ci`) fails when an image/icon/font/sound/video/raw/ICC/XMP file is not matched
@@ -101,7 +161,9 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
- **Never send OS-level synthetic input** (osascript/System Events keystrokes or clicks, `cliclick`, accessibility
automation): it goes to whatever window is frontmost — the user's terminal or other apps. Drive LightCraft only
through its control channel (`ui.key`, `ui.pointer`, `ui.clickWidget`, `ui.menu.invoke`) or headless snapshots.
- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`, compare with `plan/lightroom/screenshots/`.
- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`. Compare with
`plan/lightroom/screenshots/` when available. Without that optional notebook, verify the result against the
task's requirements, committed documentation and regression tests; do not request the notebook or block work.
- **Unattended (display asleep/locked, CI, nightly runs): prefer headless snapshots** — no window needed:
`lightcraft-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000` (control-protocol requests,
one per line; see `docs/control-protocol.md` → Headless rendering). In a running app use
@@ -110,10 +172,12 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
the running app). See `docs/mcp.md`. Quick non-UI checks: `lightcraft-cli render in.jpg -o out.jpg --set light.exposure=1`.
- Export goes through `lightcraft_engine::export` (one encoder for app, CLI, MCP and web); UI-only commands live in
`crates/ui-egui/src/menus.rs`.
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Text boxes use `crates/ui-egui/src/widgets/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the
Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id
that is unique on screen. Older fields still on `TextEdit` move over as they are touched.
- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-<name>`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`<scratch>/<agent-name>/`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone).
- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media.
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
## Testing & performance (do this often)
- Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`,
@@ -123,9 +187,15 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
- **Benchmarks:** `cargo xtask bench` (24 MP raw from corpus; CPU and GPU columns) appends to `target/bench/history.jsonl`
and flags CPU-time regressions > 20 % vs the previous run (`--strict` to fail). Run it before and after perf work.
- **Measure, don't guess**: `LIGHTCRAFT_PROFILE=1` prints per-stage pipeline timings to stderr; time CLI renders
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
with `/usr/bin/time`. Timings may go in the optional `plan/` notebook. Budgets: slider update ≤ 16 ms (draft) / loupe
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it
passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with
`#[ignore = "flaky: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
@@ -142,22 +212,20 @@ evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the work
## Contributor credits (About window)
- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json`
(commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for
(commit stats; never hand-edit) and `contributors/people.toml` (names people chose for
themselves). See `docs/contributors.md`.
- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
whether they want to be credited by more than their username: a real name, a display name, and/or
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
(copy the template at the top of the file, or run
`python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`)
(copy the template at the top of the file)
and include it in their PR, committed as them. If no, change nothing: they are credited as
`@username` anyway.
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
GitHub profiles). Never hand-edit `contributors.json`.
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- `ci.yml` is the Linux gate, on every pull request. `ci-windows.yml` adds a Windows leg (clippy and tests of the crates with `cfg(windows)` code) when a pull request changes the paths it lists; add the `full-ci` label to run it on any other pull request. When you add `cfg(windows)` code in a new file, add the file to its `paths` in a CI PR.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
+1 -159
View File
@@ -1,159 +1 @@
# LightCraft — instructions for agents
LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructive raw developer targeting Adobe Lightroom parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../pdfcraft` (Acrobat), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator) and `../filmcraft` (Premiere), with the same conventions.
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next unchecked task, blockers).
2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README/docs of the crate you touch. Behaviour/visual reference: `plan/lightroom/` (incl. `10-observed-ui.md` + screenshots).
3. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for
method and evidence, [`docs/target-app-parity.md`](docs/target-app-parity.md). The checklist counts features that
*exist*; the real gaps are quality and coverage: camera colour calibration, CR3 / compressed raws, per-model
verification, render fidelity against Lightroom, AI models, HDR / video / Classic modules (raw detail:
[`docs/raw-parity.md`](docs/raw-parity.md)). A ✅ row is not proof of parity — if you find a ✅ feature that is
wrong or incomplete, downgrade it to 🟡 with a note.
4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row
tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut).
When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` /
`docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history, per
craftrules `standards/progress-docs.md`); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and
path the tracker cites still exists and that `docs/gaps.md` lists each gap once, and `cargo xtask parity --write`
refreshes its summary.
5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local-only).
**Merging agent branches:** merge one branch, run `cargo xtask ci`, fix, commit — then the next. Two individually green
branches can still break each other (e.g. a new struct field vs. a new constructor).
**Resuming after a crash / another session:** check `git status` on main, `git worktree list`, and each worktree's
`git log main..HEAD` + `git status` for unmerged commits or uncommitted work before starting anything new. Commit small
and often so a crash loses minutes, not hours.
## Never crash (outranks feature work)
People trust LightCraft with their photo libraries and edits; a crash loses their work. A malformed raw/JPEG/XMP, a bad
command, control or MCP argument, a corrupt catalog or settings file, or a full disk must produce an error the user (or
agent) can act on, never a panic. Don't ship a feature by adding a panic path, and fix a crash before building on top
of it. Full standard: `../craftrules/standards/never-crash.md`
([storytold/craftrules](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md)).
- **Non-test code never panics:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`, and
no `unsafe`. Return the crate's error type through `Result` and `?`; use `ok_or(..)?`, `let … else`, `if let`, or a
fallback (`unwrap_or…`) only where it can't silently corrupt a document. An unfinished feature returns an
"unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]`
+ `.expect("why it can't fail")`.
- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed
allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
fallback where possible, and a line here naming it.
- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or
arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative
casts to `usize`; cap allocations sized by input; slice strings only at char boundaries.
- **Bound recursion** (depth limits or seen-sets: IFD chains, nested metadata, collections). **Don't cascade:**
`lock().unwrap_or_else(PoisonError::into_inner)` or an error; worker-thread joins are `Result`s.
- **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped
panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native.
- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix.
- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace
denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with
`[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root
(`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include
`[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include
the attribute before modules or other crate items; crate-level `//!` documentation may precede it.
## Non-negotiables
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…).
- **Pure Rust** in the product. No C/C++ dependencies.
- **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd.
- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec.
- **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything
that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind,
label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses
`Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row.
- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages'
tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR
(`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see
the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`).
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment.
## Assets: icons, images, fonts (ABSOLUTE RULE — never violate)
- **Never use any iconography, image, artwork, font, sound or other asset from Adobe products** (no Lightroom/Creative Cloud icons, no screenshots, no presets/profiles/LUTs, no UI bitmaps — not even as a temporary placeholder or "reference copy"). Observing Adobe's UI to imitate *layout and behaviour* is allowed; copying or tracing its assets is not.
- **This includes Adobe's open-licensed assets**: no Source Sans/Serif/Code or Source Han fonts, no Adobe Fonts, no
Adobe-published icon sets, sample photos, colour profiles or LUTs — even when OFL/MIT. The UI font is Inter (OFL);
Japanese and Chinese fonts come from craft-fonts (below). **One exception (maintainer decision, 2026-10-07): Noto
Sans/Serif CJK** (Google-branded, OFL, co-developed with Adobe as Source Han) is allowed via craft-fonts for Chinese
text, because nearly every OFL Chinese face derives from it. Use it unmodified under its OFL; this does not open the
door to Source Han under Adobe's name or to any other Adobe asset.
- Every asset in the repository must be one of: **our own original work** (e.g. icons drawn in code as vectors, procedurally generated demo photos), **public domain / CC0**, **Creative Commons** (CC-BY / CC-BY-SA with attribution honoured), **OFL** (fonts), or **permissive open-source** (MIT/Apache-2.0/BSD/ISC) — or contributed by a person who created the asset and licenses it openly.
- **Exception: `docs/brand/`.** The ArtCraft name, wordmark and logos there are ArtCraft Team trademarks, not open source and not covered by LightCraft's MIT OR Apache-2.0 licence (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`); their terms are in `docs/brand/LICENSE-brand.txt`. Use them only unmodified and never redraw, recolour or derive from them.
- **Every asset must have an entry in `assets/ATTRIBUTION.md`** (path, title, author/creator, source URL or "original work", licence, date added, modifications) and its licence text when required (e.g. `assets/fonts/OFL-*.txt`). Add the entry in the same commit as the asset. Assets without an attribution entry must not be committed.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo.** Don't commit
font files here (Inter, already in `assets/fonts/`, is the one exception); add new fonts to craft-fonts. LightCraft
uses it as the optional build input `CRAFT_FONTS_DIR`: `git clone https://github.com/storytold/craft-fonts ../craft-fonts`
then `CRAFT_FONTS_DIR=../craft-fonts cargo run -p lightcraft` (or any cargo/xtask command). `crates/engine/build.rs`
embeds the manifest's fonts as `lightcraft_engine::CRAFT_FONTS` (wasm32: BIZ UDPGothic Regular only); `cargo xtask web`
ships Noto Sans CJK SC Regular as a separate asset loaded by the UI before startup. The UI
(`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter; the UI also falls back on the faces of other scripts (Thai, Arabic, …). Unset,
`CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build
with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip
without it; the FreeBSD CI job runs them with it. Rules: craftrules
[`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md).
- Icons drawn in code (e.g. `crates/ui-egui/src/icons.rs`) are original work and are recorded in `assets/ATTRIBUTION.md` as such; do not trace them from Adobe icons.
- Demo/test images: generated procedurally by `lightcraft-scenes`, or CC0 downloads kept in the gitignored `corpus/` with their source recorded. Screenshots of Adobe apps live only in the gitignored `plan/` and are never committed or published.
- **Enforced:** `cargo xtask assets` (in `ci`) fails when an image/icon/font/sound/video/raw/ICC/XMP file is not matched
by a path pattern in the first column of `assets/ATTRIBUTION.md`, when a referenced licence file is missing, when a
file name suggests Adobe material, or when an Adobe profile/template format (`.dcp`, `.lcp`, `.lrtemplate`, …) appears.
Never weaken this check to make a commit pass — fix the attribution or remove the asset.
- When in doubt about an asset's licence: don't use it.
## Running and looking at the app
- `cargo run --release -p lightcraft -- --control 7980` opens the desktop app with the JSON-lines control server (see `docs/control-protocol.md`).
- **Never send OS-level synthetic input** (osascript/System Events keystrokes or clicks, `cliclick`, accessibility
automation): it goes to whatever window is frontmost — the user's terminal or other apps. Drive LightCraft only
through its control channel (`ui.key`, `ui.pointer`, `ui.clickWidget`, `ui.menu.invoke`) or headless snapshots.
- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`, compare with `plan/lightroom/screenshots/`.
- **Unattended (display asleep/locked, CI, nightly runs): prefer headless snapshots** — no window needed:
`lightcraft-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000` (control-protocol requests,
one per line; see `docs/control-protocol.md` → Headless rendering). In a running app use
`ui.screenshot {"path": …, "headless": true}`; windowed screenshots fall back to headless after 2 s.
- MCP: `lightcraft-cli mcp` (headless, `--demo` for the procedural library) or `lightcraft-cli mcp --connect` (drives
the running app). See `docs/mcp.md`. Quick non-UI checks: `lightcraft-cli render in.jpg -o out.jpg --set light.exposure=1`.
- Export goes through `lightcraft_engine::export` (one encoder for app, CLI, MCP and web); UI-only commands live in
`crates/ui-egui/src/menus.rs`.
- Text boxes use `crates/ui-egui/src/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the
Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id
that is unique on screen. Older fields still on `TextEdit` move over as they are touched.
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-<name>`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`<scratch>/<agent-name>/`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone).
- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media.
- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
## Testing & performance (do this often)
- Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`,
`apps/lightcraft-cli/tests/`). New features need at least one test that would fail without them.
- **Run the app after every user-visible change**: launch with `--control 7980`, drive it with a JSON-lines script
(`docs/showcase/run.py file.jsonl`), take `ui.screenshot`, and look at it. Check `ui.inspect` → `perf`.
- **Benchmarks:** `cargo xtask bench` (24 MP raw from corpus; CPU and GPU columns) appends to `target/bench/history.jsonl`
and flags CPU-time regressions > 20 % vs the previous run (`--strict` to fail). Run it before and after perf work.
- **Measure, don't guess**: `LIGHTCRAFT_PROFILE=1` prints per-stage pipeline timings to stderr; time CLI renders
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
## Map of the code
`geom`, `color`, `raster`, `tiff` (L0) → `raw`, `codecs`, `meta`, `develop` (L1) → `pipeline` → `catalog` → `engine`
→ `ui-egui`, `mcp` (L5) → apps `lightcraft` (desktop), `lightcraft-cli` (render/commands/MCP). `scenes` generates demo
photos. `xtask` = tooling (`ci`, `layers`, `assets`, `parity`, `wasm`, `corpus`, `stats`); `testkit` = test helpers
(dev-dependency only). `flake.nix` +
`nix/package.nix` = the Nix package (`nix build` builds both binaries with the craft-fonts input, installs the
desktop file/icons/AppStream metadata and runs `cargo test --workspace`; `nix develop` = dev shell). Community-maintained; CI only
evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the workspace; see README → Quick start.
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
@AGENTS.md
Generated
+140 -59
View File
@@ -1181,20 +1181,28 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f3b62ec61f45534392376492fc5ad33047375205#f3b62ec61f45534392376492fc5ad33047375205"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1217,7 +1225,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1238,7 +1246,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116"
source = "git+https://github.com/storytold/craft-libs?rev=a231e517c3b371e1bf0ee8af71ed807424a9a05d#a231e517c3b371e1bf0ee8af71ed807424a9a05d"
dependencies = [
"chrono",
"dunce",
@@ -1264,7 +1272,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1680,6 +1688,19 @@ dependencies = [
"winit",
]
[[package]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"egui",
"enum-map",
"itertools 0.15.0",
"log",
"profiling",
]
[[package]]
name = "egui_glow"
version = "0.37.0"
@@ -1766,6 +1787,26 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "enum-map"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06"
dependencies = [
"enum-map-derive",
]
[[package]]
name = "enum-map-derive"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "enumflags2"
version = "0.7.12"
@@ -1871,7 +1912,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2098,6 +2139,16 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "fs4"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5"
dependencies = [
"rustix 1.1.5",
"windows-sys 0.61.2",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -3536,7 +3587,7 @@ dependencies = [
[[package]]
name = "lightcraft"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"chrono",
"craft-update",
@@ -3548,12 +3599,14 @@ dependencies = [
"lightcraft-sysmem",
"lightcraft-testkit",
"lightcraft-ui-egui",
"lightcraft-wincolor",
"log",
"muda",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"pollster 1.0.1",
"raw-window-handle",
"rfd",
"serde_json",
"winit",
@@ -3563,10 +3616,11 @@ dependencies = [
[[package]]
name = "lightcraft-catalog"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"chrono",
"crc32fast",
"dhat",
"lightcraft-develop",
"lightcraft-geom",
"lightcraft-meta",
@@ -3583,7 +3637,7 @@ dependencies = [
[[package]]
name = "lightcraft-cli"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"dhat",
"lightcraft-codecs",
@@ -3593,13 +3647,14 @@ dependencies = [
"lightcraft-merge",
"lightcraft-raster",
"lightcraft-sysmem",
"lightcraft-testkit",
"lightcraft-ui-egui",
"serde_json",
]
[[package]]
name = "lightcraft-codecs"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"avif-serialize",
"bytemuck",
@@ -3630,7 +3685,7 @@ dependencies = [
[[package]]
name = "lightcraft-color"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"lightcraft-geom",
"proptest",
@@ -3639,7 +3694,7 @@ dependencies = [
[[package]]
name = "lightcraft-denoise"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"faer-core",
"lightcraft-denoise-core",
@@ -3656,7 +3711,7 @@ dependencies = [
[[package]]
name = "lightcraft-denoise-core"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"dhat",
"lightcraft-raster",
@@ -3672,7 +3727,7 @@ dependencies = [
[[package]]
name = "lightcraft-develop"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"lightcraft-color",
"lightcraft-geom",
@@ -3684,11 +3739,12 @@ dependencies = [
[[package]]
name = "lightcraft-engine"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"ab_glyph",
"chrono",
"craft-docpath",
"fs4",
"harfrust 0.13.3",
"jxl-oxide",
"libc",
@@ -3722,13 +3778,14 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"unicode-normalization",
"unicode-segmentation",
"web-time",
]
[[package]]
name = "lightcraft-faces"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"lightcraft-testkit",
"matrixmultiply",
@@ -3743,7 +3800,7 @@ dependencies = [
[[package]]
name = "lightcraft-fetch"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"log",
"rustls",
@@ -3752,9 +3809,16 @@ dependencies = [
"webpki-roots",
]
[[package]]
name = "lightcraft-film"
version = "0.18.0"
dependencies = [
"libm",
]
[[package]]
name = "lightcraft-geocode"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"miniz_oxide 0.9.1",
"serde",
@@ -3762,7 +3826,7 @@ dependencies = [
[[package]]
name = "lightcraft-geom"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"proptest",
"serde",
@@ -3770,7 +3834,7 @@ dependencies = [
[[package]]
name = "lightcraft-gpu"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"bytemuck",
"lightcraft-color",
@@ -3790,7 +3854,7 @@ dependencies = [
[[package]]
name = "lightcraft-heif"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"heic-rs",
"rayon",
@@ -3798,14 +3862,14 @@ dependencies = [
[[package]]
name = "lightcraft-inpaint"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"rayon",
]
[[package]]
name = "lightcraft-lensdb"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"lightcraft-develop",
"lightcraft-geom",
@@ -3814,7 +3878,7 @@ dependencies = [
[[package]]
name = "lightcraft-mcp"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"lightcraft-codecs",
"lightcraft-engine",
@@ -3825,7 +3889,7 @@ dependencies = [
[[package]]
name = "lightcraft-merge"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"lightcraft-codecs",
"lightcraft-color",
@@ -3841,10 +3905,11 @@ dependencies = [
[[package]]
name = "lightcraft-meta"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"chrono",
"lightcraft-geom",
"lightcraft-heif",
"lightcraft-tiff",
"proptest",
"quick-xml 0.41.0",
@@ -3854,7 +3919,7 @@ dependencies = [
[[package]]
name = "lightcraft-pipeline"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"dhat",
"image",
@@ -3873,7 +3938,7 @@ dependencies = [
[[package]]
name = "lightcraft-preview"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"jpeg-encoder",
"lightcraft-raster",
@@ -3885,7 +3950,7 @@ dependencies = [
[[package]]
name = "lightcraft-raster"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"libc",
"lightcraft-color",
@@ -3897,8 +3962,10 @@ dependencies = [
[[package]]
name = "lightcraft-raw"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"chrono",
"craft-crw",
"dhat",
"jpeg-encoder",
"jxl-oxide",
@@ -3921,7 +3988,7 @@ dependencies = [
[[package]]
name = "lightcraft-scenes"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"image",
"lightcraft-color",
@@ -3932,7 +3999,7 @@ dependencies = [
[[package]]
name = "lightcraft-segment"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"candle-core",
"candle-nn",
@@ -3946,7 +4013,7 @@ dependencies = [
[[package]]
name = "lightcraft-slideshow"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"lightcraft-raster",
"serde",
@@ -3955,15 +4022,15 @@ dependencies = [
[[package]]
name = "lightcraft-sysmem"
version = "0.15.0"
version = "0.18.0"
[[package]]
name = "lightcraft-testkit"
version = "0.15.0"
version = "0.18.0"
[[package]]
name = "lightcraft-tiff"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"proptest",
"serde",
@@ -3972,12 +4039,13 @@ dependencies = [
[[package]]
name = "lightcraft-ui-egui"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"craft-ui",
"craft-update",
"craft-window",
"egui",
"egui_extras",
"egui_kittest",
"lightcraft-catalog",
"lightcraft-codecs",
@@ -3995,6 +4063,7 @@ dependencies = [
"lightcraft-slideshow",
"lightcraft-testkit",
"log",
"pollster 1.0.1",
"serde",
"serde_json",
"toml",
@@ -4003,16 +4072,18 @@ dependencies = [
[[package]]
name = "lightcraft-web"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"crc32fast",
"eframe",
"egui",
"js-sys",
"lightcraft-codecs",
"lightcraft-color",
"lightcraft-engine",
"lightcraft-preview",
"lightcraft-raster",
"lightcraft-raw",
"lightcraft-ui-egui",
"log",
"serde",
@@ -4022,6 +4093,14 @@ dependencies = [
"web-sys",
]
[[package]]
name = "lightcraft-wincolor"
version = "0.18.0"
dependencies = [
"lightcraft-testkit",
"windows-sys 0.61.2",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
@@ -4884,7 +4963,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5843,7 +5922,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5900,7 +5979,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6479,10 +6558,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6595,6 +6674,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokio"
version = "1.53.1"
@@ -6801,6 +6886,15 @@ version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-properties"
version = "0.1.4"
@@ -7405,7 +7499,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -7820,7 +7914,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.15.0"
version = "0.18.0"
dependencies = [
"brotli",
"flate2",
@@ -8111,7 +8205,6 @@ dependencies = [
"nix",
"typed-path 0.13.0",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
@@ -8126,18 +8219,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.5.3"
+13 -5
View File
@@ -3,24 +3,27 @@ resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.15.0"
version = "0.18.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/lightcraft"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
# Canon CRW decoder shared with the other Craft apps
craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
# internal
lightcraft-denoise-core = { path = "crates/denoise-core" }
lightcraft-denoise = { path = "crates/denoise", default-features = false }
lightcraft-geom = { path = "crates/geom" }
lightcraft-faces = { path = "crates/faces" }
lightcraft-sysmem = { path = "crates/sysmem" }
lightcraft-wincolor = { path = "crates/wincolor" }
lightcraft-color = { path = "crates/color" }
lightcraft-raster = { path = "crates/raster" }
lightcraft-tiff = { path = "crates/tiff" }
@@ -28,6 +31,7 @@ lightcraft-raw = { path = "crates/raw" }
lightcraft-codecs = { path = "crates/codecs" }
lightcraft-meta = { path = "crates/meta" }
lightcraft-develop = { path = "crates/develop" }
lightcraft-film = { path = "crates/film" }
lightcraft-lensdb = { path = "crates/lensdb" }
lightcraft-inpaint = { path = "crates/inpaint" }
lightcraft-scenes = { path = "crates/scenes" }
@@ -55,11 +59,14 @@ log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
rayon = "1"
# free/total space of a drive (engine's low-disk alert); MIT OR Apache-2.0, pure Rust (rustix / windows-sys)
fs4 = { version = "1.1", default-features = false }
winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows
proptest = "1"
bytemuck = { version = "1", features = ["derive"] }
crc32fast = "1"
siphasher = "1"
libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results)
libc = "0.2" # dev-only: process CPU time in benches
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
@@ -189,6 +196,7 @@ egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7996815719
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+54 -6
View File
@@ -259,7 +259,8 @@ lightcraft --control 7980 ~/Pictures/trip
- **Command registry.** `engine.commands` lists the available commands; `develop.controls` lists every slider's
range, default and current value.
- **MCP server.** `lightcraft-cli mcp` exposes the command registry to Claude (or any MCP client), alongside
helpers for import, query, develop, mask, render (returned as an image) and export. It runs headless, or attached
helpers for import, query, develop, render (returned as an image) and export. Masks have no helper of their own:
create and edit them through `run_command` (e.g. `mask.add`). It runs headless, or attached
to the running app with screenshots, clicks and gestures. See [docs/mcp.md](docs/mcp.md).
```sh
@@ -348,8 +349,8 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
casual use.** It's great for JPEG/DNG and most Sony / Panasonic /
Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera.
- **The biggest gaps:**
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix;
- **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 and CRW raws have guarded estimates from their camera JPEGs, with built-in Canon EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration covers one model so far (chart-measured matrices for the Canon EOS D60), and other raws or rejected fits retain a neutral matrix;
- **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF now decodes sensor data on 58 more bodies (2 verified) ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
- **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an
optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and
linear-RGB denoise and Super Resolution remain missing; see [AI masks](docs/ai-masks.md) and [AI Denoise](docs/denoise.md);
@@ -369,7 +370,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
| Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ |
| Camera colour: DNG matrices, guarded camera-JPEG look fits and built-in profiles for selected cameras | 🚧 measured calibration and per-model coverage remain incomplete ([raw parity](docs/raw-parity.md)) |
| Native macOS menu bar (generated from the command registry), control channel + every widget addressable, headless UI snapshots | ✅ |
| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed ORF / SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) |
| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp, compressed), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) |
| Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights; [setup](docs/denoise.md)), Super Resolution ⬜ |
| Remove / Heal / Clone spots (auto source), non-generative Fill, editable spot pins, Visualize Spots, Red Eye and Pet Eye | ✅ · Fill uses PatchMatch; no generative fill |
| Export: JPEG / PNG / TIFF / flat PSD / WebP / AVIF / JPEG XL / raw or rendered DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ |
@@ -451,6 +452,36 @@ information combined with LTO and one codegen unit on low-memory builders. A PKG
its own profile settings can override inherited variables; adjust the packaging recipe locally or
contact its maintainer rather than assuming an environment prefix on `makepkg` will take precedence.
**Linux/Arch build troubleshooting: rustc SIGILL with ThinLTO.**
In [#2811](https://github.com/storytold/lightcraft/issues/2811), an Arch Linux x86_64 build on an
AMD Ryzen 9 7900X3D with 64 GB RAM failed with rustc 1.99.0 / LLVM 23.1.1, AUR `lightcraft`
`0.7.1-1` and `0.13.0-1`, `RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`, and release settings
`opt-level=3`, `lto=thin`, `codegen-units=1`. `cargo build --frozen --release` reached the executable
crates before rustc crashed with signal 4 (`SIGILL` / `ILL_ILLOPN`). The core dumps point into LLVM's
SelectionDAG / vector-combine optimization path; the exact compiler root cause has not been isolated.
This does not mean every machine with that hardware or toolchain will fail. It is a different observed
failure from the 16 GB OOM kills in [#1196](https://github.com/storytold/lightcraft/issues/1196) above;
there is no evidence establishing a shared root cause.
For a direct Cargo source build, the equivalent command-local LTO override is:
```sh
CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release
```
Reporter @rwarmstr verified the workaround by exporting `CARGO_PROFILE_RELEASE_LTO=off` **inside the
AUR PKGBUILD's `_srcenv()` function** and rebuilding both package versions, without changing
`RUSTFLAGS`. The reporter tested the AUR recipe, not the direct Cargo invocation above.
A variable prefixed to `makepkg` alone may be overwritten by the PKGBUILD's own exports; the recipe
must honor or set the override. The AUR `!lto` opt-out behavior is tracked separately in
[#2813](https://github.com/storytold/lightcraft/issues/2813).
[Cargo's LTO documentation](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) distinguishes
`false` from `off`: `false` can still perform thin local LTO across codegen units (unless
`codegen-units=1` or `opt-level=0`); `off` disables LTO explicitly. The low-memory recipe above is
unchanged. This workaround is for affected builds, not a new default; disabling LTO may change
performance, binary size and build behavior.
Tests that need a GPU, the corpus, the craft-fonts faces or a model pass without checking anything when
those are missing (libtest has no "skipped" status), so `cargo xtask ci` lists them: tests record a skip
with `lightcraft_testkit::skip!`, and the run ends with what the machine offered (OS, CPUs, RAM, GPU
@@ -466,7 +497,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft
```
Without it LightCraft builds and runs the same, but Chinese and Japanese text have no glyphs. Fonts are never committed to this
repo — the standard for what goes there lives with it: see the [craft-fonts README](https://github.com/storytold/craft-fonts#readme).
repo — what goes there is described in the [craft-fonts README](https://github.com/storytold/craft-fonts#readme).
**Interface language:** **Edit → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Polski, Čeština, Italiano, ქართული, Svenska, Suomi, Bahasa Indonesia, Tiếng Việt) or **Settings → General →
Language**; the choice applies immediately and persists. See [docs/localization.md](docs/localization.md).
@@ -570,6 +601,14 @@ option to start it. For unattended installs: `msiexec /i lightcraft-<ver>-window
A silent install is per-user by default. `INSTALLFOLDER` chooses the folder, not who it is installed for;
add `ALLUSERS=1`, from an elevated terminal or deployment tool, for an all-users install.
**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
(an update then ends with error 1603). Download the release MSI of the version and build you have installed from
[all releases](https://github.com/storytold/lightcraft/releases) and run
`msiexec /fv "<path to that .msi>" /qb+ /norestart`, approving the permission prompt if Windows shows one. That restores
the cached copy; then retry the update or uninstall. Opening the MSI, or choosing Repair or Uninstall on it, may still
fail. Error 1603 has other causes too; if this doesn't help, open an issue with the error message.
### macOS
| Build | File | Notes |
@@ -617,10 +656,19 @@ stand on its own.
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | **Photo library and raw development · you are here** | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
+30 -2
View File
@@ -241,7 +241,7 @@ lightcraft --control 7980 ~/Pictures/trip
- **命令注册表。** `engine.commands` 列出可用命令;`develop.controls` 列出每个滑块的范围、
默认值和当前值。
- **MCP 服务器。** `lightcraft-cli mcp` 把命令注册表开放给 Claude(或任何 MCP 客户端),
同时提供导入、查询、显影、蒙版、渲染(以图像返回)和导出的辅助工具。它既能无界面运行,也能附着
同时提供导入、查询、显影、渲染(以图像返回)和导出的辅助工具。蒙版没有专门的辅助工具,请通过 `run_command` 使用(例如 `mask.add`)。它既能无界面运行,也能附着
到正在运行的应用上,支持截图、点击和手势。见 [docs/mcp.md](docs/mcp.md)。
```sh
@@ -384,6 +384,34 @@ CARGO_BUILD_JOBS=1 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_LTO=false
设置可以覆盖继承的环境变量;应在本地调整打包配方或联系维护者,而不要假定给
`makepkg` 添加环境变量前缀就能优先生效。
**Linux/Arch 构建故障:rustc 在 ThinLTO 阶段发生 SIGILL。**
在 [#2811](https://github.com/storytold/lightcraft/issues/2811) 中,报告者的 Arch Linux x86_64
机器配备 AMD Ryzen 9 7900X3D 和 64 GB RAM,使用 rustc 1.99.0 / LLVM 23.1.1、AUR
`lightcraft` `0.7.1-1` 和 `0.13.0-1`、`RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`,
以及 release 设置 `opt-level=3`、`lto=thin`、`codegen-units=1`。
`cargo build --frozen --release` 在编译到可执行 crate 时,rustc 因 signal 4
(`SIGILL` / `ILL_ILLOPN`)崩溃。core dump 指向 LLVM 的 SelectionDAG / vector-combine
优化路径;编译器的具体根因尚未确定。这不表示所有使用这些硬件或工具链的机器都会失败。
此故障与上文 [#1196](https://github.com/storytold/lightcraft/issues/1196) 中 16 GB 机器上的
OOM 终止表现不同,没有证据表明两者根因相同。
直接使用 Cargo 从源码构建时,等价的单条命令 LTO 覆盖方式是:
```sh
CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release
```
报告者 @rwarmstr 验证成功的是:在 **AUR PKGBUILD 的 `_srcenv()` 函数内部**导出
`CARGO_PROFILE_RELEASE_LTO=off` 后重新构建上述两个版本,无需更改 `RUSTFLAGS`。
报告者测试的是 AUR 配方,并未单独验证上面的直接 Cargo 命令。仅在 `makepkg` 前添加变量,
可能会被 PKGBUILD 自己的 export 覆盖;打包配方必须保留或设置该覆盖值。
AUR 的 `!lto` 选项行为由 [#2813](https://github.com/storytold/lightcraft/issues/2813) 单独跟踪。
[Cargo 的 LTO 文档](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) 区分了 `false`
和 `off`:`false` 仍可能在代码生成单元之间执行 thin local LTO(除非 `codegen-units=1`
或 `opt-level=0`);`off` 则明确禁用 LTO。上文的低内存配方保持不变。
此绕过方法仅针对受影响的构建,不是新的默认建议;禁用 LTO 可能改变性能、二进制大小和构建行为。
**中文和日文文字**需要共享字体仓库,这是一个可选的构建输入(所有正式发布版都会包含它):
```sh
@@ -392,7 +420,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft
```
不指定它时,LightCraft 构建和运行的方式完全相同,只是中文和日文文字没有字形。字体从不提交到
本仓库;见 [craftrules `standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)。
本仓库。
**界面语言:** **编辑 → 语言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français)或 **设置 → 一般 →
语言**;选择立即生效并会保留。见 [docs/localization.md](docs/localization.md)。
+29 -1
View File
@@ -240,7 +240,7 @@ lightcraft --control 7980 ~/Pictures/trip
- **指令註冊表。** `engine.commands` 列出可用的指令;`develop.controls` 列出每個滑桿的範圍、
預設值與目前值。
- **MCP 伺服器。** `lightcraft-cli mcp` 把指令註冊表開放給 Claude(或任何 MCP 用戶端),
同時提供匯入、查詢、顯影、遮色片、算繪(以影像回傳)與匯出的輔助工具。它可以無介面執行,也可以附掛
同時提供匯入、查詢、顯影、算繪(以影像回傳)與匯出的輔助工具。遮色片沒有專屬的輔助工具,請透過 `run_command` 使用(例如 `mask.add`)。它可以無介面執行,也可以附掛
到正在執行的應用程式上,支援截圖、點擊與手勢。詳見 [docs/mcp.md](docs/mcp.md)。
```sh
@@ -402,6 +402,34 @@ CARGO_BUILD_JOBS=1 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_LTO=false
PKGBUILD 可能會覆寫繼承的環境變數;請在本機調整打包腳本或聯絡維護者,而不要假設替
`makepkg` 加上環境變數前綴就能優先生效。
**Linux/Arch 建置故障:rustc 在 ThinLTO 階段發生 SIGILL。**
在 [#2811](https://github.com/storytold/lightcraft/issues/2811) 中,回報者的 Arch Linux x86_64
機器配備 AMD Ryzen 9 7900X3D 與 64 GB RAM,使用 rustc 1.99.0 / LLVM 23.1.1、AUR
`lightcraft` `0.7.1-1` 與 `0.13.0-1`、`RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`,
以及 release 設定 `opt-level=3`、`lto=thin`、`codegen-units=1`。
`cargo build --frozen --release` 在編譯到可執行 crate 時,rustc 因 signal 4
(`SIGILL` / `ILL_ILLOPN`)當機。core dump 指向 LLVM 的 SelectionDAG / vector-combine
最佳化路徑;編譯器的具體根因尚未確定。這不表示所有使用這些硬體或工具鏈的機器都會失敗。
此故障與上文 [#1196](https://github.com/storytold/lightcraft/issues/1196) 中 16 GB 機器上的
OOM 終止表現不同,沒有證據顯示兩者根因相同。
直接使用 Cargo 從原始碼建置時,等價的單條指令 LTO 覆寫方式是:
```sh
CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release
```
回報者 @rwarmstr 驗證成功的是:在 **AUR PKGBUILD 的 `_srcenv()` 函式內部**匯出
`CARGO_PROFILE_RELEASE_LTO=off` 後重新建置上述兩個版本,無須變更 `RUSTFLAGS`。
回報者測試的是 AUR 腳本,並未單獨驗證上面的直接 Cargo 指令。僅在 `makepkg` 前加上變數,
可能會被 PKGBUILD 自己的 export 覆寫;打包腳本必須保留或設定該覆寫值。
AUR 的 `!lto` 選項行為由 [#2813](https://github.com/storytold/lightcraft/issues/2813) 另行追蹤。
[Cargo 的 LTO 文件](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) 區分了 `false`
與 `off`:`false` 仍可能在程式碼產生單元之間執行 thin local LTO(除非 `codegen-units=1`
或 `opt-level=0`);`off` 則明確停用 LTO。上文的低記憶體建置配方維持不變。
此繞過方法僅適用於受影響的建置,不是新的預設建議;停用 LTO 可能改變效能、二進位檔大小與建置行為。
測試在缺少 GPU、語料庫、craft-fonts 字型或模型時會直接通過而不檢查任何內容(libtest 沒有「已跳過」
這個狀態),所以 `cargo xtask ci` 會把它們列出來:測試會用 `lightcraft_testkit::skip!` 記錄跳過原因,
執行結束時會列出機器提供的環境(作業系統、CPU、記憶體、每個後端的 GPU 配接器、語料庫、字型)以及每一項
+27 -18
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~14 points and ~340–600 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
> **Last reviewed:** 2026-10-10 · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 · **Changes:** [revision history](#revision-history)
One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work
from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in
@@ -14,25 +14,25 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are
|---|---:|---|
| **Feature breadth** (checklist) | **81.6%** of 532 rows (P0 98.0%, P1 95.2%, P2 50.0%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount |
| **Feature breadth** (weighted by use) | **~77%** | estimated |
| **Ready for real work** (full target) | **~61%** (56–66%) | estimated: weighted sum over the dimensions |
| **Ready for real work** (full target) | **~62%** (57–67%) | estimated: weighted sum over the dimensions |
| **Mainstream practitioner** | **~51%** (46–56%) | estimated |
| **Essentials user** | **~65%** (60–70%) | estimated |
| Remaining to **beta** | **~340–600 h** (Opus 5.5 agent hours, ~60% parallel) | estimated |
| Remaining to **full parity** | **~1,000–1,800 h** (~70% parallel) | estimated |
| Remaining to **full parity** | **~980–1,750 h** (~70% parallel) | estimated |
Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%):
| Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates |
|---|---:|---:|---|
| Full target (ready for real work) | **~61%** | **1,000–1,800 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
| Mainstream practitioner | **~51%** | **450–840 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
| Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
| Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send |
The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), compressed ORF and HE NEF
open as previews, rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
tests run in CI on FreeBSD only. **Why alpha:** core workflows run end to end, but readiness is below
the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have blocking gaps (compressed ORF and HE NEF open as previews; Canon,
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens
as preview (compressed ORF now decodes on 58 more bodies (2 verified)), rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below
the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have gaps (Nikon HE NEF opens as preview; Canon,
~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows
(import, cull, develop, save and reopen, batch looks, export) work end to end on macOS
([docs/roadmap.md](docs/roadmap.md#alpha-gate)). The three readiness numbers and their weights and discounts are in
@@ -45,7 +45,7 @@ Hours are calibrated on this repo's PR history; see
| Dimension | Ready | Breadth | Remaining | Doc |
|---|---:|---:|---:|---|
| Features | ~61% | ~77% (checklist 81.1%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) |
| ↳ RAW cameras, colour, lens profiles | ~60% | 83% of 1,446 Adobe models decode, 38% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
| ↳ RAW cameras, colour, lens profiles | ~60% | 85% of 1,446 Adobe models decode, 39% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
| UI/UX fidelity | ~70% | ~85% | 32–54 h | [ui-parity](docs/ui-parity.md) |
| File formats (non-raw) | ~70% | ~85% | 30–55 h | [file-format-parity](docs/file-format-parity.md) |
| Hardware | ~40% | ~50% | 40–80 h | [hardware-parity](docs/hardware-parity.md) |
@@ -107,18 +107,25 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
3. Render-fidelity suite against Lightroom, then tuning (30–60 h)
4. ~~Full-resolution zoom~~ (done 2026-10-12)
5. AI masks: Subject / Sky / People (40–70 h + model decision)
6. Compressed ORF and HE NEF (28–55 h)
7. Lens profile database of our own (40–80 h)
8. Tests in CI on macOS, Windows and Linux (6–12 h)
6. ~~Compressed ORF~~ (done 2026-11-04) and HE NEF (20–40 h)
7. Lens profile database of our own (40–80 h, #329)
8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h)
9. Per-model raw verification (20–35 h)
## Progress log
- 2026-11-04: Olympus / OM System compressed ORF decodes from sensor data: clean-room pure-Rust bitstream decoder (`crates/raw/src/vendor/orfc.rs`) derived strictly from Olympus patents US7333035B2/US7715639B2, maker notes and CC0 samples without third-party decoder code (see `docs/orf-compression.md`), verified on OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) CC0 samples; 58 bodies newly unlocked (78 total across Olympus and OM; OM/Olympus 6% → 81% fully working, overall weighted camera coverage 94% → 97%).
- 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判
(89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200),
六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog
and `print.set` take their customary names, and names are matched case-, space- and
punctuation-insensitively (`L判`, `l`, `L-size` are one paper).
- 2026-10-13: Canon CRW (the 2000–2004 CIFF bodies) decodes from sensor data: compression
derived clean-room against a black-box reference and frozen (`craft-libs crates/crw/clean-room/02-crw-format.md`);
EOS D30/D60/10D/300D and PowerShot G1/G6 verified pixel-exact on 28 of 29 corpus files (18 of
them the maintainer's D60 shots); as-shot white balance, black level, rotation and capture time
from the CIFF records; the PowerShot G5's anomalous coding stays preview-only. With the
camera-coverage sweep and MRW merged, 557 models verified; Canon bucket 95% → 98%.
- 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor
hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking
identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277.
@@ -150,10 +157,9 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
- 2026-10-10 (RAW): RAW measured model by model against Adobe's 1,446-model list (234 verified, 943
unverified, 233 preview-only, 36 unsupported; ~84% of photographers' cameras decode, ~40% on a
verified body). Full ~61%, mainstream ~49%, essentials ~64%; beta ~14 points away.
- 2026-10-10 (final): full ready is a weighted sum over the dimensions (~59%; method aligned with
the standard); mainstream practitioner ~51% (450–840 h), essentials user ~63% (160–300 h);
- 2026-10-10 (final): full ready is a weighted sum over the dimensions (~59%; no new evidence); mainstream practitioner ~51% (450–840 h), essentials user ~63% (160–300 h);
alpha gate passes.
- 2026-10-10: full re-measure for the progress-docs standard: stage alpha, ready ~55%, checklist
- 2026-10-10: full re-measure, progress docs restructured: stage alpha, ready ~55%, checklist
81.1%; new docs (target-app-parity, gaps, roadmap, architecture, raw / file-format / hardware / UI
/ localization parity); `docs/parity.md` renamed `docs/parity-checklist.md`. Landed today: Nikon
lossy-after-split NEF (#633), ORF 12.8 bpp (#651), HDR gain map JPEG / PQ AVIF / float TIFF export
@@ -191,8 +197,11 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| Date | Change | Summary |
|---|---|---|
| 2026-10-24 | minor | Priority 7 (lens profile database) links its tracking issue #329; headline numbers unchanged |
| 2026-10-24 | patch | Alpha rationale: tests run in CI on Linux x64 (#2667) and FreeBSD nightly, not on macOS or Windows; ranked item 8 now reads "Tests in CI on macOS and Windows, and the GPU tests in CI"; percentages and hours unchanged |
| 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged |
| 2026-10-19 | minor | Indonesian interface (`id`): every plain and formats message, plus 69 command labels, locale, menu command and tests; What's New left in English; Localization ~55% → ~64% (mean of the 12 key languages), 8 of 12 present |
| 2026-10-13 | minor | Canon CRW decoded (clean-room): 6 bodies verified pixel-exact, G5 preview; 551 models verified after merging the coverage sweep |
| 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged |
| 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged |
| 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled |
@@ -212,10 +221,10 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| 2026-10-12 | minor | 117 Nikon and Fujifilm bodies verified (354 models, 24%); headline numbers unchanged |
| 2026-10-11 | minor | EOS R5 Mark II CR3 verified: CR3 on four verified bodies, RAW decoding 76% → 77%; headline numbers unchanged |
| 2026-10-10 | minor | RAW measured model by model; RAW decode and colour as explicit rows: full 59% → 61%, mainstream 51% → 49%, essentials 63% → 64%; beta ~14 points |
| 2026-10-10 | minor | Full ready restored to the additive weighted sum (~59%; method aligned with the standard, no new evidence); hours per audience; beta ~16 points away |
| 2026-10-10 | minor | Full ready restored to the additive weighted sum (~59%; no new evidence); hours per audience; beta ~16 points away |
| 2026-10-10 | minor | Mainstream practitioner and essentials user numbers; full ready 55% → 46% (method written down); beta 340–600 h |
| 2026-10-10 | minor | Alpha gate added (core-workflow check): passes, stays alpha |
| 2026-10-10 | major | Restructured to the progress-docs standard; re-measured; *Where we stand*, *Parity estimate* and *Totals* moved to docs/target-app-parity.md, milestones and risks to docs/roadmap.md, raw coverage to docs/raw-parity.md, catalog migration to docs/file-format-parity.md, CJK notes to docs/localization-parity.md |
| 2026-10-10 | major | Progress docs restructured; re-measured; *Where we stand*, *Parity estimate* and *Totals* moved to docs/target-app-parity.md, milestones and risks to docs/roadmap.md, raw coverage to docs/raw-parity.md, catalog migration to docs/file-format-parity.md, CJK notes to docs/localization-parity.md |
| 2026-10-08 | minor | *Where we stand* by dimension and by kind of user |
| 2026-10-02 | major | Parity estimate and effort table |
| 2026-09-30 | major | Created |
+3
View File
@@ -25,6 +25,9 @@ lightcraft-merge = { workspace = true }
serde_json = { workspace = true }
dhat = { workspace = true, optional = true }
[dev-dependencies]
lightcraft-testkit = { workspace = true }
[features]
default = ["denoise"]
denoise = ["lightcraft-engine/denoise"]
+585
View File
@@ -0,0 +1,585 @@
//! `lightcraft-cli bench-cull FOLDER`: time what culling a shoot costs, headless, on real files.
//!
//! What a wedding photographer does most is open a folder of a few thousand raws, look at each
//! one, rate it and move on. This times the engine side of each step on the files themselves (the
//! desktop app's own frame timings come from `ui.inspect` → `perf.loupeSteps`, see
//! `tools/cull-bench.py`):
//!
//! - browse: reading the folder into the Local view (`library.browse`, the whole folder);
//! - grid thumbnails: the camera JPEG at 512 px for the first screen, on as many threads as the
//! app renders with;
//! - camera preview at loupe sizes (1280, 2560) and at full size (the 100 % view), one at a time;
//! - LightCraft's render of the loupe (2560 px) from a cold source;
//! - rating: `photo.rate` on many photos in a row, journal included;
//! - import: adding N files in place to a fresh library, and copying M of them into it (`--n 0`:
//! no import).
//!
//! `--files K` reads only the first K files (by name) of the folder, as browsing reads them: a
//! sample of a folder on a network share, where reading thousands of raws takes hours.
//!
//! Each number is printed as `name: X ms wall` (median, with p95 and n), the format
//! `cargo xtask bench` parses, and the lot as one JSON object with `--json FILE`. Nothing is
//! written next to the photos: every library is made in a new folder of the run's own under
//! `--work` (default: a folder in the system temp directory; nothing already there is deleted),
//! XMP auto-write stays off, and the source folder is only read.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
use lightcraft_engine::Session;
use lightcraft_engine::catalog::PhotoId;
use serde_json::{Value, json};
const USAGE: &str = "lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]";
/// Threads the app renders thumbnails with (`Renderer::default`: cores − 1, at most 6).
fn render_threads() -> usize {
std::thread::available_parallelism().map(|n| n.get().saturating_sub(1)).unwrap_or(2).clamp(2, 6)
}
/// Median, p95 and count of `ms` (milliseconds).
fn stats(ms: &[f64]) -> Value {
if ms.is_empty() {
return Value::Null;
}
let mut v = ms.to_vec();
v.sort_by(f64::total_cmp);
let at = |q: f64| v.get(((v.len() - 1) as f64 * q).round() as usize).copied().unwrap_or(0.0);
json!({"p50": round(at(0.5)), "p95": round(at(0.95)), "max": round(at(1.0)), "n": v.len()})
}
fn round(x: f64) -> f64 {
(x * 10.0).round() / 10.0
}
fn ms_since(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}
/// Print one result line the way `xtask bench` parses it (`name: X ms wall`).
fn line(name: &str, s: &Value) {
if let Some(p50) = s.get("p50").and_then(Value::as_f64) {
println!("{name}: {p50:.1} ms wall (p95 {} ms, n {})", s["p95"], s["n"]);
}
}
/// A new, empty folder `name` in this run's own folder; never deletes anything already there.
fn fresh_dir(root: &Path, name: &str) -> Result<PathBuf, String> {
let d = root.join(name);
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
Ok(d)
}
/// A folder of this run's own under `work`, which must not exist yet: a run never deletes or
/// reuses what is already under `--work`.
fn run_dir(work: &Path) -> Result<PathBuf, String> {
std::fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?;
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
static RUNS: AtomicUsize = AtomicUsize::new(0);
let n = RUNS.fetch_add(1, Ordering::Relaxed);
let d = work.join(format!("bench-cull-run-{}-{stamp}-{n}", std::process::id()));
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
Ok(d)
}
/// `take` items of `v` after the first `skip` (photos the stages before have read, so cold in the
/// file cache), or, when `v` has no more than `skip`, its first `take`: a small folder is measured
/// on photos already read rather than not at all.
fn sample_after<T>(v: &[T], skip: usize, take: usize) -> &[T] {
let from = if v.len() > skip { skip } else { 0 };
let rest = v.get(from..).unwrap_or_default();
rest.get(..take.min(rest.len())).unwrap_or_default()
}
/// Whether `path` names a file in `folder` (the source folder, which a run only reads), checked
/// twice: where its own entry sits (the folder holding it, the final link not followed: writing the
/// results replaces that entry, so a link to a file elsewhere that sits in the source folder, maybe
/// standing for a photo, would be replaced; CodeRabbit on #3080), and where it resolves to: a file
/// that is there by itself (a link to a photo there is the photo), a link that points nowhere yet
/// by where writing through it would create the file, and anything else by its nearest folder that
/// exists (a `--work` folder may not be there yet).
fn inside_source(path: &Path, folder: &Path) -> bool {
let Ok(folder) = std::fs::canonicalize(folder) else { return false };
entry_inside(path, &folder) || resolves_inside(path, &folder, 0)
}
/// Whether the folder holding `path`'s own entry (its nearest folder that exists, resolved) is in
/// `folder` (already resolved). The entry itself is not followed.
fn entry_inside(path: &Path, folder: &Path) -> bool {
let mut p = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
loop {
if let Ok(c) = std::fs::canonicalize(p) {
return c.starts_with(folder);
}
match p.parent() {
Some(up) if !up.as_os_str().is_empty() => p = up,
Some(_) => p = Path::new("."),
None => return false,
}
}
}
/// [`inside_source`] for a `folder` already resolved; `hops`: links followed so far (a loop of
/// links counts as inside: refused).
fn resolves_inside(path: &Path, folder: &Path, hops: u32) -> bool {
if let Ok(c) = std::fs::canonicalize(path) {
return c.starts_with(folder);
}
if let Ok(target) = std::fs::read_link(path) {
if hops >= 40 {
return true;
}
let target = path.parent().map_or_else(|| target.clone(), |dir| dir.join(&target));
return resolves_inside(&target, folder, hops + 1);
}
entry_inside(path, folder)
}
/// Refuse `--json` or `--work` in the folder being measured: nothing is written next to the photos,
/// the results and the run's libraries included. Checked before anything is made.
fn check_outputs(folder: &Path, json: Option<&Path>, work: &Path) -> Result<(), String> {
// a `..` after a folder not made yet can't be resolved now, and the run makes that folder:
// `--json NEW/../FOLDER/r.json` would pass the checks below and land in the source folder
// (CodeRabbit on #3544)
for (name, p) in [("--json", json), ("--work", Some(work))] {
if let Some(p) = p.filter(|p| p.components().any(|c| c == std::path::Component::ParentDir)) {
return Err(format!("{}: {name} must not contain \"..\"; give the folder without it", p.display()));
}
}
if let Some(j) = json.filter(|j| inside_source(j, folder)) {
return Err(format!("{}: --json must not be in the folder being measured", j.display()));
}
if inside_source(&work.join("run"), folder) {
return Err(format!("{}: --work must not be in the folder being measured", work.display()));
}
Ok(())
}
fn library(dir: &Path) -> Result<Session, String> {
let mut s = Session::new().with_fs().with_system_clock();
s.open_library(dir, false).map_err(|e| format!("{}: {e}", dir.display()))?;
// nothing is ever written next to the photos
s.execute("library.xmpPreferences", &json!({"autoWrite": false})).map_err(|e| e.to_string())?;
Ok(s)
}
pub fn run(args: &[String]) -> Result<(), String> {
let mut folder = None;
let mut n = 2000usize;
let mut copy = 200usize;
let mut work = None;
let mut json_out = None;
let mut files = None;
let mut i = 0;
while i < args.len() {
let value = |i: usize| args.get(i + 1).cloned().ok_or_else(|| format!("{} needs a value\n{USAGE}", args[i]));
match args[i].as_str() {
"--n" => {
n = value(i)?.parse().map_err(|_| "--n needs a number".to_string())?;
i += 1;
}
"--copy" => {
copy = value(i)?.parse().map_err(|_| "--copy needs a number".to_string())?;
i += 1;
}
"--files" => {
files = Some(value(i)?.parse::<usize>().map_err(|_| "--files needs a number".to_string())?);
i += 1;
}
"--work" => {
work = Some(PathBuf::from(value(i)?));
i += 1;
}
"--json" => {
json_out = Some(PathBuf::from(value(i)?));
i += 1;
}
"-h" | "--help" => {
println!("{USAGE}");
return Ok(());
}
a if a.starts_with("--") => return Err(format!("unknown option {a}\n{USAGE}")),
// (a second folder would replace the first and be timed in its place: CodeRabbit on #3583)
a if folder.is_some() => return Err(format!("{a}: one FOLDER only\n{USAGE}")),
a => folder = Some(PathBuf::from(a)),
}
i += 1;
}
let folder = folder.ok_or_else(|| USAGE.to_string())?;
if !folder.is_dir() {
return Err(format!("{}: not a folder", folder.display()));
}
let work = work.unwrap_or_else(|| std::env::temp_dir().join(format!("lightcraft-bench-cull-{}", std::process::id())));
check_outputs(&folder, json_out.as_deref(), &work)?;
let work = run_dir(&work)?;
let mut out = json!({"folder": folder.display().to_string(), "threads": render_threads()});
// --- browse: the whole folder into the Local view -------------------------------------------
let mut s = library(&fresh_dir(&work, "lib-browse")?)?;
// `--files K`: only the first K files by name, read as browsing reads them (a sample of a slow
// network folder)
let t = Instant::now();
let (photos, ids): (u64, Vec<PhotoId>) = match files {
None => {
let r = s.execute("library.browse", &json!({"path": folder.display().to_string()})).map_err(|e| e.to_string())?;
(r["photos"].as_u64().unwrap_or(0), s.visible_cloned())
}
Some(k) => {
let mut list: Vec<String> = std::fs::read_dir(&folder)
.map_err(|e| format!("{}: {e}", folder.display()))?
.flatten()
.map(|e| e.path())
.filter(|p| p.is_file() && lightcraft_engine::import::is_supported(p))
.map(|p| p.display().to_string())
.collect();
list.sort();
list.truncate(k);
let r = s.execute("library.import", &json!({"paths": list, "mode": "add", "local": true})).map_err(|e| e.to_string())?;
let ids: Vec<PhotoId> = r["imported"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(PhotoId).collect();
(ids.len() as u64, ids)
}
};
let browse_ms = ms_since(t);
let what = if files.is_some() { "first files" } else { "whole folder" };
println!("browse {photos} photos ({what}): {browse_ms:.1} ms wall");
out["browse"] = json!({"ms": round(browse_ms), "photos": photos, "perPhotoMs": round(browse_ms / photos.max(1) as f64)});
let paths: Vec<String> = ids
.iter()
.filter_map(|id| match &s.catalog.photo(*id)?.source {
lightcraft_engine::catalog::Source::File { path } => Some(path.clone()),
_ => None,
})
.collect();
if paths.is_empty() {
return Err(format!("{}: no photos", folder.display()));
}
let loader = s.media.preview_loader.clone().ok_or("no preview loader")?;
// --- grid thumbnails: the first screen, in parallel ------------------------------------------
let screen: Vec<String> = paths.iter().take(48).cloned().collect();
let next = Arc::new(AtomicUsize::new(0));
let t = Instant::now();
let per: Vec<(f64, f64)> = std::thread::scope(|sc| {
let workers: Vec<_> = (0..render_threads())
.map(|_| {
let (next, loader, screen) = (next.clone(), loader.clone(), &screen);
sc.spawn(move || {
let mut done = Vec::new();
while let Some(p) = screen.get(next.fetch_add(1, Ordering::Relaxed)) {
let a = Instant::now();
let _ = loader(p, 512);
done.push((ms_since(a), ms_since(t)));
}
done
})
})
.collect();
workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect()
});
let first = per.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
let all = per.iter().map(|p| p.1).fold(0.0, f64::max);
let each = stats(&per.iter().map(|p| p.0).collect::<Vec<_>>());
println!("grid: first thumbnail: {first:.1} ms wall");
println!("grid: {} thumbnails: {all:.1} ms wall", per.len());
line("grid: one 512 px thumbnail", &each);
out["thumbs"] = json!({"firstMs": round(first), "allMs": round(all), "count": per.len(), "each": each});
// --- camera previews at loupe sizes, one at a time (what a step costs without look-ahead) -----
let sample = sample_after(&paths, 48, 20);
for edge in [1280usize, 2560, usize::MAX] {
let ms: Vec<f64> = sample
.iter()
.map(|p| {
let a = Instant::now();
let _ = loader(p, edge);
ms_since(a)
})
.collect();
let name = if edge == usize::MAX { "camera preview full size (100 %)".to_string() } else { format!("camera preview {edge} px") };
let st = stats(&ms);
line(&name, &st);
out[if edge == usize::MAX { "cameraFull".to_string() } else { format!("camera{edge}") }] = st;
}
// --- LightCraft's loupe render (2560 px) from a cold source --------------------------------
let ms: Vec<f64> = sample_after(&ids, 80, 5)
.iter()
.filter_map(|id| {
let job = s.loupe_job(*id, 2560, 1708, true)?;
let a = Instant::now();
let r = job.run();
let t = ms_since(a);
r.rendered.is_ok().then_some(t)
})
.collect();
let st = stats(&ms);
line("loupe render 2560 px (cold)", &st);
out["loupeRender"] = st;
// --- rating: a culling pass of keypresses ---------------------------------------------------
let ms: Vec<f64> = ids
.iter()
.take(50)
.enumerate()
.filter_map(|(k, id)| {
// the key acts on the selected photo, as in the loupe
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).ok()?;
let a = Instant::now();
s.execute("photo.rate", &json!({"rating": (k % 5) + 1})).ok()?;
Some(ms_since(a))
})
.collect();
let st = stats(&ms);
line("rate one photo (journal written)", &st);
out["rate"] = st;
drop(s);
// --- import: add in place, then copy ----------------------------------------------------------
if n == 0 {
return finish(out, json_out);
}
let add: Vec<String> = paths.iter().take(n).cloned().collect();
let mut s = library(&fresh_dir(&work, "lib-add")?)?;
let t = Instant::now();
let r = s.execute("library.import", &json!({"paths": add, "mode": "add"})).map_err(|e| e.to_string())?;
let add_ms = ms_since(t);
let added = r["imported"].as_array().map(Vec::len).unwrap_or(0);
println!("import {added} photos in place: {add_ms:.1} ms wall");
out["importAdd"] = json!({"ms": round(add_ms), "photos": added, "perPhotoMs": round(add_ms / added.max(1) as f64)});
drop(s);
if copy > 0 {
let some: Vec<String> = paths.iter().take(copy).cloned().collect();
let lib = fresh_dir(&work, "lib-copy")?;
let mut s = library(&lib)?;
let t = Instant::now();
let r = s
.execute("library.import", &json!({"paths": some, "mode": "copy", "destination": lib.join("Originals").display().to_string()}))
.map_err(|e| e.to_string())?;
let copy_ms = ms_since(t);
let copied = r["imported"].as_array().map(Vec::len).unwrap_or(0);
println!("import {copied} photos by copying: {copy_ms:.1} ms wall");
out["importCopy"] = json!({"ms": round(copy_ms), "photos": copied, "perPhotoMs": round(copy_ms / copied.max(1) as f64)});
drop(s);
let _ = std::fs::remove_dir_all(&lib);
}
finish(out, json_out)
}
fn finish(out: Value, json_out: Option<PathBuf>) -> Result<(), String> {
if let Some(p) = json_out {
write_replacing(&p, serde_json::to_string_pretty(&out).unwrap_or_default().as_bytes())?;
}
println!("{}", serde_json::to_string(&out).unwrap_or_default());
Ok(())
}
/// Write `bytes` to `path` through a new file next to it, renamed over `path`: an existing `path`
/// is replaced as a name, never written into. A hard link there shares its data with another file
/// (maybe a photo in the source folder, which [`inside_source`] can't tell), and writing into it
/// would overwrite that file too (CodeRabbit on #3077). The temporary file is removed on error.
fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), String> {
use std::io::Write;
let err = |e: std::io::Error| format!("{}: {e}", path.display());
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
let name = path.file_name().ok_or_else(|| format!("{}: not a file name", path.display()))?;
static TEMPS: AtomicUsize = AtomicUsize::new(0);
let n = TEMPS.fetch_add(1, Ordering::Relaxed);
let mut tmp_name = std::ffi::OsString::from(".");
tmp_name.push(name);
tmp_name.push(format!(".{}-{n}.tmp", std::process::id()));
let tmp = dir.join(tmp_name);
let written =
std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|()| f.sync_all()));
if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) {
let _ = std::fs::remove_file(&tmp);
return Err(err(e));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_second_folder_is_an_error() {
let e = run(&["a".to_string(), "b".to_string()]).unwrap_err();
assert!(e.starts_with("b: one FOLDER only"), "{e}");
}
/// `--work` may hold anything: a run makes a new folder of its own there and never deletes
/// what is already in it (it used to remove `lib-browse`, `lib-add` and `lib-copy` there).
#[test]
fn a_run_never_deletes_what_is_under_work() {
// a folder this test owns (made new), so the cleanup below removes nothing else
let work = run_dir(&std::env::temp_dir()).unwrap();
let keep = work.join("lib-browse").join("keep.txt");
std::fs::create_dir_all(keep.parent().unwrap()).unwrap();
std::fs::write(&keep, b"mine").unwrap();
let a = run_dir(&work).unwrap();
let b = run_dir(&work).unwrap();
assert_ne!(a, b);
fresh_dir(&a, "lib-browse").unwrap();
assert!(fresh_dir(&a, "lib-browse").is_err(), "an existing folder is never reused");
assert_eq!(std::fs::read(&keep).unwrap(), b"mine");
let _ = std::fs::remove_dir_all(&work);
}
/// A folder too small for the disjoint samples is measured on the photos it has (CodeRabbit on #3077).
#[test]
fn a_small_folder_is_sampled_from_its_start() {
let v: Vec<u32> = (0..100).collect();
assert_eq!(sample_after(&v, 48, 20), &v[48..68]);
assert_eq!(sample_after(&v, 90, 20), &v[90..100]);
assert_eq!(sample_after(&v[..3], 48, 20), &v[..3]);
assert_eq!(sample_after(&v[..48], 48, 5), &v[..5]);
assert!(sample_after::<u32>(&[], 48, 20).is_empty());
}
/// A file link at `at` to `target`.
#[cfg(unix)]
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(target, at)
}
/// A file link at `at` to `target` (Windows: needs Developer Mode or the right to make links).
#[cfg(windows)]
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_file(target, at)
}
#[cfg(not(any(unix, windows)))]
fn link(_: &Path, _: &Path) -> std::io::Result<()> {
Err(std::io::Error::other("no file links here"))
}
/// `--json` naming a link (made elsewhere) to a file in the source folder is refused: writing
/// the results would follow it and overwrite a photo (CodeRabbit on #3080). So is a link that
/// points to a file not made yet in the source folder, and a loop of links.
#[test]
fn a_json_link_into_the_source_folder_is_refused() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let photo = src.join("a.jpg");
std::fs::write(&photo, b"photo").unwrap();
let to_photo = work.join("report.json");
if let Err(e) = link(&photo, &to_photo) {
let _ = std::fs::remove_dir_all(&work);
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
return;
}
assert!(inside_source(&to_photo, &src), "a link to a photo in the source folder");
let e = check_outputs(&src, Some(&to_photo), &work.join("elsewhere")).unwrap_err();
assert!(e.contains("--json"), "{e}");
let to_new = work.join("new.json");
link(&src.join("not-yet.json"), &to_new).unwrap();
assert!(inside_source(&to_new, &src), "a link to a file not made yet in the source folder");
let (x, y) = (work.join("x.json"), work.join("y.json"));
link(&y, &x).unwrap();
link(&x, &y).unwrap();
assert!(inside_source(&x, &src), "a loop of links");
let to_elsewhere = work.join("fine.json");
link(&work.join("out.json"), &to_elsewhere).unwrap();
assert!(!inside_source(&to_elsewhere, &src), "a link to a file outside is fine");
assert_eq!(std::fs::read(&photo).unwrap(), b"photo");
let _ = std::fs::remove_dir_all(&work);
}
/// `--json` naming a link that sits in the source folder and points to a file outside it is
/// refused: writing the results would replace the link itself, an entry of the source folder
/// (CodeRabbit on #3080). The link stays as it was.
#[test]
fn a_json_link_in_the_source_folder_to_a_file_outside_is_refused() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let outside = work.join("out.json");
std::fs::write(&outside, b"outside").unwrap();
let in_src = src.join("a.jpg");
if let Err(e) = link(&outside, &in_src) {
let _ = std::fs::remove_dir_all(&work);
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
return;
}
assert!(inside_source(&in_src, &src), "a link in the source folder, wherever it points");
let e = check_outputs(&src, Some(&in_src), &work.join("elsewhere")).unwrap_err();
assert!(e.contains("--json"), "{e}");
assert!(std::fs::symlink_metadata(&in_src).unwrap().file_type().is_symlink(), "the link stays");
assert_eq!(std::fs::read_link(&in_src).unwrap(), outside);
assert_eq!(std::fs::read(&outside).unwrap(), b"outside");
// a new file in the source folder (nothing there yet) is refused too
assert!(check_outputs(&src, Some(&src.join("new.json")), &work.join("elsewhere")).is_err());
let _ = std::fs::remove_dir_all(&work);
}
/// `--json` naming a hard link (made elsewhere) to a photo in the source folder passes
/// [`inside_source`] (a hard link has no target to resolve), so the results replace the link
/// instead of writing into it: the photo keeps its bytes (CodeRabbit on #3077).
#[test]
fn a_json_hard_link_to_a_photo_leaves_the_photo_alone() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let photo = src.join("a.jpg");
std::fs::write(&photo, b"photo").unwrap();
let report = work.join("report.json");
if let Err(e) = std::fs::hard_link(&photo, &report) {
let _ = std::fs::remove_dir_all(&work);
lightcraft_testkit::skip!(System, "can't make a hard link here ({e})");
return;
}
finish(json!({"browse": 1}), Some(report.clone())).unwrap();
assert_eq!(std::fs::read(&photo).unwrap(), b"photo", "the photo is unchanged");
let written: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap();
assert_eq!(written["browse"], 1);
let left: Vec<_> = std::fs::read_dir(&work).unwrap().flatten().map(|e| e.file_name()).collect();
assert_eq!(left.len(), 2, "no temporary file is left: {left:?}");
// a folder that isn't there: an error, nothing panics
assert!(write_replacing(&work.join("missing").join("r.json"), b"x").is_err());
let _ = std::fs::remove_dir_all(&work);
}
/// `--json` naming a file in the source folder is refused (CodeRabbit on #3077); elsewhere it is fine.
#[test]
fn the_results_never_go_in_the_source_folder() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let sub = fresh_dir(&src, "sub").unwrap();
assert!(inside_source(&src.join("a.png"), &src));
assert!(inside_source(&sub.join("x.json"), &src));
assert!(inside_source(&src.join("sub").join("..").join("a.png"), &src));
assert!(!inside_source(&work.join("out.json"), &src));
let _ = std::fs::remove_dir_all(&work);
}
/// `--work` in the source folder is refused before anything is made there, also when it doesn't
/// exist yet (CodeRabbit on #3077); elsewhere it is fine.
#[test]
fn the_work_folder_never_goes_in_the_source_folder() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let inside = src.join("out").join("deeper");
let e = check_outputs(&src, None, &inside).unwrap_err();
assert!(e.contains("--work"), "{e}");
assert!(check_outputs(&src, None, &src).is_err(), "the source folder itself");
assert!(!src.join("out").exists(), "nothing was made in the source folder");
assert!(check_outputs(&src, None, &work.join("elsewhere")).is_ok());
assert!(check_outputs(&src, Some(&src.join("r.json")), &work.join("elsewhere")).is_err());
let _ = std::fs::remove_dir_all(&work);
}
/// A `..` in `--json` or `--work` is refused: after a folder the run hasn't made yet it can't be
/// resolved now, and would lead into the source folder once the run makes it (CodeRabbit on #3544).
#[test]
fn a_dot_dot_in_the_outputs_is_refused() {
let work = run_dir(&std::env::temp_dir()).unwrap();
let src = fresh_dir(&work, "src").unwrap();
let sneaky = work.join("new").join("..").join("src").join("r.json");
let e = check_outputs(&src, Some(&sneaky), &work.join("elsewhere")).unwrap_err();
assert!(e.contains("--json") && e.contains(".."), "{e}");
let e = check_outputs(&src, None, &work.join("new").join("..").join("src")).unwrap_err();
assert!(e.contains("--work"), "{e}");
assert!(!work.join("new").exists(), "nothing was made");
let _ = std::fs::remove_dir_all(&work);
}
}
+205 -34
View File
@@ -11,11 +11,13 @@
//! lightcraft-cli commands [--json]
//! lightcraft-cli controls [--json]
//! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
//! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
//! ```
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod alloc_release;
mod bench_cull;
use std::io::Write;
use std::path::Path;
@@ -106,10 +108,16 @@ USAGE:
lightcraft-cli controls [--json] list every develop control id with its range
lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
Fit a colour profile per camera model from raw files and their embedded camera JPEGs
(Sony ARW, Nikon NEF, Fujifilm RAF): up to N files spread over the folders (default 300; 0 = all), pooled per
(Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW): up to N files spread over the folders (default 300; 0 = all), pooled per
model, written as <model>.json to DIR (default: the profiles folder LightCraft reads,
<config>/camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then
take their colour from the profile and only their tone from their own JPEG.
lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
Time what culling a shoot costs on its own files: reading the folder (browse), the first
screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render,
rating, and importing N files in place (default 2000) and copying M (default 200). Libraries
are made in a new folder under DIR (default: the temp folder); nothing is written next to the
photos. --files K reads only the first K files by name (a sample of a slow network folder).
lightcraft-cli --version | --help
";
@@ -155,7 +163,16 @@ fn main() -> ExitCode {
// Warnings (a GPU render redone on the CPU, an unknown backend name) on stderr; LIGHTCRAFT_LOG
// or RUST_LOG picks another level (#168).
lightcraft_engine::logging::install("lightcraft-cli");
let args: Vec<String> = std::env::args().skip(1).collect();
let mut args: Vec<String> = Vec::new();
for (index, arg) in std::env::args_os().skip(1).enumerate() {
match arg.into_string() {
Ok(arg) => args.push(arg),
Err(_) => {
eprintln!("lightcraft-cli: argument {} is not valid Unicode", index + 1);
return ExitCode::FAILURE;
}
}
}
let r = match args.first().map(String::as_str) {
Some("run") => run(&args[1..]),
Some("mcp") => mcp(&args[1..]),
@@ -167,6 +184,7 @@ fn main() -> ExitCode {
Some("controls") => controls(&args[1..]),
Some("denoise-serve") => denoise_serve(&args[1..]),
Some("calibrate") => calibrate(&args[1..]),
Some("bench-cull") => bench_cull::run(&args[1..]),
Some("--version" | "-V" | "version") => {
println!("lightcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
@@ -187,26 +205,35 @@ fn main() -> ExitCode {
}
/// Raw files below `path` (or `path` itself), skipping hidden and NAS metadata folders.
fn raw_files(path: &Path, out: &mut Vec<std::path::PathBuf>, depth: usize) {
let is_raw =
|p: &Path| p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf"].iter().any(|x| e.eq_ignore_ascii_case(x)));
///
/// Folders go through the engine's bounded walk ([`lightcraft_engine::walk::files_in`]): it enters
/// a folder reached through a link once at most and stops at a depth and an entry budget. A
/// folder of links pointing back at their parents made the old recursive walk re-read the same
/// folders exponentially often before its depth limit cut it off (CWE-400).
fn raw_files(path: &Path, out: &mut Vec<std::path::PathBuf>) {
let is_raw = |p: &Path| {
p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf", "crw"].iter().any(|x| e.eq_ignore_ascii_case(x)))
};
if path.is_file() {
if is_raw(path) {
out.push(path.to_path_buf());
}
return;
}
let Ok(entries) = std::fs::read_dir(path) else { return };
if depth > 32 {
return;
}
for entry in entries.flatten() {
let name = entry.file_name();
if name.to_string_lossy().starts_with(['.', '@']) {
continue;
}
raw_files(&entry.path(), out, depth + 1);
// (hidden entries are left out by the walk; `@eaDir` and other NAS metadata folders and files
// here, folders before they are listed so their entries do not use up the walk's budget)
let nas_metadata = |p: &Path| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('@'));
let walked = lightcraft_engine::walk::files_in_entering(
path,
None,
lightcraft_engine::walk::Limits::default(),
|p| is_raw(p) && !nas_metadata(p) && p.is_file(),
|p| !nas_metadata(p),
);
if walked.truncated {
eprintln!("calibrate: {} has more folders or entries than a walk looks at; the rest is left out", path.display());
}
out.extend(walked.files);
}
fn calibrate(args: &[String]) -> Result<(), String> {
@@ -228,7 +255,7 @@ fn calibrate(args: &[String]) -> Result<(), String> {
}
let mut files = Vec::new();
for input in &inputs {
raw_files(Path::new(input), &mut files, 0);
raw_files(Path::new(input), &mut files);
}
files.sort();
files.dedup();
@@ -416,7 +443,7 @@ fn merge(args: &[String]) -> Result<(), String> {
}
i += 1;
}
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
let mut s = file_session();
let paths = expand_paths(&files);
let r = s.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?;
let mut ids: Vec<u64> = r["imported"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
@@ -557,6 +584,8 @@ fn run(args: &[String]) -> Result<(), String> {
} else {
std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?
};
// Windows PowerShell 5.1 writes a UTF-8 BOM; it is not part of the first JSON line.
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
for (n, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty() && !l.trim_start().starts_with('#')) {
let v: Value = serde_json::from_str(line).map_err(|e| format!("{path}:{}: {e}", n + 1))?;
// `{"command": id, "params": …}` or a control request `{"method": m, "params": …}`
@@ -565,7 +594,11 @@ fn run(args: &[String]) -> Result<(), String> {
.or(v.get("method"))
.and_then(Value::as_str)
.ok_or_else(|| format!("{path}:{}: needs `command` or `method`", n + 1))?;
let params = v.get("params").cloned().filter(|p| p.is_object()).unwrap_or_else(|| json!({}));
let params = match v.get("params") {
None | Some(Value::Null) => json!({}),
Some(Value::Object(params)) => Value::Object(params.clone()),
Some(_) => return Err(format!("{path}:{}: `params` must be a JSON object", n + 1)),
};
steps.push(Step { id: id.to_string(), params });
}
}
@@ -594,14 +627,7 @@ fn run(args: &[String]) -> Result<(), String> {
None => Headless::default(),
};
if !imports.is_empty() {
let paths = expand_paths(&imports);
let r = h.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?;
// what follows acts on the imported photos (already-known files are reported as duplicates)
let mut ids: Vec<Value> = r["imported"].as_array().cloned().unwrap_or_default();
ids.extend(r["duplicates"].as_array().into_iter().flatten().filter_map(|d| d.get("existing").filter(|v| v.is_u64()).cloned()));
if let Some(first) = ids.first().cloned() {
h.session.execute("library.select", &json!({"ids": ids, "active": first})).map_err(|e| e.to_string())?;
}
import_and_select(&mut h.session, &imports)?;
}
Box::new(h)
}
@@ -626,6 +652,34 @@ fn run(args: &[String]) -> Result<(), String> {
if failed > 0 { Err(format!("{failed} command(s) failed")) } else { Ok(()) }
}
fn import_and_select(session: &mut Session, imports: &[String]) -> Result<(), String> {
let selection = session.selection.clone();
let paths = expand_paths(imports);
let result = (|| {
let r = session.execute("library.import", &json!({"paths": paths})).map_err(|e| format!("import failed: {e}; no commands were run"))?;
let ids = import_targets(&r)?;
let first = ids.first().cloned().ok_or("import found no photos to select; no commands were run")?;
session.execute("library.select", &json!({"ids": ids, "active": first})).map_err(|e| e.to_string())?;
Ok::<(), String>(())
})();
if result.is_err() {
session.selection = selection;
}
result
}
fn import_targets(report: &Value) -> Result<Vec<Value>, String> {
if let Some(failed) = report["failed"].as_array().filter(|failed| !failed.is_empty()) {
return Err(format!("import failed for {} item(s): {}; no commands were run", failed.len(), json!(failed)));
}
let mut ids: Vec<Value> = report["imported"].as_array().cloned().unwrap_or_default();
ids.extend(report["duplicates"].as_array().into_iter().flatten().filter_map(|d| d.get("existing").filter(|v| v.is_u64()).cloned()));
ids.extend(report["restored"].as_array().into_iter().flatten().filter(|id| id.is_u64()).cloned());
let mut seen = std::collections::HashSet::new();
ids.retain(|id| id.as_u64().is_none_or(|id| seen.insert(id)));
if ids.is_empty() { Err("import found no photos to select; no commands were run".into()) } else { Ok(ids) }
}
fn take_value<'a>(args: &'a [String], i: &mut usize, flag: &str) -> Result<&'a str, String> {
*i += 1;
args.get(*i).map(String::as_str).ok_or_else(|| format!("{flag} needs a value"))
@@ -667,6 +721,12 @@ fn read_settings(p: &str) -> Result<SettingsFile, String> {
}
}
/// The session `render` and `merge` develop files in: with the lens database the desktop app downloaded, when it is
/// there (never fetched from here: scripts and tests stay offline).
fn file_session() -> Session {
Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_lens_database()
}
fn render(args: &[String]) -> Result<(), String> {
let mut input = None;
let mut output = None;
@@ -683,7 +743,9 @@ fn render(args: &[String]) -> Result<(), String> {
"--set" => {
let kv = take_value(args, &mut i, "--set")?;
let (k, v) = kv.split_once('=').ok_or_else(|| format!("--set expects control=value, got `{kv}`"))?;
let v: f64 = v.trim().parse().map_err(|_| format!("--set {k}: `{v}` is not a number"))?;
// `inf` / `NaN` parse as f64 but become JSON null, which the control would silently ignore.
let v: f64 =
v.trim().parse().ok().filter(|n: &f64| n.is_finite()).ok_or_else(|| format!("--set {k}: `{v}` is not a finite number"))?;
values.insert(k.trim().to_string(), json!(v));
}
"--settings" => settings = Some(read_settings(take_value(args, &mut i, "--settings")?)?),
@@ -703,7 +765,7 @@ fn render(args: &[String]) -> Result<(), String> {
}
let input = input.ok_or("render: missing input file")?;
let output = output.ok_or("render: missing -o OUTPUT")?;
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
let mut s = file_session();
let abs = expand_paths(std::slice::from_ref(&input));
let r = s.execute("library.import", &json!({"paths": abs})).map_err(|e| e.to_string())?;
let id = r["imported"][0].as_u64().ok_or_else(|| format!("{input}: not a readable photo"))?;
@@ -798,15 +860,30 @@ fn snapshot(args: &[String]) -> Result<(), String> {
let t0 = Instant::now();
let mut session = match &library {
Some(dir) => {
let mut s =
Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates();
let mut s = Session::new()
.with_fs()
.with_default_denoise_models()
.with_system_clock()
.with_default_face_models()
.with_default_lens_database()
.with_default_slide_templates();
s.open_library(dir, false).map_err(|e| library_error(dir, e))?;
s
}
None if files.is_empty() => {
Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates()
}
None => Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates(),
None if files.is_empty() => Session::with_demo()
.with_fs()
.with_default_denoise_models()
.with_system_clock()
.with_default_face_models()
.with_default_lens_database()
.with_default_slide_templates(),
None => Session::new()
.with_fs()
.with_default_denoise_models()
.with_system_clock()
.with_default_face_models()
.with_default_lens_database()
.with_default_slide_templates(),
};
// Apply compute policy before imports or the first scripted query can discover an adapter.
session.execute("app.gpu", &json!({"enabled": false})).map_err(|e| e.to_string())?;
@@ -852,6 +929,8 @@ fn snapshot(args: &[String]) -> Result<(), String> {
let mut failed = 0usize;
if let Some(script) = &script {
let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?;
// Windows PowerShell 5.1 writes a UTF-8 BOM; it is not part of the first JSON line.
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let mut out = std::io::stdout().lock();
for (n, line) in text.lines().enumerate() {
let line = line.trim();
@@ -1028,3 +1107,95 @@ fn denoise_serve(args: &[String]) -> Result<(), String> {
fn denoise_serve(_: &[String]) -> Result<(), String> {
Err("denoise-serve: this build has no denoise support (build with the `denoise` feature)".into())
}
#[cfg(all(test, unix))]
mod raw_files_tests {
use super::raw_files;
/// Links back to their own folders are entered once, not once per path that reaches them: a
/// handful of such links made the old walk list the same folders exponentially often.
#[test]
fn folder_links_back_up_are_walked_once() {
let dir = std::env::temp_dir().join(format!("lightcraft-cli-raw-files-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let a = dir.join("a");
std::fs::create_dir_all(a.join("@eaDir")).unwrap();
std::fs::write(a.join("one.NEF"), b"").unwrap();
std::fs::write(a.join("@eaDir").join("thumb.nef"), b"").unwrap();
std::fs::write(a.join("notes.txt"), b"").unwrap();
for i in 0..8 {
std::os::unix::fs::symlink(&dir, a.join(format!("up{i}"))).unwrap();
}
// a named pipe with a raw extension: not a file, so never opened (a read would block)
assert!(std::process::Command::new("mkfifo").arg(a.join("pipe.nef")).status().unwrap().success());
let started = std::time::Instant::now();
let mut files = Vec::new();
raw_files(&dir, &mut files);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "walk took {:?}", started.elapsed());
assert_eq!(files, vec![a.join("one.NEF")]);
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod tests {
/// `render` and `merge` read the lens database the desktop app downloaded, as the desktop does (the same raw
/// gets the same profile everywhere), but never fetch it.
#[test]
fn render_reads_the_downloaded_lens_database() {
let s = super::file_session();
assert_eq!(lightcraft_engine::lens_profiles::host_dir(), lightcraft_engine::lensfun_download::default_dir());
assert!(!s.lens_auto_download, "selecting it is not permission to download it");
}
}
#[cfg(test)]
mod import_target_tests {
use super::{import_and_select, import_targets, json};
#[test]
fn empty_reports_and_duplicates_without_ids_have_no_target() {
assert!(import_targets(&json!({})).is_err());
assert!(import_targets(&json!({"imported": [], "duplicates": [{"existing": null}]})).is_err());
}
#[test]
fn restored_only_and_mixed_reports_keep_target_order() {
assert_eq!(import_targets(&json!({"restored": [9]})).unwrap(), vec![json!(9)]);
assert_eq!(
import_targets(&json!({"imported": [1], "duplicates": [{"existing": null}, {"existing": 2}], "restored": [3]})).unwrap(),
vec![json!(1), json!(2), json!(3)]
);
}
#[test]
fn repeated_targets_are_selected_once_in_first_occurrence_order() {
let report = json!({"imported": [5, 7], "duplicates": [{"existing": 5}, {"existing": 8}, {"existing": 8}, {"existing": 7}, {"existing": null}], "restored": [8, 9, 5]});
assert_eq!(import_targets(&report).unwrap(), vec![json!(5), json!(7), json!(8), json!(9)]);
}
#[test]
fn failed_items_reject_even_when_targets_exist() {
let error = import_targets(&json!({"imported": [1], "failed": [["broken.png", "invalid"]]})).unwrap_err();
assert!(error.contains("1") && error.contains("broken.png") && error.contains("no commands were run"), "{error}");
}
#[test]
fn failed_partial_import_restores_empty_selection() {
let dir = std::env::temp_dir().join(format!("lightcraft-import-selection-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("valid.png");
let broken = dir.join("broken.png");
let img = lightcraft_raster::Rgba8::from_fn(2, 2, |_, _| [20, 40, 60, 255]);
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
std::fs::write(&input, png).unwrap();
std::fs::write(&broken, b"not a PNG").unwrap();
let mut headless = lightcraft_mcp::Headless::default();
let session = &mut headless.session;
let selection = session.selection.clone();
assert!(selection.ids.is_empty() && selection.active.is_none());
assert!(import_and_select(session, &[input.to_string_lossy().into_owned(), broken.to_string_lossy().into_owned()]).is_err());
assert_eq!(session.selection, selection);
let _ = std::fs::remove_dir_all(dir);
}
}
+422 -15
View File
@@ -101,6 +101,75 @@ fn gradient_png(path: &std::path::Path) {
std::fs::write(path, png).unwrap();
}
/// PERF-CULL-5: `bench-cull` times a folder end to end and writes nothing next to the photos.
#[test]
fn bench_cull_times_a_folder_and_leaves_it_untouched() {
let dir = tmp("bench-cull-src");
std::fs::create_dir_all(&dir).unwrap();
for (seed, name) in ["a.png", "b.png", "c.png"].iter().enumerate() {
// three different pictures (the same bytes would import as one photo)
let img = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, (seed * 80) as u8, 255]);
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
std::fs::write(dir.join(name), png).unwrap();
}
// every file's name and bytes: nothing added, and no photo written into (CodeRabbit on #3577)
let listing = |d: &std::path::Path| {
let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(d)
.unwrap()
.map(|e| e.unwrap())
.map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read(e.path()).unwrap()))
.collect();
v.sort();
v
};
let before = listing(&dir);
let work = tmp("bench-cull-work");
let json_out = tmp("bench-cull.json");
let r = Command::new(binary())
.arg("bench-cull")
.arg(&dir)
.args(["--n", "3", "--copy", "1", "--work"])
.arg(&work)
.arg("--json")
.arg(&json_out)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&r.stdout);
assert!(r.status.success(), "{stdout}{}", String::from_utf8_lossy(&r.stderr));
assert!(stdout.contains("browse 3 photos") && stdout.contains("ms wall"), "{stdout}");
let v: Value = serde_json::from_str(&std::fs::read_to_string(&json_out).unwrap()).unwrap();
assert_eq!(v["browse"]["photos"], 3);
assert_eq!(v["importAdd"]["photos"], 3);
assert_eq!(v["importCopy"]["photos"], 1);
assert_eq!(v["rate"]["n"], 3);
// a folder smaller than the samples is measured on the photos it has, not reported empty
for stage in ["camera1280", "camera2560", "cameraFull", "loupeRender"] {
assert_eq!(v[stage]["n"], 3, "{stage}: {}", v[stage]);
}
assert_eq!(listing(&dir), before, "nothing written next to the photos");
// results asked for in the source folder: refused, the photo untouched
let photo = std::fs::read(dir.join("a.png")).unwrap();
let r = Command::new(binary())
.arg("bench-cull")
.arg(&dir)
.args(["--n", "0", "--work"])
.arg(&work)
.arg("--json")
.arg(dir.join("a.png"))
.output()
.unwrap();
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("--json"), "{}", String::from_utf8_lossy(&r.stderr));
assert_eq!(std::fs::read(dir.join("a.png")).unwrap(), photo);
assert_eq!(listing(&dir), before);
// a sample of the folder, no import
let r = Command::new(binary()).arg("bench-cull").arg(&dir).args(["--files", "2", "--n", "0", "--work"]).arg(&work).output().unwrap();
let stdout = String::from_utf8_lossy(&r.stdout);
assert!(r.status.success() && stdout.contains("browse 2 photos (first files)") && !stdout.contains("import"), "{stdout}");
// a bad folder is an error, not a panic
let r = Command::new(binary()).args(["bench-cull", "/no/such/folder"]).output().unwrap();
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("not a folder"));
}
#[test]
fn calibrate_reads_raf_inputs_and_reports_bad_files() {
let input = tmp("invalid.RAF");
@@ -162,6 +231,43 @@ fn mcp_over_stdio_sets_exposure_and_renders() {
assert!(b > a + 10.0, "{a} → {b}");
}
#[cfg(unix)]
#[test]
fn non_utf8_argument_fails_without_a_panic() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let out = tmp("non-utf8-output.png");
let _ = std::fs::remove_file(&out);
let output = Command::new(binary()).arg("render").arg(OsString::from_vec(b"bad-\xff.png".to_vec())).arg("-o").arg(&out).output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{stderr}");
assert!(stderr.contains("argument 2"), "{stderr}");
assert!(stderr.contains("is not valid Unicode"), "{stderr}");
assert!(!stderr.contains("panicked"), "{stderr}");
assert!(!out.exists());
assert!(Command::new(binary()).arg("--version").status().unwrap().success());
}
#[cfg(windows)]
#[test]
fn non_unicode_argument_fails_without_a_panic_on_windows() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let out = tmp("non-unicode-output.png");
let _ = std::fs::remove_file(&out);
let name: Vec<u16> = "bad-".encode_utf16().chain([0xD800]).chain(".png".encode_utf16()).collect();
let output = Command::new(binary()).arg("render").arg(OsString::from_wide(&name)).arg("-o").arg(&out).output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{stderr}");
assert!(stderr.contains("argument 2"), "{stderr}");
assert!(stderr.contains("is not valid Unicode"), "{stderr}");
assert!(!stderr.contains("panicked"), "{stderr}");
assert!(!out.exists());
assert!(Command::new(binary()).arg("--version").status().unwrap().success());
}
#[test]
fn render_subcommand() {
let input = tmp("r-in.png");
@@ -184,6 +290,12 @@ fn render_subcommand() {
let o = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "nope=1"]).output().unwrap();
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown control"));
// Values that parse as f64 but are not finite fail cleanly too.
for bad in ["light.exposure=inf", "light.exposure=-inf", "light.exposure=NaN", "light.exposure=1e999"] {
let o = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", bad]).output().unwrap();
assert!(!o.status.success(), "{bad} must be refused");
assert!(String::from_utf8_lossy(&o.stderr).contains("not a finite number"), "{bad}");
}
}
/// Issue #1730: `render --settings` took a `.lcpreset` from `preset.export`, ignored its wrapper
@@ -443,7 +555,12 @@ fn snapshot_defaults_to_cpu_without_gpu_environment_overrides() {
let script = tmp("default-cpu.jsonl");
std::fs::write(
&script,
format!("{}\n{}\n", json!({"method": "engine.execute", "params": {"command": "app.gpu"}}), json!({"method": "ui.screenshot"})),
format!(
"{}\n{}\n{}\n",
json!({"method": "engine.execute", "params": {"command": "app.gpu", "params": {"wait": false}}}),
json!({"method": "engine.execute", "params": {"command": "app.gpu"}}),
json!({"method": "ui.screenshot"})
),
)
.unwrap();
let image = tmp("default-cpu.png");
@@ -457,15 +574,52 @@ fn snapshot_defaults_to_cpu_without_gpu_environment_overrides() {
assert!(output.status.success(), "status {}: {}", output.status, String::from_utf8_lossy(&output.stderr));
let replies: Vec<Value> = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert!(replies.iter().all(|reply| reply["ok"] == true), "{replies:?}");
let gpu = &replies[0]["result"];
assert_eq!(gpu["enabled"], false, "{gpu}");
assert_eq!(gpu["available"], false, "{gpu}");
assert_eq!(gpu["adapter"], Value::Null, "no device is created: {gpu}");
assert!(gpu["reason"].as_str().is_some_and(|reason| reason.contains("preference")), "{gpu}");
// `wait: false` (what the UI sends) still says why the GPU is off: no device is being created
for gpu in [&replies[0]["result"], &replies[1]["result"]] {
assert_eq!(gpu["enabled"], false, "{gpu}");
assert_eq!(gpu["available"], false, "{gpu}");
assert_eq!(gpu["adapter"], Value::Null, "no device is created: {gpu}");
assert!(gpu["reason"].as_str().is_some_and(|reason| reason.contains("preference")), "{gpu}");
}
let decoded = lightcraft_codecs::decode(&std::fs::read(image).unwrap(), Default::default()).unwrap();
assert_eq!((decoded.width, decoded.height), (480, 320));
}
/// Issue #136: `app.gpu {enabled: true, wait: false}` (what the UI sends on its first frame) answers
/// at once while the device is still being created: enabled, and nothing known yet (`null`), instead
/// of waiting for the driver. It starts creating the device (off the calling thread), so this test
/// touches the GPU driver and skips when the environment turns the GPU off.
#[test]
fn enabling_the_gpu_without_waiting_answers_before_the_device_exists() {
if std::env::var("LIGHTCRAFT_GPU").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")) {
lightcraft_testkit::skip!(Gpu, "LIGHTCRAFT_GPU=0: enabling the GPU starts creating a device");
return;
}
let script = tmp("gpu-starting.jsonl");
std::fs::write(
&script,
format!("{}\n", json!({"method": "engine.execute", "params": {"command": "app.gpu", "params": {"enabled": true, "wait": false}}})),
)
.unwrap();
let image = tmp("gpu-starting.png");
let output = Command::new(binary())
.env_remove("LIGHTCRAFT_GPU")
.env_remove("LIGHTCRAFT_GPU_BACKEND")
.env_remove("WGPU_BACKEND")
.args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", image.to_str().unwrap(), "--size", "480x320"])
.output()
.unwrap();
assert!(output.status.success(), "status {}: {}", output.status, String::from_utf8_lossy(&output.stderr));
let replies: Vec<Value> = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], true, "{replies:?}");
let gpu = &replies[0]["result"];
assert_eq!(gpu["enabled"], true, "{gpu}");
for field in ["available", "adapter", "reason"] {
assert_eq!(gpu[field], Value::Null, "{field} is not known while the device is created: {gpu}");
}
}
/// Issue #136: with the GPU switched off from the environment the UI starts and renders on the CPU,
/// without creating a GPU device (no driver is loaded), and says why.
#[test]
@@ -502,6 +656,29 @@ fn snapshot_starts_without_a_gpu() {
}
}
/// A loopback port nothing listens on, for tests that need `--connect` to be refused (#3070).
/// A fixed port is not safe: agents give their apps' control servers ports in 18000–19999 (and
/// 7980 is the default), so a test could reach someone's running app and drive it. The OS hands
/// out a free port for `:0`; the listener is dropped so connecting to it is refused. Another
/// process could bind the port between the drop and the connect. That window is a few
/// milliseconds, and `:0` draws from the OS's ephemeral range (from 32768 on Linux, 49152 on
/// macOS and Windows), where nobody puts a control server (7980, 18000–19999): the standard
/// trade-off for a test that needs a refused connection.
///
/// Within this binary the window is closed: the tests that take an ephemeral port and let it go
/// hold [`ephemeral_ports`], so `denoise-serve` can't start on a port a refused-connection test
/// picked while it runs.
fn unused_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
/// Held by each test that picks an ephemeral port and releases it before use, for the whole test.
fn ephemeral_ports() -> std::sync::MutexGuard<'static, ()> {
static PORTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
// a test that failed while holding it doesn't fail the others
PORTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn run_cli(args: &[&str], stdin: Option<&str>) -> (bool, Vec<Value>, String) {
let mut child = Command::new(binary()).arg("run").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
if let Some(text) = stdin {
@@ -513,6 +690,230 @@ fn run_cli(args: &[&str], stdin: Option<&str>) -> (bool, Vec<Value>, String) {
(o.status.success(), lines, String::from_utf8_lossy(&o.stderr).to_string())
}
/// Windows PowerShell 5.1 writes a UTF-8 BOM; `--script` (file and stdin) must accept it.
#[test]
fn run_script_accepts_a_utf8_bom() {
let text = "\u{feff}{\"command\": \"library.info\", \"params\": {}}\n";
let script = tmp("bom-steps.jsonl");
std::fs::write(&script, text).unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--script", script.to_str().unwrap()], None);
assert!(ok, "file: {err}");
assert_eq!(lines.len(), 1, "{lines:?}");
let (ok, lines, err) = run_cli(&["--demo", "--script", "-"], Some(text));
assert!(ok, "stdin: {err}");
assert_eq!(lines.len(), 1, "{lines:?}");
}
#[test]
fn run_script_params_validate_before_any_commands() {
let path = tmp("run-invalid-params.jsonl");
let path_str = path.to_str().unwrap();
for params in [json!([]), json!("invalid"), json!(42), json!(true)] {
let script = format!("{}\n{}\n", json!({"command": "library.info"}), json!({"command": "develop.reset", "params": params}));
std::fs::write(&path, &script).unwrap();
for (source, stdin) in [("-", Some(script.as_str())), (path_str, None)] {
let (ok, lines, err) = run_cli(&["--script", source], stdin);
assert!(!ok, "{source}: {params}: {lines:?}");
assert!(lines.is_empty(), "{source}: {params}: {lines:?}");
assert!(err.contains(&format!("{source}:2")), "{err}");
assert!(err.contains("`params` must be a JSON object"), "{err}");
}
}
for script in
["{\"command\":\"library.info\"}\n", "{\"command\":\"library.info\",\"params\":null}\n", "{\"command\":\"library.info\",\"params\":{}}\n"]
{
let (ok, lines, err) = run_cli(&["--script", "-"], Some(script));
assert!(ok, "{script}: {err}");
assert_eq!(lines.len(), 1, "{script}: {lines:?}");
assert_eq!(lines[0]["ok"], true, "{script}: {lines:?}");
}
std::fs::remove_file(path).unwrap();
}
#[test]
fn run_failed_import_never_edits_existing_selection() {
let dir = tmp("failed-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let lib = dir.join("library");
let missing = dir.join("missing.png");
let empty = dir.join("empty");
std::fs::create_dir(&empty).unwrap();
assert!(!missing.exists());
let lib = lib.to_str().unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--library", lib, "library.state"], None);
assert!(ok, "{err}");
let id = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, _, err) = run_cli(&["--library", lib, "photo.rate", &format!("ids=[{id}]"), "rating=0"], None);
assert!(ok, "{err}");
for path in [&missing, &empty] {
let (ok, lines, err) = run_cli(&["--library", lib, "--import", path.to_str().unwrap(), "photo.rate", "rating=5"], None);
assert!(!ok, "import unexpectedly succeeded for {}: {lines:?}", path.display());
assert!(lines.is_empty(), "commands ran: {lines:?}");
assert!(err.contains("import") && err.contains("no commands were run"), "{err}");
if path == &missing {
assert!(err.contains("failed") && err.contains("missing.png"), "{err}");
}
let (ok, lines, err) = run_cli(&["--library", lib, "photo.inspect", &format!("id={id}")], None);
assert!(ok, "{err}");
assert_eq!(lines[0]["result"]["rating"], 0);
}
}
#[test]
fn run_partial_import_stops_commands_and_import_targets_remain_usable() {
let dir = tmp("partial-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("valid.png");
let broken = dir.join("broken.png");
gradient_png(&input);
std::fs::write(&broken, b"not a PNG").unwrap();
let mixed_lib = dir.join("mixed");
let mixed_lib = mixed_lib.to_str().unwrap();
let input = input.to_str().unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--library", mixed_lib, "catalog.query"], None);
assert!(ok, "{err}");
let photos = lines[0]["result"]["photos"].as_array().unwrap();
let a = photos[0]["id"].as_u64().unwrap();
let b = photos[1]["id"].as_u64().unwrap();
let (ok, lines, err) = run_cli(
&[
"--library",
mixed_lib,
"library.select",
&format!("ids=[{a},{b}]"),
&format!("active={a}"),
"photo.rate",
&format!("ids=[{a}]"),
"rating=0",
"library.state",
],
None,
);
assert!(ok, "{err}");
let selection = lines[2]["result"]["selection"].clone();
assert_eq!(selection["ids"], json!([a, b]));
assert_eq!(selection["active"], a);
let (ok, lines, err) =
run_cli(&["--library", mixed_lib, "--import", input, "--import", broken.to_str().unwrap(), "photo.rate", "rating=5"], None);
let (query_ok, after, query_err) =
run_cli(&["--library", mixed_lib, "library.state", "photo.inspect", &format!("id={a}"), "catalog.query"], None);
assert!(query_ok, "{query_err}");
assert_eq!(after[0]["result"]["selection"], selection, "selection changed after partial import");
assert!(!ok, "partial import unexpectedly succeeded: {lines:?}");
assert!(lines.is_empty() && err.contains("failed") && err.contains("no commands were run"), "{err}: {lines:?}");
assert_eq!(after[1]["result"]["rating"], 0);
assert!(after[2]["result"]["photos"].as_array().unwrap().iter().any(|p| p["fileName"] == "valid.png"));
let lib = dir.join("duplicates");
let lib = lib.to_str().unwrap();
let (ok, lines, err) = run_cli(&["--demo", "--library", lib, "library.state"], None);
assert!(ok, "{err}");
let previous = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, lines, err) = run_cli(&["--library", lib, "--import", input, "photo.rate", "rating=4", "library.state"], None);
assert!(ok, "{err}");
let id = lines[1]["result"]["selection"]["active"].as_u64().unwrap();
assert_ne!(id, previous);
let (ok, _, err) = run_cli(&["--library", lib, "library.select", &format!("ids=[{previous}]"), "photo.rate", "rating=0"], None);
assert!(ok, "{err}");
let (ok, _, err) = run_cli(&["--library", lib, "--import", input, "photo.rate", "rating=3"], None);
assert!(ok, "{err}");
let (ok, lines, err) = run_cli(&["--library", lib, "photo.inspect", &format!("id={id}"), "photo.inspect", &format!("id={previous}")], None);
assert!(ok, "{err}");
assert_eq!(lines[0]["result"]["rating"], 3);
assert_eq!(lines[1]["result"]["rating"], 0);
}
#[test]
fn run_restored_import_is_selected() {
let dir = tmp("restored-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("valid.png");
gradient_png(&input);
let lib = dir.join("library");
let (lib, input) = (lib.to_str().unwrap(), input.to_str().unwrap());
let (ok, lines, err) = run_cli(&["--library", lib, "--import", input, "library.state"], None);
assert!(ok, "{err}");
let id = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, _, err) = run_cli(&["--library", lib, "photo.delete"], None);
assert!(ok, "{err}");
let (ok, _, err) = run_cli(&["--library", lib, "--import", input, "photo.rate", "rating=4"], None);
assert!(ok, "{err}");
let (ok, lines, err) = run_cli(&["--library", lib, "catalog.query"], None);
assert!(ok, "{err}");
assert_eq!(lines[0]["result"]["photos"].as_array().unwrap().len(), 1);
assert_eq!(lines[0]["result"]["photos"][0]["id"], id);
assert_eq!(lines[0]["result"]["photos"][0]["rating"], 4);
}
#[test]
fn run_same_batch_duplicates_selects_photo_once() {
let dir = tmp("same-batch-duplicates");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let first = dir.join("first.png");
let second = dir.join("second.png");
gradient_png(&first);
std::fs::copy(&first, &second).unwrap();
let library = dir.join("library");
let (ok, lines, err) = run_cli(
&[
"--library",
library.to_str().unwrap(),
"--import",
first.to_str().unwrap(),
"--import",
second.to_str().unwrap(),
"photo.rate",
"rating=4",
"library.state",
"catalog.query",
],
None,
);
assert!(ok, "{err}");
let selection = &lines[1]["result"]["selection"];
let ids = selection["ids"].as_array().unwrap();
assert_eq!(ids.len(), 1, "same photo selected more than once: {selection}");
assert_eq!(selection["active"], ids[0]);
let photos = lines[2]["result"]["photos"].as_array().unwrap();
assert_eq!(photos.len(), 1);
assert_eq!(photos[0]["id"], ids[0]);
assert_eq!(photos[0]["rating"], 4);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn run_mixed_new_and_restored_import_selects_both() {
let dir = tmp("mixed-restored-import");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let restored = dir.join("restored.png");
let new = dir.join("new.png");
gradient_png(&restored);
let image = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, 200, 255]);
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&image), &Default::default()).unwrap();
std::fs::write(&new, png).unwrap();
let lib = dir.join("library");
let (lib, restored, new) = (lib.to_str().unwrap(), restored.to_str().unwrap(), new.to_str().unwrap());
let (ok, lines, err) = run_cli(&["--library", lib, "--import", restored, "library.state"], None);
assert!(ok, "{err}");
let restored_id = lines[0]["result"]["selection"]["active"].as_u64().unwrap();
let (ok, _, err) = run_cli(&["--library", lib, "photo.delete"], None);
assert!(ok, "{err}");
let (ok, lines, err) = run_cli(&["--library", lib, "--import", new, "--import", restored, "photo.rate", "rating=4", "library.state"], None);
assert!(ok, "{err}");
assert_eq!(lines[1]["result"]["selection"]["ids"].as_array().unwrap().len(), 2);
let (ok, lines, err) = run_cli(&["--library", lib, "catalog.query"], None);
assert!(ok, "{err}");
let photos = lines[0]["result"]["photos"].as_array().unwrap();
assert_eq!(photos.len(), 2);
assert!(photos.iter().any(|p| p["id"] == restored_id && p["rating"] == 4));
assert!(photos.iter().any(|p| p["fileName"] == "new.png" && p["id"] != restored_id && p["rating"] == 4));
}
#[test]
fn run_subcommand_chains_commands_and_persists_a_library() {
let input = tmp("run-in.png");
@@ -614,9 +1015,11 @@ fn a_library_open_in_another_process_is_refused() {
/// ADDR actually names — following the old fixed "7980" left the retry connecting elsewhere.
#[test]
fn connect_failure_hint_names_the_attempted_port() {
let (ok, _lines, err) = run_cli(&["--connect", "127.0.0.1:18437", "ui.inspect"], None);
let _ports = ephemeral_ports();
let port = unused_port();
let (ok, _lines, err) = run_cli(&["--connect", &format!("127.0.0.1:{port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "the hint must name the port it tried: {err}");
assert!(err.contains(&format!("--control {port}")), "the hint must name the port it tried: {err}");
assert!(!err.contains("--control 7980"), "{err}");
}
@@ -626,20 +1029,23 @@ fn connect_failure_hint_names_the_attempted_port() {
/// works; non-numeric, non-`ADDR`-shaped tokens (e.g. a real command id) keep falling through.
#[test]
fn connect_bare_port_is_treated_as_loopback_port() {
let _ports = ephemeral_ports();
let port = unused_port();
let hint = format!("--control {port}");
// Bare port: the failure hint names that port.
let (ok, _lines, err) = run_cli(&["--connect", "18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&["--connect", &port.to_string(), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "bare port must reach the hint: {err}");
assert!(err.contains(&hint), "bare port must reach the hint: {err}");
assert!(!err.contains("--control 7980"), "{err}");
// `<host>:<port>` still works (issue #167 case).
let (ok, _lines, err) = run_cli(&["--connect", "127.0.0.1:18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&["--connect", &format!("127.0.0.1:{port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "{err}");
assert!(err.contains(&hint), "{err}");
// `--connect=<bare-port>` already worked (the `a.starts_with("--connect=")` arm); spot-check
// the hint matches its port too.
let (ok, _lines, err) = run_cli(&["--connect=18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&[&format!("--connect={port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "{err}");
assert!(err.contains(&hint), "{err}");
}
/// The CLI logs warnings on stderr (#168): with `RUST_LOG=warn` an unknown GPU backend name is
@@ -785,7 +1191,8 @@ fn denoise_serve_runs_tiles_for_another_computer() {
Command::new(binary()).args(["denoise-serve", "--models", models.to_str().unwrap(), "--token-env", "LC_TEST_NO_SUCH_VAR"]).output().unwrap();
assert!(!o.status.success() && String::from_utf8_lossy(&o.stderr).contains("LC_TEST_NO_SUCH_VAR"));
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let _ports = ephemeral_ports();
let port = unused_port();
let addr = format!("127.0.0.1:{port}");
let token = "cli-test-token-0123456789";
let mut child = Command::new(binary())
+6
View File
@@ -32,10 +32,14 @@ js-sys = { workspace = true }
web-sys = { workspace = true, features = [
"Blob",
"BlobPropertyBag",
"CustomEvent",
"CustomEventInit",
"CssStyleDeclaration",
"DedicatedWorkerGlobalScope",
"Document",
"DomStringList",
"Element",
"Event",
"EventTarget",
"File",
"FileList",
@@ -80,3 +84,5 @@ heif = ["lightcraft-codecs/heif"]
[dev-dependencies]
egui = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-raw = { workspace = true }
+36
View File
@@ -233,6 +233,25 @@ pub fn parse_central(cd: &[u8]) -> Result<Vec<ZipEntry>, String> {
Ok(out)
}
/// What a restore writes, each storage key once, checked against the whole directory before any
/// payload is read: a backup names a file once, so a directory naming the same destination again
/// is damaged or altered, and its entries' bytes can't add up to more than the file holds (a
/// directory can point many entries at one stored range and have each read, checked and written).
pub fn restore_plan<'a>(entries: &'a [ZipEntry], dir: &str, file_len: u64) -> Result<Vec<(String, &'a ZipEntry)>, String> {
let mut seen = std::collections::HashSet::new();
let mut plan = Vec::new();
let mut bytes = 0u64;
for e in entries {
let Some(key) = restore_key(&e.name, dir) else { continue };
if !seen.insert(key.clone()) {
return Err(format!("{}: listed twice (damaged or altered backup)", e.name));
}
bytes = bytes.checked_add(e.size).filter(|&b| b <= file_len).ok_or_else(|| format!("{}: entries larger than the backup itself", e.name))?;
plan.push((key, e));
}
Ok(plan)
}
/// Offset of an entry's data from its local header's first 30 bytes.
pub fn data_offset(entry: &ZipEntry, local: &[u8]) -> Result<u64, String> {
if rd32(local, 0) != Some(LOCAL_SIG) {
@@ -342,6 +361,23 @@ mod tests {
assert!(!valid_library_dir("library-../x") && !valid_library_dir("originals") && !valid_library_dir("library-"));
}
#[test]
fn restore_plan_refuses_repeated_and_oversized_entries() {
let entry = |name: &str, size: u64| ZipEntry { name: name.into(), crc: 0, size, header: 0, method: 0 };
let ok = [entry("README.txt", 10), entry("library/catalog.log", 10), entry("originals/abc123/a.jpg", 100)];
let plan = restore_plan(&ok, "d", 200).unwrap();
assert_eq!(plan.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["d/catalog.log", "originals/abc123"]);
// one stored range named 3 times would be read, checked and written 3 times
let twice = [entry("originals/abc123/a.jpg", 100), entry("originals/abc123/b.jpg", 100)];
assert!(restore_plan(&twice, "d", 1000).unwrap_err().contains("twice"));
let twice = [entry("library/catalog.log", 10), entry("library/catalog.log", 10)];
assert!(restore_plan(&twice, "d", 1000).is_err());
// entries claiming more bytes than the file has
let big = [entry("library/catalog.log", 150), entry("originals/abc123/a.jpg", 100)];
assert!(restore_plan(&big, "d", 200).is_err());
assert!(restore_plan(&[entry("library/catalog.log", u64::MAX), entry("library/presets.json", 1)], "d", u64::MAX).is_err());
}
#[test]
fn size_limits_are_errors_not_panics() {
let mut w = ZipWriter { offset: MAX_BYTES - 10, ..Default::default() };
+3
View File
@@ -2,6 +2,9 @@
//! control exactly like a slider drag (begin interaction → N `develop.set` → end) and time each
//! step from the command to the moment the new loupe texture is ready. Results go to the log
//! (the browser console on the web) as one `lightcraft-bench {…json…}` line.
//!
//! The web host runs it only on the generated demo photos in an unsaved library (`?bench` implies `?store=memory`): it
//! commits edits to the photo it opens, which must never be one in the user's stored library.
use lightcraft_ui_egui::LightcraftApp;
use lightcraft_ui_egui::render::Slot;
+632
View File
@@ -0,0 +1,632 @@
//! The bridge to a host page (issue #2270): a same-origin page embeds LightCraft in an `<iframe>`
//! (`?host=parent`) or in its own document (`data-host="page"` on the canvas). The protocol is
//! the one PdfCraft, GridCraft and DeckCraft speak, with `lightcraft:` message types:
//!
//! - `lightcraft:ready` (to the parent): `{ version }`, the app is listening.
//! - `lightcraft:failed` (to the parent): `{ error }`, the app couldn't start, or it refused a
//! `lightcraft:open` (a file larger than a library backup can hold, [`crate::backup::MAX_BYTES`]).
//! - `lightcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
//! `Uint8Array`. The photo is added to the library, as one dropped on the window is; `name`
//! gives the format (its extension), `photo.jpg` when missing.
//! - `lightcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
//! file LightCraft would otherwise download: exports and the library backup (the preset, keyword
//! and curve file dialogs have no web implementation yet). The parent stores it and reports
//! failures itself.
//! - `lightcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
//! On the web every change is written to browser storage a moment after it is made, so `dirty`
//! means "closing the page right now would lose something": a write still queued or running,
//! or changes that storage refused (quota).
//! - `lightcraft:cmd` (from the parent): `{ id, params }`, params a JSON string (`{}` when
//! missing, empty or `null`; anything but a JSON object is refused unrun, see [`crate::automation::params`]).
//! Runs the command by id, like `lightcraft.command(..)` from the page itself, and answers with
//! `lightcraft:response` `{ ok, value }` (the JSON result, or the error text).
//! Responses carry no request id (none of the sibling bridges' do): they come back in the order
//! the commands were sent, one per `cmd` that had an id; a `cmd` without one gets no response.
//!
//! Only the parent window on the page's own origin is heard or answered. A page whose origin is
//! opaque (`"null"`: a sandboxed iframe, a `data:` page) gets no bridge at all, since every other
//! opaque-origin window would then pass as the parent. A parent on another origin gets no bridge
//! either: its `location` cannot be read, and exports keep downloading. There is no `docClosed`: LightCraft has a
//! library, not documents that close.
//!
//! ## `data-host="page"` — the page's own document
//!
//! A page can also run LightCraft in its own document, no iframe: the canvas opts in with
//! `data-host="page"`, and the same messages travel as DOM `CustomEvent`s on the canvas instead
//! of `postMessage` — outward with the message's fields as the event's `detail`, inward as
//! `lightcraft:open` and `lightcraft:cmd` events the page dispatches on the canvas. Events don't
//! bubble, so two editors on one page can't hear each other, and the canvas is the only target
//! the bridge listens on.
//!
//! The message layer (what a message means, what is sent back) is plain Rust, tested natively;
//! [`Bridge`] (wasm32 only) moves it over `postMessage`, or over DOM events in page mode.
/// A message from the parent page, once understood.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Incoming {
/// `lightcraft:open`: add this photo to the library.
Open { name: String, bytes: Vec<u8> },
/// `lightcraft:cmd`: run this command (params as JSON text).
Cmd { id: String, params: String },
/// `lightcraft:open` with a file too large to keep: tell the parent why (`lightcraft:failed`).
Refused(String),
}
/// The fields of a message from the parent, as read off the event (each may be missing).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Raw {
pub kind: Option<String>,
pub name: Option<String>,
pub bytes: Option<Vec<u8>>,
pub id: Option<String>,
pub params: Option<String>,
/// The size of `bytes` when it was too large to copy (`bytes` is then `None`).
pub oversize: Option<u64>,
}
/// Why a photo of `len` bytes sent with `lightcraft:open` is refused, or `None` when it fits: one
/// larger than a library backup can hold ([`crate::backup::MAX_BYTES`]) is never copied in.
pub fn open_size_error(len: u64) -> Option<String> {
let max = crate::backup::MAX_BYTES;
(len > max).then(|| format!("the file is too large to open ({} MB; the limit is {} MB)", len >> 20, max >> 20))
}
/// The name a photo sent without one is stored under (its extension picks the decoder).
pub const DEFAULT_OPEN_NAME: &str = "photo.jpg";
impl Incoming {
/// What the parent asked for; `None` for a message type that isn't ours, an `open` without
/// bytes or a `cmd` without an id (dropped, the page's other messages are none of our business).
pub fn parse(raw: Raw) -> Option<Incoming> {
match raw.kind.as_deref() {
Some("lightcraft:open") => {
if let Some(error) = raw.oversize.and_then(open_size_error) {
return Some(Incoming::Refused(error));
}
let name = raw.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| DEFAULT_OPEN_NAME.to_string());
Some(Incoming::Open { name, bytes: raw.bytes? })
}
Some("lightcraft:cmd") => {
let id = raw.id.filter(|i| !i.trim().is_empty())?;
Some(Incoming::Cmd { id, params: raw.params.filter(|p| !p.trim().is_empty()).unwrap_or_else(|| "{}".to_string()) })
}
_ => None,
}
}
}
/// A field of a message to the parent.
#[derive(Clone, Debug, PartialEq)]
pub enum Field {
Str(String),
Bool(bool),
}
/// A message to the parent, without bytes (`lightcraft:save` carries a transferred buffer and is
/// built by the bridge itself).
#[derive(Clone, Debug, PartialEq)]
pub enum Outgoing {
Ready,
Failed(String),
Dirty(bool),
/// How a `lightcraft:cmd` ended: the JSON result, or the error text.
Response {
ok: bool,
value: String,
},
}
impl Outgoing {
/// The message's fields, `type` first.
pub fn fields(&self) -> Vec<(&'static str, Field)> {
match self {
Outgoing::Ready => vec![("type", Field::Str("lightcraft:ready".into())), ("version", Field::Str(env!("CARGO_PKG_VERSION").into()))],
Outgoing::Failed(error) => vec![("type", Field::Str("lightcraft:failed".into())), ("error", Field::Str(error.clone()))],
Outgoing::Dirty(dirty) => vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(*dirty))],
Outgoing::Response { ok, value } => {
vec![("type", Field::Str("lightcraft:response".into())), ("ok", Field::Bool(*ok)), ("value", Field::Str(value.clone()))]
}
}
}
}
/// The unsaved-changes state as the parent last heard it: `lightcraft:dirty` goes out only when
/// it changes (not every frame), and a message that couldn't be sent is sent again next time.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirtyReport {
reported: Option<bool>,
}
impl DirtyReport {
/// `Some(message)` when `dirty` differs from what the parent knows; call [`DirtyReport::sent`]
/// once it went out.
pub fn change(&self, dirty: bool) -> Option<Outgoing> {
(self.reported != Some(dirty)).then_some(Outgoing::Dirty(dirty))
}
pub fn sent(&mut self, dirty: bool) {
self.reported = Some(dirty);
}
/// Record `dirty` before the send. A page host can report another state while the event is
/// still dispatching, and that later report wins. Returns the message to send and the state
/// to put back if this send fails and nothing else recorded one.
pub fn prepare(&mut self, dirty: bool) -> (Option<Outgoing>, Option<bool>) {
let previous = self.reported;
let message = self.change(dirty);
if message.is_some() {
self.sent(dirty);
}
(message, previous)
}
/// Forget a send that failed, unless a nested report already recorded a different state.
pub fn restore_if_unchanged(&mut self, dirty: bool, previous: Option<bool>) {
if self.reported == Some(dirty) {
self.reported = previous;
}
}
}
/// Whether a page origin can tell the parent apart from any other window: an opaque origin
/// (`"null"`, as a sandboxed iframe or a `data:` page has) cannot, so such a page gets no bridge.
pub fn origin_is_usable(origin: &str) -> bool {
let o = origin.trim();
!o.is_empty() && o != "null"
}
/// The name a saved file is handed over under: the file name of the path the export chose.
pub fn save_name(path: &str) -> String {
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string())
}
/// The one `data-host` value that opts a page into page host mode: the exact string `"page"`.
pub const PAGE_HOST: &str = "page";
/// How a host page reaches the app. The modes behave the same; they differ only in how an event
/// goes out ([`Bridge::post`] and `save`, wasm32) and how one comes in ([`Bridge::listen`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// `?host=parent`: the page framed LightCraft in an `<iframe>`; `postMessage`.
Parent,
/// `data-host="page"`: the page runs LightCraft in its own document; DOM `CustomEvent`s.
Page,
}
/// The mode the page asked for. `?host=parent` wins when the page asks for both, the same order
/// as the other apps. Page mode is the exact `data-host="page"` ([`PAGE_HOST`]). `None` with
/// neither, so that URL stays the normal app with downloads.
pub fn transport_for(data_host: Option<&str>, query: &str) -> Option<Mode> {
if host_parent_requested(query) {
Some(Mode::Parent)
} else if data_host == Some(PAGE_HOST) {
Some(Mode::Page)
} else {
None
}
}
/// The message type. A page-mode `CustomEvent` is named `lightcraft:open` or `lightcraft:cmd`
/// and its `detail` is only the fields, so the event name is the type. A parent `postMessage`
/// carries `type` in the object and has no event name.
pub fn incoming_kind(event_name: Option<&str>, detail_type: Option<String>) -> Option<String> {
event_name.map(str::to_string).or(detail_type)
}
/// Does the query ask for the parent bridge? The same reading of `?host=parent` the URL options
/// always used: the first `host` parameter whose value is exactly `parent`.
pub fn host_parent_requested(query: &str) -> bool {
query.trim_start_matches('?').split('&').find_map(|p| {
let (k, v) = p.split_once('=').unwrap_or((p, ""));
(k == "host").then_some(v == "parent")
}) == Some(true)
}
#[cfg(target_arch = "wasm32")]
pub use bridge::Bridge;
#[cfg(target_arch = "wasm32")]
mod bridge {
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::JsCast as _;
use wasm_bindgen::JsValue;
use wasm_bindgen::closure::Closure;
use super::{DirtyReport, Field, Incoming, Mode, Outgoing, Raw, open_size_error, origin_is_usable, save_name};
/// How an event goes to the host page, per mode ([`Mode`]).
#[derive(Clone)]
enum Transport {
/// `?host=parent`: `postMessage` between same-origin windows.
Parent { parent: web_sys::Window, origin: String },
/// `data-host="page"`: DOM `CustomEvent`s on the editor's own canvas.
Page { canvas: web_sys::HtmlCanvasElement },
}
impl Transport {
/// Hand an event to the host. Parent mode: a `postMessage` whose `type` field is `event`
/// (the same message as before, transferring `transfer` when given). Page mode: a
/// non-bubbling `CustomEvent` of that name on the canvas, whose `detail` holds the
/// fields; nothing is transferred there, the buffer just rides inside `detail`.
fn send(&self, event: &str, fields: &[(&str, JsValue)], transfer: Option<&js_sys::ArrayBuffer>) -> Result<(), String> {
match self {
Transport::Parent { parent, origin } => {
let mut all = Vec::with_capacity(fields.len() + 1);
all.push(("type", JsValue::from_str(event)));
all.extend_from_slice(fields);
let message = message(&all).ok_or_else(|| "couldn't build the message".to_string())?;
let sent = match transfer {
Some(buffer) => parent.post_message_with_transfer(&message, origin, &js_sys::Array::of1(buffer)),
None => parent.post_message(&message, origin),
};
sent.map_err(|e| js_error(&e, "couldn't post the message"))
}
Transport::Page { canvas } => {
let detail = message(fields).ok_or_else(|| "couldn't build the event detail".to_string())?;
let init = web_sys::CustomEventInit::new();
init.set_bubbles(false);
init.set_detail(&detail);
let custom =
web_sys::CustomEvent::new_with_event_init_dict(event, &init).map_err(|e| js_error(&e, "couldn't create the event"))?;
canvas.dispatch_event(&custom).map_err(|e| js_error(&e, "couldn't dispatch the event"))?;
Ok(())
}
}
}
}
/// The host page's end of the bridge (cheap to clone; one per page).
#[derive(Clone)]
pub struct Bridge {
transport: Transport,
/// What the host sent since the last frame, oldest first.
incoming: Rc<RefCell<Vec<Incoming>>>,
dirty: Rc<RefCell<DirtyReport>>,
}
impl Bridge {
/// The parent bridge for `?host=parent`. `None` when the page isn't framed, its origin is
/// opaque, or the parent is on another origin (exports then keep downloading).
pub fn new() -> Option<Self> {
let window = web_sys::window()?;
let parent = window.parent().ok().flatten()?;
if js_sys::Object::is(&parent, &window) {
return None;
}
// the document's own origin (`window.origin`), not the URL's: a sandboxed iframe keeps
// its URL but runs with the opaque origin "null"
let origin = window.origin();
if !origin_is_usable(&origin) {
return None;
}
// Reading another origin's location throws, so this is `None` for a cross-origin parent.
if parent.location().origin().ok().as_deref() != Some(origin.as_str()) {
return None;
}
Some(Self { transport: Transport::Parent { parent, origin }, incoming: Rc::default(), dirty: Rc::default() })
}
/// The page bridge for `data-host="page"`: the host page runs LightCraft in its own
/// document and hears the app's DOM `CustomEvent`s on this canvas.
pub fn for_page(canvas: &web_sys::HtmlCanvasElement) -> Self {
Self { transport: Transport::Page { canvas: canvas.clone() }, incoming: Rc::default(), dirty: Rc::default() }
}
/// The bridge for the mode the page opted into (`host::transport_for`): page mode needs
/// its canvas, and parent mode falls back to `None` as [`Bridge::new`] always did.
pub fn for_mode(mode: Mode, canvas: Option<&web_sys::HtmlCanvasElement>) -> Option<Self> {
match mode {
Mode::Page => canvas.map(Self::for_page),
Mode::Parent => Self::new(),
}
}
/// Hear the host from now on; a message wakes the app for the next frame.
pub fn listen(&self, ctx: egui::Context) {
match &self.transport {
Transport::Parent { parent, origin } => {
let parent = parent.clone();
let origin = origin.clone();
let incoming = self.incoming.clone();
let on_message = Closure::<dyn Fn(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
return;
}
deliver(&incoming, &ctx, &event.data(), None);
});
if web_sys::window().is_some_and(|w| w.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok()) {
// the listener lives as long as the page
on_message.forget();
}
}
Transport::Page { canvas } => {
// non-bubbling events: the page dispatches on the canvas, the canvas listens
for kind in ["lightcraft:open", "lightcraft:cmd"] {
let incoming = self.incoming.clone();
let ctx = ctx.clone();
let event_type = kind.to_string();
// `Fn`, not `FnMut`: a page event is dispatched synchronously, and a host
// that answers one event with another would re-enter an `FnMut` listener.
let on_custom = Closure::<dyn Fn(web_sys::Event)>::new(move |event: web_sys::Event| {
let Some(custom) = event.dyn_ref::<web_sys::CustomEvent>() else { return };
deliver(&incoming, &ctx, &custom.detail(), Some(event_type.as_str()));
});
if canvas.add_event_listener_with_callback(kind, on_custom.as_ref().unchecked_ref()).is_ok() {
// the listener lives as long as the page
on_custom.forget();
}
}
}
}
}
/// What the parent sent since the last frame, oldest first.
pub fn take_incoming(&self) -> Vec<Incoming> {
std::mem::take(&mut *self.incoming.borrow_mut())
}
/// Post a message; false if it couldn't be sent.
pub fn post(&self, m: &Outgoing) -> bool {
let fields = m.fields();
// every message names its type first (tested natively); the rest go to the transport
let Some((_, Field::Str(event))) = fields.first() else { return false };
let event = event.clone();
let rest: Vec<(&str, JsValue)> = fields.into_iter().skip(1).map(|(k, v)| (k, field(&v))).collect();
self.transport.send(&event, &rest, None).is_ok()
}
/// Tell the parent whether closing now would lose something, when that changed.
/// The new state is recorded before the send: page mode dispatches synchronously, and a
/// host that reports another state from that event wins. A failed send is forgotten
/// only when nothing else recorded one, so the next frame retries it.
pub fn report_dirty(&self, dirty: bool) {
let (message, previous) = self.dirty.borrow_mut().prepare(dirty);
if let Some(m) = message
&& !self.post(&m)
{
self.dirty.borrow_mut().restore_if_unchanged(dirty, previous);
}
}
/// Hand a file to the parent instead of downloading it (`lightcraft:save`).
pub fn save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
let name = save_name(path);
let buffer = js_sys::Uint8Array::from(bytes).buffer();
self.transfer(&name, buffer)
}
/// [`Bridge::save`] for a blob built outside the wasm heap (the library backup).
pub async fn save_blob(&self, name: String, blob: web_sys::Blob) -> Result<(), String> {
let buffer = wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await.map_err(|e| format!("{e:?}"))?;
self.transfer(&name, buffer.unchecked_into::<js_sys::ArrayBuffer>())
}
fn transfer(&self, name: &str, buffer: js_sys::ArrayBuffer) -> Result<(), String> {
self.transport.send("lightcraft:save", &[("name", name.into()), ("bytes", buffer.clone().into())], Some(&buffer))?;
log::info!("handed {name} to the page");
Ok(())
}
}
/// A message from the host (the `data` of a window message, or the `detail` of a page-mode
/// `CustomEvent`), read with the same field code both transports share, and pushed for the
/// next frame.
fn deliver(incoming: &Rc<RefCell<Vec<Incoming>>>, ctx: &egui::Context, data: &JsValue, event_type: Option<&str>) {
// moved, not cloned: an accepted photo can be hundreds of MB
let (bytes, oversize) = match bytes(data) {
Some(Ok(b)) => (Some(b), None),
Some(Err(len)) => (None, Some(len)),
None => (None, None),
};
let raw = Raw {
kind: super::incoming_kind(event_type, string(data, "type")),
name: string(data, "name"),
bytes,
id: string(data, "id"),
params: string(data, "params"),
oversize,
};
if let Some(m) = Incoming::parse(raw) {
incoming.borrow_mut().push(m);
ctx.request_repaint();
}
}
fn field(v: &Field) -> JsValue {
match v {
Field::Str(s) => s.as_str().into(),
Field::Bool(b) => (*b).into(),
}
}
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
let m = js_sys::Object::new();
for (key, value) in fields {
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
}
Some(m)
}
fn string(data: &JsValue, key: &str) -> Option<String> {
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
}
/// `bytes` as an `ArrayBuffer` or `Uint8Array`.
/// `bytes` as an `ArrayBuffer` or `Uint8Array`, copied only when within the size cap
/// ([`open_size_error`]); `Err(len)` for an oversize one, never copied into the app's memory.
fn bytes(data: &JsValue) -> Option<Result<Vec<u8>, u64>> {
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
let array = if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
array.clone()
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
js_sys::Uint8Array::new(&bytes)
} else {
return None;
};
let len = u64::from(array.byte_length());
Some(if open_size_error(len).is_some() { Err(len) } else { Ok(array.to_vec()) })
}
/// A `JsValue` error as a string, after `what` went wrong.
fn js_error(e: &JsValue, what: &str) -> String {
format!("{what}: {}", e.as_string().unwrap_or_else(|| format!("{e:?}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn raw(kind: &str) -> Raw {
Raw { kind: Some(kind.into()), ..Default::default() }
}
#[test]
fn open_needs_bytes_and_names_a_nameless_photo() {
let mut m = raw("lightcraft:open");
assert_eq!(Incoming::parse(m.clone()), None, "no bytes, nothing to add");
m.bytes = Some(vec![1, 2, 3]);
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
m.name = Some(" ".into());
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
m.name = Some("IMG_0001.CR2".into());
assert_eq!(Incoming::parse(m), Some(Incoming::Open { name: "IMG_0001.CR2".into(), bytes: vec![1, 2, 3] }));
}
#[test]
fn cmd_needs_an_id_and_defaults_its_params() {
let mut m = raw("lightcraft:cmd");
assert_eq!(Incoming::parse(m.clone()), None);
m.id = Some("library.info".into());
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Cmd { id: "library.info".into(), params: "{}".into() }));
m.params = Some(r#"{"rating": 5}"#.into());
assert_eq!(Incoming::parse(m), Some(Incoming::Cmd { id: "library.info".into(), params: r#"{"rating": 5}"#.into() }));
}
#[test]
fn an_oversize_open_is_refused_not_copied() {
let max = crate::backup::MAX_BYTES;
assert!(open_size_error(max).is_none());
assert!(open_size_error(max + 1).is_some_and(|e| e.contains("too large")));
let m = Raw { name: Some("big.tif".into()), oversize: Some(max + 1), ..raw("lightcraft:open") };
assert!(matches!(Incoming::parse(m), Some(Incoming::Refused(e)) if e.contains("too large")));
}
#[test]
fn other_pages_messages_are_not_ours() {
for kind in ["deckcraft:open", "lightcraft:save", "lightcraft:ready", ""] {
let m = Raw { bytes: Some(vec![1]), id: Some("x".into()), ..raw(kind) };
assert_eq!(Incoming::parse(m), None, "{kind:?}");
}
assert_eq!(Incoming::parse(Raw::default()), None);
}
#[test]
fn outgoing_messages_name_their_type_first() {
let ready = Outgoing::Ready.fields();
assert_eq!(ready[0], ("type", Field::Str("lightcraft:ready".into())));
assert_eq!(ready[1].0, "version");
assert_eq!(Outgoing::Failed("boom".into()).fields()[1], ("error", Field::Str("boom".into())));
assert_eq!(Outgoing::Dirty(true).fields(), vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(true))]);
let r = Outgoing::Response { ok: false, value: "no such command".into() }.fields();
assert_eq!(r[1], ("ok", Field::Bool(false)));
assert_eq!(r[2], ("value", Field::Str("no such command".into())));
}
/// The parent hears `dirty` when it changes, not every frame, and again if a send failed.
#[test]
fn dirty_is_reported_on_change_only() {
let mut d = DirtyReport::default();
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)), "the first state is news");
d.sent(false);
assert_eq!(d.change(false), None);
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
// not marked sent (the post failed): still owed
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
d.sent(true);
assert_eq!(d.change(true), None);
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)));
}
/// A failed send is retried. A report that lands during the send (page mode dispatches
/// synchronously) is the one that stays.
#[test]
fn a_failed_dirty_send_is_retried_unless_a_later_report_landed() {
let mut d = DirtyReport::default();
let (message, previous) = d.prepare(true);
assert_eq!(message, Some(Outgoing::Dirty(true)));
d.restore_if_unchanged(true, previous);
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
let (message, previous) = d.prepare(true);
assert!(message.is_some());
let (later, _) = d.prepare(false);
assert_eq!(later, Some(Outgoing::Dirty(false)));
d.restore_if_unchanged(true, previous);
assert_eq!(d.change(false), None);
}
/// A canvas event is named for its type; the detail does not have to repeat it.
#[test]
fn a_page_event_is_named_for_its_type() {
assert_eq!(incoming_kind(Some("lightcraft:open"), None).as_deref(), Some("lightcraft:open"));
assert_eq!(incoming_kind(Some("lightcraft:cmd"), Some("lightcraft:open".into())).as_deref(), Some("lightcraft:cmd"));
assert_eq!(incoming_kind(None, Some("lightcraft:open".into())).as_deref(), Some("lightcraft:open"));
assert_eq!(incoming_kind(None, None), None);
}
/// A sandboxed iframe or a `data:` page has the opaque origin `"null"`, which any other such
/// window shares: no bridge there, so the origin check keeps meaning something.
#[test]
fn an_opaque_origin_gets_no_bridge() {
assert!(origin_is_usable("https://photos.example"));
assert!(origin_is_usable("http://localhost:8080"));
assert!(!origin_is_usable("null"));
assert!(!origin_is_usable(" null "));
assert!(!origin_is_usable(""));
}
#[test]
fn saved_files_are_handed_over_by_file_name() {
assert_eq!(save_name("exports/2026/IMG_0001.jpg"), "IMG_0001.jpg");
assert_eq!(save_name("IMG_0001.jpg"), "IMG_0001.jpg");
assert_eq!(save_name("lightcraft-library-backup-2026-10-19.zip"), "lightcraft-library-backup-2026-10-19.zip");
}
/// Page mode is opt-in by the exact attribute value, parent mode by the query, and parent
/// mode wins when a page asks for both.
#[test]
fn page_mode_is_opt_in_and_parent_mode_wins_when_both_are_set() {
assert_eq!(transport_for(Some("page"), ""), Some(Mode::Page));
assert_eq!(transport_for(Some("page"), "?host=parent"), Some(Mode::Parent), "parent mode wins");
// only the exact value opts in; anything else falls back to the query, or to standalone
for not_page in ["Page", " page", "page ", "parent", "host"] {
assert_eq!(transport_for(Some(not_page), "?host=parent"), Some(Mode::Parent), "{not_page:?}");
assert_eq!(transport_for(Some(not_page), ""), None, "{not_page:?}");
}
assert_eq!(transport_for(None, ""), None);
assert_eq!(transport_for(None, "?store=idb"), None);
assert_eq!(transport_for(None, "?host="), None);
assert_eq!(transport_for(None, "?host=Parent"), None);
assert_eq!(transport_for(None, "?xhost=parent"), None);
}
/// The query is read the way the URL options always read it: the first `host` parameter wins,
/// and only a value of exactly `parent` counts.
#[test]
fn the_query_asks_for_the_parent_bridge() {
assert!(host_parent_requested("?host=parent"));
assert!(host_parent_requested("host=parent"));
assert!(host_parent_requested("?host=parent&store=idb"));
assert!(host_parent_requested("?store=idb&host=parent"));
assert!(!host_parent_requested(""));
assert!(!host_parent_requested("?"));
assert!(!host_parent_requested("?host"));
assert!(!host_parent_requested("?host="));
assert!(host_parent_requested("?host=parent&host=id"), "the first host parameter wins");
assert!(!host_parent_requested("?host=id&host=parent"));
assert!(!host_parent_requested("?hosts=parent"));
}
}
+7 -1
View File
@@ -11,8 +11,13 @@
//! - export downloads the file through the browser.
//!
//! `?bench` in the URL runs a scripted first-paint / slider-latency measurement and logs it to the
//! console (see [`bench`]); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
//! console (see [`bench`]) on the generated demo photos in an unsaved library (it implies `?store=memory`, so it never edits
//! the library in browser storage); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
//! persistence and `?workers=0` renders on the main thread.
//! `?host=parent` speaks to a same-origin page framing LightCraft (see [`host`]): it hands
//! photos in, receives what would be downloaded and hears about unsaved changes. A page can also
//! host LightCraft in its own document, no iframe: `data-host="page"` on the canvas opts in, and
//! the same messages travel as DOM `CustomEvent`s on the canvas.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -24,6 +29,7 @@ pub mod bench;
#[cfg(any(test, target_arch = "wasm32"))]
mod drop_gate;
pub mod files;
pub mod host;
pub mod store;
pub mod wire;
+9 -6
View File
@@ -13,7 +13,7 @@ use wasm_bindgen_futures::JsFuture;
use crate::backend::Backend;
use crate::backup::{
ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_key, restored_dir_name, tail_len,
ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_plan, restored_dir_name, tail_len,
valid_hash, verify, verify_original,
};
use crate::files::{Files, LIBRARY_FILES};
@@ -149,10 +149,14 @@ pub fn download_blob(name: &str, blob: &web_sys::Blob) -> Result<(), String> {
Ok(())
}
/// Where a finished backup goes: the browser's downloads ([`download_blob`]), or the page framing
/// LightCraft (`?host=parent`). Awaited, so the backup counts as done only once it is handed over.
pub type Deliver = Box<dyn FnOnce(String, web_sys::Blob) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>>>>>;
/// File ▸ Back Up Library…: a zip of the library files (as the app has them, saved or not) and
/// every original in storage, built entry by entry into the browser's memory (outside the wasm
/// heap) and downloaded. `names`: content hash → the photo's file name.
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>) -> Result<(usize, f64), String> {
/// heap) and handed to `deliver`. `names`: content hash → the photo's file name.
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>, deliver: Deliver) -> Result<(usize, f64), String> {
let parts = js_sys::Array::new();
let mut zip = ZipWriter::default();
let mut bytes = 0f64;
@@ -190,7 +194,7 @@ pub async fn backup(files: Files, backend: Backend, names: HashMap<String, Strin
opts.set_type("application/zip");
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(|e| format!("{e:?}"))?;
let day: String = String::from(js_sys::Date::new_0().to_iso_string()).chars().take(10).collect();
download_blob(&format!("lightcraft-library-backup-{day}.zip"), &blob)?;
deliver(format!("lightcraft-library-backup-{day}.zip"), blob).await?;
Ok((originals, bytes + tail.len() as f64))
}
@@ -214,8 +218,7 @@ pub async fn restore(file: web_sys::File, backend: Backend) -> Result<String, St
}
let dir = restored_dir_name(js_sys::Date::now());
let mut written = 0usize;
for e in &entries {
let Some(key) = restore_key(&e.name, &dir) else { continue };
for (key, e) in restore_plan(&entries, &dir, len)? {
// originals are named by their content: one already stored is the same file
if key.starts_with("originals/") && backend.exists(&key).await? {
continue;
+63 -3
View File
@@ -12,7 +12,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use lightcraft_engine::files::{load_bytes, probe_bytes};
use lightcraft_engine::files::{load_bytes_decoded, probe_bytes};
use lightcraft_engine::media::{FileLoader, FileProbe};
/// Prefix of the catalog paths of files kept in browser storage.
@@ -144,9 +144,11 @@ impl Originals {
/// Engine hooks that decode/probe from memory.
pub fn hooks(&self) -> (FileLoader, FileProbe) {
let s = self.clone();
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| {
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
// whether it decodes in a worker or inline when workers are unavailable)
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, with: lightcraft_engine::media::RawDecode<'_>| {
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
load_bytes(&bytes, max_edge)
load_bytes_decoded(&bytes, max_edge, lightcraft_engine::media::RawDecode { dcp: None, outliers: with.outliers })
});
let s = self.clone();
let probe: FileProbe = Arc::new(move |path: &str| {
@@ -237,6 +239,64 @@ mod tests {
assert_eq!(out.image.width, 20);
}
/// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this
/// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the
/// documented web behaviour). The loader now ignores it.
#[test]
fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() {
use lightcraft_raw::*;
let (w, h) = (32usize, 24usize);
let raw = RawImage {
format: RawFormat::Dng,
width: w,
height: h,
cpp: 1,
data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()),
cfa: Cfa::bayer("RGGB"),
bits: 14,
black: BlackLevel::uniform(256.0),
white: vec![16000.0],
active_area: Rect::new(0, 0, w, h),
crop: Rect::new(0, 0, w, h),
orientation: Orientation::Normal,
color: ColorData {
illuminant: [21, 0],
color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None],
as_shot_neutral: Some([0.5, 1.0, 0.7]),
..Default::default()
},
wb_multipliers: None,
linearized: false,
pixel_aspect: 1.0,
opcodes: OpcodeLists::default(),
metadata: Default::default(),
lens_metadata: Default::default(),
};
let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap();
// our own numbers: a matrix that swaps the camera's red and blue
let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([
[3.2406, -1.5372, -0.4986],
[-0.9689, 1.8758, 0.0415],
[0.0557, -0.2040, 1.0570],
]));
let profile = dcp::DcpProfile {
name: "Swap".into(),
camera_model: "LightCraft Test Camera".into(),
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
};
assert_ne!(
lightcraft_engine::files::load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
lightcraft_engine::files::load_bytes_with(&dng, 64, None).unwrap().0.data,
"the profile changes a raw's colour where it is applied"
);
let store = Originals::default();
store.insert("h1", Arc::from(dng));
let (loader, _) = store.hooks();
let with = loader("web/h1/a.dng", 64, lightcraft_engine::media::RawDecode { dcp: Some(&profile), outliers: false }).unwrap();
let without = loader("web/h1/a.dng", 64, Default::default()).unwrap();
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
}
#[test]
fn download_names() {
assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png");
+186 -23
View File
@@ -2,14 +2,14 @@
//! `<canvas id="lightcraft_canvas">`, wires the file picker and drag-and-drop, and turns exports
//! into downloads.
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use lightcraft_engine::Session;
use lightcraft_engine::catalog::Source;
use lightcraft_engine::library::LibraryStores;
use lightcraft_ui_egui::{LightcraftApp, Services, UiState};
use lightcraft_ui_egui::{LightcraftApp, Services, UiState, WriteFn};
use serde_json::json;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
@@ -18,6 +18,7 @@ use crate::backend::Backend;
use crate::backup::{ACTIVE_LIBRARY, DEFAULT_LIBRARY_DIR, valid_library_dir};
use crate::bench::Bench;
use crate::files::{Files, FlushOp, LIBRARY_FILES};
use crate::host::{Incoming, Outgoing};
use crate::safety::{self, notice};
use crate::store::{Originals, content_hash, download_name, storage_key};
use crate::wire::ThumbIndex;
@@ -68,13 +69,15 @@ pub(crate) fn request_repaint() {
});
}
/// URL options (`?bench&store=idb&workers=2&reset`).
/// URL options (`?bench&store=idb&workers=2&reset&host=parent`).
struct Options {
bench: bool,
/// "opfs" (default: OPFS, falling back to IndexedDB), "idb" or "memory".
store: String,
workers: Option<usize>,
reset: bool,
/// The raw query string, for the host mode ([`crate::host::transport_for`]).
query: String,
}
impl Options {
@@ -90,11 +93,15 @@ impl Options {
})
.collect();
let get = |k: &str| params.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let bench = get("bench").is_some();
Options {
bench: get("bench").is_some(),
store: get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()),
workers: get("workers").and_then(|v| v.parse().ok()),
bench,
// the benchmark edits the first photo it finds: a link with `?bench` must never reach
// the library in browser storage, so it always runs on the demo photos in an unsaved library
store: if bench { "memory".into() } else { get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()) },
workers: get("workers").and_then(|v| v.parse().ok()).map(|n: usize| n.min(crate::workers::MAX_WORKERS)),
reset: get("reset").is_some(),
query: q,
}
}
}
@@ -168,12 +175,75 @@ fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
Ok(())
}
/// Keep egui's hidden text field content-box, so host page CSS cannot misplace typed text:
/// eframe (0.36 web) types through a hidden `<input type="text">` it inserts as the canvas's
/// next sibling, and a host page's global `* { box-sizing: border-box }` reaches it and leaves it
/// no content box, so the next key lands before text just committed by an input method or a
/// paste-like insert. Inline style beats any host stylesheet rule without `!important`, so the
/// property is set on the element itself, in every host mode, and retried on the next animation
/// frames while eframe hasn't inserted the field yet.
fn fix_text_field_box_sizing() {
/// How many animation frames the fix may wait for eframe to insert its hidden text field.
const MAX_FRAMES: u32 = 120;
/// True when the field was found and set: the canvas's next sibling, or an
/// `input[type=text]` in the canvas's parent.
fn fix_once() -> bool {
let Some(doc) = window().and_then(|w| w.document()) else { return false };
let Some(canvas) = doc.get_element_by_id("lightcraft_canvas") else { return false };
let input = canvas.next_element_sibling().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()).or_else(|| {
canvas
.parent_element()
.and_then(|p| p.query_selector("input[type=text]").ok())
.flatten()
.and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok())
});
input.is_some_and(|i| i.style().set_property("box-sizing", "content-box").is_ok())
}
// the closure reschedules itself until the field is fixed or the frames run out; done, it is
// left parked in its slot (dropping it from inside itself would free its own state, and the
// slot holds the only reference) — a one-off leak, like the forgotten listeners
let tries = Rc::new(Cell::new(MAX_FRAMES));
let slot: Rc<RefCell<Option<Closure<dyn FnMut()>>>> = Rc::default();
let own = Rc::clone(&slot);
*slot.borrow_mut() = Some(Closure::new(move || {
if fix_once() || tries.get() <= 1 {
return; // done: stop rescheduling
}
tries.set(tries.get() - 1);
let again = own.borrow_mut().take();
if let Some(again) = again {
let _ = window().and_then(|w| w.request_animation_frame(again.as_ref().unchecked_ref()).ok());
// put the same closure back, now that the frame it was handed to has its own reference
*own.borrow_mut() = Some(again);
}
}));
let first = slot.borrow_mut().take();
if let Some(first) = first {
let _ = window().and_then(|w| w.request_animation_frame(first.as_ref().unchecked_ref()).ok());
*slot.borrow_mut() = Some(first);
}
}
/// Build the browser host's `Services`: library backup/restore through browser storage and a
/// download, asynchronous file picking, downloads for writes, and PNG encoding. Desktop-only
/// services (native pickers, reveal, model folders) stay unset.
fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen: Rc<Cell<bool>>, ctx: egui::Context) -> Services {
let (backup_backend, backup_files) = (backend.clone(), files);
fn services(
originals: Originals,
backend: Option<Backend>,
files: Files,
frozen: Rc<Cell<bool>>,
ctx: egui::Context,
bridge: Option<crate::host::Bridge>,
) -> Services {
let (backup_backend, backup_files, backup_bridge) = (backend.clone(), files, bridge.clone());
let restore_backend = backend.clone();
// what would be downloaded goes to the page framing LightCraft instead, when there is one
let write: WriteFn = match bridge {
Some(bridge) => Box::new(move |path: &str, bytes: &[u8]| bridge.save(path, bytes)),
None => Box::new(download),
};
Services {
local_places: None,
picker: None,
@@ -194,9 +264,18 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
})
.collect();
let files = backup_files.clone();
notice("Backing up the library… (the download starts when it's ready)");
// awaited by `backup`: "backed up" is said only once the page has the file
let deliver: safety::Deliver = match backup_bridge.clone() {
Some(bridge) => Box::new(move |name: String, blob: web_sys::Blob| Box::pin(async move { bridge.save_blob(name, blob).await })),
None => Box::new(|name: String, blob: web_sys::Blob| Box::pin(async move { safety::download_blob(&name, &blob) })),
};
notice(if backup_bridge.is_some() {
"Backing up the library… (handed to the page when it's ready)"
} else {
"Backing up the library… (the download starts when it's ready)"
});
wasm_bindgen_futures::spawn_local(async move {
match safety::backup(files, b, names).await {
match safety::backup(files, b, names, deliver).await {
Ok((n, bytes)) => notice(format!(
"Library backed up: {n} original{} ({:.1} MB). Keep the file somewhere safe.",
if n == 1 { "" } else { "s" },
@@ -234,7 +313,7 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
save_slideshow_template: None,
pick_print_templates: None,
save_print_template: None,
write: Some(Box::new(download)),
write: Some(write),
// the browser download path has no meaningful create-new file write; the control channel
// (and therefore screenshot paths) is not available on the web
write_new: None,
@@ -286,7 +365,8 @@ async fn flush(files: Files, backend: Backend, dir: String, flushing: Rc<Cell<bo
}
}
flushing.set(false);
// the page title drops its unsaved • now, even when nothing else wakes the page
// the page title drops its unsaved • now, and the page framing LightCraft hears `dirty: false`,
// even when nothing else wakes the page
request_repaint();
}
@@ -298,12 +378,14 @@ struct Boot {
index: ThumbIndex,
/// The library folder in storage (`library`, or a restored backup's).
lib_dir: String,
/// The page framing LightCraft (`?host=parent`), when there is one.
bridge: Option<crate::host::Bridge>,
/// Library files that exist but couldn't be read (#1507): the library isn't opened and
/// nothing is saved, so the stored copy stays as it was.
load_error: Option<String>,
}
async fn boot(opts: Options) -> Boot {
async fn boot(opts: Options, bridge: Option<crate::host::Bridge>) -> Boot {
let t0 = perf_now();
let backend = if opts.store == "memory" {
None
@@ -400,7 +482,7 @@ async fn boot(opts: Options) -> Boot {
index.len(),
index.total() as f64 / 1e6
);
Boot { opts, backend, files, index, lib_dir, load_error }
Boot { opts, backend, files, index, lib_dir, bridge, load_error }
}
struct WebApp {
@@ -421,6 +503,7 @@ struct WebApp {
title: String,
last_save: f64,
ui_written: Vec<u8>,
bridge: Option<crate::host::Bridge>,
}
/// The browser host's drop queues, taken only through the shared gate: a prompt or blocking
@@ -455,7 +538,7 @@ impl WebApp {
/// browser storage (a read failure starts an empty session and a blocking `LibraryProblem`),
/// load the stored UI state, start render workers and the optional benchmark.
fn new(cc: &eframe::CreationContext<'_>, boot: Boot, chinese_font: Vec<u8>) -> Self {
let Boot { opts, backend, files, index, lib_dir, load_error } = boot;
let Boot { opts, backend, files, index, lib_dir, bridge, load_error } = boot;
let originals = Originals::default();
let t = perf_now();
let mut session = Session::new();
@@ -496,6 +579,10 @@ impl WebApp {
});
}
}
// `?bench` never has storage (see `Options::from_url`): it measures the generated demo photos
if opts.bench && backend.is_none() && session.catalog.len() == 0 {
lightcraft_engine::demo::load(&mut session);
}
if backend.is_some() {
notice(
"LightCraft in the browser is experimental. Your library is kept in this browser's storage: keep your original photos \
@@ -506,13 +593,16 @@ impl WebApp {
session.media.preview_capacity = 3;
// nothing is saved while the stored library couldn't be read
let frozen = Rc::new(Cell::new(read_failed));
let mut app = LightcraftApp::new(session, services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone()))
.with_chinese_font(chinese_font);
let services = services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone(), bridge.clone());
let mut app = LightcraftApp::new(session, services).with_chinese_font(chinese_font);
let ui_written = files.get("ui.json").unwrap_or_default();
// an arrangement from an older docking version starts again from the default
let mut saved = serde_json::from_slice::<serde_json::Value>(&ui_written).unwrap_or_default();
if let Some(fields) = saved.as_object_mut() {
lightcraft_ui_egui::docking::drop_outdated(fields);
// a stored ui.json means an installation that has been run: due What's New, never
// the first-run tour (the same migration the desktop settings loader runs)
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
}
if let Ok(ui) = serde_json::from_value::<UiState>(saved) {
app.ui = ui;
@@ -540,6 +630,13 @@ impl WebApp {
}
log::info!("lightcraft: {n} render workers");
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
if let Some(b) = &bridge {
// hear the page from now on, and tell it the app is listening
b.listen(cc.egui_ctx.clone());
if !b.post(&Outgoing::Ready) {
log::warn!("lightcraft: the page framing LightCraft could not be told the app is ready");
}
}
let origin = lightcraft_ui_egui::monotonic_ms();
WebApp {
app,
@@ -556,9 +653,49 @@ impl WebApp {
title: String::new(),
last_save: 0.0,
ui_written,
bridge,
}
}
/// What the page framing LightCraft sent since the last frame: photos to add (as if dropped
/// on the window) and commands to run, each answered with `lightcraft:response`.
fn run_host(&mut self, ctx: &egui::Context) {
let Some(bridge) = self.bridge.clone() else { return };
for m in bridge.take_incoming() {
match m {
Incoming::Open { name, bytes } => {
wasm_bindgen_futures::spawn_local(store_file(self.originals.clone(), self.backend.clone(), name, bytes, ctx.clone()));
}
Incoming::Refused(error) => {
if !bridge.post(&Outgoing::Failed(error)) {
log::warn!("lightcraft: a refused open could not be reported to the page");
}
}
Incoming::Cmd { id, params } => {
let r = match crate::automation::params(&params) {
Err(e) => Err(format!("{id}: {e}")),
Ok(_) if id == "web.stats" => Ok(self.web_stats()),
Ok(params) => self.app.run(&id, params),
};
let response = match r {
Ok(v) => Outgoing::Response { ok: true, value: v.to_string() },
Err(e) => Outgoing::Response { ok: false, value: e },
};
if !bridge.post(&response) {
log::warn!("lightcraft: the answer to {id} could not reach the page");
}
}
}
}
}
/// Whether closing the page now would lose something: a write to browser storage still
/// queued or running, or changes storage refused (quota). The page framing LightCraft hears
/// when this changes (`lightcraft:dirty`), so it can ask before closing a window with edits.
fn dirty_for_host(&self) -> bool {
self.files.is_dirty() || self.flushing.get() || self.app.session.unsaved().is_some()
}
/// Consume the drops the raw-input hook queued once (never re-read `raw.dropped_files` in a
/// hidden logic tick), and add originals whose bytes have arrived.
fn import_dropped(&mut self, ctx: &egui::Context) {
@@ -735,6 +872,7 @@ impl eframe::App for WebApp {
self.app.ui.toast = Some((text, now + NOTICE_SECS, None));
}
self.run_inbox();
self.run_host(ctx);
self.load_originals(ctx);
if let Some(w) = &self.workers {
// `library.preferences ▸ cacheMb` is read by the session; the worker index prunes on
@@ -743,6 +881,9 @@ impl eframe::App for WebApp {
}
self.app.logic(ctx);
self.save();
if let Some(b) = &self.bridge {
b.report_dirty(self.dirty_for_host());
}
}
/// Pass the browser's raw input to the app hook before egui processes it, so prompt barriers
@@ -830,6 +971,21 @@ pub fn start(chinese_font: Vec<u8>) {
log::warn!("lightcraft: no Simplified Chinese font supplied; Chinese-only glyphs will show as boxes");
}
let opts = Options::from_url();
// `?host=parent`: a same-origin page framing LightCraft hands photos in, stores what would
// be downloaded and hears about unsaved changes (see `host`). `data-host="page"` on the
// canvas opts a page in instead: it runs LightCraft in its own document and talks over DOM
// `CustomEvent`s on the canvas. `?host=parent` wins when a page asks for both.
let canvas = window()
.and_then(|w| w.document())
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok());
let mode = crate::host::transport_for(canvas.as_ref().and_then(|c| c.get_attribute("data-host")).as_deref(), &opts.query);
let bridge = mode.and_then(|m| crate::host::Bridge::for_mode(m, canvas.as_ref()));
if mode == Some(crate::host::Mode::Parent) && bridge.is_none() {
log::warn!(
"lightcraft: ?host=parent, but this page is not framed, has an opaque origin, or its parent is on another origin; exports keep downloading"
);
}
wasm_bindgen_futures::spawn_local(async move {
// one tab per library: two would each keep their own copy and overwrite each other's saves
if opts.store != "memory" && safety::acquire_tab_lock().await == Some(false) {
@@ -837,17 +993,19 @@ pub fn start(chinese_font: Vec<u8>) {
"LightCraft is already open in another tab or window of this browser.\n\n\
Switch to that tab, or close it and reload this page. (Two tabs would overwrite each other's changes.)",
);
if let Some(b) = &bridge {
b.post(&Outgoing::Failed("LightCraft is already open in another tab or window of this browser".into()));
}
return;
}
let Some(canvas) = window()
.and_then(|w| w.document())
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok())
else {
let Some(canvas) = canvas else {
log::error!("missing <canvas id=\"lightcraft_canvas\">");
if let Some(b) = &bridge {
b.post(&Outgoing::Failed("the page has no <canvas id=\"lightcraft_canvas\">".into()));
}
return;
};
let boot = boot(opts).await;
let boot = boot(opts, bridge.clone()).await;
let runner = eframe::WebRunner::new();
let r = runner.start(canvas, eframe::WebOptions::default(), Box::new(move |cc| Ok(Box::new(WebApp::new(cc, boot, chinese_font))))).await;
match r {
@@ -855,10 +1013,15 @@ pub fn start(chinese_font: Vec<u8>) {
if let Some(el) = window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id("lightcraft_loading")) {
el.remove();
}
// the runner just started: egui's hidden text field exists from now on
fix_text_field_box_sizing();
}
Err(e) => {
log::error!("LightCraft failed to start: {e:?}");
set_status(&format!("LightCraft failed to start: {e:?}"));
if let Some(b) = &bridge {
b.post(&Outgoing::Failed(format!("{e:?}")));
}
}
}
});
+27 -5
View File
@@ -33,6 +33,9 @@ pub struct WireJob {
pub origin: Source,
/// Decode the source at most this long.
pub max_edge: usize,
/// Resize an already decoded source exactly as the engine's cached-source path does.
#[serde(default)]
pub fit_edge: Option<usize>,
pub raw: bool,
#[serde(default)]
pub relative_wb: bool,
@@ -67,7 +70,8 @@ impl WireJob {
/// `view`: the slot name, for jobs that keep a stage cache.
pub fn from_job(job: &RenderJob, thumb_cached: bool, view: &str) -> WireJob {
let max_edge = match &job.source {
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } | SourceRef::Fit { max_edge, .. } => *max_edge,
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } => *max_edge,
SourceRef::Fit { from, .. } => from.image.width.max(from.image.height),
SourceRef::Loaded(img) => img.image.width.max(img.image.height),
SourceRef::Smart { .. } => 2560,
};
@@ -77,6 +81,10 @@ impl WireJob {
level: job.level,
origin: job.origin.clone(),
max_edge,
fit_edge: match &job.source {
SourceRef::Fit { max_edge, .. } => Some(*max_edge),
_ => None,
},
raw: job.info.raw,
relative_wb: job.info.relative_wb,
legacy_relative_wb: job.info.legacy_relative_wb,
@@ -114,6 +122,7 @@ impl WireJob {
RenderRequest {
max_w: self.max_w,
max_h: self.max_h,
exact_size: false,
quality: if self.draft { Quality::Draft } else { Quality::Full },
apply_crop: self.apply_crop,
overlay: lightcraft_engine::pipeline::Overlay::from_parts(self.overlay.0, self.overlay.1),
@@ -129,7 +138,9 @@ impl WireJob {
/// Identifies the decoded source this job needs.
fn source_key(&self) -> String {
match &self.origin {
Source::File { path } => format!("{}:{:?}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge),
Source::File { path } => {
format!("{}:{:?}:{}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge, self.settings.removes_hot_pixels())
}
Source::Demo { scene } => format!("{}:{:?}:{}:demo:{scene}", self.cache_generation, self.source_identity, self.max_edge),
}
}
@@ -181,8 +192,10 @@ impl WorkerCore {
None => {
let src = match (&job.origin, original) {
(Source::File { .. }, Some(bytes)) => {
let (image, info) = lightcraft_engine::files::load_bytes(bytes, job.max_edge)?;
DecodedSource::new(Arc::new(image), Some(info))
let outliers = job.settings.removes_hot_pixels();
let with = lightcraft_engine::media::RawDecode { dcp: None, outliers };
let (image, info) = lightcraft_engine::files::load_bytes_decoded(bytes, job.max_edge, with)?;
DecodedSource { outliers, ..DecodedSource::new(Arc::new(image), Some(info)) }
}
(Source::File { path }, None) => return Err(format!("{path}: original not found in browser storage")),
(origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge).load_source()?,
@@ -192,6 +205,10 @@ impl WorkerCore {
src
}
};
let src = match job.fit_edge {
Some(max_edge) => SourceRef::Fit { from: Box::new(src), max_edge }.load_source()?,
None => src,
};
let info = src.info_or(job.info());
let mut rendered = match &job.stages {
Some(view) => {
@@ -451,7 +468,11 @@ mod tests {
let mut core = WorkerCore::default();
assert_eq!(core.needs_original(&wire), None, "demo scenes are generated");
let a = core.render(&wire, None).unwrap();
let b = job.run().rendered.unwrap();
// The worker uses the CPU. A native thumbnail job may use an already initialized GPU,
// so exact serialization parity must use the engine's CPU reference (#3778), regardless
// of test order. The window test above separately checks native CPU/GPU equivalence.
let source = job.source.load_source().unwrap();
let b = lightcraft_engine::pipeline::render(&source.image, &source.info_or(job.info), &job.settings, &job.request);
assert_eq!((a.image.width, a.image.height), (b.image.width, b.image.height));
assert_eq!(a.image.data, b.image.data);
assert_eq!(a.histogram, b.histogram);
@@ -468,6 +489,7 @@ mod tests {
level: SourceLevel::Thumb,
origin,
max_edge: 512,
fit_edge: None,
raw: false,
relative_wb: false,
legacy_relative_wb: false,
+21 -1
View File
@@ -207,6 +207,15 @@ impl Inner {
}
}
/// The most workers started, whatever `?workers=` asks: more than this brings nothing to a
/// render queue and a link can't make the page spawn workers (and their copies of the module)
/// without end.
pub const MAX_WORKERS: usize = 16;
/// Worker constructions failing in a row after which the rest are not tried: a browser that
/// refused this many refuses the next ones too.
const MAX_FAILED_STARTS: usize = 3;
/// The main thread's handle on the render workers.
#[derive(Clone)]
pub struct Workers(Rc<RefCell<Inner>>);
@@ -244,7 +253,12 @@ impl Workers {
return w;
}
let mut slots = WorkerSlots::default();
for attempt in 0..n {
let mut failed = 0;
for attempt in 0..n.min(MAX_WORKERS) {
if failed >= MAX_FAILED_STARTS {
log::warn!("render workers: {failed} failed to start in a row; not trying the rest");
break;
}
// The callbacks name their worker by its place in `workers`; a failed attempt takes none.
let i = slots.peek();
let opts = web_sys::WorkerOptions::new();
@@ -254,6 +268,7 @@ impl Workers {
Ok(x) => x,
Err(e) => {
log::warn!("render worker {attempt}: {e:?}");
failed += 1;
continue;
}
};
@@ -274,10 +289,12 @@ impl Workers {
worker.set_onmessage(None);
worker.set_onerror(None);
worker.terminate();
failed += 1;
continue;
}
w.0.borrow_mut().workers.push(W { worker, ready: false, dead: false, busy: None });
slots.commit();
failed = 0;
}
w
}
@@ -301,6 +318,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((b.slot, r, 0.0));
}
@@ -392,6 +410,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
},
ms,
));
@@ -446,6 +465,7 @@ impl RenderOffload for Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((slot, r, 0.0));
return None;
+3
View File
@@ -58,3 +58,6 @@ lightcraft-testkit = { workspace = true }
[target.'cfg(windows)'.dependencies]
craft-update = { workspace = true }
# the colour profile of the monitor showing the window (`win_screen_profile`)
lightcraft-wincolor = { workspace = true }
raw-window-handle = "0.6"
+1 -29
View File
@@ -18,8 +18,6 @@ use std::time::Duration;
const POLL: Duration = Duration::from_secs(3);
/// A wait before trying again when colord isn't there (not installed, no system bus).
const RETRY: Duration = Duration::from_secs(30);
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
const MAX_PROFILE: u64 = 16 << 20;
const SERVICE: &str = "org.freedesktop.ColorManager";
const DEVICE: &str = "org.freedesktop.ColorManager.Device";
@@ -72,7 +70,7 @@ fn read(conn: &zbus::blocking::Connection) -> Option<Vec<u8>> {
}
}
let file = pick(&files)?;
load(std::path::Path::new(file))
crate::profile_file::load(std::path::Path::new(file))
}
/// The profile to use for these displays' profile files: the one they share, `None` with none or
@@ -83,15 +81,6 @@ fn pick(files: &[String]) -> Option<&str> {
named.all(|f| f == first).then_some(first)
}
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
fn load(path: &std::path::Path) -> Option<Vec<u8>> {
use std::io::Read as _;
let file = std::fs::File::open(path).ok()?;
let mut bytes = Vec::new();
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -105,21 +94,4 @@ mod tests {
assert_eq!(pick(&s(&["/a.icc", "/b.icc"])), None, "which one the window is on isn't known");
assert_eq!(pick(&s(&[""])), None);
}
#[test]
fn profile_files_are_read_with_a_size_cap() {
let dir = std::env::temp_dir().join(format!("colord-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let small = dir.join("small.icc");
std::fs::write(&small, b"acsp").unwrap();
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
let empty = dir.join("empty.icc");
std::fs::write(&empty, b"").unwrap();
assert_eq!(load(&empty), None);
assert_eq!(load(&dir.join("missing.icc")), None);
let big = dir.join("big.icc");
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
assert_eq!(load(&big), None);
std::fs::remove_dir_all(&dir).unwrap();
}
}
+115 -19
View File
@@ -87,7 +87,7 @@ fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context, id
log::warn!("control connection closed: could not set idle read timeout: {e}");
return;
}
serve_lines(&stream, &stream, |method, params| {
serve_stream(stream, |method, params| {
let (req, rrx) = ControlRequest::new(method, params);
let state = Arc::clone(&req.state);
tx.send(req).ok()?;
@@ -96,6 +96,40 @@ fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context, id
});
}
/// The longest a closing connection is drained, however slowly its peer keeps sending.
const DRAIN_TIME: Duration = Duration::from_secs(1);
/// [`serve_lines`] on a socket, then close it so the peer reads every reply.
fn serve_stream(stream: TcpStream, handle: impl FnMut(String, Value) -> Option<Value>) {
serve_lines(&stream, &stream, handle);
close_gracefully(&stream);
}
/// Close a connection the server is done with without destroying its last reply. A socket closed
/// while the peer's later lines are unread, or arrive after it, answers them with a reset, and a
/// reset can discard the replies the peer has not read yet (on Windows it does): the client sees
/// "connection reset" instead of why. Send FIN, then read and drop what is left (at most
/// [`MAX_LINE`] bytes, 500 ms per read and [`DRAIN_TIME`] in all) before closing. From #1970
/// (LochLogic).
fn close_gracefully(stream: &TcpStream) {
let _ = stream.shutdown(std::net::Shutdown::Write);
let start = std::time::Instant::now();
let mut sink = [0u8; 8192];
let mut left = MAX_LINE;
let mut reader = stream;
while left > 0 {
// a peer that keeps trickling bytes must not hold the connection slot past DRAIN_TIME
let wait = DRAIN_TIME.saturating_sub(start.elapsed()).min(Duration::from_millis(500));
if wait.is_zero() || stream.set_read_timeout(Some(wait)).is_err() {
break;
}
match reader.read(&mut sink) {
Ok(0) | Err(_) => break,
Ok(n) => left = left.saturating_sub(n),
}
}
}
/// Wait for a request's reply. While the app has not picked the request up and `frames` (its
/// frame counter) stands still for `no_frames`, the request is abandoned (it will not run late)
/// and the reply says why; a request the app is running gets the whole `timeout`.
@@ -170,15 +204,40 @@ fn parse_line(bytes: &[u8]) -> Line {
}
}
/// The error of the notice sent when an idle connection is closed. Clients match the reply's
/// `"closed": "idle"` marker; `crates/mcp/src/backend.rs` also matches this text, for apps from
/// before the marker, so keep the two in step.
const IDLE_CLOSE_ERROR: &str = "control connection idle read timed out; closing the connection";
/// Why the server closes a connection; its error reply says so.
#[derive(Debug, PartialEq)]
enum Closing {
/// Nothing complete arrived within the idle timeout. Nothing more is read, so a request that
/// crosses the notice is never run: the reply carries `"closed": "idle"` to tell clients it is
/// safe to send that request again on a new connection.
Idle,
/// Junk, an overlong line or a failed read.
Error(String),
}
impl Closing {
fn reply(&self) -> Value {
match self {
Self::Idle => json!({"ok": false, "error": IDLE_CLOSE_ERROR, "closed": "idle"}),
Self::Error(e) => json!({"ok": false, "error": e}),
}
}
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, Closing> {
buf.clear();
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() {
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => "control connection idle read timed out; closing the connection".to_string(),
_ => e.to_string(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => Closing::Idle,
_ => Closing::Error(e.to_string()),
})?;
if n == 0 {
return Ok(false);
@@ -191,7 +250,7 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -
return Ok(true);
}
if buf.len() > max {
return Err(format!("request line longer than {max} bytes; closing the connection"));
return Err(Closing::Error(format!("request line longer than {max} bytes; closing the connection")));
}
// Last line without a newline, then end of stream.
Ok(true)
@@ -204,12 +263,12 @@ fn serve_lines<R: Read, W: Write>(read: R, mut out: W, mut handle: impl FnMut(St
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
let closing = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
Ok(false) => return,
Err(e) => e,
Err(closing) => closing,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
Line::Reject(e) => Closing::Error(e),
Line::Request { id, method, params } => {
let Some(mut r) = handle(method, params) else { return };
if let Some(o) = r.as_object_mut() {
@@ -222,7 +281,7 @@ fn serve_lines<R: Read, W: Write>(read: R, mut out: W, mut handle: impl FnMut(St
}
},
};
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush());
let _ = writeln!(out, "{}", closing.reply()).and_then(|()| out.flush());
return;
}
}
@@ -287,7 +346,9 @@ mod tests {
assert!(connection.requests.try_recv().is_err(), "incomplete input never runs");
let reply: Value = serde_json::from_str(&reply).unwrap();
assert_eq!(reply["ok"], false);
assert!(reply["error"].as_str().unwrap().contains("idle read timed out"));
assert_eq!(reply["error"], IDLE_CLOSE_ERROR);
assert_eq!(reply["closed"], "idle", "clients may resend a request that crossed this notice");
assert!(reply.get("id").is_none());
// A subsequent connection is admitted through the same accounting path.
let mut next = Connection::new(&open, Duration::from_secs(1), |c| c.shutdown(std::net::Shutdown::Write).unwrap());
@@ -413,6 +474,7 @@ mod tests {
assert_eq!(r.len(), 1);
assert_eq!(r[0]["ok"], false);
assert!(r[0]["error"].as_str().unwrap().contains("closing the connection"));
assert!(r[0].get("closed").is_none(), "only an idle close invites a resend: {}", r[0]);
}
#[test]
@@ -502,18 +564,52 @@ mod tests {
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
let read = s.try_clone().unwrap();
serve_lines(read, s, |_, _| Some(json!({"ok": true})));
serve_stream(s, |_, _| Some(json!({"ok": true})));
});
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
let mut text = String::new();
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap();
let mut replies = BufReader::new(c.try_clone().unwrap());
let (mut first, mut second) = (String::new(), String::new());
replies.read_line(&mut first).unwrap();
replies.read_line(&mut second).unwrap();
assert!(first.contains("\"id\":7"), "{first}");
assert!(second.contains("closing the connection"), "{second}");
// A client that keeps sending after the junk: its next line reaches the server after the
// rejection. A socket closed by then answers that line with a reset, which the client reads
// as "connection reset" (os error 10053 / 10054 on Windows) instead of the end of the
// replies. The pause lets a reset arrive before the read.
c.write_all(b"{\"method\":\"y\"}\n").unwrap();
std::thread::sleep(Duration::from_millis(100));
let mut rest = String::new();
let read = replies.read_to_string(&mut rest);
server.join().unwrap();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 2, "{text}");
assert!(lines[0].contains("\"id\":7"));
assert!(lines[1].contains("closing the connection"));
assert!(read.is_ok(), "the close must be clean, not a reset: {read:?}");
assert_eq!(rest, "", "nothing follows the rejection");
}
#[test]
fn a_closing_connection_is_not_held_open_by_a_trickling_peer() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let server_done = Arc::clone(&done);
let server = std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
let t0 = std::time::Instant::now();
close_gracefully(&s);
server_done.store(true, Ordering::SeqCst);
t0.elapsed()
});
let mut c = TcpStream::connect(addr).unwrap();
// one byte every 100 ms: each read returns well within its 500 ms timeout
for _ in 0..100 {
if done.load(Ordering::SeqCst) || c.write_all(b"x").is_err() {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
let drained = server.join().unwrap();
assert!(drained < DRAIN_TIME + Duration::from_secs(1), "drained for {drained:?}");
}
}
+39 -7
View File
@@ -3,7 +3,8 @@ use super::prefs::config_dir;
pub(crate) const HELP: &str = "\
lightcraft — photo library + raw developer
USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported)
USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported; a library's catalog.snap or
folder opens that library)
OPTIONS:
--library DIR open (or create) this library (env LIGHTCRAFT_LIBRARY; default: the last library opened, or
@@ -30,17 +31,48 @@ ENVIRONMENT:
/// The launch arguments' files and folders to import (absolute), and a notice for each one that
/// is not imported (see [`lightcraft_engine::import::launch_path`]; issue #374).
pub(crate) fn launch_imports(args: &[String]) -> (Vec<String>, Vec<String>) {
pub(crate) fn launch_imports(args: &[String]) -> LaunchArgs {
let cwd = std::env::current_dir().ok();
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
launch_imports_in(args, cwd.as_deref(), home.as_deref())
}
pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> (Vec<String>, Vec<String>) {
use lightcraft_engine::import::{LaunchPath, launch_path};
let (mut files, mut notices) = (Vec::new(), Vec::new());
/// The library a launch argument names, after `--library` (`flag`) and `LIGHTCRAFT_LIBRARY` (`env`):
/// the library to pass on as the flag, and whether the argument chose it (it is then remembered).
pub(crate) fn launch_library_choice(
flag: Option<std::path::PathBuf>,
env: Option<&std::path::PathBuf>,
argument: Option<std::path::PathBuf>,
) -> (Option<std::path::PathBuf>, bool) {
match (flag, env, argument) {
(Some(flag), _, _) => (Some(flag), false),
(None, None, Some(argument)) => (Some(argument), true),
_ => (None, false),
}
}
/// What the launch arguments ask for: files and folders to import, a library to open (a library's `catalog.snap`
/// or folder, double-clicked in the file manager), and a notice for each argument
/// left alone.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct LaunchArgs {
pub(crate) files: Vec<String>,
pub(crate) library: Option<std::path::PathBuf>,
pub(crate) notices: Vec<String>,
}
pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> LaunchArgs {
use lightcraft_engine::import::{LaunchPath, launch_deadline, launch_path_until};
let (mut files, mut notices, mut library) = (Vec::new(), Vec::new(), None);
// one deadline for every argument's library check: they all run before the window opens
let deadline = launch_deadline();
for a in args {
match launch_path(a, cwd, home, lightcraft_engine::devices::dcim_in) {
match launch_path_until(a, cwd, home, lightcraft_engine::devices::dcim_in, deadline) {
Some(LaunchPath::Library(dir)) if library.is_none() => library = Some(std::path::PathBuf::from(dir)),
Some(LaunchPath::Library(dir)) => {
log::warn!("one library at a time: not opening {dir} given at launch");
notices.push(format!("{dir} was not opened: LightCraft opens one library at a time. Open it with File ▸ Open Library…"));
}
Some(LaunchPath::Import(p)) => files.push(p),
Some(LaunchPath::Refused { path, why }) => {
log::warn!("not importing {path} given at launch: {why}");
@@ -50,7 +82,7 @@ pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>,
None => {}
}
}
(files, notices)
LaunchArgs { files, library, notices }
}
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
+13 -1
View File
@@ -167,7 +167,19 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
let message = message.strip_suffix('\n').unwrap_or(message);
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
// A message can carry text from files and peers (a file name, a rejected value): it must not be able to start a
// record of its own. Later lines of a multi-line message (a panic report) are indented, so none begins like a
// record; other control characters (a bare CR, an escape sequence) are shown escaped.
let mut safe = String::with_capacity(message.len());
for c in message.chars() {
match c {
'\n' => safe.push_str("\n "),
'\t' => safe.push(c),
c if c.is_control() => safe.extend(c.escape_default()),
c => safe.push(c),
}
}
format!("{ts} {level:<5} [{thread}] {target}: {safe}\n")
}
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
+6 -2
View File
@@ -167,7 +167,11 @@ fn a_line_carries_time_level_thread_target_and_message() {
"2026-10-08T07:59:17.728Z INFO [main] lightcraft: library /photos: 12 photos\n"
);
// A multi-line message keeps its lines; the record still ends in one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
// later lines are indented and control characters escaped, so a message cannot forge a record
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n"));
let forged = format_line("t", log::Level::Info, "w", "x", "name\r\n2026-01-01T00:00:00Z ERROR [main] x: fake\u{1b}[2J");
assert!(forged.lines().skip(1).all(|l| l.starts_with(' ')), "{forged:?}");
assert!(!forged.contains('\r') && !forged.contains('\u{1b}'), "{forged:?}");
}
#[test]
@@ -357,7 +361,7 @@ fn a_panic_report_goes_to_the_file_and_never_deadlocks() {
logger.record_panic("main", "while the sink is held");
}
let text = read(&path);
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\nboom\n"), "{text}");
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\n boom\n"), "{text}");
assert!(!text.contains("while the sink is held"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
+121 -6
View File
@@ -35,8 +35,12 @@ mod hdr_display;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
#[cfg(any(target_os = "linux", windows))]
mod profile_file;
#[cfg(target_os = "macos")]
mod screen_profile;
#[cfg(windows)]
mod win_screen_profile;
mod window_gpu;
use dialog_filter::FileDialogExt as _;
@@ -55,7 +59,10 @@ use gpu_crash::{gpu_crash_check, gpu_lost_check_at, gpu_lost_marker_path, gpu_lo
use gpu_crash::{gpu_crash_check_at, gpu_crash_notice, window_wgpu_options};
#[cfg(test)]
use launch::launch_imports_in;
use launch::{HELP, control_port_from, launch_imports, log_dir, panic_log_path_with, startup_failed, stopped_text, stopped_while_running};
use launch::{
HELP, LaunchArgs, control_port_from, launch_imports, launch_library_choice, log_dir, panic_log_path_with, startup_failed, stopped_text,
stopped_while_running,
};
#[cfg(test)]
use platform::{explorer_select_arg, explorer_select_command, windows_open_url_command};
use prefs::{PrefsWriter, as_remembered, load_prefs, prefs_path};
@@ -76,12 +83,77 @@ fn app_icon() -> egui::IconData {
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
struct App(LightcraftApp, PrefsWriter, Option<WindowTextures>, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
/// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu
/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]).
struct WindowTextures {
device: eframe::wgpu::Device,
queue: eframe::wgpu::Queue,
renderer: std::sync::Arc<egui::mutex::RwLock<eframe::egui_wgpu::Renderer>>,
}
impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures {
fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option<egui::TextureId>) -> Option<egui::TextureId> {
let view = frame.texture.create_view(&Default::default());
let mut r = self.renderer.write();
let filter = eframe::wgpu::FilterMode::Linear;
Some(match id {
Some(id) => {
r.update_egui_texture_from_wgpu_texture(&self.device, &view, filter, id);
id
}
None => r.register_native_texture(&self.device, &view, filter),
})
}
fn free(&mut self, id: egui::TextureId) {
self.renderer.write().free_texture(&id);
}
fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option<egui::ColorImage> {
match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) {
Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())),
Err(e) => {
log::warn!("gpu: a view can't be read back for the screenshot: {e}");
None
}
}
}
}
/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the
/// loupe's drafts are drawn straight from the GPU; the textures they leave are shown through
/// [`WindowTextures`] once that worked. Otherwise the GPU renderer makes a device of its own, as
/// before, and every render comes back as pixels.
fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context) -> WindowTextures {
let (device, queue, info) = (rs.device.clone(), rs.queue.clone(), rs.adapter.get_info());
let ctx = ctx.clone();
// before the first frame's GPU warm-up can start a device of its own
lightcraft_engine::gpu::set_window_device_pending(true);
let spawned = std::thread::Builder::new().name("lc-gpu-window".into()).spawn(move || {
match lightcraft_engine::gpu::adopt_window_device(device, queue, info) {
Ok(()) => log::info!("gpu: rendering on the window's device"),
Err(e) => log::info!("gpu: renders come back as pixels: {e}"),
}
ctx.request_repaint();
});
if let Err(e) = spawned {
log::warn!("gpu: {e}");
lightcraft_engine::gpu::set_window_device_pending(false);
}
WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() }
}
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
// The transparency-capable DirectComposition window is a presentation workaround;
// translucent UI layers (disabled panels, modal dimming) must not reveal the desktop.
egui::Color32::from_rgb(12, 12, 12).to_normalized_gamma_f32()
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if let Some(m) = self.2.as_mut()
if let Some(m) = self.3.as_mut()
&& m.update(&mut self.0, ctx)
&& lightcraft_ui_egui::panels::notices::may_close(&mut self.0)
{
@@ -101,6 +173,13 @@ impl eframe::App for App {
}
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);
// the GPU renderer adopted the window's device: its renders can be drawn as they are
if self.2.is_some()
&& lightcraft_engine::gpu::on_window_device()
&& let Some(t) = self.2.take()
{
self.0.renderer.set_screen_textures(Box::new(t));
}
self.0.ui(ui);
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
@@ -116,6 +195,12 @@ impl eframe::App for App {
if !self.0.shutdown(EXIT_WAIT) {
log::warn!("quit: background work was still running after {EXIT_WAIT:?}");
}
// macOS only: the process ends below without running destructors, and only the lock's
// `Drop` removes `catalog.lock.owner` (the OS frees the lock, not the note), so let go of
// the library's lock here, saved or not (we leave either way). Elsewhere eframe drops the
// app after this and the session's last writes (face data) still go out under the lock.
#[cfg(target_os = "macos")]
self.0.session.release_library_lock();
// macOS (#1331): end the process here, before eframe tears the window down, as Quit from
// the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's
// content view and restores its class on teardown; AppKit's Touch Bar support observes
@@ -192,7 +277,11 @@ fn main() -> eframe::Result {
}
// what the arguments name, resolved now: an empty or relative argument never becomes a drive
// root, and a whole drive or home folder is not walked (issue #374)
let (files, launch_notices) = launch_imports(&files);
let LaunchArgs { files, library: launch_library, notices: launch_notices } = launch_imports(&files);
// a library double-clicked (its catalog.snap or folder) is the one that opens, not the last one
// used; --library and LIGHTCRAFT_LIBRARY still win
let env_library: Option<std::path::PathBuf> = std::env::var_os("LIGHTCRAFT_LIBRARY").filter(|p| !p.is_empty()).map(Into::into);
let (library_dir, opened_by_argument) = launch_library_choice(library_dir, env_library.as_ref(), launch_library);
let (prefs, prefs_warning, keep_prefs_file) = load_prefs(in_memory);
// the saved language from the start, so a failed start is reported in it too
if let Some(ui) = &prefs {
@@ -203,7 +292,7 @@ fn main() -> eframe::Result {
let launch = lightcraft_ui_egui::panels::library_problem::launch_plan(
in_memory,
library_dir,
std::env::var_os("LIGHTCRAFT_LIBRARY").filter(|p| !p.is_empty()).map(Into::into),
env_library,
prefs.as_ref().map(|u| &u.settings),
lightcraft_engine::library::default_dir(),
);
@@ -214,8 +303,11 @@ fn main() -> eframe::Result {
lightcraft_engine::gpu::set_enabled(gpu_on);
// the window's renderer: probed (Windows) and with a fallback chain, so a driver that can't
// build egui's pipeline never kills the start-up
let compose_window =
prefs.as_ref().map_or_else(|| lightcraft_ui_egui::state::AppSettings::default().compose_window, |ui| ui.settings.compose_window)
&& std::env::var_os("WGPU_BACKEND").is_none();
let win_files = std::sync::Arc::new(window_files(in_memory));
let window_gpu::Chosen { renderer, wgpu_options, which: window_renderer, notice: window_notice } = window_gpu::choose(&win_files);
let window_gpu::Chosen { renderer, wgpu_options, which: window_renderer, notice: window_notice } = window_gpu::choose(&win_files, compose_window);
win_files.arm(window_renderer);
let win_files_app = win_files.clone();
// the window came up: a failure after this is LightCraft stopping, not a start that failed
@@ -228,6 +320,7 @@ fn main() -> eframe::Result {
viewport: as_remembered(egui::ViewportBuilder::default().with_title("LightCraft"), opens_as)
.with_min_inner_size(lightcraft_ui_egui::window_place::MIN_SIZE)
.with_drag_and_drop(true)
.with_transparent(window_gpu::composes_window(compose_window, window_renderer))
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
@@ -282,6 +375,7 @@ fn main() -> eframe::Result {
app.notices.extend(launch_notices);
app.notices.extend(window_notice);
app.gpu_notice = true;
app.disk_space_notice = true;
// an empty library opens where Import is offered (a grid, with the sidebar); before
// the snapshot below, so this alone isn't written to the settings file
if problem.is_none() && files.is_empty() {
@@ -295,6 +389,20 @@ fn main() -> eframe::Result {
keep_file: keep_prefs_file,
..Default::default()
};
// a library opened from its catalog file is the one in use from now on, as Open Library makes it
// (after the snapshot above, so the writer saves it)
if opened_by_argument
&& problem.is_none()
&& let Some(dir) = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.to_string_lossy().into_owned())
{
let settings = &mut app.ui.settings;
if settings.library_path != dir && !settings.library_path.is_empty() {
let previous = settings.library_path.clone();
lightcraft_ui_egui::panels::settings::remember_library(&mut settings.recent_libraries, &previous);
}
lightcraft_ui_egui::panels::settings::remember_library(&mut settings.recent_libraries, &dir);
settings.library_path = dir;
}
// after the snapshot above, so the writer saves the switched-off preference
if let Some(notice) = gpu_crash {
app.ui.settings.gpu = false;
@@ -322,9 +430,16 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
let menu =
(std::env::var_os("LIGHTCRAFT_NO_NATIVE_MENU").is_none()).then(|| native_menu::NativeMenu::install(&mut app, &cc.egui_ctx));
// the GPU renderer on the window's device, when GPU rendering is on
// (LIGHTCRAFT_GPU_WINDOW=0: a device of its own, renders read back - for comparison or a driver
// that misbehaves with compute and drawing on one device)
let window_device = std::env::var_os("LIGHTCRAFT_GPU_WINDOW").is_none_or(|v| v != "0");
let window_textures =
cc.wgpu_render_state.as_ref().filter(|_| gpu_on && window_device).map(|rs| adopt_window_device(rs, &cc.egui_ctx));
Ok(Box::new(App(
app,
writer,
window_textures,
#[cfg(target_os = "macos")]
menu,
)))
+290 -59
View File
@@ -118,6 +118,74 @@ impl Item {
}
}
impl SyncRow for Item {
fn label(&self) -> &str {
&self.label
}
fn show_label(&mut self, label: String) {
match &self.handle {
Handle::Plain(h) => h.set_text(label.replace('&', "&&")),
Handle::Check(h) => h.set_text(label.replace('&', "&&")),
}
self.label = label;
}
fn enabled(&self) -> bool {
self.enabled
}
fn show_enabled(&mut self, enabled: bool) {
match &self.handle {
Handle::Plain(h) => h.set_enabled(enabled),
Handle::Check(h) => h.set_enabled(enabled),
}
self.enabled = enabled;
}
fn show_checked(&mut self, checked: bool) {
if let Handle::Check(h) = &self.handle {
// also resyncs after AppKit toggled it on click
if h.is_checked() != checked {
h.set_checked(checked);
}
self.checked = Some(checked);
}
}
}
/// What the per-frame sync needs of a native row, so it can be run on stand-ins without a
/// main-thread `muda::Menu` (as [`SwapTarget`] does for the swap).
trait SyncRow {
fn label(&self) -> &str;
fn show_label(&mut self, label: String);
fn enabled(&self) -> bool;
fn show_enabled(&mut self, enabled: bool);
/// Only a row that is a check item takes it.
fn show_checked(&mut self, checked: bool);
}
/// Puts each model row's live label, enabled and checked state on its own native row, found by
/// the row's native id (two rows may run the same command and params).
fn sync_rows<R: SyncRow>(nodes: &[MenuNode], items: &mut HashMap<String, R>, keymap: &lightcraft_ui_egui::shortcuts::Keymap) {
let mut rows = Vec::new();
native_rows(nodes, &mut RowIds::default(), &mut rows);
for (native_id, node) in rows {
let MenuNode::Item { id, params, label, shortcut, enabled, checked } = node else { continue };
let Some(it) = items.get_mut(&native_id) else { continue };
let (native_label, _) = native_item_presentation(keymap, id, params, label, shortcut.as_deref());
if it.label() != native_label {
it.show_label(native_label);
}
if it.enabled() != *enabled {
it.show_enabled(*enabled);
}
if let Some(c) = checked {
it.show_checked(*c);
}
}
}
/// The accelerator the native item has after trying to put `want` on it: `want` when the native
/// call worked, else what it had, so the caller sees the mismatch and tries again.
fn settled(had: Option<Accelerator>, want: Option<Accelerator>, native_call_worked: bool) -> Option<Accelerator> {
@@ -295,12 +363,64 @@ fn label_text(s: &str) -> String {
lightcraft_ui_egui::i18n::tr(s).replace('&', "&&")
}
/// Drop a trailing separator (left behind when an item moved to the app menu).
fn tidy_separators(mut nodes: Vec<MenuNode>) -> Vec<MenuNode> {
while matches!(nodes.last(), Some(MenuNode::Separator)) {
nodes.pop();
/// Drop the separators left behind when an item moved to the app menu: a leading one, a trailing
/// one and the second of two in a row.
fn tidy_separators(nodes: Vec<MenuNode>) -> Vec<MenuNode> {
let mut out: Vec<MenuNode> = Vec::with_capacity(nodes.len());
for node in nodes {
if node == MenuNode::Separator && out.last().is_none_or(|last| *last == MenuNode::Separator) {
continue;
}
out.push(node);
}
while out.last() == Some(&MenuNode::Separator) {
out.pop();
}
out
}
/// The model's rows of one menu as the native menu installs them: About, Settings and Quit live in
/// the app menu on macOS.
fn install_nodes(nodes: &[MenuNode]) -> Vec<MenuNode> {
let kept = nodes.iter().filter(|n| !matches!(n, MenuNode::Item { id, .. } if id == "app.about" || id == SETTINGS || id == QUIT));
tidy_separators(kept.cloned().collect())
}
/// Native (muda) ids, one per menu row. muda ids must be unique, but the model may hold the same
/// command and params twice (`dialog.export` is File ▸ Export… and Export with Preset ▸ Custom…;
/// `dialog.newAlbum` is in File and in Photo ▸ Add to Album), so a repeated key gets an occurrence
/// suffix. The first row keeps the plain [`MenuNode::key`]. Rows are numbered in model order, so
/// the install and the per-frame sync, which both walk the model in that order, agree.
#[derive(Default)]
struct RowIds {
seen: HashMap<String, usize>,
}
impl RowIds {
/// The row's native id, and whether an earlier row already has the same command and params.
fn next(&mut self, id: &str, params: &Value) -> (String, bool) {
let key = MenuNode::key(id, params);
let n = self.seen.entry(key.clone()).or_insert(0);
*n += 1;
if *n == 1 { (key, false) } else { (format!("{key}#{n}"), true) }
}
}
/// The key a row is installed with. A repeated row has none: AppKit would list one key twice, and
/// the first row of the command keeps it (a click on either row runs the command).
fn row_accelerator(native_key: Option<&str>, repeated: bool) -> Option<Accelerator> {
native_key.filter(|s| !repeated && !CONTEXTUAL.contains(s)).and_then(accelerator)
}
/// Every item of the model with its native id, in model order.
fn native_rows<'a>(nodes: &'a [MenuNode], ids: &mut RowIds, out: &mut Vec<(String, &'a MenuNode)>) {
for n in nodes {
match n {
MenuNode::Item { id, params, .. } => out.push((ids.next(id, params).0, n)),
MenuNode::Submenu { children, .. } => native_rows(children, ids, out),
MenuNode::Separator => {}
}
}
nodes
}
impl NativeMenu {
@@ -371,6 +491,8 @@ impl NativeMenu {
}
let _ = self.menu.append(&app_menu);
let mut ids = RowIds::default();
let mut help_menu = None;
for (title, nodes) in &bar {
let sub = Submenu::new(label_text(title), true);
if title == "Window" {
@@ -380,16 +502,10 @@ impl NativeMenu {
&PredefinedMenuItem::separator(),
]);
}
// About and Settings live in the app menu on macOS
let nodes: Vec<MenuNode> = nodes
.iter()
.filter(|n| !matches!(n, MenuNode::Item { id, .. } if id == "app.about" || id == SETTINGS || id == QUIT))
.cloned()
.collect();
let nodes = tidy_separators(nodes);
let nodes = install_nodes(nodes);
// Swapping an item in the Help menu leaves the old row in place and adds a second one
// (measured on macOS 27 with muda 0.21): the Help menu is not addressed row for row.
self.append_nodes(&sub, &nodes, &app.ui.settings.keymap, title != "Help");
self.append_nodes(&sub, &nodes, &app.ui.settings.keymap, title != "Help", &mut ids);
if title == "File" {
// ⌘W, the system's own item
let _ = sub.append_items(&[
@@ -405,11 +521,16 @@ impl NativeMenu {
sub.set_as_windows_menu_for_nsapp();
}
if title == "Help" {
sub.set_as_help_menu_for_nsapp();
help_menu = Some(sub.clone());
}
let _ = self.menu.append(&sub);
}
self.menu.init_for_nsapp();
// muda finds the submenu through the main menu installed just above; asked earlier it does
// nothing, and AppKit never learns which menu is the Help menu
if let Some(help) = help_menu {
help.set_as_help_menu_for_nsapp();
}
self.text_focus = false;
self.capturing = false;
self.accelerators_pending = false;
@@ -418,7 +539,7 @@ impl NativeMenu {
/// Install translated rows with their effective accelerators, preserving hint-only keys.
/// `swappable`: whether its items may be replaced to drop their key (see `Item::swappable`).
fn append_nodes(&mut self, sub: &Submenu, nodes: &[MenuNode], keymap: &lightcraft_ui_egui::shortcuts::Keymap, swappable: bool) {
fn append_nodes(&mut self, sub: &Submenu, nodes: &[MenuNode], keymap: &lightcraft_ui_egui::shortcuts::Keymap, swappable: bool, ids: &mut RowIds) {
for n in nodes {
match n {
MenuNode::Separator => {
@@ -426,16 +547,13 @@ impl NativeMenu {
}
MenuNode::Submenu { label, children } => {
let s = Submenu::new(label_text(label), true);
self.append_nodes(&s, children, keymap, swappable);
self.append_nodes(&s, children, keymap, swappable, ids);
let _ = sub.append(&s);
}
MenuNode::Item { id, params, label, shortcut, enabled, checked } => {
let key = MenuNode::key(id, params);
if self.items.contains_key(&key) {
continue; // muda ids must be unique
}
let (key, repeated) = ids.next(id, params);
let (native_label, native_key) = native_item_presentation(keymap, id, params, label, shortcut.as_deref());
let accel = native_key.filter(|s| !CONTEXTUAL.contains(s)).and_then(accelerator);
let accel = row_accelerator(native_key, repeated);
let handle = match checked {
Some(c) => {
let it = CheckMenuItem::with_id(key.clone(), native_label.replace('&', "&&"), *enabled, *c, accel);
@@ -489,9 +607,7 @@ impl NativeMenu {
// events never reach `shortcuts::handle`, so this is the one guard for AppKit's
// accelerators and clicks: while the blocking library window or a quit/settings notice
// owns input, a queued command is dropped (Quit stays for the existing confirmation).
let (cmd, params) = if key == QUIT {
(key, serde_json::json!({}))
} else if key == "app.about" || key == SETTINGS {
let (cmd, params) = if key == QUIT || key == "app.about" || key == SETTINGS {
(key, serde_json::json!({}))
} else if let Some(it) = self.items.get(&key) {
(it.cmd.clone(), it.params.clone())
@@ -508,41 +624,10 @@ impl NativeMenu {
// to, so the sync below runs in this same frame and no key reaches the menu in between)
self.rebuild(app);
}
/// Synchronize live labels and states; accelerator ownership changes already triggered a rebuild.
fn walk(nodes: &[MenuNode], items: &mut HashMap<String, Item>, keymap: &lightcraft_ui_egui::shortcuts::Keymap) {
for n in nodes {
match n {
MenuNode::Submenu { children, .. } => walk(children, items, keymap),
MenuNode::Item { id, params, label, shortcut, enabled, checked } => {
let Some(it) = items.get_mut(&MenuNode::key(id, params)) else { continue };
let (native_label, _) = native_item_presentation(keymap, id, params, label, shortcut.as_deref());
if it.label != native_label {
match &it.handle {
Handle::Plain(h) => h.set_text(native_label.replace('&', "&&")),
Handle::Check(h) => h.set_text(native_label.replace('&', "&&")),
}
it.label = native_label;
}
if it.enabled != *enabled {
match &it.handle {
Handle::Plain(h) => h.set_enabled(*enabled),
Handle::Check(h) => h.set_enabled(*enabled),
}
it.enabled = *enabled;
}
if let (Handle::Check(h), Some(c)) = (&it.handle, checked) {
// also resyncs after AppKit toggled it on click
if h.is_checked() != *c {
h.set_checked(*c);
}
it.checked = Some(*c);
}
}
MenuNode::Separator => {}
}
}
}
walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::<Vec<_>>(), &mut self.items, &app.ui.settings.keymap);
// Synchronize live labels and states row by row (accelerator ownership changes already
// triggered a rebuild).
let all: Vec<MenuNode> = bar.into_iter().flat_map(|(_, v)| v).collect();
sync_rows(&all, &mut self.items, &app.ui.settings.keymap);
let focus = ctx.egui_wants_keyboard_input();
let capturing = app.recording_shortcut.is_some();
@@ -570,6 +655,24 @@ impl NativeMenu {
mod tests {
use super::*;
/// An item that moves to the app menu (Settings…) can sit between two separators, or open or
/// close the menu's list: the rows left behind keep at most one separator between them.
#[test]
fn rows_left_after_a_move_keep_single_separators() {
let item = |id: &str| MenuNode::Item {
id: id.to_string(),
label: id.to_string(),
shortcut: None,
enabled: true,
checked: None,
params: Value::Null,
};
let sep = || MenuNode::Separator;
let tidy = tidy_separators(vec![sep(), item("a"), sep(), sep(), item("b"), sep(), sep()]);
assert_eq!(tidy, vec![item("a"), sep(), item("b")]);
assert_eq!(tidy_separators(vec![sep(), sep()]), Vec::<MenuNode>::new());
}
/// The menu model's titles stay English, so only the language can tell the native menu to
/// rebuild its titles (and the macOS app menu): every language switch — also between two CJK
/// languages — must change the structure key.
@@ -587,6 +690,134 @@ mod tests {
set_language(Locale::En);
}
/// Every row of the model gets its own native row and keeps its own label, and a click on a
/// native id runs that row's command (two rows may share a command and params).
#[test]
fn rows_sharing_a_command_get_their_own_native_ids_and_labels() {
let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default());
let bar = menu_bar(&app);
let all: Vec<MenuNode> = bar.iter().flat_map(|(_, v)| v.clone()).collect();
let mut rows = Vec::new();
native_rows(&all, &mut RowIds::default(), &mut rows);
fn count(n: &[MenuNode]) -> usize {
n.iter()
.map(|x| match x {
MenuNode::Item { .. } => 1,
MenuNode::Submenu { children, .. } => count(children),
MenuNode::Separator => 0,
})
.sum()
}
assert_eq!(rows.len(), count(&all));
let ids: HashSet<&str> = rows.iter().map(|(id, _)| id.as_str()).collect();
assert_eq!(ids.len(), rows.len(), "a native id per row");
// The install walks each menu as `install_nodes` leaves it, the per-frame sync walks the whole
// bar: a row the menu has must get the same id, so the same node (label, command, params),
// from both, and a click on its id runs that row's command.
let mut installed = Vec::new();
let mut install_ids = RowIds::default();
let menus: Vec<Vec<MenuNode>> = bar.iter().map(|(_, nodes)| install_nodes(nodes)).collect();
for nodes in &menus {
native_rows(nodes, &mut install_ids, &mut installed);
}
let synced: HashMap<&str, &MenuNode> = rows.iter().map(|(id, n)| (id.as_str(), *n)).collect();
for (nid, n) in &installed {
assert_eq!(synced.get(nid.as_str()), Some(n), "{nid}");
}
for (cmd, labels) in [("dialog.export", ["Export…", "Custom…"]), ("dialog.newAlbum", ["New Album…", "New Album…"])] {
let own: Vec<(&str, &str)> = installed
.iter()
.filter_map(|(nid, n)| match n {
MenuNode::Item { id, label, params, .. } if id == cmd && params.is_null() => Some((nid.as_str(), label.as_str())),
_ => None,
})
.collect();
assert_eq!(own.len(), 2, "{cmd} is in two menus");
assert_ne!(own[0].0, own[1].0, "{cmd}: one native id per row");
assert_eq!([own[0].1, own[1].1], labels, "{cmd}: each row keeps its label");
}
// A repeated row is installed without its key (AppKit would list one key twice).
assert_eq!(row_accelerator(Some("G"), false), accelerator("G"));
assert_eq!(row_accelerator(Some("G"), true), None);
let mut ids = RowIds::default();
assert_eq!(ids.next("view.layoutImage", &Value::Null), ("view.layoutImage".to_string(), false));
assert_eq!(ids.next("view.layoutImage", &Value::Null), ("view.layoutImage#2".to_string(), true));
}
/// A native row's shown state, to run the per-frame sync without a main-thread `muda::Menu`.
#[derive(Debug, PartialEq)]
struct FakeRow {
label: String,
enabled: bool,
checked: Option<bool>,
}
impl SyncRow for FakeRow {
fn label(&self) -> &str {
&self.label
}
fn show_label(&mut self, label: String) {
self.label = label;
}
fn enabled(&self) -> bool {
self.enabled
}
fn show_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
}
fn show_checked(&mut self, checked: bool) {
self.checked = Some(checked);
}
}
/// Two rows with the same command and params keep their own label, enabled and checked state
/// when the model changes (the sync once wrote the last row's state onto the first).
#[test]
fn the_sync_updates_rows_sharing_a_command_independently() {
use lightcraft_ui_egui::i18n::{Locale, set_language};
set_language(Locale::En);
let keymap = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()).ui.settings.keymap.clone();
let item = |cmd: &str, label: &str, enabled: bool, checked: Option<bool>| MenuNode::Item {
id: cmd.into(),
params: Value::Null,
label: label.into(),
shortcut: None,
enabled,
checked,
};
let model = |a: (&str, bool, Option<bool>), b: (&str, bool, Option<bool>), c: (&str, bool, Option<bool>), d: (&str, bool, Option<bool>)| {
vec![
item("dialog.export", a.0, a.1, a.2),
MenuNode::Separator,
MenuNode::Submenu { label: "Export with Preset".into(), children: vec![item("dialog.export", b.0, b.1, b.2)] },
item("view.toggle", c.0, c.1, c.2),
MenuNode::Submenu { label: "More".into(), children: vec![item("view.toggle", d.0, d.1, d.2)] },
]
};
// what the native rows show after the install
let installed = model(("Export…", true, None), ("Custom…", true, None), ("Show", true, Some(false)), ("Show", true, Some(false)));
let mut rows = Vec::new();
native_rows(&installed, &mut RowIds::default(), &mut rows);
let mut items: HashMap<String, FakeRow> = rows
.iter()
.filter_map(|(nid, n)| match n {
MenuNode::Item { label, enabled, checked, .. } => {
Some((nid.clone(), FakeRow { label: label.clone(), enabled: *enabled, checked: *checked }))
}
_ => None,
})
.collect();
assert_eq!(items.len(), 4, "a native row for each of the four rows");
// the model changes: each row of a pair gets a different state
let live = model(("Export…", false, None), ("Custom…", true, None), ("Show", true, Some(true)), ("Hide", false, Some(false)));
sync_rows(&live, &mut items, &keymap);
let shown: Vec<&FakeRow> = rows.iter().map(|(nid, _)| &items[nid]).collect();
let row = |label: &str, enabled: bool, checked: Option<bool>| FakeRow { label: label.into(), enabled, checked };
assert_eq!(shown[0], &row("Export…", false, None), "File ▸ Export… keeps its label and is disabled alone");
assert_eq!(shown[1], &row("Custom…", true, None), "Custom… stays enabled and keeps its label");
assert_eq!(shown[2], &row("Show", true, Some(true)), "the first toggle is checked alone");
assert_eq!(shown[3], &row("Hide", false, Some(false)), "the second toggle has its own label and state");
}
#[test]
fn accelerators_yield_to_text_focus_and_shortcut_recording() {
let g = accelerator("G");
+5
View File
@@ -67,6 +67,11 @@ fn decode_saved_ui(bytes: &[u8]) -> Result<(UiState, bool), String> {
if recovered {
fields.remove("docking");
}
// A settings file from before the startup dialog existed has no `seenVersion` key: the file
// is there, so this is an installation that has been run, due What's New — never the
// first-run tour. Shared with the browser's loader, which runs the same migration on its
// stored `ui.json` (`startup::migrate_legacy_seen_version` carries the full story).
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
let ui = serde_json::from_value(saved).map_err(|error| error.to_string())?;
Ok((ui, recovered))
}
+87
View File
@@ -0,0 +1,87 @@
//! Reading a display's ICC profile file for the screen-profile services (`colord` on Linux,
//! `win_screen_profile` on Windows).
use std::path::{Path, PathBuf};
use std::time::SystemTime;
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
pub const MAX_PROFILE: u64 = 16 << 20;
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
pub fn load(path: &Path) -> Option<Vec<u8>> {
use std::io::Read as _;
let file = std::fs::File::open(path).ok()?;
let mut bytes = Vec::new();
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
}
/// A profile file read again only when it changes: the services are asked about once a second, and
/// calibration software rewrites its profile under the same name.
#[cfg_attr(not(windows), allow(dead_code))]
#[derive(Default)]
pub struct Cached {
/// The file last read: its path, length and modification time.
stamp: Option<(PathBuf, u64, Option<SystemTime>)>,
bytes: Option<Vec<u8>>,
}
#[cfg_attr(not(windows), allow(dead_code))]
impl Cached {
/// The bytes of profile file `path`, read again when it isn't the file read last time or has
/// changed since (see [`load`]).
pub fn read(&mut self, path: &Path) -> Option<Vec<u8>> {
let stamp = std::fs::metadata(path).ok().map(|m| (path.to_path_buf(), m.len(), m.modified().ok()));
if stamp.is_none() || stamp != self.stamp {
self.bytes = stamp.as_ref().and_then(|_| load(path));
self.stamp = stamp;
}
self.bytes.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn profile_files_are_read_with_a_size_cap() {
let dir = std::env::temp_dir().join(format!("profile-file-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let small = dir.join("small.icc");
std::fs::write(&small, b"acsp").unwrap();
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
let empty = dir.join("empty.icc");
std::fs::write(&empty, b"").unwrap();
assert_eq!(load(&empty), None);
assert_eq!(load(&dir.join("missing.icc")), None);
let big = dir.join("big.icc");
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
assert_eq!(load(&big), None);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_cached_profile_is_read_again_when_the_file_changes() {
let dir = std::env::temp_dir().join(format!("profile-cache-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (a, b) = (dir.join("a.icc"), dir.join("b.icc"));
std::fs::write(&a, b"first").unwrap();
std::fs::write(&b, b"other").unwrap();
let mut cache = Cached::default();
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
// another monitor's profile
assert_eq!(cache.read(&b).as_deref(), Some(&b"other"[..]));
// rewritten under the same name (a different length, so the change shows whatever the
// file system's time resolution)
std::fs::write(&b, b"calibrated").unwrap();
assert_eq!(cache.read(&b).as_deref(), Some(&b"calibrated"[..]));
// gone: nothing, then read again once it is back
std::fs::remove_file(&b).unwrap();
assert_eq!(cache.read(&b), None);
std::fs::write(&b, b"back").unwrap();
assert_eq!(cache.read(&b).as_deref(), Some(&b"back"[..]));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+19 -4
View File
@@ -144,7 +144,11 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
// Linux: the profile the desktop assigns in colord, read off the UI thread
#[cfg(target_os = "linux")]
screen_profile: Some(colord::service()),
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
// Windows: the profile it uses for the window's monitor, unless it colour-manages the
// desktop itself (HDR, Auto Color Management)
#[cfg(windows)]
screen_profile: win_screen_profile::service(cc),
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
screen_profile: None,
pick_display_profile: Some(Box::new(|| {
let mut d = file_dialog()
@@ -253,8 +257,12 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
let (mut s, problem) = match launch {
Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None),
Launch::Open { dir, .. } => open_library_session(in_memory, dir.clone(), seed_demo),
Launch::Open { dir, remembered, .. } => open_library_session(in_memory, dir.clone(), *remembered, seed_demo),
};
// lens profiles from the app's own lensfun copy, offered on the first launch (not for a throwaway session)
if !in_memory {
s = s.with_default_lens_database().with_lens_auto_download();
}
s.face_models_dir = lightcraft_engine::config::default_face_models_dir();
s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME));
// Control requests are answered on the UI thread: Add to Apple Photos must not wait there
@@ -267,7 +275,9 @@ pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) ->
/// If the library can't be opened the session is empty and in memory — never seeded with the
/// demo photos, never written anywhere — and the problem is returned: the window then says so
/// and offers Try Again / Choose Another Library… / Continue Without Saving / Quit (issue #100).
fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
/// So is a `remembered` library (the one last opened) that isn't there any more: opening would
/// make a new, empty one in its place, e.g. on an unmounted drive's path (issue #3239).
fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, remembered: bool, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
if in_memory {
return (if seed_demo { Session::with_demo() } else { Session::new() }.with_fs().with_default_denoise_models().with_system_clock(), None);
}
@@ -276,9 +286,14 @@ fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_d
log::warn!("no library location (set --library or LIGHTCRAFT_LIBRARY)");
return (unopened(), Some(LibraryProblem::new("", "There is no home folder to keep the library in. Choose a folder for it.")));
};
if remembered && let Some(why) = lightcraft_ui_egui::panels::library_problem::missing_library_reason(&dir) {
log::error!("library {} can't be opened: {why}", dir.display());
// Try Again must not make one there either (an empty mount point, issue #3239)
return (unopened(), Some(LibraryProblem { existing_only: true, ..LibraryProblem::new(dir.to_string_lossy(), why) }));
}
let t0 = std::time::Instant::now();
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
match s.open_library(&dir, seed_demo) {
match s.open_library(&dir, seed_demo && !remembered) {
Ok(r) => {
let (replayed, torn) = (r.replayed, r.torn_bytes);
log::info!(
+200 -3
View File
@@ -1,5 +1,21 @@
use super::*;
#[test]
fn desktop_clear_color_stays_opaque_with_a_modal_open() {
let mut app = App(
LightcraftApp::new(Session::new(), Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
app.0.run("app.settings", serde_json::json!({})).unwrap();
assert!(app.0.ui.dialog.is_some());
for visuals in [egui::Visuals::dark(), egui::Visuals::light()] {
assert_eq!(eframe::App::clear_color(&app, &visuals)[3], 1.0);
}
}
fn dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-app-prefs-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
@@ -14,22 +30,62 @@ fn launch_arguments_never_walk_a_drive_or_the_home_folder() {
let home = dir("launch");
std::fs::create_dir_all(home.join("Trip")).unwrap();
let args: Vec<String> = ["", " ", ".", "Trip", &home.to_string_lossy()].iter().map(|s| s.to_string()).collect();
let (files, notices) = launch_imports_in(&args, Some(&home), Some(&home));
let LaunchArgs { files, notices, library } = launch_imports_in(&args, Some(&home), Some(&home));
assert_eq!(library, None);
assert_eq!(files, [home.join("Trip").to_string_lossy().to_string()]);
assert_eq!(notices.len(), 2, "{notices:?}");
assert!(notices.iter().all(|n| n.contains("was not imported")), "{notices:?}");
// the working folder is a drive root (a launcher's choice): `.` is never the whole drive
let root = home.ancestors().last().unwrap().to_path_buf();
let (files, notices) = launch_imports_in(&[".".to_string()], Some(&root), None);
let LaunchArgs { files, notices, .. } = launch_imports_in(&[".".to_string()], Some(&root), None);
assert!(files.iter().all(|f| f.ends_with("DCIM")) && files.len() + notices.len() == 1, "{files:?} {notices:?}");
let _ = std::fs::remove_dir_all(&home);
}
/// `--library` and `LIGHTCRAFT_LIBRARY` win over a library given as an argument, which is
/// then not remembered either.
#[test]
fn the_library_flag_and_variable_win_over_a_library_argument() {
use std::path::PathBuf;
let (flag, env, arg) = (PathBuf::from("flag"), PathBuf::from("env"), PathBuf::from("arg"));
assert_eq!(launch_library_choice(Some(flag.clone()), Some(&env), Some(arg.clone())), (Some(flag.clone()), false));
assert_eq!(launch_library_choice(None, Some(&env), Some(arg.clone())), (None, false), "the variable is passed on as itself");
assert_eq!(launch_library_choice(None, None, Some(arg.clone())), (Some(arg), true));
assert_eq!(launch_library_choice(None, None, None), (None, false));
assert_eq!(launch_library_choice(Some(flag.clone()), None, None), (Some(flag), false));
}
/// A library's catalog.snap (double-clicked in Explorer) or its folder given at
/// launch opens that library and is never imported as photos; a second library is left with a notice.
#[test]
fn a_librarys_catalog_given_at_launch_opens_that_library() {
let home = dir("launch-library");
let lib = home.join("Wedding LC");
let mut s = lightcraft_engine::Session::new().with_fs();
s.open_library(&lib, false).unwrap();
s.close_library().unwrap();
let snap = lib.join("catalog.snap");
assert!(snap.is_file(), "a library keeps its catalog.snap");
let other = home.join("Other LC");
let mut s = lightcraft_engine::Session::new().with_fs();
s.open_library(&other, false).unwrap();
s.close_library().unwrap();
for arg in [snap.to_string_lossy().to_string(), lib.to_string_lossy().to_string(), "Wedding LC/catalog.snap".to_string()] {
let got = launch_imports_in(std::slice::from_ref(&arg), Some(&home), Some(&home.join("elsewhere")));
assert_eq!(got.library.as_deref(), Some(lib.as_path()), "{arg}");
assert!(got.files.is_empty() && got.notices.is_empty(), "{arg}: never imported: {got:?}");
}
let got = launch_imports_in(&[snap.to_string_lossy().to_string(), other.to_string_lossy().to_string()], Some(&home), None);
assert_eq!(got.library.as_deref(), Some(lib.as_path()), "the first one");
assert_eq!(got.notices.len(), 1, "{got:?}");
let _ = std::fs::remove_dir_all(&home);
}
/// Issue #236: the window answers control requests on its UI thread, so the desktop session
/// adds to Apple Photos on a worker (headless sessions wait instead).
#[test]
fn the_desktop_session_adds_to_apple_photos_in_the_background() {
let (s, problem) = open_session(true, &Launch::Open { dir: None, alt_asks: false }, false);
let (s, problem) = open_session(true, &Launch::Open { dir: None, alt_asks: false, remembered: false }, false);
assert!(problem.is_none());
assert!(s.apple_photos_background);
assert!(!lightcraft_engine::Session::new().apple_photos_background);
@@ -63,6 +119,74 @@ fn asking_at_launch_opens_nothing_and_still_saves_the_settings() {
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #3239: the library remembered in Settings whose folder is missing at launch (a disk or
/// network share not connected) is reported in the library problem window. Nothing is created
/// there (not the folder, not its parents) and no demo photos are added.
#[test]
fn a_remembered_library_missing_at_launch_is_reported_not_made_anew() {
let d = dir("missing-library");
let gone = d.join("gone");
let lib = gone.join("Lib");
let launch = Launch::Open { dir: Some(lib.clone()), alt_asks: true, remembered: true };
let (s, problem) = open_session(false, &launch, true);
let problem = problem.expect("the missing library is reported");
assert_eq!(problem.path, lib.to_string_lossy());
assert!(problem.can_retry, "Try Again once the drive is back");
assert!(problem.existing_only, "Try Again makes no library there either");
assert!(!gone.exists(), "nothing is created where the library was");
assert!(s.library.is_none() && s.catalog.is_empty(), "no library, no demo photos");
// a remembered folder that is there but holds no library is reported too
std::fs::create_dir_all(&lib).unwrap();
let (s, problem) = open_session(false, &launch, true);
assert!(problem.as_ref().is_some_and(|p| p.existing_only) && s.library.is_none() && s.catalog.is_empty(), "{problem:?}");
assert!(!lightcraft_engine::library::is_library(&lib), "nothing written in it");
// the default location (or --library) is still made when it's missing, with the demo photos
let fresh = d.join("fresh").join("Lib");
let (s, problem) = open_session(false, &Launch::Open { dir: Some(fresh.clone()), alt_asks: true, remembered: false }, true);
assert!(problem.is_none() && s.library.is_some() && !s.catalog.is_empty(), "{problem:?}");
assert!(lightcraft_engine::library::is_library(&fresh));
drop(s);
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #3239: a remembered library whose folder can't be looked into (no permission) is
/// reported as unreadable at launch, not as gone, and nothing is opened or written there.
#[cfg(unix)]
#[test]
fn a_remembered_library_it_may_not_read_at_launch_says_so() {
use std::os::unix::fs::PermissionsExt;
let d = dir("denied-library");
let lib = d.join("Lib");
let mut s = lightcraft_engine::Session::new().with_fs();
s.open_library(&lib, false).unwrap();
s.close_library().unwrap();
drop(s);
let names = |dir: &std::path::Path| {
let mut names: Vec<_> = std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name()).collect();
names.sort();
names
};
let before = names(&lib);
std::fs::set_permissions(&lib, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::read_dir(&lib).is_ok() {
std::fs::set_permissions(&lib, std::fs::Permissions::from_mode(0o755)).unwrap();
let _ = std::fs::remove_dir_all(&d);
lightcraft_testkit::skip!(System, "running as root: a folder with mode 000 is still readable");
return;
}
let launch = Launch::Open { dir: Some(lib.clone()), alt_asks: true, remembered: true };
let (s, problem) = open_session(false, &launch, true);
std::fs::set_permissions(&lib, std::fs::Permissions::from_mode(0o755)).unwrap();
let problem = problem.expect("the unreadable library is reported");
assert!(problem.error.starts_with("This folder can't be read:"), "{}", problem.error);
assert!(problem.error.to_lowercase().contains("permission denied"), "{}", problem.error);
assert!(problem.existing_only, "Try Again makes no library there either");
assert!(s.library.is_none() && s.catalog.is_empty(), "no library, no demo photos");
assert_eq!(names(&lib), before, "nothing written there");
drop(s);
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #103: a damaged ui.json (which holds the library location) is kept aside and
/// reported, not silently replaced by the defaults.
#[test]
@@ -99,6 +223,42 @@ fn memory_session_leaves_a_damaged_ui_json_alone() {
let _ = std::fs::remove_dir_all(&d);
}
/// A settings file from before the startup dialog existed (no `seenVersion`) belongs to an
/// installation that has been run: its first launch after the update shows What's New, never
/// the first-run tour. A file this version saved before the dialog was presented carries an
/// explicit `null` and is not migrated; only a missing file stays a first run as well.
#[test]
fn legacy_ui_json_shows_whats_new_not_the_first_run_tour() {
let d = dir("legacy-startup");
let path = d.join("ui.json");
std::fs::write(&path, br#"{"language":"en","settings":{"startupView":"detail"}}"#).unwrap();
let (ui, warning, keep) = load_prefs_at(&path, true);
assert!(warning.is_none() && !keep);
let ui = ui.unwrap();
assert_eq!(ui.seen_version.as_deref(), Some(lightcraft_ui_egui::startup::LEGACY_SEEN_VERSION));
assert_eq!(
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
Some(lightcraft_ui_egui::startup::StartupDialog::WhatsNew)
);
// a file that already records the running version is migrated nowhere
std::fs::write(&path, format!(r#"{{"seenVersion":"{}"}}"#, env!("CARGO_PKG_VERSION"))).unwrap();
let (ui, warning, _) = load_prefs_at(&path, true);
assert!(warning.is_none());
assert_eq!(ui.unwrap().seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
// an explicit `null` is this version's "not presented yet" (the launch chooser saves while
// the tour still waits): it stays a first run, not a pre-feature file
std::fs::write(&path, br#"{"language":"en","seenVersion":null}"#).unwrap();
let (ui, warning, _) = load_prefs_at(&path, true);
assert!(warning.is_none());
let ui = ui.unwrap();
assert_eq!(ui.seen_version, None);
assert_eq!(
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
Some(lightcraft_ui_egui::startup::StartupDialog::FirstRun)
);
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn docking_survives_native_settings_file_reload() {
use lightcraft_ui_egui::docking::Panel;
@@ -443,6 +603,7 @@ fn on_exit_ends_the_process_on_macos() {
let mut app = App(
app,
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
@@ -462,3 +623,39 @@ fn on_exit_ends_the_process_on_macos() {
assert!(stdout.contains("calling on_exit"), "the child didn't run the test: {stdout}");
assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}");
}
/// Quitting leaves no `catalog.lock.owner` behind, though the process ends without running
/// destructors (macOS): `on_exit` releases the library's lock itself. The child opens a library
/// and calls `on_exit` (on macOS that ends it); the parent looks at the folder afterwards. Other
/// systems drop the app after `on_exit`, which removes the note anyway.
#[test]
fn on_exit_removes_the_lock_owner_note() {
if let Some(dir) = std::env::var_os("LIGHTCRAFT_TEST_LOCK_DIR") {
let mut session = lightcraft_engine::Session::new();
session.open_library(&dir, false).unwrap();
let mut app = App(
LightcraftApp::new(session, Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
eframe::App::on_exit(&mut app, None);
return;
}
let dir = std::env::temp_dir().join(format!("lc-app-lock-owner-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::on_exit_removes_the_lock_owner_note", "--nocapture"])
.env("LIGHTCRAFT_TEST_LOCK_DIR", &dir)
.env("LIGHTCRAFT_NO_PREFS", "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{stdout}");
assert!(dir.join("catalog.snap").exists(), "the child didn't open and save the library: {stdout}");
assert!(!dir.join("catalog.lock.owner").exists(), "the owner note was left behind");
assert!(lightcraft_engine::Session::new().open_library(&dir, false).is_ok(), "the library is still locked");
let _ = std::fs::remove_dir_all(&dir);
}
+40
View File
@@ -0,0 +1,40 @@
//! The ICC profile Windows assigns to the monitor showing LightCraft's window.
//!
//! On an SDR desktop Windows passes what an app draws to the monitor unchanged, so sRGB previews
//! look oversaturated on a wide-gamut monitor and ignore a calibration. While no monitor profile is
//! chosen in Settings ▸ Display, previews are shown through the profile Windows uses for the window's
//! monitor (`Services::screen_profile`, see `lightcraft_wincolor`), followed when the window moves to
//! another monitor or the profile changes in Windows' Color Management. When Windows colour-manages
//! the desktop itself (HDR, Auto Color Management) previews stay sRGB, as Windows expects then.
use lightcraft_wincolor::MonitorColor;
/// The service the UI polls, for the window `cc` belongs to; `None` when its handle isn't a Win32 one.
pub fn service(cc: &eframe::CreationContext<'_>) -> Option<lightcraft_ui_egui::ScreenProfileFn> {
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
let RawWindowHandle::Win32(handle) = cc.window_handle().ok()?.as_raw() else { return None };
let hwnd = handle.hwnd.get();
let mut file = crate::profile_file::Cached::default();
let mut last: Option<MonitorColor> = None;
Some(Box::new(move || {
let answer = lightcraft_wincolor::monitor_color(hwnd);
if last.as_ref() != Some(&answer) {
log::info!("screen profile: {}", describe(&answer));
last = Some(answer.clone());
}
match answer {
MonitorColor::Profile(path) => file.read(&path),
MonitorColor::ManagedByWindows | MonitorColor::NoProfile | MonitorColor::Unknown => None,
}
}))
}
/// For the log: what the window's monitor answered.
fn describe(answer: &MonitorColor) -> String {
match answer {
MonitorColor::Profile(path) => format!("the monitor's profile, {}", path.display()),
MonitorColor::ManagedByWindows => "Windows colour-manages this monitor (HDR or Auto Color Management): previews are sRGB".into(),
MonitorColor::NoProfile => "no profile is assigned to the monitor: previews are sRGB".into(),
MonitorColor::Unknown => "not known for this monitor: previews are sRGB".into(),
}
}
+125 -10
View File
@@ -54,7 +54,12 @@ impl Files {
if let Some(d) = p.parent() {
let _ = std::fs::create_dir_all(d);
}
if let Err(e) = std::fs::write(&p, format!("{}\n", r.name())) {
// on disk before the driver is touched: a driver fault can take the machine down with it
let written = std::fs::File::create(&p).and_then(|mut f| {
std::io::Write::write_all(&mut f, format!("{}\n", r.name()).as_bytes())?;
f.sync_all()
});
if let Err(e) = written {
log::warn!("window: could not write {}: {e}", p.display());
}
}
@@ -85,7 +90,7 @@ impl Files {
}
/// The renderer for this start: see the module docs.
pub fn choose(files: &Files) -> Chosen {
pub fn choose(files: &Files, compose_window: bool) -> Chosen {
let forced =
backend::forced_window_renderer(std::env::var("LIGHTCRAFT_GPU_BACKEND").ok().as_deref(), std::env::var("WGPU_BACKEND").ok().as_deref());
let failed = files.take_failed();
@@ -95,7 +100,7 @@ pub fn choose(files: &Files) -> Chosen {
let order = backend::window_renderer_order(forced, remembered, failed, os, compiled, true);
let mut problems = Vec::new();
let chosen = if cfg!(windows) {
pick_probed(&order, &mut problems)
pick_probed(files, &order, &mut problems, compose_window)
} else if forced == Some(WindowRenderer::Glow) || (forced.is_none() && failed.is_some_and(|f| f != WindowRenderer::Glow)) {
// elsewhere eframe's own wgpu set-up stays the default; glow after a failed start
Some((WindowRenderer::Glow, None))
@@ -142,24 +147,47 @@ fn user_notice(failed: Option<WindowRenderer>, forced: Option<WindowRenderer>, p
}
/// eframe's defaults with the app's backends and DX12 shader compiler (issues #136, #471).
///
/// Taken from `NativeOptions::default()`, whose surface is egui-wgpu's `LOW_LATENCY` (one frame in
/// flight; two drawables on Metal). `WgpuConfiguration::default()` is `HIGH_THROUGHPUT` instead (two
/// frames queued, three drawables): every drag, slider and crop handle reached the screen a frame
/// later than eframe's default. Live window resizing still gets three drawables from egui-wgpu.
pub fn base_options() -> WgpuConfiguration {
let mut c = WgpuConfiguration::default();
let mut c = eframe::NativeOptions::default().wgpu_options;
if let WgpuSetup::CreateNew(n) = &mut c.wgpu_setup {
n.instance_descriptor.backends = backend::window_backends();
n.instance_descriptor.backend_options = backend::backend_options();
// no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250)
n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags);
// the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's
// buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults
let default = n.device_descriptor.clone();
n.device_descriptor = std::sync::Arc::new(move |adapter| {
if adapter.get_info().backend == wgpu::Backend::Gl {
return default(adapter);
}
wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() }
});
}
c
}
/// The first renderer of `order` that probes cleanly (glow is taken without a probe).
fn pick_probed(order: &[WindowRenderer], problems: &mut Vec<String>) -> Option<(WindowRenderer, Option<WgpuSetupExisting>)> {
fn pick_probed(
files: &Files,
order: &[WindowRenderer],
problems: &mut Vec<String>,
compose_window: bool,
) -> Option<(WindowRenderer, Option<WgpuSetupExisting>)> {
for &r in order {
match r {
WindowRenderer::Glow => return Some((r, None)),
WindowRenderer::Wgpu(b) => {
let probed = std::panic::catch_unwind(|| probe(b)).unwrap_or_else(|_| Err("panicked".into()));
// name the renderer being probed before the crash-prone device
// creation and egui pipeline compile: if the driver kills the
// start, the marker survives so the next launch tries it last
files.arm(r);
let probed = std::panic::catch_unwind(|| probe(b, compose_window)).unwrap_or_else(|_| Err("panicked".into()));
match probed {
Ok(e) => return Some((r, Some(e))),
Err(e) => {
@@ -174,11 +202,11 @@ fn pick_probed(order: &[WindowRenderer], problems: &mut Vec<String>) -> Option<(
}
/// Create a device on `backends` and build egui's pipeline on it; any wgpu error is returned.
fn probe(backends: Backends) -> Result<WgpuSetupExisting, String> {
fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting, String> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends,
flags: backend::instance_flags_from_env(wgpu::InstanceFlags::from_build_config().with_env()),
backend_options: backend::backend_options(),
backend_options: presentation_options(backends, compose_window),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: None,
});
@@ -187,10 +215,12 @@ fn probe(backends: Backends) -> Result<WgpuSetupExisting, String> {
..Default::default()
}))
.map_err(|e| format!("no adapter: {e}"))?;
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() };
// (not GL: the adapter's own limits, which the GPU renderer needs when it adopts this device)
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { adapter.limits() };
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("egui wgpu device"),
required_limits: wgpu::Limits { max_texture_dimension_2d: 8192, ..base },
// (GL takes the conservative defaults for everything else, whose 2048 is too small for a window)
required_limits: wgpu::Limits { max_texture_dimension_2d: adapter.limits().max_texture_dimension_2d, ..base },
..Default::default()
}))
.map_err(|e| format!("{}: no device: {e}", adapter.get_info().name))?;
@@ -242,6 +272,22 @@ pub fn relaunch_after_failure(files: &Files) -> bool {
.is_ok()
}
/// Only DX12 windows use the compositor; fallback renderers retain their normal presentation.
/// Adapted from kmnkv1's PhotoCraft PR: https://github.com/storytold/photocraft/pull/7035.
pub fn composes_window(enabled: bool, renderer: WindowRenderer) -> bool {
cfg!(target_os = "windows") && enabled && renderer == WindowRenderer::Wgpu(Backends::DX12)
}
/// Select DirectComposition for opted-in Windows DX12 windows, preserving
/// the default presentation options for other renderers.
fn presentation_options(backends: Backends, enabled: bool) -> wgpu::BackendOptions {
let mut options = backend::backend_options();
if composes_window(enabled, WindowRenderer::Wgpu(backends)) {
options.dx12.presentation_system = wgpu::Dx12SwapchainKind::DxgiFromVisual;
}
options
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
@@ -290,6 +336,23 @@ mod tests {
assert!(died.contains("last time") && !died.contains("Validation Error"), "{died}");
}
/// The window keeps eframe's low-latency surface: one frame queued (two Metal drawables), not
/// the high-throughput `WgpuConfiguration::default()`, which held input a frame longer. The
/// probed (Windows) and forced-backend configurations are built on the same options.
#[test]
fn window_surface_keeps_one_frame_in_flight() {
let surface = base_options().surface;
assert_eq!(surface, eframe::NativeOptions::default().wgpu_options.surface);
assert_eq!(surface, eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
assert_eq!(surface.desired_maximum_frame_latency, Some(1));
assert_eq!(surface.present_mode, wgpu::PresentMode::AutoVsync);
assert_ne!(surface, WgpuConfiguration::default().surface, "egui-wgpu's own default is the high-throughput one");
// what `main` hands eframe (on Windows `choose` probes the adapters first; not here)
if !cfg!(windows) {
assert_eq!(choose(&Files::new(None), false).wgpu_options.surface, surface);
}
}
/// The crash report: a pipeline that fails validation must come back as an error, never as
/// wgpu's default panic. Needs an adapter; skipped where there is none (CI without a GPU).
#[test]
@@ -334,4 +397,56 @@ mod tests {
// outside a scope: logged by our handler, not a panic
let _ = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl("not wgsl".into()) });
}
/// The probed device keeps the adapter's own `max_texture_dimension_2d`, so a window
/// ballooned past 8192 px can still configure its surface. Needs an adapter; skipped
/// where there is none (CI without a GPU).
#[test]
fn probed_device_uses_adapter_max_texture_size() {
let Ok(setup) = probe(backend::window_backends(), false) else {
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
return;
};
assert_eq!(
setup.device.limits().max_texture_dimension_2d,
setup.adapter.limits().max_texture_dimension_2d,
"the probed device must use the adapter's own max_texture_dimension_2d, not a fixed 8192 cap",
);
}
/// The workaround is opt-in and changes presentation only for Windows DX12.
#[test]
fn composition_only_changes_windows_dx12_presentation() {
let legacy: lightcraft_ui_egui::state::AppSettings = serde_json::from_str("{}").unwrap();
assert!(!legacy.compose_window, "existing settings keep the workaround off until opted in");
assert!(!lightcraft_ui_egui::state::AppSettings::default().compose_window);
let enabled: lightcraft_ui_egui::state::AppSettings = serde_json::from_str(r#"{"composeWindow":true}"#).unwrap();
let saved = serde_json::to_value(&enabled).unwrap();
assert_eq!(saved["composeWindow"], true);
for backend in [Backends::DX12, Backends::VULKAN, Backends::GL] {
let wanted = cfg!(target_os = "windows") && backend == Backends::DX12;
assert_eq!(composes_window(true, WindowRenderer::Wgpu(backend)), wanted);
assert_eq!(presentation_options(backend, true).dx12.presentation_system == wgpu::Dx12SwapchainKind::DxgiFromVisual, wanted);
assert!(!composes_window(false, WindowRenderer::Wgpu(backend)));
}
assert!(!composes_window(true, WindowRenderer::Glow));
}
/// The probe builds egui's pipeline on a live device before the window opens; a driver crash
/// there must leave the window-init marker on disk so the next launch tries another renderer.
#[cfg(windows)]
#[test]
fn the_window_marker_is_written_while_the_renderer_is_probed() {
// glow is taken without a probe, so a forced glow arms nothing here
let forced =
backend::forced_window_renderer(std::env::var("LIGHTCRAFT_GPU_BACKEND").ok().as_deref(), std::env::var("WGPU_BACKEND").ok().as_deref());
if forced == Some(WindowRenderer::Glow) {
return;
}
let d = dir("probe-marker");
let f = Files::new(Some(d.clone()));
choose(&f, false);
assert!(f.armed(), "the window-init marker must be written while the renderer is probed");
let _ = std::fs::remove_dir_all(&d);
}
}
+3 -1
View File
@@ -19,11 +19,13 @@ covers a whole directory), or if a licence file referenced in the Licence column
| `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 LightCraft | LightCraft contributors; source photographs supplied by @AlexChambers | original work: fitted by `lightcraft-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/Canon_EOS_D60.json` | Canon EOS D60 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by Robert Woldberg | original work: fitted by `lightcraft-cli calibrate` to 1,424 usable EOS D60 CRWs (of 1,520, 2005 to 2014, Auto white balance) 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_6_2.json` | Nikon Z 6II camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 296 usable Z 6II NEFs of my own (of 299, 2024 to 2026, Standard and Auto picture controls; NIKKOR Z 20mm f/1.8 S, Z 24-70mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_Z_8.json` | Nikon Z 8 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 261 usable Z 8 NEFs of my own (of 278, 2023 and 2026, nearly all Standard picture control, lossless 14-bit; NIKKOR Z 24-120mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/ILCE-7RM5.json` | Sony ILCE-7RM5 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Yule (Brian) Wang (@peaperfish) | original work: fitted by `lightcraft-cli calibrate` to 220 usable ILCE-7RM5 ARWs of my own (of 241, 2025 to 2026, Standard creative style; Sigma 24-70mm F2.8 DG DN II Art and Sony FE 200-600mm F5.6-6.3 G OSS) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-26 | none |
| `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix |
| `crates/raw/src/chart_table.rs` | Chart-measured camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D50) for the Canon EOS D60 | LightCraft contributors; ColorChecker photographs taken by Robert Woldberg on the maintainer's EOS D60 | original work: fitted to our own CRWs of a ColorChecker Classic (post-November-2014 formulation) under a ~2,900 K tungsten bulb (11 frames) and direct sun (~4,850 K, 20 frames); reference colours: X-Rite's published L*a*b* (D50) for the chart, as packaged by [colour-science](https://github.com/colour-science/colour) (BSD-3-Clause), used for fitting only and not shipped; method in `clean-room/crw/10-chart-calibration.md` | MIT OR Apache-2.0 | 2026-10-25 | kept by hand: a 3×3 matrix per illuminant fitted on chromaticity with neutral held at D50; no Adobe or third-party camera matrix, no number from a GPL raw decoder |
| `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none |
| `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a |
| `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a |
@@ -53,4 +55,4 @@ Notes
- CJK fonts (BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC) are not in this repository. They live in
[storytold/craft-fonts](https://github.com/storytold/craft-fonts), with their licences and attribution in its
`ATTRIBUTION.md`, and are embedded only in builds made with the optional `CRAFT_FONTS_DIR` build input (all official
releases). Never commit font files here; add new fonts to craft-fonts (craftrules `standards/fonts.md`).
releases). Never commit font files here; add new fonts to craft-fonts.
+2 -3
View File
@@ -20,9 +20,8 @@ Windows and Linux files use the full-bleed tile so the lynx reads at 16-48 px.
## Provenance
The owner's original drawing, made in ArtCraft (2880 px, keyed to the three colours), vectorised with
craftrules `assets/logo-options/_tools/vectorize_tile.py`. The source drawing stays in craftrules at
`assets/app-icons/lightcraft/source.png`; `lightcraft.svg` here is the canonical artwork. Licence:
The owner's original drawing, made in ArtCraft (2880 px, keyed to the three colours) and
vectorised. `lightcraft.svg` here is the canonical artwork. Licence:
`LICENSE.txt` (MIT OR Apache-2.0, like the repo).
## Files
@@ -0,0 +1 @@
{"version":1,"model":"Canon EOS D60","files":1424,"samples":5140322,"matrix":[[1.13012,-0.360203,0.234919],[-0.0483286,1.21254,-0.166746],[-0.0238897,-0.834382,1.86577]],"hue_sat":{"hue_divisions":72,"sat_divisions":5,"val_divisions":5,"data":[[0.0,1.0,1.0],[8.29241,1.23189,1.0],[6.24278,1.25426,1.0],[5.85238,1.20774,1.0],[3.78008,1.10233,1.0],[0.0,1.0,1.0],[7.49695,1.19919,1.0],[4.58151,1.21364,1.0],[3.60262,1.15474,1.0],[2.74306,1.07068,1.0],[0.0,1.0,1.0],[6.97455,1.16634,1.0],[3.67004,1.18558,1.0],[1.9923,1.12524,1.0],[0.245554,0.982395,1.0],[0.0,1.0,1.0],[6.42589,1.13738,1.0],[2.66266,1.14834,1.0],[0.226251,1.09372,1.0],[-2.23194,0.930707,1.0],[0.0,1.0,1.0],[6.09352,1.1248,1.0],[1.65699,1.12876,1.0],[-1.52059,1.07635,1.0],[-3.87766,0.926268,1.0],[0.0,1.0,1.0],[6.2146,1.10729,1.0],[1.13044,1.11602,1.0],[-2.4179,1.08135,1.0],[-4.69366,0.96409,1.0],[0.0,1.0,1.0],[6.73255,1.09443,1.0],[1.15502,1.09451,1.0],[-2.95449,1.05376,1.0],[-5.86916,0.954201,1.0],[0.0,1.0,1.0],[7.0143,1.0883,1.0],[1.25698,1.07945,1.0],[-3.3853,1.03275,1.0],[-6.46471,0.9465,1.0],[0.0,1.0,1.0],[7.44031,1.08414,1.0],[1.9515,1.06401,1.0],[-3.08108,1.00026,1.0],[-6.03475,0.917114,1.0],[0.0,1.0,1.0],[8.29527,1.07925,1.0],[2.86018,1.03974,1.0],[-2.25228,0.96454,1.0],[-4.98936,0.860481,1.0],[0.0,1.0,1.0],[9.14683,1.08392,1.0],[3.8335,1.01361,1.0],[-1.06889,0.935075,1.0],[-4.04616,0.821455,1.0],[0.0,1.0,1.0],[9.19479,1.10285,1.0],[4.68727,1.00463,1.0],[0.536387,0.911486,1.0],[-2.795,0.795914,1.0],[0.0,1.0,1.0],[8.67599,1.12913,1.0],[5.14131,1.01389,1.0],[1.77075,0.910094,1.0],[-0.965505,0.813756,1.0],[0.0,1.0,1.0],[7.95628,1.12916,1.0],[5.32373,1.0083,1.0],[2.91716,0.905281,1.0],[1.05035,0.834887,1.0],[0.0,1.0,1.0],[6.83544,1.13214,1.0],[4.95639,1.00769,1.0],[3.81032,0.903303,1.0],[2.8937,0.82685,1.0],[0.0,1.0,1.0],[5.89142,1.1369,1.0],[4.55603,1.00893,1.0],[4.04927,0.902735,1.0],[3.59749,0.8313,1.0],[0.0,1.0,1.0],[5.07797,1.14498,1.0],[4.14717,1.01358,1.0],[3.95316,0.909713,1.0],[4.03064,0.834461,1.0],[0.0,1.0,1.0],[3.93584,1.15444,1.0],[3.29081,1.02539,1.0],[3.28057,0.922408,1.0],[3.7798,0.840035,1.0],[0.0,1.0,1.0],[2.45431,1.17195,1.0],[2.1184,1.04565,1.0],[2.31804,0.94015,1.0],[2.84532,0.862496,1.0],[0.0,1.0,1.0],[0.914128,1.1919,1.0],[0.658994,1.06124,1.0],[1.06903,0.95232,1.0],[1.60007,0.890999,1.0],[0.0,1.0,1.0],[-0.709287,1.20875,1.0],[-0.970683,1.0793,1.0],[-0.571268,0.969075,1.0],[-0.0688885,0.893104,1.0],[0.0,1.0,1.0],[-2.56506,1.23369,1.0],[-2.97984,1.10163,1.0],[-2.79742,0.983848,1.0],[-2.01335,0.892256,1.0],[0.0,1.0,1.0],[-4.47609,1.26079,1.0],[-4.91221,1.12068,1.0],[-4.5471,1.00002,1.0],[-2.72325,0.931381,1.0],[0.0,1.0,1.0],[-6.07811,1.27839,1.0],[-6.49836,1.12664,1.0],[-5.47092,0.99826,1.0],[-1.83561,0.972328,1.0],[0.0,1.0,1.0],[-8.37879,1.29932,1.0],[-8.93662,1.13395,1.0],[-7.32093,1.02059,1.0],[-0.98037,0.994534,1.0],[0.0,1.0,1.0],[-10.2729,1.25707,1.0],[-11.0599,1.09129,1.0],[-9.32287,1.00616,1.0],[-1.21689,0.994275,1.0],[0.0,1.0,1.0],[-11.9931,1.22624,1.0],[-12.4979,1.05021,1.0],[-10.2083,0.969313,1.0],[-1.172,0.991243,1.0],[0.0,1.0,1.0],[-13.5442,1.18901,1.0],[-13.5809,1.00396,1.0],[-10.7308,0.93446,1.0],[-1.1717,0.98724,1.0],[0.0,1.0,1.0],[-14.1202,1.16045,1.0],[-14.1451,0.982771,1.0],[-10.5188,0.911345,1.0],[-1.10721,0.983353,1.0],[0.0,1.0,1.0],[-14.5581,1.16209,1.0],[-13.8126,0.986909,1.0],[-8.30721,0.90898,1.0],[-0.995621,0.97911,1.0],[0.0,1.0,1.0],[-14.4013,1.1613,1.0],[-13.2596,0.979666,1.0],[-8.95671,0.890826,1.0],[-2.10024,0.967003,1.0],[0.0,1.0,1.0],[-15.1417,1.16939,1.0],[-13.2246,0.977241,1.0],[-9.7885,0.871629,1.0],[-2.78003,0.957243,1.0],[0.0,1.0,1.0],[-16.0188,1.15745,1.0],[-14.0864,0.974714,1.0],[-10.4183,0.871201,1.0],[-2.37086,0.964302,1.0],[0.0,1.0,1.0],[-16.2546,1.14581,1.0],[-13.912,0.987045,1.0],[-8.19204,0.901434,1.0],[-1.1791,0.982516,1.0],[0.0,1.0,1.0],[-16.3253,1.14274,1.0],[-13.1974,0.996884,1.0],[-7.37707,0.909881,1.0],[-0.796766,0.988333,1.0],[0.0,1.0,1.0],[-17.4833,1.13741,1.0],[-13.1058,0.977386,1.0],[-5.85941,0.919339,1.0],[-0.352557,0.99447,1.0],[0.0,1.0,1.0],[-17.5235,1.10838,1.0],[-13.7099,0.974525,1.0],[-5.10075,0.930882,1.0],[-0.176921,0.995738,1.0],[0.0,1.0,1.0],[-17.5967,1.05115,1.0],[-13.6048,0.938325,1.0],[-5.27843,0.910606,1.0],[-0.167657,0.994507,1.0],[0.0,1.0,1.0],[-17.4696,0.996524,1.0],[-13.115,0.908347,1.0],[-4.95967,0.899867,1.0],[-0.174963,0.992617,1.0],[0.0,1.0,1.0],[-16.5982,0.955417,1.0],[-11.0254,0.879437,1.0],[-3.31212,0.863198,1.0],[-0.175046,0.977174,1.0],[0.0,1.0,1.0],[-15.5952,0.929258,1.0],[-8.31794,0.86823,1.0],[-0.528212,0.846517,1.0],[0.380461,0.923401,1.0],[0.0,1.0,1.0],[-14.4398,0.910204,1.0],[-8.05514,0.876305,1.0],[-0.57323,0.868118,1.0],[0.470409,0.948896,1.0],[0.0,1.0,1.0],[-13.0585,0.905534,1.0],[-7.90773,0.889057,1.0],[-0.976436,0.905932,1.0],[0.542039,0.983099,1.0],[0.0,1.0,1.0],[-11.876,0.908437,1.0],[-7.06937,0.903432,1.0],[-0.539651,0.916127,1.0],[0.779286,0.983595,1.0],[0.0,1.0,1.0],[-10.0702,0.929172,1.0],[-5.39408,0.937425,1.0],[-0.2061,0.920171,1Line truncated
+97
View File
@@ -0,0 +1,97 @@
# EOS D60 colour matrices from a ColorChecker (2026-10-25)
The Canon EOS D60 has no published spectral sensitivities, so it is not in `spectral_table.rs`.
These are its DNG-style matrices (`ColorMatrix1/2`, `ForwardMatrix1/2`), fitted to our own
photographs of a ColorChecker Classic under two lights. They are in
`crates/raw/src/chart_table.rs`. Measurements come from the maintainer's own captures (names,
sizes and SHA-256 in `logs/chart-captures.tsv`; no image content recorded) and the chart's
published reference colours (craft-libs `crates/crw/clean-room/sources.md`). Scripts and measurements are local-only, in
`plan/crw/chart/`.
## Captures
| Set | Frames used | Light | Notes |
|---|---:|---|---|
| `SunlightColorCard/` | 20 of 22 | Direct afternoon sun, ISO 100 | Calibrite ColorChecker Classic (50th-anniversary edition, post-2014 formulation) leaning on a wall, filling most of the frame. Auto and Daylight white balance, a shutter bracket. Two frames dropped: a white-patch sample ≥ 3900 (clip ≈ 4000 at ISO 100, craft-libs `crates/crw/clean-room/04-color.md` §2). |
| `TungstonColorChart/` 2696–2706 | 11 | One household tungsten bulb, ISO 100 | Chart flat on a wall, a shutter bracket. Brightest white patch 2657 of ~4000. |
| `TungstonColorChart/` 2688–2691 | not used | Same bulb, 8 minutes earlier | Steady within the set, but its neutral reads ~3,040 K against ~2,900 K for the later set: the light changed (window light or bulb warm-up). The later, warmer and better-exposed set is used. |
All 37 frames decode sample-exact against the black-box reference (`craft-crw`'s digest-pinned sample test, formerly `crw_oracle.rs` here).
An earlier set on a ColorChecker-layout clone (Pixel Perfect "24 Standard Color Calibration
Chart", 2026-10-15) was not used. The maker publishes no reference values, and its grey patches
are not neutral: against an 18 % grey board they read R/G 0.88–0.94 in shade and B/G up to
1.29 under warm LED light, the darker patches drifting most. That is the sign of greys printed
from coloured inks.
## Measurement
- Patches are located on the embedded JPEG (four corner patch centres, bilinear grid), tracked
per frame by phase correlation, and checked visually on drawn boxes. The tungsten-set chart
was upside down in the first four frames; patch order is mapped accordingly.
- Each patch is measured in a central box of about 40 % of its width in the linear raw (black
from the far masked border per CFA site; R, mean of both G, B per 2×2 site). Uniformity
across the box (3×3 sub-blocks): ≤ 4 % in sun, ≤ 7 % under the bulb (light falloff across
the closer chart).
- Frames are normalised by the four middle neutrals (patches 20–23), averaged, and white
balanced on those neutrals. White balance (R, B multipliers, G = 1): sun 2.362, 1.298; bulb
1.353, 2.213. The neutrals agree on it to ±2 %.
## Fit
- The reference is X-Rite's published L\*a\*b\* (D50) for charts made after November 2014.
- The model is a 3×3 matrix from white-balanced camera RGB to XYZ (D50), with neutral (1, 1, 1)
held exactly at the engine's D50 white (`lightcraft_color::D50`): the third column is D50
minus the first two. That is a DNG `ForwardMatrix`.
- **Chromaticity only.** Each prediction is scaled to the patch's reference luminance before
the CIEDE2000 residual. In the sun the chart warped as it heated: the grey row's brightness
slope swung from +4 % to −7 % across the 70 s of shooting, in time order, and the per-patch
brightness needed was not smooth across the chart. A fit including lightness would have
absorbed that into the matrix. Chromaticity still determines the whole 3×3 up to scale,
which the white constraint fixes. The cost is that luminance of saturated blues and purples
rests on the model, not the measurement.
- `ColorMatrix` per light = diag(1 / multipliers) · ForwardMatrix⁻¹ · Bradford(light → D50),
scaled so the light's white maps to camera values with maximum 1. By construction it maps
the filed illuminant's white to the measured camera neutral.
| Light | CIEDE2000 on the 24 patches | Leaving each patch out | Worst |
|---|---|---|---|
| Sun (filed as D50) | mean 1.70, median 1.46 | mean 1.97 | white 4.5 |
| Bulb (filed as A) | mean 2.42, median 1.79 | mean 2.74 | bluish green 6.7 |
- One matrix does not serve both lights: the sun's matrix on the bulb's chart gives mean 3.6
(cyan 9.0), the bulb's on the sun's 3.4 (red 7.7). Hence the dual-illuminant entry.
- The neutral row reads a\* within ±0.4 for the middle greys; white and the darkest patches
are off by up to 2 (white patch sheen, flare).
## Which illuminants
The two lights' colour temperatures come from the camera's own white-balance presets
(ColorBalance slots, craft-libs `crates/crw/clean-room/04-color.md` §3) at the temperatures Canon's manuals give them (Daylight
5200 K, Tungsten 3200 K, Fluorescent 4000 K), interpolated in mired on ln(R/B): sun ~4,850 K,
bulb ~2,900 K. They are filed under the nearest DNG illuminants the engine knows, **D50
(5003 K) and Standard Illuminant A (2856 K)**, so `Camera` now carries its own illuminant
pair (spectral rows: A and D65).
## Checks in the app
- `spectral::tests::the_chart_measured_eos_d60_reads_its_presets_in_kelvin`: the camera's
presets, which the fit never saw, read through the matrices as Tungsten 3,264 K, Daylight
5,603 K, Cloudy 6,613 K, Flash 7,085 K, near the locus. Canon's nominal values are 3200, 5200,
6000 and 6000 K. Order and spacing hold; the daylight presets read 8–15 % high, as Sony's
dial does against its spectral matrices (#730).
- Real files through the headless app (As Shot): WBModes Fluorescent 4,103 K, tint +26 (green
compensation); LED-lit room, Auto 3,761 K; open shade, Auto 6,596 K; sunlit chart, Auto
4,762 K.
- `files::tests::crw_probes_name_their_camera_from_the_ciff_records`: CRW imports now take make,
model and capture time from the decoder's CIFF records (no Exif in a CRW; the catalog had an
empty camera, so a D60 stayed on the relative white-balance scale).
## Limits
- One body, one bulb, one afternoon. The chart is 24 patches; a 3×3 matrix cannot follow the
sensor's departures from the CIE observer (the bulb fit's worst patches are 5–7 ΔE).
- The lights are filed under standard illuminants they only approximate (~50 K for the bulb,
~150 K for the sun).
- The D60's look is still the per-file JPEG fit and the pooled profile; these matrices give the
white-balance scale and the fallback colour only.
+18
View File
@@ -0,0 +1,18 @@
# Canon CRW: where the record is
The Canon CRW (CIFF) decoder and its clean-room record (the frozen format, the verification
summary, the colour, geometry and metadata notes, the private-corpus summary and the source log)
live in craft-libs:
[`crates/crw/clean-room/`](https://github.com/storytold/craft-libs/tree/main/crates/crw/clean-room).
The derivation trail and the frozen table-generation materials stay in LightCraft PR #3021.
LightCraft uses the crate `craft-crw` through the adapter `crates/raw/src/vendor/crw.rs`.
What stays here is LightCraft's own colour work on these cameras:
- [`10-chart-calibration.md`](10-chart-calibration.md): the EOS D60 colour matrices fitted to
ColorChecker captures, implemented in `crates/raw/src/chart_table.rs`.
- [`logs/chart-captures.tsv`](logs/chart-captures.tsv): names, sizes and SHA-256 of the chart
frames (no image content).
The capture statistics those documents cite (`04-color.md`, `05-private-corpus.md`, `sources.md`)
are in the craft-libs record.
+39
View File
@@ -0,0 +1,39 @@
# EOS D60 ColorChecker Classic captures (maintainer, local only; never committed). Names, sizes, SHA-256; no image content. Generated 2026-10-25.
file bytes sha256
SunlightColorCard/CRW_2666.CRW 7791628 371d8e18c12801c72754dd7b277163a866afc422c8edf6ad1ea822009e4170f8
SunlightColorCard/CRW_2667.CRW 6638578 188d625c31ab44475a6cf54a5dae00fd861e26aafc90f4b5d18a1905c0a3cef5
SunlightColorCard/CRW_2668.CRW 6832770 1189b8dc79642c57a8c9496b5629e36a1741c545d2b0b864d6e6e20d901510c1
SunlightColorCard/CRW_2669.CRW 7079102 baf1686b27a9e0a04bf87c0b6cf55168f398d85247f8115a0af69b5e9ea1884c
SunlightColorCard/CRW_2670.CRW 7225298 067ba3f4d3026b8009cfe4babb5e4c3b28f988d95c48024a75c6715de32afccf
SunlightColorCard/CRW_2671.CRW 7504700 cf81cbb96389624318e890b5506221d49f5fba8e2d45447d87e0f3ff3e9bdc72
SunlightColorCard/CRW_2672.CRW 7830852 7a59446bfb1f00d6eabd0115b8e5451c34f5d3d48f483cb27608ce9508e43ee5
SunlightColorCard/CRW_2673.CRW 8053180 feeb8f818325d6ddb4e88b5eabe4a74f4cb5e1da9f70135ae3f85938c86695dc
SunlightColorCard/CRW_2674.CRW 8312060 45e7402c888582adadb607599eae80644d657d61c9607b426c411ee306e42daf
SunlightColorCard/CRW_2675.CRW 8565950 be28d2fa049aa4158ae9e3ec49dd28eb56fcd0ffa7af060235b8bda0d89dfd0a
SunlightColorCard/CRW_2676.CRW 7795508 76f7418a82e45e1034b3adacacf4bc756cb65a0d683e5bb3631992784e654f93
SunlightColorCard/CRW_2677.CRW 7747450 a5e7bc618e6b80ea70f9bad6a1bf41ee63eadbc51df28b82d0864a73434f7964
SunlightColorCard/CRW_2678.CRW 6815054 28824f0f64b087488d8dc5a66a8bdf717e83a4d4e1660676d07991bf32dffb96
SunlightColorCard/CRW_2679.CRW 7050606 b5c915fa89542265deb4fa16da3ca7ffda01b1d961903836b0059d024316673a
SunlightColorCard/CRW_2680.CRW 7231410 a5780dfe99a2df2a3ed9de1888e91baa614b2e009a2b6e0a84d442b6bf1af9fd
SunlightColorCard/CRW_2681.CRW 7438088 eb4475919c2770f816d47787656ab7ecb5396f30d2c03628c3ab167ebbc47c65
SunlightColorCard/CRW_2682.CRW 7584262 a6fe417b90ce41b03552963dee6b21e4f02b59a5c51148edc04af7224e8c59e9
SunlightColorCard/CRW_2683.CRW 7811474 5402ad40e2689d78ade083d8855ecced5caea9368b9d77ecc4a61a16dc55aa36
SunlightColorCard/CRW_2684.CRW 8043372 bbef5da457c0b6d6c45c74a99f3e318e6c80a7d3a0ad5c7cb7e13d24205f64fa
SunlightColorCard/CRW_2685.CRW 8242344 8d68d592a5c8933f0f35630114fe7017be808b007867beaf1a8d6d2bd1441f70
SunlightColorCard/CRW_2686.CRW 8462380 79f7db32b18a834d5408500185c65d316387d1440aa61e26a11be85883fcc382
SunlightColorCard/CRW_2687.CRW 7690732 0333d8d18390e77128f186239e6de71c0432ab6ee9669a71c210255e4d915d19
TungstonColorChart/CRW_2688.CRW 6269390 d9c4334edfe3636a8a7e69f29c1d1e89f820b7b704697684d7996faee41f5d43
TungstonColorChart/CRW_2689.CRW 6001348 1e8b47645d76a71fd9fb4111c4dce805d6dcd41ac82e6b4ce52debbf71565455
TungstonColorChart/CRW_2690.CRW 6114056 f63fe49a9ed13af33ddb8d8ed8d75de4e304a3bc2c1f1d4275ba7edbc4f459f3
TungstonColorChart/CRW_2691.CRW 6299730 ad8a2844c00965fb6a12e8fc85a6e8bfbdf1924e6d1a68b55472701cb8ffa115
TungstonColorChart/CRW_2696.CRW 6169684 105ee515c94da78dedc1f8d777982c4a1e62781b160428524fbe922f62b3ef5c
TungstonColorChart/CRW_2697.CRW 5565982 327eebf702185127feb8a5f4bfac5d7ebad5532f7417b302997b19b97d7ff4a8
TungstonColorChart/CRW_2698.CRW 5709092 f0fca20f8dcd51046e53bebf9fb9f624677ee674ad739622cdb2578977669705
TungstonColorChart/CRW_2699.CRW 5873492 57724a1ff507cf4e78c80a34cd4e0b77eac397322228d32e5215fc3869853dd1
TungstonColorChart/CRW_2700.CRW 5988146 6c97ae2c72114034e2fbe6aed0ef97f475696e43b56ed62273eccbfbba4cbaa0
TungstonColorChart/CRW_2701.CRW 6202756 c4032e46b753a718d8748e269a9da5d124891d07912542368ea867529143aa62
TungstonColorChart/CRW_2702.CRW 6409582 89b65c1c07e0685841046db85923b0bf80e747fed141ddf0335ba12dc75f3f3c
TungstonColorChart/CRW_2703.CRW 6407270 50179d0a330c967a74d76bc8342eea1052689c5c544aa1a913769b241ac6f736
TungstonColorChart/CRW_2704.CRW 6483154 6bac4d8229a8d0fff1445d212ca63e53911dc7bda988743215009257b87787fa
TungstonColorChart/CRW_2705.CRW 7170488 629f94131e7f598964d2635e3039a20c441563201c4f3cbf177d83ad6b061f78
TungstonColorChart/CRW_2706.CRW 6383026 67657e7a21f6fd8580012fccd2210afccf285e747bc4d39b8ea775811528ce83
1 # EOS D60 ColorChecker Classic captures (maintainer, local only; never committed). Names, sizes, SHA-256; no image content. Generated 2026-10-25.
2 file bytes sha256
3 SunlightColorCard/CRW_2666.CRW 7791628 371d8e18c12801c72754dd7b277163a866afc422c8edf6ad1ea822009e4170f8
4 SunlightColorCard/CRW_2667.CRW 6638578 188d625c31ab44475a6cf54a5dae00fd861e26aafc90f4b5d18a1905c0a3cef5
5 SunlightColorCard/CRW_2668.CRW 6832770 1189b8dc79642c57a8c9496b5629e36a1741c545d2b0b864d6e6e20d901510c1
6 SunlightColorCard/CRW_2669.CRW 7079102 baf1686b27a9e0a04bf87c0b6cf55168f398d85247f8115a0af69b5e9ea1884c
7 SunlightColorCard/CRW_2670.CRW 7225298 067ba3f4d3026b8009cfe4babb5e4c3b28f988d95c48024a75c6715de32afccf
8 SunlightColorCard/CRW_2671.CRW 7504700 cf81cbb96389624318e890b5506221d49f5fba8e2d45447d87e0f3ff3e9bdc72
9 SunlightColorCard/CRW_2672.CRW 7830852 7a59446bfb1f00d6eabd0115b8e5451c34f5d3d48f483cb27608ce9508e43ee5
10 SunlightColorCard/CRW_2673.CRW 8053180 feeb8f818325d6ddb4e88b5eabe4a74f4cb5e1da9f70135ae3f85938c86695dc
11 SunlightColorCard/CRW_2674.CRW 8312060 45e7402c888582adadb607599eae80644d657d61c9607b426c411ee306e42daf
12 SunlightColorCard/CRW_2675.CRW 8565950 be28d2fa049aa4158ae9e3ec49dd28eb56fcd0ffa7af060235b8bda0d89dfd0a
13 SunlightColorCard/CRW_2676.CRW 7795508 76f7418a82e45e1034b3adacacf4bc756cb65a0d683e5bb3631992784e654f93
14 SunlightColorCard/CRW_2677.CRW 7747450 a5e7bc618e6b80ea70f9bad6a1bf41ee63eadbc51df28b82d0864a73434f7964
15 SunlightColorCard/CRW_2678.CRW 6815054 28824f0f64b087488d8dc5a66a8bdf717e83a4d4e1660676d07991bf32dffb96
16 SunlightColorCard/CRW_2679.CRW 7050606 b5c915fa89542265deb4fa16da3ca7ffda01b1d961903836b0059d024316673a
17 SunlightColorCard/CRW_2680.CRW 7231410 a5780dfe99a2df2a3ed9de1888e91baa614b2e009a2b6e0a84d442b6bf1af9fd
18 SunlightColorCard/CRW_2681.CRW 7438088 eb4475919c2770f816d47787656ab7ecb5396f30d2c03628c3ab167ebbc47c65
19 SunlightColorCard/CRW_2682.CRW 7584262 a6fe417b90ce41b03552963dee6b21e4f02b59a5c51148edc04af7224e8c59e9
20 SunlightColorCard/CRW_2683.CRW 7811474 5402ad40e2689d78ade083d8855ecced5caea9368b9d77ecc4a61a16dc55aa36
21 SunlightColorCard/CRW_2684.CRW 8043372 bbef5da457c0b6d6c45c74a99f3e318e6c80a7d3a0ad5c7cb7e13d24205f64fa
22 SunlightColorCard/CRW_2685.CRW 8242344 8d68d592a5c8933f0f35630114fe7017be808b007867beaf1a8d6d2bd1441f70
23 SunlightColorCard/CRW_2686.CRW 8462380 79f7db32b18a834d5408500185c65d316387d1440aa61e26a11be85883fcc382
24 SunlightColorCard/CRW_2687.CRW 7690732 0333d8d18390e77128f186239e6de71c0432ab6ee9669a71c210255e4d915d19
25 TungstonColorChart/CRW_2688.CRW 6269390 d9c4334edfe3636a8a7e69f29c1d1e89f820b7b704697684d7996faee41f5d43
26 TungstonColorChart/CRW_2689.CRW 6001348 1e8b47645d76a71fd9fb4111c4dce805d6dcd41ac82e6b4ce52debbf71565455
27 TungstonColorChart/CRW_2690.CRW 6114056 f63fe49a9ed13af33ddb8d8ed8d75de4e304a3bc2c1f1d4275ba7edbc4f459f3
28 TungstonColorChart/CRW_2691.CRW 6299730 ad8a2844c00965fb6a12e8fc85a6e8bfbdf1924e6d1a68b55472701cb8ffa115
29 TungstonColorChart/CRW_2696.CRW 6169684 105ee515c94da78dedc1f8d777982c4a1e62781b160428524fbe922f62b3ef5c
30 TungstonColorChart/CRW_2697.CRW 5565982 327eebf702185127feb8a5f4bfac5d7ebad5532f7417b302997b19b97d7ff4a8
31 TungstonColorChart/CRW_2698.CRW 5709092 f0fca20f8dcd51046e53bebf9fb9f624677ee674ad739622cdb2578977669705
32 TungstonColorChart/CRW_2699.CRW 5873492 57724a1ff507cf4e78c80a34cd4e0b77eac397322228d32e5215fc3869853dd1
33 TungstonColorChart/CRW_2700.CRW 5988146 6c97ae2c72114034e2fbe6aed0ef97f475696e43b56ed62273eccbfbba4cbaa0
34 TungstonColorChart/CRW_2701.CRW 6202756 c4032e46b753a718d8748e269a9da5d124891d07912542368ea867529143aa62
35 TungstonColorChart/CRW_2702.CRW 6409582 89b65c1c07e0685841046db85923b0bf80e747fed141ddf0335ba12dc75f3f3c
36 TungstonColorChart/CRW_2703.CRW 6407270 50179d0a330c967a74d76bc8342eea1052689c5c544aa1a913769b241ac6f736
37 TungstonColorChart/CRW_2704.CRW 6483154 6bac4d8229a8d0fff1445d212ca63e53911dc7bda988743215009257b87787fa
38 TungstonColorChart/CRW_2705.CRW 7170488 629f94131e7f598964d2635e3039a20c441563201c4f3cbf177d83ad6b061f78
39 TungstonColorChart/CRW_2706.CRW 6383026 67657e7a21f6fd8580012fccd2210afccf285e747bc4d39b8ea775811528ce83
+14 -5
View File
@@ -1,13 +1,10 @@
# Contributor names for the About window (craftrules standards/contributors.md).
# Contributor names for the About window.
#
# Everyone who contributes is credited by GitHub username automatically. Anything more is up to
# you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a
# maintainer may add a person only when that person asked, recording where in consent_source.
#
# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \
# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name]
#
# Or copy this block, replacing your-github-username (every field is optional):
# Copy this block, replacing your-github-username (every field is optional):
#
# [people.your-github-username]
# real_name = "Your Name" # shown when the viewer picks "Real name"
@@ -71,9 +68,21 @@ sync_github_name = true
[people.ronibalthazar]
sync_github_name = true
[people.esli1283]
real_name = "Aaron Lopez"
sync_github_name = false
[people.dotCooCoo]
real_name = "Robert Lee"
sync_github_name = true
[people.samuelili]
real_name = "Samuel Li"
sync_github_name = true
[people.dylanmtaylor]
sync_github_name = true
[people.Peaperfish]
real_name = "Yule Wang"
display_name = "Brian Wang"
+1
View File
@@ -24,6 +24,7 @@ web-time = { workspace = true }
winapi-util = { workspace = true }
[dev-dependencies]
dhat = { workspace = true }
lightcraft-geom = { workspace = true }
lightcraft-testkit = { workspace = true }
proptest = { workspace = true }
+14 -1
View File
@@ -49,7 +49,12 @@ pub fn weekday(iso: &str) -> Option<&'static str> {
pub fn shift_iso(iso: &str, secs: i64) -> Option<String> {
let iso = iso.trim();
let tail = iso.get(tail_start(iso)?..)?;
let t = iso_seconds(iso)?.checked_add(secs)?;
let base = iso_seconds(iso)?;
// reject impossible dates that the arithmetic silently rolls over (2026-02-30)
if civil(base).get(..10) != iso.get(..10) {
return None;
}
let t = base.checked_add(secs)?;
let (first, last) = (iso_seconds("0000-01-01T00:00:00")?, iso_seconds("9999-12-31T23:59:59")?);
if !(first..=last).contains(&t) {
return None;
@@ -295,6 +300,14 @@ mod tests {
assert_eq!(normalize_iso("2026-02-30"), None);
}
#[test]
fn shift_refuses_impossible_dates() {
assert_eq!(shift_iso("2026-02-30T10:00:00", 60), None);
assert_eq!(shift_iso("2026-02-29T10:00:00", 0), None);
assert_eq!(shift_iso("2026-04-31T10:00:00", 0), None);
assert_eq!(shift_iso("2024-02-29T10:00:00", 0).as_deref(), Some("2024-02-29T10:00:00"));
}
#[test]
fn shift_keeps_the_zone_of_a_time_without_seconds() {
assert_eq!(shift_iso("2026-01-01T10:00+02:00", 3600).as_deref(), Some("2026-01-01T11:00:00+02:00"));
+70
View File
@@ -0,0 +1,70 @@
//! Fault injection for the catalog log's writer thread (tests only: nothing in the product
//! installs a hook, and with none installed a check is one uncontended lock of an empty list).
//!
//! A test makes the drive under one library directory slow (a hook that sleeps) or failing (a
//! hook that returns an error) and proves that a flag never waits for it and that nothing handed
//! over is lost: `crates/catalog/src/tests_log_thread.rs`, `crates/engine/src/tests/slow_drive.rs`.
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
/// Where the log thread is about to touch the drive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
/// Writing bytes to the log (or to the file that replaces it).
Write,
/// Syncing them.
Sync,
}
/// Runs before each [`Step`] in the hooked directory: an error fails that step.
pub type Hook = Arc<dyn Fn(Step) -> io::Result<()> + Send + Sync>;
static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one).
#[doc(hidden)]
pub fn install(dir: &Path, hook: Hook) {
let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
hooks.retain(|(d, _)| d != dir);
hooks.push((dir.to_path_buf(), hook));
}
/// Remove the hook of `dir`.
#[doc(hidden)]
pub fn remove(dir: &Path) {
HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir);
}
static ON_CALLER: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds
/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too).
#[doc(hidden)]
pub fn write_on_caller(dir: &Path, on: bool) {
let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
dirs.retain(|d| d != dir);
if on {
dirs.push(dir.to_path_buf());
}
}
pub(crate) fn on_caller(dir: &Path) -> bool {
let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
!dirs.is_empty() && dirs.iter().any(|d| d == dir)
}
pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> {
let hook = {
let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
if hooks.is_empty() {
return Ok(());
}
hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone())
};
match hook {
Some(h) => h(step),
None => Ok(()),
}
}
+166 -30
View File
@@ -6,7 +6,10 @@
//! rename).
//! - `catalog.log` — JSON lines, one per op applied after the snapshot:
//! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are
//! fsynced before [`Journal::append`] returns.
//! fsynced before [`Journal::append`] returns, except natively: [`crate::FsStore`] hands them to
//! a thread of its own that writes and syncs them in order right after (so a flag never waits
//! for the drive), holds and retries whatever fails ([`Journal::unwritten`]) and refuses later
//! appends meanwhile, so the log never has a gap and nothing handed over is dropped.
//!
//! Loading = snapshot + replay of the records with `seq > snapshot seq`. Recovery rules:
//! - a **torn final record** (crash mid-append: truncated line or bad CRC at the end) is dropped
@@ -22,6 +25,12 @@
//! - a bad record **followed by good ones** is real damage: replay stops there, the log is kept
//! as `catalog.log.damaged-<seq>`, and a fresh snapshot is written so the library stays usable.
//!
//! Segmentation grids are shared within a snapshot (issue #2154): each distinct grid is written
//! once into `Catalog.grids` and the masks of the photo's develop settings, versions, history
//! steps and import look refer to it by index, so an unchanged mask no longer repeats with every
//! history step. The table lives only in the snapshot file; log records keep the full grids
//! inline.
//!
//! **Background compaction** ([`Journal::snapshot_in_background`], when the store offers a
//! [`Store::background_writer`]): a worker thread writes the snapshot of a copy of the catalog at
//! op `N` while appends go on (durably, as always) to the same log. Once the snapshot is durable,
@@ -52,6 +61,9 @@
//! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` |
//! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` |
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) |
//! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` |
//! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
@@ -76,7 +88,7 @@ pub const LOG: &str = "catalog.log";
const FORMAT: &str = "lightcraft-catalog";
/// 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 = 9;
pub const VERSION: u32 = 12;
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
@@ -193,6 +205,10 @@ pub struct Journal {
/// A failed append may have left part of its records after `log_bytes`, and cutting them off
/// failed too: the next append cuts the log back to `log_bytes` first.
tail_dirty: bool,
/// An append failed (natively that can be the store's own log thread failing to write records
/// handed over before, which it holds and retries): the next chance writes a snapshot, a fresh
/// file holding everything, in case only the log's file is broken.
snapshot_due: bool,
}
/// A background snapshot in flight.
@@ -263,12 +279,18 @@ fn newer(what: String) -> CatalogError {
CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older"))
}
/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid
/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start
/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt
/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps
/// and reports, same state as before, minus the CPU.
const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
#[cfg(test)]
thread_local! {
/// Start markers that `resync` decoded on this thread (test builds only; see the cost test).
pub(crate) static RESYNC_CANDIDATES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Total bytes of candidate suffixes `resync` may decode per damaged line: every attempt reads
/// the rest of the line, so trying every candidate of a crafted line would make
/// [`Journal::open`] quadratic in the line length (CWE-407). The budget is far above any
/// fragment-plus-retry a failed append can leave, but caps the stall; past it the line reads as
/// damage, which is handled safely.
pub(crate) const MAX_SCAN: usize = 64 << 20;
/// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed
/// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns
@@ -276,32 +298,70 @@ const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
/// The record's CRC must match, so damage is never mistaken for it.
fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> {
const START: &[u8] = b"{\"seq\":";
// One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and
// one validation covers every candidate; only a line that is not wholly valid re-checks, and
// then up to the budget rather than the suffix length times the candidate count.
let whole = std::str::from_utf8(line).ok();
let mut spent = 0usize;
(1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| {
let text = match &whole {
Some(t) => &t[i..],
None => {
if spent >= RESYNC_BUDGET_BYTES {
return None;
}
spent = spent.saturating_add(line.len() - i);
std::str::from_utf8(&line[i..]).ok()?
}
// The retry record starts with the `{"seq":` marker, but that marker can also occur inside
// the op body (a smart-album rule value such as `{"seq":1}`); then the last occurrence is
// nested, not the record start, and decoding it rejects a valid retry. Scan every marker
// once, left to right, then try them from the end. A candidate must match the record header
// shape — `{"seq":<digits>,"crc":<digits>,"op":`, what `encode_record` writes — so a marker
// nested inside the op body (followed by `}` or `,`) or plain junk never reaches
// `decode_record`; only a real record start does. This imposes no fixed limit on how many
// nested markers a valid record may contain. Each attempt then decodes the rest of the line,
// so the scan budget bounds the total when a hostile line still holds many header-shaped
// markers, keeping the work near-linear instead of quadratic. The fragment that precedes the
// record stays to its left (`i > 0`).
let digits = |b: &[u8]| b.iter().take_while(|x| x.is_ascii_digit()).count();
let mut candidates: Vec<usize> = Vec::new();
let mut from = 0;
while let Some(i) = line[from..].windows(START.len()).position(|w| w == START) {
let pos = from + i;
let Some(after) = line.get(pos + START.len()..) else { break };
let seq_digits = digits(after);
let crc_field = after.get(seq_digits..).and_then(|rest| rest.strip_prefix(b",\"crc\":"));
let crc_digits = crc_field.map(digits).unwrap_or(0);
let op_field = crc_field.and_then(|rest| rest.get(crc_digits..)).and_then(|rest| rest.strip_prefix(b",\"op\":"));
if seq_digits > 0 && crc_digits > 0 && op_field.is_some() {
candidates.push(pos);
}
from = pos + START.len();
}
let mut scanned = 0usize;
for &i in candidates.iter().rev() {
if i == 0 {
break; // the record must follow a fragment
}
let Some(suffix) = line.get(i..) else { continue };
scanned = match scanned.checked_add(suffix.len()) {
Some(total) if total <= MAX_SCAN => total,
_ => break, // the budget is spent: stop trying further candidates
};
let rec = decode_record(text.trim_end_matches('\r'))?;
(rec.0 <= last.saturating_add(1)).then_some((i, rec))
})
let Ok(text) = std::str::from_utf8(suffix) else { continue };
#[cfg(test)]
RESYNC_CANDIDATES.with(|c| c.set(c.get() + 1));
if let Some((seq, op)) = decode_record(text.trim_end_matches('\u{0D}'))
&& seq <= last.saturating_add(1)
{
return Some((i, (seq, op)));
}
}
None
}
/// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no
/// whole-file string). The bytes are exactly
/// `{"format":"lightcraft-catalog","version":1,"seq":N,"catalog":<serde_json of the catalog>}\n`,
/// as before streaming. Fills in the serialise / write+sync times and the size.
/// as before streaming. Each distinct segmentation grid of the photos' settings holders (see
/// `Photo::settings_holders`) is written once (`Catalog.grids`), with the masks referring to it
/// by index, so an unchanged mask does not repeat with every history step (issue #2154). Fills
/// in the serialise / write+sync times and the size.
fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io::Result<SnapshotTiming> {
write_snapshot_owned(store, seq, catalog.clone())
}
/// The same write, taking the catalog by value: the background path hands over the copy it
/// already made, so a snapshot in flight holds one catalog, not two ([`Catalog::clone`] copies
/// the photo pointers and the small tables, and the derived indexes start empty — real work on a
/// large library).
fn write_snapshot_owned(store: &mut dyn Store, seq: u64, mut snapshot: Catalog) -> std::io::Result<SnapshotTiming> {
let t0 = web_time::Instant::now();
let mut serialize_ms = 0.0;
let bytes = store.write_atomic_with(SNAPSHOT, &mut |w| {
@@ -311,7 +371,35 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io
// 1 MiB chunks go through the store's `dyn Write`
let mut b = std::io::BufWriter::with_capacity(1 << 20, w);
write!(b, "{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"catalog\":")?;
serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?;
// The shared grids, in first-appearance order. The pool is a serialization detail:
// `snapshot` itself is never modified (log records, presets and XMP stay inline).
let mut pool: Vec<String> = Vec::new();
let mut index: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
{
let mut see = |s: &lightcraft_develop::DevelopSettings| {
s.visit_seg_masks(&mut |m| {
// borrowed lookup: a grid every history step shares is not cloned just to
// find it already indexed (only a new grid is copied, into pool and table)
if !m.data.is_empty() && !index.contains_key(m.data.as_str()) {
index.insert(m.data.clone(), pool.len() as u32);
pool.push(m.data.clone());
}
});
};
for p in snapshot.photos.values() {
for settings in p.settings_holders() {
see(settings);
}
}
}
snapshot.grids = pool;
match lightcraft_develop::with_grid_interner(index, || serde_json::to_writer(&mut b, &snapshot)) {
// no interner can be active here (snapshot writes don't nest), so `None` is a bug:
// fail the write rather than store a truncated or reference-less snapshot
Some(Ok(())) => {}
Some(Err(e)) => return Err(std::io::Error::other(e)),
None => return Err(std::io::Error::other("nested grid interner while writing a snapshot")),
}
b.write_all(b"}\n")?;
b.flush()?;
serialize_ms = ms_since(t);
@@ -381,6 +469,7 @@ impl Journal {
pending: None,
retry_at_records: 0,
tail_dirty: false,
snapshot_due: false,
};
let log = log.unwrap_or_default();
@@ -514,6 +603,7 @@ impl Journal {
self.tail_dirty = false;
}
if let Err(e) = self.store.append(LOG, buf.as_bytes()) {
self.snapshot_due = true;
// Part of the batch may be in the file. Cut it back to the last whole record, so the
// retry (same seqs) starts on a clean line instead of after a fragment that would
// read back as damage.
@@ -596,7 +686,7 @@ impl Journal {
let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) };
let copy = catalog.clone();
let seq = self.seq;
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot(writer.as_mut(), seq, &copy));
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot_owned(writer.as_mut(), seq, copy));
let worker = match spawned {
Ok(w) => w,
Err(e) => {
@@ -676,6 +766,7 @@ impl Journal {
}
fn record_snapshot(&mut self, t: SnapshotTiming) {
self.snapshot_due = false;
self.stats.snapshots += 1;
self.stats.last_snapshot = t;
self.stats.max_snapshot_ms = self.stats.max_snapshot_ms.max(t.total_ms);
@@ -695,6 +786,23 @@ impl Journal {
}
}
/// Wait until every appended record is in the file and synced (natively the store writes the
/// log on a thread of its own, [`crate::FsStore`]): before the files are read or copied from
/// outside. An error says why some aren't yet: they are held and retried, never dropped.
pub fn flush(&mut self) -> Result<()> {
self.store.flush().map_err(io)
}
/// Appended records the store holds because writing them failed (retried), and why; `None`
/// when nothing is held back. Never waits for the drive.
pub fn unwritten(&self) -> Option<(usize, String)> {
// a snapshot that holds every op holds whatever the log's thread still holds
if self.snapshot_seq >= self.seq && self.pending.is_none() {
return None;
}
self.store.unwritten()
}
/// Where persistence time went so far.
pub fn stats(&self) -> PersistStats {
PersistStats { snapshot_running: self.pending.is_some(), ..self.stats }
@@ -704,7 +812,10 @@ impl Journal {
pub fn wants_snapshot(&self) -> bool {
self.pending.is_none()
&& self.log_records >= self.retry_at_records
&& (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes)
&& (self.snapshot_due
|| self.unwritten().is_some()
|| self.log_records >= self.policy.max_records
|| self.log_bytes >= self.policy.max_bytes)
}
pub fn seq(&self) -> u64 {
@@ -760,4 +871,29 @@ mod tests_resync {
// matches, so the double `Some` is only reached with `last >= 4`
assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
}
/// A retry record whose op body holds more than eight nested `{"seq":` markers (a
/// `SetAlbumRules` with nine rule values of `{"seq":1}`) exhausts `resync`'s fixed
/// `MAX_DECODES = 8` decode budget on the nested markers, so the outer record's real
/// start is never decoded and the valid operation is truncated as damage.
#[test]
fn resync_recovers_retry_beyond_eight_nested_markers() {
let mut c = Catalog::new();
let album_id = c.alloc_album_id();
let mut rules = Vec::new();
for _ in 0..9 {
rules.push(crate::Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) });
}
let retry_op = Op::SetAlbumRules {
id: album_id,
rules: Box::new(crate::Filter { rule_set: Some(crate::RuleSet { mode: crate::Match::All, rules }), ..Default::default() }),
};
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let record = format!("{{\"seq\":5,\"crc\":{crc},\"op\":{body}}}");
let mut line = Vec::from(b"torn fragment" as &[u8]);
let fragment = line.len();
line.extend_from_slice(record.as_bytes());
assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
}
}
+123 -23
View File
@@ -43,6 +43,33 @@ pub fn reparent(k: &str, from: &str, to: &str) -> String {
std::iter::once(to).filter(|t| !t.is_empty()).chain(rest).collect::<Vec<_>>().join("|")
}
/// A photo's keywords as a sidecar writes them: the two lists [`to_file`] fills.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FileKeywords {
/// For `dc:subject`: every level of every keyword, each once.
pub flat: Vec<String>,
/// For `lr:hierarchicalSubject`: every keyword as its path, when any keyword has levels;
/// empty otherwise, so a library without hierarchy doesn't gain the property.
pub hierarchical: Vec<String>,
}
/// A photo's keywords as a sidecar writes them, the inverse of [`from_file`]. `dc:subject` is the
/// flat list other applications search, so it gets names (`travel`, `Italy`, `Rome`), never paths,
/// as Lightroom Classic and darktable write it; the paths go to `lr:hierarchicalSubject`. Unlike
/// [`Catalog::export_keywords`] it applies no export options (a sidecar is the photo's own record,
/// not an export): no keyword is left out and no synonym added, so [`from_file`] reads the pair
/// back as the same keywords. When any keyword has levels, every keyword is listed in
/// `hierarchical`, the flat ones too: a flat `Rome` beside `travel|Italy|Rome` would otherwise be
/// taken for a level of the path on the way back.
pub fn to_file(keywords: &[String]) -> FileKeywords {
let mut paths: Vec<String> = keywords.iter().map(|k| clean(k)).collect();
dedupe(&mut paths);
let mut flat: Vec<String> = paths.iter().flat_map(|p| p.split(SEP).map(str::to_string)).collect();
dedupe(&mut flat);
let hierarchical = if paths.iter().any(|p| p.contains(SEP)) { paths } else { Vec::new() };
FileKeywords { flat, hierarchical }
}
/// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, then the
/// names of `dc:subject` that aren't levels of those paths (Lightroom Classic writes each keyword's
/// name, its parents' and synonyms flat besides its path). Each once, cleaned.
@@ -60,6 +87,12 @@ pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec<String> {
/// The deepest a keyword list file may nest keywords: a file is input, so its nesting is bounded.
pub const MAX_LEVELS: usize = 64;
/// The most bytes of full keyword paths a keyword list file may spell out. Every line names its
/// keyword by its whole path (`parent|child`), so a file of one long keyword with many short ones
/// inside it would otherwise grow into far more memory than its own size (CWE-400). Lightroom
/// Classic's own lists of tens of thousands of keywords come to a few MiB.
pub const MAX_LIST_PATH_BYTES: usize = 64 << 20; // 64 MiB
/// A keyword list as written by [`Catalog::keyword_list_text`]: the file's text, the keywords in
/// it (paths), and what the format can't hold and so is left out (a keyword, with those inside it,
/// as its path; a synonym as `path {synonym}`).
@@ -87,6 +120,8 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
let mut synonyms: std::collections::HashMap<usize, std::collections::HashSet<String>> = std::collections::HashMap::new();
// the keyword at each level above the line: its path and where it is in `out`
let mut above: Vec<(String, usize)> = Vec::new();
// bytes of full paths spelled out so far, checked against `MAX_LIST_PATH_BYTES` before each
let mut path_bytes = 0usize;
for (i, line) in text.split('\n').enumerate() {
let n = i + 1;
if line.trim().is_empty() {
@@ -135,6 +170,11 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
return Err(bad(n, "“|” separates a keyword's levels: a name can't hold one"));
}
above.truncate(depth);
let parent_len = above.last().map_or(0, |(parent, _)| parent.len().saturating_add(1));
path_bytes = path_bytes.saturating_add(parent_len.saturating_add(name.len()));
if path_bytes > MAX_LIST_PATH_BYTES {
return Err(bad(n, &format!("the keywords' full paths come to more than {} MiB", MAX_LIST_PATH_BYTES >> 20)));
}
let path = match above.last() {
Some((parent, _)) => format!("{parent}{SEP}{name}"),
None => name.to_string(),
@@ -162,6 +202,14 @@ pub fn closest<'a>(k: &str, from: &'a [String]) -> Option<&'a String> {
from.iter().filter(|f| is_under(k, f)).max_by_key(|f| f.split(SEP).count())
}
/// Add each of `more` to `synonyms` that isn't there in any case, in order. One lowered set of
/// what is there, not a search of the growing list per synonym: an imported list can give a
/// keyword many synonyms, and the search was quadratic in them (CWE-407).
fn merge_synonyms(synonyms: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
let mut seen: std::collections::HashSet<String> = synonyms.iter().map(|s| s.to_lowercase()).collect();
synonyms.extend(more.into_iter().filter(|s| seen.insert(s.to_lowercase())));
}
/// Keep the first of case-insensitively equal keywords.
fn dedupe(v: &mut Vec<String>) {
let mut seen = std::collections::HashSet::new();
@@ -192,6 +240,10 @@ pub struct KeywordInfo {
/// most, see [`Catalog::default_keyword_parent`].
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub new_keywords_inside: bool,
/// Part of the keyword shortcut (Set Keyword Shortcut), which ⇧K adds to or removes from the
/// selected photos: see [`Catalog::keyword_shortcut`].
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub keyword_shortcut: bool,
}
fn yes() -> bool {
@@ -207,6 +259,7 @@ impl Default for KeywordInfo {
export_synonyms: true,
person: false,
new_keywords_inside: false,
keyword_shortcut: false,
}
}
}
@@ -369,11 +422,8 @@ impl Catalog {
match list.get_mut(&path.to_lowercase()) {
Some(there) => {
there.info.new_keywords_inside |= l.info.new_keywords_inside;
for s in l.info.synonyms {
if !there.info.synonyms.iter().any(|x| same(x, &s)) {
there.info.synonyms.push(s);
}
}
there.info.keyword_shortcut |= l.info.keyword_shortcut;
merge_synonyms(&mut there.info.synonyms, l.info.synonyms);
}
None => {
list.insert(path.to_lowercase(), ListedKeyword { path, info: l.info });
@@ -434,8 +484,11 @@ impl Catalog {
let defaults = KeywordInfo::default();
let info = |path: &str| self.keyword_info(path).unwrap_or(&defaults);
let mut out = ExportKeywords::default();
let push = |v: &mut Vec<String>, s: &str| {
if !s.is_empty() && !v.iter().any(|x| same(x, s)) {
// what each list holds, lowered: a search of the list per name was quadratic in a keyword's
// synonyms, which an imported list sets (CWE-407)
let (mut flat_seen, mut paths_seen) = (std::collections::HashSet::new(), std::collections::HashSet::new());
let push = |v: &mut Vec<String>, seen: &mut std::collections::HashSet<String>, s: &str| {
if !s.is_empty() && seen.insert(s.to_lowercase()) {
v.push(s.to_string());
}
};
@@ -448,11 +501,11 @@ impl Catalog {
let levels: Vec<&str> = path.split(SEP).collect();
let mut names = |at: usize, i: &KeywordInfo| {
if let Some(name) = levels.get(at) {
push(&mut out.flat, name);
push(&mut out.flat, &mut flat_seen, name);
}
if i.export_synonyms {
for s in &i.synonyms {
push(&mut out.flat, s.trim());
push(&mut out.flat, &mut flat_seen, s.trim());
}
}
};
@@ -466,7 +519,7 @@ impl Catalog {
}
}
}
push(&mut out.hierarchical, &path);
push(&mut out.hierarchical, &mut paths_seen, &path);
}
out
}
@@ -476,6 +529,13 @@ impl Catalog {
/// keyword, a keyword left out of export in square brackets; by name. What the format can't hold
/// is left out and named, so the file always reads back.
pub fn keyword_list_text(&self) -> KeywordListFile {
self.keyword_list_text_within(MAX_LIST_PATH_BYTES)
}
/// [`keyword_list_text`](Self::keyword_list_text) with the full paths written held to
/// `max_path_bytes` as [`parse_keyword_list`] holds them: a keyword past it is named
/// unwritable, with its subtree, so the file reads back.
fn keyword_list_text_within(&self, max_path_bytes: usize) -> KeywordListFile {
// a name the list would read as something else, or not at all
fn unwritable(name: &str) -> bool {
name.trim().is_empty()
@@ -486,14 +546,27 @@ impl Catalog {
|| (name.starts_with('[') && name.ends_with(']'))
|| (name.starts_with('{') && name.ends_with('}'))
}
fn write(c: &Catalog, nodes: &[KeywordNode], depth: usize, file: &mut KeywordListFile) {
fn write(
c: &Catalog,
nodes: &[KeywordNode],
depth: usize,
file: &mut KeywordListFile,
path_bytes: &mut usize,
max_path_bytes: usize,
parent_len: usize,
) {
let tabs = "\t".repeat(depth);
for n in nodes {
// the keywords inside go with it: under its parent they'd be other keywords
if depth >= MAX_LEVELS || unwritable(&n.name) {
// (a line's full path is what the reader counts against its path budget)
// the path the reader rebuilds from the lines written: the parent as emitted, a
// separator, the name (a child's `n.path` can spell its parent in another case)
let emitted = if depth == 0 { n.name.len() } else { parent_len + SEP.len_utf8() + n.name.len() };
if depth >= MAX_LEVELS || unwritable(&n.name) || path_bytes.saturating_add(emitted) > max_path_bytes {
file.unwritable.push(n.path.clone());
continue;
}
*path_bytes += emitted;
let info = c.keyword_info(&n.path).cloned().unwrap_or_default();
if info.include_on_export {
file.text.push_str(&format!("{tabs}{}\n", n.name));
@@ -503,19 +576,21 @@ impl Catalog {
file.written.push(n.path.clone());
// the reader trims synonyms and takes one per spelling: an empty one, or another's
// in a different case, is no loss; a line break or a “|” is
let mut synonyms: Vec<&str> = Vec::new();
// (one lowered set, not a search of those written so far per synonym: quadratic
// in a keyword's synonyms, which an imported list sets — CWE-407)
let mut synonyms: std::collections::HashSet<String> = std::collections::HashSet::new();
for s in info.synonyms.iter().map(|s| s.trim()) {
if s.is_empty() || synonyms.iter().any(|x| same(x, s)) {
if s.is_empty() || synonyms.contains(&s.to_lowercase()) {
continue;
}
if s.chars().any(char::is_control) || s.contains(SEP) {
file.unwritable.push(format!("{} {{{s}}}", n.path));
} else {
synonyms.push(s);
synonyms.insert(s.to_lowercase());
file.text.push_str(&format!("{tabs}\t{{{s}}}\n"));
}
}
write(c, &n.children, depth + 1, file);
write(c, &n.children, depth + 1, file, path_bytes, max_path_bytes, emitted);
}
}
let mut file = KeywordListFile::default();
@@ -535,7 +610,7 @@ impl Catalog {
}
}
}
write(self, &self.keyword_tree(), 0, &mut file);
write(self, &self.keyword_tree(), 0, &mut file, &mut 0, max_path_bytes, 0);
file.unwritable.extend(over_deep);
file
}
@@ -580,7 +655,13 @@ impl Catalog {
continue;
}
if !known.contains_key(&key) {
list.insert(key.clone(), ListedKeyword { path: path.clone(), info: KeywordInfo { new_keywords_inside: false, ..info.clone() } });
list.insert(
key.clone(),
ListedKeyword {
path: path.clone(),
info: KeywordInfo { new_keywords_inside: false, keyword_shortcut: false, ..info.clone() },
},
);
// it and its parents are the library's now: what follows spells them so
let levels: Vec<&str> = path.split(SEP).collect();
for i in 0..levels.len() {
@@ -593,11 +674,7 @@ impl Catalog {
// one the library has: the list's synonyms join its own (listed only if it gains some)
let mut info_now = list.get(&key).map(|l| l.info.clone()).unwrap_or_default();
let before = info_now.synonyms.len();
for s in &info.synonyms {
if !info_now.synonyms.iter().any(|x| same(x, s)) {
info_now.synonyms.push(s.clone());
}
}
merge_synonyms(&mut info_now.synonyms, info.synonyms.iter().cloned());
if info_now.synonyms.len() > before {
let path = list.get(&key).map_or(path, |l| l.path.clone());
list.insert(key, ListedKeyword { path, info: info_now });
@@ -666,6 +743,29 @@ impl Catalog {
})
}
/// The keyword shortcut's keywords (Set Keyword Shortcut), in the keyword list's order.
pub fn keyword_shortcut(&self) -> Vec<String> {
self.keyword_list.values().filter(|l| l.info.keyword_shortcut).map(|l| l.path.clone()).collect()
}
/// Make `keywords` the keyword shortcut, in one batch. A keyword the library doesn't have yet is
/// listed, and the others keep the attributes they have.
pub fn set_keyword_shortcut_ops(&self, keywords: &[String]) -> Op {
let paths: Vec<String> =
keywords.iter().map(|k| self.keyword_path(k).unwrap_or_else(|| self.spelled(&clean(k)))).filter(|k| !k.is_empty()).collect();
Op::Batch {
ops: self.list_ops(|list| {
for l in list.values_mut() {
l.info.keyword_shortcut = false;
}
for path in paths {
let l = list.entry(path.to_lowercase()).or_insert_with(|| ListedKeyword { path, info: KeywordInfo::default() });
l.info.keyword_shortcut = true;
}
}),
}
}
/// The keyword as written in the library (whatever the case of `path`): its listing, or the
/// levels a photo's keyword spells it with. `None` when there is no such keyword.
pub fn keyword_path(&self, path: &str) -> Option<String> {
+117 -1
View File
@@ -424,6 +424,36 @@ fn one_keyword_is_where_new_keywords_go() {
assert_eq!(c.default_keyword_parent(), None, "undo of the first: none was");
}
/// The keyword shortcut is a mark on its keywords: setting it is one undo step (a new name is
/// listed), and the mark moves with its keyword (also into a merge), goes with it, and comes
/// back with undo.
#[test]
fn the_keyword_shortcut_moves_with_its_keywords() {
let (mut c, _) = lib(&[&["Events|Weddings"], &["Travel"]]);
let op = c.set_keyword_shortcut_ops(&["travel".into(), "Lisbon".into()]);
let undo = c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Lisbon", "Travel"], "spelled as the library spells it; a new name listed");
let op = c.set_keyword_shortcut_ops(&["events|weddings".into(), "Travel".into()]);
c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings", "Travel"], "the old marks are cleared");
let op = c.rename_keyword_ops("travel", "Trips").unwrap();
let undo_rename = c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings", "Trips"]);
c.apply(undo_rename).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings", "Travel"], "undo moves it back");
let op = c.set_keyword_shortcut_ops(&["Travel".into()]);
c.apply(op).unwrap();
let op = c.merge_keywords_ops(&["travel".into()], "Events|Weddings").unwrap();
c.apply(op).unwrap();
assert_eq!(c.keyword_shortcut(), ["Events|Weddings"], "into the merge");
let op = c.delete_keyword_ops("events").unwrap();
c.apply(op).unwrap();
assert!(c.keyword_shortcut().is_empty());
assert_eq!(c.set_keyword_shortcut_ops(&[]), Op::Batch { ops: vec![] }, "none to clear");
c.apply(undo).unwrap();
assert!(c.keyword_shortcut().is_empty(), "undo of the first: there was none");
}
/// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, and the
/// names of `dc:subject` that aren't levels of those paths (an exported `travel|Italy` comes
/// back as one keyword, not three). Without paths, the names as they are.
@@ -433,7 +463,38 @@ fn a_files_keywords_keep_their_hierarchy() {
assert_eq!(from_file(&v(&["Rome", "Italy", "travel", "beach"]), &v(&["travel|Italy|Rome"])), ["travel|Italy|Rome", "beach"]);
assert_eq!(from_file(&v(&["ROME"]), &v(&["travel|Rome", " travel | rome "])), ["travel|Rome"], "each once, cleaned");
assert_eq!(from_file(&v(&["beach", " sea "]), &[]), ["beach", "sea"]);
assert_eq!(from_file(&v(&["a|b"]), &[]), ["a|b"], "LightCraft's own sidecars write paths flat");
assert_eq!(from_file(&v(&["a|b"]), &[]), ["a|b"], "sidecars from LightCraft 0.13 and older wrote paths flat");
}
/// A sidecar's keywords: names in `dc:subject`, never paths, and the paths in
/// `lr:hierarchicalSubject`; read back, the same keywords, however they were spelt or nested.
#[test]
fn a_sidecar_writes_names_flat_and_paths_hierarchical() {
let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let f = to_file(&v(&["Places|Italy|Rome", "sunset"]));
assert_eq!(f.flat, ["Places", "Italy", "Rome", "sunset"]);
assert_eq!(f.hierarchical, ["Places|Italy|Rome", "sunset"]);
assert!(f.flat.iter().all(|k| !k.contains(SEP)), "no path in dc:subject");
let f = to_file(&v(&["beach", " sea ", "Beach"]));
assert_eq!((f.flat, f.hierarchical), (v(&["beach", "sea"]), v(&[])), "no hierarchy: no lr:hierarchicalSubject");
assert_eq!(to_file(&[]), FileKeywords::default());
for keywords in [
v(&["Places|Italy|Rome", "sunset"]),
v(&["travel|Italy|Rome", "Rome"]),
v(&["travel|Italy", "travel|France", "Italy"]),
v(&["beach", "sea"]),
v(&[" a | b ", "A|B|c"]),
] {
let f = to_file(&keywords);
let mut back = from_file(&f.flat, &f.hierarchical);
let mut want: Vec<String> = keywords.iter().map(|k| clean(k)).collect();
dedupe(&mut want);
back.sort_by_key(|k| k.to_lowercase());
want.sort_by_key(|k| k.to_lowercase());
assert_eq!(back, want, "round trip of {keywords:?}");
}
}
/// A new keyword inside one the library has takes the library's spelling of it: creating
@@ -495,6 +556,17 @@ fn the_keyword_list_is_written_as_tab_indented_text() {
assert_eq!(c.keyword_list_text().text, "beach\nEvents\n\tWeddings\n[Places]\n\tLisbon\n\t\t{Lisboa}\n");
}
/// The path budget the reader enforces holds for the writer too: a keyword past it, and its
/// subtree, is named unwritable instead of making a file `keyword.import` rejects.
#[test]
fn the_keyword_list_written_stays_within_the_path_budget() {
let (c, _) = lib(&[&["Places|Lisbon", "beach"], &["Events|Weddings"]]);
let file = c.keyword_list_text_within(17);
assert_eq!(file.text, "beach\nEvents\nPlaces\n");
assert_eq!(file.unwritable, ["Events|Weddings", "Places|Lisbon"]);
assert_eq!(c.keyword_list_text().unwritable, Vec::<String>::new());
}
/// Reading a list gives each keyword's path and attributes: what was written comes back, and a
/// file from elsewhere (Windows line ends, a byte-order mark, blank lines) reads too.
#[test]
@@ -704,3 +776,47 @@ fn keyword_tree_caps_a_keyword_at_the_list_depth() {
let deepest = tree_paths(&c.keyword_tree()).iter().map(|(p, _)| p.split(SEP).count()).max().unwrap_or(0);
assert_eq!(deepest, MAX_LEVELS);
}
/// A keyword list file spells each keyword's whole path, so one long keyword with many short ones
/// inside it expands into far more than its own size: past `MAX_LIST_PATH_BYTES` it is refused
/// with the line where that happened, instead of growing without bound (CWE-400).
#[test]
fn a_list_whose_paths_expand_past_the_budget_is_refused() {
let parent = "p".repeat(1 << 20);
let children = MAX_LIST_PATH_BYTES / parent.len() + 2;
let mut text = format!("{parent}\n");
for i in 0..children {
text.push_str(&format!("\tc{i}\n"));
}
let err = parse_keyword_list(&text).unwrap_err().to_string();
assert!(err.contains("full paths come to more than"), "{err}");
// a list within the budget still reads
let ok = parse_keyword_list(&format!("{parent}\n\tchild\n")).unwrap();
assert_eq!(ok.len(), 2);
assert_eq!(ok[1].0, format!("{parent}|child"));
}
/// Many synonyms joining a keyword the library has, its export and its keyword list file each keep
/// every spelling once, in order, without a search of the growing list per synonym (CWE-407).
#[test]
fn many_synonyms_are_gathered_once_each_in_order() {
const N: usize = 40_000;
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "travel".into(), info: Some(with_synonyms(&["Trip"])) }).unwrap();
let mut incoming: Vec<String> = (0..N).map(|i| format!("syn{i}")).collect();
incoming.push("TRIP".into());
incoming.push("SYN7".into());
let started = std::time::Instant::now();
let (op, added, updated) = c.import_keywords_ops(&[("travel".into(), KeywordInfo { synonyms: incoming, ..KeywordInfo::default() })]);
c.apply(op).unwrap();
assert_eq!((added, updated), (0, 1));
let synonyms = c.keyword_info("travel").unwrap().synonyms.clone();
assert_eq!(synonyms.len(), N + 1);
assert_eq!(synonyms[0], "Trip");
assert_eq!(synonyms[8], "syn7");
let exported = c.export_keywords(&["travel".into()]);
assert_eq!(exported.flat.len(), N + 2);
let file = c.keyword_list_text();
assert_eq!(file.text.lines().count(), N + 2);
assert!(started.elapsed() < std::time::Duration::from_secs(20), "took {:?}", started.elapsed());
}
+345 -7
View File
@@ -14,12 +14,17 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod dates;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub mod fault;
pub mod folders;
mod index;
pub mod journal;
pub mod keywords;
pub mod local;
pub mod lock;
#[cfg(not(target_arch = "wasm32"))]
mod log_writer;
pub mod model;
pub mod query;
pub mod rules;
@@ -284,6 +289,13 @@ pub struct Catalog {
/// What the library keeps about its folders (folder identity → record), see [`folders`].
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
folder_records: BTreeMap<String, FolderRecord>,
/// Segmentation grids shared by this snapshot's masks: each distinct grid's data once, in
/// first-appearance order, referenced by index from the masks ([`lightcraft_develop::\
/// SegMask::grid`] is a position here). A serialization detail of snapshots
/// ([`journal`]): never held in the live catalog — [`Catalog::repair`] resolves the
/// references and clears the table when a snapshot is read.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
grids: Vec<String>,
/// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog
/// changed, so what is keyed by the revision is out of date).
#[serde(skip)]
@@ -294,6 +306,10 @@ pub struct Catalog {
/// Lookups derived from the above (never saved), see [`index`].
#[serde(skip)]
index: index::Indexes,
/// Each smart album's rules ready to run (cheapest rule first), worked out when first asked and
/// forgotten when an op adds or removes an album or changes rules.
#[serde(skip)]
plans: PlansMemo,
}
/// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a
@@ -332,6 +348,51 @@ impl Aspects {
/// The most photos remembered as touched; older changes are then answered with "anything may have changed".
const MAX_TOUCHED: usize = 8192;
/// [`Catalog::plans`] as last worked out: derived from the albums, like [`index::Indexes`], so no
/// part of what a catalog is; a copy starts without it.
#[derive(Default)]
struct PlansMemo {
plans: std::sync::OnceLock<std::collections::HashMap<AlbumId, query::Prepared>>,
guard: std::sync::OnceLock<bool>,
}
impl Clone for PlansMemo {
fn clone(&self) -> Self {
Self::default()
}
}
impl PartialEq for PlansMemo {
fn eq(&self, _: &PlansMemo) -> bool {
true
}
}
impl std::fmt::Debug for PlansMemo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PlansMemo")
}
}
/// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`])
/// against a snapshot's grid table: each referenced mask takes its
/// grid's data and the reference is cleared. A reference past the table (a damaged snapshot)
/// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the
/// mask itself wins over a stray reference. Returns the dangling count added to `dangling`.
fn resolve_grids(settings: &mut Arc<DevelopSettings>, grids: &[String], dangling: usize) -> usize {
let mut dangling = dangling;
Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| {
if let Some(i) = m.grid.take() {
match (m.data.is_empty(), grids.get(i as usize)) {
(true, Some(data)) => m.data = data.clone(),
(true, None) => dangling += 1,
(false, _) => {}
}
}
});
dangling
}
/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
/// follow a small edit without being worked out again from every photo.
#[derive(Clone, Debug, Default)]
@@ -442,12 +503,61 @@ impl Catalog {
/// no smart album).
pub fn album_contains(&self, id: AlbumId, p: &Photo) -> bool {
match self.albums.get(&id) {
Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_one(), p),
Some(Album { smart: Some(rules), .. }) => match self.plans().get(&id) {
Some(plan) => self.smart_album_has(id, rules, plan, p),
None => self.smart_album_has(id, rules, &rules.prepare_one(self), p),
},
Some(a) => self.album_lists(a.id, p.id),
None => false,
}
}
/// Every smart album's [`Filter::prepare_one`], worked out once for the albums as they are
/// (so a photo asked about does not prepare the album's rules again).
fn plans(&self) -> &std::collections::HashMap<AlbumId, query::Prepared> {
self.plans.plans.get_or_init(|| self.albums.values().filter_map(|a| a.smart.as_ref().map(|rules| (a.id, rules.prepare_one(self)))).collect())
}
/// Whether rules must be tested as written, not cheapest first ([`Filter::prepare`]): some smart
/// album tests itself (a saved or damaged catalog; the app refuses to make one), or a chain of
/// smart albums testing smart albums is as long as [`rules::MAX_ALBUM_DEPTH`], where the
/// innermost hold nothing. There an answer can depend on which album was asked first (the
/// answers memo keeps what was worked out under the cut), so reordering could change who
/// matches. Worked out once for the albums as they are.
pub(crate) fn keeps_written_order(&self) -> bool {
*self.plans.guard.get_or_init(|| {
self.albums.values().any(|a| a.smart.is_some() && self.album_reaches(a.id, a.id)) || self.longest_chain() >= rules::MAX_ALBUM_DEPTH
})
}
/// The most smart albums one smart album leads through, itself included, by the smart albums
/// its rules and album filter test. Only asked of albums that lead back to none.
fn longest_chain(&self) -> usize {
let tests = |id: &AlbumId| -> Vec<AlbumId> {
let tested = self.albums.get(id).and_then(|a| a.smart.as_deref()).map(Filter::albums_tested).unwrap_or_default();
tested.into_iter().filter(|t| self.albums.get(t).is_some_and(|a| a.smart.is_some())).collect()
};
let mut chain: std::collections::HashMap<AlbumId, usize> = std::collections::HashMap::new();
for root in self.albums.values().filter(|a| a.smart.is_some()).map(|a| a.id) {
let mut stack = vec![root];
while let Some(a) = stack.last().copied() {
if chain.contains_key(&a) {
stack.pop();
continue;
}
let kids = tests(&a);
let pending: Vec<AlbumId> = kids.iter().copied().filter(|k| !chain.contains_key(k)).collect();
if pending.is_empty() {
chain.insert(a, 1 + kids.iter().filter_map(|k| chain.get(k)).copied().max().unwrap_or(0));
stack.pop();
} else {
stack.extend(pending);
}
}
}
chain.values().copied().max().unwrap_or(0)
}
/// Whether smart album `id` with `rules` (as [`Filter::prepare`]d) holds `p`.
fn smart_album_has(&self, id: AlbumId, rules: &Filter, prepared: &query::Prepared, p: &Photo) -> bool {
// guarded: a smart album testing smart albums can't loop or recurse without end
@@ -502,7 +612,7 @@ impl Catalog {
pub fn album_photos(&self, id: AlbumId) -> Vec<PhotoId> {
match self.albums.get(&id) {
Some(Album { smart: Some(rules), .. }) => {
let prepared = rules.prepare();
let prepared = rules.prepare(self);
self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect()
}
Some(a) => a.photos.clone(),
@@ -515,7 +625,7 @@ impl Catalog {
match self.albums.get(&id) {
// counted in place: no id list is built just for its length
Some(Album { smart: Some(rules), .. }) => {
let prepared = rules.prepare();
let prepared = rules.prepare(self);
self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).count()
}
Some(a) => a.photos.iter().filter(|p| self.photos.get(p).is_some_and(|p| !p.deleted)).count(),
@@ -652,6 +762,44 @@ impl Catalog {
Ok(inv)
}
/// [`Self::apply`] for a new edit (not an undo, a redo or the replay of a saved log, which bring
/// back what was): refused when it would put a smart album on a loop, one that includes itself
/// through the albums it tests. THE place that rule is kept, whichever command, importer or
/// task makes the edit, alone or in a batch. A library that already holds a loop still opens,
/// and an edit that puts no album on one it was not on goes through, also to an album on a loop.
///
/// The check is made on what the edit would do to the albums, before it is done: a refused
/// edit never touched the library, so there is nothing to take back.
pub fn apply_new(&mut self, op: Op) -> Result<Op> {
if let Some((id, name)) = self.would_put_on_a_loop(&op) {
return Err(CatalogError::Invalid(format!(
"smart album “{name}” (album {}) would include itself: its rules lead back to it through the albums they test",
id.0
)));
}
self.apply(op)
}
/// The album `op` would newly put on a loop, as its id and name: the album the op is about
/// when that is one of them. `None` when it makes none (or changes no album's rules).
fn would_put_on_a_loop(&self, op: &Op) -> Option<(AlbumId, String)> {
if !changes_what_albums_test(op) {
return None;
}
let mut graph = AlbumGraph::of(self.albums.values());
let now = graph.on_a_loop();
let mut edited = Vec::new();
foresee(&mut graph, op, &mut edited);
let then = graph.on_a_loop();
let name_of = |id: AlbumId| self.albums.get(&id).map(|a| a.name.clone()).unwrap_or_default();
let new_edited = edited.iter().find(|(id, _)| then.contains(id) && !now.contains(id));
match new_edited {
Some((id, name)) => Some((*id, name.map_or_else(|| name_of(*id), str::to_string))),
// an album the edit is not about (it tests one that now leads back to it)
None => then.difference(&now).next().map(|id| (*id, name_of(*id))),
}
}
fn apply_inner(&mut self, op: Op) -> Result<Op> {
// An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind
// can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's
@@ -699,10 +847,11 @@ impl Catalog {
| Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1),
}
Ok(match op {
Op::AddPhoto { photo } => {
Op::AddPhoto { mut photo } => {
if self.photos.contains_key(&photo.id) {
return Err(CatalogError::Invalid(format!("photo {:?} exists", photo.id)));
}
photo.trim_history();
let id = photo.id;
self.next_photo = self.next_photo.max(id.0.saturating_add(1));
self.photos.insert(id, Arc::new(*photo));
@@ -753,7 +902,14 @@ impl Catalog {
}
Op::SetHistory { id, history } => {
let p = self.photo_mut(id)?;
Op::SetHistory { id, history: std::mem::replace(&mut p.history, history) }
let old = std::mem::replace(&mut p.history, history);
let old_cursor = p.history_cursor;
p.trim_history();
if p.history_cursor == old_cursor {
Op::SetHistory { id, history: old }
} else {
Op::Batch { ops: vec![Op::SetHistory { id, history: old }, Op::SetHistoryCursor { id, cursor: old_cursor }] }
}
}
Op::PushHistory { id, step } => {
let p = self.photo_mut(id)?;
@@ -779,6 +935,7 @@ impl Catalog {
Op::SetHistoryCursor { id, cursor: std::mem::replace(&mut p.history_cursor, cursor) }
}
Op::AddAlbum { album } => {
self.plans = PlansMemo::default();
if self.albums.contains_key(&album.id) {
return Err(CatalogError::Invalid(format!("album {:?} exists", album.id)));
}
@@ -800,6 +957,7 @@ impl Catalog {
Op::RemoveAlbum { id }
}
Op::RemoveAlbum { id } => {
self.plans = PlansMemo::default();
if self.albums.values().any(|a| a.parent == Some(id)) {
return Err(CatalogError::Invalid("folder is not empty".into()));
}
@@ -860,6 +1018,7 @@ impl Catalog {
Op::SetAlbumCover { id, cover: std::mem::replace(&mut a.cover, cover) }
}
Op::SetAlbumRules { id, rules } => {
self.plans = PlansMemo::default();
self.validate_rules(&rules)?;
let a = self.album_mut(id)?;
let Some(old) = a.smart.as_mut() else {
@@ -1054,15 +1213,37 @@ impl Catalog {
/// finds in them, and walks folders up to the top): every photo, album and stack carries the
/// id it is filed under; the id counters lie past every id in use; a stack keeps only photos
/// in the catalog, once each, and goes when fewer than two are left; an album whose parent is
/// missing, not a folder or inside itself moves to the top level. Returns what was changed
/// (nothing, for a catalog this build wrote).
/// missing, not a folder or inside itself moves to the top level; a photo keeps its newest
/// [`HISTORY_LIMIT`] History steps. Returns what was changed (nothing, for a catalog this build
/// wrote).
pub fn repair(&mut self) -> Vec<String> {
let mut changed = Vec::new();
// Segmentation grids shared by the snapshot this was read from (issue #2154): each
// reference takes its grid's data, and the table is not kept — a live catalog always
// stores the data inline, so masks render and serialize without the snapshot's table.
// Resolving is the normal way a snapshot in this format reads (not reported); a
// reference past the table is damage and is reported — that includes a reference into
// an empty table, which is always dangling, so the table being empty does not skip it.
let grids = std::mem::take(&mut self.grids);
let mut dangling = 0usize;
for p in self.photos.values_mut() {
let photo = Arc::make_mut(p);
for settings in photo.settings_holders_mut() {
dangling = resolve_grids(settings, &grids, dangling);
}
}
if dangling > 0 {
changed.push(format!("{dangling} segmentation grid reference(s) pointed past the shared table: cleared"));
}
for (id, p) in self.photos.iter_mut() {
if p.id != *id {
changed.push(format!("photo {} was filed as {}", p.id.0, id.0));
Arc::make_mut(p).id = *id;
}
if p.history.len() > HISTORY_LIMIT {
let n = Arc::make_mut(p).trim_history();
changed.push(format!("photo {}: {n} History step(s) beyond the newest {HISTORY_LIMIT} dropped", id.0));
}
}
for (id, a) in self.albums.iter_mut() {
if a.id != *id {
@@ -1149,6 +1330,8 @@ impl Catalog {
if !changed.is_empty() {
// stacks and albums changed outside `apply`: the lookups are built again when asked
self.index = index::Indexes::default();
// (and what was worked out from the albums, the guard of [`Self::keeps_written_order`] too)
self.plans = PlansMemo::default();
}
changed
}
@@ -1180,6 +1363,153 @@ impl Catalog {
}
}
/// Whether `op` changes which albums a smart album tests: it adds or removes an album, or changes
/// rules (alone or in a batch).
fn changes_what_albums_test(op: &Op) -> bool {
// listed kind by kind (as in `apply_inner`), so a new kind has to be put on one side
match op {
Op::AddAlbum { .. } | Op::RemoveAlbum { .. } | Op::SetAlbumRules { .. } => true,
Op::Batch { ops } => ops.iter().any(changes_what_albums_test),
Op::AddPhoto { .. }
| Op::RemovePhoto { .. }
| Op::SetDeleted { .. }
| Op::SetLocal { .. }
| Op::SetContent { .. }
| Op::SetEmbeddedLens { .. }
| Op::SetAsShotWb { .. }
| Op::SetRating { .. }
| Op::SetFlag { .. }
| Op::SetLabel { .. }
| Op::SetMeta { .. }
| Op::SetCaptured { .. }
| Op::SetFile { .. }
| Op::Relink { .. }
| Op::SetAnalysis { .. }
| Op::SetDevelop { .. }
| Op::SetVersions { .. }
| Op::SetHistory { .. }
| Op::PushHistory { .. }
| Op::SetHistoryCursor { .. }
| Op::RenameAlbum { .. }
| Op::MoveAlbum { .. }
| Op::SetAlbumOrder { .. }
| Op::SetAlbumPhotos { .. }
| Op::SetAlbumCover { .. }
| Op::AddStack { .. }
| Op::RemoveStack { .. }
| Op::SetStack { .. }
| Op::SetLabelName { .. }
| Op::SetBrowsed { .. }
| Op::SetKeyword { .. }
| Op::SetFolderRecord { .. } => false,
}
}
/// What `op` would do to `graph`, as far as loops go (which album tests which), without the
/// checks `apply` makes: an op it would refuse is refused there. `edited` gets the albums the op
/// is about, with their name when the op brings it.
fn foresee<'a>(graph: &mut AlbumGraph, op: &'a Op, edited: &mut Vec<(AlbumId, Option<&'a str>)>) {
match op {
Op::AddAlbum { album } => {
// an id that is taken stays as it is: `apply` refuses the add
if let std::collections::hash_map::Entry::Vacant(slot) = graph.leads_to.entry(album.id) {
slot.insert(album.smart.as_deref().map(Filter::albums_tested));
edited.push((album.id, Some(album.name.as_str())));
}
}
Op::RemoveAlbum { id } => {
graph.leads_to.remove(id);
}
Op::SetAlbumRules { id, rules } => {
// only a smart album has rules: `apply` refuses them for another
if let Some(tested) = graph.leads_to.get_mut(id).filter(|t| t.is_some()) {
*tested = Some(rules.albums_tested());
edited.push((*id, None));
}
}
Op::Batch { ops } => ops.iter().for_each(|op| foresee(graph, op, edited)),
_ => {}
}
}
/// Which album tests which: what a smart album's photos depend on beyond its own rules. Made in
/// one look at the albums, for questions about all of them.
struct AlbumGraph {
/// Every album; `Some(albums its rules test)` for a smart album, `None` for any other.
leads_to: std::collections::HashMap<AlbumId, Option<Vec<AlbumId>>>,
}
impl AlbumGraph {
fn of<'a>(albums: impl Iterator<Item = &'a Album>) -> AlbumGraph {
AlbumGraph { leads_to: albums.map(|a| (a.id, a.smart.as_deref().map(Filter::albums_tested))).collect() }
}
/// The smart albums that lead back to themselves: those in a ring of albums leading to one
/// another (a strongly connected part of more than one album), or testing themselves. One
/// walk over the albums (Tarjan's, with its own stack rather than recursion: a chain of
/// thousands of albums must not overflow the call stack).
fn on_a_loop(&self) -> std::collections::BTreeSet<AlbumId> {
// only what tests an album can be on a ring: number those
let testing: Vec<(AlbumId, &[AlbumId])> =
self.leads_to.iter().filter_map(|(id, tested)| tested.as_deref().filter(|t| !t.is_empty()).map(|t| (*id, t))).collect();
let number: std::collections::HashMap<AlbumId, usize> = testing.iter().enumerate().map(|(i, (id, _))| (*id, i)).collect();
let leads: Vec<Vec<usize>> = testing.iter().map(|(_, t)| t.iter().filter_map(|to| number.get(to).copied()).collect()).collect();
const UNSEEN: usize = usize::MAX;
let n = testing.len();
// when each was first reached, the earliest still-open album it leads back to, the open
// ones in the order reached, and whether each ended up on a ring
let (mut reached, mut back) = (vec![UNSEEN; n], vec![0usize; n]);
let (mut open, mut is_open, mut ringed) = (Vec::new(), vec![false; n], vec![false; n]);
let mut clock = 0usize;
for root in 0..n {
if reached[root] != UNSEEN {
continue;
}
// (album, how many of its leads were followed)
let mut walk: Vec<(usize, usize)> = vec![(root, 0)];
while let Some(&(v, followed)) = walk.last() {
if followed == 0 && reached[v] == UNSEEN {
reached[v] = clock;
back[v] = clock;
clock += 1;
open.push(v);
is_open[v] = true;
}
if let Some(&w) = leads[v].get(followed) {
if let Some(top) = walk.last_mut() {
top.1 += 1;
}
if reached[w] == UNSEEN {
walk.push((w, 0));
} else if is_open[w] {
back[v] = back[v].min(reached[w]);
}
continue;
}
// every lead of `v` followed: it closes, and with it the ring it is the first of
walk.pop();
if let Some(&(parent, _)) = walk.last() {
back[parent] = back[parent].min(back[v]);
}
if back[v] == reached[v] {
let mut ring = Vec::new();
while let Some(w) = open.pop() {
is_open[w] = false;
ring.push(w);
if w == v {
break;
}
}
if ring.len() > 1 || leads[v].contains(&v) {
ring.into_iter().for_each(|w| ringed[w] = true);
}
}
}
}
testing.iter().zip(&ringed).filter(|(_, ringed)| **ringed).map(|((id, _), _)| *id).collect()
}
}
/// How siblings are listed: folders first, then the ones with a place of their own by it, then by
/// name; the id settles any tie.
fn album_order_key(a: &Album) -> (bool, bool, u32, String, AlbumId) {
@@ -1189,6 +1519,8 @@ fn album_order_key(a: &Album) -> (bool, bool, u32, String, AlbumId) {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_album_loops;
#[cfg(test)]
mod tests_album_order;
#[cfg(test)]
mod tests_background;
@@ -1199,6 +1531,8 @@ mod tests_folders;
#[cfg(test)]
mod tests_format_version;
#[cfg(test)]
mod tests_grids;
#[cfg(test)]
mod tests_index;
#[cfg(test)]
mod tests_journal;
@@ -1206,9 +1540,13 @@ mod tests_journal;
mod tests_local;
#[cfg(test)]
mod tests_lock;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_log_thread;
#[cfg(test)]
mod tests_repair;
#[cfg(test)]
mod tests_rule_order;
#[cfg(test)]
mod tests_scale;
#[cfg(test)]
mod tests_tally;
+4 -2
View File
@@ -17,8 +17,10 @@
//! open" for a moment and a re-open would be refused (issue #680). `LOCK_UN` through our
//! descriptor frees the lock whatever copies a child still holds.
//! - Who holds it (process id, computer, program, version) is written to `catalog.lock.owner`, for
//! the error message. It's a separate file because a Windows lock also blocks reading the
//! locked file. It's only a hint: it may be missing or left over from a crash.
//! the error message. Only dropping the [`LibraryLock`] removes it, so a program that ends with
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). It's a separate
//! file because a Windows lock also blocks reading the locked file. It's only a hint: it may be
//! missing or left over from a crash.
//! - File systems without lock support (some network shares): the library opens unlocked, with a
//! warning — refusing it would lock the user out of their own library. Locks over SMB/NFS are
//! advisory and depend on the server; the owner file is then the only hint.
+378
View File
@@ -0,0 +1,378 @@
//! The thread that writes the catalog log for [`crate::FsStore`] (natively).
//!
//! An append hands its bytes over and returns; the thread writes them in order and makes each batch
//! durable (`sync_data`) before the next. The caller (the UI thread, for the app) never waits for
//! the drive: on Windows a write to a file waits for a sync of that file in flight, so with the log
//! written and synced on the UI thread every flag, rating and step waited for the drive, 30–90 ms
//! on a busy disk in a test and over a second on a photographer's machine while previews were
//! written.
//!
//! **Nothing handed over is ever dropped.** The store's log is the file's first `good` bytes (written
//! and synced) followed by `held`, the bytes handed over and not yet synced. A write or sync that
//! fails keeps `held` and retries it (on every later message, and every [`RETRY`] meanwhile), first
//! cutting the file back to `good` so a fragment of the failed write never stays in it. While a
//! failure stands, [`LogWriter::append`] refuses new bytes with the failure (the journal keeps those
//! records queued, as for any failed append) and [`LogWriter::unwritten`] says how many records are
//! held, so the app counts them as not saved and its quit prompt warns before anything could be
//! lost. Cutting the log back, replacing it and reading it act on that logical content, after
//! everything handed over before; the caller waits for them. Dropping the writer waits for
//! everything handed over and tries a last time.
use std::io::{self, Seek, Write};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush).
const WAIT: Duration = Duration::from_secs(60);
/// How often held bytes are retried while a failure stands and nothing else arrives.
pub(crate) const RETRY: Duration = Duration::from_millis(500);
enum Msg {
Append(Vec<u8>),
Truncate(u64, Sender<io::Result<()>>),
Replace(Vec<u8>, Sender<io::Result<()>>),
Read(Sender<io::Result<Option<Vec<u8>>>>),
/// Reply once everything before is written and synced (or why it isn't).
Flush(Sender<io::Result<()>>),
}
/// What the caller can see without waiting.
#[derive(Default)]
struct Shared {
/// Why the held bytes couldn't be written (until they are, or the log is cut or replaced).
failed: Option<String>,
/// Records (lines) handed over and not yet written and synced, while `failed` stands.
held_records: usize,
}
pub(crate) struct LogWriter {
pub(crate) name: String,
tx: Option<Sender<Msg>>,
shared: Arc<Mutex<Shared>>,
thread: Option<std::thread::JoinHandle<()>>,
}
fn stopped() -> io::Error {
io::Error::other("the catalog log writer stopped")
}
fn not_written(why: &str) -> io::Error {
io::Error::other(format!("the catalog log could not be written: {why}"))
}
impl LogWriter {
/// A writer for `dir/name` (`None` when no thread can start: the store then writes itself).
pub(crate) fn start(dir: PathBuf, name: &str) -> Option<LogWriter> {
let (tx, rx) = channel::<Msg>();
let shared = Arc::new(Mutex::new(Shared::default()));
let sh = shared.clone();
let mut w = Writer::new(dir, name);
let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?;
Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) })
}
fn send(&self, m: Msg) -> io::Result<()> {
self.tx.as_ref().ok_or_else(stopped)?.send(m).map_err(|_| stopped())
}
fn ask<T>(&self, make: impl FnOnce(Sender<io::Result<T>>) -> Msg) -> io::Result<T> {
let (tx, rx) = channel();
self.send(make(tx))?;
rx.recv_timeout(WAIT).map_err(|e| match e {
RecvTimeoutError::Timeout => io::Error::new(io::ErrorKind::TimedOut, "the drive took over a minute to write the catalog log"),
RecvTimeoutError::Disconnected => stopped(),
})?
}
/// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't
/// be written: the caller keeps `data` and appends it again later.
pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> {
if let Some(why) = self.shared.lock().unwrap_or_else(PoisonError::into_inner).failed.clone() {
return Err(not_written(&why));
}
self.send(Msg::Append(data.to_vec()))
}
/// Cut the log to `len` bytes, after everything handed over; waits for it.
pub(crate) fn truncate(&self, len: u64) -> io::Result<()> {
self.ask(|r| Msg::Truncate(len, r))
}
/// Replace the log with `data` (atomically, durably), after everything handed over; waits.
pub(crate) fn replace(&self, data: &[u8]) -> io::Result<()> {
self.ask(|r| Msg::Replace(data.to_vec(), r))
}
/// The log as appended so far (written or still held), after everything handed over.
pub(crate) fn read(&self) -> io::Result<Option<Vec<u8>>> {
self.ask(Msg::Read)
}
/// Wait until everything handed over is written and synced; an error says why it isn't (the
/// bytes are still held and retried).
pub(crate) fn flush(&self) -> io::Result<()> {
self.ask(Msg::Flush)
}
/// Records handed over that can't be written yet, and why (`None`: nothing is held back by a
/// failure). Never waits.
pub(crate) fn unwritten(&self) -> Option<(usize, String)> {
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed.clone().map(|why| (sh.held_records.max(1), why))
}
}
impl Drop for LogWriter {
fn drop(&mut self) {
drop(self.tx.take());
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
/// The thread's side: the file and what is held for it.
struct Writer {
dir: PathBuf,
path: PathBuf,
tmp: PathBuf,
file: Option<std::fs::File>,
/// Bytes of the file written whole and synced (`None` until the file was first opened).
good: Option<u64>,
/// Handed over, not yet written and synced.
held: Vec<u8>,
failed: Option<String>,
}
fn lines(b: &[u8]) -> usize {
b.iter().filter(|c| **c == b'\n').count()
}
impl Writer {
fn new(dir: PathBuf, name: &str) -> Writer {
let path = dir.join(name);
let tmp = dir.join(format!("{name}.tmp"));
Writer { dir, path, tmp, file: None, good: None, held: Vec::new(), failed: None }
}
fn hook(&self, step: crate::fault::Step) -> io::Result<()> {
crate::fault::check(&self.dir, step)
}
/// Open the file positioned at `good` (a fragment past it, from a write that failed, is cut).
fn open(&mut self) -> io::Result<u64> {
if let (Some(_), Some(g)) = (&self.file, self.good) {
return Ok(g);
}
// (a link or a device planted at the name meanwhile is refused, as at the first append)
crate::store::check_regular_directory_entry(&self.path)?;
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?;
let len = f.metadata()?.len();
let good = match self.good {
None => len,
Some(g) if len > g => {
f.set_len(g)?;
g
}
Some(g) if len < g => {
// shorter than what was synced: someone else cut it; continue at its end
log::error!("catalog: {} is {len} bytes, {g} were written", self.path.display());
len
}
Some(g) => g,
};
f.seek(io::SeekFrom::Start(good))?;
self.good = Some(good);
self.file = Some(f);
Ok(good)
}
/// Write and sync what is held.
fn write_held(&mut self) -> io::Result<()> {
if self.held.is_empty() {
return Ok(());
}
let r = (|| {
self.hook(crate::fault::Step::Write)?;
self.open()?;
let f = self.file.as_mut().ok_or_else(|| io::Error::other("catalog log not open"))?;
f.write_all(&self.held)?;
self.hook(crate::fault::Step::Sync)?;
self.file.as_ref().ok_or_else(|| io::Error::other("catalog log not open"))?.sync_data()
})();
match r {
Ok(()) => {
let n = self.held.len() as u64;
self.good = Some(self.good.unwrap_or(0).saturating_add(n));
self.held.clear();
Ok(())
}
Err(e) => {
// the handle may be dead (a network share that reconnected, a removed volume): the
// retry opens the file again and cuts what this attempt left past `good`
self.file = None;
Err(e)
}
}
}
/// Cut the logical log (file then held) to `len` bytes.
fn truncate(&mut self, len: u64) -> io::Result<()> {
let good = match self.good {
Some(g) => g,
None => match self.open() {
Ok(g) => g,
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
Err(e) => return Err(e),
},
};
// (to exactly `good` with bytes held: the file is cut, since a write that failed may have
// left some of them past `good`)
if len > good || (len == good && self.held.is_empty()) {
// within what is held: nothing on the drive changes (what a failed write left past
// `good` is cut before the next write)
let keep = usize::try_from(len - good).unwrap_or(usize::MAX).min(self.held.len());
self.held.truncate(keep);
return Ok(());
}
self.file = None;
crate::store::check_regular_directory_entry(&self.path)?;
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
self.good = None;
self.held.clear();
return Ok(());
}
Err(e) => return Err(e),
};
f.set_len(len)?;
f.sync_all()?;
self.good = Some(len);
self.held.clear();
Ok(())
}
fn replace(&mut self, data: &[u8]) -> io::Result<()> {
self.file = None;
let written = (|| {
self.hook(crate::fault::Step::Write)?;
let mut f = crate::store::create_staging(&self.tmp)?;
f.write_all(data)?;
self.hook(crate::fault::Step::Sync)?;
f.sync_all()?;
drop(f);
std::fs::rename(&self.tmp, &self.path)
})();
match written {
Ok(()) => {
// what was held is part of what the caller replaced the log with (a snapshot holds
// the records before it, `data` the ones after)
self.good = Some(data.len() as u64);
self.held.clear();
self.failed = None;
Ok(())
}
Err(e) => {
let _ = std::fs::remove_file(&self.tmp);
Err(e)
}
}
}
fn read(&mut self) -> io::Result<Option<Vec<u8>>> {
let mut bytes = match std::fs::read(&self.path) {
Ok(b) => b,
Err(e) if e.kind() == io::ErrorKind::NotFound && self.held.is_empty() => return Ok(None),
Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e),
};
if let Some(g) = self.good {
bytes.truncate(usize::try_from(g).unwrap_or(usize::MAX));
}
bytes.extend_from_slice(&self.held);
Ok(Some(bytes))
}
fn publish(&self, shared: &Mutex<Shared>) {
let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed = self.failed.clone().filter(|_| !self.held.is_empty());
sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 };
}
fn run(&mut self, rx: &Receiver<Msg>, shared: &Mutex<Shared>) {
loop {
let first = if self.failed.is_some() && !self.held.is_empty() {
match rx.recv_timeout(RETRY) {
Ok(m) => Some(m),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
}
} else {
match rx.recv() {
Ok(m) => Some(m),
Err(_) => break,
}
};
let mut batch: Vec<Msg> = first.into_iter().collect();
while let Ok(m) = rx.try_recv() {
batch.push(m);
}
let mut flushes = Vec::new();
for m in batch {
match m {
Msg::Append(data) => self.held.extend_from_slice(&data),
// (published before the reply: the caller reads what it left at once)
Msg::Truncate(len, reply) => {
let r = self.truncate(len);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Replace(data, reply) => {
let r = self.replace(&data);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Read(reply) => {
let _ = reply.send(self.read());
}
Msg::Flush(reply) => flushes.push(reply),
}
}
self.step();
self.publish(shared);
for r in flushes {
let _ = r.send(match &self.failed {
Some(why) if !self.held.is_empty() => Err(not_written(why)),
_ => Ok(()),
});
}
}
// the store is closing: everything handed over gets one more try
self.step();
self.publish(shared);
if !self.held.is_empty() {
log::error!("catalog: {} record(s) could not be written to {} (the closing snapshot holds them)", lines(&self.held), self.path.display());
}
}
/// Write what is held; a failure is kept (and logged when it is new).
fn step(&mut self) {
match self.write_held() {
Ok(()) => {
if self.failed.take().is_some() {
log::info!("catalog: {} written again", self.path.display());
}
}
Err(e) => {
let why = e.to_string();
if self.failed.as_deref() != Some(why.as_str()) {
log::error!("catalog: {}: {why} ({} record(s) held, retried)", self.path.display(), lines(&self.held));
}
self.failed = Some(why);
}
}
}
}
+88 -2
View File
@@ -157,7 +157,10 @@ impl CopyrightStatus {
pub fn parse_shutter_seconds(s: &str) -> Option<f64> {
let s = s.trim().trim_end_matches(['s', '"']).trim();
match s.split_once('/') {
Some((n, d)) => Some(n.trim().parse::<f64>().ok()? / d.trim().parse::<f64>().ok()?),
Some((n, d)) => {
let (n, d) = (n.trim().parse::<f64>().ok()?, d.trim().parse::<f64>().ok()?);
if n > 0.0 && d > 0.0 { Some(n / d) } else { None }
}
None => s.parse().ok(),
}
.filter(|v: &f64| v.is_finite() && *v > 0.0)
@@ -168,11 +171,26 @@ pub fn parse_shutter_seconds(s: &str) -> Option<f64> {
#[serde(default)]
pub struct Meta {
pub camera: String,
/// The camera's maker, from Exif `Make` (`camera` is maker and model together).
#[serde(skip_serializing_if = "String::is_empty")]
pub make: String,
pub lens: String,
/// The lens's maker, from Exif `LensMake`.
#[serde(skip_serializing_if = "String::is_empty")]
pub lens_make: String,
pub focal_mm: Option<f32>,
pub aperture: Option<f32>,
pub shutter: String,
pub iso: Option<u32>,
/// Whether the flash fired, from Exif `Flash`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flash: Option<bool>,
/// Exposure compensation in EV, from Exif `ExposureBiasValue`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exposure_bias: Option<f32>,
/// The camera body's serial number.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub serial_number: String,
/// Place (sublocation, e.g. a landmark).
pub location: String,
pub city: String,
@@ -329,7 +347,9 @@ pub struct Analysis {
/// file's white balance is edited relative to its as-shot look or in Kelvin depends on the camera:
/// [`relative_wb_camera`].
pub fn relative_wb_format(format: &str) -> bool {
["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW"].iter().any(|f| format.eq_ignore_ascii_case(f))
["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW", "CRW"]
.iter()
.any(|f| format.eq_ignore_ascii_case(f))
}
/// Whether a raw of `format` shot on `camera` (Exif make and model, as [`Meta::camera`] keeps them) is developed
@@ -354,6 +374,17 @@ pub fn preview_stamp(preview_only: &Option<String>) -> String {
}
impl Photo {
/// Keep the newest [`HISTORY_LIMIT`](crate::HISTORY_LIMIT) History steps; the cursor moves with
/// its step, or to the oldest step kept when its own is dropped. Returns how many were dropped.
pub fn trim_history(&mut self) -> usize {
let n = self.history.len().saturating_sub(crate::HISTORY_LIMIT);
if n > 0 {
self.history.drain(..n);
self.history_cursor = self.history_cursor.map(|c| c.saturating_sub(n));
}
n
}
/// The History step the settings are at (the cursor, clamped to the list; `None` = no history).
pub fn history_index(&self) -> Option<usize> {
let last = self.history.len().checked_sub(1)?;
@@ -423,6 +454,23 @@ impl Photo {
pub fn relative_wb(&self) -> bool {
self.develops_raw() && relative_wb_camera(&self.format, &self.meta.camera)
}
/// Every settings holder of this photo that can carry segmentation grids: the develop
/// settings, the versions', the history steps' and the import look. A snapshot's shared grid
/// table ([`crate::Catalog`]'s `grids`) covers all of them, so a new holder belongs here.
pub(crate) fn settings_holders(&self) -> impl Iterator<Item = &Arc<DevelopSettings>> {
std::iter::once(&self.develop)
.chain(self.versions.iter().map(|v| &v.settings))
.chain(self.history.iter().map(|h| &h.settings))
.chain(self.import_look.iter())
}
/// [`Photo::settings_holders`] with mutable access (resolving a snapshot's grid references).
pub(crate) fn settings_holders_mut(&mut self) -> impl Iterator<Item = &mut Arc<DevelopSettings>> {
let Photo { develop, versions, history, import_look, .. } = self;
std::iter::once(develop)
.chain(versions.iter_mut().map(|v| &mut v.settings))
.chain(history.iter_mut().map(|h| &mut h.settings))
.chain(import_look.as_mut())
}
/// The develop settings import gave this photo: [`Photo::camera_defaults`], or the user's
/// default preset applied on top of them ([`Photo::import_look`]). Like the camera defaults,
/// in the photo's own rendering process.
@@ -458,6 +506,15 @@ impl Photo {
pub fn extension(&self) -> &str {
self.file_name.rsplit_once('.').filter(|(stem, _)| !stem.is_empty()).map_or("", |(_, ext)| ext)
}
/// A video clip (an MP4, a MOV, …), which the image decoders can't read. Besides the kind, the
/// format and the extension count: a Lightroom catalog lists its videos with the format `VIDEO`,
/// and libraries made before they were imported as videos hold them as images.
pub fn is_video(&self) -> bool {
const EXTENSIONS: [&str; 12] = ["mp4", "mov", "m4v", "avi", "mts", "m2ts", "3gp", "mkv", "webm", "wmv", "mpg", "mpeg"];
self.kind == MediaKind::Video
|| self.format.eq_ignore_ascii_case("VIDEO")
|| EXTENSIONS.iter().any(|e| self.extension().eq_ignore_ascii_case(e))
}
/// Width and height in pixels as the photo is shown: turned by its orientation and cut by its
/// crop. Straightening and Constrain Crop shrink the crop without changing its shape, so the
/// aspect is exact and the edges can read a little larger than an export.
@@ -554,6 +611,22 @@ mod edited_tests {
use super::*;
use lightcraft_develop::WbScale;
#[test]
fn a_video_is_known_by_its_kind_format_or_extension() {
let file = |name: &str, format: &str| Photo::new(PhotoId(1), Source::Demo { scene: 0 }, name, format, 10, 10, "2026-10-01T00:00:00");
let mut clip = file("a.jpg", "JPEG");
clip.kind = MediaKind::Video;
assert!(clip.is_video(), "by its kind");
assert!(file("clip", "video").is_video(), "by the format a Lightroom catalog gives videos");
for name in ["VID_1.mp4", "a.MOV", "b.m4v", "c.mts", "d.webm"] {
assert!(file(name, "").is_video(), "{name}");
}
// (a name without an extension, or a dot file, has none)
for (name, format) in [("a.jpg", "JPEG"), ("a.arw", "ARW"), ("a.heic", "HEIC"), ("mp4", ""), (".mov", "")] {
assert!(!file(name, format).is_video(), "{name}");
}
}
#[test]
fn raw_with_import_settings_is_not_edited() {
let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, "a.arw", "ARW", 10, 10, "2026-10-01T00:00:00");
@@ -680,3 +753,16 @@ mod edited_tests {
}
}
}
#[cfg(test)]
mod shutter_tests {
use super::parse_shutter_seconds;
#[test]
fn a_fraction_needs_a_positive_numerator_and_denominator() {
for s in ["-1/-250", "1/-250", "-1/250", "0/250"] {
assert_eq!(parse_shutter_seconds(s), None, "{s}");
}
assert_eq!(parse_shutter_seconds("1/250"), Some(0.004));
}
}
+73 -25
View File
@@ -20,7 +20,7 @@ pub enum RatingOp {
#[serde(default, rename_all = "camelCase")]
pub struct Filter {
/// Free-text search: every token must match filename, title, caption, keywords, camera, lens,
/// location or format. Tokens like `rating:3`, `flag:pick`, `iso:>800`, `camera:x2` are fielded.
/// location or format. Tokens like `rating:3`, `rating:>=3`, `flag:pick`, `iso:>800`, `camera:x2` are fielded.
pub text: String,
pub rating: u8,
pub rating_op: RatingOp,
@@ -36,6 +36,10 @@ pub struct Filter {
/// Any of these labels (the filter bar's multi-select); empty = no constraint.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<ColorLabel>,
/// Any of these flags (the filter bar's multi-select: Picked and Unflagged hide only the
/// rejects); empty = no constraint.
#[serde(skip_serializing_if = "Vec::is_empty", deserialize_with = "null_as_empty")]
pub flags: Vec<Flag>,
pub kind: Option<MediaKind>,
pub edited: Option<bool>,
pub album: Option<AlbumId>,
@@ -72,6 +76,11 @@ pub struct Filter {
pub rule_set: Option<crate::RuleSet>,
}
/// A list that may be given as `null`, read as empty: agents clear `flags` the way they clear `flag`.
fn null_as_empty<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
Ok(Option::<Vec<T>>::deserialize(d)?.unwrap_or_default())
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SortKey {
@@ -143,6 +152,9 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 {
pub(crate) struct Prepared {
root: Option<String>,
only: Option<std::collections::HashSet<PhotoId>>,
/// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]);
/// `None` tests them as written.
rules: Option<crate::RuleSet>,
}
/// The tokens of a search text: split at whitespace, except inside double quotes, so
@@ -179,23 +191,25 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
// a token that starts with a quote is a phrase, even with a colon in it
if let Some((field, quoted)) = t.split_once(':').filter(|_| !t.starts_with('"')) {
let val = unquote(quoted);
let num = |s: &str| -> Option<(char, f64)> {
let (op, rest) = match s.chars().next()? {
c @ ('>' | '<' | '=') => (c, &s[1..]),
_ => ('=', s),
};
rest.parse().ok().map(|v| (op, v))
// `>=` / `<=` before `>` / `<`: otherwise `rating:>=3` reads `=3` as the number and matches nothing
let num = |s: &str| -> Option<(&str, f64)> {
let op = [">=", "<=", ">", "<", "="].into_iter().find(|op| s.starts_with(op)).unwrap_or("");
s.get(op.len()..)?.parse().ok().map(|v| (op, v))
};
let cmp = |x: f64, s: &str| match num(s) {
Some(('>', v)) => x > v,
Some(('<', v)) => x < v,
Some((">", v)) => x > v,
Some(("<", v)) => x < v,
Some((">=", v)) => x >= v,
Some(("<=", v)) => x <= v,
Some((_, v)) => (x - v).abs() < 1e-9,
None => false,
};
// Fields stored as `f32` compare at f32 precision: 2.8f32 widened to f64 is not 2.8.
let cmp32 = |x: f32, s: &str| match num(s) {
Some(('>', v)) => x > v as f32,
Some(('<', v)) => x < v as f32,
Some((">", v)) => x > v as f32,
Some(("<", v)) => x < v as f32,
Some((">=", v)) => x >= v as f32,
Some(("<=", v)) => x <= v as f32,
Some((_, v)) => x == v as f32,
None => false,
};
@@ -212,7 +226,7 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
"person" | "who" => has_person(p, val),
"type" | "kind" => format!("{:?}", p.kind).eq_ignore_ascii_case(val),
"edited" => (val == "true" || val == "yes") == p.is_edited(),
"date" => p.captured.as_deref().is_some_and(|c| c.starts_with(val)),
"date" => p.captured.as_deref().is_some_and(|c| c.get(..val.len()).is_some_and(|h| h.eq_ignore_ascii_case(val))),
"copy" | "virtual" => (val == "true" || val == "yes") == p.copy_of.is_some(),
"name" | "file" => p.file_name.to_lowercase().contains(val),
// Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted
@@ -261,6 +275,17 @@ impl Filter {
self.describe_in(Some(cat))
}
/// The flags that `flag` and `flags` let through together (they AND), in the filter bar's
/// order; `None` when neither is set, empty when they exclude each other. The chip and the
/// filter bar's buttons show this, so they match what is filtered.
pub fn flags_shown(&self) -> Option<Vec<Flag>> {
if self.flag.is_none() && self.flags.is_empty() {
return None;
}
let passes = |f: &Flag| self.flag.is_none_or(|x| x == *f) && (self.flags.is_empty() || self.flags.contains(f));
Some([Flag::Pick, Flag::Reject, Flag::None].into_iter().filter(passes).collect())
}
fn describe_in(&self, cat: Option<&crate::Catalog>) -> String {
let mut v: Vec<String> = Vec::new();
if self.rating > 0 {
@@ -274,6 +299,9 @@ impl Filter {
if let Some(f) = self.flag {
v.push(format!("flag {}", format!("{f:?}").to_lowercase()));
}
if !self.flags.is_empty() {
v.push(format!("flag {}", self.flags.iter().map(|f| format!("{f:?}").to_lowercase()).collect::<Vec<_>>().join(" or ")));
}
if let Some(l) = self.label {
v.push(format!("label {}", format!("{l:?}").to_lowercase()));
}
@@ -327,18 +355,35 @@ impl Filter {
}
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
self.matches_in(p, cat, &self.prepare_one())
// one photo: its rules are tested as written (ordering them would cost more than it saves)
self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, rules: None })
}
/// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed).
pub(crate) fn prepare_one(&self) -> Prepared {
Prepared { root: self.library_root(), only: None }
/// [`Filter::prepare`] for testing one photo at a time, with what each needs worked out once
/// (the `only` ids are looked through, not hashed).
pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared {
Prepared { root: self.library_root(), only: None, rules: self.ordered_rules(cat) }
}
/// The rule set to test, cheapest rule first: once per prepared filter, not per photo. `None`
/// (as written) while any smart album tests itself or a chain is too deep ([`Catalog::keeps_written_order`]), where the
/// order could change which photos match.
fn ordered_rules(&self, cat: &Catalog) -> Option<crate::RuleSet> {
if cat.keeps_written_order() {
return None;
}
self.rule_set.as_ref().map(|rs| rs.by_cost(cat))
}
/// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than
/// once per photo: the library folder's identity and the `only` ids as a set.
pub(crate) fn prepare(&self) -> Prepared {
Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()) }
/// once per photo: the library folder's identity, the `only` ids as a set and the rules in the
/// order to test them.
pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared {
Prepared {
root: self.library_root(),
only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()),
rules: self.ordered_rules(cat),
}
}
/// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice.
@@ -382,13 +427,16 @@ impl Filter {
return false;
}
if let Some(rs) = &self.rule_set
&& !rs.matches(p, cat)
&& !prepared.rules.as_ref().unwrap_or(rs).matches(p, cat)
{
return false;
}
if !self.labels.is_empty() && !p.label.is_some_and(|l| self.labels.contains(&l)) {
return false;
}
if !self.flags.is_empty() && !self.flags.contains(&p.flag) {
return false;
}
if self.only_none {
return false;
}
@@ -482,9 +530,9 @@ impl Catalog {
/// album's rules, the filter bar), as long as they are still where the view looks (`within`: in the library,
/// the album, the folder; not deleted).
pub fn query_keeping(&self, filter: &Filter, sort: &Sort, keep: &std::collections::HashSet<PhotoId>, within: &Filter) -> Vec<PhotoId> {
let prepared = filter.prepare();
let prepared = filter.prepare(self);
// `within` only decides for the few kept photos: worked out per photo, not hashed
let within_prepared = within.prepare_one();
let within_prepared = within.prepare_one(self);
let mut v: Vec<&Photo> = self
.photos()
.map(|p| p.as_ref())
@@ -502,7 +550,7 @@ impl Catalog {
pub fn follow(&self, was: &[PhotoId], touched: &[PhotoId], filter: &Filter, sort: &Sort, within: Option<&Filter>) -> Vec<PhotoId> {
let listed: std::collections::HashSet<PhotoId> = was.iter().copied().filter(|id| touched.binary_search(id).is_ok()).collect();
let mut ids: Vec<PhotoId> = was.iter().copied().filter(|id| !listed.contains(id)).collect();
let (prepared, within_prepared) = (filter.prepare_one(), within.map(Filter::prepare_one));
let (prepared, within_prepared) = (filter.prepare_one(self), within.map(|w| w.prepare_one(self)));
for id in touched {
let Some(p) = self.photo(*id) else { continue };
let kept = within.zip(within_prepared.as_ref()).is_some_and(|(w, wp)| listed.contains(id) && w.matches_in(p, self, wp));
@@ -517,7 +565,7 @@ impl Catalog {
/// How many photos match `filter`: [`Catalog::query`]'s length without its sorting.
pub fn count(&self, filter: &Filter) -> usize {
let prepared = filter.prepare();
let prepared = filter.prepare(self);
self.photos().filter(|p| filter.matches_in(p, self, &prepared)).count()
}
@@ -574,7 +622,7 @@ impl Catalog {
pub fn people_in(&self, filter: &Filter) -> Vec<Person> {
let filter = Filter { person: None, ..filter.clone() };
let mut m: std::collections::HashMap<String, (Person, f64)> = Default::default();
let prepared = filter.prepare();
let prepared = filter.prepare(self);
for p in self.photos().filter(|p| filter.matches_in(p, self, &prepared)) {
let mut seen: Vec<String> = Vec::new();
for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) {
+147 -7
View File
@@ -105,6 +105,9 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[
("aperture", "Aperture", Kind::Number),
("shutterSpeed", "Shutter Speed", Kind::Number),
("iso", "ISO Speed", Kind::Number),
("flash", "Flash", Kind::Bool),
("exposureBias", "Exposure Bias", Kind::Number),
("cameraSerial", "Camera Serial Number", Kind::Text),
// Location
("location", "Location", Kind::Text),
("city", "City", Kind::Text),
@@ -136,7 +139,7 @@ pub const FIELD_GROUPS: &[(&str, &[&str])] = &[
("Date", &["captureDate", "importDate", "editDate"]),
("Keywords & People", &["keywords", "keywordCount", "person", "personCount"]),
("Description", &["title", "caption", "altText", "creator", "copyright", "copyrightStatus"]),
("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso"]),
("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso", "flash", "exposureBias", "cameraSerial"]),
("Location", &["location", "city", "state", "country", "hasGps"]),
("Size", &["longEdge", "shortEdge", "aspect", "megapixels"]),
("Develop", &["edited", "cropped", "treatment"]),
@@ -488,6 +491,12 @@ fn pass_answer(id: crate::AlbumId, photo: crate::PhotoId) -> Option<bool> {
})
}
#[cfg(test)]
thread_local! {
/// Tests: test rules in the order they were written, as before [`RuleSet::by_cost`].
pub(crate) static WRITTEN_ORDER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(test)]
thread_local! {
/// How many times a smart album's rules were worked out on this thread (tests count them).
@@ -514,9 +523,11 @@ pub(crate) fn smart_album_holds(id: crate::AlbumId, photo: crate::PhotoId, match
}
}
}
let _forget = Forget(EVALUATING.with_borrow(Vec::is_empty));
let outermost = EVALUATING.with_borrow(Vec::is_empty);
let _forget = Forget(outermost);
let answer = evaluating(id, matches);
if let Some(a) = answer {
// (the outermost answer would be forgotten as this returns: only what a nested question worked out is kept)
if let (Some(a), false) = (answer, outermost) {
ANSWERS.with_borrow_mut(|known| known.insert((id, photo), a));
}
answer.unwrap_or(false)
@@ -901,9 +912,11 @@ fn path_bytes_contains(hay: &[u8], needle: &[u8]) -> bool {
tail.iter().enumerate().any(|(j, &c)| at(tail_from + j, c))
}
/// A `filePath` rule. The common case (an ASCII path and an ASCII text) is compared in place, folding
/// case and `\` as it goes, with nothing allocated per photo; any other text takes
/// [`file_path_matches_slow`], so Unicode lower-casing (ß, İ, final sigma…) behaves as it always did.
/// A `filePath` rule. An ASCII path and an ASCII text are compared as bytes, a path or text with other
/// characters folded into stack buffers ([`file_path_matches_folded`]); both fold case and `\` as they
/// go, with nothing allocated per photo. Only what that can't reproduce (a text that is not a string, a
/// path or text longer than the buffers, or a capital sigma, whose lower case depends on its neighbors)
/// takes [`file_path_matches_slow`], so Unicode lower-casing (ß, İ, final sigma…) behaves as it always did.
fn file_path_matches(op: &str, source: &Source, value: &Value) -> bool {
let path = match source {
Source::File { path } => path.as_str(),
@@ -911,7 +924,7 @@ fn file_path_matches(op: &str, source: &Source, value: &Value) -> bool {
};
let Value::String(want) = value else { return file_path_matches_slow(op, path, value) };
if !path.is_ascii() || !want.is_ascii() {
return file_path_matches_slow(op, path, value);
return file_path_matches_folded(op, path, want).unwrap_or_else(|| file_path_matches_slow(op, path, value));
}
let (path, want) = (path.trim().as_bytes(), want.trim().as_bytes());
match op {
@@ -928,6 +941,70 @@ fn file_path_matches(op: &str, source: &Source, value: &Value) -> bool {
}
}
/// Room for a folded path (a path of 1 KiB; the fold of a character is at most 1.5 times its bytes) and a folded text.
const FOLDED_PATH_BYTES: usize = 1536;
const FOLDED_TEXT_BYTES: usize = 384;
/// The pair tried first.
const SMALL_PATH_BYTES: usize = 256;
const SMALL_TEXT_BYTES: usize = 96;
/// `s` as the `filePath` rules compare it, written into `buf`: `\` as `/`, every character lower-cased
/// the way [`str::to_lowercase`] does (`İ` becomes `i` and U+0307). `None` when it doesn't fit, or for a
/// capital sigma, which `to_lowercase` writes as `ς` at the end of a word and `σ` elsewhere, by Unicode
/// tables this module can't reach; the caller takes the allocating comparison.
fn fold_path<'b>(s: &str, buf: &'b mut [u8]) -> Option<&'b str> {
let (mut n, mut at) = (0, 0);
while at < s.len() {
// an ASCII run is copied and folded as one block
let run = s.as_bytes()[at..].iter().position(|b| !b.is_ascii()).unwrap_or(s.len() - at);
if run > 0 {
let out = buf.get_mut(n..n + run)?;
out.copy_from_slice(&s.as_bytes()[at..at + run]);
out.iter_mut().for_each(|b| *b = fold_path_byte(*b));
(n, at) = (n + run, at + run);
continue;
}
let c = s[at..].chars().next()?;
if c == '\u{3a3}' {
return None;
}
for l in c.to_lowercase() {
n += l.encode_utf8(buf.get_mut(n..)?.get_mut(..l.len_utf8())?).len();
}
at += c.len_utf8();
}
std::str::from_utf8(&buf[..n]).ok()
}
/// [`file_path_matches`] for a path or text with non-ASCII characters: both folded into stack buffers, then
/// compared as the allocating comparison does, so the answers are the same by construction (a match may
/// begin inside one character's several lower-case characters, `İ` then U+0307, as it does there).
/// Photo paths are short, so a small pair of buffers goes first (clearing a big one costs more than a
/// short path's fold); `None` where [`fold_path`] can't fold them in the large pair either.
fn file_path_matches_folded(op: &str, path: &str, want: &str) -> Option<bool> {
file_path_matches_folded_in::<{ SMALL_PATH_BYTES }, { SMALL_TEXT_BYTES }>(op, path, want)
.or_else(|| file_path_matches_folded_in::<{ FOLDED_PATH_BYTES }, { FOLDED_TEXT_BYTES }>(op, path, want))
}
fn file_path_matches_folded_in<const PATH: usize, const TEXT: usize>(op: &str, path: &str, want: &str) -> Option<bool> {
if matches!(op, "isEmpty" | "isNotEmpty") {
return Some((op == "isEmpty") == path.trim().is_empty());
}
let mut want_buf = [0u8; TEXT];
let mut path_buf = [0u8; PATH];
let want = fold_path(want.trim(), &mut want_buf)?;
Some(match op {
// the whole string, spaces included (not word by word like the other text fields)
"contains" => !want.is_empty() && fold_path(path, &mut path_buf)?.contains(want),
"notContains" => want.is_empty() || !fold_path(path, &mut path_buf)?.contains(want),
"is" => fold_path(path.trim(), &mut path_buf)? == want,
"isNot" => fold_path(path.trim(), &mut path_buf)? != want,
"startsWith" => fold_path(path.trim(), &mut path_buf)?.starts_with(want),
"endsWith" => fold_path(path.trim(), &mut path_buf)?.ends_with(want),
_ => false,
})
}
/// [`file_path_matches`] for any text: the path and the text are normalised into new strings.
fn file_path_matches_slow(op: &str, path: &str, value: &Value) -> bool {
// `/` and `\` both separate, whatever platform the catalog came from; demo photos have no path
@@ -1025,6 +1102,9 @@ impl Rule {
"editDate" => date_op(op, p.edited.as_deref(), value),
"shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)),
"iso" => num_op(op, m.iso.map(|v| v as f64), value),
"flash" => yes(m.flash.unwrap_or(false)),
"exposureBias" => num_op(op, m.exposure_bias.map(f32_as_decimal), value),
"cameraSerial" => text(&m.serial_number),
"aperture" => num_op(op, m.aperture.map(f32_as_decimal), value),
"focalLength" => num_op(op, m.focal_mm.map(f32_as_decimal), value),
"longEdge" | "shortEdge" => {
@@ -1048,6 +1128,48 @@ impl Rule {
}
}
/// How much work one rule is, in tiers: [`RuleSet::by_cost`] tests the cheaper first.
const COST_SCALAR: u8 = 0;
const COST_SMALL: u8 = 1;
const COST_TEXT: u8 = 2;
const COST_ALBUM: u8 = 3;
impl Rule {
/// A rule's tier: 0 numbers, choices and yes/no questions about one photo's own record (and
/// anything that is settled at once: an unknown field or a missing album); 1 dates, keyword and
/// people lists, short single fields, an index lookup and a plain album's list (a folder holds no photos here: an empty lookup); 2 text built
/// from several fields and file paths (long strings, matched for each photo); 3 a smart album,
/// which runs a whole rule set for the photo. A group costs as much as its dearest rule.
fn cost(&self, cat: &Catalog) -> u8 {
match self {
Rule::Group { group } => group.rules.iter().map(|r| r.cost(cat)).max().unwrap_or(COST_SCALAR),
Rule::Field { field, value, .. } => match field.as_str() {
"album" => album_rule_id(value).map_or(COST_SCALAR, |id| match cat.albums.get(&id) {
None => COST_SCALAR,
Some(a) if a.smart.is_some() => COST_ALBUM,
Some(_) => COST_SMALL,
}),
"text" | "filePath" | "location" => COST_TEXT,
"keywords" | "person" | "personCount" | "stacked" | "copyName" | "fileName" | "extension" | "format" | "title" | "caption"
| "altText" | "city" | "state" | "country" | "camera" | "lens" | "creator" | "copyright" | "captureDate" | "importDate"
| "editDate" | "shutterSpeed" | "aspect" | "flash" | "cameraSerial" | "exposureBias" => COST_SMALL,
_ => COST_SCALAR,
},
}
}
/// This rule with its nested groups ordered by cost, and its tier.
fn by_cost(&self, cat: &Catalog) -> (u8, Rule) {
match self {
Rule::Group { group } => {
let group = group.by_cost(cat);
(group.rules.iter().map(|r| r.cost(cat)).max().unwrap_or(COST_SCALAR), Rule::Group { group })
}
field => (field.cost(cat), field.clone()),
}
}
}
impl RuleSet {
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
if self.rules.is_empty() {
@@ -1060,6 +1182,22 @@ impl RuleSet {
}
}
/// This rule set with its rules (and those of nested groups) in the order to test them: the
/// cheapest first ([`Rule::cost`]), the user's order among equals. Rules are pure (they read
/// the photo and the catalog; a smart album's answer is the same however it is reached as long
/// as no smart album tests itself and no chain is cut by the depth limit, which callers check first: [`Catalog::keeps_written_order`]),
/// so for all, any and none the photos that match are the same in any order; only the work
/// differs. Worked out once for a pass, never per photo. The saved rules are untouched.
pub(crate) fn by_cost(&self, cat: &Catalog) -> RuleSet {
#[cfg(test)]
if WRITTEN_ORDER.get() {
return self.clone();
}
let mut rules: Vec<(u8, Rule)> = self.rules.iter().map(|r| r.by_cost(cat)).collect();
rules.sort_by_key(|(cost, _)| *cost);
RuleSet { mode: self.mode, rules: rules.into_iter().map(|(_, r)| r).collect() }
}
/// Whether matches depend on the clock ("in the last…" rules, nested groups included): the
/// same photos can enter or leave the set without any catalog change.
pub fn depends_on_now(&self) -> bool {
@@ -1180,3 +1318,5 @@ impl RuleSet {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_path_fold;
+21
View File
@@ -385,6 +385,27 @@ fn in_the_last_survives_hostile_counts() {
set_now(None);
}
/// Flash, exposure bias and camera serial number can be tested by a rule, like the other
/// camera info; an unrecorded one is empty (or zero bias is no bias).
#[test]
fn flash_exposure_bias_and_serial_rules() {
let cat = Catalog::new();
// the values arrive with the photo's metadata, as fields on its meta, as probed from a file
let mut v = serde_json::to_value(photo(1)).unwrap();
let meta = v.get_mut("meta").unwrap();
meta["flash"] = json!(true);
meta["exposure_bias"] = json!(-0.67);
meta["serial_number"] = json!("SN-X2");
let p: Photo = serde_json::from_value(v).unwrap();
let m = |field: &str, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(&p, &cat);
assert!(m("flash", "is", json!(true)) && !m("flash", "is", json!(false)));
assert!(m("exposureBias", "lt", json!(0)) && m("exposureBias", "between", json!([-1.0, -0.3])));
assert!(m("cameraSerial", "contains", json!("x2")));
assert_eq!(field_group("flash"), Some("Camera Info"));
assert_eq!(field_group("exposureBias"), Some("Camera Info"));
assert_eq!(field_group("cameraSerial"), Some("Camera Info"));
}
/// Every rule's value is checked against its field, so a rule that can't mean anything is
/// reported instead of quietly matching nothing (or everything). Each problem says which rule
/// it is about: "rule 2", or "rule 2.1" inside a group.
+135
View File
@@ -0,0 +1,135 @@
//! A `filePath` rule over a non-ASCII path or text compares in place, with the answers the
//! allocating comparison ([`file_path_matches_slow`]) always gave. That nothing is allocated per
//! photo is checked in `tests/path_fold_heap.rs` (dhat's profiler is global, so it has its own binary).
use proptest::prelude::*;
use serde_json::{Value, json};
use super::*;
use crate::Source;
const OPS: [&str; 9] = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty", "bogus"];
fn file(path: &str) -> Source {
Source::File { path: path.to_string() }
}
fn fast(op: &str, path: &str, want: &str) -> bool {
file_path_matches(op, &file(path), &Value::String(want.to_string()))
}
fn old(op: &str, path: &str, want: &str) -> bool {
file_path_matches_slow(op, path, &Value::String(want.to_string()))
}
#[test]
fn pinned_unicode_cases_keep_their_old_answers() {
// (path, text) pairs where lower-casing changes the length, folds across scripts or looks at its neighbors
let pairs = [
("İstanbul/Photo", "i̇stanbul"), // İ lower-cases to i + U+0307
("a/İ", "\u{307}"), // a match that starts inside an expansion
("STRASSE", "straße"), // ß never equals ss, either way
("Straße", "STRASSE"),
("ẞ/x", "ß"), // capital sharp s lower-cases to ß
("ΟΔΟΣ", "οδος"), // final sigma: Σ → ς at the end of a word
("ΟΔΟΣ", "οδοσ"),
("ΣΑΣ/ΟΔΟΣ", "σας"),
("\u{212A}elvin", "kelvin"), // Kelvin sign → k
("Dž/x", "dž"), // a title-case digraph
("D:\\Фото\\Ё", "d:/фото/ё"),
(" Ünï ", "ünï"), // whitespace around the path is trimmed for is / startsWith / endsWith
("Ünï", " ünï\t"),
("\u{85}Ü\u{2003}", "ü"),
("", "é"),
("é", ""),
];
for (path, want) in pairs {
for op in OPS {
assert_eq!(fast(op, path, want), old(op, path, want), "{op} {path:?} {want:?}");
}
}
}
#[test]
fn a_path_or_text_longer_than_the_buffers_still_answers_as_before() {
// İ grows by half when lower-cased, so these cross FOLDED_PATH_BYTES and FOLDED_TEXT_BYTES on either side of the limit
for len in [FOLDED_PATH_BYTES / 3, FOLDED_PATH_BYTES / 2 - 1, FOLDED_PATH_BYTES / 2, FOLDED_PATH_BYTES, FOLDED_PATH_BYTES * 2] {
let path = format!("/Фото/{}/IMG.JPG", "İ".repeat(len / 2));
for want_len in [3, FOLDED_TEXT_BYTES / 3, FOLDED_TEXT_BYTES / 2, FOLDED_TEXT_BYTES, FOLDED_TEXT_BYTES * 2] {
let tail = "i̇".repeat(want_len / 3);
for want in [tail.clone(), format!("{tail}/img.jpg"), format!("/фото/{tail}")] {
for op in OPS {
assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{op} {len} {want_len}");
}
}
}
}
}
#[test]
fn a_text_that_is_not_a_string_still_answers_as_before() {
for value in [json!(7), json!(null), json!(true), json!(["é"])] {
for op in OPS {
let src = file("/Фото/7.jpg");
assert_eq!(file_path_matches(op, &src, &value), file_path_matches_slow(op, "/Фото/7.jpg", &value), "{op} {value}");
}
}
}
/// Letters whose lower-casing is odd, plus plain ones, separators and whitespace.
fn glyph() -> impl Strategy<Value = char> {
prop::sample::select(vec![
'a', 'A', 's', 'S', 'ß', 'ẞ', 'İ', 'i', 'I', '\u{307}', 'é', 'É', 'ü', 'Ü', 'Σ', 'σ', 'ς', 'Dž', 'dž', 'DŽ', '\u{212A}', 'k', 'Ω', 'ω', 'Ё',
'ё', 'Ф', 'ф', '日', '本', '/', '\\', ' ', '\t', '\u{85}', '\u{2003}', '.', '1',
])
}
fn text() -> impl Strategy<Value = String> {
prop::collection::vec(glyph(), 0..14).prop_map(|v| v.into_iter().collect())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4000))]
#[test]
fn the_in_place_comparison_equals_the_allocating_one(path in text(), want in text(), op in prop::sample::select(OPS.to_vec())) {
prop_assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{} {:?} {:?}", op, path, want);
}
#[test]
fn a_slice_of_the_path_is_found_whatever_its_case(path in text(), from in 0usize..14, len in 0usize..14, upper in any::<bool>(), op in prop::sample::select(OPS.to_vec())) {
let chars: Vec<char> = path.chars().collect();
let from = from.min(chars.len());
let to = (from + len).min(chars.len());
let slice: String = chars[from..to].iter().collect();
let want = if upper { slice.to_uppercase() } else { slice.to_lowercase() };
prop_assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{} {:?} {:?}", op, path, want);
}
#[test]
fn any_unicode_text_agrees(path in "\\PC{0,12}", want in "\\PC{0,6}", op in prop::sample::select(OPS.to_vec())) {
prop_assert_eq!(fast(op, &path, &want), old(op, &path, &want), "{} {:?} {:?}", op, path, want);
}
}
/// A timed loop over a library's worth of non-ASCII paths: run it with
/// `just test catalog path_fold_timing -- --ignored --nocapture` (release numbers: `--release`).
#[test]
#[ignore = "a measurement, not a check"]
fn path_fold_timing() {
const N: usize = 844_425;
let folders = ["Фото", "Ünïcode", "日本語", "Straße", "Éclair", "İstanbul"];
let paths: Vec<Source> = (0..N).map(|i| file(&format!("/Volumes/share/{}/{}/IMG_{i:07}.JPG", folders[i % 6], folders[(i / 6) % 6]))).collect();
let wants = [("contains", "ÉCLAIR/img_000"), ("contains", "tokyo"), ("startsWith", "/volumes/share/фото"), ("endsWith", "99.jpg")];
for (op, want) in wants {
let value = Value::String(want.to_string());
let t = std::time::Instant::now();
let new_hits = paths.iter().filter(|p| file_path_matches(op, p, &value)).count();
let new_time = t.elapsed();
let t = std::time::Instant::now();
let old_hits = paths.iter().filter(|p| matches!(p, Source::File { path } if file_path_matches_slow(op, path, &value))).count();
let old_time = t.elapsed();
assert_eq!(new_hits, old_hits);
println!("{op:<11} {want:<22} hits {new_hits:>7} in place {new_time:>10.2?} allocating {old_time:>10.2?}");
}
}
+100 -6
View File
@@ -28,7 +28,9 @@ pub trait Store: Send {
self.write_atomic(name, &buf)?;
Ok(buf.len() as u64)
}
/// Append and make durable (fsync) before returning. On an error, part of `data` may have
/// Append and make durable (fsync): before returning, or, natively, by the store's own log
/// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a
/// read through the store sees every byte handed over). On an error, part of `data` may have
/// been written (a full disk, a dropped network share): the journal cuts the file back to its
/// previous length with [`Store::truncate`] before appending again.
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>;
@@ -43,12 +45,23 @@ pub trait Store: Send {
fn background_writer(&self) -> Option<Box<dyn Store>> {
None
}
/// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a
/// thread of its own; the default has nothing to wait for). An error says why some aren't: they
/// are still held and retried, never dropped.
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
/// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the
/// store's own thread failed: they are held and retried), and why. `None`: nothing held back.
fn unwritten(&self) -> Option<(usize, String)> {
None
}
}
/// Appends and truncates open the name's own file, so anything else at the name is the library's
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
/// hangs the open. Refused with an error the open can show, before anything is written through.
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(md) if md.is_file() => Ok(()),
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
@@ -60,15 +73,24 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
/// Files in a directory.
pub struct FsStore {
dir: PathBuf,
/// Open append handle (kept between appends; dropped on rewrite/truncate).
/// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread
/// writes the log (the browser build, or one that couldn't start).
appender: Option<(String, std::fs::File)>,
/// The thread that writes the log (natively; started by the first append).
#[cfg(not(target_arch = "wasm32"))]
log: Option<crate::log_writer::LogWriter>,
}
impl FsStore {
/// Use `dir` (created if missing).
pub fn open(dir: impl AsRef<Path>) -> io::Result<FsStore> {
std::fs::create_dir_all(dir.as_ref())?;
Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None })
Ok(FsStore {
dir: dir.as_ref().to_path_buf(),
appender: None,
#[cfg(not(target_arch = "wasm32"))]
log: None,
})
}
pub fn dir(&self) -> &Path {
&self.dir
@@ -76,6 +98,21 @@ impl FsStore {
fn path(&self, name: &str) -> PathBuf {
self.dir.join(name)
}
/// The log thread, when it writes `name`.
#[cfg(not(target_arch = "wasm32"))]
fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> {
self.log.as_ref().filter(|w| w.name == name)
}
/// Wait until the log thread has written and synced everything handed to it.
pub fn flush_log(&self) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = &self.log {
return w.flush();
}
Ok(())
}
fn sync_dir(&self) {
// Makes the rename durable on POSIX; opening a directory fails on Windows (where
// `rename` is already journaled by NTFS), so errors are ignored.
@@ -97,6 +134,11 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result<std::fs::File>
impl Store for FsStore {
fn read(&mut self, name: &str) -> io::Result<Option<Vec<u8>>> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// what was handed over, written or still held
return w.read();
}
match std::fs::read(self.path(name)) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
@@ -106,6 +148,13 @@ impl Store for FsStore {
fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (after the appends handed over before)
w.replace(data)?;
self.sync_dir();
return Ok(());
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -122,6 +171,15 @@ impl Store for FsStore {
fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result<u64> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (the log is small: buffered, and replaced by its thread after the appends before)
let mut buf = Vec::new();
fill(&mut buf)?;
w.replace(&buf)?;
self.sync_dir();
return Ok(buf.len() as u64);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -148,6 +206,23 @@ impl Store for FsStore {
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
{
if self.log.is_none() && !crate::fault::on_caller(&self.dir) {
check_regular_directory_entry(&self.path(name))?;
if !self.path(name).exists() {
// created here, so the open's errors are this append's and its entry is durable
std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
self.sync_dir();
}
self.appender = None;
self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name);
}
// (another name than the log's is written here, as without a thread)
if let Some(w) = self.log_for(name) {
return w.append(data);
}
}
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
check_regular_directory_entry(&self.path(name))?;
let existed = self.path(name).exists();
@@ -158,6 +233,12 @@ impl Store for FsStore {
self.appender = Some((name.to_string(), f));
}
let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) };
#[cfg(not(target_arch = "wasm32"))]
let written = crate::fault::check(&self.dir, crate::fault::Step::Write)
.and_then(|()| f.write_all(data))
.and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync))
.and_then(|()| f.sync_data());
#[cfg(target_arch = "wasm32")]
let written = f.write_all(data).and_then(|()| f.sync_data());
if written.is_err() {
// The handle may be dead (a network share that reconnected, a removed volume): the next
@@ -169,6 +250,10 @@ impl Store for FsStore {
}
fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
return w.truncate(len);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -189,7 +274,16 @@ impl Store for FsStore {
#[cfg(not(target_arch = "wasm32"))]
fn background_writer(&self) -> Option<Box<dyn Store>> {
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None }))
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None }))
}
fn flush(&mut self) -> io::Result<()> {
self.flush_log()
}
#[cfg(not(target_arch = "wasm32"))]
fn unwritten(&self) -> Option<(usize, String)> {
self.log.as_ref().and_then(|w| w.unwritten())
}
}
@@ -256,13 +350,13 @@ impl Store for MemStore {
}
}
// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused)
#[cfg(all(test, unix))]
mod tests_staging {
use super::*;
/// A link planted at a staging name (`<name>.tmp`) is removed, never followed: the file it points to keeps its
/// bytes and the save still lands (issue #1502).
#[cfg(unix)]
#[test]
fn a_link_at_the_staging_name_is_never_written_through() {
let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id()));
+74 -1
View File
@@ -12,6 +12,17 @@ fn photo(c: &mut Catalog, name: &str, date: &str) -> PhotoId {
id
}
#[test]
fn date_token_matches_time_part_case_insensitively() {
let mut c = Catalog::new();
let a = photo(&mut c, "a.jpg", "2026-05-01T10:00:00");
let q = |c: &Catalog, text: &str| c.query(&Filter { text: text.into(), ..Default::default() }, &Sort::default());
assert_eq!(q(&c, "date:2026-05-01T10"), vec![a]);
assert_eq!(q(&c, "date:2026-05-01t10"), vec![a]);
assert_eq!(q(&c, "date:2026-05"), vec![a]);
assert!(q(&c, "date:2026-05-01T11").is_empty());
}
#[test]
fn apply_and_inverse_roundtrip() {
let mut c = Catalog::new();
@@ -125,6 +136,31 @@ fn filter_search_sort() {
/// A search word with a colon whose left part is not a known field ("10:30", "Re:") is plain
/// text, not a fielded token that matches nothing.
/// `flags` (#2588) matches any of its flags; a filter saved before it, with the single `flag`, reads
/// and filters as it did, and a filter without `flags` is written without the key.
#[test]
fn filter_flags_any_of_and_the_old_single_flag() {
let mut c = Catalog::new();
let a = photo(&mut c, "a.jpg", "2026-01-01T10:00:00");
let b = photo(&mut c, "b.jpg", "2026-01-02T10:00:00");
let d = photo(&mut c, "d.jpg", "2026-01-03T10:00:00");
c.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap();
c.apply(Op::SetFlag { id: d, flag: Flag::Reject }).unwrap();
let f = Filter { flags: vec![Flag::Pick, Flag::None], ..Default::default() };
assert_eq!(c.query(&f, &Sort::default()), vec![b, a]);
let f = Filter { flags: vec![Flag::Reject, Flag::None], ..Default::default() };
assert_eq!(c.query(&f, &Sort::default()), vec![d, b]);
let saved: Filter = serde_json::from_value(serde_json::json!({"text": "", "rating": 0, "flag": "reject", "label": null})).unwrap();
assert!(saved.flags.is_empty());
assert_eq!(c.query(&saved, &Sort::default()), vec![d]);
let written = serde_json::to_value(&saved).unwrap();
assert_eq!(written.get("flag"), Some(&serde_json::json!("reject")));
assert!(written.get("flags").is_none(), "{written}");
let round: Filter =
serde_json::from_value(serde_json::to_value(Filter { flags: vec![Flag::Pick, Flag::None], ..Default::default() }).unwrap()).unwrap();
assert_eq!(round.flags, vec![Flag::Pick, Flag::None]);
}
#[test]
fn free_text_with_a_colon_searches_the_text_fields() {
let mut c = Catalog::new();
@@ -163,6 +199,42 @@ fn search_tokens_match_f32_aperture_and_focal() {
assert!(q("f:>2.8").is_empty(), "f:>2.8");
assert!(q("focal:<5.6").is_empty(), "focal:<5.6");
assert_eq!(q("f:>2.7"), vec![a], "f:>2.7");
assert_eq!(q("f:>=2.8"), vec![a], "f:>=2.8 counts the photo's own value");
assert_eq!(q("focal:<=5.6"), vec![a], "focal:<=5.6");
assert!(q("f:>=2.9").is_empty(), "f:>=2.9");
assert!(q("focal:<=5.5").is_empty(), "focal:<=5.5");
}
/// `>=` and `<=` in a fielded token are the inclusive comparisons. They used to read the `=` as
/// part of the number, so `rating:>=3` or `iso:<=400` silently matched no photo at all.
#[test]
fn search_tokens_compare_inclusively() {
let mut c = Catalog::new();
let (two, three, four) = (
photo(&mut c, "two.jpg", "2026-05-01T10:00:00"),
photo(&mut c, "three.jpg", "2026-05-02T10:00:00"),
photo(&mut c, "four.jpg", "2026-05-03T10:00:00"),
);
for (id, rating, iso) in [(two, 2, 200), (three, 3, 400), (four, 4, 800)] {
c.apply(Op::SetRating { id, rating }).unwrap();
let mut m = c.photo(id).unwrap().meta.clone();
m.iso = Some(iso);
c.apply(Op::SetMeta { id, meta: Box::new(m) }).unwrap();
}
let q = |t: &str| {
let mut ids = c.query(&Filter { text: t.into(), ..Default::default() }, &Sort::default());
ids.sort();
ids
};
assert_eq!(q("rating:>=3"), vec![three, four]);
assert_eq!(q("stars:<=3"), vec![two, three]);
assert_eq!(q("iso:>=400"), vec![three, four]);
assert_eq!(q("iso:<=400"), vec![two, three]);
assert_eq!(q("rating:>3"), vec![four], "strict comparisons are unchanged");
assert_eq!(q("rating:=3"), vec![three]);
assert_eq!(q("rating:3"), vec![three]);
assert!(q("rating:>=").is_empty(), "an operator without a number matches nothing");
assert!(q("rating:=>3").is_empty(), "not an operator");
}
/// A `captured` string that is not ASCII (the Lightroom importer copies `captureTime` into an
@@ -564,7 +636,8 @@ fn set_embedded_lens_is_undoable_and_journaled() {
photo: Box::new(Photo::new(a, Source::File { path: "/x.rw2".into() }, "x.rw2", "RW2", 4000, 3000, "2026-10-06T00:00:00")),
})
.unwrap();
let lens = lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default() };
let lens =
lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default(), source: Default::default() };
let op = Op::SetEmbeddedLens { id: a, lens: Some(Box::new(lens)) };
let op: Op = serde_json::from_str(&serde_json::to_string(&op).unwrap()).unwrap();
let inv = c.apply(op).unwrap();
+243
View File
@@ -0,0 +1,243 @@
//! Smart albums that would include themselves, through the albums they test.
//!
//! The rule is the catalog's: a new edit that would put a smart album on such a loop is refused
//! (`Catalog::apply_new`), whoever makes it and however it is packed (alone, in a batch, as a
//! new album). A library that already holds a loop opens and keeps working (`Catalog::apply`,
//! `replay` and snapshots take it).
//!
//! Scenarios:
//! - When a new edit (adding a smart album, changing rules, alone or in a batch) would put a
//! smart album on a loop, then it is refused, names the album, and nothing changed.
//! - When a new edit makes no loop, then it goes through, whatever else is in the library.
//! - Given a library that already holds a loop, then it opens, and edits that add no loop go
//! through (also to the albums on it), and the loop can be mended.
//! - Given a ring of thousands of smart albums, then the edit that closes it is refused without
//! running out of stack.
use crate::*;
fn smart(c: &mut Catalog, name: &str, rules: Filter) -> AlbumId {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(rules)), ..Album::new(id, name) } }).unwrap();
id
}
fn plain(c: &mut Catalog, name: &str) -> AlbumId {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album::new(id, name) }).unwrap();
id
}
/// Rules of Album rules: `(op, album)` joined by `all`.
fn tests(rules: &[(&str, AlbumId)]) -> Filter {
let rules: Vec<serde_json::Value> = rules.iter().map(|(op, a)| serde_json::json!({"field": "album", "op": op, "value": a.0})).collect();
serde_json::from_value(serde_json::json!({"ruleSet": {"match": "all", "rules": rules}})).unwrap()
}
/// The same, with the albums in a group of the rules.
fn tests_in_a_group(album: AlbumId) -> Filter {
serde_json::from_value(serde_json::json!({"ruleSet": {"match": "all", "rules": [
{"field": "rating", "op": "is", "value": 3},
{"group": {"match": "any", "rules": [{"field": "album", "op": "is", "value": album.0}]}}
]}}))
.unwrap()
}
fn set_rules(id: AlbumId, rules: Filter) -> Op {
Op::SetAlbumRules { id, rules: Box::new(rules) }
}
fn rated(rating: u8) -> Filter {
Filter { rating, ..Default::default() }
}
/// What the albums are: the whole library as saved.
fn saved(c: &Catalog) -> String {
c.to_snapshot()
}
#[test]
fn a_new_edit_that_would_make_a_loop_is_refused() {
let mut c = Catalog::new();
let a = smart(&mut c, "A", rated(1));
let b = smart(&mut c, "B", tests(&[("is", a)]));
let chain = smart(&mut c, "Chain", tests(&[("isNot", b)]));
let (x, y) = (smart(&mut c, "X", rated(2)), smart(&mut c, "Y", rated(3)));
// F tests E; E is removed, so F tests an album that is not there (a saved rule may)
let e = smart(&mut c, "E", rated(4));
let f = smart(&mut c, "F", tests(&[("is", e)]));
c.apply(Op::RemoveAlbum { id: e }).unwrap();
let (before, revision) = (saved(&c), c.revision);
let refused: Vec<(&str, Op, &str)> = vec![
("tests an album that tests it", set_rules(a, tests(&[("is", b)])), "A"),
("tests itself", set_rules(a, tests(&[("is", a)])), "A"),
("tests itself through a group", set_rules(a, tests_in_a_group(a)), "A"),
("tests the end of a chain that leads to it", set_rules(a, tests(&[("isNot", chain)])), "A"),
("limited to itself by its album field", set_rules(a, Filter { album: Some(a), ..Default::default() }), "A"),
("two edits, each alone without a loop", Op::Batch { ops: vec![set_rules(x, tests(&[("is", y)])), set_rules(y, tests(&[("is", x)]))] }, "X"),
("a rename and a loop", Op::Batch { ops: vec![Op::RenameAlbum { id: a, name: "Renamed".into() }, set_rules(a, tests(&[("is", b)]))] }, "A"),
(
"a batch in a batch",
Op::Batch {
ops: vec![Op::Batch { ops: vec![set_rules(x, tests(&[("is", y)]))] }, Op::Batch { ops: vec![set_rules(y, tests(&[("is", x)]))] }],
},
"X",
),
(
"a new album that takes the id an album was tested by",
Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", f)]))), ..Album::new(e, "Back") } },
"Back",
),
(
"a new album and its own rules in one batch",
Op::Batch {
ops: vec![
Op::AddAlbum { album: Album { smart: Some(Box::new(rated(1))), ..Album::new(AlbumId(90), "Fresh") } },
set_rules(AlbumId(90), tests(&[("is", AlbumId(90))])),
],
},
"Fresh",
),
];
for (what, op, name) in refused {
let e = c.apply_new(op).unwrap_err().to_string();
assert!(e.contains(&format!("“{name}”")) && e.contains("include itself"), "{what}: {e}");
assert_eq!(saved(&c), before, "{what}: nothing changed");
assert_eq!(c.revision, revision, "{what}: not even looked at as changed");
}
}
#[test]
fn a_new_edit_that_makes_no_loop_goes_through() {
let mut c = Catalog::new();
let a = smart(&mut c, "A", rated(1));
let b = smart(&mut c, "B", tests(&[("is", a)]));
let list = plain(&mut c, "List");
let c1 = smart(&mut c, "C", tests(&[("isNot", b)]));
let allowed = vec![
("a chain gets longer", set_rules(a, rated(2))),
("testing a plain album", set_rules(a, tests(&[("is", list)]))),
("a smart album testing another, the other way round", set_rules(c1, tests(&[("is", a), ("is", b)]))),
(
"a new smart album testing others",
Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", c1)]))), ..Album::new(AlbumId(50), "New") } },
),
("a new plain album", Op::AddAlbum { album: Album::new(AlbumId(51), "Plain") }),
("a rename", Op::RenameAlbum { id: b, name: "B2".into() }),
("a removal", Op::RemoveAlbum { id: c1 }),
("photos of a plain album", Op::SetAlbumPhotos { id: list, photos: vec![] }),
("the album field of the rules", set_rules(b, Filter { album: Some(list), ..Default::default() })),
(
"a batch of edits that don't meet",
Op::Batch { ops: vec![set_rules(a, rated(3)), Op::RenameAlbum { id: a, name: "A3".into() }, set_rules(b, tests(&[("is", a)]))] },
),
(
"a batch that passes through a loop and ends without one",
Op::Batch { ops: vec![set_rules(a, tests(&[("is", b)])), set_rules(b, rated(1))] },
),
];
for (what, op) in allowed {
let revision = c.revision;
let undo = c.apply_new(op).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(c.revision, revision + 1, "{what}");
assert!(c.albums().all(|al| !c.smart_album_problems(al.id).iter().any(|p| p.issue == rules::Issue::AlbumLoop)), "{what}: no loop");
// and it is undone by what it returned
c.apply(undo).unwrap();
}
}
/// The refusal is the only difference between the two ways in: an edit that makes no loop does
/// the same through either.
#[test]
fn apply_new_changes_what_apply_changes() {
let mut a = Catalog::new();
let first = smart(&mut a, "A", rated(1));
let second = smart(&mut a, "B", tests(&[("is", first)]));
let mut b = Catalog::from_snapshot(&saved(&a)).unwrap();
let ops = vec![set_rules(first, rated(4)), Op::RenameAlbum { id: second, name: "B2".into() }, set_rules(second, tests(&[("isNot", first)]))];
for op in ops {
let (ia, ib) = (a.apply(op.clone()).unwrap(), b.apply_new(op).unwrap());
assert_eq!(Catalog::op_to_log_line(&ia), Catalog::op_to_log_line(&ib));
}
assert_eq!(saved(&a), saved(&b));
}
/// A library saved by a version without the rule: it may hold a loop. It opens (a snapshot, a
/// replayed log), its albums still list and count, edits that make no loop go through, also
/// those to the albums on the loop, and an edit that closes another loop is still refused.
#[test]
fn a_library_that_already_holds_a_loop_opens_and_can_be_mended() {
let mut old = Catalog::new();
let mut log = String::new();
let mut record = |c: &mut Catalog, op: Op| {
log.push_str(&Catalog::op_to_log_line(&op));
c.apply(op).unwrap();
};
let (first, second, other, third) = (AlbumId(1), AlbumId(2), AlbumId(3), AlbumId(4));
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(first, "First") } });
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", first)]))), ..Album::new(second, "Second") } });
record(&mut old, set_rules(first, tests(&[("is", second)])));
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(other, "Other") } });
record(&mut old, Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", other)]))), ..Album::new(third, "Third") } });
let mut c = Catalog::new();
assert_eq!(c.replay(&log).unwrap(), 5, "the log replays, loop and all");
let mut from_snapshot = Catalog::from_snapshot(&c.to_snapshot()).unwrap();
for lib in [&mut c, &mut from_snapshot] {
// they still answer
for id in [first, second, other, third] {
let _ = (lib.album_photos(id), lib.album_count(id), lib.smart_album_problems(id));
}
// edits that make no loop go through: elsewhere, and to the albums on the loop
lib.apply_new(Op::RenameAlbum { id: first, name: "First, renamed".into() }).unwrap();
lib.apply_new(set_rules(other, rated(2))).unwrap();
lib.apply_new(set_rules(third, tests(&[("isNot", other)]))).unwrap();
lib.apply_new(Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", second)]))), ..Album::new(AlbumId(60), "Reads the loop") } })
.unwrap();
lib.apply_new(set_rules(first, Filter { rating: 3, rule_set: tests(&[("is", second)]).rule_set, ..Default::default() })).unwrap();
// not one that closes another
let e = lib.apply_new(set_rules(other, tests(&[("is", third)]))).unwrap_err().to_string();
assert!(e.contains("“Other”") && e.contains("include itself"), "{e}");
// mended by an edit that makes no loop
lib.apply_new(set_rules(second, rated(1))).unwrap();
assert!(!lib.smart_album_problems(first).iter().any(|p| p.issue == rules::Issue::AlbumLoop), "mended");
assert!(!lib.smart_album_problems(second).iter().any(|p| p.issue == rules::Issue::AlbumLoop), "mended");
}
}
/// What an album on a loop holds is whatever it held before the refusal existed: the rule keeps
/// new loops out and decides nothing about the photos of old ones.
#[test]
fn what_an_album_on_a_loop_holds_is_left_as_it_was() {
let mut c = Catalog::new();
let id = c.alloc_photo_id();
c.apply(Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 1 }, "p.jpg", "JPEG", 60, 40, "2026-02-01T10:00:00")) }).unwrap();
c.apply(Op::SetRating { id, rating: 3 }).unwrap();
let first = smart(&mut c, "First", Filter::default());
let second = smart(&mut c, "Second", tests(&[("is", first)]));
c.apply(set_rules(first, tests(&[("is", second)]))).unwrap();
let held = |c: &Catalog| [first, second].map(|a| (c.album_photos(a), c.album_count(a)));
let looped = held(&c);
// edits that go through the check, one of them to an album on the loop
c.apply_new(set_rules(first, Filter { rule_set: tests(&[("is", second)]).rule_set, ..Default::default() })).unwrap();
let id = c.alloc_album_id();
c.apply_new(Op::AddAlbum { album: Album { smart: Some(Box::new(tests(&[("is", second)]))), ..Album::new(id, "Reads the loop") } }).unwrap();
assert_eq!(held(&c), looped);
}
/// The search for loops walks the albums with its own stack: a ring of thousands of smart albums
/// is found, not overflowed.
#[test]
fn a_very_long_ring_is_refused_without_running_out_of_stack() {
const N: usize = 20_000;
let mut c = Catalog::new();
let ids: Vec<AlbumId> = (0..N).map(|i| smart(&mut c, &format!("S{i}"), Filter::default())).collect();
// each tests the next; the last one is left open
for pair in ids.windows(2) {
c.apply(set_rules(pair[0], tests(&[("is", pair[1])]))).unwrap();
}
let (first, last) = (ids[0], ids[N - 1]);
let e = c.apply_new(set_rules(last, tests(&[("is", first)]))).unwrap_err().to_string();
assert!(e.contains("include itself"), "{e}");
// and what makes no ring goes through
c.apply_new(set_rules(last, rated(5))).unwrap();
}
+2 -1
View File
@@ -269,9 +269,10 @@ fn fs_store_background_snapshot() {
}
// a previous crash mid-snapshot left a partial temp file
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"{\"format\":\"lightcraft-catal").unwrap();
// (closed first: its log thread writes what was handed over)
drop(j);
let (mut j2, c2, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert_eq!((c2.to_snapshot(), r.snapshot_seq), (live.to_snapshot(), 0));
drop(j);
let n = j2.seq();
j2.snapshot_in_background(&live).unwrap();
for k in 200..260 {
+3 -2
View File
@@ -238,8 +238,9 @@ fn op_variants_are_versioned() {
Op::SetHistoryCursor { .. } => 8,
}
}
/// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`.
const NEWEST_FIELDS: u32 = 9;
/// v12: `Catalog.grids` and `SegMask.grid`, shared by a snapshot's masks (#2154) (v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9:
/// `Photo.preview_checked` and `Op::SetContent.preview_checked`).
const NEWEST_FIELDS: u32 = 12;
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
}
+392
View File
@@ -0,0 +1,392 @@
//! Issue #2154: a snapshot keeps each distinct segmentation grid once (`Catalog.grids`) and the
//! masks of the develop settings, versions, history steps and import look refer to it by index,
//! so an unchanged mask no longer repeats with every history step. In-memory catalogs and log
//! records always hold the grids inline; older catalogs (inline everywhere) load and are upgraded.
use std::sync::Arc;
use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape, SegMask};
use crate::journal::{LOG, SNAPSHOT, VERSION};
use crate::*;
fn snapshot_version(m: &MemStore) -> u64 {
let v: serde_json::Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap();
v["version"].as_u64().unwrap()
}
fn open(m: &MemStore) -> (Journal, Catalog, LoadReport) {
Journal::open(Box::new(m.clone())).unwrap()
}
/// Develop settings with one AI mask over an object segmentation.
fn settings_with_seg(seg: SegMask, exposure: f64) -> DevelopSettings {
let mut s = DevelopSettings::default();
s.light.exposure = exposure;
s.masks.push(Mask {
id: 1,
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Object {
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
exclude: vec![],
seg: Some(seg),
detail: vec![],
edge: 0.0,
},
}],
..Default::default()
});
s
}
/// One mask (`id`) whose only component is an Object segmentation `seg`.
fn object_mask(id: u32, seg: SegMask) -> Mask {
Mask {
id,
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Object {
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
exclude: vec![],
seg: Some(seg),
detail: vec![],
edge: 0.0,
},
}],
..Default::default()
}
}
/// A catalog of one photo whose history is `steps` slider edits over the same mask, plus the
/// ops that built it (each step is one `SetDevelop` + one `PushHistory`, as the engine commits
/// an edit) and the shared grid's bytes.
fn masked_catalog(steps: usize) -> (Catalog, Vec<Op>, PhotoId, String) {
let seg = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
let blob = seg.data.clone();
let mut c = Catalog::new();
let id = c.alloc_photo_id();
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::File { path: "/p/1.jpg".into() }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) };
c.apply(add.clone()).unwrap();
let mut ops = vec![add];
for i in 1..=steps {
let settings = Arc::new(settings_with_seg(seg.clone(), f64::from(i as u32) * 0.1));
let op = Op::Batch {
ops: vec![
Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some(format!("t{i}")) },
Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings } },
],
};
c.apply(op.clone()).unwrap();
ops.push(op);
}
(c, ops, id, blob)
}
/// N history steps over one mask store the grid exactly once and load back identical.
#[test]
fn snapshot_deduplicates_shared_grid() {
let (live, ops, id, blob) = masked_catalog(20);
let m = MemStore::new();
let (mut j, _, report) = open(&m);
assert!(report.created);
j.append(&ops).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(snapshot_version(&m), u64::from(VERSION));
assert_eq!(body.match_indices(&blob).count(), 1, "the grid is stored once for every step that shares it");
let v: serde_json::Value = serde_json::from_str(body).unwrap();
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1);
let (_, loaded, report) = open(&m);
assert_eq!((report.replayed, report.upgraded_from, report.repaired.len()), (0, None, 0));
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
let p = loaded.photo(id).unwrap();
assert_eq!(p.history.len(), 20);
for h in &p.history {
let MaskShape::Object { seg: Some(seg), .. } = &h.settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), (blob.as_str(), None), "every step's grid is back inline");
}
}
/// A catalog written before the shared table (grids inline everywhere, format v9) loads as it
/// was and its upgrade rewrite deduplicates.
#[test]
fn v9_catalog_with_inline_grids_loads_and_is_upgraded() {
let (live, _, _, blob) = masked_catalog(3);
let body = live.to_snapshot();
assert!(body.contains(&blob), "a live catalog stores its grids inline");
let m = MemStore::new();
m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":2,\"catalog\":{body}}}\n").into_bytes());
let (_, loaded, report) = open(&m);
assert_eq!((report.replayed, report.upgraded_from), (0, Some(9)));
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
// rewritten in this format before anything is appended, with the grid once
assert_eq!(snapshot_version(&m), u64::from(VERSION));
let rewritten_bytes = m.get(SNAPSHOT).unwrap();
let rewritten = std::str::from_utf8(&rewritten_bytes).unwrap();
assert_eq!(rewritten.match_indices(&blob).count(), 1);
assert!(rewritten.contains("\"grids\":["), "the shared table is in the file");
}
/// The op log is not deduplicated: every record keeps the grids inline (a log never carries the
/// shared table), and replaying it rebuilds the same state.
#[test]
fn log_records_keep_their_grids_inline() {
let (live, ops, _, blob) = masked_catalog(2);
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
drop(j); // no snapshot: the log holds the whole state
let log_bytes = m.get(LOG).unwrap();
let log = std::str::from_utf8(&log_bytes).unwrap();
assert_eq!(log.match_indices(&blob).count(), 4, "two edits, SetDevelop + PushHistory each, inline");
let (_, loaded, report) = open(&m);
assert_eq!(report.replayed, 3, "the photo and the two edits");
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// A reference that points past the shared table is cleared (the mask renders nothing, like any
/// damaged grid); a good reference resolves back to the full grid.
#[test]
fn shared_grid_references_resolve_or_are_repaired() {
let (live, _, id, blob) = masked_catalog(1);
let inline = live.to_snapshot();
// a damaged snapshot: the develop mask refers past the one-entry table
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":7", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!(
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"dHdv\"],{} }} }}\n",
&body[1..body.len() - 1]
)
.into_bytes(),
);
let (_, damaged, report) = open(&m);
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
let p = damaged.photo(id).unwrap();
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared, never a crash");
// the history step's inline grid is untouched
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!(seg.data, blob);
// a good reference resolves (the normal way a snapshot in this format reads, so it is not
// reported as a repair): the mask reads exactly as it was written
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!(
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"{blob}\"],{} }} }}\n",
&body[1..body.len() - 1]
)
.into_bytes(),
);
let (_, resolved, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
assert_eq!(resolved.to_snapshot(), live.to_snapshot());
}
/// The background snapshot path shares the grids too (the interner is per thread).
#[test]
fn background_snapshot_deduplicates_shared_grid() {
let (live, ops, _, blob) = masked_catalog(5);
let mut m = MemStore::new();
m.background = true;
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
j.snapshot_in_background(&live).unwrap();
j.wait().unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(body.match_indices(&blob).count(), 1);
let (_, loaded, _) = open(&m);
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// A version (not only history steps) shares the grid: one photo with a snapshot version and a
/// history step over the same mask stores the grid once.
#[test]
fn versions_share_the_grid_too() {
let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]);
let blob = seg.data.clone();
let id = PhotoId(1);
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "d.jpg", "JPEG", 60, 40, "2026-01-01")) };
let settings = Arc::new(settings_with_seg(seg, 0.5));
let versions =
Op::SetVersions { id, versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }] };
let history = Op::PushHistory { id, step: HistoryStep { label: "e".into(), settings } };
let mut live = Catalog::new();
for op in [&add, &versions, &history] {
live.apply(op.clone()).unwrap();
}
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&[add, versions, history]).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(body.match_indices(&blob).count(), 1, "the version and the step share the grid");
let (_, loaded, _) = open(&m);
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// The import look (`Photo.import_look`, the settings a default preset gave the photo on import)
/// can hold AI masks, and their grids can be grids the develop settings or a history step hold.
/// Every settings holder shares the snapshot's table, so the look's masks are referenced and
/// resolved on load like the others; a grid only the look holds is in the table too.
#[test]
fn import_look_masks_share_the_table_and_resolve_on_load() {
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
let look_only = SegMask::from_logits(64, &vec![-0.5f32; 64 * 64]);
let mut look = DevelopSettings::default();
look.masks.push(object_mask(1, shared.clone()));
look.masks.push(object_mask(2, look_only.clone()));
let mut edit = DevelopSettings::default();
edit.light.exposure = 0.7;
edit.masks.push(object_mask(1, shared.clone()));
let edit = Arc::new(edit);
let id = PhotoId(1);
let mut photo = Photo::new(id, Source::File { path: "/p/2.jpg".into() }, "2.jpg", "JPEG", 60, 40, "2026-01-01");
photo.develop = edit.clone();
photo.import_look = Some(Arc::new(look));
photo.history.push(HistoryStep { label: "Exposure".into(), settings: edit });
let add = Op::AddPhoto { photo: Box::new(photo) };
let mut live = Catalog::new();
live.apply(add.clone()).unwrap();
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&[add]).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let body = std::str::from_utf8(&snap_bytes).unwrap();
assert_eq!(body.match_indices(&shared.data).count(), 1, "the grid of the look and of the edit is stored once");
assert_eq!(body.match_indices(&look_only.data).count(), 1);
let (_, loaded, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
let p = loaded.photo(id).unwrap();
let look_masks = &p.import_look.as_ref().unwrap().masks;
assert_eq!(look_masks.len(), 2);
for (mask, want) in look_masks.iter().zip([&shared, &look_only]) {
let MaskShape::Object { seg: Some(seg), .. } = &mask.components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), (want.data.as_str(), None), "the look's grid is back inline");
}
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
let v: serde_json::Value = serde_json::from_str(body).unwrap();
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 2, "one table entry per distinct grid, the look's included");
}
/// A `grid` that arrives from a document (a command's mask JSON, a preset, a merged partial) is
/// not a reference and is never written as one: a snapshot must not resolve it to another mask's
/// grid. Here photo two's mask carries `grid: 0` with empty data, while photo one's grid is the
/// table's entry 0; before the fix the inline form wrote `"grid":0` and the load filled photo two
/// with photo one's grid.
#[test]
fn stray_grid_from_a_document_is_not_written_as_a_reference() {
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
let stray: SegMask = serde_json::from_str(r#"{"side":64,"data":"","grid":0}"#).unwrap();
assert_eq!(stray.grid, Some(0), "a document can set grid");
let mut stray_settings = DevelopSettings::default();
stray_settings.masks.push(object_mask(1, stray));
let (one, two) = (PhotoId(1), PhotoId(2));
let photo = |id: PhotoId, name: &str| Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01");
let ops = [
Op::AddPhoto { photo: Box::new(photo(one, "1.jpg")) },
Op::SetDevelop { id: one, settings: Arc::new(settings_with_seg(shared.clone(), 0.2)), label: "Exposure".into(), edited: Some("t1".into()) },
Op::AddPhoto { photo: Box::new(photo(two, "2.jpg")) },
Op::SetDevelop { id: two, settings: Arc::new(stray_settings), label: "Edit".into(), edited: Some("t2".into()) },
];
let mut live = Catalog::new();
for op in &ops {
live.apply(op.clone()).unwrap();
}
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let (_, loaded, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
let MaskShape::Object { seg: Some(seg), .. } = &loaded.photo(two).unwrap().develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the stray reference is not resolved to photo one's grid");
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
}
/// A snapshot whose shared grid table is empty (`grids: []`) but whose masks still refer into
/// it: the table being empty must not skip the repair. A reference past an empty table is
/// dangling, so it is cleared (the mask renders nothing, like any other damaged grid), the
/// repair is reported, and a mask that carries its own grid inline is left untouched.
#[test]
fn empty_shared_grid_table_clears_dangling_references() {
let (live, _, id, blob) = masked_catalog(1);
let inline = live.to_snapshot();
// a damaged snapshot: an empty table, but the develop mask still refers to entry 0
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!(
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[],{} }} }}\n",
&body[1..body.len() - 1]
)
.into_bytes(),
);
let (_, damaged, report) = open(&m);
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
let p = damaged.photo(id).unwrap();
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with an empty table");
// the history step carries its grid inline: nothing there to resolve, left as it was
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
}
/// A snapshot that omits the shared grid table entirely (no `grids` key) but whose masks still
/// refer into it: an absent table deserializes to an empty Vec, so a reference past it is
/// dangling and is cleared and reported, just like the empty-table case.
#[test]
fn omitted_shared_grid_table_clears_dangling_references() {
let (live, _, id, blob) = masked_catalog(1);
let inline = live.to_snapshot();
// a damaged snapshot: no table at all, but the develop mask still refers to entry 0
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
let m = MemStore::new();
m.set(
SNAPSHOT,
format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{{} }} }}\n", &body[1..body.len() - 1])
.into_bytes(),
);
let (_, damaged, report) = open(&m);
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
let p = damaged.photo(id).unwrap();
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with no table");
// the history step carries its grid inline: nothing there to resolve, left as it was
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
}
+25
View File
@@ -262,6 +262,31 @@ fn push_history_is_bounded_and_invertible() {
assert_eq!(c.to_snapshot(), before);
}
/// A photo added with, or given, a whole History (op log replay, undo of a removal) kept every
/// step: only `PushHistory` applied the limit (#2579).
#[test]
fn add_photo_and_set_history_are_bounded_and_invertible() {
let mut c = Catalog::new();
let id = c.alloc_photo_id();
let step = |i: usize| HistoryStep { label: format!("s{i}"), settings: Arc::new(DevelopSettings::default()) };
let mut p = Photo::new(id, Source::Demo { scene: 1 }, "a", "JPEG", 1, 1, "t");
p.history = (0..HISTORY_LIMIT + 5).map(step).collect();
p.history_cursor = Some(10);
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let p = c.photo(id).unwrap();
assert_eq!((p.history.len(), p.history[0].label.as_str()), (HISTORY_LIMIT, "s5"));
assert_eq!(p.history_cursor, Some(5), "the cursor stays on step s10");
let before = c.to_snapshot();
let inv = c.apply(Op::SetHistory { id, history: (0..HISTORY_LIMIT * 2).map(step).collect() }).unwrap();
let p = c.photo(id).unwrap();
assert_eq!(p.history.len(), HISTORY_LIMIT);
assert_eq!(p.history[0].label, format!("s{HISTORY_LIMIT}"));
assert_eq!(p.history_cursor, Some(0), "its step was dropped: the oldest one kept");
c.apply(inv).unwrap();
assert_eq!(c.to_snapshot(), before);
}
#[test]
fn fs_store_roundtrip() {
let dir = std::env::temp_dir().join(format!("lc-journal-{}", std::process::id()));
+232
View File
@@ -0,0 +1,232 @@
//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once
//! however slow the drive is; everything handed over is written in order; a write that fails is
//! held, reported and retried, never dropped, and the log never has a gap.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use crate::fault::{self, Step};
use crate::store::{FsStore, Store};
const LOG: &str = "catalog.log";
fn temp_dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
let t = Instant::now();
while !done() {
assert!(t.elapsed() < Duration::from_secs(20), "{what}");
std::thread::sleep(Duration::from_millis(10));
}
}
/// Appends are written by the thread in order; a read through the store sees every one; a cut
/// and a replace come after the appends before them; dropping the store writes what is left.
#[test]
fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() {
let dir = temp_dir("order");
let mut store = FsStore::open(&dir).unwrap();
let mut want = Vec::new();
for i in 0..200u32 {
let line = format!("{i}\n");
store.append(LOG, line.as_bytes()).unwrap();
want.extend_from_slice(line.as_bytes());
if i % 50 == 0 {
assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store");
}
}
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file");
store.truncate(LOG, 4).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
// never longer than it is
store.truncate(LOG, 400).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
store.append(LOG, b"x\n").unwrap();
store.write_atomic(LOG, b"tail\n").unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n");
store.append(LOG, b"more\n").unwrap();
drop(store);
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n");
let _ = std::fs::remove_dir_all(&dir);
}
/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of
/// them in the file (before, each append waited for its own sync: 30 s for these).
#[test]
fn an_append_never_waits_for_a_slow_sync() {
let dir = temp_dir("slow");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"first\n").unwrap();
let syncs = Arc::new(AtomicUsize::new(0));
let n = syncs.clone();
fault::install(
&dir,
Arc::new(move |step| {
if step == Step::Sync {
n.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(300));
}
Ok(())
}),
);
let mut want = b"first\n".to_vec();
let mut slowest = Duration::ZERO;
for i in 0..100u32 {
let line = format!("{i}\n");
let t = Instant::now();
store.append(LOG, line.as_bytes()).unwrap();
slowest = slowest.max(t.elapsed());
want.extend_from_slice(line.as_bytes());
std::thread::sleep(Duration::from_millis(2));
}
assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}");
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want);
// batched: far fewer syncs than appends
assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst));
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later
/// appends are refused so the caller keeps them, and once writes work again the held bytes land,
/// in order, with no fragment of the failed attempts and no gap.
#[test]
fn a_failed_write_is_held_reported_and_retried() {
let dir = temp_dir("fail");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"0\n").unwrap();
store.flush().unwrap();
let fail = Arc::new(AtomicBool::new(true));
let f = fail.clone();
fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) }));
// (one append: the log thread can fail the first before a second arrives, and then refuses it)
store.append(LOG, b"1\n2\n").unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
let (held, why) = store.unwritten().unwrap();
assert!(why.contains("disk full"), "{why}");
assert!(held >= 1, "{held}");
let refused = store.append(LOG, b"3\n");
assert!(refused.is_err(), "refused while held");
assert!(store.flush().is_err(), "a flush says it isn't written");
// a read through the store still sees what was handed over
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a cut within what is held keeps it (the journal cuts back to its own length on an error)
store.truncate(LOG, 6).unwrap();
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a fragment of a failed write left in the file is cut before the retry
{
use std::io::Write;
let mut file = std::fs::OpenOptions::new().append(true).open(dir.join(LOG)).unwrap();
file.write_all(b"{\"seq\":").unwrap();
}
fail.store(false, Ordering::SeqCst);
wait_until("retried on its own", || store.unwritten().is_none());
store.append(LOG, b"3\n").unwrap();
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n");
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a
/// journal over a log that failed has no gap (no damage on load).
#[test]
fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() {
use crate::{Catalog, Journal, Op, Photo, PhotoId, Source};
let dir = temp_dir("journal");
let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
let fail = Arc::new(AtomicBool::new(false));
let f = fail.clone();
fault::install(
&dir,
Arc::new(move |step| {
if f.load(Ordering::SeqCst) {
return Err(std::io::Error::other("network share dropped (test)"));
}
if step == Step::Sync {
std::thread::sleep(Duration::from_millis(40));
}
Ok(())
}),
);
let mut queued: Vec<Op> = Vec::new();
for id in 1..=60u64 {
if id == 20 {
fail.store(true, Ordering::SeqCst);
}
if id == 40 {
fail.store(false, Ordering::SeqCst);
}
let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02");
let op = Op::AddPhoto { photo: Box::new(p) };
c.apply(op.clone()).unwrap();
queued.push(op);
// as the engine does: a failed append keeps its ops queued for the next one
if j.append(&queued).is_ok() {
queued.clear();
}
std::thread::sleep(Duration::from_millis(5));
}
wait_until("everything written", || {
if !queued.is_empty() && j.append(&queued).is_ok() {
queued.clear();
}
queued.is_empty() && j.unwritten().is_none()
});
j.flush().unwrap();
let expect = c.to_snapshot();
drop(j);
fault::remove(&dir);
let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert!(report.damaged.is_none(), "{report:?}");
assert_eq!(again.to_snapshot(), expect);
assert_eq!(again.len(), 60);
let _ = std::fs::remove_dir_all(&dir);
}
/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly
/// that length removes them from the file too, so they never come back on the next open (review
/// of #3557).
#[test]
fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() {
let dir = temp_dir("cut-synced");
let mut store = FsStore::open(&dir).unwrap();
store
.append(
LOG, b"0
",
)
.unwrap();
store.flush().unwrap();
fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) }));
store
.append(
LOG, b"1
",
)
.unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
1
",
"written, not synced"
);
store.truncate(LOG, 2).unwrap();
fault::remove(&dir);
drop(store);
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
"
);
let _ = std::fs::remove_dir_all(&dir);
}
+51
View File
@@ -195,6 +195,33 @@ fn id_counters_are_moved_past_the_ids_in_use() {
assert!(c.apply(Op::AddPhoto { photo: Box::new(p) }).is_err(), "the id is taken: refused, not overwritten");
}
/// History was bounded only where an edit adds a step, so a snapshot holding more steps kept
/// every one in memory on each load (#2579). The newest are kept and the cursor stays on its step.
#[test]
fn history_beyond_the_limit_is_trimmed_on_load() {
let (mut c, ids) = sound();
let extra = HISTORY_LIMIT * 5;
let step = HistoryStep { label: "s0".into(), settings: std::sync::Arc::new(lightcraft_develop::DevelopSettings::default()) };
c.apply(Op::PushHistory { id: ids[0], step }).unwrap();
c.apply(Op::SetHistoryCursor { id: ids[0], cursor: Some(extra - 3) }).unwrap();
let (loaded, report) = load_edited(&c, |v| {
let history = &mut v["photos"][ids[0].0.to_string()]["history"];
let one = history[0].clone();
*history = (0..extra)
.map(|i| {
let mut s = one.clone();
s["label"] = format!("s{i}").into();
s
})
.collect();
});
let p = loaded.photo(ids[0]).unwrap();
assert_eq!(p.history.len(), HISTORY_LIMIT);
assert_eq!(p.history[0].label, format!("s{}", extra - HISTORY_LIMIT));
assert_eq!(p.history_index().map(|i| p.history[i].label.clone()), Some(format!("s{}", extra - 3)));
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
}
/// A sound catalog loads unchanged.
#[test]
fn a_sound_snapshot_needs_no_repair() {
@@ -218,3 +245,27 @@ fn an_album_filed_under_another_id_gets_its_own() {
assert_eq!((a.id, a.parent), (inner, Some(folder)));
assert_eq!(c.album_children(Some(folder)).iter().map(|a| a.id).collect::<Vec<_>>(), vec![inner]);
}
/// What was worked out from the albums (whether rules may be tested cheapest first) is worked out
/// again when a repair changes the albums.
#[test]
fn a_repair_forgets_what_was_worked_out_from_the_albums() {
let (mut c, _) = sound();
let smart = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..album(smart.0, None, false, vec![]) } }).unwrap();
assert!(!c.keeps_written_order(), "worked out, and remembered");
// damaged outside `apply`: the smart album tests itself, and an album is filed under another id
let rules: Filter =
serde_json::from_value(serde_json::json!({"ruleSet": {"match": "all", "rules": [{"field": "album", "op": "is", "value": smart.0}]}}))
.unwrap();
if let Some(a) = c.albums.get_mut(&smart) {
a.smart = Some(Box::new(rules));
}
let inner = c.albums().find(|a| !a.folder && a.smart.is_none()).unwrap().id;
if let Some(mut a) = c.albums.remove(&inner) {
a.id = AlbumId(900);
c.albums.insert(inner, a);
}
assert!(!c.repair().is_empty());
assert!(c.keeps_written_order(), "the loop the repair left is seen");
}
+365
View File
@@ -0,0 +1,365 @@
//! A rule set is tested cheapest rule first ([`RuleSet::by_cost`]), once per pass; what matches
//! is what testing the rules in the order they were written gives.
//!
//! Scenarios:
//! - Given random libraries (Unicode and Windows paths, nested groups, album rules that test
//! smart albums and missing albums), then every album, query and count gives what the written
//! order gives, for all, any and none.
//! - Given a library where smart albums test themselves (the app refuses to make one; a saved or
//! damaged catalog can hold it, and there the answer can depend on which album is asked first),
//! then the rules are tested as written, so the answers are the written order's, as before.
//! - Given `all[album is <smart album>, <a rule no photo meets>]`, then the smart album is never
//! asked about a photo: the cheap rule ends it first (written first, it ran for every photo).
//! - Given rules in any order, then the saved rules and the order the editor shows are untouched.
use serde_json::json;
use crate::rules::{EVALUATED, WRITTEN_ORDER};
use crate::*;
/// A small generator: the same sequence every run.
struct Rng(u64);
impl Rng {
fn next(&mut self, n: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % n
}
fn pick<'a, T>(&mut self, of: &'a [T]) -> &'a T {
&of[self.next(of.len() as u64) as usize]
}
}
const PATHS: &[&str] = &[
"/Volumes/share/photos/Asie/Japon/Été/IMG_0001.jpg",
"/Volumes/share/photos/ASIE/japon/IMG_0002.JPG",
"C:\\Users\\me\\Pictures\\Ünïcode\\Tokyo\\IMG_0003.jpg",
"/Volumes/share/photos/Straße/İstanbul/IMG_0004.cr2",
"/Volumes/share/photos/東京/渋谷/IMG_0005.jpg",
"/Volumes/share/photos/Asie/Chine/clip.mp4",
"relative/dir/IMG_0007.jpg",
];
const WORDS: &[&str] =
&["asie", "Japon", "été", "ÜNÏCODE", "tokyo", "straße", "i̇stanbul", "東京", "photos\\asie", "photos/Asie/", " ", "", "img_000"];
fn library(rng: &mut Rng) -> (Catalog, Vec<PhotoId>) {
let mut c = Catalog::new();
let ids: Vec<PhotoId> = (0..24)
.map(|i| {
let id = c.alloc_photo_id();
let path = if i == 5 { None } else { Some(rng.pick(PATHS).to_string()) };
let source = path.map_or(Source::Demo { scene: 1 }, |path| Source::File { path });
let name = format!("IMG_{i:04}.{}", ["jpg", "cr2", "mp4"][rng.next(3) as usize]);
let mut p = Photo::new(id, source, &name, "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.rating = rng.next(6) as u8;
p.flag = [Flag::None, Flag::Pick, Flag::Reject][rng.next(3) as usize];
p.label = [None, Some(ColorLabel::Red), Some(ColorLabel::Blue)][rng.next(3) as usize];
p.meta.keywords = (0..rng.next(4)).map(|k| format!("kw{}", k + rng.next(2))).collect();
p.captured = Some(format!("20{}-0{}-1{}T10:00:00", 10 + rng.next(16), 1 + rng.next(9), rng.next(9)));
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
id
})
.collect();
(c, ids)
}
fn leaf(rng: &mut Rng, albums: &[AlbumId]) -> serde_json::Value {
let field = |f: &str, op: &str, v: serde_json::Value| json!({"field": f, "op": op, "value": v});
match rng.next(14) {
0 => field("rating", ["gte", "lte", "is", "gt", "lt"][rng.next(5) as usize], json!(rng.next(6))),
1 => field("flag", ["is", "isNot"][rng.next(2) as usize], json!(["pick", "reject", "none"][rng.next(3) as usize])),
2 => field("label", ["is", "isNot"][rng.next(2) as usize], json!(["red", "blue", "none"][rng.next(3) as usize])),
3 => field("kind", ["is", "isNot"][rng.next(2) as usize], json!(["image", "raw", "video"][rng.next(3) as usize])),
4 => field("keywordCount", ["lte", "gte"][rng.next(2) as usize], json!(rng.next(4))),
5 => field("keywords", ["contains", "notContains", "isEmpty"][rng.next(3) as usize], json!(format!("kw{}", rng.next(3)))),
6 => field("captureDate", ["before", "after"][rng.next(2) as usize], json!(format!("20{}", 10 + rng.next(16)))),
7 | 8 => field("filePath", ["contains", "notContains", "startsWith", "is", "isEmpty"][rng.next(5) as usize], json!(*rng.pick(WORDS))),
9 => field("fileName", "contains", json!(["img_000", ".cr2", "mp4"][rng.next(3) as usize])),
10 => field("text", ["contains", "notContains"][rng.next(2) as usize], json!(*rng.pick(WORDS))),
// an album that may not exist (99) or may be on a loop
_ => {
let album = if rng.next(8) == 0 { AlbumId(99) } else { *rng.pick(albums) };
field("album", ["is", "isNot"][rng.next(2) as usize], json!(album.0))
}
}
}
fn rule_set(rng: &mut Rng, albums: &[AlbumId], depth: u32) -> serde_json::Value {
let rules: Vec<serde_json::Value> = (0..rng.next(5))
.map(|_| if depth < 2 && rng.next(4) == 0 { json!({"group": rule_set(rng, albums, depth + 1)}) } else { leaf(rng, albums) })
.collect();
let mode = ["all", "any", "none"][rng.next(3) as usize];
json!({"match": mode, "rules": rules})
}
fn filter(rules: serde_json::Value) -> Filter {
Filter { rule_set: Some(serde_json::from_value(rules).unwrap()), ..Default::default() }
}
/// What a catalog answers for every album, photo and a few queries.
fn answers(c: &Catalog, albums: &[AlbumId], photos: &[PhotoId], queries: &[Filter]) -> String {
let mut out = String::new();
for a in albums {
let held: Vec<bool> = photos.iter().map(|p| c.album_contains(*a, c.photo(*p).unwrap())).collect();
out += &format!("{a:?} {held:?} {:?} {}\n", c.album_photos(*a), c.album_count(*a));
}
for p in photos {
out += &format!("{p:?} {:?}\n", c.albums_of(*p));
}
for q in queries {
out += &format!("{:?} {}\n", c.query(q, &Sort::default()), c.count(q));
}
out
}
#[test]
fn the_cheapest_first_order_matches_what_the_written_order_matches() {
let chained = same_answers_in_random_libraries(Rng(11), false);
assert!(chained > 20, "the generator makes smart albums that test smart albums: {chained}");
}
#[test]
fn a_library_with_loops_answers_as_written_and_does_not_hang() {
let looping = same_answers_in_random_libraries(Rng(5), true);
assert!(looping > 20, "the generator makes loops: {looping}");
}
/// Albums of random libraries and queries answer the same cheapest first and as written; returns
/// how many smart albums tested a smart album (`loops`: one that leads back to itself).
fn same_answers_in_random_libraries(mut rng: Rng, loops: bool) -> usize {
let mut chained = 0;
for round in 0..150 {
let (mut c, photos) = library(&mut rng);
let plain = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { photos: photos.iter().copied().step_by(3).collect(), ..Album::new(plain, "Plain") } }).unwrap();
let folder = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { folder: true, ..Album::new(folder, "F") } }).unwrap();
let smarts: Vec<AlbumId> = (0..6)
.map(|i| {
let id = c.alloc_album_id();
let parent = (i % 3 == 0).then_some(folder);
c.apply(Op::AddAlbum { album: Album { parent, smart: Some(Box::default()), ..Album::new(id, format!("S{i}")) } }).unwrap();
id
})
.collect();
let albums: Vec<AlbumId> = [plain, folder].into_iter().chain(smarts.iter().copied()).collect();
for (i, s) in smarts.iter().enumerate() {
// (without loops a smart album tests only the albums made before it)
let testable = if loops { &albums[..] } else { &albums[..2 + i] };
let _ = c.apply(Op::SetAlbumRules { id: *s, rules: Box::new(filter(rule_set(&mut rng, testable, 0))) });
}
let queries: Vec<Filter> = (0..4).map(|_| filter(rule_set(&mut rng, &albums, 0))).collect();
// (the copy starts without what the catalog worked out, so each is worked out under its own order)
let written = c.clone();
let ordered_answers = answers(&c, &albums, &photos, &queries);
WRITTEN_ORDER.set(true);
let written_answers = answers(&written, &albums, &photos, &queries);
WRITTEN_ORDER.set(false);
assert_eq!(ordered_answers, written_answers, "round {round}: {}", c.to_snapshot());
let reaching = |s: &AlbumId| {
smarts.iter().any(|t| if loops { c.album_reaches(*t, *s) && c.album_reaches(*s, *t) } else { t != s && c.album_reaches(*s, *t) })
};
chained += smarts.iter().filter(|s| reaching(s)).count();
assert_eq!(c.keeps_written_order(), smarts.iter().any(|s| c.album_reaches(*s, *s)));
assert!(loops || !c.keeps_written_order(), "round {round}: {}", c.to_snapshot());
}
chained
}
#[test]
fn a_cheap_rule_that_fails_ends_the_test_before_a_smart_album_runs() {
let mut c = Catalog::new();
let photos: Vec<PhotoId> = (0..20)
.map(|i| {
let id = c.alloc_photo_id();
let p = Photo::new(id, Source::File { path: format!("/a/b/{i}.jpg") }, &format!("{i}.jpg"), "JPEG", 6000, 4000, "2026-09-30T10:00:00");
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
id
})
.collect();
let inner = c.alloc_album_id();
c.apply(Op::AddAlbum {
album: Album {
smart: Some(Box::new(filter(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/a/"}]})))),
..Album::new(inner, "Inner")
},
})
.unwrap();
let rules = |first: serde_json::Value, second: serde_json::Value| json!({"match": "all", "rules": [first, second]});
let album = json!({"field": "album", "op": "is", "value": inner.0});
// no photo is rated 6 stars (a rating is at most 5)
let never = json!({"field": "rating", "op": "gte", "value": 6});
let outer = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(filter(rules(album.clone(), never.clone())))), ..Album::new(outer, "Outer") } })
.unwrap();
EVALUATED.set(0);
assert_eq!(c.album_count(outer), 0);
// (the outer album's own rules count as one run for each photo; its inner album must run for none)
assert_eq!(EVALUATED.get(), photos.len(), "only the outer album ran, once per photo");
// the same photos whichever way round the rules are written
let swapped = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(filter(rules(never, album)))), ..Album::new(swapped, "Swapped") } }).unwrap();
assert_eq!((c.album_count(swapped), c.album_photos(swapped)), (0, vec![]));
}
#[test]
fn rules_are_ordered_by_cost_without_touching_the_saved_ones() {
let mut c = Catalog::new();
let plain = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album::new(plain, "Plain") }).unwrap();
let smart = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(smart, "Smart") } }).unwrap();
let written: RuleSet = serde_json::from_value(json!({"match": "all", "rules": [
{"field": "album", "op": "is", "value": smart.0},
{"field": "filePath", "op": "contains", "value": "x"},
{"group": {"match": "any", "rules": [
{"field": "album", "op": "isNot", "value": smart.0},
{"field": "rating", "op": "gte", "value": 3}]}},
{"field": "keywords", "op": "contains", "value": "k"},
{"field": "album", "op": "is", "value": plain.0},
{"field": "rating", "op": "gte", "value": 3},
{"field": "album", "op": "is", "value": 99},
{"field": "flag", "op": "is", "value": "pick"}]}))
.unwrap();
let before = written.clone();
let ordered = written.by_cost(&c);
assert_eq!(written, before, "the saved rules stay as the user wrote them");
let names: Vec<String> = ordered
.rules
.iter()
.map(|r| match r {
Rule::Group { .. } => "group".to_string(),
Rule::Field { field, op, .. } => format!("{field} {op}"),
})
.collect();
// scalars (a missing album is false at once), then lists and a plain album, then text, then
// smart albums and the group that holds one; equals keep the written order
assert_eq!(names, ["rating gte", "album is", "flag is", "keywords contains", "album is", "filePath contains", "album is", "group"]);
let inner: Vec<&str> = match ordered.rules.get(7) {
Some(Rule::Group { group }) => group.rules.iter().map(|r| if let Rule::Field { field, .. } = r { field.as_str() } else { "group" }).collect(),
_ => Vec::new(),
};
assert_eq!(inner, ["rating", "album"], "nested groups are ordered too");
}
/// B = all[album is C], C = all[album isNot B], A = all[any[album is C, flag is pick], album is B]:
/// asked in the order the rules are written, a picked photo is not in A; asked cheapest first
/// (the flag, then the albums) it was. With a loop the order stays as written.
#[test]
fn smart_albums_that_test_each_other_keep_the_written_order() {
let mut c = Catalog::new();
let mut p = Photo::new(c.alloc_photo_id(), Source::File { path: "/a/1.jpg".into() }, "1.jpg", "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.flag = Flag::Pick;
let photo = p.id;
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let ids: Vec<AlbumId> = ["A", "B", "C"]
.iter()
.map(|name| {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(id, *name) } }).unwrap();
id
})
.collect();
let (a, b, cc) = (ids[0], ids[1], ids[2]);
let album = |op: &str, id: AlbumId| json!({"field": "album", "op": op, "value": id.0});
let set = |c: &mut Catalog, id: AlbumId, rules: serde_json::Value| c.apply(Op::SetAlbumRules { id, rules: Box::new(filter(rules)) }).unwrap();
set(&mut c, b, json!({"match": "all", "rules": [album("is", cc)]}));
set(&mut c, cc, json!({"match": "all", "rules": [album("isNot", b)]}));
set(
&mut c,
a,
json!({"match": "all", "rules": [
{"group": {"match": "any", "rules": [album("is", cc), {"field": "flag", "op": "is", "value": "pick"}]}},
album("is", b)]}),
);
let written = c.clone();
let ask = |c: &Catalog| {
ids.iter().map(|id| (c.album_contains(*id, c.photo(photo).unwrap()), c.album_photos(*id), c.album_count(*id))).collect::<Vec<_>>()
};
WRITTEN_ORDER.set(true);
let as_written = ask(&written);
WRITTEN_ORDER.set(false);
assert!(c.keeps_written_order());
assert_eq!(ask(&c), as_written);
}
/// A = all[any[album is D1, flag is pick], album is W], D1 tests D2 … D30, D30 tests W, W tests Z,
/// Z = rating ≥ 0: asked from A, the chain is cut by the depth limit, and asked cheapest first (the
/// flag, then the albums) the cut falls elsewhere. Chains that long keep the written order.
#[test]
fn a_chain_as_deep_as_the_limit_keeps_the_written_order() {
let mut c = Catalog::new();
let mut p = Photo::new(c.alloc_photo_id(), Source::File { path: "/a/1.jpg".into() }, "1.jpg", "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.flag = Flag::Pick;
p.rating = 0; // (Z, rating at least 0, holds for it)
let photo = p.id;
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let new_smart = |c: &mut Catalog, name: &str| {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::default()), ..Album::new(id, name) } }).unwrap();
id
};
let a = new_smart(&mut c, "A");
let chain: Vec<AlbumId> = (1..=30).map(|i| new_smart(&mut c, &format!("D{i}"))).collect();
let (w, z) = (new_smart(&mut c, "W"), new_smart(&mut c, "Z"));
let album = |id: AlbumId| json!({"field": "album", "op": "is", "value": id.0});
let set = |c: &mut Catalog, id: AlbumId, rules: serde_json::Value| c.apply(Op::SetAlbumRules { id, rules: Box::new(filter(rules)) }).unwrap();
set(
&mut c,
a,
json!({"match": "all", "rules": [{"group": {"match": "any", "rules": [album(chain[0]), {"field": "flag", "op": "is", "value": "pick"}]}}, album(w)]}),
);
for pair in chain.windows(2) {
set(&mut c, pair[0], json!({"match": "all", "rules": [album(pair[1])]}));
}
set(&mut c, chain[29], json!({"match": "all", "rules": [album(w)]}));
set(&mut c, w, json!({"match": "all", "rules": [album(z)]}));
set(&mut c, z, json!({"match": "all", "rules": [{"field": "rating", "op": "gte", "value": 0}]}));
let written = c.clone();
let ask = |c: &Catalog| [a, w, z, chain[0]].map(|id| (c.album_contains(id, c.photo(photo).unwrap()), c.album_photos(id), c.album_count(id)));
WRITTEN_ORDER.set(true);
let as_written = ask(&written);
// (the expected answers, written down: the same evaluator gives both sides below, so a
// regression that lets the 33rd album in would otherwise change both alike)
assert_eq!(as_written.each_ref().map(|answer| answer.0), [false, true, true, true], "the depth limit cuts the chain only while A is asked");
WRITTEN_ORDER.set(false);
assert!(c.keeps_written_order());
assert_eq!(ask(&c), as_written);
}
/// What was worked out from the albums (whether rules may be tested cheapest first) is worked out
/// again after an album is added or removed: 31 smart albums in a chain are fine, a 32nd on top of
/// it reaches the depth limit (the written order from then on), and taking it away lifts that.
#[test]
fn adding_or_removing_an_album_forgets_whether_the_rules_may_be_reordered() {
let mut c = Catalog::new();
let mut p = Photo::new(c.alloc_photo_id(), Source::File { path: "/a/1.jpg".into() }, "1.jpg", "JPEG", 6000, 4000, "2026-09-30T10:00:00");
p.flag = Flag::Pick;
let photo = p.id;
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let album = |id: AlbumId| json!({"field": "album", "op": "is", "value": id.0});
let smart = |c: &mut Catalog, name: &str, rules: serde_json::Value| {
let id = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(filter(rules))), ..Album::new(id, name) } }).unwrap();
id
};
// S1 tests S2 … S30 tests S31, which tests nothing: 31 albums
let mut chain = vec![smart(&mut c, "S31", json!({"match": "all", "rules": []}))];
for i in (1..=30).rev() {
let next = chain[chain.len() - 1];
chain.push(smart(&mut c, &format!("S{i}"), json!({"match": "all", "rules": [album(next)]})));
}
let bottom = chain[0];
let top = chain[30];
let ask = |c: &Catalog| [top, bottom].map(|id| (c.album_contains(id, c.photo(photo).unwrap()), c.album_photos(id), c.album_count(id)));
assert!(!c.keeps_written_order(), "31 albums in a chain are under the limit (worked out, and remembered)");
let before = ask(&c);
let head = smart(&mut c, "S0", json!({"match": "all", "rules": [album(top)]}));
assert!(c.keeps_written_order(), "a 32nd album on top of the chain reaches the depth limit");
assert_eq!(c.clone().keeps_written_order(), c.keeps_written_order(), "as a catalog that worked it out afresh");
assert_eq!(ask(&c), ask(&c.clone()));
c.apply(Op::RemoveAlbum { id: head }).unwrap();
assert!(!c.keeps_written_order(), "without it the chain is under the limit again");
assert_eq!(c.clone().keeps_written_order(), c.keeps_written_order());
assert_eq!(ask(&c), before);
}
+209 -1
View File
@@ -4,7 +4,7 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use crate::journal::LOG;
use crate::journal::{LOG, RESYNC_CANDIDATES};
use crate::*;
/// A store whose next append writes only a prefix of its data, then fails.
@@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() {
assert!(j.append(&batch).is_err(), "tear at {tear}");
// cut back to the last whole record
assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}");
// and a snapshot is due (records handed over before may be missing from a log written
// by a thread of its own: note 2 of 2026-10-25)
assert!(j.wants_snapshot(), "tear at {tear}");
j.append(&batch).unwrap();
let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]);
j.append(&more).unwrap();
@@ -221,3 +224,208 @@ fn fs_store_truncates_a_missing_file_quietly() {
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"");
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #2124: `resync` must be linear in the line length, not quadratic. A line that is nothing
/// but the start marker repeated 300k times must open fast, and a valid retry record placed after
/// it must still be recovered.
#[test]
fn resync_is_not_quadratic_in_line_length() {
let probe = MemStore::new();
// Build a valid snapshot + an initial record so `j.seq()` is non-zero and the `seq <= last + 1`
// gate in resync can be exercised.
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
let first = apply(&mut c, vec![add]);
j.append(&first).unwrap();
let log = probe.get(LOG).unwrap();
let base_len = log.len();
// A hostile 300k-repetition marker line (about 2.3 MB), then one valid retried record that
// continues the log (seq == j.seq() + 1, so resync's gate accepts it).
let marker = b"{\"seq\":";
let mut hostile = Vec::with_capacity(marker.len() * 300_000 + log.len() + 256);
hostile.extend_from_slice(&log[..base_len]);
for _ in 0..300_000 {
hostile.extend_from_slice(marker);
}
// Encode the retry record the same way the journal writes records, so decode_record accepts it.
let next_seq = j.seq() + 1;
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
hostile.extend_from_slice(retry.as_bytes());
probe.set(LOG, hostile);
// Count the start markers resync decodes instead of timing it: a slow worker must not fail this.
RESYNC_CANDIDATES.with(|c| c.set(0));
let (j2, _c2, report) = Journal::open(Box::new(probe.clone())).unwrap();
let candidates = RESYNC_CANDIDATES.with(|c| c.get());
assert!(candidates <= 1, "resync decoded {candidates} start markers of a hostile 2 MB line; only the last one may be decoded");
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
}
/// A retry record whose op body holds a nested `{"seq":` (a smart-album rule value such as
/// `{"seq":1}` on a `title isEmpty` rule) shadows the record's own start marker: `rposition` in
/// `resync` picks the nested occurrence, `decode_record` rejects the suffix, and `Journal::open`
/// truncates the final line instead of replaying the retry — the valid operation is lost.
#[test]
fn resync_preserves_retry_record_with_nested_start_marker() {
let probe = MemStore::new();
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
j.append(&apply(&mut c, vec![add])).unwrap();
let album_id = c.alloc_album_id();
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
j.append(&apply(&mut c, vec![add_album])).unwrap();
let retry_op = Op::SetAlbumRules {
id: album_id,
rules: Box::new(Filter {
rule_set: Some(RuleSet {
mode: Match::All,
rules: vec![Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }],
}),
..Default::default()
}),
};
apply(&mut c, vec![retry_op.clone()]);
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
// resync finds its real start: `seq` continues the log and the CRC matches the body.
let next_seq = j.seq() + 1;
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
// A torn fragment glued to the retry on the final line. The outer record start sits right
// after the fragment, but the last `{"seq":` byte occurrence is the nested rule value.
let mut log = probe.get(LOG).unwrap();
log.extend_from_slice(b"torn fragment without a newline");
log.extend_from_slice(retry.as_bytes());
probe.set(LOG, log);
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be truncated as torn");
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the recovered smart-album rule should be preserved");
}
/// The maintainer's regression for issue #2124, with the damaged line as the file's LAST one: a
/// torn fragment glued to a CRC-valid `SetAlbumRules` retry whose rules hold several nested
/// `{"seq":1}` values. Picking the last raw `{"seq":` occurrence as the record start (as the
/// original `rposition` scan did) lands in a nested value, rejects the whole record, and cuts the
/// final line away — losing the valid operation. `resync` must recover the retry (its real start
/// is followed by the `,"crc":` header no nested rule value has) and leave the log file whole.
#[test]
fn resync_recovers_rules_retry_with_many_nested_values_on_the_final_line() {
let probe = MemStore::new();
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
j.append(&apply(&mut c, vec![add])).unwrap();
let album_id = c.alloc_album_id();
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
j.append(&apply(&mut c, vec![add_album])).unwrap();
let rules =
(0..12).map(|_| Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }).collect::<Vec<_>>();
let retry_op =
Op::SetAlbumRules { id: album_id, rules: Box::new(Filter { rule_set: Some(RuleSet { mode: Match::All, rules }), ..Default::default() }) };
apply(&mut c, vec![retry_op.clone()]);
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
// resync finds its real start: `seq` continues the log and the CRC matches the body.
let next_seq = j.seq() + 1;
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}");
// The failed append's fragment glued to the retry, and nothing after: the damaged line is the
// file's last, without a closing newline.
let mut log = probe.get(LOG).unwrap();
log.extend_from_slice(b"torn fragment without a newline");
log.extend_from_slice(retry.as_bytes());
let damaged = log.clone();
probe.set(LOG, log);
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
assert_eq!(report.torn_fragments, 1, "the fragment must be reported and the retry recovered");
assert_eq!(report.torn_bytes, 0, "the retry record must not be cut away as a torn tail");
assert_eq!(j2.seq(), next_seq, "the retried SetAlbumRules must be recovered");
assert_eq!(report.replayed, 3);
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the smart-album rules must survive the reload");
// The log file is preserved: its bytes stay (plus only the newline that closes the final
// line), instead of the damaged line being truncated away.
let after = probe.get(LOG).unwrap();
assert_eq!(after.len(), damaged.len() + 1, "the log must keep the fragment and the recovered record");
assert_eq!(&after[..damaged.len()], &damaged[..]);
}
/// A crafted final line of many header-shaped markers (`{"seq":1,"crc":2,"op":`) passes the
/// record-header filter, so every marker becomes a resync candidate, and each attempt decodes the
/// whole rest of the line: trying all of them is quadratic in the line length, a stall of
/// `Journal::open` on a hostile log (CWE-407). The per-line scan budget must bound the candidate
/// decodes (counted, not timed) and open must still finish safely. A CRC-valid retry placed after
/// the junk must stay recoverable: it is the last candidate, so the scan reaches it first.
#[test]
fn resync_scan_budget_bounds_a_line_of_header_shaped_markers() {
let probe = MemStore::new();
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
let add = add_photo(&mut c);
j.append(&apply(&mut c, vec![add])).unwrap();
let good = probe.get(LOG).unwrap();
const MARKERS: usize = 5_000;
let marker: &[u8] = b"{\"seq\":1,\"crc\":2,\"op\":";
let mut hostile = good.clone();
hostile.extend_from_slice(b"torn fragment"); // so no marker sits at line position 0
for _ in 0..MARKERS {
hostile.extend_from_slice(marker);
}
let hostile_len = (hostile.len() - good.len()) as u64;
probe.set(LOG, hostile);
RESYNC_CANDIDATES.with(|count| count.set(0));
let (j2, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
assert!(
candidates < MARKERS,
"resync tried all {candidates} candidates of a hostile {hostile_len}-byte line; the scan budget must bound the work"
);
assert!(report.damaged.is_none(), "{report:?}");
assert_eq!(report.torn_fragments, 0);
assert_eq!(report.torn_bytes, hostile_len, "the hostile line must be dropped as a torn tail");
assert_eq!(j2.seq(), 1, "the records before the hostile line must survive");
assert_eq!(probe.get(LOG).unwrap().len(), good.len(), "the log must be cut back to the last good record");
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
let next_seq = j2.seq() + 1;
let body = serde_json::to_string(&retry_op).unwrap();
let crc = crc32fast::hash(body.as_bytes());
let mut log = good.clone();
for _ in 0..MARKERS {
log.extend_from_slice(marker);
}
log.extend_from_slice(format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n").as_bytes());
probe.set(LOG, log);
RESYNC_CANDIDATES.with(|count| count.set(0));
let (j3, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
assert_eq!(candidates, 1, "the retry is the last candidate and must decode first");
assert_eq!(j3.seq(), next_seq, "the retried record after the junk must be recovered");
assert_eq!(report.torn_fragments, 1, "the junk before the retry is one skipped fragment");
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be cut away");
}
+62
View File
@@ -0,0 +1,62 @@
//! Heap blocks a smart album's `filePath` rules allocate per photo, measured with dhat's testing mode. A rule over
//! a non-ASCII path or text (`crates/catalog/src/rules.rs`, `file_path_matches`) used to build two lower-cased
//! strings for every photo it was asked about; a large library asks it for every photo of every smart album, so
//! it compares in place. One test per binary (dhat's profiler is global).
use lightcraft_catalog::{Catalog, Photo, PhotoId, RuleSet, Source};
use serde_json::json;
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
fn photo(id: u64, path: &str) -> Photo {
Photo::new(PhotoId(id), Source::File { path: path.to_string() }, "IMG_0001.JPG", "JPG", 6000, 4000, "2026-09-20T10:00:00")
}
fn rule_set(op: &str, value: &str) -> RuleSet {
serde_json::from_value(json!({"rules": [{"field": "filePath", "op": op, "value": value}]})).unwrap()
}
#[test]
fn a_file_path_rule_allocates_nothing_per_photo() {
let cat = Catalog::new();
let photos: Vec<Photo> = ["/Volumes/tokyo/Фото/Éclair/Straße/ÜBER_2026.JPG", "D:\\日本語\\İstanbul\\IMG_0001.jpg", "/srv/plain/ascii/path.jpg"]
.iter()
.zip(1u64..)
.map(|(p, i)| photo(i, p))
.collect();
let rules: Vec<RuleSet> = [
("contains", "éCLAIR"),
("contains", "tokyo"),
("notContains", "ÜBER"),
("is", "/srv/plain/ascii/path.jpg"),
("isNot", "straße"),
("startsWith", "\\Volumes\\TOKYO\\ФОТО"),
("endsWith", ".JPG"),
("isEmpty", ""),
("isNotEmpty", ""),
]
.iter()
.map(|(op, v)| rule_set(op, v))
.collect();
// warm anything lazily built (the clock, thread locals) before counting
let expected: Vec<Vec<bool>> = rules.iter().map(|r| photos.iter().map(|p| r.matches(p, &cat)).collect()).collect();
let _profiler = dhat::Profiler::builder().testing().build();
let before = dhat::HeapStats::get().total_blocks;
let mut hits = 0usize;
for _ in 0..100 {
for (r, want) in rules.iter().zip(&expected) {
for (p, w) in photos.iter().zip(want) {
let got = r.matches(p, &cat);
assert_eq!(got, *w);
hits += usize::from(got);
}
}
}
let blocks = dhat::HeapStats::get().total_blocks - before;
assert!(hits > 0, "the rules matched nothing: the test measures nothing");
// dhat counts every thread, and the test harness's own thread can allocate a few blocks while this
// runs. An allocation per photo would be thousands, two per rule test.
let tests = 100 * rules.len() * photos.len();
assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests");
}
+1 -1
View File
@@ -46,7 +46,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d
| Format | Decode | Encode | Notes |
|---|---|---|---|
| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2, multi-chunk), Adobe APP14, MPF previews |
| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews |
| PNG | yes, 1–16-bit, palette, tRNS, interlaced | 8/16-bit, gray/GA/RGB/RGBA | iCCP, eXIf, iTXt XMP; sRGB/cICP/cHRM/gAMA honoured when no ICC |
| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `lightcraft-tiff`) |
| WebP | lossy + lossless, alpha, first frame of animations | lossless only | ICCP/EXIF/XMP chunks |
+6 -4
View File
@@ -78,6 +78,8 @@ pub(crate) struct Raw {
#[derive(Default)]
pub(crate) struct Meta {
pub icc: Option<Vec<u8>>,
/// An ICC profile was declared by the container but its sequence was invalid.
pub icc_invalid: bool,
pub exif: Option<Vec<u8>>,
pub xmp: Option<String>,
/// Orientation from the container itself (e.g. TIFF tag); EXIF blob is consulted otherwise.
@@ -120,7 +122,7 @@ pub(crate) fn finish(format: Format, raw: Raw, meta: Meta, source_dims: (u32, u3
let (image, space) = if let Some(space) = meta.already_linear.clone() {
(to_rgb_passthrough(&raw, ch), space)
} else if raw.model == Model::Cmyk {
cmyk(&raw, ch, meta.icc.as_deref(), parsed_icc.as_ref())
cmyk(&raw, ch, meta.icc.as_deref(), parsed_icc.as_ref(), meta.icc_invalid)
} else {
rgb_or_gray(&raw, ch, &meta, parsed_icc.as_ref(), float)
};
@@ -299,7 +301,7 @@ fn rgb_or_gray(raw: &Raw, ch: usize, meta: &Meta, info: Option<&icc::IccInfo>, f
_ => {}
}
}
if meta.icc.is_some() {
if meta.icc.is_some() || meta.icc_invalid {
// Present but unusable (malformed, mismatched model, CMS failure): assume sRGB.
let s = SourceSpace::named(NamedSpace::Srgb, SpaceOrigin::IccUnsupported);
let t = NamedSpace::Srgb.trc();
@@ -323,7 +325,7 @@ fn rgb_or_gray(raw: &Raw, ch: usize, meta: &Meta, info: Option<&icc::IccInfo>, f
(linearize(raw, ch, &t), s)
}
fn cmyk(raw: &Raw, ch: usize, icc_bytes: Option<&[u8]>, info: Option<&icc::IccInfo>) -> (Rgb32f, SourceSpace) {
fn cmyk(raw: &Raw, ch: usize, icc_bytes: Option<&[u8]>, info: Option<&icc::IccInfo>, icc_invalid: bool) -> (Rgb32f, SourceSpace) {
let samples = device_samples(raw, ch, 4);
if let (Some(bytes), Some(info)) = (icc_bytes, info)
&& info.model == IccColorModel::Cmyk
@@ -343,6 +345,6 @@ fn cmyk(raw: &Raw, ch: usize, icc_bytes: Option<&[u8]>, info: Option<&icc::IccIn
[(1.0 - c[0]) * k, (1.0 - c[1]) * k, (1.0 - c[2]) * k].map(lightcraft_color::transfer::srgb_to_linear)
})
.collect();
let origin = if icc_bytes.is_some() { SpaceOrigin::IccUnsupported } else { SpaceOrigin::Naive };
let origin = if icc_bytes.is_some() || icc_invalid { SpaceOrigin::IccUnsupported } else { SpaceOrigin::Naive };
(from_vec(raw.width, raw.height, px), SourceSpace::named(NamedSpace::Srgb, origin))
}
+429 -12
View File
@@ -24,6 +24,8 @@ pub(crate) struct Markers {
pub exif_offset: usize,
pub xmp: Option<String>,
pub icc: Option<Vec<u8>>,
/// An ICC_PROFILE APP2 segment was present but its sequence was invalid.
pub icc_invalid: bool,
pub adobe_transform: Option<u8>,
/// Offset of the MPF TIFF header within the file and its bytes.
pub mpf: Option<(usize, Vec<u8>)>,
@@ -45,7 +47,8 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
return None;
}
let mut m = Markers::default();
let mut icc_chunks: Vec<(u8, &[u8])> = Vec::new();
let mut icc_chunks: [Option<&[u8]>; 255] = [None; 255];
let mut icc_total = None;
let mut p = 2;
while p + 4 <= b.len() {
if b[p] != 0xFF {
@@ -73,9 +76,11 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
if len < 2 {
return None;
}
let start = p + 4;
let end = (p + 2 + len).min(b.len());
let seg = &b[start..end];
let start = p.checked_add(4)?;
let declared_end = p.checked_add(2)?.checked_add(len)?;
let complete = declared_end <= b.len();
let end = declared_end.min(b.len());
let seg = b.get(start..end)?;
match marker {
0xC0..=0xCF if marker != 0xC4 && marker != 0xC8 && marker != 0xCC && seg.len() >= 6 && m.components == 0 => {
m.precision = seg[0];
@@ -96,8 +101,30 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
}
}
0xE2 => {
if seg.starts_with(b"ICC_PROFILE\0") && seg.len() >= 14 {
icc_chunks.push((seg[12], &seg[14..]));
if seg.starts_with(b"ICC_PROFILE\0") {
if !complete || seg.len() < 14 {
m.icc_invalid = true;
} else if let (Some(&sequence), Some(&total)) = (seg.get(12), seg.get(13)) {
if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) {
m.icc_invalid = true;
} else {
icc_total = Some(total);
let Some(slot) = icc_chunks.get_mut(usize::from(sequence - 1)) else {
m.icc_invalid = true;
p = declared_end;
continue;
};
if slot.is_some() {
m.icc_invalid = true;
} else if let Some(data) = seg.get(14..) {
*slot = Some(data);
} else {
m.icc_invalid = true;
}
}
} else {
m.icc_invalid = true;
}
} else if seg.starts_with(b"MPF\0") && m.mpf.is_none() {
m.mpf = Some((start + 4, seg[4..].to_vec()));
} else if let Some(p) = seg.strip_prefix(crate::gainmap::ISO_URN)
@@ -111,11 +138,32 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
}
_ => {}
}
p += 2 + len;
p = declared_end;
}
if !icc_chunks.is_empty() {
icc_chunks.sort_by_key(|c| c.0);
m.icc = Some(icc_chunks.iter().flat_map(|c| c.1.iter().copied()).collect());
if let Some(total) = icc_total {
let mut profile_len = 0usize;
for chunk in icc_chunks.iter().take(usize::from(total)) {
let Some(bytes) = chunk else {
m.icc_invalid = true;
break;
};
let Some(next_len) = profile_len.checked_add(bytes.len()) else {
m.icc_invalid = true;
break;
};
profile_len = next_len;
}
let maximum_len = usize::from(total).checked_mul(65_519);
if maximum_len.is_none_or(|maximum| profile_len > maximum) {
m.icc_invalid = true;
}
if !m.icc_invalid {
let mut profile = Vec::with_capacity(profile_len);
for bytes in icc_chunks.iter().take(usize::from(total)).flatten() {
profile.extend_from_slice(bytes);
}
m.icc = Some(profile);
}
}
Some(m)
}
@@ -131,6 +179,7 @@ const MAX_APP1: u32 = 128;
/// type or component count, or when its markers don't run to an end-of-image marker after the
/// image data (a truncated file). Damage *inside* the entropy-coded data can't be seen this way.
pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> {
let bytes = &*without_sef_trailer(bytes);
let m = parse_markers(bytes).ok_or_else(|| Error::Malformed(F, "missing SOI".into()))?;
if m.components == 0 {
return Err(Error::Malformed(F, "no frame header".into()));
@@ -177,7 +226,62 @@ fn reaches_eoi(b: &[u8]) -> bool {
}
}
/// A Samsung panorama whose scan runs straight into its SEF trailer, with no EOI marker (issue
/// #3350), as the file it stands for: the bytes before the trailer's earliest data block plus an
/// EOI. Every other file, a genuinely truncated one included, is borrowed unchanged.
fn without_sef_trailer(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
use std::borrow::Cow;
// The trailer is checked first: it reads only the file's last bytes, not the scan data.
let Some(image) = sef_image_end(bytes).and_then(|end| bytes.get(..end)) else { return Cow::Borrowed(bytes) };
// the image before the trailer: an FF D9 inside the SEF data doesn't end the scan
if reaches_eoi(image) {
return Cow::Borrowed(bytes);
}
let mut fixed = Vec::with_capacity(image.len().saturating_add(2));
fixed.extend_from_slice(image);
fixed.extend_from_slice(&[0xFF, 0xD9]);
// The cut must leave the scan data, not a segment or anything before the first scan, open.
let in_scan = parse_markers(&fixed).is_some_and(|m| m.first_scan_components > 0) && reaches_eoi(&fixed);
if in_scan { Cow::Owned(fixed) } else { Cow::Borrowed(bytes) }
}
/// Where the image ends in a file carrying a Samsung SEF trailer: the start of its earliest data
/// block. The trailer is the file's last bytes: `SEFH`, a u32 LE version and entry count, 12-byte
/// entries (u16 padding, u16 type, u32 LE offset of the block back from `SEFH`, u32 LE length),
/// then the u32 LE length of that directory and `SEFT`. Each block starts with the same padding
/// and type as its entry. `None` unless every entry's block is nonempty, starts with its entry's
/// type and lies inside the file, before `SEFH`.
fn sef_image_end(b: &[u8]) -> Option<usize> {
let le32 = |at: usize| b.get(at..at.checked_add(4)?)?.try_into().ok().map(|v| u32::from_le_bytes(v) as usize);
let tail = b.len().checked_sub(8)?;
if b.get(tail.checked_add(4)?..)? != b"SEFT" {
return None;
}
let dir = tail.checked_sub(le32(tail)?)?;
if b.get(dir..dir.checked_add(4)?)? != b"SEFH" {
return None;
}
let count = le32(dir.checked_add(8)?)?;
let entries = dir.checked_add(12)?;
if count == 0 || count > tail.checked_sub(entries)? / 12 {
return None;
}
let mut start = dir;
for i in 0..count {
let entry = entries.checked_add(i.checked_mul(12)?)?;
let block = dir.checked_sub(le32(entry.checked_add(4)?)?)?;
let len = le32(entry.checked_add(8)?)?;
let kind = |at: usize| b.get(at.checked_add(2)?..at.checked_add(4)?);
if len < 4 || block.checked_add(len)? > dir || kind(block)? != kind(entry)? {
return None;
}
start = start.min(block);
}
Some(start)
}
pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback: Option<crate::NamedSpace>) -> Result<Decoded> {
let bytes = &*without_sef_trailer(bytes);
let m = parse_markers(bytes).ok_or_else(|| Error::Malformed(F, "missing SOI".into()))?;
if m.components == 0 {
return Err(Error::Malformed(F, "no frame header".into()));
@@ -201,8 +305,10 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
};
// A raw container may carry the colour declaration of an otherwise untagged preview.
// Apply it before linearization/resizing; existing JPEG metadata always wins.
let hint = fallback.filter(|_| m.icc.is_none() && m.exif.is_none()).map(|space| crate::SourceSpace::named(space, crate::SpaceOrigin::Container));
let meta = Meta { icc: m.icc, exif: m.exif, xmp: m.xmp, hint, ..Default::default() };
let hint = fallback
.filter(|_| m.icc.is_none() && !m.icc_invalid && m.exif.is_none())
.map(|space| crate::SourceSpace::named(space, crate::SpaceOrigin::Container));
let meta = Meta { icc: m.icc, icc_invalid: m.icc_invalid, exif: m.exif, xmp: m.xmp, hint, ..Default::default() };
finish(F, raw, meta, (m.width, m.height), opts)
}
@@ -450,6 +556,110 @@ mod tests {
assert!(crate::decode_jpeg_with_fallback(b"bad JPEG", DecodeOptions::default(), NamedSpace::AdobeRgb).is_err());
}
fn app2_icc(sequence: u8, total: u8, data: &[u8]) -> Vec<u8> {
let mut payload = b"ICC_PROFILE\0".to_vec();
payload.extend_from_slice(&[sequence, total]);
payload.extend_from_slice(data);
let mut segment = vec![0xff, 0xe2];
segment.extend_from_slice(&u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
segment.extend_from_slice(&payload);
segment
}
fn jpeg_with_icc_chunks(chunks: &[Vec<u8>]) -> Vec<u8> {
use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let pixels = [180, 60, 40, 180, 60, 40, 180, 60, 40, 180, 60, 40];
let base = encode_jpeg(&EncodeImage::new(2, 2, 3, Samples::U8(&pixels)), 100, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
let mut jpeg = base.get(..2).unwrap_or_default().to_vec();
for chunk in chunks {
jpeg.extend_from_slice(chunk);
}
jpeg.extend_from_slice(base.get(2..).unwrap_or_default());
jpeg
}
#[test]
fn jpeg_icc_accepts_reordered_chunks_and_preserves_pixels() {
use crate::{NamedSpace, SpaceOrigin, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let (first, second) = profile.split_at(profile.len() / 2);
let single = jpeg_with_icc_chunks(&[app2_icc(1, 1, &profile)]);
let reordered = jpeg_with_icc_chunks(&[app2_icc(2, 2, second), app2_icc(1, 2, first)]);
let one = crate::decode(&single, DecodeOptions::default()).unwrap();
let two = crate::decode(&reordered, DecodeOptions::default()).unwrap();
assert_eq!(one.icc.as_deref(), Some(profile.as_slice()));
assert_eq!(two.icc.as_deref(), Some(profile.as_slice()));
assert!(!parse_markers(&reordered).unwrap().icc_invalid);
assert_eq!(one.space, two.space);
assert_eq!(two.space.origin, SpaceOrigin::IccMatrixTrc);
let (a, b) = (one.to_working(), two.to_working());
assert_eq!(a.data.len(), b.data.len());
for (left, right) in a.data.iter().zip(&b.data) {
assert!(left.iter().zip(right).all(|(x, y)| (x - y).abs() < 0.00001), "{left:?} != {right:?}");
}
}
#[test]
fn jpeg_icc_rejects_incoherent_chunks_and_uses_unsupported_fallback() {
use crate::{NamedSpace, SpaceOrigin, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let (first, second) = profile.split_at(profile.len() / 2);
let base = jpeg_with_icc_chunks(&[]);
let reference = crate::decode(&base, DecodeOptions::default()).unwrap();
let cases = [
("missing", vec![app2_icc(1, 2, &profile)]),
("duplicate", vec![app2_icc(1, 2, first), app2_icc(1, 2, second)]),
("zero sequence", vec![app2_icc(0, 1, &profile)]),
("zero total", vec![app2_icc(1, 0, &profile)]),
("out of range", vec![app2_icc(2, 1, &profile)]),
("gap", vec![app2_icc(1, 3, first), app2_icc(3, 3, second)]),
("inconsistent totals", vec![app2_icc(1, 2, first), app2_icc(2, 3, second)]),
("short header", {
let mut segment = vec![0xff, 0xe2];
segment.extend_from_slice(&15u16.to_be_bytes());
segment.extend_from_slice(b"ICC_PROFILE\0\x01");
vec![segment]
}),
];
for (name, chunks) in cases {
let jpeg = jpeg_with_icc_chunks(&chunks);
let markers = parse_markers(&jpeg).unwrap();
let decoded = crate::decode(&jpeg, DecodeOptions::default()).unwrap();
assert_eq!(decoded.space.origin, SpaceOrigin::IccUnsupported, "{name}: invalid profile must not be applied");
assert!(markers.icc.is_none(), "{name}: invalid ICC must not be assembled");
assert!(markers.icc_invalid, "{name}: invalid ICC presence must be retained");
assert_eq!(decoded.icc, None, "{name}: invalid ICC bytes must not escape decode");
assert_eq!(decoded.space.origin, SpaceOrigin::IccUnsupported, "{name}");
assert_eq!(decoded.space.named, Some(NamedSpace::Srgb), "{name}");
assert_eq!(decoded.to_working(), reference.to_working(), "{name}: fallback pixels");
}
}
#[test]
fn jpeg_icc_invalid_sequence_prevents_raw_colour_hint() {
use crate::{NamedSpace, SpaceOrigin, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let jpeg = jpeg_with_icc_chunks(&[app2_icc(1, 2, &profile)]);
let decoded = crate::decode_jpeg_with_fallback(&jpeg, DecodeOptions::default(), NamedSpace::AdobeRgb).unwrap();
assert_eq!(decoded.space.origin, SpaceOrigin::IccUnsupported);
assert_eq!(decoded.space.named, Some(NamedSpace::Srgb));
}
#[test]
fn jpeg_icc_rejects_truncated_app2_segment() {
use crate::{NamedSpace, icc};
let profile = icc::write_named(NamedSpace::DisplayP3);
let mut segment = app2_icc(1, 1, &profile);
let declared = u16::from_be_bytes([segment[2], segment[3]]).saturating_add(1);
segment[2..4].copy_from_slice(&declared.to_be_bytes());
let mut jpeg = vec![0xff, 0xd8];
jpeg.extend_from_slice(&segment);
let markers = parse_markers(&jpeg).unwrap();
assert!(markers.icc.is_none());
assert!(markers.icc_invalid);
}
#[test]
fn scaled_request_covers() {
assert_eq!(scaled_request(6000, 4000, 256, 256), (256, 171));
@@ -652,3 +862,210 @@ mod tests {
}
}
}
/// [`crate::decode_jpeg_srgb8_fit`]: a plain 8-bit sRGB JPEG decoded (DCT-scaled when that still
/// covers the box) and area-averaged in linear light straight into 8-bit sRGB, without the
/// float image the general path builds (for a 45 MP camera preview fitted to 2560 px that float
/// image and its conversions were half the time). `Ok(None)` for anything else.
pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(lightcraft_raster::Rgba8, u16)>> {
// (a Samsung SEF trailer read as the file it stands for, as the general decode does: CodeRabbit on #3583)
let bytes = &*without_sef_trailer(bytes);
let Some(m) = parse_markers(bytes) else { return Ok(None) };
let plain = matches!(m.components, 1 | 3)
&& m.precision == 8
&& matches!(m.sof, 0xC0..=0xC2)
&& m.icc.is_none()
&& !m.icc_invalid
&& m.adobe_transform.is_none();
let summary = m.exif.as_deref().map(exif::summarize).unwrap_or_default();
if !plain || summary.adobe_rgb_hint || max_w == 0 || max_h == 0 {
return Ok(None);
}
let budget = DecodeOptions::default();
check_size(F, m.width as u64, m.height as u64, &budget)?;
// as in the general decode: the decoders below walk every APP1 again
if m.app1 > MAX_APP1 {
return Err(Error::Malformed(F, "too many APP1 markers".into()));
}
let scale_to = (m.width >= max_w.saturating_mul(2) || m.height >= max_h.saturating_mul(2)).then_some((max_w, max_h));
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
let raw =
if scale_to.is_some() || non_interleaved { decode_jpeg_decoder(bytes, &m, scale_to, &budget)? } else { decode_zune(bytes, &m, &budget)? };
let Buf::U8(px) = &raw.buf else { return Ok(None) };
let ch = match raw.model {
Model::Rgb => 3,
Model::Gray => 1,
Model::Cmyk => return Ok(None),
};
let (w, h) = (raw.width, raw.height);
if w == 0 || h == 0 || px.len() < w.saturating_mul(h).saturating_mul(ch) {
return Err(Error::Malformed(F, "short output".into()));
}
// the size `lightcraft_raster::resample::fit` gives: within the box, aspect kept, never larger
let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0);
let tw = ((w as f64 * s).round() as usize).clamp(1, w);
let th = ((h as f64 * s).round() as usize).clamp(1, h);
let orientation = summary.orientation.filter(|o| (1..=8).contains(o)).unwrap_or(1);
Ok(Some((area_average_srgb8(px, w, h, ch, tw, th), orientation)))
}
/// Source pixels and weights each output pixel along one axis covers: a box of the scale's width
/// (`n` source pixels onto `out`), partly covered pixels at its ends weighted by their share.
fn box_taps(n: usize, out: usize) -> Vec<(usize, Vec<f32>)> {
let scale = n as f64 / out as f64;
(0..out)
.map(|o| {
let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n as f64));
let first = (a.floor() as usize).min(n - 1);
let last = ((b.ceil() as usize).max(first + 1)).min(n);
let ws: Vec<f32> =
(first..last).map(|j| ((b.min(j as f64 + 1.0) - a.max(j as f64)).max(0.0) / (b - a).max(f64::MIN_POSITIVE)) as f32).collect();
(first, ws)
})
.collect()
}
/// `px` (`w × h`, `ch` = 1 or 3 interleaved 8-bit sRGB samples) averaged over boxes in linear
/// light into `tw × th` opaque 8-bit sRGB pixels. A copy when the size doesn't change.
fn area_average_srgb8(px: &[u8], w: usize, h: usize, ch: usize, tw: usize, th: usize) -> lightcraft_raster::Rgba8 {
use lightcraft_color::transfer::{decode_srgb8, encode_srgb8};
let mut out = lightcraft_raster::Rgba8::new(tw, th);
let sample = |x: usize, y: usize, c: usize| px.get((y * w + x) * ch + if ch == 3 { c } else { 0 }).copied().unwrap_or(0);
if (tw, th) == (w, h) {
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
*o = [sample(x, y, 0), sample(x, y, 1), sample(x, y, 2), 255];
}
});
return out;
}
let lut: [f32; 256] = std::array::from_fn(|i| decode_srgb8(i as u8));
let xs = box_taps(w, tw);
let ys = box_taps(h, th);
// one source row filtered across into linear RGB at the output width
let across = |sy: usize, buf: &mut Vec<[f32; 3]>| {
buf.clear();
let Some(src) = px.get(sy * w * ch..(sy + 1) * w * ch) else {
buf.resize(tw, [0.0; 3]);
return;
};
for (x0, wx) in &xs {
let mut a = [0f32; 3];
if let Some(span) = src.get(x0 * ch..(x0 + wx.len()) * ch) {
for (p, &k) in span.chunks_exact(ch).zip(wx) {
match p {
[r, g, b] => {
a[0] += lut[*r as usize] * k;
a[1] += lut[*g as usize] * k;
a[2] += lut[*b as usize] * k;
}
[v] => {
let l = lut[*v as usize] * k;
a = [a[0] + l, a[1] + l, a[2] + l];
}
_ => {}
}
}
}
buf.push(a);
}
};
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
let Some((y0, wy)) = ys.get(y) else { return };
let mut acc = vec![[0f32; 3]; tw];
let mut line = Vec::with_capacity(tw);
for (dy, &k) in wy.iter().enumerate() {
across(y0 + dy, &mut line);
for (a, l) in acc.iter_mut().zip(&line) {
a[0] += l[0] * k;
a[1] += l[1] * k;
a[2] += l[2] * k;
}
}
for (o, a) in row.iter_mut().zip(&acc) {
*o = [encode_srgb8(a[0]), encode_srgb8(a[1]), encode_srgb8(a[2]), 255];
}
});
out
}
#[cfg(test)]
mod srgb8_fit_tests {
use super::*;
fn jpeg(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
let data: Vec<[u8; 4]> = (0..w * h)
.map(|i| {
let [r, g, b] = f(i % w, i / w);
[r, g, b, 255]
})
.collect();
let img = lightcraft_raster::Rgba8 { width: w, height: h, data };
crate::encode_jpeg(&crate::EncodeImage::rgba8(&img), 95, crate::ChromaSubsampling::S420, &crate::EncodeMeta::default()).unwrap()
}
/// The fast path shows what the general decode shows for a plain sRGB JPEG, at the same size.
#[test]
fn matches_the_general_decode_within_a_few_levels() {
let b = jpeg(1203, 801, |x, y| [((x * 7) ^ (y * 3)) as u8, (x / 5 + y / 3) as u8, ((x * y) % 251) as u8]);
for (mw, mh) in [(300u32, 300u32), (640, 640), (1203, 801), (5000, 5000), (500, 120)] {
let (fast, o) = srgb8_fit(&b, mw, mh).unwrap().unwrap();
let slow = crate::decode(&b, DecodeOptions::fit(mw, mh)).unwrap().to_srgb8();
assert_eq!((fast.width, fast.height), (slow.width, slow.height), "box {mw}×{mh}");
assert_eq!(o, 1);
let diff: Vec<u32> =
fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect();
let mean = diff.iter().sum::<u32>() as f64 / diff.len() as f64;
assert!(mean < 3.0, "box {mw}×{mh}: mean difference {mean}");
}
}
/// Anything but plain 8-bit sRGB goes the general way; junk is an error or `None`, never a panic.
#[test]
fn declines_what_it_does_not_cover_and_never_panics() {
let b = jpeg(64, 48, |x, _| [x as u8, 0, 0]);
assert!(srgb8_fit(&b, 0, 10).unwrap().is_none());
assert!(srgb8_fit(b"not a jpeg", 10, 10).unwrap().is_none());
for cut in [0, 2, 20, b.len() / 2, b.len() - 3] {
let _ = srgb8_fit(&b[..cut], 32, 32);
}
// a 1-pixel-wide image into a box much smaller in one axis
let thin = jpeg(1, 300, |_, y| [y as u8, y as u8, y as u8]);
let (img, _) = srgb8_fit(&thin, 10, 10).unwrap().unwrap();
assert_eq!((img.width, img.height), (1, 10));
}
/// An incomplete ICC_PROFILE sequence (chunk 1 of 2) is "has a profile we can't read", not
/// "plain sRGB": the general decode handles it, as the doc says (CodeRabbit on #3577).
#[test]
fn an_incomplete_icc_sequence_goes_the_general_way() {
let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]);
let mut seg = vec![0xFF, 0xE2, 0, 0];
seg.extend_from_slice(b"ICC_PROFILE");
seg.extend_from_slice(&[1, 2]);
seg.extend_from_slice(&[0u8; 64]);
let len = u16::try_from(seg.len() - 2).unwrap();
seg[2..4].copy_from_slice(&len.to_be_bytes());
let mut with = b[..2].to_vec();
with.extend_from_slice(&seg);
with.extend_from_slice(&b[2..]);
assert!(parse_markers(&with).unwrap().icc_invalid);
assert!(srgb8_fit(&b, 8, 8).unwrap().is_some());
assert!(srgb8_fit(&with, 8, 8).unwrap().is_none());
}
/// The 8-bit path refuses an APP1 flood before its decoders walk it again, as the general one does.
#[test]
fn an_app1_flood_is_refused_by_the_8_bit_path_too() {
let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]);
let mut flood = b[..2].to_vec();
for _ in 0..200 {
flood.extend_from_slice(&[0xFF, 0xE1, 0x00, 0x02]);
}
flood.extend_from_slice(&b[2..]);
match srgb8_fit(&flood, 8, 8) {
Err(Error::Malformed(_, m)) => assert!(m.contains("APP1"), "{m}"),
other => panic!("unexpected: {other:?}"),
}
}
}
+16
View File
@@ -169,6 +169,21 @@ pub fn decode(bytes: &[u8], opts: DecodeOptions) -> Result<Decoded> {
std::panic::catch_unwind(|| decode_unguarded(bytes, format, &opts)).unwrap_or_else(|_| Err(Error::Malformed(format, "decoder panicked".into())))
}
/// A JPEG for display, fast: fitted within `max_w × max_h` (never enlarged) as 8-bit sRGB with its
/// EXIF orientation (1..=8, not applied), the picture `decode(bytes, DecodeOptions::fit(..))
/// .to_srgb8()` gives within a few levels, in about half the time for a large camera preview.
/// `Ok(None)` when the file is not a plain 8-bit sRGB JPEG (an ICC profile or an Adobe RGB EXIF
/// hint, CMYK, 12-bit, lossless or arithmetic coding) or its headers can't be read: use
/// [`decode`], which reports a malformed header as an error. Bad scan data is an error here, and
/// nothing is ever a panic.
pub fn decode_jpeg_srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(lightcraft_raster::Rgba8, u16)>> {
if sniff(bytes) != Some(Format::Jpeg) {
return Ok(None);
}
std::panic::catch_unwind(|| jpeg::srgb8_fit(bytes, max_w, max_h))
.unwrap_or_else(|_| Err(Error::Malformed(Format::Jpeg, "decoder panicked".into())))
}
/// What a file's headers say about its image: enough to catalogue it without decoding pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
@@ -207,6 +222,7 @@ pub fn read_header_unguarded(bytes: &[u8], format: Format) -> Result<Header> {
Format::WebP => webp::header(bytes)?,
Format::Psd => psd::header(bytes)?,
Format::Heif => heif::header(bytes)?,
Format::Gif | Format::Bmp => other::header(bytes, format)?,
// rare here (or, for JPEG XL, without a header reader yet): a small decode, as before
_ => {
let d = decode_unguarded(bytes, format, &DecodeOptions::fit(64, 64))?;
+333 -1
View File
@@ -4,6 +4,291 @@ use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::{DecodeOptions, Decoded, Error, Format, Result};
use image::{DynamicImage, ImageDecoder};
/// Canvases up to this many pixels are still decoded by [`header`] (at most 16 MB), so a truncated
/// small file is refused at import as before.
const HEADER_DECODE_MAX_PIXELS: u64 = 4_000_000;
/// Stored size for the import probe (issue #2553). The probe used to decode these in full, and a
/// few-dozen-byte file declaring a gigapixel canvas allocated gigabytes. The size now comes from the
/// header and must be one the file's bytes can fill; only a canvas small enough to be cheap is
/// decoded (to catch truncation). Orientation is always 1: neither format carries EXIF here.
pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> {
let err = |e: image::ImageError| Error::Malformed(format, e.to_string());
let cursor = std::io::Cursor::new(bytes);
let (w, h) = match format {
Format::Gif => image::codecs::gif::GifDecoder::new(cursor).map_err(err)?.dimensions(),
Format::Bmp => image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?.dimensions(),
_ => return Err(Error::Unsupported(format, "not handled by this decoder")),
};
if w == 0 || h == 0 {
return Err(Error::Malformed(format, "zero dimension".into()));
}
check_fillable(format, bytes, w, h)?;
if u64::from(w).saturating_mul(u64::from(h)) <= HEADER_DECODE_MAX_PIXELS {
let d = decode(bytes, format, &DecodeOptions::fit(64, 64))?;
return Ok((d.source_width, d.source_height, d.orientation));
}
Ok((w, h, 1))
}
/// The decoder's allocation limit: the RGBA buffer of the largest image `opts` allows. It bounds the
/// decoders' own frame buffers only: `DynamicImage::from_decoder` allocates the canvas without
/// consulting it, so the canvas is bounded by `check_size` and [`check_fillable`] beforehand (a
/// mostly blank one by [`SPARSE_MAX_PIXELS`]).
fn limits(opts: &DecodeOptions) -> image::Limits {
let mut l = image::Limits::default();
l.max_alloc = Some(opts.max_pixels.saturating_mul(4));
l
}
/// The largest canvas allowed that the file's pixel data leaves mostly blank: a GIF screen its
/// first frame's codes don't cover, or an RLE BMP whose runs don't. Its decode still allocates the
/// whole canvas (16 MB at this size), so it is held well below `max_pixels`.
const SPARSE_MAX_PIXELS: u64 = 4_000_000;
/// Refuses a canvas larger than the file's pixel data can describe, before the decoder allocates it
/// (issue #2553). Coverage is measured from the pixel data itself, never from the file's length, so
/// padding (comments, bytes after an end code, trailing bytes) covers nothing:
///
/// - Uncompressed BMP rows are read in full, padding included, from the offset the file header
/// gives, so the data must hold every row: anything shorter fails to decode once the canvas is
/// allocated, and is refused here instead.
/// - An RLE BMP covers the pixels its runs and absolute blocks draw, as the decoder paints them; an
/// end-of-row, end-of-bitmap or delta code leaves the rest blank.
/// - A GIF covers the pixels its first frame's LZW codes draw up to the end code. A code expands to
/// at most 4096 pixels and takes 12 bits once the table holds that many (fewer bits only while its
/// strings are shorter), so a frame larger than 2731 pixels per byte of LZW data is refused
/// outright. The screen around the frame may be larger, and is blank there.
///
/// Canvases the data leaves mostly blank are limited to [`SPARSE_MAX_PIXELS`].
fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> {
let area = |w: u32, h: u32| u64::from(w).saturating_mul(u64::from(h));
let canvas = area(w, h);
// the pixels the file's data can cover
let covered = match format {
Format::Gif => {
// without a frame there is nothing to decode, and nothing to bound the canvas by
let Some(frame) = gif_first_frame(bytes) else {
return Err(Error::Malformed(format, "no readable first frame".into()));
};
let (fw, fh, len) = (frame.width, frame.height, frame.data_len);
if area(fw, fh) > (len as u64).saturating_mul(2_731) {
return Err(Error::Malformed(format, format!("a {fw} × {fh} frame is far larger than its {len} bytes of pixel data can hold")));
}
gif_frame_pixels(bytes, frame.codes, area(fw, fh))
}
_ => match bmp_layout(bytes) {
BmpLayout::Rle { offset, rle4 } => bmp_rle_pixels(bytes, offset, rle4, w, h),
BmpLayout::Rows { offset, bits } => {
let row = u64::from(w).saturating_mul(u64::from(bits)).div_ceil(32).saturating_mul(4);
let needed = row.saturating_mul(u64::from(h));
let held = bytes.len().saturating_sub(offset) as u64;
if held < needed {
return Err(Error::Malformed(
format,
format!("a {w} × {h} canvas is larger than its {held} bytes of pixel data can hold ({needed} needed)"),
));
}
canvas
}
},
};
if canvas > covered && canvas > SPARSE_MAX_PIXELS {
return Err(Error::Malformed(
format,
format!(
"a {w} × {h} canvas is mostly blank (its pixel data covers at most {covered} pixels), and such pictures are limited to {SPARSE_MAX_PIXELS} pixels"
),
));
}
Ok(())
}
/// Where a BMP's pixels start (the offset in its file header, which the decoder seeks to) and how
/// they are stored.
enum BmpLayout {
/// RLE8 or RLE4 commands.
Rle { offset: usize, rle4: bool },
/// Rows of `bits` per pixel, each padded to 4 bytes.
Rows { offset: usize, bits: u16 },
}
/// The layout the decoder reads, from the file header and the bitmap header: a 12-byte core header
/// (bits per pixel at 24, never compressed) or a 40-byte or larger one (bits at 28, compression at
/// 30). Fields the decoder would have refused are read as 1 bit per pixel at offset 0, the most
/// lenient layout.
fn bmp_layout(bytes: &[u8]) -> BmpLayout {
let u16_at = |i: usize| bytes.get(i..i.checked_add(2)?).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let u32_at = |i: usize| bytes.get(i..i.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
let offset = u32_at(10).and_then(|o| usize::try_from(o).ok()).unwrap_or(0);
let (bits, compression) = match u32_at(14) {
Some(12) => (u16_at(24), Some(0)),
_ => (u16_at(28), u32_at(30)),
};
match compression {
Some(1) => BmpLayout::Rle { offset, rle4: false },
Some(2) => BmpLayout::Rle { offset, rle4: true },
_ => BmpLayout::Rows { offset, bits: bits.filter(|&b| b > 0).unwrap_or(1) },
}
}
/// The pixels an RLE8 or RLE4 BMP's commands draw on a `w` × `h` canvas, read the way the decoder
/// paints them: a run is clipped at the end of its row, an end-of-row code moves to the next row, a
/// delta skips pixels (left blank), and an end-of-bitmap code, a truncated command or the last row
/// ends the picture. Every command takes at least 2 bytes, so the walk is linear in the file.
fn bmp_rle_pixels(bytes: &[u8], offset: usize, rle4: bool, w: u32, h: u32) -> u64 {
let (w, h) = (u64::from(w), u64::from(h));
let (mut pos, mut x, mut y, mut covered) = (offset, 0u64, 0u64, 0u64);
while y < h {
let (Some(&count), Some(&value)) = (bytes.get(pos), bytes.get(pos.saturating_add(1))) else {
break;
};
pos = pos.saturating_add(2);
match (count, value) {
// end of row
(0, 0) => (x, y) = (0, y.saturating_add(1)),
// end of bitmap
(0, 1) => break,
// delta: right and down
(0, 2) => {
let (Some(&dx), Some(&dy)) = (bytes.get(pos), bytes.get(pos.saturating_add(1))) else {
break;
};
pos = pos.saturating_add(2);
(x, y) = (x.saturating_add(u64::from(dx)), y.saturating_add(u64::from(dy)));
}
// absolute: `value` pixels stored one per byte (RLE8) or nibble (RLE4), padded to 2 bytes
(0, n) => {
let len = if rle4 { usize::from(n).div_ceil(2) } else { usize::from(n) };
pos = pos.saturating_add(len + (len & 1));
if pos > bytes.len() {
break;
}
covered = covered.saturating_add(u64::from(n).min(w.saturating_sub(x)));
x = x.saturating_add(u64::from(n));
}
// a run of `count` pixels
(n, _) => {
covered = covered.saturating_add(u64::from(n).min(w.saturating_sub(x)));
x = x.saturating_add(u64::from(n));
}
}
}
covered
}
/// A GIF's first frame, from its image descriptor.
struct GifFrame {
width: u32,
height: u32,
/// Bytes of LZW data present (its palettes, comments and other extensions describe no pixels).
data_len: usize,
/// Position of its LZW minimum code size, which its data sub-blocks follow.
codes: usize,
}
/// A GIF's first frame. `None` when the blocks before the frame can't be walked.
fn gif_first_frame(bytes: &[u8]) -> Option<GifFrame> {
let u16_at = |i: usize| bytes.get(i..i.checked_add(2)?).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 };
let mut pos = 13 + table(*bytes.get(10)?);
loop {
match *bytes.get(pos)? {
// extension: introducer, label, sub-blocks
0x21 => pos = sub_blocks(bytes, pos.saturating_add(2)).1,
// image descriptor (separator, left, top, width, height, flags), local colour table,
// LZW minimum code size, data sub-blocks
0x2C => {
let (fw, fh) = (u16_at(pos.saturating_add(5))?, u16_at(pos.saturating_add(7))?);
let codes = pos.saturating_add(10).saturating_add(table(*bytes.get(pos.saturating_add(9))?));
let data_len = sub_blocks(bytes, codes.saturating_add(1)).0;
return Some(GifFrame { width: u32::from(fw), height: u32::from(fh), data_len, codes });
}
_ => return None,
}
}
}
/// The pixels a GIF frame's LZW codes draw, at most `max` (the frame's size): the codes are walked
/// up to the end code, an invalid code or the end of the data, keeping only the length of each
/// table string, never the pixels. Data after the end code draws nothing. Codes are packed
/// least-significant bit first across the data sub-blocks and start one bit wider than the minimum
/// code size; a code is one bit wider each time the table fills its width, up to 12 bits, and a
/// clear code starts the table again (GIF89a, appendix F).
fn gif_frame_pixels(bytes: &[u8], codes: usize, max: u64) -> u64 {
// the `gif` decoder accepts minimum code sizes of 1 to 11
let Some(min_size) = bytes.get(codes).copied().filter(|s| (1..=11).contains(s)) else {
return 0;
};
let clear = 1usize << min_size;
let end = clear + 1;
let mut lens = [1u16; 4096]; // string length of each code; literals (below `clear`) are 1
let (mut width, mut next, mut prev) = (u32::from(min_size) + 1, end + 1, None::<usize>);
let (mut bits, mut held, mut covered) = (0u32, 0u32, 0u64);
let mut pos = codes.saturating_add(1);
while let Some(&n) = bytes.get(pos) {
let start = pos.saturating_add(1);
pos = start.saturating_add(usize::from(n));
if n == 0 {
break;
}
for &byte in bytes.get(start..pos.min(bytes.len())).unwrap_or_default() {
bits |= u32::from(byte) << held;
held += 8;
while held >= width {
let code = (bits & ((1 << width) - 1)) as usize;
bits >>= width;
held -= width;
if code == clear {
(width, next, prev) = (u32::from(min_size) + 1, end + 1, None);
continue;
}
let len_of = |c: usize| lens.get(c).copied().unwrap_or(1);
let len = match prev {
_ if code == end => return covered,
None if code < clear => 1,
Some(_) if code < next => len_of(code),
// the string just being defined: the previous one and its first pixel
Some(p) if code == next => len_of(p).saturating_add(1),
_ => return covered,
};
// each code after the first defines the next string: the previous one and a pixel
let defined = prev.map(|p| len_of(p).saturating_add(1));
if let Some(defined) = defined
&& let Some(slot) = lens.get_mut(next)
{
*slot = defined;
next += 1;
if next == 1 << width && width < 12 {
width += 1;
}
}
prev = Some(code);
covered = covered.saturating_add(u64::from(len));
if covered >= max {
return max;
}
}
}
}
covered
}
/// The GIF sub-blocks starting at `pos`: the data bytes present, and the position after them.
fn sub_blocks(bytes: &[u8], mut pos: usize) -> (usize, usize) {
let mut data = 0usize;
while let Some(&n) = bytes.get(pos) {
let start = pos.saturating_add(1);
if n == 0 {
return (data, start);
}
let end = start.saturating_add(usize::from(n));
data = data.saturating_add(end.min(bytes.len()).saturating_sub(start));
pos = end;
}
(data, pos)
}
pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Result<Decoded> {
if format == Format::Gif {
gated_first_frame(bytes, opts)?;
@@ -15,6 +300,8 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu
let mut d = image::codecs::gif::GifDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
@@ -22,6 +309,8 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu
let mut d = image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
@@ -88,7 +377,7 @@ fn gated_first_frame(bytes: &[u8], opts: &DecodeOptions) -> Result<()> {
#[cfg(test)]
mod tests {
use crate::{DecodeOptions, Error};
use super::*;
fn gif(blocks: &[u8]) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
@@ -118,4 +407,47 @@ mod tests {
let r = crate::decode(&bytes, DecodeOptions::default());
assert!(matches!(r, Err(Error::Malformed(..)) | Err(Error::TooLarge(..))), "{r:?}");
}
/// A GIF whose blocks can't be walked to a first frame (here a comment that runs to the end of the
/// file) is refused, instead of the whole file being counted as pixel data for its 400 MP screen.
/// The `image` decoder also stops at such a file when it opens it, but the canvas bound doesn't
/// rely on the two walks agreeing.
#[test]
fn a_gif_with_no_readable_first_frame_is_refused() {
let mut b = b"GIF89a".to_vec();
b.extend(20_000u16.to_le_bytes());
b.extend(20_000u16.to_le_bytes());
b.extend([0, 0, 0, 0x21, 0xFE]);
for _ in 0..600 {
b.push(255);
b.extend([b'x'; 255]);
}
let r = check_fillable(Format::Gif, &b, 20_000, 20_000);
assert!(matches!(&r, Err(Error::Malformed(_, m)) if m.contains("no readable first frame")), "{r:?}");
}
/// The LZW walk counts exactly the pixels an encoder wrote up to its end code: a frame of one
/// colour (long strings, the smallest codes), a 256-colour gradient and noise (a table that fills
/// up and is cleared again).
#[test]
fn the_lzw_walk_counts_every_pixel_an_encoder_wrote() {
let (w, h) = (640u32, 480u32);
let mut seed = 2_553u32;
let mut noise = move || {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 24) as u8
};
let frames = [
("solid", image::RgbaImage::from_pixel(w, h, image::Rgba([90, 90, 90, 255]))),
("gradient", image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x / 40 * 16) as u8, (y / 30 * 16) as u8, 0, 255]))),
("noise", image::RgbaImage::from_fn(w, h, |_, _| image::Rgba([noise(), noise(), noise(), 255]))),
];
for (name, frame) in frames {
let mut gif = Vec::new();
image::codecs::gif::GifEncoder::new_with_speed(&mut gif, 30).encode_frame(image::Frame::new(frame)).unwrap();
let first = gif_first_frame(&gif).unwrap();
assert_eq!((first.width, first.height), (w, h), "{name}");
assert_eq!(gif_frame_pixels(&gif, first.codes, u64::MAX), u64::from(w * h), "{name}");
}
}
}
+206
View File
@@ -74,6 +74,212 @@ fn thumbnail_rejects_huge_gif_before_allocating_source_pixels() {
assert!(matches!(result, Err(Error::TooLarge(42_127, 16_304))), "{result:?}");
}
/// A GIF of a few dozen bytes: a `w` × `h` logical screen and one empty frame of that size.
fn tiny_gif(w: u16, h: u16) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend([0, 0, 0, b',', 0, 0, 0, 0]);
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend([0, 2, 0, b';']);
b
}
/// A 54-byte uncompressed 24-bit BMP header declaring `w` × `h` and no pixel data.
fn tiny_bmp(w: i32, h: i32) -> Vec<u8> {
let mut b = b"BM".to_vec();
b.extend(54u32.to_le_bytes());
b.extend(0u32.to_le_bytes());
b.extend(54u32.to_le_bytes());
b.extend(40u32.to_le_bytes());
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend(1u16.to_le_bytes());
b.extend(24u16.to_le_bytes());
b.extend([0u8; 24]);
b
}
/// Issue #2553: the import probe had no header reader for GIF or BMP and decoded them in full, so
/// a tiny file declaring a canvas just under the 1-gigapixel limit allocated ~4.3 GB (an abort, not
/// an error, when it failed). Both the probe and a decode now refuse a canvas the file's bytes
/// can't fill, before the decoder allocates it.
#[test]
fn tiny_gif_and_bmp_declaring_a_gigapixel_canvas_are_refused_before_allocating() {
for (name, bytes) in [("gif", tiny_gif(32_767, 32_767)), ("bmp", tiny_bmp(32_000, 32_000))] {
assert!(bytes.len() < 64, "{name}: {} bytes", bytes.len());
let header = read_header(&bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{name}: {header:?}");
let decoded = decode(&bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{name}: {:?}", decoded.err());
}
}
/// Above 4 MP the probe reads GIF and BMP sizes from the header without decoding; the size agrees
/// with a full decode.
#[test]
fn large_gif_and_bmp_sizes_come_from_the_header() {
let (w, h) = (2_100u32, 2_000u32);
let rgb = vec![90u8; (w * h * 3) as usize];
let mut bmp = Vec::new();
image::codecs::bmp::BmpEncoder::new(&mut bmp).encode(&rgb, w, h, image::ExtendedColorType::Rgb8).unwrap();
let mut gif = Vec::new();
let frame = image::RgbaImage::from_pixel(w, h, image::Rgba([90, 90, 90, 255]));
image::codecs::gif::GifEncoder::new(&mut gif).encode_frame(image::Frame::new(frame)).unwrap();
for (name, bytes) in [("bmp", bmp), ("gif", gif)] {
let header = read_header(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!((header.width, header.height, header.orientation), (w, h, 1), "{name}");
let d = decode(&bytes, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (w, h), "{name}");
}
}
/// A 64-byte RLE8 BMP declaring `w` × `h` whose pixels are one end-of-bitmap code: all blank.
fn rle_bmp_ending_at_once(w: i32, h: i32) -> Vec<u8> {
let mut b = b"BM".to_vec();
b.extend(64u32.to_le_bytes()); // file size
b.extend(0u32.to_le_bytes());
b.extend(62u32.to_le_bytes()); // pixel data offset: 14 + 40 + 2 palette entries
b.extend(40u32.to_le_bytes());
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend(1u16.to_le_bytes());
b.extend(8u16.to_le_bytes());
b.extend(1u32.to_le_bytes()); // BI_RLE8
b.extend(2u32.to_le_bytes()); // pixel data size
b.extend([0u8; 8]);
b.extend(2u32.to_le_bytes()); // colours used
b.extend(0u32.to_le_bytes());
b.extend([0, 0, 0, 0, 255, 255, 255, 0]);
b.extend([0, 1]); // end of bitmap
assert_eq!(b.len(), 64);
b
}
/// An RLE8 BMP may end its pixels with an end-of-bitmap code that leaves the rest blank, so a file
/// of a few dozen bytes is a valid picture: up to 4 MP it opens, at its declared size.
#[test]
fn an_rle_bmp_that_ends_early_still_opens() {
let (w, h) = (2_000i32, 2_000i32);
let b = rle_bmp_ending_at_once(w, h);
let header = read_header(&b).unwrap();
assert_eq!((header.width, header.height), (w as u32, h as u32));
let d = decode(&b, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (w as u32, h as u32));
}
/// A mostly blank canvas still costs its full size to decode, so a tiny RLE BMP can't claim a
/// gigapixel one: canvases the file's runs can't cover are limited to 4 MP, refused before the
/// decoder allocates them.
#[test]
fn a_tiny_rle_bmp_declaring_a_gigapixel_canvas_is_refused_before_allocating() {
for (w, h) in [(2_001, 2_000), (32_000, 32_000)] {
let b = rle_bmp_ending_at_once(w, h);
let header = read_header(&b);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{w} × {h}: {header:?}");
let decoded = decode(&b, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{w} × {h}: {:?}", decoded.err());
}
}
/// A `sw` × `sh` GIF screen whose first frame is one pixel (black, from a 2-colour palette).
fn gif_with_one_pixel_frame(sw: u16, sh: u16) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
b.extend(sw.to_le_bytes());
b.extend(sh.to_le_bytes());
b.extend([0x80, 0, 0]); // global colour table of 2 entries
b.extend([0, 0, 0, 255, 255, 255]);
b.extend([b',', 0, 0, 0, 0, 1, 0, 1, 0, 0]); // a 1 × 1 frame at the origin
b.extend([2, 2, 0x44, 0x01, 0]); // LZW: clear, index 0, end
b.push(b';');
b
}
/// Density is judged on the first frame's own size, not the screen's: a valid GIF with a small first
/// frame on a larger screen opens, at the screen's size (up to 4 MP, as for other mostly blank
/// canvases).
#[test]
fn a_gif_with_a_small_first_frame_on_a_larger_screen_opens() {
let b = gif_with_one_pixel_frame(2_000, 2_000);
let header = read_header(&b).unwrap();
assert_eq!((header.width, header.height), (2_000, 2_000));
let d = decode(&b, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (2_000, 2_000));
}
#[test]
fn a_gif_whose_one_pixel_frame_sits_on_a_gigapixel_screen_is_refused_before_allocating() {
let b = gif_with_one_pixel_frame(32_767, 32_767);
let header = read_header(&b);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{header:?}");
let decoded = decode(&b, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{:?}", decoded.err());
}
/// A GIF's comments and other extensions describe no pixels, so padding a tiny GIF with 100 KB of
/// comment doesn't let it claim a gigapixel canvas: only the frame's LZW data counts.
#[test]
fn a_gif_padded_with_comments_still_cannot_claim_a_gigapixel_canvas() {
let mut bytes = tiny_gif(32_767, 32_767);
let mut comment = vec![0x21, 0xFE];
for _ in 0..400 {
comment.push(255);
comment.extend([b'x'; 255]);
}
comment.push(0);
bytes.splice(13..13, comment);
assert!(bytes.len() > 100_000);
let header = read_header(&bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{header:?}");
let decoded = decode(&bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{:?}", decoded.err());
}
/// Padding is not pixel data: coverage comes from what the pixel data draws, not from the file's
/// length. Each file here is padded past what the old length-based bounds (8 pixels per byte for
/// uncompressed BMP, 128 for RLE, 2731 per LZW byte for a GIF frame) needed to accept its 9 MP
/// canvas, and each draws far less, so each is refused before the decoder allocates the canvas.
#[test]
fn files_padded_with_junk_cannot_claim_a_canvas_their_pixel_data_doesnt_draw() {
let refused = |name: &str, bytes: &[u8], why: &str| {
let header = read_header(bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains(why)), "{name}: {header:?}");
let decoded = decode(bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains(why)), "{name}: {:?}", decoded.err());
};
// a 24-bit BMP needs 3 bytes a pixel (27 MB here); 1.2 MB of zeros used to pass as 8 pixels a byte
let mut bmp = tiny_bmp(3_000, 3_000);
bmp.resize(bmp.len() + 1_200_000, 0);
refused("uncompressed bmp", &bmp, "can hold");
// an RLE BMP's picture ends at its end-of-bitmap code; 100 KB of runs after it draw nothing
let mut rle = rle_bmp_ending_at_once(3_000, 3_000);
rle.extend([255, 1].repeat(50_000));
refused("rle bmp padded after its end", &rle, "mostly blank");
// runs that never end their row are clipped to it: 100 KB of them draw one 3000-pixel row
let mut rle = rle_bmp_ending_at_once(3_000, 3_000);
rle.truncate(rle.len() - 2);
rle.extend([255, 1].repeat(50_000));
refused("rle bmp padded within one row", &rle, "mostly blank");
// a GIF frame's picture ends at its LZW end code; 4 KB of data sub-blocks after it draw nothing
let mut gif = b"GIF89a".to_vec();
gif.extend(3_000u16.to_le_bytes());
gif.extend(3_000u16.to_le_bytes());
gif.extend([0x80, 0, 0, 0, 0, 0, 255, 255, 255]); // 2-colour global table
gif.extend([b',', 0, 0, 0, 0]);
gif.extend(3_000u16.to_le_bytes());
gif.extend(3_000u16.to_le_bytes());
gif.extend([0, 2]); // no local table; LZW minimum code size 2
gif.extend([255, 0x2C]); // a full sub-block: 3-bit clear (4) then end (5), then padding
gif.extend([0xFF; 254]);
for _ in 0..15 {
gif.push(255);
gif.extend([0xFF; 255]);
}
gif.extend([0, b';']);
refused("gif padded after its end code", &gif, "mostly blank");
}
#[test]
fn thumbnail_respects_configured_source_pixel_limit() {
let image = Rgba8::from_fn(3, 2, |_, _| [40, 80, 120, 255]);
+70
View File
@@ -160,6 +160,76 @@ fn truncation_details() {
assert!(read_header(&png[..png.len() - 12]).is_err(), "nothing after the image data: truncated");
}
/// A Samsung SEF trailer as the end of `image`: one `Panorama_Shot_Info` data block, then the
/// `SEFH` directory with one entry (type 0x08E0) whose offset counts back from `SEFH` by `back`,
/// the directory's length and `SEFT`.
fn with_sef_trailer(image: &[u8], back: u32, magic: &[u8; 4]) -> Vec<u8> {
// marker-like bytes: both decoders refuse them as a second frame header after the scan
sef_file(image, back, magic, 0x08E0, &[0xFF, 0xC0, 0, 0x11, 0xFF, 0xDA, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], None)
}
/// [`with_sef_trailer`] with the entry's type, the block's data after its name, and the length
/// the entry gives (`None`: the block's own).
fn sef_file(image: &[u8], back: u32, magic: &[u8; 4], kind: u16, data: &[u8], len: Option<u32>) -> Vec<u8> {
let mut b = image.to_vec();
let mut block = vec![0, 0, 0xE0, 0x08];
block.extend_from_slice(&18u32.to_le_bytes());
block.extend_from_slice(b"Panorama_Shot_Info");
block.extend_from_slice(data);
b.extend_from_slice(&block);
let mut dir = magic.to_vec();
dir.extend_from_slice(&106u32.to_le_bytes());
dir.extend_from_slice(&1u32.to_le_bytes());
dir.extend_from_slice(&[0, 0]);
dir.extend_from_slice(&kind.to_le_bytes());
dir.extend_from_slice(&back.to_le_bytes());
dir.extend_from_slice(&len.unwrap_or(block.len() as u32).to_le_bytes());
let len = dir.len() as u32;
b.extend_from_slice(&dir);
b.extend_from_slice(&len.to_le_bytes());
b.extend_from_slice(b"SEFT");
b
}
/// Issue #3350: a Samsung panorama has no EOI; its scan data runs into the SEF trailer. It reads
/// and decodes (both decoders: zune-jpeg in full, jpeg-decoder DCT-scaled) as the image before the
/// trailer, and a file cut short with no trailer, or with a broken one, is still truncated.
#[test]
fn samsung_sef_trailer_without_eoi() {
let jpeg = fixtures(160, 96).into_iter().find(|x| x.0 == "jpeg 420 o6").map(|x| x.1).unwrap();
let scan = &jpeg[..jpeg.len() - 2];
let block = 4 + 4 + 18 + 18;
let pano = with_sef_trailer(scan, block, b"SEFH");
let header = read_header(&pano).unwrap();
assert_eq!((header.width, header.height, header.orientation), (160, 96, 6));
let full = decode(&pano, DecodeOptions::default()).unwrap();
assert_eq!((full.source_width, full.source_height), (160, 96));
let reference = decode(&jpeg, DecodeOptions::default()).unwrap();
assert_eq!(full.image.data, reference.image.data, "the same pixels as the file with its EOI");
let small = decode(&pano, DecodeOptions::fit(32, 32)).unwrap();
assert_eq!((small.source_width, small.source_height), (160, 96));
// the fast display decode too, scaled (where the trailer after the scan used to fail it)
let (fit, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&pano, 32, 32).unwrap().unwrap();
let (fit_ref, _) = lightcraft_codecs::decode_jpeg_srgb8_fit(&jpeg, 32, 32).unwrap().unwrap();
assert_eq!((fit.width, fit.height, &fit.data), (fit_ref.width, fit_ref.height, &fit_ref.data));
// an FF D9 inside the SEF data is not the image's end
let eoi_in_data = sef_file(scan, block, b"SEFH", 0x08E0, &[0xFF, 0xC0, 0, 0x11, 0xFF, 0xD9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], None);
assert_eq!(read_header(&eoi_in_data).unwrap().width, 160);
let small = decode(&eoi_in_data, DecodeOptions::fit(32, 32)).unwrap();
assert_eq!((small.source_width, small.source_height), (160, 96));
// still truncated: no trailer, offsets outside the file or past `SEFH`, no `SEFH`, an empty
// entry, an entry whose type isn't its block's, a cut before the first scan
assert!(read_header(scan).is_err());
assert!(read_header(&with_sef_trailer(scan, u32::MAX, b"SEFH")).is_err());
assert!(read_header(&with_sef_trailer(scan, block - 1, b"SEFH")).is_err());
assert!(read_header(&with_sef_trailer(scan, block, b"SEFX")).is_err());
assert!(read_header(&sef_file(scan, 0, b"SEFH", 0x08E0, &[], Some(0))).is_err());
assert!(read_header(&sef_file(scan, block, b"SEFH", 0x0A01, &[0; 18], None)).is_err());
let cut_in_headers = with_sef_trailer(&jpeg[..40], block, b"SEFH");
assert!(read_header(&cut_in_headers).is_err());
assert!(decode(&cut_in_headers, DecodeOptions::fit(32, 32)).is_err());
}
/// eXIf after the image data counts, as it does for a decode (which reads the whole file).
#[test]
fn png_exif_after_idat() {
+10 -1
View File
@@ -132,7 +132,9 @@ fn hue_of(c: [f32; 3], max: f32, d: f32) -> f32 {
} else {
(c[0] - c[1]) / d + 4.0
};
h * 60.0
let deg = h * 60.0;
// rem_euclid can round up to exactly 6.0 in f32; keep the range [0, 360).
if deg >= 360.0 { 0.0 } else { deg }
}
#[cfg(test)]
@@ -173,4 +175,11 @@ mod tests {
}
assert_eq!(rgb_to_hsv([0.0, 1.0, 0.0])[0], 120.0);
}
#[test]
fn hue_below_360_for_tiny_blue() {
let c = [1.0, 0.0, 1e-9];
assert!(rgb_to_hsv(c)[0] < 360.0, "hsv hue {}", rgb_to_hsv(c)[0]);
assert!(rgb_to_hsl(c)[0] < 360.0, "hsl hue {}", rgb_to_hsl(c)[0]);
}
}
+32 -3
View File
@@ -56,6 +56,10 @@ impl MonotoneCurve {
}
pub fn eval(&self, x: f64) -> f64 {
// NaN passes both bound checks below and would send the search past either end
if x.is_nan() {
return x;
}
let n = self.xs.len();
if x <= self.xs[0] {
return self.ys[0] + self.ms[0] * (x - self.xs[0]).min(0.0) * 0.0;
@@ -76,8 +80,9 @@ impl MonotoneCurve {
+ (t3 - t2) * h * self.ms[i + 1]
}
/// Sample into a LUT of `n` entries over `0..1`.
/// Sample into a LUT of `n` entries (at least 2) over `0..1`.
pub fn to_lut(&self, n: usize) -> Lut1 {
let n = n.max(2);
Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() }
}
@@ -93,16 +98,24 @@ pub struct Lut1 {
}
impl Lut1 {
/// At least 2 entries, like [`Lut1::from_fn`].
pub fn identity(n: usize) -> Lut1 {
Lut1 { v: (0..n).map(|i| i as f32 / (n - 1) as f32).collect() }
Lut1::from_fn(n, |x| x)
}
/// `f` sampled at `n` evenly spaced points over `0..1` (at least 2).
pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 {
let n = n.max(2);
Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() }
}
/// `v` is public, so a table shorter than 2 entries is read as constant (1) or the identity (0).
#[inline]
pub fn eval(&self, x: f32) -> f32 {
let x = x.clamp(0.0, 1.0);
let n = self.v.len();
let f = x.clamp(0.0, 1.0) * (n - 1) as f32;
if n < 2 {
return self.v.first().copied().unwrap_or(x);
}
let f = x * (n - 1) as f32;
let i = (f as usize).min(n - 2);
let t = f - i as f32;
self.v[i] + (self.v[i + 1] - self.v[i]) * t
@@ -163,6 +176,22 @@ mod tests {
assert!((c.eval(0.3) - 0.3).abs() < 2e-3);
}
#[test]
fn nan_input_and_short_luts_do_not_panic() {
let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]);
assert!(c.eval(f64::NAN).is_nan());
assert!(c.eval(-f64::NAN).is_nan());
for n in [0, 1] {
assert_eq!(c.to_lut(n).v.len(), 2, "{n}");
assert!(Lut1::identity(n).is_identity(), "{n}");
assert_eq!(Lut1::from_fn(n, |x| x).v.len(), 2, "{n}");
}
assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3);
assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0, "inputs outside 0..1 clamp, as for any table");
assert_eq!(Lut1 { v: vec![] }.eval(2.0), 1.0);
assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7);
}
proptest::proptest! {
#[test]
fn monotone_for_increasing_data(ys in proptest::collection::vec(0.0f64..1.0, 3..8)) {
+6
View File
@@ -49,6 +49,7 @@ pub fn hlg_encode(e: f64) -> f64 {
}
pub fn hlg_decode(s: f64) -> f64 {
let s = s.max(0.0);
if s <= 0.5 { s * s / 3.0 } else { (((s - HLG_C) / HLG_A).exp() + HLG_B) / 12.0 }
}
@@ -112,6 +113,11 @@ mod tests {
}
}
#[test]
fn hlg_decode_clamps_negative() {
assert_eq!(hlg_decode(-0.5), 0.0);
}
#[test]
fn pq_hlg_roundtrip() {
for i in 0..=50 {
+601
View File
@@ -0,0 +1,601 @@
//! Block-matching collaborative filtering (after Dabov, Foi, Katkovnik and Egiazarian, "Image denoising by sparse 3-D
//! transform-domain collaborative filtering", 2007; the colour variant is their CBM3D), written from the paper.
//!
//! It works on the same planes as [`crate::nlm`]: four Bayer planes of unit noise (see [`crate::nlm::Stabiliser`]),
//! rotated by a Hadamard transform into a brightness plane and three colour-difference planes. Blocks of the
//! brightness plane that look alike are stacked into a group; the stack is transformed (2-D DCT of each block, Haar
//! across the stack) where the picture is sparse and the noise is not, shrunk, transformed back and put back with
//! weights. The first step shrinks by a hard threshold and gives a basic estimate; the second matches blocks on that
//! cleaner estimate and shrinks by a Wiener filter built from it. Every plane of a group follows the brightness
//! plane's matches, so the colour differences are only averaged across like brightness.
use crate::nlm::hadamard;
use std::f32::consts::FRAC_1_SQRT_2;
/// What the filter may be tuned by (the defaults are what the built-in denoiser uses).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Params {
/// Side of a block, in cells.
pub block: usize,
/// Distance, in cells, between the blocks that start a group (1 = every block; larger is faster).
pub step: usize,
/// How far, in cells, a match is looked for round a block.
pub search: usize,
/// The most blocks in a group (rounded down to a power of two).
pub group: usize,
/// How far above the noise two blocks may differ (mean square, in units of the noise variance) and still be
/// grouped, in the first step (on the noisy picture) and in the second (on the basic estimate).
pub tau1: f32,
pub tau2: f32,
/// The first step's hard-threshold level, in noise deviations, as a function of how noisy the photo is: points of
/// (the noise's deviation at mid-grey, with white = 1; the threshold), rising with the noise and joined in a straight
/// line against the logarithm of the noise (flat beyond the first and last). A quieter photo has more fine detail
/// per unit of noise to keep, a noisier one less. Fitted on real Canon raws with noise added at their ISO levels
/// (docs/denoise.md → Why block matching).
pub lambda: [(f32, f32); 6],
/// The noise's deviation as the filter takes it (1 = as measured; more cleans harder).
pub sigma: f32,
/// Whether the second (Wiener) step runs.
pub wiener: bool,
}
impl Default for Params {
/// What the built-in denoiser runs with: 4 × 4 blocks taken every 3 cells, matched within 8 cells, up to 16 to a
/// group, the fitted threshold curve, and the Wiener step on.
fn default() -> Self {
Params {
block: 4,
step: 3,
search: 8,
group: 16,
tau1: 4.0,
tau2: 1.0,
lambda: [(0.0028, 1.2), (0.0062, 1.9), (0.0094, 2.3), (0.0152, 2.65), (0.038, 3.2), (0.14, 3.5)],
sigma: 1.0,
wiener: true,
}
}
}
/// The threshold for a photo whose noise has deviation `noise` at mid-grey: `curve` read in a straight line against the
/// logarithm of the noise (the ends hold). A curve that is empty or not rising in its first coordinate gives its first
/// point's value for any noise, and a noise that is not a number is the quietest.
pub fn threshold_for(curve: &[(f32, f32)], noise: f32) -> f32 {
let Some(&(x0, y0)) = curve.first() else { return 3.0 };
if !noise.is_finite() || noise <= x0 {
return y0;
}
for pair in curve.windows(2) {
let ((xa, ya), (xb, yb)) = (pair[0], pair[1]);
if xa.is_finite() && xb.is_finite() && xa > 0.0 && xb > xa && noise <= xb {
return ya + (yb - ya) * (noise / xa).ln() / (xb / xa).ln();
}
}
curve.last().map_or(y0, |p| p.1)
}
/// The orthonormal DCT-II of a block and the window the filtered blocks are put back with.
struct Transform {
n: usize,
c: Vec<f32>,
window: Vec<f32>,
}
/// The zeroth-order modified Bessel function of the first kind (a series; the Kaiser window needs it).
fn bessel_i0(x: f32) -> f32 {
let (mut sum, mut term) = (1.0f32, 1.0f32);
for k in 1..30 {
term *= x * x / (4.0 * (k * k) as f32);
sum += term;
}
sum
}
impl Transform {
/// The transform for `n × n` blocks: the DCT-II matrix and the Kaiser window the filtered blocks are put back with.
fn new(n: usize) -> Self {
let mut c = vec![0f32; n * n];
for (k, row) in c.chunks_exact_mut(n).enumerate() {
let scale = if k == 0 { (1.0 / n as f32).sqrt() } else { (2.0 / n as f32).sqrt() };
for (i, v) in row.iter_mut().enumerate() {
*v = scale * (std::f32::consts::PI * (2 * i + 1) as f32 * k as f32 / (2 * n) as f32).cos();
}
}
// a Kaiser window (beta 2) down each side, so a block's edge counts less than its middle
let beta = 2.0f32;
let side: Vec<f32> = (0..n)
.map(|i| {
let r = if n > 1 { 2.0 * i as f32 / (n - 1) as f32 - 1.0 } else { 0.0 };
bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / bessel_i0(beta)
})
.collect();
let window = side.iter().flat_map(|y| side.iter().map(move |x| x * y)).collect();
Transform { n, c, window }
}
/// `blk` (`n × n`) becomes its 2-D DCT.
fn forward(&self, blk: &mut [f32], tmp: &mut [f32]) {
let n = self.n;
for (trow, crow) in tmp.chunks_exact_mut(n).zip(self.c.chunks_exact(n)) {
trow.fill(0.0);
for (&ck, brow) in crow.iter().zip(blk.chunks_exact(n)) {
for (t, &b) in trow.iter_mut().zip(brow) {
*t += ck * b;
}
}
}
for (orow, trow) in blk.chunks_exact_mut(n).zip(tmp.chunks_exact(n)) {
for (o, crow) in orow.iter_mut().zip(self.c.chunks_exact(n)) {
*o = trow.iter().zip(crow).map(|(a, b)| a * b).sum();
}
}
}
/// The inverse of [`Transform::forward`].
fn inverse(&self, blk: &mut [f32], tmp: &mut [f32]) {
let n = self.n;
tmp.fill(0.0);
for (crow, xrow) in self.c.chunks_exact(n).zip(blk.chunks_exact(n)) {
for (trow, &cki) in tmp.chunks_exact_mut(n).zip(crow) {
for (t, &x) in trow.iter_mut().zip(xrow) {
*t += cki * x;
}
}
}
for (brow, trow) in blk.chunks_exact_mut(n).zip(tmp.chunks_exact(n)) {
brow.fill(0.0);
for (&t, crow) in trow.iter().zip(self.c.chunks_exact(n)) {
for (b, &c) in brow.iter_mut().zip(crow) {
*b += t * c;
}
}
}
}
}
/// The orthonormal Haar transform of a vector whose length is a power of two.
fn haar_forward(v: &mut [f32], tmp: &mut [f32]) {
let mut len = v.len();
while len > 1 {
let half = len / 2;
for i in 0..half {
let (a, b) = (v.get(2 * i).copied().unwrap_or(0.0), v.get(2 * i + 1).copied().unwrap_or(0.0));
if let Some(x) = tmp.get_mut(i) {
*x = (a + b) * FRAC_1_SQRT_2;
}
if let Some(x) = tmp.get_mut(half + i) {
*x = (a - b) * FRAC_1_SQRT_2;
}
}
if let (Some(dst), Some(src)) = (v.get_mut(..len), tmp.get(..len)) {
dst.copy_from_slice(src);
}
len = half;
}
}
/// Undoes [`haar_forward`] in place; `tmp` is scratch of the same length.
fn haar_inverse(v: &mut [f32], tmp: &mut [f32]) {
let mut len = 2;
while len <= v.len() {
let half = len / 2;
for i in 0..half {
let (avg, det) = (v.get(i).copied().unwrap_or(0.0), v.get(half + i).copied().unwrap_or(0.0));
if let Some(x) = tmp.get_mut(2 * i) {
*x = (avg + det) * FRAC_1_SQRT_2;
}
if let Some(x) = tmp.get_mut(2 * i + 1) {
*x = (avg - det) * FRAC_1_SQRT_2;
}
}
if let (Some(dst), Some(src)) = (v.get_mut(..len), tmp.get(..len)) {
dst.copy_from_slice(src);
}
len *= 2;
}
}
/// Reusable buffers of the group transforms.
#[derive(Default)]
struct Scratch {
tmp: Vec<f32>,
col: Vec<f32>,
col_tmp: Vec<f32>,
}
/// A group (`m` blocks of `n × n`, one after the other in `buf`) to the transform domain, or back.
fn group_transform(tf: &Transform, buf: &mut [f32], m: usize, s: &mut Scratch, forward: bool) {
let nn = tf.n * tf.n;
s.tmp.resize(nn, 0.0);
if !forward {
haar_columns(buf, m, nn, s, false);
}
for blk in buf.chunks_exact_mut(nn) {
if forward {
tf.forward(blk, &mut s.tmp);
} else {
tf.inverse(blk, &mut s.tmp);
}
}
if forward {
haar_columns(buf, m, nn, s, true);
}
}
/// The Haar transform across the blocks of a group, at each of the `nn` positions of a block.
fn haar_columns(buf: &mut [f32], m: usize, nn: usize, s: &mut Scratch, forward: bool) {
if m < 2 {
return;
}
s.col.resize(m, 0.0);
s.col_tmp.resize(m, 0.0);
for k in 0..nn {
for (i, c) in s.col.iter_mut().enumerate() {
*c = buf.get(i * nn + k).copied().unwrap_or(0.0);
}
if forward {
haar_forward(&mut s.col, &mut s.col_tmp);
} else {
haar_inverse(&mut s.col, &mut s.col_tmp);
}
for (i, c) in s.col.iter().enumerate() {
if let Some(b) = buf.get_mut(i * nn + k) {
*b = *c;
}
}
}
}
/// Copy the blocks of a group out of a plane (`members` are the blocks' top-left cells).
pub(crate) fn gather(plane: &[f32], t: usize, n: usize, members: &[u32], out: &mut Vec<f32>) {
out.clear();
for &pos in members {
for j in 0..n {
let at = pos as usize + j * t;
match plane.get(at..at + n) {
Some(row) => out.extend_from_slice(row),
None => out.extend(std::iter::repeat_n(0.0, n)),
}
}
}
}
/// Where a plane's blocks start along one side: every `step` cells, and the last one too, so the edge is covered.
pub fn starts(blocks: usize, step: usize) -> Vec<usize> {
let mut v: Vec<usize> = (0..blocks).step_by(step.max(1)).collect();
if let Some(last) = blocks.checked_sub(1)
&& v.last() != Some(&last)
{
v.push(last);
}
v
}
/// Insert `(distance, block)` into a list ordered by distance, keeping at most `cap`.
fn insert(list: &mut Vec<(f32, u32)>, cap: usize, d: f32, pos: u32) {
if list.len() >= cap && list.last().is_some_and(|l| d >= l.0) {
return;
}
let at = list.partition_point(|e| e.0 <= d);
list.insert(at, (d, pos));
list.truncate(cap);
}
/// For every block that starts a group, the blocks of `plane` within `search` cells (itself first) whose mean squared
/// difference from it is at most `tau`, nearest first and at most `cap`. Blocks (of `n × n` cells) are named by their
/// top-left cell, and a block starts a group every `step` cells.
pub(crate) fn match_groups(plane: &[f32], t: usize, n: usize, step: usize, search: usize, cap: usize, tau: f32) -> Vec<Vec<u32>> {
let nb = t + 1 - n;
let refs = starts(nb, step);
let nr = refs.len();
let cap = cap.max(1);
let mut lists: Vec<Vec<(f32, u32)>> = Vec::with_capacity(nr * nr);
for &ry in &refs {
for &rx in &refs {
let mut l = Vec::with_capacity(cap + 1);
l.push((0.0, (ry * t + rx) as u32));
lists.push(l);
}
}
let norm = 1.0 / (n * n) as f32;
let r = search as isize;
let (mut d, mut hsum) = (vec![0f32; t * t], vec![0f32; t * nr]);
let valid = |v: usize, o: isize| (v as isize + o) >= 0 && ((v as isize + o) as usize) < nb;
for oy in -r..=r {
for ox in -r..=r {
if ox == 0 && oy == 0 {
continue;
}
// squared differences between the plane and itself shifted by the offset
let (x0, x1) = (0.max(-ox) as usize, (t as isize).min(t as isize - ox) as usize);
for y in 0..t {
let sy = y as isize + oy;
if sy < 0 || sy >= t as isize {
continue;
}
let (Some(a), Some(b), Some(out)) = (
plane.get(y * t + x0..y * t + x1),
plane.get(sy as usize * t + (x0 as isize + ox) as usize..sy as usize * t + (x1 as isize + ox) as usize),
d.get_mut(y * t + x0..y * t + x1),
) else {
continue;
};
for ((o, &a), &b) in out.iter_mut().zip(a).zip(b) {
*o = (a - b) * (a - b);
}
}
// block sums: along rows at the starting columns, then down at the starting rows
for y in 0..t {
for (ri, &rx) in refs.iter().enumerate() {
if !valid(rx, ox) {
continue;
}
let s: f32 = d.get(y * t + rx..y * t + rx + n).map_or(0.0, |v| v.iter().sum());
if let Some(h) = hsum.get_mut(y * nr + ri) {
*h = s;
}
}
}
for (rj, &ry) in refs.iter().enumerate() {
if !valid(ry, oy) {
continue;
}
for (ri, &rx) in refs.iter().enumerate() {
if !valid(rx, ox) {
continue;
}
let s: f32 = (0..n).map(|j| hsum.get((ry + j) * nr + ri).copied().unwrap_or(0.0)).sum::<f32>() * norm;
if s <= tau {
let other = ((ry as isize + oy) as usize * t) as isize + (rx as isize + ox);
if let Some(l) = lists.get_mut(rj * nr + ri) {
insert(l, cap, s, other as u32);
}
}
}
}
}
}
lists.into_iter().map(|l| l.into_iter().map(|(_, pos)| pos).collect()).collect()
}
/// [`match_groups`] with each group cut to a power of two, so the Haar transform across it is complete.
fn match_blocks(plane: &[f32], t: usize, p: &Params, tau: f32) -> Vec<Vec<u32>> {
let mut groups = match_groups(plane, t, p.block, p.step, p.search, p.group, tau);
for g in &mut groups {
let m = if g.is_empty() { 0 } else { 1usize << g.len().ilog2() };
g.truncate(m);
}
groups
}
/// Filter every plane of `y` over the groups: hard threshold when there is no `pilot`, Wiener shrinkage by it when
/// there is.
fn collaborate(y: &[Vec<f32>], pilot: Option<&[Vec<f32>]>, groups: &[Vec<u32>], t: usize, p: &Params, lambda: f32, tf: &Transform) -> Vec<Vec<f32>> {
let n = tf.n;
let sigma = p.sigma.max(1e-3);
let lambda = lambda * sigma;
let mut s = Scratch::default();
let (mut buf, mut pbuf) = (Vec::new(), Vec::new());
let mut out = Vec::with_capacity(y.len());
for plane in y {
let mut num = vec![0f32; t * t];
let mut den = vec![0f32; t * t];
let c = out.len();
let pilot_plane = pilot.and_then(|pl| pl.get(c));
for members in groups {
let m = members.len();
gather(plane, t, n, members, &mut buf);
group_transform(tf, &mut buf, m, &mut s, true);
let weight = match pilot_plane {
None => {
let mut kept = 0usize;
for v in buf.iter_mut() {
if v.abs() < lambda {
*v = 0.0;
} else {
kept += 1;
}
}
1.0 / kept.max(1) as f32
}
Some(pl) => {
gather(pl, t, n, members, &mut pbuf);
group_transform(tf, &mut pbuf, m, &mut s, true);
let mut energy = 0f32;
for (v, &q) in buf.iter_mut().zip(&pbuf) {
let w = q * q / (q * q + sigma * sigma);
*v *= w;
energy += w * w;
}
1.0 / energy.max(1e-3)
}
};
group_transform(tf, &mut buf, m, &mut s, false);
for (&pos, blk) in members.iter().zip(buf.chunks_exact(n * n)) {
for (j, row) in blk.chunks_exact(n).enumerate() {
let at = pos as usize + j * t;
let (Some(nu), Some(de)) = (num.get_mut(at..at + n), den.get_mut(at..at + n)) else { continue };
let win = tf.window.get(j * n..(j + 1) * n).unwrap_or_default();
for (((nu, de), &v), &w) in nu.iter_mut().zip(de.iter_mut()).zip(row).zip(win) {
*nu += weight * w * v;
*de += weight * w;
}
}
}
}
// cells no block reached keep their value
out.push(num.iter().zip(&den).zip(plane).map(|((&nu, &de), &own)| if de > 0.0 { nu / de } else { own }).collect());
}
out
}
/// What a run over tiles of `t` cells uses once the parameters are made safe: shared by every device that runs the filter.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Plan {
pub params: Params,
/// The first step's hard threshold, in noise deviations (before `params.sigma` scales it).
pub lambda: f32,
}
/// The parameters as they are used for tiles of `t` cells and a photo whose noise has deviation `noise` at mid-grey
/// (white = 1; see [`Params::lambda`]), or `None` when the tiles are smaller than a block (they are then left as they
/// are).
pub fn plan(p: &Params, t: usize, noise: f32) -> Option<Plan> {
let n = p.block.clamp(2, 16);
if t < n {
return None;
}
let params = Params { block: n, search: p.search.min(t), group: p.group.clamp(1, 64), ..*p };
Some(Plan { params, lambda: threshold_for(&p.lambda, noise) })
}
/// The block-to-block DCT matrix (`n × n`, row `k` is frequency `k`) and the window (`n × n`) the filtered blocks are put
/// back with: the constants the graphics-card version is given so that both use the very same numbers.
pub fn constants(n: usize) -> (Vec<f32>, Vec<f32>) {
let tf = Transform::new(n.clamp(2, 16));
(tf.c, tf.window)
}
/// Denoise four unit-noise planes of `t × t` cells (see the module description); `noise` is the photo's noise at
/// mid-grey, which sets how hard it cleans (see [`Params::lambda`]).
pub fn filter(planes: &[Vec<f32>], t: usize, p: &Params, noise: f32) -> Vec<Vec<f32>> {
let y = hadamard(planes);
let Some(Plan { params: p, lambda }) = plan(p, t, noise) else { return hadamard(&y) };
if y.len() != 4 || y.iter().any(|pl| pl.len() != t * t) {
return hadamard(&y);
}
let tf = Transform::new(p.block);
let var = p.sigma.max(1e-3).powi(2);
let Some(brightness) = y.first() else { return hadamard(&y) };
let first = match_blocks(brightness, t, &p, p.tau1 * var);
let basic = collaborate(&y, None, &first, t, &p, lambda, &tf);
if !p.wiener {
return hadamard(&basic);
}
let Some(pilot) = basic.first() else { return hadamard(&basic) };
let second = match_blocks(pilot, t, &p, p.tau2 * var);
hadamard(&collaborate(&y, Some(&basic), &second, t, &p, lambda, &tf))
}
#[cfg(test)]
mod tests {
use super::*;
/// The DCT keeps a block's energy, and both it and the Haar transform are undone exactly by their inverses.
#[test]
fn the_dct_and_haar_transforms_invert() {
for n in [2, 4, 8] {
let tf = Transform::new(n);
let block: Vec<f32> = (0..n * n).map(|i| (i as f32 * 0.7).sin() * 3.0).collect();
let (mut b, mut tmp) = (block.clone(), vec![0f32; n * n]);
tf.forward(&mut b, &mut tmp);
let energy = |v: &[f32]| v.iter().map(|x| x * x).sum::<f32>();
assert!((energy(&b) - energy(&block)).abs() < 1e-3, "the DCT keeps energy");
tf.inverse(&mut b, &mut tmp);
assert!(b.iter().zip(&block).all(|(a, c)| (a - c).abs() < 1e-4));
}
for m in [1usize, 2, 4, 16] {
let v: Vec<f32> = (0..m).map(|i| i as f32 * 0.3 - 1.0).collect();
let (mut w, mut tmp) = (v.clone(), vec![0f32; m]);
haar_forward(&mut w, &mut tmp);
assert!((w.iter().map(|x| x * x).sum::<f32>() - v.iter().map(|x| x * x).sum::<f32>()).abs() < 1e-4);
haar_inverse(&mut w, &mut tmp);
assert!(w.iter().zip(&v).all(|(a, c)| (a - c).abs() < 1e-5));
}
}
/// Four planes of unit noise (an LCG and Box-Muller, so the tests need no dependency) round `level`.
fn noisy(t: usize, level: f32, seed: u64) -> Vec<Vec<f32>> {
let mut state = seed;
let mut uniform = move || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32
};
(0..4)
.map(|_| {
(0..t * t)
.map(|_| {
let (u, v) = (uniform(), uniform());
level + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
})
.collect()
})
.collect()
}
/// The deviation of the planes' values around `level`.
fn spread(planes: &[Vec<f32>], level: f32) -> f32 {
let all: Vec<f32> = planes.iter().flatten().copied().collect();
(all.iter().map(|v| (v - level) * (v - level)).sum::<f32>() / all.len().max(1) as f32).sqrt()
}
/// The threshold holds at the ends of the curve, passes through its points and never falls as the noise rises; a
/// noise that is not a number, an empty curve and curves out of order give a value instead of a panic.
#[test]
fn the_threshold_follows_the_noise_and_survives_odd_curves() {
let c = Params::default().lambda;
let at = |n: f32| threshold_for(&c, n);
assert_eq!((at(0.0), at(1.0)), (1.2, 3.5), "the ends hold");
assert!((at(0.0062) - 1.9).abs() < 1e-4 && (at(0.0152) - 2.65).abs() < 1e-4, "the points are on the curve");
let mut last = 0.0;
for i in 0..250 {
let v = at(0.001 * 1.04f32.powi(i));
assert!(v >= last - 1e-6, "the threshold never falls as the noise rises");
last = v;
}
assert_eq!(at(f32::NAN), 1.2, "a noise that is not a number is the quietest");
assert_eq!(threshold_for(&[], 0.1), 3.0);
// curves that are out of order, or with numbers that are not numbers, give some value and never panic
for curve in [vec![(0.0, 1.0), (f32::NAN, 2.0), (0.01, 5.0), (0.005, 4.0)], vec![(0.01, 2.0), (0.01, 3.0)], vec![(-1.0, 2.0), (0.0, 3.0)]] {
for n in [0.0, 0.003, 0.02, 1.0, f32::INFINITY] {
assert!(threshold_for(&curve, n).is_finite() || !curve.iter().all(|p| p.1.is_finite()));
}
}
}
/// Filtering a flat picture of pure noise leaves well under half of the noise's deviation.
#[test]
fn a_flat_noisy_picture_comes_out_much_quieter() {
let t = 48;
let planes = noisy(t, 5.0, 7);
let out = filter(&planes, t, &Params::default(), 0.5);
// the Hadamard transform keeps the level, so what is left of the spread is the noise that got through
assert!(spread(&out, 5.0) < 0.35 * spread(&planes, 5.0), "{} vs {}", spread(&out, 5.0), spread(&planes, 5.0));
assert!(out.iter().flatten().all(|v| v.is_finite()));
}
/// A step edge under noise stays a step: a few cells either side of it the values are still near their two levels.
#[test]
fn a_step_edge_stays_sharp() {
let t = 48;
let mut planes = noisy(t, 0.0, 9);
for pl in &mut planes {
for (i, v) in pl.iter_mut().enumerate() {
if i % t >= t / 2 {
*v += 12.0;
}
}
}
let out = filter(&planes, t, &Params::default(), 0.5);
let row = t / 2;
let at = |x: usize| out.iter().map(|pl| pl.get(row * t + x).copied().unwrap_or(0.0)).sum::<f32>() / 4.0;
assert!(at(t / 2 - 3) < 2.0 && at(t / 2 + 2) > 10.0, "{} {}", at(t / 2 - 3), at(t / 2 + 2));
}
/// Tiny and empty tiles, planes of NaN, a tuning with a zero block, step or group, and no planes at all give finite
/// values or empty planes and never a panic.
#[test]
fn odd_inputs_never_panic() {
// the sizes and values a tile or a caller could hand over
for t in [0usize, 1, 3, 4, 5, 9] {
let planes = noisy(t.max(1), 1.0, 3);
let out = filter(&planes, t, &Params::default(), 0.5);
assert!(out.iter().flatten().all(|v| v.is_finite()));
}
let planes = vec![vec![f32::NAN; 64]; 4];
let _ = filter(&planes, 8, &Params::default(), 0.5);
let wild = Params { block: 0, step: 0, search: 1000, group: 0, ..Params::default() };
assert!(filter(&noisy(16, 2.0, 1), 16, &wild, 0.5).iter().flatten().all(|v| v.is_finite()));
assert!(filter(&[], 8, &Params::default(), 0.5).iter().all(|p| p.is_empty()));
}
}
+679
View File
@@ -0,0 +1,679 @@
//! The built-in denoiser: what AI Denoise runs when no model has been installed, so it works out of the box.
//!
//! It is a [`TileRunner`] with the same contract as a model (four Bayer planes in, camera RGB at twice the plane
//! size out), written from scratch and needing no file: the noise level of the photo is measured from the photo itself
//! (Poisson-Gaussian: variance = a · signal + b; [`estimate_noise`], with a tile's own measure as the fallback), the
//! four planes are cleaned together by block-matching collaborative filtering on variance-stabilised data
//! ([`crate::bm3d`]; the non-local-means filter of [`crate::nlm`] is the fallback), which cleans harder as the noise
//! grows, and the cleaned mosaic is demosaiced with edge-directed green and colour-difference red and blue.
use crate::bayer::reflect;
use crate::licence::{Commercial, Licence};
use crate::manifest::{DenoiserManifest, Domain, Gain};
use crate::nlm::{self, Stabiliser, Tuning};
use crate::run::{Error, TileRunner};
/// Id of the built-in denoiser; no installed model may use it (the models folder is never searched for it).
pub const ID: &str = "builtin";
/// Changes when the algorithm does, so that cached pictures made by an older one are made again.
pub const VERSION: u32 = 5;
/// Side of its tile, in cells.
pub const TILE: u32 = 256;
/// Cells neighbouring tiles share.
pub const OVERLAP: u32 = 16;
/// Cells on a side of the blocks the noise level is measured over.
const BLOCK: usize = 16;
/// The smallest variance used, so that a clean tile is left alone instead of divided by zero.
const MIN_VARIANCE: f32 = 1e-10;
/// Blocks with a mean above this (white = 1) may be clipped and say nothing about the noise.
const CLIPPED: f32 = 0.9;
/// The manifest of the built-in denoiser, as the engine treats an installed model.
pub fn manifest() -> DenoiserManifest {
DenoiserManifest {
id: ID.into(),
name: "Built-in".into(),
version: VERSION.to_string(),
licence: Licence {
name: "MIT OR Apache-2.0".into(),
commercial: Commercial::Yes,
url: None,
notice: "Part of LightCraft: no download, no weights.".into(),
},
source: None,
sha256: None,
size_bytes: None,
provenance: "Block-matching collaborative filtering with a noise level measured from each photo, written for LightCraft.".into(),
domain: Domain::BayerToRgb,
tile: TILE,
overlap: OVERLAP,
gain: Gain::None,
}
}
/// The built-in denoiser as a tile runner.
#[derive(Clone, Copy, Debug, Default)]
pub struct Builtin {
/// The noise of the whole photo as `(a, b)`, variance = `a · signal + b` (see [`estimate_noise`]). Without it each
/// tile measures its own, which is rougher and can show as a change of strength between tiles.
pub noise: Option<(f32, f32)>,
pub tuning: Tuning,
}
impl Builtin {
/// The runner told the photo's noise as `(a, b)`, variance = `a · signal + b` (see [`estimate_noise`]), with the default tuning.
pub fn with_noise(noise: (f32, f32)) -> Self {
Builtin { noise: Some(noise), tuning: Tuning::default() }
}
/// The block-matching filter's parameters when this one uses it (the only filter with a graphics-card version, see
/// `lightcraft_gpu::bm3d`), else `None`.
pub fn bm3d_params(&self) -> Option<crate::bm3d::Params> {
self.tuning.bm3d
}
/// [`TileRunner::run`] with the filter stage given: it gets the four variance-stabilised planes (unit noise), their
/// side, and the photo's noise at mid-grey (which sets how strongly to clean, see [`Tuning::strength`]), and returns
/// the cleaned planes. Everything else (measuring the noise, stabilising and its inverse, demosaicing) is shared, so
/// a filter that is the same computation on another device gives the same picture.
pub fn run_with(&self, input: &[f32], filter: &dyn Fn(&[Vec<f32>], usize, f32) -> Result<Vec<Vec<f32>>, Error>) -> Result<Vec<f32>, Error> {
let t = side_of(input.len()).ok_or_else(|| Error::Input("the tile is not four square planes".into()))?;
let clean: Vec<f32> = input.iter().map(|v| if v.is_finite() { *v } else { 0.0 }).collect();
let n = t * t;
let (a, b) = match self.noise {
Some((a, b)) if a.is_finite() && b.is_finite() => (a, b),
_ => noise_model(&clean.chunks_exact(n).collect::<Vec<_>>(), t),
};
let st = Stabiliser::new(a, b);
let stabilised: Vec<Vec<f32>> = clean.chunks_exact(n).map(|p| p.iter().map(|&v| st.forward(v)).collect()).collect();
let cleaned = filter(&stabilised, t, (a * 0.18 + b).max(0.0).sqrt())?;
if cleaned.len() != 4 || cleaned.iter().any(|p| p.len() != n) {
return Err(Error::Runtime("the filter returned planes of the wrong size".into()));
}
let planes: Vec<Vec<f32>> = cleaned.iter().map(|p| p.iter().map(|&v| st.inverse(v)).collect()).collect();
Ok(demosaic(&planes, t))
}
/// The filter stage on the processor.
pub fn filter_on_cpu(&self, stabilised: &[Vec<f32>], t: usize, noise: f32) -> Vec<Vec<f32>> {
match &self.tuning.bm3d {
Some(p) => crate::bm3d::filter(stabilised, t, p, noise),
None => nlm::filter(stabilised, t, &self.tuning, noise),
}
}
}
impl TileRunner for Builtin {
/// Clean one tile, all on the processor.
fn run(&self, input: &[f32]) -> Result<Vec<f32>, Error> {
self.run_with(input, &|planes, t, noise| Ok(self.filter_on_cpu(planes, t, noise)))
}
}
/// The side of the planes of a tile of `len` values, if it is four squares.
fn side_of(len: usize) -> Option<usize> {
let per = len / 4;
let t = (per as f64).sqrt().round() as usize;
(len.is_multiple_of(4) && (8..=2048).contains(&t) && t * t == per).then_some(t)
}
/// Measure the noise of a tile: `(a, b)` with variance = `a · signal + b`. Each block of a plane gives the signal
/// (its mean) and the variance of its cells' difference from their four neighbours (which texture and edges only
/// raise), the lower part of the variances at each brightness is the noise, and a line is fitted through them.
fn noise_model(planes: &[&[f32]], t: usize) -> (f32, f32) {
let mut blocks: Vec<(f32, f32)> = Vec::new();
for p in planes {
let at = |x: usize, y: usize| p.get(y * t + x).copied().unwrap_or(0.0);
let mut by = 1;
while by + BLOCK < t {
let mut bx = 1;
while bx + BLOCK < t {
let (mut sum, mut sq) = (0f64, 0f64);
for y in by..by + BLOCK {
for x in bx..bx + BLOCK {
let c = at(x, y);
let r = c - 0.25 * (at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1));
sum += f64::from(c);
sq += f64::from(r * r);
}
}
let cells = (BLOCK * BLOCK) as f64;
let mean = (sum / cells) as f32;
// a cell minus the mean of four neighbours has 1.25 times the variance of one
let variance = (sq / cells / 1.25) as f32;
if mean < CLIPPED && mean.is_finite() && variance.is_finite() {
blocks.push((mean, variance));
}
bx += BLOCK;
}
by += BLOCK;
}
}
fit_noise(blocks)
}
/// The noise of a whole mosaic as `(a, b)` (variance = `a · signal + b`), measured from the picture itself.
///
/// Each of the four colour planes (they sit at different levels in a raw, so they are never mixed) is cut into blocks.
/// A block's noise variance is read from a second-difference operator (`[1 -2 1; -2 4 -2; 1 -2 1]`, which cancels flat
/// and smoothly sloping signal and has `36 σ²` of white noise's variance); texture and edges only add to it. At each
/// brightness the quietest few blocks are the noise (a low quantile, divided by the bias of that quantile of pure
/// noise), and a line is fitted through them. A picture with no flat area still reads somewhat high, never low.
pub fn estimate_noise(mosaic: &[f32], width: usize, height: usize) -> (f32, f32) {
estimate_noise_with(mosaic, width, height, &NoiseProbe::default())
}
/// [`estimate_noise`], or `None` when the mosaic could not be measured (too small, the wrong size, or no unclipped
/// block): the runner then measures each tile's own noise instead of being told a made-up one.
pub fn measure_noise(mosaic: &[f32], width: usize, height: usize) -> Option<(f32, f32)> {
let noise = estimate_noise(mosaic, width, height);
(noise != (0.0, MIN_VARIANCE)).then_some(noise)
}
/// What [`estimate_noise_with`] may be tuned by.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NoiseProbe {
/// Cells on a side of the blocks, in a colour plane.
pub block: usize,
/// Which of a brightness's blocks (by how noisy they look, 0 = the quietest) is taken as the noise.
pub quantile: f32,
/// What that quantile of the variances of noise-only blocks is, as a fraction of their true variance.
pub correction: f32,
}
impl Default for NoiseProbe {
/// The settings the estimator was calibrated with: 12-cell blocks, the quietest 5 %, and the 0.67 bias of that quantile.
fn default() -> Self {
NoiseProbe { block: 12, quantile: 0.05, correction: 0.67 }
}
}
/// [`estimate_noise`] with its settings given.
pub fn estimate_noise_with(mosaic: &[f32], width: usize, height: usize, probe: &NoiseProbe) -> (f32, f32) {
let (pw, ph) = (width / 2, height / 2);
let b = probe.block.clamp(6, 64);
if pw < b + 2 || ph < b + 2 || width.checked_mul(height) != Some(mosaic.len()) {
return (0.0, MIN_VARIANCE);
}
let mut blocks: Vec<(f32, f32)> = Vec::new();
let mut plane = vec![0f32; pw * ph];
for c in 0..4 {
let (dx, dy) = (c % 2, c / 2);
for (y, row) in plane.chunks_exact_mut(pw).enumerate() {
for (x, v) in row.iter_mut().enumerate() {
*v = mosaic.get((2 * y + dy) * width + 2 * x + dx).copied().unwrap_or(0.0);
}
}
let at = |x: usize, y: usize| plane.get(y * pw + x).copied().unwrap_or(0.0);
let mut by = 1;
while by + b < ph {
let mut bx = 1;
while bx + b < pw {
let (mut sum, mut sq, mut top) = (0f64, 0f64, f32::MIN);
for y in by..by + b {
for x in bx..bx + b {
let m = at(x, y);
let r = 4.0 * m - 2.0 * (at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1))
+ (at(x - 1, y - 1) + at(x + 1, y - 1) + at(x - 1, y + 1) + at(x + 1, y + 1));
sum += f64::from(m);
sq += f64::from(r * r);
top = top.max(m);
}
}
let cells = (b * b) as f64;
let (mean, variance) = ((sum / cells) as f32, (sq / cells / 36.0) as f32);
if top < CLIPPED && mean.is_finite() && variance.is_finite() {
blocks.push((mean, variance));
}
bx += b;
}
by += b;
}
}
fit_quiet_blocks(blocks, probe.quantile, probe.correction)
}
/// Fit `variance = a · signal + b` through the `(mean, variance)` of blocks: at each brightness (about 300 blocks of
/// each) the `quantile` of the variances, divided by `correction`, is the noise.
fn fit_quiet_blocks(mut blocks: Vec<(f32, f32)>, quantile: f32, correction: f32) -> (f32, f32) {
if blocks.is_empty() {
return (0.0, MIN_VARIANCE);
}
blocks.sort_by(|x, y| x.0.total_cmp(&y.0));
let groups = (blocks.len() / 300).clamp(1, 10);
let q = if quantile.is_finite() { quantile.clamp(0.0, 0.5) } else { 0.1 };
let correction = if correction.is_finite() && correction > 0.05 { correction } else { 1.0 };
let mut points: Vec<(f64, f64)> = Vec::new();
for g in 0..groups {
let slice = blocks.get(g * blocks.len() / groups..(g + 1) * blocks.len() / groups).unwrap_or(&[]);
if slice.is_empty() {
continue;
}
let mean = slice.iter().map(|b| f64::from(b.0)).sum::<f64>() / slice.len() as f64;
let mut variances: Vec<f32> = slice.iter().map(|b| b.1).collect();
variances.sort_by(f32::total_cmp);
let quiet = variances.get(((variances.len() as f32 * q) as usize).min(variances.len().saturating_sub(1))).copied().unwrap_or(0.0);
points.push((mean, f64::from(quiet / correction)));
}
fit_line(&points)
}
/// The noise of a whole mosaic as `(a, b)` (variance = `a · signal + b`), from blocks spread over the picture. This is
/// the first version (blocks mix the colour planes, a plain neighbour difference, the lower quarter of the blocks):
/// it reads texture as noise and reports at least about 0.003 at mid-grey whatever the noise. Kept to compare with.
pub fn estimate_noise_v1(mosaic: &[f32], width: usize, height: usize) -> (f32, f32) {
const SIDE: usize = 32;
const MOST_BLOCKS: usize = 6000;
let mut blocks: Vec<(f32, f32)> = Vec::new();
if width < SIDE + 4 || height < SIDE + 4 || width.checked_mul(height) != Some(mosaic.len()) {
return (0.0, MIN_VARIANCE);
}
let total = (width / SIDE).saturating_mul(height / SIDE);
let skip = (total / MOST_BLOCKS + 1).isqrt().max(1);
let at = |x: usize, y: usize| mosaic.get(y * width + x).copied().unwrap_or(0.0);
let mut by = 2;
while by + SIDE + 2 <= height {
let mut bx = 2;
while bx + SIDE + 2 <= width {
let (mut sum, mut sq) = (0f64, 0f64);
for y in by..by + SIDE {
for x in bx..bx + SIDE {
let c = at(x, y);
// the neighbours of the same colour, two samples away
let r = c - 0.25 * (at(x - 2, y) + at(x + 2, y) + at(x, y - 2) + at(x, y + 2));
sum += f64::from(c);
sq += f64::from(r * r);
}
}
let cells = (SIDE * SIDE) as f64;
let (mean, variance) = ((sum / cells) as f32, (sq / cells / 1.25) as f32);
if mean < CLIPPED && mean.is_finite() && variance.is_finite() {
blocks.push((mean, variance));
}
bx += SIDE * skip;
}
by += SIDE * skip;
}
fit_noise(blocks)
}
/// Fit `variance = a · signal + b` through the `(mean, variance)` of blocks: the quieter part of the variances at
/// each brightness is the noise (texture and edges only raise a block's variance), and a line is fitted through them.
fn fit_noise(mut blocks: Vec<(f32, f32)>) -> (f32, f32) {
if blocks.is_empty() {
return (0.0, MIN_VARIANCE);
}
blocks.sort_by(|x, y| x.0.total_cmp(&y.0));
let groups = (blocks.len() / 8).clamp(1, 6);
let points: Vec<(f64, f64)> = {
let mut points: Vec<(f64, f64)> = Vec::new();
for g in 0..groups {
let slice = blocks.get(g * blocks.len() / groups..(g + 1) * blocks.len() / groups).unwrap_or(&[]);
if slice.is_empty() {
continue;
}
let mean = slice.iter().map(|b| f64::from(b.0)).sum::<f64>() / slice.len() as f64;
let mut variances: Vec<f32> = slice.iter().map(|b| b.1).collect();
variances.sort_by(f32::total_cmp);
let quiet = variances.get(variances.len() / 4).copied().unwrap_or(0.0);
points.push((mean, f64::from(quiet)));
}
points
};
fit_line(&points)
}
/// The line `variance = a · signal + b` through `(signal, variance)` points, with neither `a` nor `b` negative.
fn fit_line(points: &[(f64, f64)]) -> (f32, f32) {
if points.is_empty() {
return (0.0, MIN_VARIANCE);
}
let n = points.len() as f64;
let (sx, sy) = points.iter().fold((0.0, 0.0), |s, p| (s.0 + p.0, s.1 + p.1));
let (sxx, sxy) = points.iter().fold((0.0, 0.0), |s, p| (s.0 + p.0 * p.0, s.1 + p.0 * p.1));
let det = n * sxx - sx * sx;
let (mut a, mut b) =
if points.len() >= 2 && det.abs() > 1e-12 { ((n * sxy - sx * sy) / det, (sy - (n * sxy - sx * sy) / det * sx) / n) } else { (0.0, sy / n) };
if a < 0.0 {
(a, b) = (0.0, sy / n);
} else if b < 0.0 {
(a, b) = (if sxx > 0.0 { sxy / sxx } else { 0.0 }, 0.0);
}
(a.max(0.0) as f32, (b.max(0.0) as f32).max(MIN_VARIANCE))
}
/// Demosaic four planes `[R, G1, G2, B]` of an RGGB tile into camera RGB planes `[R, G, B]` of `2t × 2t`.
pub fn demosaic(planes: &[Vec<f32>], t: usize) -> Vec<f32> {
let s = 2 * t;
let si = s as isize;
// the mosaic: R at (even, even), G1 at (odd, even), G2 at (even, odd), B at (odd, odd)
let mut m = vec![0f32; s * s];
for (p, plane) in planes.iter().enumerate() {
let (dx, dy) = (p % 2, p / 2);
for cy in 0..t {
for cx in 0..t {
if let (Some(dst), Some(v)) = (m.get_mut((2 * cy + dy) * s + 2 * cx + dx), plane.get(cy * t + cx)) {
*dst = *v;
}
}
}
}
let at = |x: isize, y: isize| m.get(reflect(y, s) * s + reflect(x, s)).copied().unwrap_or(0.0);
// green everywhere: measured where there is a green sample, else interpolated along the smoother direction
let mut g = vec![0f32; s * s];
for y in 0..si {
for x in 0..si {
let v = if (x + y) % 2 == 1 {
at(x, y)
} else {
let c = at(x, y);
let (l, r, u, d) = (at(x - 1, y), at(x + 1, y), at(x, y - 1), at(x, y + 1));
let (gh, gv) =
((l + r) / 2.0 + (2.0 * c - at(x - 2, y) - at(x + 2, y)) / 4.0, (u + d) / 2.0 + (2.0 * c - at(x, y - 2) - at(x, y + 2)) / 4.0);
let (dh, dv) =
((l - r).abs() + (2.0 * c - at(x - 2, y) - at(x + 2, y)).abs(), (u - d).abs() + (2.0 * c - at(x, y - 2) - at(x, y + 2)).abs());
let est = if dh < dv {
gh
} else if dv < dh {
gv
} else {
(gh + gv) / 2.0
};
est.clamp(l.min(r).min(u).min(d), l.max(r).max(u).max(d))
};
if let Some(dst) = g.get_mut(y as usize * s + x as usize) {
*dst = v;
}
}
}
let gat = |x: isize, y: isize| g.get(reflect(y, s) * s + reflect(x, s)).copied().unwrap_or(0.0);
// red and blue: the difference from green is smooth, so interpolate it from the nearest samples of the colour
let chroma = |px: isize, py: isize| -> Vec<f32> {
let diff = |x: isize, y: isize| at(x, y) - gat(x, y);
let mut out = vec![0f32; s * s];
for y in 0..si {
for x in 0..si {
let (col, row) = (x % 2 == px, y % 2 == py);
let d = match (col, row) {
(true, true) => diff(x, y),
(false, true) => (diff(x - 1, y) + diff(x + 1, y)) / 2.0,
(true, false) => (diff(x, y - 1) + diff(x, y + 1)) / 2.0,
(false, false) => (diff(x - 1, y - 1) + diff(x + 1, y - 1) + diff(x - 1, y + 1) + diff(x + 1, y + 1)) / 4.0,
};
if let Some(dst) = out.get_mut(y as usize * s + x as usize) {
*dst = d + gat(x, y);
}
}
}
out
};
let mut out = chroma(0, 0);
out.extend_from_slice(&g);
out.extend(chroma(1, 1));
out
}
#[cfg(test)]
mod tests {
use super::*;
/// Deterministic standard normal numbers.
struct Noise(u64);
impl Noise {
/// The next uniform number, strictly between 0 and 1.
fn uniform(&mut self) -> f32 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((self.0 >> 40) as f32 + 0.5) / (1u64 << 24) as f32
}
/// The next standard normal number (Box-Muller).
fn normal(&mut self) -> f32 {
let (u, v) = (self.uniform(), self.uniform());
(-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
}
}
/// A scene of camera RGB with an edge and a gradient, `s × s`.
fn scene(s: usize) -> [Vec<f32>; 3] {
let mut out = [vec![0f32; s * s], vec![0f32; s * s], vec![0f32; s * s]];
for y in 0..s {
for x in 0..s {
let base = 0.15 + 0.5 * x as f32 / s as f32;
let step = if y > s / 2 { 0.2 } else { 0.0 };
for (c, plane) in out.iter_mut().enumerate() {
plane[y * s + x] = base + step * (1.0 + c as f32 * 0.3) / 1.6;
}
}
}
out
}
/// The scene's RGGB mosaic with noise of variance `a · signal + b`, as the four planes a tile has.
fn mosaic_planes(truth: &[Vec<f32>; 3], t: usize, a: f32, b: f32, seed: u64) -> Vec<f32> {
let s = 2 * t;
let mut rng = Noise(seed);
let mut planes = vec![0f32; 4 * t * t];
for (p, &(dx, dy)) in [(0, 0), (1, 0), (0, 1), (1, 1)].iter().enumerate() {
let c = [0, 1, 1, 2][p];
for cy in 0..t {
for cx in 0..t {
let v = truth[c][(2 * cy + dy) * s + 2 * cx + dx];
planes[p * t * t + cy * t + cx] = v + rng.normal() * (a * v + b).sqrt();
}
}
}
planes
}
/// Mean squared error of an RGB result against the scene, away from the tile's edges.
fn error(out: &[f32], truth: &[Vec<f32>; 3], s: usize) -> f64 {
let (mut sum, mut n) = (0f64, 0f64);
for (c, plane) in truth.iter().enumerate() {
for y in 12..s - 12 {
for x in 12..s - 12 {
let d = f64::from(out[c * s * s + y * s + x] - plane[y * s + x]);
sum += d * d;
n += 1.0;
}
}
}
sum / n
}
/// A noisy tile comes out at least five times closer to the scene (squared error) than a plain demosaic of it.
#[test]
fn a_noisy_tile_comes_out_much_closer_to_the_scene_than_a_plain_demosaic() {
let (t, a, b) = (64, 0.004, 0.0004);
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, a, b, 7);
let planes: Vec<Vec<f32>> = input.chunks_exact(t * t).map(<[f32]>::to_vec).collect();
let plain = error(&demosaic(&planes, t), &truth, 2 * t);
let cleaned = error(&Builtin::default().run(&input).unwrap(), &truth, 2 * t);
assert!(cleaned < plain / 5.0, "plain {plain}, cleaned {cleaned}");
}
/// A tile with no noise is demosaiced almost exactly, and the step between two rows of its scene survives.
#[test]
fn a_noise_free_tile_is_demosaiced_without_blurring_its_edge() {
let t = 64;
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, 0.0, 0.0, 1);
let out = Builtin::default().run(&input).unwrap();
assert!(error(&out, &truth, 2 * t) < 2e-5);
// the step between rows 63 and 65 survives
let s = 2 * t;
let (above, below) = (out[s * (s / 2 - 2) + s / 2], out[s * (s / 2 + 2) + s / 2]);
assert!(below - above > 0.9 * 0.2 / 1.6, "{above} {below}");
}
/// The tile's own noise model finds the added noise within 30 % at two brightness levels.
#[test]
fn the_noise_level_is_found_from_the_tile() {
let (t, a, b) = (128, 0.004, 0.0004);
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, a, b, 3);
let planes: Vec<&[f32]> = input.chunks_exact(t * t).collect();
let (ea, eb) = noise_model(&planes, t);
for signal in [0.2f32, 0.5] {
let (want, got) = (a * signal + b, ea * signal + eb);
assert!((got / want - 1.0).abs() < 0.3, "at {signal}: {got} against {want}");
}
}
/// Black, mid-grey and fully clipped tiles give finite results that stay at their level.
#[test]
fn flat_dark_and_clipped_tiles_do_not_break_it() {
let t = 32;
for v in [0.0f32, 0.5, 1.0] {
let out = Builtin::default().run(&vec![v; 4 * t * t]).unwrap();
assert_eq!(out.len(), 3 * 4 * t * t);
assert!(out.iter().all(|x| x.is_finite() && (x - v).abs() < 1e-4), "{v}");
}
}
/// Empty tiles and tiles that are not four squares are errors; NaN and infinite values in a tile are cleaned up.
#[test]
fn bad_tiles_are_errors_and_bad_numbers_are_cleaned_up() {
assert!(Builtin::default().run(&[]).is_err());
assert!(Builtin::default().run(&[0.0; 30]).is_err());
assert!(Builtin::default().run(&vec![0.0; 4 * 9 * 10]).is_err());
let mut input = vec![0.3f32; 4 * 16 * 16];
input[5] = f32::NAN;
input[77] = f32::INFINITY;
assert!(Builtin::default().run(&input).unwrap().iter().all(|v| v.is_finite()));
}
/// The whole-mosaic estimate finds the added noise within 25 %; a mosaic that is too small or not the size it says
/// gets the minimum variance instead of a panic.
#[test]
fn the_noise_of_a_whole_mosaic_is_found_and_hostile_mosaics_are_refused() {
let (s, a, b) = (384, 0.01f32, 0.0005f32);
let truth = scene(s);
let mut rng = Noise(5);
let mosaic: Vec<f32> = (0..s * s)
.map(|i| {
let (x, y) = (i % s, i / s);
let v = truth[[0, 1, 1, 2][(y % 2) * 2 + x % 2]][i];
v + rng.normal() * (a * v + b).sqrt()
})
.collect();
let (ea, eb) = estimate_noise(&mosaic, s, s);
for signal in [0.2f32, 0.5] {
let (want, got) = (a * signal + b, ea * signal + eb);
assert!((got / want - 1.0).abs() < 0.25, "at {signal}: {got} against {want}");
}
// too small, or not the size it says: no estimate, and no panic
assert_eq!(estimate_noise(&mosaic, 10, 10).1, MIN_VARIANCE);
assert_eq!(estimate_noise(&mosaic, s, s - 1).1, MIN_VARIANCE);
assert_eq!(estimate_noise(&[], 0, 0).1, MIN_VARIANCE);
assert_eq!(measure_noise(&[], 0, 0), None, "a mosaic that cannot be measured has no noise to tell the runner");
assert_eq!(measure_noise(&mosaic, 10, 10), None);
assert!(measure_noise(&mosaic, s, s).is_some());
assert_eq!(estimate_noise(&mosaic, usize::MAX, usize::MAX).1, MIN_VARIANCE);
}
/// A 640 x 640 mosaic: a smooth slope (dark at the top, bright at the bottom), texture (fine lines, edges) over its
/// left part and flat over the rest, with noise of variance `a · signal + b` added.
fn textured_and_flat(a: f32, b: f32, flat_from: usize, seed: u64) -> Vec<f32> {
let s = 640;
let mut rng = Noise(seed);
(0..s * s)
.map(|i| {
let (x, y) = (i % s, i / s);
let slope = 0.02 + 0.6 * y as f32 / s as f32 + 0.1 * x as f32 / s as f32;
let texture = if x < flat_from {
0.04 * ((x as f32 * 1.3).sin() + (y as f32 * 0.9).sin()) + if (x / 9 + y / 7) % 2 == 0 { 0.05 } else { 0.0 }
} else {
0.0
};
let v = (slope + texture).max(0.0);
v + rng.normal() * (a * v + b).sqrt()
})
.collect()
}
/// With texture over most of the picture and a flat strip beside it, the estimate follows the strip's noise within
/// 25 % (in deviation), where the first version read the texture as several times too much.
#[test]
fn the_noise_is_read_from_the_flat_areas_and_not_from_the_texture_beside_them() {
let (a, b) = (5e-4f32, 1e-6f32);
// texture over the left 70 % and flat over the rest: the flat part is what shows the noise
let mosaic = textured_and_flat(a, b, 450, 7);
let (ea, eb) = estimate_noise(&mosaic, 640, 640);
for signal in [0.1f32, 0.2, 0.4] {
let (want, got) = ((a * signal + b).sqrt(), (ea * signal + eb).sqrt());
assert!((got / want - 1.0).abs() < 0.25, "the deviation at {signal}: {got} against {want}");
}
// the first version read the texture as noise (several times too much); this one is far closer
let old = estimate_noise_v1(&mosaic, 640, 640);
assert!(((old.0 * 0.2 + old.1) / (a * 0.2 + b)).sqrt() > 1.4, "the first version is the thing this one improves on");
}
/// A picture that is all texture is read as noisier than it is, never as meaningfully quieter.
#[test]
fn a_picture_with_no_flat_area_reads_noisier_than_it_is_never_quieter() {
let (a, b) = (5e-4f32, 1e-6f32);
let mosaic = textured_and_flat(a, b, 640, 9);
let (ea, eb) = estimate_noise(&mosaic, 640, 640);
for signal in [0.1f32, 0.3] {
assert!(ea * signal + eb >= 0.9 * (a * signal + b), "at {signal}: {} against {}", ea * signal + eb, a * signal + b);
}
}
/// Black, fully clipped and NaN mosaics, and a nonsensical probe setting, give finite numbers and no panic.
#[test]
fn a_clipped_or_all_dark_mosaic_is_measured_without_a_panic() {
for level in [0.0f32, 1.0, f32::NAN] {
let mosaic = vec![level; 200 * 200];
let (a, b) = estimate_noise(&mosaic, 200, 200);
assert!(a.is_finite() && b.is_finite() && a >= 0.0 && b > 0.0, "{level}: {a} {b}");
}
let probe = NoiseProbe { block: 0, quantile: f32::NAN, correction: -1.0 };
let (a, b) = estimate_noise_with(&vec![0.3; 200 * 200], 200, 200, &probe);
assert!(a.is_finite() && b.is_finite());
}
/// A heavily noisy tile is cleaned to under an eighth of a plain demosaic's error, whether the runner measures the
/// noise itself or is told it.
#[test]
fn a_heavily_noisy_tile_is_cleaned_far_more_than_a_plain_demosaic_and_by_the_photos_noise() {
let (t, a, b) = (64, 0.03, 0.004);
let truth = scene(2 * t);
let input = mosaic_planes(&truth, t, a, b, 9);
let planes: Vec<Vec<f32>> = input.chunks_exact(t * t).map(<[f32]>::to_vec).collect();
let plain = error(&demosaic(&planes, t), &truth, 2 * t);
let own = error(&Builtin::default().run(&input).unwrap(), &truth, 2 * t);
let told = error(&Builtin::with_noise((a, b)).run(&input).unwrap(), &truth, 2 * t);
assert!(own < plain / 8.0 && told < plain / 8.0, "plain {plain}, own {own}, told {told}");
}
/// Noise values that are not numbers fall back to the tile's own measurement; a tuning with no search, and the
/// non-local-means fallback, still give finite pictures; and the strength rises with the noise from 0 to 1.
#[test]
fn noise_values_that_are_not_numbers_fall_back_to_the_tiles_own_and_the_strength_follows_the_noise() {
let t = 32;
let input = vec![0.3f32; 4 * t * t];
for bad in [(f32::NAN, 1e-3), (0.01, f32::INFINITY), (-1.0, -1.0)] {
let out = Builtin { noise: Some(bad), tuning: Tuning::default() }.run(&input).unwrap();
assert!(out.iter().all(|v| v.is_finite()), "{bad:?}");
}
// no search at all is a plain demosaic, not a crash
let none = Builtin { noise: Some((0.01, 1e-3)), tuning: Tuning { search: 0, search2: 0, bm3d: None, ..Tuning::default() } };
assert!(none.run(&input).unwrap().iter().all(|v| v.is_finite()));
let nlm = Builtin { noise: Some((0.01, 1e-3)), tuning: Tuning { bm3d: None, ..Tuning::default() } };
assert!(nlm.run(&input).unwrap().iter().all(|v| v.is_finite()));
let tune = Tuning::default();
let ramp: Vec<f32> = [0.0, 0.02, 0.05, 0.1, 0.2].iter().map(|&n| tune.strength(n)).collect();
assert!(ramp.windows(2).all(|w| w[0] <= w[1]) && ramp[0] == 0.0 && ramp[4] == 1.0, "{ramp:?}");
}
/// The built-in denoiser's manifest passes the manifest check and carries the tile and overlap the runner uses.
#[test]
fn its_manifest_is_valid() {
let m = manifest();
crate::manifest::validate(&m).unwrap();
assert_eq!((m.tile, m.overlap), (TILE, OVERLAP));
}
}
+3
View File
@@ -4,10 +4,13 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod archive;
pub mod bayer;
pub mod bm3d;
pub mod builtin;
pub mod hash;
pub mod known;
pub mod licence;
pub mod manifest;
pub mod nlm;
pub mod product;
pub mod run;
pub mod tiles;
+416
View File
@@ -0,0 +1,416 @@
//! The built-in denoiser's filter: variance stabilisation and a non-local-means average whose weights come from all
//! four colour planes of a tile at once, so the planes are cleaned together instead of each on its own.
//!
//! Noise in a raw file has variance `a · signal + b`. The generalised Anscombe transform ([`Stabiliser`]) turns that
//! into noise of variance 1 everywhere, so one threshold fits every brightness. The four planes are then rotated
//! (a Hadamard transform, which keeps unit noise) into a brightness plane and three colour-difference planes.
//! Each cell becomes the average of the cells around it whose patch, over all four planes, looks like its own
//! within the noise, in two passes: the second finds matches on the first pass's much cleaner picture, so it can
//! look further and keep finer detail.
use crate::bayer::reflect;
/// What the filter may be tuned by (the defaults are what the built-in denoiser uses).
///
/// How strongly a photo is cleaned follows its noise, measured as the standard deviation at mid-grey (0.18, white = 1):
/// below `light` it is cleaned gently and in one pass, above `heavy` as hard as the filter goes, and in between smoothly.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tuning {
/// Search window radius, in cells, of the first pass.
pub search: usize,
/// Search window radius of the second pass, which finds matches on the first pass's cleaner picture; 0 skips it.
pub search2: usize,
/// How far above the noise two patches may differ and still be averaged in the first pass (larger blurs more),
/// for a light and for a heavily noisy photo.
pub h_light: f32,
pub h_heavy: f32,
/// The same for the second pass, which is blended in as the noise grows.
pub h2: f32,
/// Noise at mid-grey where the stronger settings start and where they are in full.
pub light: f32,
pub heavy: f32,
/// Search radius and threshold of the colour-difference planes' own pass, guided by the cleaned brightness
/// plane (colour noise is the cheapest to remove without losing texture); radius 0 skips it.
pub search_c: usize,
pub h_c: f32,
/// Patch radius (a patch is `2 · half + 1` cells on a side) of the first and of the later passes.
pub half: usize,
pub half2: usize,
/// How much looser (a multiple of the threshold) the average is that cells with few matching patches lean on in
/// the first pass; 0 turns it off.
pub loose: f32,
/// The matched weight below which they lean on it, in a heavily noisy photo (scaled down with the noise).
pub few: f32,
/// Block-matching collaborative filtering ([`crate::bm3d`]) is what cleans the planes; with `None` the non-local-means
/// averages above do (their settings apply only then).
pub bm3d: Option<crate::bm3d::Params>,
}
impl Default for Tuning {
/// The built-in denoiser's tuning: block matching on, and the non-local-means settings it falls back to when that is off.
fn default() -> Self {
Tuning {
search: 3,
search2: 5,
h_light: 0.3,
h_heavy: 0.45,
h2: 0.1,
light: 0.03,
heavy: 0.14,
search_c: 7,
h_c: 1.0,
half: 1,
half2: 1,
loose: 4.0,
few: 0.6,
bm3d: Some(crate::bm3d::Params::default()),
}
}
}
impl Tuning {
/// 0 for a lightly noisy photo up to 1 for a heavily noisy one.
pub fn strength(&self, noise: f32) -> f32 {
let span = (self.heavy - self.light).max(1e-6);
let x = ((noise - self.light) / span).clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
}
/// The generalised Anscombe transform for noise of variance `a · v + b`.
#[derive(Clone, Copy, Debug)]
pub struct Stabiliser {
a: f32,
b: f32,
}
/// Below this the noise has no signal-dependent part worth modelling.
const MIN_GAIN: f32 = 1e-6;
impl Stabiliser {
/// The transform for noise of variance `a · signal + b`; a gain or offset that is not a number counts as none.
pub fn new(a: f32, b: f32) -> Self {
Stabiliser { a: if a.is_finite() { a.max(0.0) } else { 0.0 }, b: if b.is_finite() { b.max(1e-12) } else { 1e-12 } }
}
/// A value as a signal with unit noise deviation (a plain scaling when the noise has no signal-dependent part).
pub fn forward(self, v: f32) -> f32 {
if self.a < MIN_GAIN {
return v / self.b.sqrt();
}
let x = (v + self.b / self.a) / self.a;
2.0 * (x + 0.375).max(0.0).sqrt()
}
/// The inverse, with the correction for the bias a plain inverse has on averaged data.
pub fn inverse(self, y: f32) -> f32 {
if self.a < MIN_GAIN {
return y * self.b.sqrt();
}
let x = if y >= 1.5 {
let (i1, i2) = (1.0 / y, 1.0 / (y * y));
y * y / 4.0 + 0.25 * 1.5f32.sqrt() * i1 - 11.0 / 8.0 * i2 + 5.0 / 8.0 * 1.5f32.sqrt() * i2 * i1 - 0.125
} else {
y * y / 4.0 - 0.375
};
self.a * x - self.b / self.a
}
}
/// The orthonormal 4 × 4 Hadamard transform across four planes (its own inverse).
pub fn hadamard(p: &[Vec<f32>]) -> Vec<Vec<f32>> {
let n = p.first().map_or(0, Vec::len);
let mut out = vec![vec![0f32; n]; 4];
for i in 0..n {
let g = |c: usize| p.get(c).and_then(|v| v.get(i)).copied().unwrap_or(0.0);
let (r, g1, g2, b) = (g(0), g(1), g(2), g(3));
let vals = [(r + g1 + g2 + b) / 2.0, (r - g1 + g2 - b) / 2.0, (r + g1 - g2 - b) / 2.0, (r - g1 - g2 + b) / 2.0];
for (c, v) in vals.into_iter().enumerate() {
if let Some(o) = out.get_mut(c).and_then(|o| o.get_mut(i)) {
*o = v;
}
}
}
out
}
/// A plane with `pad` cells mirrored round every edge (`t + 2 · pad` on a side).
fn padded(src: &[f32], t: usize, pad: usize) -> Vec<f32> {
let wd = t + 2 * pad;
let mut out = vec![0f32; wd * wd];
for y in 0..wd {
let sy = reflect(y as isize - pad as isize, t);
for x in 0..wd {
let sx = reflect(x as isize - pad as isize, t);
if let (Some(o), Some(v)) = (out.get_mut(y * wd + x), src.get(sy * t + sx)) {
*o = *v;
}
}
}
out
}
/// What one [`pass`] is run with.
#[derive(Clone, Copy)]
struct Pass {
/// Search window radius and patch radius, in cells.
radius: usize,
half: usize,
/// The threshold and the floor of the weights (see [`pass`]).
h: f32,
floor: f32,
/// A second, looser average (threshold `h · loose`) that cells with few matches lean on, so a cell no patch
/// resembles is not left as it was; 0 turns it off.
loose: f32,
/// Matched weight below which a cell starts to lean on that looser average.
few: f32,
}
/// One pass: every cell becomes the weighted average of the cells within `radius` whose patch (`2 · half + 1` cells
/// on a side), over all planes, is like its own. `guide` holds the planes the patches are compared on, `data` the
/// planes that are averaged (the same ones in the first pass). Weights are `exp(-(excess) / h)`, `excess` being how
/// far the mean squared difference of the patches is above `floor` (what two noisy views of one signal give).
fn pass(guide: &[Vec<f32>], data: &[Vec<f32>], t: usize, p: &Pass) -> Vec<Vec<f32>> {
let Pass { radius, half, h, floor, loose, few } = *p;
let pad = radius + half;
let wd = t + 2 * pad;
let guide: Vec<Vec<f32>> = guide.iter().map(|p| padded(p, t, pad)).collect();
let data: Vec<Vec<f32>> = data.iter().map(|p| padded(p, t, pad)).collect();
let (n, region, span) = (t * t, t + 2 * half, 2 * half + 1);
let planes = data.len().max(1);
let mut num = vec![vec![0f32; n]; planes];
let mut den = vec![0f32; n];
let mut num_l = vec![vec![0f32; n]; if loose > 0.0 { planes } else { 0 }];
let mut den_l = vec![0f32; if loose > 0.0 { n } else { 0 }];
let (mut d, mut rows) = (vec![0f32; region * region], vec![0f32; region * t]);
let norm = 1.0 / ((span * span) as f32 * guide.len().max(1) as f32);
let r = radius as isize;
for oy in -r..=r {
for ox in -r..=r {
if ox == 0 && oy == 0 {
continue;
}
let shift = oy * wd as isize + ox;
// squared differences over the planes, for the cells and the ring round them the patch reaches
for j in 0..region {
let base = (j + pad - half) * wd + pad - half;
for i in 0..region {
let pos = base + i;
let other = (pos as isize + shift) as usize;
let mut s = 0f32;
for p in &guide {
let (a, b) = (p.get(pos).copied().unwrap_or(0.0), p.get(other).copied().unwrap_or(0.0));
s += (a - b) * (a - b);
}
if let Some(v) = d.get_mut(j * region + i) {
*v = s;
}
}
}
// the sum over each cell's patch: along rows, then down columns
for j in 0..region {
for x in 0..t {
let k = j * region + x;
let s: f32 = (0..span).map(|i| d.get(k + i).copied().unwrap_or(0.0)).sum();
if let Some(v) = rows.get_mut(j * t + x) {
*v = s;
}
}
}
for y in 0..t {
for x in 0..t {
let k = y * t + x;
let patch = (0..span).map(|j| rows.get(k + j * t).copied().unwrap_or(0.0)).sum::<f32>() * norm;
let excess = (patch - floor).max(0.0);
let wide = if loose > 0.0 { loose } else { 1.0 };
// beyond this the weight is below 5e-5: not worth the exponential and the sums
if excess > 10.0 * h * wide {
continue;
}
let pos = (y + pad) * wd + x + pad;
let other = (pos as isize + shift) as usize;
if excess <= 10.0 * h {
let w = (-excess / h).exp();
if let Some(dn) = den.get_mut(k) {
*dn += w;
}
for (nu, p) in num.iter_mut().zip(&data) {
if let (Some(nu), Some(v)) = (nu.get_mut(k), p.get(other)) {
*nu += w * v;
}
}
}
if loose > 0.0 {
let w = (-excess / (h * loose)).exp();
if let Some(dn) = den_l.get_mut(k) {
*dn += w;
}
for (nu, p) in num_l.iter_mut().zip(&data) {
if let (Some(nu), Some(v)) = (nu.get_mut(k), p.get(other)) {
*nu += w * v;
}
}
}
}
}
}
}
// the cell itself counts as much as a perfect match
let mut out = vec![vec![0f32; n]; planes];
for (c, (o, (nu, p))) in out.iter_mut().zip(num.iter().zip(&data)).enumerate() {
for k in 0..n {
let own = p.get((k / t + pad) * wd + k % t + pad).copied().unwrap_or(0.0);
if let (Some(o), Some(nu), Some(dn)) = (o.get_mut(k), nu.get(k), den.get(k)) {
let tight = (nu + own) / (dn + 1.0);
*o = match (num_l.get(c).and_then(|v| v.get(k)), den_l.get(k)) {
(Some(nl), Some(dl)) => {
let loose = (nl + own) / (dl + 1.0);
let lean = if few > 0.0 { few / (dn + few) } else { 0.0 };
tight + (loose - tight) * lean
}
_ => tight,
};
}
}
}
out
}
/// Denoise four unit-noise planes of `t × t` cells (see the module description); `noise` is the photo's noise at
/// mid-grey, which sets how strongly (see [`Tuning`]).
pub fn filter(planes: &[Vec<f32>], t: usize, tune: &Tuning, noise: f32) -> Vec<Vec<f32>> {
let y = hadamard(planes);
let k = tune.strength(if noise.is_finite() { noise } else { 0.0 });
// two noisy views of one signal differ by 2 in mean square: the floor the excess is counted from
let h1 = tune.h_light + (tune.h_heavy - tune.h_light) * k;
let first = pass(&y, &y, t, &Pass { radius: tune.search, half: tune.half, h: h1, floor: 2.0, loose: tune.loose, few: tune.few * k });
if tune.search2 == 0 || k <= 0.0 {
return hadamard(&first);
}
// the first pass's picture still carries a little noise (of unknown size), so the floor is 0 and the threshold
// alone decides
let second = pass(&first, &y, t, &Pass { radius: tune.search2, half: tune.half2, h: tune.h2, floor: 0.0, loose: 0.0, few: 0.0 });
let mut blended: Vec<Vec<f32>> = first.iter().zip(&second).map(|(f, s)| f.iter().zip(s).map(|(f, s)| f + (s - f) * k).collect()).collect();
if tune.search_c > 0 {
// matches found on the cleaned brightness plane alone, so colour is only averaged across like brightness
let guide = blended.get(..1).unwrap_or_default();
let colour = pass(
guide,
y.get(1..).unwrap_or_default(),
t,
&Pass { radius: tune.search_c, half: tune.half2, h: tune.h_c, floor: 0.0, loose: 0.0, few: 0.0 },
);
for (b, c) in blended.iter_mut().skip(1).zip(&colour) {
for (b, c) in b.iter_mut().zip(c) {
*b += (c - *b) * k;
}
}
}
hadamard(&blended)
}
#[cfg(test)]
mod tests {
use super::*;
/// The transform is undone by its inverse within a little, a step of one noise deviation is a step of about 1
/// whatever the brightness, and with no signal-dependent noise it is a plain scaling.
#[test]
fn the_stabiliser_round_trips_and_gives_unit_noise() {
let s = Stabiliser::new(0.01, 0.0005);
for v in [0.0f32, 0.01, 0.1, 0.5, 0.9] {
let back = s.inverse(s.forward(v));
assert!((back - v).abs() < 0.005 + 0.03 * v, "{v} -> {back}");
}
// a step of one standard deviation is a step of about 1 whatever the brightness
for v in [0.05f32, 0.2, 0.6] {
let sigma = (0.01 * v + 0.0005).sqrt();
let step = s.forward(v + sigma) - s.forward(v);
assert!((step - 1.0).abs() < 0.15, "at {v}: {step}");
}
let flat = Stabiliser::new(0.0, 4e-4);
assert!((flat.forward(0.1) - 5.0).abs() < 1e-4 && (flat.inverse(5.0) - 0.1).abs() < 1e-6);
}
/// The Hadamard transform applied twice gives the planes back, and it keeps their energy.
#[test]
fn the_hadamard_transform_is_its_own_inverse_and_keeps_energy() {
let planes: Vec<Vec<f32>> = (0..4).map(|c| (0..9).map(|i| (c * 9 + i) as f32 * 0.37 - 3.0).collect()).collect();
let back = hadamard(&hadamard(&planes));
for (a, b) in planes.iter().flatten().zip(back.iter().flatten()) {
assert!((a - b).abs() < 1e-4);
}
let energy = |p: &[Vec<f32>]| p.iter().flatten().map(|v| v * v).sum::<f32>();
assert!((energy(&planes) - energy(&hadamard(&planes))).abs() < 1e-2);
}
/// Four planes of unit noise (an LCG and Box-Muller, so the tests need no dependency) round `level`.
fn noisy(t: usize, level: f32, seed: u64) -> Vec<Vec<f32>> {
let mut state = seed;
let mut uniform = move || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((state >> 40) as f32 + 0.5) / (1u64 << 24) as f32
};
(0..4)
.map(|_| {
(0..t * t)
.map(|_| {
let (u, v) = (uniform(), uniform());
level + (-2.0 * u.ln()).sqrt() * (std::f32::consts::TAU * v).cos()
})
.collect()
})
.collect()
}
/// The deviation of the planes' values around `level`.
fn spread(planes: &[Vec<f32>], level: f32) -> f32 {
let all: Vec<f32> = planes.iter().flatten().copied().collect();
(all.iter().map(|v| (v - level) * (v - level)).sum::<f32>() / all.len().max(1) as f32).sqrt()
}
/// The colour planes' own pass leaves less noise than brightness alone would, and takes unit noise well below 0.5.
#[test]
fn the_colour_pass_cleans_colour_planes_further_than_brightness_alone_would() {
let (t, noise) = (40, 0.2);
let planes = noisy(t, 5.0, 3);
let with = filter(&planes, t, &Tuning::default(), noise);
let without = filter(&planes, t, &Tuning { search_c: 0, ..Tuning::default() }, noise);
// after the Hadamard rotation the colour differences are planes 1..4 of the mixed result, so compare it all
assert!(spread(&with, 5.0) < spread(&without, 5.0), "{} vs {}", spread(&with, 5.0), spread(&without, 5.0));
assert!(spread(&with, 5.0) < 0.5, "unit noise should drop well below 0.5: {}", spread(&with, 5.0));
}
/// A cell far from its surroundings, which no patch resembles, ends up nearer to them with the looser average than without it.
#[test]
fn a_cell_no_patch_resembles_is_not_left_as_a_speck_in_heavy_noise() {
let (t, noise) = (40, 0.2);
let mut planes = noisy(t, 5.0, 9);
// one cell far from its surroundings in every plane: nothing matches it
let at = (t / 2) * t + t / 2;
for p in &mut planes {
if let Some(v) = p.get_mut(at) {
*v += 6.0;
}
}
let with = filter(&planes, t, &Tuning::default(), noise);
let without = filter(&planes, t, &Tuning { loose: 0.0, ..Tuning::default() }, noise);
let peak = |planes: &[Vec<f32>]| planes.iter().filter_map(|p| p.get(at)).map(|v| (v - 5.0).abs()).fold(0f32, f32::max);
assert!(peak(&with) < peak(&without), "{} vs {}", peak(&with), peak(&without));
}
/// Noise of 0, NaN or next to nothing, with one cell far from the rest, still gives finite values.
#[test]
fn a_photo_with_no_measured_noise_stays_finite_even_with_an_odd_cell() {
let t = 24;
let mut planes = noisy(t, 5.0, 5);
for p in &mut planes {
if let Some(v) = p.get_mut(t * t / 2) {
*v += 50.0;
}
}
for noise in [0.0, f32::NAN, 1e-9] {
assert!(filter(&planes, t, &Tuning::default(), noise).iter().flatten().all(|v| v.is_finite()), "noise {noise}");
}
}
}
+20 -1
View File
@@ -160,7 +160,10 @@ pub fn write(path: &Path, img: &Rgb32f, key: &str) -> Result<(), ProductError> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let mut f = std::io::BufWriter::new(std::fs::File::create(&tmp)?);
// a new temp file: an entry already under the name (a link planted in the cache folder
// would be written through) is removed, never opened
let _ = std::fs::remove_file(&tmp);
let mut f = std::io::BufWriter::new(std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?);
f.write_all(MAGIC)?;
f.write_all(&[VERSION, 0, 0, 0])?;
f.write_all(&(header.len() as u32).to_le_bytes())?;
@@ -459,6 +462,22 @@ mod tests {
std::env::temp_dir().join(format!("lc-denoise-{name}-{}.lcdn", std::process::id()))
}
#[cfg(unix)]
#[test]
fn a_link_planted_under_the_temp_name_is_not_written_through() {
let p = temp("planted");
let victim = temp("victim");
std::fs::write(&victim, b"keep").unwrap();
let _ = std::fs::remove_file(p.with_extension("tmp"));
std::os::unix::fs::symlink(&victim, p.with_extension("tmp")).unwrap();
write(&p, &picture(16, 4), "k").unwrap();
assert_eq!(std::fs::read(&victim).unwrap(), b"keep");
assert!(read_header_at(&p).is_ok());
for f in [p, victim] {
let _ = std::fs::remove_file(f);
}
}
fn picture(w: usize, h: usize) -> Rgb32f {
Rgb32f {
width: w,
+1 -1
View File
@@ -1,6 +1,6 @@
# lightcraft-denoise
L1 pure-Rust AI RAW denoise primitives and CPU inference. No weights are bundled.
L1 pure-Rust AI RAW denoise primitives and CPU inference. No weights are bundled; `lightcraft_denoise_core::builtin` is the model-free denoiser used by default.
See [user workflow and limitations](../../docs/denoise.md).
`lightcraft-denoise-core` provides metadata, Bayer helpers and cache formats,
+30
View File
@@ -97,6 +97,10 @@ impl ControlSpec {
}
pub fn format(&self, v: f64) -> String {
let s = format!("{:.*}", self.decimals as usize, v);
if v.is_finite() && !s.bytes().any(|b| matches!(b, b'1'..=b'9')) {
// Rounds to zero: no sign.
return s.trim_start_matches('-').to_string();
}
if v > 0.0 && self.min < 0.0 { format!("+{s}") } else { s }
}
/// Where `v` sits on the slider track, from 0 (left end) to 1 (right end). Linear, except for the Kelvin
@@ -410,6 +414,9 @@ pub static INDEXED: &[ControlSpec] = &[
fn split_indexed(id: &str) -> Option<(&str, usize, &str)> {
let mut it = id.splitn(3, '.');
let (fam, i, field) = (it.next()?, it.next()?, it.next()?);
if i.is_empty() || !i.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
Some((fam, i.parse().ok()?, field))
}
@@ -493,6 +500,17 @@ pub fn in_section(section: Section) -> impl Iterator<Item = &'static ControlSpec
mod tests {
use super::*;
#[test]
fn format_shows_no_sign_on_a_value_that_rounds_to_zero() {
let e = find("light.exposure").unwrap();
assert_eq!(e.format(0.004), "0.00");
assert_eq!(e.format(-0.004), "0.00");
assert_eq!(e.format(0.5), "+0.50");
assert_eq!(e.format(-0.5), "-0.50");
assert_eq!(e.format(f64::INFINITY), "+inf");
assert_eq!(e.format(f64::NEG_INFINITY), "-inf");
}
#[test]
fn every_control_reads_its_default() {
let s = DevelopSettings::default();
@@ -538,6 +556,18 @@ mod tests {
}
}
#[test]
fn signed_indexes_are_unknown_ids() {
let mut s = DevelopSettings::default();
s.point_colors.push(Default::default());
let before = s.point_colors[0].hue_shift;
assert!(!set(&mut s, "pointColor.+0.hueShift", 10.0), "signed index");
assert_eq!(s.point_colors[0].hue_shift, before);
assert_eq!(get(&s, "pointColor.+0.hueShift"), None);
assert!(find("pointColor.+0.hueShift").is_none());
assert!(find("redEye.+0.darken").is_none());
}
#[test]
fn formatting() {
let e = find("light.exposure").unwrap();
+168 -7
View File
@@ -13,7 +13,7 @@ pub mod settings;
pub use controls::{CONTROLS, ControlSpec, Section, Track};
pub use presets::{Preset, SettingsGroup, apply_partial, extract_groups};
pub use segmask::SegMask;
pub use segmask::{SegMask, with_grid_interner};
pub use settings::*;
use serde_json::Value;
@@ -27,6 +27,7 @@ impl DevelopSettings {
s.wb.tint = as_shot_tint;
s.detail.sharpen_amount = 40.0;
s.detail.nr_color = 25.0;
s.detail.nr_outliers = true;
s
}
@@ -38,6 +39,26 @@ impl DevelopSettings {
serde_json::from_value(v.clone())
}
/// [`Self::to_json`] with Remove Hot Pixels (`detail.nr_outliers`) stated even when off, for JSON that is copied,
/// merged, scaled or compared key by key (copy / paste, presets, Auto Sync). The stored JSON leaves it out when
/// off, so settings saved before it keep their hash; a merge needs the `false`, or copying Detail would not turn
/// the box off and a preset applied at an amount would not find its base value.
pub fn to_json_for_merge(&self) -> Value {
let mut v = self.to_json();
if let Some(detail) = v.get_mut("detail").and_then(Value::as_object_mut) {
detail.insert("nr_outliers".into(), Value::Bool(self.detail.nr_outliers));
}
v
}
/// [`Self::from_json`] for settings from outside the app, such as a sidecar's `lc:settings`
/// (issue #2555): kept in range as [`Self::merged`] keeps them.
pub fn from_untrusted_json(v: &Value) -> Result<DevelopSettings, serde_json::Error> {
let mut s = DevelopSettings::from_json(v)?;
s.keep_in_range(&DevelopSettings::default());
Ok(s)
}
/// Merge a partial JSON object into these settings (fields not mentioned are kept). A white balance that
/// names no [`WbScale`] keeps the meaning it always had (`Legacy`), whatever scale these settings were on: a
/// partial from before the scale existed, or one that never said, must not become Kelvin by landing on
@@ -58,8 +79,9 @@ impl DevelopSettings {
/// What crs XMP import does to the values it reads, for settings that arrive as JSON (presets, `develop.merge`,
/// `render --settings`; issue #1946): every slider clamped through its control spec, point curves in 0..1, and a
/// crop with no area left as it was in `before`. Unrotated, the crop is clipped to the photo first; a turned crop
/// may reach past 0..1 and is left to the crop tools, which know the photo's size.
/// crop with no area left as it was in `before`. The angle is kept within ±45° (not finite: 0). Unrotated, the crop
/// is clipped to the photo first; a turned crop may reach past 0..1 and is bounded where the photo's size is known
/// (`CropGeometry::bounded`, applied by the pipeline).
fn keep_in_range(&mut self, before: &DevelopSettings) {
for c in controls::CONTROLS {
if let Some(v) = controls::get(self, c.id) {
@@ -71,6 +93,7 @@ impl DevelopSettings {
*p = lightcraft_geom::Point::new(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0));
}
let g = &mut self.crop.geometry;
g.angle = if g.angle.is_finite() { g.angle.clamp(-45.0, 45.0) } else { 0.0 };
if g.angle == 0.0 {
g.rect = g.rect.intersect(&lightcraft_geom::Rect::UNIT);
}
@@ -131,6 +154,12 @@ impl DevelopSettings {
std::borrow::Cow::Owned(d)
}
/// Whether a raw is decoded with its single outlier photosites replaced: Remove Hot Pixels is on and the Detail
/// section's eye is too (an Edit-panel section that is off contributes nothing, as in [`Self::effective`]).
pub fn removes_hot_pixels(&self) -> bool {
self.detail.nr_outliers && self.section_enabled("detail")
}
/// How much of the AI-denoised picture to mix in, 0 (none) to 1 (all of it): the Denoise amount, unless the Detail
/// section is switched off or the value is not a number.
pub fn denoise_amount(&self) -> f32 {
@@ -145,7 +174,8 @@ impl DevelopSettings {
}
}
/// Reset every control in `section` to its default.
/// Reset every control in `section` to its default, and the settings of the section that are not
/// controls (the creative profile, the curve, the white balance mode).
pub fn reset_section(&mut self, section: Section) {
for c in controls::in_section(section) {
controls::set(self, c.id, c.default);
@@ -156,14 +186,34 @@ impl DevelopSettings {
self.curve = d;
}
Section::Color => self.wb.mode = WbMode::AsShot,
Section::Detail => self.enhance.denoise_on = None,
Section::Detail => {
self.enhance.denoise_on = None;
// not a slider: reset like them, to the general default (off)
self.detail.nr_outliers = false;
}
// the creative profile is not a control: the chosen look goes back to the default one,
// and so does the camera's own local tone mapping
Section::Profile => {
self.profile = Profile::default();
}
_ => {}
}
}
/// Next free mask id.
/// Next free mask id: one past the highest, or, when that is `u32::MAX` (ids come from files,
/// pastes and agents), the lowest one no mask uses.
pub fn next_mask_id(&self) -> u32 {
self.masks.iter().map(|m| m.id).max().map_or(1, |m| m + 1)
match self.masks.iter().map(|m| m.id).max() {
None => 1,
// fewer masks than ids: one of the first `masks.len() + 1` is free
Some(max) => max
.checked_add(1)
.or_else(|| {
let used: std::collections::HashSet<u32> = self.masks.iter().map(|m| m.id).collect();
(1..=u32::MAX).find(|id| !used.contains(id))
})
.unwrap_or(0),
}
}
}
@@ -175,6 +225,37 @@ mod tests {
use super::*;
use serde_json::json;
/// Remove Hot Pixels (#1345) is on for a newly imported raw and off for everything else, and an edit saved
/// before the box existed reads as off, so it renders as it did.
#[test]
fn hot_pixel_box_is_on_for_new_raws_only() {
assert!(DevelopSettings::for_raw(5500.0, 10.0).detail.nr_outliers);
assert!(!DevelopSettings::default().detail.nr_outliers);
let mut saved = DevelopSettings::for_raw(5500.0, 10.0).to_json();
let detail = saved.get_mut("detail").and_then(|d| d.as_object_mut()).unwrap();
assert!(detail.remove("nr_outliers").is_some());
let read = DevelopSettings::from_json(&saved).unwrap();
assert!(!read.detail.nr_outliers);
assert_eq!(read.detail.nr_color, 25.0, "the rest of the saved edit is kept");
assert_ne!(read.hash64(), DevelopSettings::for_raw(5500.0, 10.0).hash64(), "cached renders are told apart");
// off is omitted: an edit saved before the box keeps its JSON, and so its hash and cached thumbnails
assert_eq!(read.to_json(), saved);
// copying Detail still carries the box when it is off
let copied = crate::extract_groups(&read, &[crate::SettingsGroup::Detail]);
assert_eq!(copied["detail"]["nr_outliers"], false);
let mut target = DevelopSettings::for_raw(5500.0, 10.0).to_json();
crate::presets::deep_merge(&mut target, &copied);
assert!(!DevelopSettings::from_json(&target).unwrap().detail.nr_outliers);
// the Detail eye switches it off for the decode too, and Reset Detail resets it like the sliders
let mut raw = DevelopSettings::for_raw(5500.0, 10.0);
assert!(raw.removes_hot_pixels());
raw.set_section_enabled("detail", false);
assert!(!raw.removes_hot_pixels());
raw.set_section_enabled("detail", true);
raw.reset_section(Section::Detail);
assert!(!raw.detail.nr_outliers && !raw.removes_hot_pixels());
}
#[test]
fn serde_roundtrip_default_and_edited() {
let mut s = DevelopSettings::default();
@@ -271,6 +352,54 @@ mod tests {
assert_eq!(s.grading.blending, 50.0);
}
/// Settings with one colour-range mask of `n` distinct samples (built in code, so not capped).
fn color_range_settings(n: usize) -> DevelopSettings {
let samples = (0..n).map(|i| [i as f64 / 1000.0, 0.1, -0.1]).collect();
let mut s = DevelopSettings::default();
s.masks.push(Mask {
id: 1,
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: MaskShape::ColorRange { samples, refine: 50.0 } }],
..Default::default()
});
s
}
fn color_range_samples(s: &DevelopSettings) -> &[[f64; 3]] {
match s.masks.first().and_then(|m| m.components.first()).map(|c| &c.shape) {
Some(MaskShape::ColorRange { samples, .. }) => samples,
other => panic!("expected a colour range, got {other:?}"),
}
}
/// Issue #2556: `mask.add`/`mask.update` capped a colour range's samples, but a sidecar `lc:settings`, a
/// preset, `develop.merge`, `render --settings` or a catalog / history load took any number (render cost is
/// pixels x samples). Every load now keeps the first [`MAX_COLOR_RANGE_SAMPLES`], in order.
#[test]
fn color_range_samples_are_capped_however_settings_load() {
let big = color_range_settings(1000);
let want = &color_range_samples(&big)[..MAX_COLOR_RANGE_SAMPLES];
let v = big.to_json();
let loaded = DevelopSettings::from_json(&v).unwrap();
assert_eq!(color_range_samples(&loaded).len(), MAX_COLOR_RANGE_SAMPLES);
assert_eq!(color_range_samples(&loaded), want);
let from_str: DevelopSettings = serde_json::from_str(&v.to_string()).unwrap();
assert_eq!(color_range_samples(&from_str), want);
// `develop.merge`, `render --settings` and presets merge a partial
let merged = DevelopSettings::default().merged(&json!({"masks": v["masks"]})).unwrap();
assert_eq!(color_range_samples(&merged), want);
let preset =
Preset { id: "p".into(), name: "P".into(), group: "G".into(), settings: json!({"masks": v["masks"]}), favorite: false, builtin: false };
assert_eq!(color_range_samples(&preset.apply(&DevelopSettings::default(), 1.0)), want);
// a capped list round-trips, and a short one is unchanged
assert_eq!(DevelopSettings::from_json(&loaded.to_json()).unwrap(), loaded);
let few = color_range_settings(2);
assert_eq!(DevelopSettings::from_json(&few.to_json()).unwrap(), few);
// a list that isn't samples is still refused
let mut bad = v.clone();
bad["masks"][0]["components"][0]["shape"]["samples"] = json!([[0.1, 0.2]]);
assert!(DevelopSettings::from_json(&bad).is_err());
}
#[test]
fn merge_partial() {
let s = DevelopSettings::default();
@@ -316,6 +445,26 @@ mod tests {
assert!(s.is_unedited());
}
#[test]
fn resetting_the_profile_section_restores_the_default_profile() {
// the chosen creative profile is not a control, so resetting the section must restore it too
let mut s = DevelopSettings::default();
s.profile.id = "lc.muted.matte-soft".into();
s.profile.amount = 40.0;
s.reset_section(Section::Profile);
assert_eq!(s.profile.id, "lc.color", "the creative profile is reset to the default one");
assert_eq!(s.profile.amount, 100.0);
}
#[test]
fn resetting_the_profile_section_clears_the_camera_local_tone() {
// the camera's local tone mapping is not a control either: a Profile reset switches it off
let mut s = DevelopSettings::default();
s.profile.camera_local_tone = true;
s.reset_section(Section::Profile);
assert!(!s.profile.camera_local_tone);
}
#[test]
fn section_toggles() {
let mut s = DevelopSettings::default();
@@ -363,4 +512,16 @@ mod tests {
s.reset_section(Section::Detail);
assert_eq!(s.enhance.denoise_on, None);
}
#[test]
fn next_mask_id_after_the_highest_id_is_unused() {
// ids come from files, pastes and agents: one at the limit must not overflow (a panic in
// debug builds) or wrap to an id another mask has
let mut s = DevelopSettings::default();
assert_eq!(s.next_mask_id(), 1);
s.masks = vec![Mask { id: u32::MAX, ..Default::default() }, Mask { id: 1, ..Default::default() }];
let next = s.next_mask_id();
assert!(!s.masks.iter().any(|m| m.id == next), "{next}");
assert_eq!(next, 2);
}
}
+331 -20
View File
@@ -1,8 +1,12 @@
//! Presets and copy/paste subsets.
//!
//! A preset is a *partial* settings object (JSON) — only the groups it includes. Applying merges it
//! into the photo's settings; `amount` (0..200 %) interpolates numeric values between the current
//! settings and the preset's. Copy/paste/sync use the same group selection ([`SettingsGroup`]).
//! A preset is a *partial* settings object (JSON) — only the settings it names. Applying it changes
//! exactly the settings it names (a leaf: a number, a flag, a name; an array is one leaf): each is
//! computed from the photo's *original* state (its import settings, when known) and the preset's
//! value, and replaces the photo's value; every other setting keeps the photo's value (issue
//! #2159). `amount` (0..200 %) moves each named number between the original and the preset's
//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the
//! current settings as before.
//!
//! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets
//! made from a photo never carry it, so the photos they change keep their own. A partial that names
@@ -126,7 +130,7 @@ impl SettingsGroup {
/// The subset of `s` covering `groups`, as a partial JSON object.
pub fn extract_groups(s: &DevelopSettings, groups: &[SettingsGroup]) -> Value {
let full = s.to_json();
let full = s.to_json_for_merge();
let mut out = Map::new();
for g in groups {
for k in g.keys() {
@@ -186,11 +190,79 @@ fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value {
/// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped
/// through the control specs, as every merge does ([`DevelopSettings::merged`]).
pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings {
let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json(), partial, amount)) };
let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json_for_merge(), partial, amount)) };
// (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`)
s.merged(&patch).unwrap_or_else(|_| s.clone())
}
/// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on
/// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and
/// a preset without them leaves the photo's alone.
const REPAIR_KEYS: [&str; 3] = ["masks", "spots", "red_eye"];
/// The settings `settings` (a partial JSON object) names, applied to `current` at `amount`: each
/// named setting is computed from `original` (the photo's import state) and the preset's value,
/// and replaces the photo's value (issue #2159). Every setting the preset does not name keeps the
/// photo's current value, edits included. Pixel repairs compose on the photo's own values, as they
/// always have.
fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings: &Value, amount: f64) -> DevelopSettings {
// At 100 % the preset's own values apply as they are, and `original` is not read. The presets
// panel calls this for every visible row on every frame, so the scaling base is built below only.
if (amount - 1.0).abs() < 1e-9 {
return current.merged(settings).unwrap_or_else(|_| current.clone());
}
let cur = current.to_json();
let mut base = original.to_json();
if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) {
for k in REPAIR_KEYS {
if let Some(v) = c.get(k) {
b.insert(k.to_string(), v.clone());
}
}
}
let composed = match settings.as_object() {
Some(patch) => Value::Object(interpolate_object(base.as_object(), patch, amount)),
None => Value::Object(Map::new()),
};
// `merged` deep-merges: the named settings replace, everything else stays as `current` has it
current.merged(&composed).unwrap_or_else(|_| current.clone())
}
/// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in
/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there.
fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Value>, t: f64) -> Map<String, Value> {
let mut out = Map::new();
for (k, pv) in patch {
let bv = base.and_then(|b| b.get(k));
let v = match pv {
Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))),
_ => interpolate_leaf(bv, pv, t),
};
if let Some(v) = v {
out.insert(k.clone(), v);
}
}
out
}
/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's
/// at half amount and up, and below it take the base's value. A null in the base is the baseline
/// value the import state recorded (a cleared option, such as a free crop aspect): below half
/// amount it applies and clears the photo's value, as the amount contract promises. A null the
/// preset writes is a value like any other, so it applies at half amount and up (a preset can
/// clear an option field such as a crop aspect).
fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value> {
match (base, patch) {
// integer fields (the grain seed, ids) are discrete like strings: see `scale_patch`
(Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => {
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number)
}
_ if t >= 0.5 => Some(patch.clone()),
_ => base.cloned(),
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Preset {
pub id: String,
@@ -209,32 +281,49 @@ impl Preset {
pub fn from_settings(id: &str, name: &str, group: &str, s: &DevelopSettings, groups: &[SettingsGroup]) -> Preset {
Preset { id: id.into(), name: name.into(), group: group.into(), settings: extract_groups(s, groups), favorite: false, builtin: false }
}
/// Apply at `amount` (1.0 = 100 %). Masks in the preset are added to the photo's own (ones it
/// already has are skipped), their effect scaled by the amount.
/// Apply at `amount` (1.0 = 100 %), with `s` as both the photo's current and its original
/// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch
/// bases. Masks in the preset are added to the photo's own (ones it already has are skipped),
/// their effect scaled by the amount.
pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings {
self.apply_on(s, s, amount)
}
/// Apply at `amount` (1.0 = 100 %), composing on `original` (the photo's import state, or the
/// photo's current settings when that is not known): each setting the preset names is computed
/// from `original` and the preset's value, `amount` moving it between the two, and replaces the
/// photo's value. Every setting the preset does not name keeps `current`'s value, and so do
/// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the
/// preset are added to the photo's own (ones it already has are skipped), their effect scaled
/// by the amount. A second preset therefore restores what the first one changed in the
/// settings it names (issue #2159), and nothing it leaves out.
pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings {
let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else {
return apply_partial(s, &self.settings, amount);
return compose_named(current, original, &self.settings, amount);
};
let mut rest = self.settings.clone();
if let Some(o) = rest.as_object_mut() {
o.remove("masks");
}
let mut out = apply_partial(s, &rest, amount);
let mut next = out.masks.iter().map(|m| m.id).max().unwrap_or(0);
for m in masks {
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
continue;
}
next += 1;
m.id = next;
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
out.masks.push(m);
}
let mut out = compose_named(current, original, &rest, amount);
add_masks(&mut out, masks, amount);
out
}
}
/// The preset's masks, added to the photo's own (ones it already has are skipped), their effect
/// scaled by the amount.
fn add_masks(out: &mut DevelopSettings, masks: &[Value], amount: f64) {
for m in masks {
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
continue;
}
m.id = out.next_mask_id();
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
out.masks.push(m);
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -287,10 +376,232 @@ mod tests {
}
}
/// A preset changes only the settings it names: a setting in a group it styles but does not
/// name keeps the photo's value, and so does a whole group it leaves out.
#[test]
fn apply_on_changes_only_the_settings_it_names() {
let mut current = DevelopSettings::default();
current.light.exposure = 2.0;
current.light.blacks = -30.0;
current.effects.clarity = 30.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"contrast": 12.0}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 1.0);
assert_eq!(out.light.contrast, 12.0);
assert_eq!(out.light.exposure, 2.0, "a setting the preset doesn't name keeps the photo's value");
assert_eq!(out.light.blacks, -30.0, "a setting in the same group, not named, keeps the photo's value");
assert_eq!(out.effects.clarity, 30.0, "a group the preset doesn't name is untouched");
}
/// A partial preset that names one colour of the mixer leaves the other colours, and the
/// unnamed settings of the colour it names, as the photo has them.
#[test]
fn apply_on_keeps_the_mixer_colours_it_does_not_name() {
let mut current = DevelopSettings::default();
current.mixer.red.sat = 20.0;
current.mixer.blue.hue = 15.0;
current.mixer.blue.sat = 5.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"mixer": {"blue": {"sat": 15.0, "lum": -25.0}}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 1.0);
assert_eq!(out.mixer.red.sat, 20.0, "a colour the preset doesn't name");
assert_eq!(out.mixer.blue.hue, 15.0, "a setting of a named colour that the preset doesn't name");
assert_eq!((out.mixer.blue.sat, out.mixer.blue.lum), (15.0, -25.0));
}
/// The white balance is not one setting: a preset that names only the temperature keeps the
/// photo's tint.
#[test]
fn apply_on_keeps_the_white_balance_fields_it_does_not_name() {
let mut current = DevelopSettings::default();
current.wb.temp = 6000.0;
current.wb.tint = 12.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"wb": {"temp": 5000.0}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 1.0);
assert_eq!((out.wb.temp, out.wb.tint), (5000.0, 12.0));
}
/// A preset's amount 0 changes nothing when the original is the photo's current settings (no
/// import state is recorded for the photo), and any other amount moves the named settings
/// from where the photo has them.
#[test]
fn apply_on_without_an_import_state_scales_from_the_current_settings() {
let mut current = DevelopSettings::default();
current.light.exposure = 2.0;
current.light.blacks = -30.0;
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"exposure": 0.45, "contrast": 12.0}}),
favorite: false,
builtin: false,
};
assert_eq!(p.apply_on(&current, &current, 0.0), current, "amount 0 applies nothing");
let half = p.apply_on(&current, &current, 0.5);
assert!((half.light.exposure - 1.225).abs() < 1e-9, "{}", half.light.exposure);
assert_eq!(half.light.blacks, -30.0);
}
/// An unresolved `crs:Look` reference (its profile object has no id; the importer leaves
/// `look` in it) changes nothing: the photo keeps its own profile.
#[test]
fn an_unresolved_profile_reference_keeps_the_photos_profile() {
let mut current = DevelopSettings::default();
current.profile.id = "lc.vivid".into();
current.profile.amount = 60.0;
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"profile": {"look": {"name": "Not imported", "amount": 100.0}}, "light": {"contrast": 12.0}}),
favorite: false,
builtin: false,
};
for amount in [1.0, 0.5] {
let out = p.apply_on(&current, &current, amount);
assert_eq!((out.profile.id.as_str(), out.profile.amount), ("lc.vivid", 60.0), "amount {amount}");
}
}
/// The amount interpolates between the original and the preset, not between the visible
/// values and the preset: a preset at 50 % looks the same however the photo was edited before.
#[test]
fn apply_on_scales_against_the_original() {
let mut current = DevelopSettings::default();
current.light.exposure = 2.0;
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"exposure": 0.45}}),
favorite: false,
builtin: false,
};
let out = p.apply_on(&current, &original, 0.5);
assert!((out.light.exposure - 0.225).abs() < 1e-9, "{}", out.light.exposure);
}
/// Pixel repairs are the photo's own: a preset's are patched in, and one without them never
/// restores the original's.
#[test]
fn apply_on_patches_pixel_repairs_into_the_current_ones() {
let current = DevelopSettings {
spots: serde_json::from_value(json!([{"mode": "heal", "points": [[0.5, 0.5]], "size": 0.05, "feather": 50.0, "opacity": 100.0}]))
.unwrap(),
..Default::default()
};
let original = DevelopSettings::default();
let none = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"light": {"contrast": 10.0}}),
favorite: false,
builtin: false,
};
let out = none.apply_on(&current, &original, 1.0);
assert_eq!(out.spots.len(), 1, "the photo's spot survives a preset without spots");
let clearing = Preset {
id: "q".into(),
name: "Q".into(),
group: "G".into(),
settings: json!({"light": {"contrast": 10.0}, "spots": []}),
favorite: false,
builtin: false,
};
let out = clearing.apply_on(&current, &original, 1.0);
assert_eq!(out.spots.len(), 0, "a preset that names spots replaces them, as before");
}
/// A null a preset writes into an option field (here a crop aspect: null is "free") is the
/// preset's value, so it clears the photo's aspect from half amount up, as any value of the
/// preset does; below half amount the import baseline applies, which here is null as well.
#[test]
fn a_preset_null_clears_an_option_field_from_half_amount() {
let mut current = DevelopSettings::default();
current.crop.aspect = Some((3, 2));
let original = DevelopSettings::default(); // the import state has no aspect
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"crop": {"aspect": null}}),
favorite: false,
builtin: false,
};
for amount in [1.0, 0.7, 0.5] {
assert_eq!(p.apply_on(&current, &original, amount).crop.aspect, None, "amount {amount}: the preset's null clears the aspect");
}
assert_eq!(p.apply_on(&current, &original, 0.3).crop.aspect, None, "below half amount the import baseline (no aspect) applies");
}
/// The import state has no aspect, and that null is the baseline below half amount (the amount
/// contract: a named setting moves between the import state and the preset's value); from half
/// amount the preset's aspect applies.
#[test]
fn a_null_in_the_original_is_the_baseline_below_half_amount() {
let mut current = DevelopSettings::default();
current.crop.aspect = Some((3, 2));
let original = DevelopSettings::default();
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "G".into(),
settings: json!({"crop": {"aspect": [16, 9]}}),
favorite: false,
builtin: false,
};
assert_eq!(p.apply_on(&current, &original, 0.4).crop.aspect, None, "40 %: the import baseline (no aspect) applies");
assert_eq!(p.apply_on(&current, &original, 0.6).crop.aspect, Some((16, 9)), "60 %: the preset's aspect applies");
}
#[test]
fn deep_merge_objects() {
let mut a = json!({"x": {"a": 1, "b": 2}, "y": [1]});
deep_merge(&mut a, &json!({"x": {"b": 3}, "y": [2, 3]}));
assert_eq!(a, json!({"x": {"a": 1, "b": 3}, "y": [2, 3]}));
}
#[test]
fn preset_masks_get_unused_ids_after_a_mask_id_at_the_limit() {
let s = DevelopSettings { masks: vec![crate::Mask { id: u32::MAX, name: "Theirs".into(), ..Default::default() }], ..Default::default() };
let p = Preset {
id: "p".into(),
name: "P".into(),
group: "User".into(),
settings: json!({"masks": [{"id": 7, "name": "A"}, {"id": 7, "name": "B"}]}),
favorite: false,
builtin: false,
};
let out = p.apply(&s, 1.0);
let mut ids: Vec<u32> = out.masks.iter().map(|m| m.id).collect();
assert_eq!(ids.len(), 3);
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), 3, "{:?}", out.masks);
}
}
+132 -5
View File
@@ -1,6 +1,9 @@
//! Model segmentations stored with a mask ([`SegMask`]), so rendering never needs the model.
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashMap;
use serde::{Deserialize, Serialize, Serializer};
/// Logits are stored in steps of 1/`SCALE`, clamped to ±127/`SCALE` (≈ ±15.9: a sigmoid of
/// 1 − 1.2e-7, i.e. fully in or out).
@@ -13,15 +16,26 @@ pub const MAX_SIDE: usize = 1024;
/// normalized `((x + 0.5) / side, (y + 0.5) / side)`), quantized to `i8`, deflated and base64
/// encoded. Coverage at a point is the sigmoid of the bilinearly sampled logit, so edges stay
/// smooth at any output size.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct SegMask {
pub side: u32,
/// The grid's bytes (quantized, deflated, base64), unless this is a reference into the
/// snapshot's shared grid table (`grid` is set and `data` is empty).
#[serde(default)]
pub data: String,
/// The part of the image the grid covers, normalized `[x0, y0, x1, y1]` (`None` = all of
/// it). A zoomed-in pass over one object covers just its surroundings, at a higher
/// resolution than a pass over the whole photo.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rect: Option<[f64; 4]>,
/// Index into the catalog snapshot's shared grid table (`Catalog::grids`) this mask refers
/// to instead of carrying its own `data`. A serialization detail of snapshots only: the
/// snapshot writer sets it (through the interner, into its own table), `Catalog::repair`
/// resolves it when a snapshot is read, and no other serialization writes it. A `grid` that
/// arrives from any other document (a command, a preset, XMP, a log record) is read but
/// never written back, so it cannot point a snapshot at another mask's grid.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grid: Option<u32>,
}
impl SegMask {
@@ -29,7 +43,7 @@ impl SegMask {
pub fn from_logits(side: usize, logits: &[f32]) -> SegMask {
let q: Vec<u8> = logits.iter().take(side * side).map(|l| ((l * SCALE).round().clamp(-127.0, 127.0) as i8) as u8).collect();
let z = miniz_oxide::deflate::compress_to_vec(&q, 8);
SegMask { side: side as u32, data: base64_encode(&z), rect: None }
SegMask { side: side as u32, data: base64_encode(&z), rect: None, grid: None }
}
/// From `side × side` logits over the part `rect` of the image.
@@ -55,6 +69,63 @@ impl SegMask {
}
}
// The grid table a snapshot serialization refers to: each distinct grid's data → its index.
thread_local! {
static INTERNER: RefCell<Option<HashMap<String, u32>>> = const { RefCell::new(None) };
}
/// Serializes masks as references into a shared grid table (`grid` = index, `data` omitted)
/// while `f` runs, one thread at a time (snapshot writes). Nested calls are ignored (`None`):
/// the outermost writer owns the table.
pub fn with_grid_interner<T>(map: HashMap<String, u32>, f: impl FnOnce() -> T) -> Option<T> {
INTERNER.with(|i| {
if i.borrow().is_some() {
return None;
}
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
INTERNER.with(|j| *j.borrow_mut() = None);
}
}
*i.borrow_mut() = Some(map);
let _guard = Guard;
Some(f())
})
}
impl Serialize for SegMask {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
// While a snapshot is being written with a shared grid table, a mask whose exact bytes
// are in the table refers to it by index instead of repeating the blob (issue #2154).
if !self.data.is_empty()
&& let Some(id) = INTERNER.with(|i| i.borrow().as_ref().and_then(|m| m.get(&self.data).copied()))
{
let len = if self.rect.is_some() { 3 } else { 2 };
let mut map = serializer.serialize_map(Some(len))?;
map.serialize_entry("side", &self.side)?;
map.serialize_entry("grid", &id)?;
if let Some(rect) = self.rect {
map.serialize_entry("rect", &rect)?;
}
return map.end();
}
// Without a table hit: exactly the pre-v10 derived form (field order and skips included),
// so every serialization that doesn't dedup keeps its bytes (`hash64`, cache keys). `grid`
// is never written here: a value read from some document is dropped on save, and only the
// interner above can write a reference (into the table of the snapshot being written).
let len = 2 + usize::from(self.rect.is_some());
let mut map = serializer.serialize_map(Some(len))?;
map.serialize_entry("side", &self.side)?;
map.serialize_entry("data", &self.data)?;
if let Some(rect) = self.rect {
map.serialize_entry("rect", &rect)?;
}
map.end()
}
}
/// Most zoomed-in detail patches one AI mask component keeps (the app makes one; each costs a
/// decode per render, so a hostile document can't make rendering explode).
pub const MAX_DETAIL: usize = 4;
@@ -104,9 +175,14 @@ fn base64_encode(bytes: &[u8]) -> String {
fn base64_decode(s: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() / 4 * 3);
let (mut acc, mut bits) = (0u32, 0u32);
let mut padded = false;
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
if c == b'=' {
break;
padded = true;
continue;
}
if padded {
return None;
}
let v = B64.iter().position(|b| *b == c)? as u32;
acc = (acc << 6) | v;
@@ -117,6 +193,9 @@ fn base64_decode(s: &str) -> Option<Vec<u8>> {
acc &= (1 << bits) - 1;
}
}
if bits == 6 {
return None;
}
Some(out)
}
@@ -133,6 +212,10 @@ mod tests {
assert_eq!(base64_encode(b"Man"), "TWFu");
assert_eq!(base64_encode(b"Ma"), "TWE=");
assert!(base64_decode("TW!u").is_none());
assert!(base64_decode("Z").is_none());
assert!(base64_decode("Zm9vY").is_none());
assert!(base64_decode("Zg==!!!not-base64").is_none());
assert_eq!(base64_decode("Zg==\n").unwrap(), b"f");
}
#[test]
@@ -177,7 +260,51 @@ mod tests {
assert!(m.logits().is_none(), "size mismatch");
m.side = 100_000;
assert!(m.logits().is_none(), "absurd size");
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None }.logits().is_none());
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None, grid: None }.logits().is_none());
assert!(SegMask { rect: Some([0.5, 0.0, 0.2, 1.0]), ..SegMask::from_logits(2, &[0.0; 4]) }.bounds().is_none());
}
/// A `grid` read from a document is never written outside the snapshot interner, with or
/// without data: the bytes stay the pre-v10 form, so `hash64` and cache keys don't depend on
/// a stray value (issue #2154).
#[test]
fn stray_grid_is_never_written_outside_the_interner() {
let empty = SegMask { side: 4, data: String::new(), rect: None, grid: None };
let stray = SegMask { grid: Some(3), ..empty.clone() };
assert_eq!(serde_json::to_string(&stray).unwrap(), "{\"side\":4,\"data\":\"\"}");
assert_eq!(serde_json::to_string(&stray).unwrap(), serde_json::to_string(&empty).unwrap());
let with_data = SegMask { grid: Some(3), ..SegMask::from_logits(4, &[1.0; 16]) };
assert!(!serde_json::to_string(&with_data).unwrap().contains("grid"), "no grid key outside the interner");
}
/// Without the snapshot interner the JSON is exactly the derived form it always was; with
/// it, a pooled grid serializes as an index and the data is left to the table (issue #2154).
#[test]
fn serialization_refs_only_under_the_interner() {
let m = SegMask::from_logits(4, &[1.0; 16]);
let plain = serde_json::to_string(&m).unwrap();
assert_eq!(plain, format!("{{\"side\":4,\"data\":\"{}\"}}", m.data), "no interner: unchanged bytes");
let with_rect = SegMask { rect: Some([0.0, 0.0, 0.5, 0.5]), ..m.clone() };
assert_eq!(serde_json::to_string(&with_rect).unwrap(), format!("{{\"side\":4,\"data\":\"{}\",\"rect\":[0.0,0.0,0.5,0.5]}}", m.data));
let mut table = std::collections::HashMap::new();
table.insert(m.data.clone(), 3u32);
let referenced = with_grid_interner(table, || serde_json::to_string(&m).unwrap()).unwrap();
assert_eq!(referenced, "{\"side\":4,\"grid\":3}", "pooled grid: an index, no data");
// a grid the table doesn't hold, and an empty-data mask, stay inline
let other = SegMask::from_logits(2, &[0.0; 4]);
let mixed = with_grid_interner(std::collections::HashMap::new(), || serde_json::to_string(&other).unwrap()).unwrap();
assert_eq!(mixed, format!("{{\"side\":2,\"data\":\"{}\"}}", other.data));
// the interner is gone afterwards: serialization is inline again
assert_eq!(serde_json::to_string(&m).unwrap(), plain);
// nested calls are ignored: the outer writer keeps its table
let outer_table = std::collections::HashMap::from([(m.data.clone(), 0u32)]);
let nested = with_grid_interner(outer_table, || {
let inner_table = std::collections::HashMap::from([(other.data.clone(), 1u32)]);
(with_grid_interner(inner_table, || serde_json::to_string(&other).unwrap()), serde_json::to_string(&m).unwrap())
})
.unwrap();
assert_eq!(nested.0, None, "the nested writer is refused");
assert_eq!(nested.1, "{\"side\":4,\"grid\":0}");
}
}
+170 -4
View File
@@ -84,17 +84,33 @@ pub enum Process {
/// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base
/// is taken of a fine median of log luminance (issue #632).
V2,
/// Pixel-scale sharpening with working Radius and Detail controls.
V3,
/// V3, with Contrast and Blacks on a raw's camera look calibrated to Lightroom: the
/// camera curve keeps V2 Whites and fitted pointwise operators follow it
/// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`).
V4,
/// V4, with a raw's tone curve rolling off into white in stops past its last fitted knot, so
/// highlights the sensor recorded keep their detail when Exposure lifts them (issue #1632).
V5,
/// V5, with colour noise reduction on the linear colour differences R−Y and B−Y, leaving Y alone, with
/// edge-aware weights from a denoised guide and a brake for isolated colour specks (issue #815).
V6,
}
impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 2] = [Process::V1, Process::V2];
pub const LATEST: Process = Process::V2;
pub const ALL: [Process; 6] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6];
pub const LATEST: Process = Process::V6;
pub const fn version(self) -> ProcessVersion {
match self {
Process::V1 => ProcessVersion(1),
Process::V2 => ProcessVersion(2),
Process::V3 => ProcessVersion(3),
Process::V4 => ProcessVersion(4),
Process::V5 => ProcessVersion(5),
Process::V6 => ProcessVersion(6),
}
}
}
@@ -134,6 +150,7 @@ pub struct DevelopSettings {
pub orientation: Orientation,
pub masks: Vec<Mask>,
pub spots: Vec<Spot>,
/// Red eye corrections; the first [`MAX_RED_EYES`] render.
pub red_eye: Vec<RedEye>,
pub lens_blur: LensBlur,
pub enhance: Enhance,
@@ -623,6 +640,13 @@ pub struct Detail {
pub nr_color: f64,
pub nr_color_detail: f64,
pub nr_color_smoothness: f64,
/// Replace single outlier photosites (noise spikes far above all their same-colour neighbours) in the
/// raw mosaic before demosaicing, so they do not become coloured dots (#1345). On for newly imported
/// raws ([`crate::DevelopSettings::for_raw`]); off for edits saved before it existed, so they look the
/// same. Raw files only. Omitted when off, so settings saved before it keep their JSON (and hash, and with it
/// their cached thumbnails).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub nr_outliers: bool,
}
impl Default for Detail {
@@ -640,6 +664,7 @@ impl Default for Detail {
nr_color: 0.0,
nr_color_detail: 50.0,
nr_color_smoothness: 50.0,
nr_outliers: false,
}
}
}
@@ -698,11 +723,32 @@ impl Default for Optics {
pub struct EmbeddedLens {
pub warp: Option<EmbeddedWarp>,
pub vignette: Option<EmbeddedVignette>,
/// Where the correction came from: the file itself, or a lens database looked up by the
/// lens named in the file (what the Optics panel says is loaded).
#[serde(skip_serializing_if = "LensSource::is_file")]
pub source: LensSource,
/// A DNG 1.6 `WarpRectilinear2` chain (up to [`WARP_STAGES`] stages, in `OpcodeList3` order; each stage warps
/// the result of the one before it). When any is set, `warp` is `None`: the chain holds every warp opcode.
pub stages: [Option<EmbeddedWarpStage>; WARP_STAGES],
}
/// Where an [`EmbeddedLens`] came from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LensSource {
/// The file's own correction (DNG opcodes, a camera's correction a raw reader converts).
#[default]
File,
/// A profile from a lensfun-format lens database, matched by the lens named in the file.
Database,
}
impl LensSource {
pub fn is_file(&self) -> bool {
*self == LensSource::File
}
}
/// Most warp stages an [`EmbeddedLens`] chain keeps.
pub const WARP_STAGES: usize = 3;
@@ -921,6 +967,35 @@ impl Default for BrushStroke {
}
}
/// Most samples a colour-range mask keeps. It compares every pixel against every sample, so render and export cost
/// is pixels x samples; the interactive sampler stops at 5, and a sidecar, preset or `mask.add` with thousands could
/// stall a render or lose the GPU device (issue #2556).
pub const MAX_COLOR_RANGE_SAMPLES: usize = 64;
/// Deserialize a colour range's samples, keeping the first [`MAX_COLOR_RANGE_SAMPLES`] (the rest are skipped without
/// being stored), however the settings arrive: sidecar, catalog, history, preset or merge.
fn de_color_range_samples<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<[f64; 3]>, D::Error> {
struct Capped;
impl<'de> serde::de::Visitor<'de> for Capped {
type Value = Vec<[f64; 3]>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of OkLab colours")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<[f64; 3]>, A::Error> {
let mut out = Vec::new();
while out.len() < MAX_COLOR_RANGE_SAMPLES {
match seq.next_element::<[f64; 3]>()? {
Some(s) => out.push(s),
None => return Ok(out),
}
}
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
Ok(out)
}
}
d.deserialize_seq(Capped)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum MaskShape {
@@ -941,8 +1016,9 @@ pub enum MaskShape {
feather: f64,
invert: bool,
},
/// Colour range: sampled OkLab colours with a refine amount 0..100.
/// Colour range: sampled OkLab colours (at most [`MAX_COLOR_RANGE_SAMPLES`]) with a refine amount 0..100.
ColorRange {
#[serde(deserialize_with = "de_color_range_samples")]
samples: Vec<[f64; 3]>,
refine: f64,
},
@@ -1023,15 +1099,101 @@ pub struct Mask {
/// Refine Edges 0..100: the mask's edges snap to the photo's (guided filter).
#[serde(skip_serializing_if = "is_zero")]
pub refine: f64,
/// Where its coordinates (gradients, brush strokes, AI selections) live: `true`, on the photo as
/// shot (user orientation, before lens corrections, Upright and Transform), so the mask stays
/// on the same content whatever those do; `false`, a mask from before that, on the corrected
/// frame. Read as `false` when absent; [`Mask::default`] (every new mask) is `true`, and an
/// edit converts an old one (`lightcraft_pipeline::mask_space::attach`).
#[serde(default, skip_serializing_if = "is_false")]
pub on_photo: bool,
}
fn is_zero(v: &f64) -> bool {
*v == 0.0
}
fn is_false(v: &bool) -> bool {
!*v
}
impl Default for Mask {
fn default() -> Self {
Self { id: 0, name: "Mask 1".into(), visible: true, invert: false, components: Vec::new(), adjust: LocalAdjustments::default(), refine: 0.0 }
Self {
id: 0,
name: "Mask 1".into(),
visible: true,
invert: false,
components: Vec::new(),
adjust: LocalAdjustments::default(),
refine: 0.0,
on_photo: true,
}
}
}
impl DevelopSettings {
/// Calls `f` for every segmentation grid stored in these settings (the `seg` and `detail`
/// of Object and Prompt mask shapes).
pub fn visit_seg_masks(&self, f: &mut impl FnMut(&crate::SegMask)) {
for mask in &self.masks {
for component in &mask.components {
visit_shape(&component.shape, f);
}
}
}
/// [`DevelopSettings::visit_seg_masks`] with mutable access (resolving references into a
/// snapshot's grid table).
pub fn visit_seg_masks_mut(&mut self, f: &mut impl FnMut(&mut crate::SegMask)) {
for mask in &mut self.masks {
for component in &mut mask.components {
visit_shape_mut(&mut component.shape, f);
}
}
}
}
fn visit_shape(shape: &MaskShape, f: &mut impl FnMut(&crate::SegMask)) {
match shape {
MaskShape::Object { seg, detail, .. } => {
if let Some(seg) = seg {
f(seg);
}
for d in detail {
f(d);
}
}
MaskShape::Prompt { seg, detail, .. } => {
if let Some(seg) = seg {
f(seg);
}
for d in detail {
f(d);
}
}
_ => {}
}
}
fn visit_shape_mut(shape: &mut MaskShape, f: &mut impl FnMut(&mut crate::SegMask)) {
match shape {
MaskShape::Object { seg, detail, .. } => {
if let Some(seg) = seg.as_mut() {
f(seg);
}
for d in detail {
f(d);
}
}
MaskShape::Prompt { seg, detail, .. } => {
if let Some(seg) = seg.as_mut() {
f(seg);
}
for d in detail {
f(d);
}
}
_ => {}
}
}
@@ -1069,6 +1231,10 @@ impl Default for Spot {
}
}
/// Most red eye / pet eye corrections a photo renders. Every output pixel goes through every eye, so render cost is
/// pixels x eyes; a sidecar, preset or agent with thousands could stall a render for hours (issue #2556).
pub const MAX_RED_EYES: usize = 64;
/// A red eye / pet eye correction: the user's ellipse (centre normalized, radii as fractions of
/// the long edge); the pupil inside it is found automatically.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+3
View File
@@ -40,6 +40,7 @@ log = { workspace = true }
ab_glyph = { workspace = true }
# Apply the font’s vertical substitutions and origins to Japanese watermarks.
harfrust = { version = "0.13", default-features = false, features = ["std"] }
unicode-normalization = "0.1"
unicode-segmentation = "1.13"
lightcraft-segment = { workspace = true, optional = true }
@@ -48,6 +49,8 @@ lightcraft-segment = { workspace = true, optional = true }
lightcraft-fetch = { workspace = true }
# capture-time parsing for face recognition (native only)
chrono = { workspace = true }
# free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys)
fs4 = { workspace = true }
[features]
# AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds.
+12 -1
View File
@@ -65,6 +65,7 @@ fn craft_fonts(dir: &Path, required: bool) -> Result<String, String> {
let manifest = dir.join("fonts/manifest.txt");
println!("cargo::rerun-if-changed={}", manifest.display());
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
let mut out = String::new();
let mut has_japanese_ui = false;
@@ -82,7 +83,17 @@ fn craft_fonts(dir: &Path, required: bool) -> Result<String, String> {
continue;
}
let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
println!("cargo::rerun-if-changed={}", path.display());
// a font is a file of the checkout: a manifest entry or a link reaching outside it would
// embed some other file of the build machine
if !path.starts_with(&root) || !path.is_file() {
return Err(format!("{file}: not a file inside {}", root.display()));
}
let shown = path.display().to_string();
// one cargo instruction per line: a line break in the path would print a second one
if shown.contains(['\n', '\r']) {
return Err(format!("{file}: the path contains a line break"));
}
println!("cargo::rerun-if-changed={shown}");
let scripts: Vec<String> = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect();
let _ = writeln!(
out,
+1 -1
View File
@@ -144,7 +144,7 @@ fn benchmark_load(args: &[String], n: usize, only: &str) {
}
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
let (loader, _) = lightcraft_engine::files::fs_hooks();
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560).expect("load"))));
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, Default::default()).expect("load"))));
}
}
+6 -1
View File
@@ -79,7 +79,12 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// a tone-only fallback for near-black scenes with too few colour pairs (#1587); DNG tone fitting uses a
/// lens-corrected proxy when the file carries lens opcodes; validated A7CR distortion, including the lens data
/// stored with each smart preview.
pub const LOOK_VERSION: u32 = 12;
/// 13: tone curves no steeper than a log-log slope of 4 between knots (#1904).
/// 13: the Canon CR3/CR2 camera JPEG read in the colour space of the Canon maker note (#2654).
/// 13: the sensor proxy of every per-file fit gets the embedded vignetting correction the render applies (Fujifilm
/// RAF; other makes with a lens database), so the render no longer applies it twice, at the position a lens warp samples;
/// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black.
pub const LOOK_VERSION: u32 = 13;
#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
+8 -6
View File
@@ -1,6 +1,6 @@
use super::look_fit::{fit_dng_tone, fit_preview};
use super::look_fit::{fit_dng_tone, fit_preview, look_proxies};
use super::mono::{fit_dark_tone, monochrome_look};
use super::proxy::{LensGeometry, proxies};
use super::proxy::LensGeometry;
use super::{CameraLook, CameraTone, CameraTransform, ColorData, D50, D65, Mat3, ProfileLook, REC2020, RawFormat, RawImage, ToneCurve, Xy, bradford};
/// Long edge of the sensor/JPEG proxy a single photo's look is fitted on (the acceptance gates
@@ -27,6 +27,7 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool {
| RawFormat::Pef
| RawFormat::Srw
| RawFormat::Orf
| RawFormat::Crw
| RawFormat::Mrw
| RawFormat::Erf
)
@@ -42,7 +43,8 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool {
/// as-shot white, the camera transform at it and the fitted look.
/// `lens` is the file's own lens-correction warp ([`lens_geometry`], read before the caller removes it from
/// `OpcodeList3`): the camera applied it to its JPEG, so the sensor proxy is warped the same way before pairing.
/// `embedded` is the file's embedded lens vignetting, for the DNG tone fit.
/// `embedded` is the file's embedded lens correction: its vignetting is applied to the sensor proxy of every fit, as
/// the render applies it.
pub(crate) fn starting_colour(
raw: &mut RawImage,
bytes: &[u8],
@@ -51,13 +53,13 @@ pub(crate) fn starting_colour(
) -> (Xy, CameraTransform, Option<CameraLook>) {
let (xy, t, look) = starting_colour_with(
raw,
|raw, t| fit_preview(raw, bytes, t, lens),
|raw, t| monochrome_look(raw, bytes, t, lens),
|raw, t| fit_preview(raw, bytes, t, lens, embedded),
|raw, t| monochrome_look(raw, bytes, t, lens, embedded),
|raw, t| {
if !file_local_look(raw.format) {
return None;
}
let (sensor, reference, clipped) = proxies(raw, bytes, t, PROXY, 0.0, lens)?;
let (sensor, reference, clipped) = look_proxies(raw, bytes, t, lens, embedded)?;
fit_dark_tone(&sensor, &reference, &clipped)
},
);
Loaded 100 of 669 files, more files were not shown because too many files have changed in this diff. Show more