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/AGENTS.md b/AGENTS.md index f10fedb20b..f179510775 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi 4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut). When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` / - `docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and + `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 `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. @@ -38,9 +38,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,10 +50,15 @@ 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 + `[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. `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…). @@ -61,7 +67,7 @@ of it. - **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. - **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). +- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, 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. ## Assets: icons, images, fonts (ABSOLUTE RULE — never violate) @@ -123,6 +129,12 @@ of it. 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/`. +- **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 +166,5 @@ 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. diff --git a/CLAUDE.md b/CLAUDE.md index 0597cbf465..6ef579697e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,7 +14,7 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi 4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut). When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` / - `docs/target-app-parity.md` when a listed gap closes (bump each doc's *Last updated* line and revision history); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and + `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. 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. @@ -39,9 +39,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. @@ -56,7 +57,9 @@ of it. (`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. + 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…). @@ -70,7 +73,7 @@ of it. - **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 + tests, layers, assets, roots, 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. @@ -137,6 +140,12 @@ of it. 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/`. +- **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). @@ -153,4 +162,5 @@ 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. diff --git a/Cargo.lock b/Cargo.lock index 1d0bb2bdc2..acd433bc27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1246,7 +1246,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=a231e517c3b371e1bf0ee8af71ed807424a9a05d#a231e517c3b371e1bf0ee8af71ed807424a9a05d" dependencies = [ "chrono", "dunce", @@ -2139,6 +2139,16 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "fs4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" +dependencies = [ + "rustix 1.1.5", + "windows-sys 0.61.2", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -3589,12 +3599,14 @@ dependencies = [ "lightcraft-sysmem", "lightcraft-testkit", "lightcraft-ui-egui", + "lightcraft-wincolor", "log", "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "pollster 1.0.1", + "raw-window-handle", "rfd", "serde_json", "winit", @@ -3732,6 +3744,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "fs4", "harfrust 0.13.3", "jxl-oxide", "libc", @@ -4080,6 +4093,14 @@ dependencies = [ "web-sys", ] +[[package]] +name = "lightcraft-wincolor" +version = "0.18.0" +dependencies = [ + "lightcraft-testkit", + "windows-sys 0.61.2", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -8184,7 +8205,6 @@ dependencies = [ "nix", "typed-path 0.13.0", "windows-sys 0.61.2", - "zopfli", ] [[package]] @@ -8199,18 +8219,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index 061507c999..8549d6167e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l # Canon CRW decoder shared with the other Craft apps craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } @@ -23,6 +23,7 @@ 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" } @@ -58,6 +59,8 @@ 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"] } diff --git a/README.md b/README.md index 1b64265b3a..21ff4306ec 100644 --- a/README.md +++ b/README.md @@ -350,7 +350,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det 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 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; - - **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); + - **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF now decodes sensor data on 58 more bodies (2 verified) ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md); - **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and linear-RGB denoise and Super Resolution remain missing; see [AI masks](docs/ai-masks.md) and [AI Denoise](docs/denoise.md); @@ -370,7 +370,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det | Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ | | Camera colour: DNG matrices, guarded camera-JPEG look fits and built-in profiles for selected cameras | 🚧 measured calibration and per-model coverage remain incomplete ([raw parity](docs/raw-parity.md)) | | Native macOS menu bar (generated from the command registry), control channel + every widget addressable, headless UI snapshots | ✅ | -| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed ORF / SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | +| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp, compressed), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | | Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights; [setup](docs/denoise.md)), Super Resolution ⬜ | | Remove / Heal / Clone spots (auto source), non-generative Fill, editable spot pins, Visualize Spots, Red Eye and Pet Eye | ✅ · Fill uses PatchMatch; no generative fill | | Export: JPEG / PNG / TIFF / flat PSD / WebP / AVIF / JPEG XL / raw or rendered DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ | diff --git a/ROADMAP.md b/ROADMAP.md index 471496ecd1..8804f42701 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~14 points and ~340–600 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Canon CRW decoded clean-room, 6 bodies verified, 557 models verified; 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: 85% of Adobe's models decode, 39% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 · **Changes:** [revision history](#revision-history) One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in @@ -14,25 +14,25 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are |---|---:|---| | **Feature breadth** (checklist) | **81.6%** of 532 rows (P0 98.0%, P1 95.2%, P2 50.0%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount | | **Feature breadth** (weighted by use) | **~77%** | estimated | -| **Ready for real work** (full target) | **~61%** (56–66%) | estimated: weighted sum over the dimensions | +| **Ready for real work** (full target) | **~62%** (57–67%) | estimated: weighted sum over the dimensions | | **Mainstream practitioner** | **~51%** (46–56%) | estimated | | **Essentials user** | **~65%** (60–70%) | estimated | | Remaining to **beta** | **~340–600 h** (Opus 5.5 agent hours, ~60% parallel) | estimated | -| Remaining to **full parity** | **~1,000–1,800 h** (~70% parallel) | estimated | +| Remaining to **full parity** | **~980–1,750 h** (~70% parallel) | estimated | Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%): | Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates | |---|---:|---:|---| -| Full target (ready for real work) | **~61%** | **1,000–1,800 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem | -| Mainstream practitioner | **~51%** | **450–840 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability | +| Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem | +| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability | | Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send | The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is -estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), compressed ORF and HE NEF -open as previews, rendering is tuned by eye, AI masks are heuristics, there is no lens database, and +estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens +as preview (compressed ORF now decodes on 58 more bodies (2 verified)), rendering is tuned by eye, AI masks are heuristics, there is no lens database, and tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below -the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have 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 @@ -107,13 +107,14 @@ 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~~ (done 2026-11-04) and HE NEF (20–40 h) 7. Lens profile database of our own (40–80 h, #329) 8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h) 9. Per-model raw verification (20–35 h) ## Progress log +- 2026-11-04: Olympus / OM System compressed ORF decodes from sensor data: clean-room pure-Rust bitstream decoder (`crates/raw/src/vendor/orfc.rs`) derived strictly from Olympus patents US7333035B2/US7715639B2, maker notes and CC0 samples without third-party decoder code (see `docs/orf-compression.md`), verified on OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) CC0 samples; 58 bodies newly unlocked (78 total across Olympus and OM; OM/Olympus 6% → 81% fully working, overall weighted camera coverage 94% → 97%). - 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判 (89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200), 六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog 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 7822bbed9a..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; @@ -110,6 +112,12 @@ USAGE: 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(()) 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 a5732beeaa..62fb546991 100644 --- a/apps/lightcraft-web/Cargo.toml +++ b/apps/lightcraft-web/Cargo.toml @@ -32,10 +32,14 @@ js-sys = { workspace = true } web-sys = { workspace = true, features = [ "Blob", "BlobPropertyBag", + "CustomEvent", + "CustomEventInit", + "CssStyleDeclaration", "DedicatedWorkerGlobalScope", "Document", "DomStringList", "Element", + "Event", "EventTarget", "File", "FileList", 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 `