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/nix.yml b/.github/workflows/nix.yml index 2fe7cd3ac9..554c712eb5 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -19,42 +19,8 @@ concurrency: jobs: git-sources: - name: Git dependencies come from storytold - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Git dependencies come from storytold - run: | - set -euo pipefail - test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } - # Source replacement, patches and path overrides in cargo config never show up - # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. - # Cargo still reads the legacy .cargo/config. - python3 - <<'PY' - import os, sys, tomllib - for path in (".cargo/config", ".cargo/config.toml"): - if not os.path.exists(path): - continue - config = tomllib.load(open(path, "rb")) - replaced = [name for name, source in config.get("source", {}).items() - if isinstance(source, dict) and "replace-with" in source] - if replaced or "patch" in config or "paths" in config: - print(f"{path} replaces, patches or overrides a source") - sys.exit(1) - PY - # Fails when Cargo.lock is out of date with the manifests. - cargo metadata --locked --format-version 1 > /dev/null - python3 - <<'PY' - import sys, tomllib - lock = tomllib.load(open("Cargo.lock", "rb")) - bad = sorted({p["source"] for p in lock.get("package", []) - if p.get("source", "").startswith("git+") - and not p["source"].startswith("git+https://github.com/storytold/")}) - if bad: - print("Git dependencies outside github.com/storytold:", *bad, sep="\n") - sys.exit(1) - PY + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main nix: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index dff954e931..4350481874 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -28,10 +28,16 @@ jobs: runs-on: windows-latest timeout-minutes: 10 steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The suite's WiX (5.0.2); the install-folder test needs no extensions. - name: Install WiX - shell: pwsh - run: dotnet tool install --global wix --version 5.0.2 + uses: storytold/craft-common-actions/actions/install-wix@main + with: + install-extensions: "false" - name: Install-folder fallback and precedence (real MSI AppSearch) shell: pwsh run: | @@ -43,6 +49,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a90fad3905..bcef3b8b6a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,6 +3,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "4 2 * * *" push: branches: [release] workflow_dispatch: @@ -12,64 +16,37 @@ on: type: string default: "" -permissions: - contents: write - packages: write +# Nothing by default; each job names what it needs. Only `release` writes (the draft GitHub Release +# and its packages). +permissions: {} concurrency: group: release-${{ github.ref }} cancel-in-progress: false jobs: - git-sources: - name: Git dependencies come from storytold - runs-on: ubuntu-latest + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: permissions: contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Git dependencies come from storytold - run: | - set -euo pipefail - test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } - # Source replacement, patches and path overrides in cargo config never show up - # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. - # Cargo still reads the legacy .cargo/config. - python3 - <<'PY' - import os, sys, tomllib - for path in (".cargo/config", ".cargo/config.toml"): - if not os.path.exists(path): - continue - config = tomllib.load(open(path, "rb")) - replaced = [name for name, source in config.get("source", {}).items() - if isinstance(source, dict) and "replace-with" in source] - if replaced or "patch" in config or "paths" in config: - print(f"{path} replaces, patches or overrides a source") - sys.exit(1) - PY - # Fails when Cargo.lock is out of date with the manifests. - cargo metadata --locked --format-version 1 > /dev/null - python3 - <<'PY' - import sys, tomllib - lock = tomllib.load(open("Cargo.lock", "rb")) - bad = sorted({p["source"] for p in lock.get("package", []) - if p.get("source", "").startswith("git+") - and not p["source"].startswith("git+https://github.com/storytold/")}) - if bad: - print("Git dependencies outside github.com/storytold:", *bad, sep="\n") - sys.exit(1) - PY + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main release: - needs: git-sources + needs: credits + permissions: + contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: lightcraft app-title: LightCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} @@ -85,3 +62,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 f10fedb20b..76c593c1d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,24 +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); `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). @@ -38,9 +89,10 @@ of it. "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. @@ -49,20 +101,31 @@ of it. - **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. @@ -81,7 +144,7 @@ of it. 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. @@ -98,7 +161,9 @@ of it. - **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 @@ -107,7 +172,9 @@ of it. 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). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. @@ -120,9 +187,15 @@ of it. - **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). @@ -154,4 +227,9 @@ evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the work ## 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. + +## Shared libraries + +Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers. diff --git a/CLAUDE.md b/CLAUDE.md index 0597cbf465..43c994c2d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,156 +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); `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. -- **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. -- 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). 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 cf7b45714f..2e30cbb47b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -641,6 +641,12 @@ dependencies = [ "serde", ] +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -1181,6 +1187,37 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247#7f30d664695cd5ce14fc30659d36c3e32f234247" +dependencies = [ + "md-5", + "rayon", +] + +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484#eeb134def2daa7e03512b4946bd59d6b419b9484" +dependencies = [ + "md-5", + "rayon", +] + +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" + +[[package]] +name = "craft-crw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1191,6 +1228,32 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +[[package]] +name = "craft-gainmap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93#9dcbd90c7d16e1a668b3afa057e940e2db328b93" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-gif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" +dependencies = [ + "gif", + "image", +] + +[[package]] +name = "craft-heif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=4ffa307f1a0a6fbd8897318cc719440ab06e9c63#4ffa307f1a0a6fbd8897318cc719440ab06e9c63" +dependencies = [ + "heic-rs", + "rayon", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1214,6 +1277,208 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" +dependencies = [ + "avif-serialize", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder 0.6.1", + "png", + "rav1e", + "ravif", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder 0.6.1", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f#478c50560d3c6fad3d613af2a30b35c3bc9f4c0f" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-jxl" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f#478c50560d3c6fad3d613af2a30b35c3bc9f4c0f" +dependencies = [ + "jixel", + "jxl-oxide", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6#5c91598ccc86537a779f438d520fa6406c26efe6" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" +dependencies = [ + "brotli-decompressor 6.0.1", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", + "quick-xml 0.41.0", + "serde", +] + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "brotli-decompressor 6.0.1", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "quick-xml 0.41.0", + "serde", +] + +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "chrono", + "craft-codepage", + "encoding_rs", +] + +[[package]] +name = "craft-pdf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0fd30aeb3e02207d9d4c7c601540d9da45abf8de#0fd30aeb3e02207d9d4c7c601540d9da45abf8de" +dependencies = [ + "flate2", + "roxmltree", +] + +[[package]] +name = "craft-plist" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bea6ed1ff031b81df2d64be470485c1ca808847e#bea6ed1ff031b81df2d64be470485c1ca808847e" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=16d838105b07965832bb43132880176f299634d5#16d838105b07965832bb43132880176f299634d5" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-raw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "chrono", + "craft-crw", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "jxl-oxide", + "miniz_oxide 0.9.1", + "rayon", + "serde", + "thiserror 2.0.21", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1238,7 +1503,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "chrono", "dunce", @@ -1248,6 +1513,7 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", @@ -1261,6 +1527,26 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-video" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6#5c91598ccc86537a779f438d520fa6406c26efe6" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6)", + "rav1e", + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-video" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "thiserror 2.0.21", +] + [[package]] name = "craft-window" version = "0.1.0" @@ -1272,6 +1558,16 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2d4b8b8ecd79f87c847961901c40305e7f448d6f#2d4b8b8ecd79f87c847961901c40305e7f448d6f" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -1680,6 +1976,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" @@ -1748,6 +2057,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1766,6 +2089,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" @@ -1909,6 +2252,22 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "faer-core" version = "0.17.1" @@ -2098,6 +2457,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" @@ -2810,6 +3179,15 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hayro-jpeg2000" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] + [[package]] name = "heck" version = "0.5.0" @@ -3058,10 +3436,12 @@ dependencies = [ "byteorder-lite", "color_quant", "gif", - "image-webp", - "moxcms 0.8.1", + "moxcms", "num-traits", "png", + "qoi", + "ravif", + "rgb", "tiff", "zune-core", "zune-jpeg", @@ -3231,13 +3611,10 @@ dependencies = [ ] [[package]] -name = "jpeg-decoder" -version = "0.3.2" +name = "jpeg-encoder" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" -dependencies = [ - "rayon", -] +checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" [[package]] name = "jpeg-encoder" @@ -3490,6 +3867,12 @@ dependencies = [ "spin", ] +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.191" @@ -3536,7 +3919,7 @@ dependencies = [ [[package]] name = "lightcraft" -version = "0.17.0" +version = "0.21.1" dependencies = [ "chrono", "craft-update", @@ -3548,12 +3931,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,7 +3948,7 @@ dependencies = [ [[package]] name = "lightcraft-catalog" -version = "0.17.0" +version = "0.21.1" dependencies = [ "chrono", "crc32fast", @@ -3584,7 +3969,7 @@ dependencies = [ [[package]] name = "lightcraft-cli" -version = "0.17.0" +version = "0.21.1" dependencies = [ "dhat", "lightcraft-codecs", @@ -3601,38 +3986,36 @@ dependencies = [ [[package]] name = "lightcraft-codecs" -version = "0.17.0" +version = "0.21.1" dependencies = [ - "avif-serialize", "bytemuck", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247)", + "craft-gainmap", + "craft-gif", + "craft-heif", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f)", + "craft-jxl", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-psd", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6)", "dhat", - "image", - "image-webp", - "jixel", - "jpeg-decoder", - "jpeg-encoder", - "jxl-oxide", + "jpeg-encoder 0.7.1", "lightcraft-color", "lightcraft-geom", - "lightcraft-heif", "lightcraft-raster", "lightcraft-testkit", - "moxcms 0.9.1", - "png", "proptest", - "rav1e", - "ravif", "rayon", "serde", "thiserror 2.0.21", - "tiff", - "zune-core", - "zune-jpeg", ] [[package]] name = "lightcraft-color" -version = "0.17.0" +version = "0.21.1" dependencies = [ "lightcraft-geom", "proptest", @@ -3641,7 +4024,7 @@ dependencies = [ [[package]] name = "lightcraft-denoise" -version = "0.17.0" +version = "0.21.1" dependencies = [ "faer-core", "lightcraft-denoise-core", @@ -3658,7 +4041,7 @@ dependencies = [ [[package]] name = "lightcraft-denoise-core" -version = "0.17.0" +version = "0.21.1" dependencies = [ "dhat", "lightcraft-raster", @@ -3674,8 +4057,9 @@ dependencies = [ [[package]] name = "lightcraft-develop" -version = "0.17.0" +version = "0.21.1" dependencies = [ + "craft-mime", "lightcraft-color", "lightcraft-geom", "miniz_oxide 0.9.1", @@ -3686,13 +4070,20 @@ dependencies = [ [[package]] name = "lightcraft-engine" -version = "0.17.0" +version = "0.21.1" dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "craft-heif", + "craft-jxl", + "craft-mime", + "craft-pdf", + "craft-plist", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "crc32fast", + "fs4", "harfrust 0.13.3", - "jxl-oxide", "libc", "lightcraft-catalog", "lightcraft-codecs", @@ -3705,7 +4096,6 @@ dependencies = [ "lightcraft-geocode", "lightcraft-geom", "lightcraft-gpu", - "lightcraft-heif", "lightcraft-lensdb", "lightcraft-merge", "lightcraft-meta", @@ -3717,20 +4107,20 @@ dependencies = [ "lightcraft-segment", "lightcraft-slideshow", "lightcraft-testkit", - "lightcraft-tiff", "log", "miniz_oxide 0.9.1", "rayon", "serde", "serde_json", "thiserror 2.0.21", + "unicode-normalization", "unicode-segmentation", "web-time", ] [[package]] name = "lightcraft-faces" -version = "0.17.0" +version = "0.21.1" dependencies = [ "lightcraft-testkit", "matrixmultiply", @@ -3745,7 +4135,7 @@ dependencies = [ [[package]] name = "lightcraft-fetch" -version = "0.17.0" +version = "0.21.1" dependencies = [ "log", "rustls", @@ -3754,9 +4144,16 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "lightcraft-film" +version = "0.21.1" +dependencies = [ + "libm", +] + [[package]] name = "lightcraft-geocode" -version = "0.17.0" +version = "0.21.1" dependencies = [ "miniz_oxide 0.9.1", "serde", @@ -3764,7 +4161,7 @@ dependencies = [ [[package]] name = "lightcraft-geom" -version = "0.17.0" +version = "0.21.1" dependencies = [ "proptest", "serde", @@ -3772,7 +4169,7 @@ dependencies = [ [[package]] name = "lightcraft-gpu" -version = "0.17.0" +version = "0.21.1" dependencies = [ "bytemuck", "lightcraft-color", @@ -3790,34 +4187,27 @@ dependencies = [ "wgpu", ] -[[package]] -name = "lightcraft-heif" -version = "0.17.0" -dependencies = [ - "heic-rs", - "rayon", -] - [[package]] name = "lightcraft-inpaint" -version = "0.17.0" +version = "0.21.1" dependencies = [ "rayon", ] [[package]] name = "lightcraft-lensdb" -version = "0.17.0" +version = "0.21.1" dependencies = [ + "craft-xml", "lightcraft-develop", "lightcraft-geom", - "quick-xml 0.41.0", ] [[package]] name = "lightcraft-mcp" -version = "0.17.0" +version = "0.21.1" dependencies = [ + "craft-mime", "lightcraft-codecs", "lightcraft-engine", "lightcraft-raster", @@ -3827,7 +4217,7 @@ dependencies = [ [[package]] name = "lightcraft-merge" -version = "0.17.0" +version = "0.21.1" dependencies = [ "lightcraft-codecs", "lightcraft-color", @@ -3843,24 +4233,27 @@ dependencies = [ [[package]] name = "lightcraft-meta" -version = "0.17.0" +version = "0.21.1" dependencies = [ "chrono", + "craft-heif", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-psd", + "craft-raw", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "lightcraft-geom", - "lightcraft-heif", - "lightcraft-tiff", "proptest", - "quick-xml 0.41.0", "serde", "serde_json", ] [[package]] name = "lightcraft-pipeline" -version = "0.17.0" +version = "0.21.1" dependencies = [ + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "dhat", - "image", "lightcraft-color", "lightcraft-develop", "lightcraft-geom", @@ -3876,19 +4269,17 @@ dependencies = [ [[package]] name = "lightcraft-preview" -version = "0.17.0" +version = "0.21.1" dependencies = [ - "jpeg-encoder", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "lightcraft-raster", "log", "siphasher", - "zune-core", - "zune-jpeg", ] [[package]] name = "lightcraft-raster" -version = "0.17.0" +version = "0.21.1" dependencies = [ "libc", "lightcraft-color", @@ -3900,33 +4291,33 @@ dependencies = [ [[package]] name = "lightcraft-raw" -version = "0.17.0" +version = "0.21.1" dependencies = [ + "chrono", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-jxl", + "craft-raw", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "dhat", - "jpeg-encoder", - "jxl-oxide", + "jixel", "lightcraft-color", "lightcraft-geom", "lightcraft-meta", "lightcraft-raster", "lightcraft-testkit", - "lightcraft-tiff", "miniz_oxide 0.9.1", "proptest", "rayon", "serde", "sha2", "thiserror 2.0.21", - "zune-core", - "zune-jpeg", - "zune-jpegxl", ] [[package]] name = "lightcraft-scenes" -version = "0.17.0" +version = "0.21.1" dependencies = [ - "image", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "lightcraft-color", "lightcraft-raster", "rayon", @@ -3935,7 +4326,7 @@ dependencies = [ [[package]] name = "lightcraft-segment" -version = "0.17.0" +version = "0.21.1" dependencies = [ "candle-core", "candle-nn", @@ -3949,7 +4340,7 @@ dependencies = [ [[package]] name = "lightcraft-slideshow" -version = "0.17.0" +version = "0.21.1" dependencies = [ "lightcraft-raster", "serde", @@ -3958,29 +4349,21 @@ dependencies = [ [[package]] name = "lightcraft-sysmem" -version = "0.17.0" +version = "0.21.1" [[package]] name = "lightcraft-testkit" -version = "0.17.0" - -[[package]] -name = "lightcraft-tiff" -version = "0.17.0" -dependencies = [ - "proptest", - "serde", - "thiserror 2.0.21", -] +version = "0.21.1" [[package]] name = "lightcraft-ui-egui" -version = "0.17.0" +version = "0.21.1" dependencies = [ "craft-ui", "craft-update", "craft-window", "egui", + "egui_extras", "egui_kittest", "lightcraft-catalog", "lightcraft-codecs", @@ -3998,6 +4381,7 @@ dependencies = [ "lightcraft-slideshow", "lightcraft-testkit", "log", + "pollster 1.0.1", "serde", "serde_json", "toml", @@ -4006,16 +4390,18 @@ dependencies = [ [[package]] name = "lightcraft-web" -version = "0.17.0" +version = "0.21.1" dependencies = [ "crc32fast", "eframe", "egui", "js-sys", "lightcraft-codecs", + "lightcraft-color", "lightcraft-engine", "lightcraft-preview", "lightcraft-raster", + "lightcraft-raw", "lightcraft-ui-egui", "log", "serde", @@ -4025,6 +4411,14 @@ dependencies = [ "web-sys", ] +[[package]] +name = "lightcraft-wincolor" +version = "0.21.1" +dependencies = [ + "lightcraft-testkit", + "windows-sys 0.61.2", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -4117,6 +4511,16 @@ dependencies = [ "rayon", ] +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -4193,16 +4597,6 @@ dependencies = [ "pxfm", ] -[[package]] -name = "moxcms" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396077b717181ce3f9a6b66739b269b82d756be5ec0f76be0bc40a7c51775830" -dependencies = [ - "num-traits", - "pxfm", -] - [[package]] name = "muda" version = "0.21.2" @@ -4221,6 +4615,34 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" @@ -5389,6 +5811,15 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "1.2.3" @@ -5775,6 +6206,15 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + [[package]] name = "rsa" version = "0.9.10" @@ -6475,6 +6915,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -6598,6 +7044,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" @@ -6804,6 +7256,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" @@ -7823,7 +8284,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.17.0" +version = "0.21.1" dependencies = [ "brotli", "flate2", @@ -8114,7 +8575,6 @@ dependencies = [ "nix", "typed-path 0.13.0", "windows-sys 0.61.2", - "zopfli", ] [[package]] @@ -8129,24 +8589,21 @@ 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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.5.15" @@ -8211,11 +8668,6 @@ name = "egui_demo_lib" version = "0.37.0" source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - [[patch.unused]] name = "egui_inspection" version = "0.37.0" diff --git a/Cargo.toml b/Cargo.toml index 31ae79d1a6..5855c21e15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,31 +3,58 @@ resolver = "3" members = ["crates/*", "apps/*", "xtask"] [workspace.package] -version = "0.17.0" +version = "0.21.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] +craft-cms-profile = { package = "craft-cms", git = "https://github.com/storytold/craft-libs", rev = "eeb134def2daa7e03512b4946bd59d6b419b9484" } +craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bea6ed1ff031b81df2d64be470485c1ca808847e" } +craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "0fd30aeb3e02207d9d4c7c601540d9da45abf8de", default-features = false, features = ["write-raster"] } 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 = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "7f30d664695cd5ce14fc30659d36c3e32f234247" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", version = "0.1.0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", features = ["frames"] } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "478c50560d3c6fad3d613af2a30b35c3bc9f4c0f", default-features = false, features = ["decode", "encode"] } +jixel = "=0.3.4" +# Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949) +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "478c50560d3c6fad3d613af2a30b35c3bc9f4c0f" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } +craft-video = { git = "https://github.com/storytold/craft-libs", rev = "5c91598ccc86537a779f438d520fa6406c26efe6", features = ["av1", "av1-large-encode", "threads"] } +# Isolate AVIF threading from the existing PNG/TIFF/WebP shared revision. +craft-avif-encode = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a", default-features = false, features = ["avif", "threads"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" } # 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 = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +# HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). +craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" } +# PSD/PSB: the header, colour mode data and image resources (craft-libs#885). +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "16d838105b07965832bb43132880176f299634d5" } +jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] } # 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" } +# TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783). +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } 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" } @@ -40,7 +67,8 @@ lightcraft-engine = { path = "crates/engine" } lightcraft-ui-egui = { path = "crates/ui-egui" } lightcraft-mcp = { path = "crates/mcp" } lightcraft-fetch = { path = "crates/fetch" } -lightcraft-heif = { path = "crates/heif" } +# HEIC/HEIF: the shared decoder (moved from crates/heif; craft-libs#784). +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "4ffa307f1a0a6fbd8897318cc719440ab06e9c63", default-features = false } lightcraft-segment = { path = "crates/segment" } lightcraft-geocode = { path = "crates/geocode" } lightcraft-slideshow = { path = "crates/slideshow" } @@ -55,36 +83,23 @@ 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 # formats -quick-xml = "0.41" miniz_oxide = "0.9" # codecs -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "webp"] } -zune-jpeg = { version = "0.5", default-features = false, features = ["std", "x86", "neon"] } -zune-core = { version = "0.5", default-features = false, features = ["std"] } -jpeg-decoder = { version = "0.3", default-features = false } -jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] } ab_glyph = { version = "0.2", default-features = false, features = ["std"] } # Apache-2.0, pure Rust glyph rasterizer (export watermarks) -png = "0.18" -tiff = "0.11" -image-webp = "0.2" moxcms = { version = "0.9", default-features = false, features = ["lut"] } -jxl-oxide = { version = "0.12", default-features = false } -jixel = "=0.3.4" # BSD-3-Clause OR Apache-2.0, pure-Rust JPEG XL encoder (export; port of libjxl-tiny) -zune-jpegxl = { version = "0.5", default-features = false, features = ["std"] } # MIT/Apache-2.0/Zlib lossless JXL encoder (test fixtures only) -ravif = { version = "0.13", default-features = false, features = ["threading"] } # no "asm": it needs nasm (non-Rust) -# HDR AVIF (PQ): ravif fixes the sRGB transfer curve, so HDR files drive its rav1e + avif-serialize directly -rav1e = { version = "0.8.1", default-features = false, features = ["threading"] } -avif-serialize = "0.8.6" # gpu (crates/gpu; native backends only, no GL: everything stays pure Rust) # SAM 3 inference (lightcraft-segment). 0.9.2: later releases pull `tokenizers` with the @@ -169,12 +184,12 @@ lightcraft-color = { opt-level = 3 } lightcraft-develop = { opt-level = 3 } lightcraft-geom = { opt-level = 3 } lightcraft-raw = { opt-level = 3 } +craft-raw = { opt-level = 3 } lightcraft-codecs = { opt-level = 3 } lightcraft-scenes = { opt-level = 3 } lightcraft-preview = { opt-level = 3 } zune-jpeg = { opt-level = 3 } zune-core = { opt-level = 3 } -jpeg-decoder = { opt-level = 3 } jpeg-encoder = { opt-level = 3 } png = { opt-level = 3 } miniz_oxide = { opt-level = 3 } diff --git a/NOTICE b/NOTICE index 39eb49db2c..73c2e2f6f2 100644 --- a/NOTICE +++ b/NOTICE @@ -335,3 +335,133 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +JPEG encoding +------------- + +The shared JPEG writer includes the following third-party encoder notice. The Apache-2.0 +alternative referred to below is also included in this distribution as LICENSE-APACHE. + +JPEG encoding dependency: jpeg-encoder 0.6.1 + +Source: https://crates.io/crates/jpeg-encoder/0.6.1 +Declared license: (MIT OR Apache-2.0) AND IJG. +This software is based in part on the work of the Independent JPEG Group. + +The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0 +alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root +(https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1). +The dependency is used unmodified; no encoder implementation is vendored here. + +LICENSE-MIT + +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +Original src/fdct.rs opening notice + +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +Original src/avx2/fdct.rs opening notice + +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/README.md b/README.md index e6ac8db59a..a3e4981360 100644 --- a/README.md +++ b/README.md @@ -349,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 is unsupported for sensor decoding and uses embedded JPEG previews when available ([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); diff --git a/ROADMAP.md b/ROADMAP.md index 0571abfb99..8531c1d1de 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~14 points and ~340–600 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-11-15 · **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 +estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens +as preview, as does compressed ORF when an embedded preview is available; 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 blocking gaps (compressed ORF and HE NEF open as previews; Canon, +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,27 @@ 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) +6. Compressed ORF (support withdrawn; estimate pending provenance review) 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-07: Compressed ORF support withdrawn pending provenance review; uncompressed support remains. Regenerated camera coverage: 557 verified, 665 unverified, 187 preview-only and 37 unsupported; 94% use-weighted coverage. See [ORF status](docs/orf-compression.md). + +- 2026-11-04: Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. - 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. @@ -190,10 +199,12 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | Lens Blur with AI subject focus and per-mask bokeh; survey tiles fit the photos' shapes and glide to their new places; direct import of Lightroom backup zips (#2592); legacy shutter repair in virtual copies; the opened-library folder-safety fix; v0.21.0 and v0.21.1 released; craft-libs cutover for TIFF/JPEG/JXL/GIF/PSD/HEIF/raw, metadata and gain maps, plus a security-hardening batch; headline numbers not re-measured | | 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 | diff --git a/apps/lightcraft-cli/Cargo.toml b/apps/lightcraft-cli/Cargo.toml index e55d458b32..380bace5f2 100644 --- a/apps/lightcraft-cli/Cargo.toml +++ b/apps/lightcraft-cli/Cargo.toml @@ -37,6 +37,6 @@ rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"] # (open it in DHAT's viewer: allocation sites by bytes at the peak). Slows allocation-heavy work. dhat-heap = ["dep:dhat"] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. heif = ["lightcraft-codecs/heif"] 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 dcb5280f61..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 "; @@ -176,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(()) @@ -196,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> { @@ -237,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(); @@ -425,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(); @@ -703,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; @@ -741,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"))?; @@ -836,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())?; @@ -1069,6 +1108,47 @@ 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}; diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs index 613197459c..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"); diff --git a/apps/lightcraft-web/Cargo.toml b/apps/lightcraft-web/Cargo.toml index d4ae0f6674..8946efb048 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", @@ -73,10 +77,12 @@ web-sys = { workspace = true, features = [ ] } [features] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. On wasm32 panics abort, so # heic-rs's `catch_unwind` guard does not apply there. 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 `