diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml new file mode 100644 index 0000000000..dc4b511b9a --- /dev/null +++ b/.github/workflows/ci-windows.yml @@ -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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a309a9fb38..6b7f92a588 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: >- diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 0000000000..de64ad3ee4 --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1841ebe7a..a9d4d065a3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 }} diff --git a/.gitignore b/.gitignore index 8c2047fe6b..c88ace5fa4 100644 --- a/.gitignore +++ b/.gitignore @@ -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__/ diff --git a/AGENTS.md b/AGENTS.md index 4044a6563e..8d0ca31a60 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,25 +1,75 @@ + +## 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. + + +## 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. + + # 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-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone). - Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media. -- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. +- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. ## Testing & performance (do this often) - Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`, @@ -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: #"]` (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.]` 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. diff --git a/CLAUDE.md b/CLAUDE.md index 9b384fc6c2..43c994c2d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone). -- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media. -- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - -## 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 diff --git a/Cargo.lock b/Cargo.lock index 0bbb53883e..f85ed64dc7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index b46c4136d8..a667ca5712 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/README.md b/README.md index 6c556e46f4..21ff4306ec 100644 --- a/README.md +++ b/README.md @@ -259,7 +259,8 @@ lightcraft --control 7980 ~/Pictures/trip - **Command registry.** `engine.commands` lists the available commands; `develop.controls` lists every slider's range, default and current value. - **MCP server.** `lightcraft-cli mcp` exposes the command registry to Claude (or any MCP client), alongside - helpers for import, query, develop, mask, render (returned as an image) and export. It runs headless, or attached + helpers for import, query, develop, render (returned as an image) and export. Masks have no helper of their own: + create and edit them through `run_command` (e.g. `mask.add`). It runs headless, or attached to the running app with screenshots, clicks and gestures. See [docs/mcp.md](docs/mcp.md). ```sh @@ -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--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 "" /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. | | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | | | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | | | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | -| | **LightCraft** | **Photo library and raw development · you are here** | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | +| | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **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) | +| | **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. diff --git a/README.zh-hans.md b/README.zh-hans.md index fa782ba10f..a577a8db7b 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -241,7 +241,7 @@ lightcraft --control 7980 ~/Pictures/trip - **命令注册表。** `engine.commands` 列出可用命令;`develop.controls` 列出每个滑块的范围、 默认值和当前值。 - **MCP 服务器。** `lightcraft-cli mcp` 把命令注册表开放给 Claude(或任何 MCP 客户端), - 同时提供导入、查询、显影、蒙版、渲染(以图像返回)和导出的辅助工具。它既能无界面运行,也能附着 + 同时提供导入、查询、显影、渲染(以图像返回)和导出的辅助工具。蒙版没有专门的辅助工具,请通过 `run_command` 使用(例如 `mask.add`)。它既能无界面运行,也能附着 到正在运行的应用上,支持截图、点击和手势。见 [docs/mcp.md](docs/mcp.md)。 ```sh @@ -384,6 +384,34 @@ CARGO_BUILD_JOBS=1 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_LTO=false 设置可以覆盖继承的环境变量;应在本地调整打包配方或联系维护者,而不要假定给 `makepkg` 添加环境变量前缀就能优先生效。 +**Linux/Arch 构建故障:rustc 在 ThinLTO 阶段发生 SIGILL。** +在 [#2811](https://github.com/storytold/lightcraft/issues/2811) 中,报告者的 Arch Linux x86_64 +机器配备 AMD Ryzen 9 7900X3D 和 64 GB RAM,使用 rustc 1.99.0 / LLVM 23.1.1、AUR +`lightcraft` `0.7.1-1` 和 `0.13.0-1`、`RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`, +以及 release 设置 `opt-level=3`、`lto=thin`、`codegen-units=1`。 +`cargo build --frozen --release` 在编译到可执行 crate 时,rustc 因 signal 4 +(`SIGILL` / `ILL_ILLOPN`)崩溃。core dump 指向 LLVM 的 SelectionDAG / vector-combine +优化路径;编译器的具体根因尚未确定。这不表示所有使用这些硬件或工具链的机器都会失败。 +此故障与上文 [#1196](https://github.com/storytold/lightcraft/issues/1196) 中 16 GB 机器上的 +OOM 终止表现不同,没有证据表明两者根因相同。 + +直接使用 Cargo 从源码构建时,等价的单条命令 LTO 覆盖方式是: + +```sh +CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release +``` + +报告者 @rwarmstr 验证成功的是:在 **AUR PKGBUILD 的 `_srcenv()` 函数内部**导出 +`CARGO_PROFILE_RELEASE_LTO=off` 后重新构建上述两个版本,无需更改 `RUSTFLAGS`。 +报告者测试的是 AUR 配方,并未单独验证上面的直接 Cargo 命令。仅在 `makepkg` 前添加变量, +可能会被 PKGBUILD 自己的 export 覆盖;打包配方必须保留或设置该覆盖值。 +AUR 的 `!lto` 选项行为由 [#2813](https://github.com/storytold/lightcraft/issues/2813) 单独跟踪。 + +[Cargo 的 LTO 文档](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) 区分了 `false` +和 `off`:`false` 仍可能在代码生成单元之间执行 thin local LTO(除非 `codegen-units=1` +或 `opt-level=0`);`off` 则明确禁用 LTO。上文的低内存配方保持不变。 +此绕过方法仅针对受影响的构建,不是新的默认建议;禁用 LTO 可能改变性能、二进制大小和构建行为。 + **中文和日文文字**需要共享字体仓库,这是一个可选的构建输入(所有正式发布版都会包含它): ```sh @@ -392,7 +420,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft ``` 不指定它时,LightCraft 构建和运行的方式完全相同,只是中文和日文文字没有字形。字体从不提交到 -本仓库;见 [craftrules `standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)。 +本仓库。 **界面语言:** **编辑 → 语言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français)或 **设置 → 一般 → 语言**;选择立即生效并会保留。见 [docs/localization.md](docs/localization.md)。 diff --git a/README.zh-hant.md b/README.zh-hant.md index 07ac908d2d..f2c223897a 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -240,7 +240,7 @@ lightcraft --control 7980 ~/Pictures/trip - **指令註冊表。** `engine.commands` 列出可用的指令;`develop.controls` 列出每個滑桿的範圍、 預設值與目前值。 - **MCP 伺服器。** `lightcraft-cli mcp` 把指令註冊表開放給 Claude(或任何 MCP 用戶端), - 同時提供匯入、查詢、顯影、遮色片、算繪(以影像回傳)與匯出的輔助工具。它可以無介面執行,也可以附掛 + 同時提供匯入、查詢、顯影、算繪(以影像回傳)與匯出的輔助工具。遮色片沒有專屬的輔助工具,請透過 `run_command` 使用(例如 `mask.add`)。它可以無介面執行,也可以附掛 到正在執行的應用程式上,支援截圖、點擊與手勢。詳見 [docs/mcp.md](docs/mcp.md)。 ```sh @@ -402,6 +402,34 @@ CARGO_BUILD_JOBS=1 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_LTO=false PKGBUILD 可能會覆寫繼承的環境變數;請在本機調整打包腳本或聯絡維護者,而不要假設替 `makepkg` 加上環境變數前綴就能優先生效。 +**Linux/Arch 建置故障:rustc 在 ThinLTO 階段發生 SIGILL。** +在 [#2811](https://github.com/storytold/lightcraft/issues/2811) 中,回報者的 Arch Linux x86_64 +機器配備 AMD Ryzen 9 7900X3D 與 64 GB RAM,使用 rustc 1.99.0 / LLVM 23.1.1、AUR +`lightcraft` `0.7.1-1` 與 `0.13.0-1`、`RUSTFLAGS="-C opt-level=3 -C target-cpu=native"`, +以及 release 設定 `opt-level=3`、`lto=thin`、`codegen-units=1`。 +`cargo build --frozen --release` 在編譯到可執行 crate 時,rustc 因 signal 4 +(`SIGILL` / `ILL_ILLOPN`)當機。core dump 指向 LLVM 的 SelectionDAG / vector-combine +最佳化路徑;編譯器的具體根因尚未確定。這不表示所有使用這些硬體或工具鏈的機器都會失敗。 +此故障與上文 [#1196](https://github.com/storytold/lightcraft/issues/1196) 中 16 GB 機器上的 +OOM 終止表現不同,沒有證據顯示兩者根因相同。 + +直接使用 Cargo 從原始碼建置時,等價的單條指令 LTO 覆寫方式是: + +```sh +CARGO_PROFILE_RELEASE_LTO=off cargo build --frozen --release +``` + +回報者 @rwarmstr 驗證成功的是:在 **AUR PKGBUILD 的 `_srcenv()` 函式內部**匯出 +`CARGO_PROFILE_RELEASE_LTO=off` 後重新建置上述兩個版本,無須變更 `RUSTFLAGS`。 +回報者測試的是 AUR 腳本,並未單獨驗證上面的直接 Cargo 指令。僅在 `makepkg` 前加上變數, +可能會被 PKGBUILD 自己的 export 覆寫;打包腳本必須保留或設定該覆寫值。 +AUR 的 `!lto` 選項行為由 [#2813](https://github.com/storytold/lightcraft/issues/2813) 另行追蹤。 + +[Cargo 的 LTO 文件](https://doc.rust-lang.org/cargo/reference/profiles.html#lto) 區分了 `false` +與 `off`:`false` 仍可能在程式碼產生單元之間執行 thin local LTO(除非 `codegen-units=1` +或 `opt-level=0`);`off` 則明確停用 LTO。上文的低記憶體建置配方維持不變。 +此繞過方法僅適用於受影響的建置,不是新的預設建議;停用 LTO 可能改變效能、二進位檔大小與建置行為。 + 測試在缺少 GPU、語料庫、craft-fonts 字型或模型時會直接通過而不檢查任何內容(libtest 沒有「已跳過」 這個狀態),所以 `cargo xtask ci` 會把它們列出來:測試會用 `lightcraft_testkit::skip!` 記錄跳過原因, 執行結束時會列出機器提供的環境(作業系統、CPU、記憶體、每個後端的 GPU 配接器、語料庫、字型)以及每一項 diff --git a/ROADMAP.md b/ROADMAP.md index 6802f92342..8804f42701 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~14 points and ~340–600 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-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 | diff --git a/apps/lightcraft-cli/Cargo.toml b/apps/lightcraft-cli/Cargo.toml index b82aca1d59..e55d458b32 100644 --- a/apps/lightcraft-cli/Cargo.toml +++ b/apps/lightcraft-cli/Cargo.toml @@ -25,6 +25,9 @@ lightcraft-merge = { workspace = true } serde_json = { workspace = true } dhat = { workspace = true, optional = true } +[dev-dependencies] +lightcraft-testkit = { workspace = true } + [features] default = ["denoise"] denoise = ["lightcraft-engine/denoise"] diff --git a/apps/lightcraft-cli/src/bench_cull.rs b/apps/lightcraft-cli/src/bench_cull.rs new file mode 100644 index 0000000000..9107a94553 --- /dev/null +++ b/apps/lightcraft-cli/src/bench_cull.rs @@ -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 { + 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 { + 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(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 { + 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::().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) = 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 = 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 = 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 = 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 = 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::>()); + 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 = 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 = 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 = 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 = 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 = 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) -> 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 = (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::(&[], 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); + } +} diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index c1f9d258c6..d384229558 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -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 .json to DIR (default: the profiles folder LightCraft reads, /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 = std::env::args().skip(1).collect(); + let mut args: Vec = Vec::new(); + for (index, arg) in std::env::args_os().skip(1).enumerate() { + match arg.into_string() { + Ok(arg) => args.push(arg), + Err(_) => { + eprintln!("lightcraft-cli: argument {} is not valid Unicode", index + 1); + return ExitCode::FAILURE; + } + } + } let r = match args.first().map(String::as_str) { Some("run") => run(&args[1..]), Some("mcp") => mcp(&args[1..]), @@ -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, 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) { + 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 = 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 = 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, String> { + if let Some(failed) = report["failed"].as_array().filter(|failed| !failed.is_empty()) { + return Err(format!("import failed for {} item(s): {}; no commands were run", failed.len(), json!(failed))); + } + let mut ids: Vec = report["imported"].as_array().cloned().unwrap_or_default(); + ids.extend(report["duplicates"].as_array().into_iter().flatten().filter_map(|d| d.get("existing").filter(|v| v.is_u64()).cloned())); + ids.extend(report["restored"].as_array().into_iter().flatten().filter(|id| id.is_u64()).cloned()); + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| id.as_u64().is_none_or(|id| seen.insert(id))); + if ids.is_empty() { Err("import found no photos to select; no commands were run".into()) } else { Ok(ids) } +} + fn take_value<'a>(args: &'a [String], i: &mut usize, flag: &str) -> Result<&'a str, String> { *i += 1; args.get(*i).map(String::as_str).ok_or_else(|| format!("{flag} needs a value")) @@ -667,6 +721,12 @@ fn read_settings(p: &str) -> Result { } } +/// 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); + } +} diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs index 8a11f5c9ab..2a052fc2d8 100644 --- a/apps/lightcraft-cli/tests/it/cli.rs +++ b/apps/lightcraft-cli/tests/it/cli.rs @@ -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)> = 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 = "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 = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect(); assert!(replies.iter().all(|reply| reply["ok"] == true), "{replies:?}"); - let gpu = &replies[0]["result"]; - assert_eq!(gpu["enabled"], false, "{gpu}"); - assert_eq!(gpu["available"], false, "{gpu}"); - assert_eq!(gpu["adapter"], Value::Null, "no device is created: {gpu}"); - assert!(gpu["reason"].as_str().is_some_and(|reason| reason.contains("preference")), "{gpu}"); + // `wait: false` (what the UI sends) still says why the GPU is off: no device is being created + for gpu in [&replies[0]["result"], &replies[1]["result"]] { + assert_eq!(gpu["enabled"], false, "{gpu}"); + assert_eq!(gpu["available"], false, "{gpu}"); + assert_eq!(gpu["adapter"], Value::Null, "no device is created: {gpu}"); + assert!(gpu["reason"].as_str().is_some_and(|reason| reason.contains("preference")), "{gpu}"); + } let decoded = lightcraft_codecs::decode(&std::fs::read(image).unwrap(), Default::default()).unwrap(); assert_eq!((decoded.width, decoded.height), (480, 320)); } +/// Issue #136: `app.gpu {enabled: true, wait: false}` (what the UI sends on its first frame) answers +/// at once while the device is still being created: enabled, and nothing known yet (`null`), instead +/// of waiting for the driver. It starts creating the device (off the calling thread), so this test +/// touches the GPU driver and skips when the environment turns the GPU off. +#[test] +fn enabling_the_gpu_without_waiting_answers_before_the_device_exists() { + if std::env::var("LIGHTCRAFT_GPU").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")) { + lightcraft_testkit::skip!(Gpu, "LIGHTCRAFT_GPU=0: enabling the GPU starts creating a device"); + return; + } + let script = tmp("gpu-starting.jsonl"); + std::fs::write( + &script, + format!("{}\n", json!({"method": "engine.execute", "params": {"command": "app.gpu", "params": {"enabled": true, "wait": false}}})), + ) + .unwrap(); + let image = tmp("gpu-starting.png"); + let output = Command::new(binary()) + .env_remove("LIGHTCRAFT_GPU") + .env_remove("LIGHTCRAFT_GPU_BACKEND") + .env_remove("WGPU_BACKEND") + .args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", image.to_str().unwrap(), "--size", "480x320"]) + .output() + .unwrap(); + assert!(output.status.success(), "status {}: {}", output.status, String::from_utf8_lossy(&output.stderr)); + let replies: Vec = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + assert_eq!(replies.len(), 1, "{replies:?}"); + assert_eq!(replies[0]["ok"], true, "{replies:?}"); + let gpu = &replies[0]["result"]; + assert_eq!(gpu["enabled"], true, "{gpu}"); + for field in ["available", "adapter", "reason"] { + assert_eq!(gpu[field], Value::Null, "{field} is not known while the device is created: {gpu}"); + } +} + /// Issue #136: with the GPU switched off from the environment the UI starts and renders on the CPU, /// without creating a GPU device (no driver is loaded), and says why. #[test] @@ -502,6 +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, 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, 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}"); // `:` still works (issue #167 case). - let (ok, _lines, err) = run_cli(&["--connect", "127.0.0.1:18437", "ui.inspect"], None); + let (ok, _lines, err) = run_cli(&["--connect", &format!("127.0.0.1:{port}"), "ui.inspect"], None); assert!(!ok); - assert!(err.contains("--control 18437"), "{err}"); + assert!(err.contains(&hint), "{err}"); // `--connect=` already worked (the `a.starts_with("--connect=")` arm); spot-check // the hint matches its port too. - let (ok, _lines, err) = run_cli(&["--connect=18437", "ui.inspect"], None); + let (ok, _lines, err) = run_cli(&[&format!("--connect={port}"), "ui.inspect"], None); assert!(!ok); - assert!(err.contains("--control 18437"), "{err}"); + assert!(err.contains(&hint), "{err}"); } /// The CLI logs warnings on stderr (#168): with `RUST_LOG=warn` an unknown GPU backend name is @@ -785,7 +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()) diff --git a/apps/lightcraft-web/Cargo.toml b/apps/lightcraft-web/Cargo.toml index d4ae0f6674..62fb546991 100644 --- a/apps/lightcraft-web/Cargo.toml +++ b/apps/lightcraft-web/Cargo.toml @@ -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 } diff --git a/apps/lightcraft-web/src/backup.rs b/apps/lightcraft-web/src/backup.rs index 281a32296d..6a4dd205e5 100644 --- a/apps/lightcraft-web/src/backup.rs +++ b/apps/lightcraft-web/src/backup.rs @@ -233,6 +233,25 @@ pub fn parse_central(cd: &[u8]) -> Result, 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, 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 { 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::>(), ["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() }; diff --git a/apps/lightcraft-web/src/bench.rs b/apps/lightcraft-web/src/bench.rs index 484c0041f6..4864834c75 100644 --- a/apps/lightcraft-web/src/bench.rs +++ b/apps/lightcraft-web/src/bench.rs @@ -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; diff --git a/apps/lightcraft-web/src/host.rs b/apps/lightcraft-web/src/host.rs new file mode 100644 index 0000000000..b7970dc22e --- /dev/null +++ b/apps/lightcraft-web/src/host.rs @@ -0,0 +1,632 @@ +//! The bridge to a host page (issue #2270): a same-origin page embeds LightCraft in an `