mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 09:19:25 +01:00
Merge main into feat/print-template-browser-folders
This commit is contained in:
commit
f9475fffe2
297 files changed
+23014
-1673
No files matched your search
@@ -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
|
||||
@@ -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: >-
|
||||
|
||||
@@ -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: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
|
||||
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
|
||||
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
|
||||
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
|
||||
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
|
||||
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
|
||||
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
|
||||
@@ -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.
|
||||
@@ -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: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
|
||||
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
|
||||
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
|
||||
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
|
||||
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
|
||||
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
|
||||
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
|
||||
@@ -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.
|
||||
Generated
+22
-14
@@ -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"
|
||||
|
||||
+4
-1
@@ -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"] }
|
||||
|
||||
@@ -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 | ✅ |
|
||||
|
||||
+10
-9
@@ -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
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
//! `lightcraft-cli bench-cull FOLDER`: time what culling a shoot costs, headless, on real files.
|
||||
//!
|
||||
//! What a wedding photographer does most is open a folder of a few thousand raws, look at each
|
||||
//! one, rate it and move on. This times the engine side of each step on the files themselves (the
|
||||
//! desktop app's own frame timings come from `ui.inspect` → `perf.loupeSteps`, see
|
||||
//! `tools/cull-bench.py`):
|
||||
//!
|
||||
//! - browse: reading the folder into the Local view (`library.browse`, the whole folder);
|
||||
//! - grid thumbnails: the camera JPEG at 512 px for the first screen, on as many threads as the
|
||||
//! app renders with;
|
||||
//! - camera preview at loupe sizes (1280, 2560) and at full size (the 100 % view), one at a time;
|
||||
//! - LightCraft's render of the loupe (2560 px) from a cold source;
|
||||
//! - rating: `photo.rate` on many photos in a row, journal included;
|
||||
//! - import: adding N files in place to a fresh library, and copying M of them into it (`--n 0`:
|
||||
//! no import).
|
||||
//!
|
||||
//! `--files K` reads only the first K files (by name) of the folder, as browsing reads them: a
|
||||
//! sample of a folder on a network share, where reading thousands of raws takes hours.
|
||||
//!
|
||||
//! Each number is printed as `name: X ms wall` (median, with p95 and n), the format
|
||||
//! `cargo xtask bench` parses, and the lot as one JSON object with `--json FILE`. Nothing is
|
||||
//! written next to the photos: every library is made in a new folder of the run's own under
|
||||
//! `--work` (default: a folder in the system temp directory; nothing already there is deleted),
|
||||
//! XMP auto-write stays off, and the source folder is only read.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use lightcraft_engine::Session;
|
||||
use lightcraft_engine::catalog::PhotoId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const USAGE: &str = "lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]";
|
||||
|
||||
/// Threads the app renders thumbnails with (`Renderer::default`: cores − 1, at most 6).
|
||||
fn render_threads() -> usize {
|
||||
std::thread::available_parallelism().map(|n| n.get().saturating_sub(1)).unwrap_or(2).clamp(2, 6)
|
||||
}
|
||||
|
||||
/// Median, p95 and count of `ms` (milliseconds).
|
||||
fn stats(ms: &[f64]) -> Value {
|
||||
if ms.is_empty() {
|
||||
return Value::Null;
|
||||
}
|
||||
let mut v = ms.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
let at = |q: f64| v.get(((v.len() - 1) as f64 * q).round() as usize).copied().unwrap_or(0.0);
|
||||
json!({"p50": round(at(0.5)), "p95": round(at(0.95)), "max": round(at(1.0)), "n": v.len()})
|
||||
}
|
||||
|
||||
fn round(x: f64) -> f64 {
|
||||
(x * 10.0).round() / 10.0
|
||||
}
|
||||
|
||||
fn ms_since(t: Instant) -> f64 {
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Print one result line the way `xtask bench` parses it (`name: X ms wall`).
|
||||
fn line(name: &str, s: &Value) {
|
||||
if let Some(p50) = s.get("p50").and_then(Value::as_f64) {
|
||||
println!("{name}: {p50:.1} ms wall (p95 {} ms, n {})", s["p95"], s["n"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, empty folder `name` in this run's own folder; never deletes anything already there.
|
||||
fn fresh_dir(root: &Path, name: &str) -> Result<PathBuf, String> {
|
||||
let d = root.join(name);
|
||||
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// A folder of this run's own under `work`, which must not exist yet: a run never deletes or
|
||||
/// reuses what is already under `--work`.
|
||||
fn run_dir(work: &Path) -> Result<PathBuf, String> {
|
||||
std::fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?;
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = RUNS.fetch_add(1, Ordering::Relaxed);
|
||||
let d = work.join(format!("bench-cull-run-{}-{stamp}-{n}", std::process::id()));
|
||||
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// `take` items of `v` after the first `skip` (photos the stages before have read, so cold in the
|
||||
/// file cache), or, when `v` has no more than `skip`, its first `take`: a small folder is measured
|
||||
/// on photos already read rather than not at all.
|
||||
fn sample_after<T>(v: &[T], skip: usize, take: usize) -> &[T] {
|
||||
let from = if v.len() > skip { skip } else { 0 };
|
||||
let rest = v.get(from..).unwrap_or_default();
|
||||
rest.get(..take.min(rest.len())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether `path` names a file in `folder` (the source folder, which a run only reads), checked
|
||||
/// twice: where its own entry sits (the folder holding it, the final link not followed: writing the
|
||||
/// results replaces that entry, so a link to a file elsewhere that sits in the source folder, maybe
|
||||
/// standing for a photo, would be replaced; CodeRabbit on #3080), and where it resolves to: a file
|
||||
/// that is there by itself (a link to a photo there is the photo), a link that points nowhere yet
|
||||
/// by where writing through it would create the file, and anything else by its nearest folder that
|
||||
/// exists (a `--work` folder may not be there yet).
|
||||
fn inside_source(path: &Path, folder: &Path) -> bool {
|
||||
let Ok(folder) = std::fs::canonicalize(folder) else { return false };
|
||||
entry_inside(path, &folder) || resolves_inside(path, &folder, 0)
|
||||
}
|
||||
|
||||
/// Whether the folder holding `path`'s own entry (its nearest folder that exists, resolved) is in
|
||||
/// `folder` (already resolved). The entry itself is not followed.
|
||||
fn entry_inside(path: &Path, folder: &Path) -> bool {
|
||||
let mut p = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
loop {
|
||||
if let Ok(c) = std::fs::canonicalize(p) {
|
||||
return c.starts_with(folder);
|
||||
}
|
||||
match p.parent() {
|
||||
Some(up) if !up.as_os_str().is_empty() => p = up,
|
||||
Some(_) => p = Path::new("."),
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`inside_source`] for a `folder` already resolved; `hops`: links followed so far (a loop of
|
||||
/// links counts as inside: refused).
|
||||
fn resolves_inside(path: &Path, folder: &Path, hops: u32) -> bool {
|
||||
if let Ok(c) = std::fs::canonicalize(path) {
|
||||
return c.starts_with(folder);
|
||||
}
|
||||
if let Ok(target) = std::fs::read_link(path) {
|
||||
if hops >= 40 {
|
||||
return true;
|
||||
}
|
||||
let target = path.parent().map_or_else(|| target.clone(), |dir| dir.join(&target));
|
||||
return resolves_inside(&target, folder, hops + 1);
|
||||
}
|
||||
entry_inside(path, folder)
|
||||
}
|
||||
|
||||
/// Refuse `--json` or `--work` in the folder being measured: nothing is written next to the photos,
|
||||
/// the results and the run's libraries included. Checked before anything is made.
|
||||
fn check_outputs(folder: &Path, json: Option<&Path>, work: &Path) -> Result<(), String> {
|
||||
// a `..` after a folder not made yet can't be resolved now, and the run makes that folder:
|
||||
// `--json NEW/../FOLDER/r.json` would pass the checks below and land in the source folder
|
||||
// (CodeRabbit on #3544)
|
||||
for (name, p) in [("--json", json), ("--work", Some(work))] {
|
||||
if let Some(p) = p.filter(|p| p.components().any(|c| c == std::path::Component::ParentDir)) {
|
||||
return Err(format!("{}: {name} must not contain \"..\"; give the folder without it", p.display()));
|
||||
}
|
||||
}
|
||||
if let Some(j) = json.filter(|j| inside_source(j, folder)) {
|
||||
return Err(format!("{}: --json must not be in the folder being measured", j.display()));
|
||||
}
|
||||
if inside_source(&work.join("run"), folder) {
|
||||
return Err(format!("{}: --work must not be in the folder being measured", work.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn library(dir: &Path) -> Result<Session, String> {
|
||||
let mut s = Session::new().with_fs().with_system_clock();
|
||||
s.open_library(dir, false).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
// nothing is ever written next to the photos
|
||||
s.execute("library.xmpPreferences", &json!({"autoWrite": false})).map_err(|e| e.to_string())?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
let mut folder = None;
|
||||
let mut n = 2000usize;
|
||||
let mut copy = 200usize;
|
||||
let mut work = None;
|
||||
let mut json_out = None;
|
||||
let mut files = None;
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let value = |i: usize| args.get(i + 1).cloned().ok_or_else(|| format!("{} needs a value\n{USAGE}", args[i]));
|
||||
match args[i].as_str() {
|
||||
"--n" => {
|
||||
n = value(i)?.parse().map_err(|_| "--n needs a number".to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
"--copy" => {
|
||||
copy = value(i)?.parse().map_err(|_| "--copy needs a number".to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
"--files" => {
|
||||
files = Some(value(i)?.parse::<usize>().map_err(|_| "--files needs a number".to_string())?);
|
||||
i += 1;
|
||||
}
|
||||
"--work" => {
|
||||
work = Some(PathBuf::from(value(i)?));
|
||||
i += 1;
|
||||
}
|
||||
"--json" => {
|
||||
json_out = Some(PathBuf::from(value(i)?));
|
||||
i += 1;
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
println!("{USAGE}");
|
||||
return Ok(());
|
||||
}
|
||||
a if a.starts_with("--") => return Err(format!("unknown option {a}\n{USAGE}")),
|
||||
// (a second folder would replace the first and be timed in its place: CodeRabbit on #3583)
|
||||
a if folder.is_some() => return Err(format!("{a}: one FOLDER only\n{USAGE}")),
|
||||
a => folder = Some(PathBuf::from(a)),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let folder = folder.ok_or_else(|| USAGE.to_string())?;
|
||||
if !folder.is_dir() {
|
||||
return Err(format!("{}: not a folder", folder.display()));
|
||||
}
|
||||
let work = work.unwrap_or_else(|| std::env::temp_dir().join(format!("lightcraft-bench-cull-{}", std::process::id())));
|
||||
check_outputs(&folder, json_out.as_deref(), &work)?;
|
||||
let work = run_dir(&work)?;
|
||||
let mut out = json!({"folder": folder.display().to_string(), "threads": render_threads()});
|
||||
|
||||
// --- browse: the whole folder into the Local view -------------------------------------------
|
||||
let mut s = library(&fresh_dir(&work, "lib-browse")?)?;
|
||||
// `--files K`: only the first K files by name, read as browsing reads them (a sample of a slow
|
||||
// network folder)
|
||||
let t = Instant::now();
|
||||
let (photos, ids): (u64, Vec<PhotoId>) = match files {
|
||||
None => {
|
||||
let r = s.execute("library.browse", &json!({"path": folder.display().to_string()})).map_err(|e| e.to_string())?;
|
||||
(r["photos"].as_u64().unwrap_or(0), s.visible_cloned())
|
||||
}
|
||||
Some(k) => {
|
||||
let mut list: Vec<String> = std::fs::read_dir(&folder)
|
||||
.map_err(|e| format!("{}: {e}", folder.display()))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file() && lightcraft_engine::import::is_supported(p))
|
||||
.map(|p| p.display().to_string())
|
||||
.collect();
|
||||
list.sort();
|
||||
list.truncate(k);
|
||||
let r = s.execute("library.import", &json!({"paths": list, "mode": "add", "local": true})).map_err(|e| e.to_string())?;
|
||||
let ids: Vec<PhotoId> = r["imported"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(PhotoId).collect();
|
||||
(ids.len() as u64, ids)
|
||||
}
|
||||
};
|
||||
let browse_ms = ms_since(t);
|
||||
let what = if files.is_some() { "first files" } else { "whole folder" };
|
||||
println!("browse {photos} photos ({what}): {browse_ms:.1} ms wall");
|
||||
out["browse"] = json!({"ms": round(browse_ms), "photos": photos, "perPhotoMs": round(browse_ms / photos.max(1) as f64)});
|
||||
let paths: Vec<String> = ids
|
||||
.iter()
|
||||
.filter_map(|id| match &s.catalog.photo(*id)?.source {
|
||||
lightcraft_engine::catalog::Source::File { path } => Some(path.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if paths.is_empty() {
|
||||
return Err(format!("{}: no photos", folder.display()));
|
||||
}
|
||||
let loader = s.media.preview_loader.clone().ok_or("no preview loader")?;
|
||||
|
||||
// --- grid thumbnails: the first screen, in parallel ------------------------------------------
|
||||
let screen: Vec<String> = paths.iter().take(48).cloned().collect();
|
||||
let next = Arc::new(AtomicUsize::new(0));
|
||||
let t = Instant::now();
|
||||
let per: Vec<(f64, f64)> = std::thread::scope(|sc| {
|
||||
let workers: Vec<_> = (0..render_threads())
|
||||
.map(|_| {
|
||||
let (next, loader, screen) = (next.clone(), loader.clone(), &screen);
|
||||
sc.spawn(move || {
|
||||
let mut done = Vec::new();
|
||||
while let Some(p) = screen.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
let a = Instant::now();
|
||||
let _ = loader(p, 512);
|
||||
done.push((ms_since(a), ms_since(t)));
|
||||
}
|
||||
done
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect()
|
||||
});
|
||||
let first = per.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
|
||||
let all = per.iter().map(|p| p.1).fold(0.0, f64::max);
|
||||
let each = stats(&per.iter().map(|p| p.0).collect::<Vec<_>>());
|
||||
println!("grid: first thumbnail: {first:.1} ms wall");
|
||||
println!("grid: {} thumbnails: {all:.1} ms wall", per.len());
|
||||
line("grid: one 512 px thumbnail", &each);
|
||||
out["thumbs"] = json!({"firstMs": round(first), "allMs": round(all), "count": per.len(), "each": each});
|
||||
|
||||
// --- camera previews at loupe sizes, one at a time (what a step costs without look-ahead) -----
|
||||
let sample = sample_after(&paths, 48, 20);
|
||||
for edge in [1280usize, 2560, usize::MAX] {
|
||||
let ms: Vec<f64> = sample
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let a = Instant::now();
|
||||
let _ = loader(p, edge);
|
||||
ms_since(a)
|
||||
})
|
||||
.collect();
|
||||
let name = if edge == usize::MAX { "camera preview full size (100 %)".to_string() } else { format!("camera preview {edge} px") };
|
||||
let st = stats(&ms);
|
||||
line(&name, &st);
|
||||
out[if edge == usize::MAX { "cameraFull".to_string() } else { format!("camera{edge}") }] = st;
|
||||
}
|
||||
|
||||
// --- LightCraft's loupe render (2560 px) from a cold source --------------------------------
|
||||
let ms: Vec<f64> = sample_after(&ids, 80, 5)
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let job = s.loupe_job(*id, 2560, 1708, true)?;
|
||||
let a = Instant::now();
|
||||
let r = job.run();
|
||||
let t = ms_since(a);
|
||||
r.rendered.is_ok().then_some(t)
|
||||
})
|
||||
.collect();
|
||||
let st = stats(&ms);
|
||||
line("loupe render 2560 px (cold)", &st);
|
||||
out["loupeRender"] = st;
|
||||
|
||||
// --- rating: a culling pass of keypresses ---------------------------------------------------
|
||||
let ms: Vec<f64> = ids
|
||||
.iter()
|
||||
.take(50)
|
||||
.enumerate()
|
||||
.filter_map(|(k, id)| {
|
||||
// the key acts on the selected photo, as in the loupe
|
||||
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).ok()?;
|
||||
let a = Instant::now();
|
||||
s.execute("photo.rate", &json!({"rating": (k % 5) + 1})).ok()?;
|
||||
Some(ms_since(a))
|
||||
})
|
||||
.collect();
|
||||
let st = stats(&ms);
|
||||
line("rate one photo (journal written)", &st);
|
||||
out["rate"] = st;
|
||||
drop(s);
|
||||
|
||||
// --- import: add in place, then copy ----------------------------------------------------------
|
||||
if n == 0 {
|
||||
return finish(out, json_out);
|
||||
}
|
||||
let add: Vec<String> = paths.iter().take(n).cloned().collect();
|
||||
let mut s = library(&fresh_dir(&work, "lib-add")?)?;
|
||||
let t = Instant::now();
|
||||
let r = s.execute("library.import", &json!({"paths": add, "mode": "add"})).map_err(|e| e.to_string())?;
|
||||
let add_ms = ms_since(t);
|
||||
let added = r["imported"].as_array().map(Vec::len).unwrap_or(0);
|
||||
println!("import {added} photos in place: {add_ms:.1} ms wall");
|
||||
out["importAdd"] = json!({"ms": round(add_ms), "photos": added, "perPhotoMs": round(add_ms / added.max(1) as f64)});
|
||||
drop(s);
|
||||
if copy > 0 {
|
||||
let some: Vec<String> = paths.iter().take(copy).cloned().collect();
|
||||
let lib = fresh_dir(&work, "lib-copy")?;
|
||||
let mut s = library(&lib)?;
|
||||
let t = Instant::now();
|
||||
let r = s
|
||||
.execute("library.import", &json!({"paths": some, "mode": "copy", "destination": lib.join("Originals").display().to_string()}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let copy_ms = ms_since(t);
|
||||
let copied = r["imported"].as_array().map(Vec::len).unwrap_or(0);
|
||||
println!("import {copied} photos by copying: {copy_ms:.1} ms wall");
|
||||
out["importCopy"] = json!({"ms": round(copy_ms), "photos": copied, "perPhotoMs": round(copy_ms / copied.max(1) as f64)});
|
||||
drop(s);
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
}
|
||||
finish(out, json_out)
|
||||
}
|
||||
|
||||
fn finish(out: Value, json_out: Option<PathBuf>) -> Result<(), String> {
|
||||
if let Some(p) = json_out {
|
||||
write_replacing(&p, serde_json::to_string_pretty(&out).unwrap_or_default().as_bytes())?;
|
||||
}
|
||||
println!("{}", serde_json::to_string(&out).unwrap_or_default());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through a new file next to it, renamed over `path`: an existing `path`
|
||||
/// is replaced as a name, never written into. A hard link there shares its data with another file
|
||||
/// (maybe a photo in the source folder, which [`inside_source`] can't tell), and writing into it
|
||||
/// would overwrite that file too (CodeRabbit on #3077). The temporary file is removed on error.
|
||||
fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
let err = |e: std::io::Error| format!("{}: {e}", path.display());
|
||||
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
let name = path.file_name().ok_or_else(|| format!("{}: not a file name", path.display()))?;
|
||||
static TEMPS: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = TEMPS.fetch_add(1, Ordering::Relaxed);
|
||||
let mut tmp_name = std::ffi::OsString::from(".");
|
||||
tmp_name.push(name);
|
||||
tmp_name.push(format!(".{}-{n}.tmp", std::process::id()));
|
||||
let tmp = dir.join(tmp_name);
|
||||
let written =
|
||||
std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|()| f.sync_all()));
|
||||
if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(err(e));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_second_folder_is_an_error() {
|
||||
let e = run(&["a".to_string(), "b".to_string()]).unwrap_err();
|
||||
assert!(e.starts_with("b: one FOLDER only"), "{e}");
|
||||
}
|
||||
|
||||
/// `--work` may hold anything: a run makes a new folder of its own there and never deletes
|
||||
/// what is already in it (it used to remove `lib-browse`, `lib-add` and `lib-copy` there).
|
||||
#[test]
|
||||
fn a_run_never_deletes_what_is_under_work() {
|
||||
// a folder this test owns (made new), so the cleanup below removes nothing else
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let keep = work.join("lib-browse").join("keep.txt");
|
||||
std::fs::create_dir_all(keep.parent().unwrap()).unwrap();
|
||||
std::fs::write(&keep, b"mine").unwrap();
|
||||
let a = run_dir(&work).unwrap();
|
||||
let b = run_dir(&work).unwrap();
|
||||
assert_ne!(a, b);
|
||||
fresh_dir(&a, "lib-browse").unwrap();
|
||||
assert!(fresh_dir(&a, "lib-browse").is_err(), "an existing folder is never reused");
|
||||
assert_eq!(std::fs::read(&keep).unwrap(), b"mine");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// A folder too small for the disjoint samples is measured on the photos it has (CodeRabbit on #3077).
|
||||
#[test]
|
||||
fn a_small_folder_is_sampled_from_its_start() {
|
||||
let v: Vec<u32> = (0..100).collect();
|
||||
assert_eq!(sample_after(&v, 48, 20), &v[48..68]);
|
||||
assert_eq!(sample_after(&v, 90, 20), &v[90..100]);
|
||||
assert_eq!(sample_after(&v[..3], 48, 20), &v[..3]);
|
||||
assert_eq!(sample_after(&v[..48], 48, 5), &v[..5]);
|
||||
assert!(sample_after::<u32>(&[], 48, 20).is_empty());
|
||||
}
|
||||
|
||||
/// A file link at `at` to `target`.
|
||||
#[cfg(unix)]
|
||||
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
|
||||
std::os::unix::fs::symlink(target, at)
|
||||
}
|
||||
|
||||
/// A file link at `at` to `target` (Windows: needs Developer Mode or the right to make links).
|
||||
#[cfg(windows)]
|
||||
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
|
||||
std::os::windows::fs::symlink_file(target, at)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn link(_: &Path, _: &Path) -> std::io::Result<()> {
|
||||
Err(std::io::Error::other("no file links here"))
|
||||
}
|
||||
|
||||
/// `--json` naming a link (made elsewhere) to a file in the source folder is refused: writing
|
||||
/// the results would follow it and overwrite a photo (CodeRabbit on #3080). So is a link that
|
||||
/// points to a file not made yet in the source folder, and a loop of links.
|
||||
#[test]
|
||||
fn a_json_link_into_the_source_folder_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let photo = src.join("a.jpg");
|
||||
std::fs::write(&photo, b"photo").unwrap();
|
||||
let to_photo = work.join("report.json");
|
||||
if let Err(e) = link(&photo, &to_photo) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
|
||||
return;
|
||||
}
|
||||
assert!(inside_source(&to_photo, &src), "a link to a photo in the source folder");
|
||||
let e = check_outputs(&src, Some(&to_photo), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json"), "{e}");
|
||||
let to_new = work.join("new.json");
|
||||
link(&src.join("not-yet.json"), &to_new).unwrap();
|
||||
assert!(inside_source(&to_new, &src), "a link to a file not made yet in the source folder");
|
||||
let (x, y) = (work.join("x.json"), work.join("y.json"));
|
||||
link(&y, &x).unwrap();
|
||||
link(&x, &y).unwrap();
|
||||
assert!(inside_source(&x, &src), "a loop of links");
|
||||
let to_elsewhere = work.join("fine.json");
|
||||
link(&work.join("out.json"), &to_elsewhere).unwrap();
|
||||
assert!(!inside_source(&to_elsewhere, &src), "a link to a file outside is fine");
|
||||
assert_eq!(std::fs::read(&photo).unwrap(), b"photo");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a link that sits in the source folder and points to a file outside it is
|
||||
/// refused: writing the results would replace the link itself, an entry of the source folder
|
||||
/// (CodeRabbit on #3080). The link stays as it was.
|
||||
#[test]
|
||||
fn a_json_link_in_the_source_folder_to_a_file_outside_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let outside = work.join("out.json");
|
||||
std::fs::write(&outside, b"outside").unwrap();
|
||||
let in_src = src.join("a.jpg");
|
||||
if let Err(e) = link(&outside, &in_src) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
|
||||
return;
|
||||
}
|
||||
assert!(inside_source(&in_src, &src), "a link in the source folder, wherever it points");
|
||||
let e = check_outputs(&src, Some(&in_src), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json"), "{e}");
|
||||
assert!(std::fs::symlink_metadata(&in_src).unwrap().file_type().is_symlink(), "the link stays");
|
||||
assert_eq!(std::fs::read_link(&in_src).unwrap(), outside);
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"outside");
|
||||
// a new file in the source folder (nothing there yet) is refused too
|
||||
assert!(check_outputs(&src, Some(&src.join("new.json")), &work.join("elsewhere")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a hard link (made elsewhere) to a photo in the source folder passes
|
||||
/// [`inside_source`] (a hard link has no target to resolve), so the results replace the link
|
||||
/// instead of writing into it: the photo keeps its bytes (CodeRabbit on #3077).
|
||||
#[test]
|
||||
fn a_json_hard_link_to_a_photo_leaves_the_photo_alone() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let photo = src.join("a.jpg");
|
||||
std::fs::write(&photo, b"photo").unwrap();
|
||||
let report = work.join("report.json");
|
||||
if let Err(e) = std::fs::hard_link(&photo, &report) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a hard link here ({e})");
|
||||
return;
|
||||
}
|
||||
finish(json!({"browse": 1}), Some(report.clone())).unwrap();
|
||||
assert_eq!(std::fs::read(&photo).unwrap(), b"photo", "the photo is unchanged");
|
||||
let written: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap();
|
||||
assert_eq!(written["browse"], 1);
|
||||
let left: Vec<_> = std::fs::read_dir(&work).unwrap().flatten().map(|e| e.file_name()).collect();
|
||||
assert_eq!(left.len(), 2, "no temporary file is left: {left:?}");
|
||||
// a folder that isn't there: an error, nothing panics
|
||||
assert!(write_replacing(&work.join("missing").join("r.json"), b"x").is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a file in the source folder is refused (CodeRabbit on #3077); elsewhere it is fine.
|
||||
#[test]
|
||||
fn the_results_never_go_in_the_source_folder() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let sub = fresh_dir(&src, "sub").unwrap();
|
||||
assert!(inside_source(&src.join("a.png"), &src));
|
||||
assert!(inside_source(&sub.join("x.json"), &src));
|
||||
assert!(inside_source(&src.join("sub").join("..").join("a.png"), &src));
|
||||
assert!(!inside_source(&work.join("out.json"), &src));
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--work` in the source folder is refused before anything is made there, also when it doesn't
|
||||
/// exist yet (CodeRabbit on #3077); elsewhere it is fine.
|
||||
#[test]
|
||||
fn the_work_folder_never_goes_in_the_source_folder() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let inside = src.join("out").join("deeper");
|
||||
let e = check_outputs(&src, None, &inside).unwrap_err();
|
||||
assert!(e.contains("--work"), "{e}");
|
||||
assert!(check_outputs(&src, None, &src).is_err(), "the source folder itself");
|
||||
assert!(!src.join("out").exists(), "nothing was made in the source folder");
|
||||
assert!(check_outputs(&src, None, &work.join("elsewhere")).is_ok());
|
||||
assert!(check_outputs(&src, Some(&src.join("r.json")), &work.join("elsewhere")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// A `..` in `--json` or `--work` is refused: after a folder the run hasn't made yet it can't be
|
||||
/// resolved now, and would lead into the source folder once the run makes it (CodeRabbit on #3544).
|
||||
#[test]
|
||||
fn a_dot_dot_in_the_outputs_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let sneaky = work.join("new").join("..").join("src").join("r.json");
|
||||
let e = check_outputs(&src, Some(&sneaky), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json") && e.contains(".."), "{e}");
|
||||
let e = check_outputs(&src, None, &work.join("new").join("..").join("src")).unwrap_err();
|
||||
assert!(e.contains("--work"), "{e}");
|
||||
assert!(!work.join("new").exists(), "nothing was made");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
}
|
||||
@@ -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 <model>.json to DIR (default: the profiles folder LightCraft reads,
|
||||
<config>/camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then
|
||||
take their colour from the profile and only their tone from their own JPEG.
|
||||
lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
|
||||
Time what culling a shoot costs on its own files: reading the folder (browse), the first
|
||||
screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render,
|
||||
rating, and importing N files in place (default 2000) and copying M (default 200). Libraries
|
||||
are made in a new folder under DIR (default: the temp folder); nothing is written next to the
|
||||
photos. --files K reads only the first K files by name (a sample of a slow network folder).
|
||||
lightcraft-cli --version | --help
|
||||
";
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -101,6 +101,75 @@ fn gradient_png(path: &std::path::Path) {
|
||||
std::fs::write(path, png).unwrap();
|
||||
}
|
||||
|
||||
/// PERF-CULL-5: `bench-cull` times a folder end to end and writes nothing next to the photos.
|
||||
#[test]
|
||||
fn bench_cull_times_a_folder_and_leaves_it_untouched() {
|
||||
let dir = tmp("bench-cull-src");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (seed, name) in ["a.png", "b.png", "c.png"].iter().enumerate() {
|
||||
// three different pictures (the same bytes would import as one photo)
|
||||
let img = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, (seed * 80) as u8, 255]);
|
||||
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
|
||||
std::fs::write(dir.join(name), png).unwrap();
|
||||
}
|
||||
// every file's name and bytes: nothing added, and no photo written into (CodeRabbit on #3577)
|
||||
let listing = |d: &std::path::Path| {
|
||||
let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(d)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap())
|
||||
.map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read(e.path()).unwrap()))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
let before = listing(&dir);
|
||||
let work = tmp("bench-cull-work");
|
||||
let json_out = tmp("bench-cull.json");
|
||||
let r = Command::new(binary())
|
||||
.arg("bench-cull")
|
||||
.arg(&dir)
|
||||
.args(["--n", "3", "--copy", "1", "--work"])
|
||||
.arg(&work)
|
||||
.arg("--json")
|
||||
.arg(&json_out)
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&r.stdout);
|
||||
assert!(r.status.success(), "{stdout}{}", String::from_utf8_lossy(&r.stderr));
|
||||
assert!(stdout.contains("browse 3 photos") && stdout.contains("ms wall"), "{stdout}");
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(&json_out).unwrap()).unwrap();
|
||||
assert_eq!(v["browse"]["photos"], 3);
|
||||
assert_eq!(v["importAdd"]["photos"], 3);
|
||||
assert_eq!(v["importCopy"]["photos"], 1);
|
||||
assert_eq!(v["rate"]["n"], 3);
|
||||
// a folder smaller than the samples is measured on the photos it has, not reported empty
|
||||
for stage in ["camera1280", "camera2560", "cameraFull", "loupeRender"] {
|
||||
assert_eq!(v[stage]["n"], 3, "{stage}: {}", v[stage]);
|
||||
}
|
||||
assert_eq!(listing(&dir), before, "nothing written next to the photos");
|
||||
// results asked for in the source folder: refused, the photo untouched
|
||||
let photo = std::fs::read(dir.join("a.png")).unwrap();
|
||||
let r = Command::new(binary())
|
||||
.arg("bench-cull")
|
||||
.arg(&dir)
|
||||
.args(["--n", "0", "--work"])
|
||||
.arg(&work)
|
||||
.arg("--json")
|
||||
.arg(dir.join("a.png"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("--json"), "{}", String::from_utf8_lossy(&r.stderr));
|
||||
assert_eq!(std::fs::read(dir.join("a.png")).unwrap(), photo);
|
||||
assert_eq!(listing(&dir), before);
|
||||
// a sample of the folder, no import
|
||||
let r = Command::new(binary()).arg("bench-cull").arg(&dir).args(["--files", "2", "--n", "0", "--work"]).arg(&work).output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&r.stdout);
|
||||
assert!(r.status.success() && stdout.contains("browse 2 photos (first files)") && !stdout.contains("import"), "{stdout}");
|
||||
// a bad folder is an error, not a panic
|
||||
let r = Command::new(binary()).args(["bench-cull", "/no/such/folder"]).output().unwrap();
|
||||
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("not a folder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibrate_reads_raf_inputs_and_reports_bad_files() {
|
||||
let input = tmp("invalid.RAF");
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,632 @@
|
||||
//! The bridge to a host page (issue #2270): a same-origin page embeds LightCraft in an `<iframe>`
|
||||
//! (`?host=parent`) or in its own document (`data-host="page"` on the canvas). The protocol is
|
||||
//! the one PdfCraft, GridCraft and DeckCraft speak, with `lightcraft:` message types:
|
||||
//!
|
||||
//! - `lightcraft:ready` (to the parent): `{ version }`, the app is listening.
|
||||
//! - `lightcraft:failed` (to the parent): `{ error }`, the app couldn't start, or it refused a
|
||||
//! `lightcraft:open` (a file larger than a library backup can hold, [`crate::backup::MAX_BYTES`]).
|
||||
//! - `lightcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
|
||||
//! `Uint8Array`. The photo is added to the library, as one dropped on the window is; `name`
|
||||
//! gives the format (its extension), `photo.jpg` when missing.
|
||||
//! - `lightcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
|
||||
//! file LightCraft would otherwise download: exports and the library backup (the preset, keyword
|
||||
//! and curve file dialogs have no web implementation yet). The parent stores it and reports
|
||||
//! failures itself.
|
||||
//! - `lightcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
|
||||
//! On the web every change is written to browser storage a moment after it is made, so `dirty`
|
||||
//! means "closing the page right now would lose something": a write still queued or running,
|
||||
//! or changes that storage refused (quota).
|
||||
//! - `lightcraft:cmd` (from the parent): `{ id, params }`, params a JSON string (`{}` when
|
||||
//! missing, empty or `null`; anything but a JSON object is refused unrun, see [`crate::automation::params`]).
|
||||
//! Runs the command by id, like `lightcraft.command(..)` from the page itself, and answers with
|
||||
//! `lightcraft:response` `{ ok, value }` (the JSON result, or the error text).
|
||||
//! Responses carry no request id (none of the sibling bridges' do): they come back in the order
|
||||
//! the commands were sent, one per `cmd` that had an id; a `cmd` without one gets no response.
|
||||
//!
|
||||
//! Only the parent window on the page's own origin is heard or answered. A page whose origin is
|
||||
//! opaque (`"null"`: a sandboxed iframe, a `data:` page) gets no bridge at all, since every other
|
||||
//! opaque-origin window would then pass as the parent. A parent on another origin gets no bridge
|
||||
//! either: its `location` cannot be read, and exports keep downloading. There is no `docClosed`: LightCraft has a
|
||||
//! library, not documents that close.
|
||||
//!
|
||||
//! ## `data-host="page"` — the page's own document
|
||||
//!
|
||||
//! A page can also run LightCraft in its own document, no iframe: the canvas opts in with
|
||||
//! `data-host="page"`, and the same messages travel as DOM `CustomEvent`s on the canvas instead
|
||||
//! of `postMessage` — outward with the message's fields as the event's `detail`, inward as
|
||||
//! `lightcraft:open` and `lightcraft:cmd` events the page dispatches on the canvas. Events don't
|
||||
//! bubble, so two editors on one page can't hear each other, and the canvas is the only target
|
||||
//! the bridge listens on.
|
||||
//!
|
||||
//! The message layer (what a message means, what is sent back) is plain Rust, tested natively;
|
||||
//! [`Bridge`] (wasm32 only) moves it over `postMessage`, or over DOM events in page mode.
|
||||
|
||||
/// A message from the parent page, once understood.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Incoming {
|
||||
/// `lightcraft:open`: add this photo to the library.
|
||||
Open { name: String, bytes: Vec<u8> },
|
||||
/// `lightcraft:cmd`: run this command (params as JSON text).
|
||||
Cmd { id: String, params: String },
|
||||
/// `lightcraft:open` with a file too large to keep: tell the parent why (`lightcraft:failed`).
|
||||
Refused(String),
|
||||
}
|
||||
|
||||
/// The fields of a message from the parent, as read off the event (each may be missing).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Raw {
|
||||
pub kind: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub bytes: Option<Vec<u8>>,
|
||||
pub id: Option<String>,
|
||||
pub params: Option<String>,
|
||||
/// The size of `bytes` when it was too large to copy (`bytes` is then `None`).
|
||||
pub oversize: Option<u64>,
|
||||
}
|
||||
|
||||
/// Why a photo of `len` bytes sent with `lightcraft:open` is refused, or `None` when it fits: one
|
||||
/// larger than a library backup can hold ([`crate::backup::MAX_BYTES`]) is never copied in.
|
||||
pub fn open_size_error(len: u64) -> Option<String> {
|
||||
let max = crate::backup::MAX_BYTES;
|
||||
(len > max).then(|| format!("the file is too large to open ({} MB; the limit is {} MB)", len >> 20, max >> 20))
|
||||
}
|
||||
|
||||
/// The name a photo sent without one is stored under (its extension picks the decoder).
|
||||
pub const DEFAULT_OPEN_NAME: &str = "photo.jpg";
|
||||
|
||||
impl Incoming {
|
||||
/// What the parent asked for; `None` for a message type that isn't ours, an `open` without
|
||||
/// bytes or a `cmd` without an id (dropped, the page's other messages are none of our business).
|
||||
pub fn parse(raw: Raw) -> Option<Incoming> {
|
||||
match raw.kind.as_deref() {
|
||||
Some("lightcraft:open") => {
|
||||
if let Some(error) = raw.oversize.and_then(open_size_error) {
|
||||
return Some(Incoming::Refused(error));
|
||||
}
|
||||
let name = raw.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| DEFAULT_OPEN_NAME.to_string());
|
||||
Some(Incoming::Open { name, bytes: raw.bytes? })
|
||||
}
|
||||
Some("lightcraft:cmd") => {
|
||||
let id = raw.id.filter(|i| !i.trim().is_empty())?;
|
||||
Some(Incoming::Cmd { id, params: raw.params.filter(|p| !p.trim().is_empty()).unwrap_or_else(|| "{}".to_string()) })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A field of a message to the parent.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Field {
|
||||
Str(String),
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// A message to the parent, without bytes (`lightcraft:save` carries a transferred buffer and is
|
||||
/// built by the bridge itself).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Outgoing {
|
||||
Ready,
|
||||
Failed(String),
|
||||
Dirty(bool),
|
||||
/// How a `lightcraft:cmd` ended: the JSON result, or the error text.
|
||||
Response {
|
||||
ok: bool,
|
||||
value: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Outgoing {
|
||||
/// The message's fields, `type` first.
|
||||
pub fn fields(&self) -> Vec<(&'static str, Field)> {
|
||||
match self {
|
||||
Outgoing::Ready => vec![("type", Field::Str("lightcraft:ready".into())), ("version", Field::Str(env!("CARGO_PKG_VERSION").into()))],
|
||||
Outgoing::Failed(error) => vec![("type", Field::Str("lightcraft:failed".into())), ("error", Field::Str(error.clone()))],
|
||||
Outgoing::Dirty(dirty) => vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(*dirty))],
|
||||
Outgoing::Response { ok, value } => {
|
||||
vec![("type", Field::Str("lightcraft:response".into())), ("ok", Field::Bool(*ok)), ("value", Field::Str(value.clone()))]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The unsaved-changes state as the parent last heard it: `lightcraft:dirty` goes out only when
|
||||
/// it changes (not every frame), and a message that couldn't be sent is sent again next time.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DirtyReport {
|
||||
reported: Option<bool>,
|
||||
}
|
||||
|
||||
impl DirtyReport {
|
||||
/// `Some(message)` when `dirty` differs from what the parent knows; call [`DirtyReport::sent`]
|
||||
/// once it went out.
|
||||
pub fn change(&self, dirty: bool) -> Option<Outgoing> {
|
||||
(self.reported != Some(dirty)).then_some(Outgoing::Dirty(dirty))
|
||||
}
|
||||
|
||||
pub fn sent(&mut self, dirty: bool) {
|
||||
self.reported = Some(dirty);
|
||||
}
|
||||
|
||||
/// Record `dirty` before the send. A page host can report another state while the event is
|
||||
/// still dispatching, and that later report wins. Returns the message to send and the state
|
||||
/// to put back if this send fails and nothing else recorded one.
|
||||
pub fn prepare(&mut self, dirty: bool) -> (Option<Outgoing>, Option<bool>) {
|
||||
let previous = self.reported;
|
||||
let message = self.change(dirty);
|
||||
if message.is_some() {
|
||||
self.sent(dirty);
|
||||
}
|
||||
(message, previous)
|
||||
}
|
||||
|
||||
/// Forget a send that failed, unless a nested report already recorded a different state.
|
||||
pub fn restore_if_unchanged(&mut self, dirty: bool, previous: Option<bool>) {
|
||||
if self.reported == Some(dirty) {
|
||||
self.reported = previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a page origin can tell the parent apart from any other window: an opaque origin
|
||||
/// (`"null"`, as a sandboxed iframe or a `data:` page has) cannot, so such a page gets no bridge.
|
||||
pub fn origin_is_usable(origin: &str) -> bool {
|
||||
let o = origin.trim();
|
||||
!o.is_empty() && o != "null"
|
||||
}
|
||||
|
||||
/// The name a saved file is handed over under: the file name of the path the export chose.
|
||||
pub fn save_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
/// The one `data-host` value that opts a page into page host mode: the exact string `"page"`.
|
||||
pub const PAGE_HOST: &str = "page";
|
||||
|
||||
/// How a host page reaches the app. The modes behave the same; they differ only in how an event
|
||||
/// goes out ([`Bridge::post`] and `save`, wasm32) and how one comes in ([`Bridge::listen`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// `?host=parent`: the page framed LightCraft in an `<iframe>`; `postMessage`.
|
||||
Parent,
|
||||
/// `data-host="page"`: the page runs LightCraft in its own document; DOM `CustomEvent`s.
|
||||
Page,
|
||||
}
|
||||
|
||||
/// The mode the page asked for. `?host=parent` wins when the page asks for both, the same order
|
||||
/// as the other apps. Page mode is the exact `data-host="page"` ([`PAGE_HOST`]). `None` with
|
||||
/// neither, so that URL stays the normal app with downloads.
|
||||
pub fn transport_for(data_host: Option<&str>, query: &str) -> Option<Mode> {
|
||||
if host_parent_requested(query) {
|
||||
Some(Mode::Parent)
|
||||
} else if data_host == Some(PAGE_HOST) {
|
||||
Some(Mode::Page)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The message type. A page-mode `CustomEvent` is named `lightcraft:open` or `lightcraft:cmd`
|
||||
/// and its `detail` is only the fields, so the event name is the type. A parent `postMessage`
|
||||
/// carries `type` in the object and has no event name.
|
||||
pub fn incoming_kind(event_name: Option<&str>, detail_type: Option<String>) -> Option<String> {
|
||||
event_name.map(str::to_string).or(detail_type)
|
||||
}
|
||||
|
||||
/// Does the query ask for the parent bridge? The same reading of `?host=parent` the URL options
|
||||
/// always used: the first `host` parameter whose value is exactly `parent`.
|
||||
pub fn host_parent_requested(query: &str) -> bool {
|
||||
query.trim_start_matches('?').split('&').find_map(|p| {
|
||||
let (k, v) = p.split_once('=').unwrap_or((p, ""));
|
||||
(k == "host").then_some(v == "parent")
|
||||
}) == Some(true)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub use bridge::Bridge;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod bridge {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
|
||||
use super::{DirtyReport, Field, Incoming, Mode, Outgoing, Raw, open_size_error, origin_is_usable, save_name};
|
||||
|
||||
/// How an event goes to the host page, per mode ([`Mode`]).
|
||||
#[derive(Clone)]
|
||||
enum Transport {
|
||||
/// `?host=parent`: `postMessage` between same-origin windows.
|
||||
Parent { parent: web_sys::Window, origin: String },
|
||||
/// `data-host="page"`: DOM `CustomEvent`s on the editor's own canvas.
|
||||
Page { canvas: web_sys::HtmlCanvasElement },
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
/// Hand an event to the host. Parent mode: a `postMessage` whose `type` field is `event`
|
||||
/// (the same message as before, transferring `transfer` when given). Page mode: a
|
||||
/// non-bubbling `CustomEvent` of that name on the canvas, whose `detail` holds the
|
||||
/// fields; nothing is transferred there, the buffer just rides inside `detail`.
|
||||
fn send(&self, event: &str, fields: &[(&str, JsValue)], transfer: Option<&js_sys::ArrayBuffer>) -> Result<(), String> {
|
||||
match self {
|
||||
Transport::Parent { parent, origin } => {
|
||||
let mut all = Vec::with_capacity(fields.len() + 1);
|
||||
all.push(("type", JsValue::from_str(event)));
|
||||
all.extend_from_slice(fields);
|
||||
let message = message(&all).ok_or_else(|| "couldn't build the message".to_string())?;
|
||||
let sent = match transfer {
|
||||
Some(buffer) => parent.post_message_with_transfer(&message, origin, &js_sys::Array::of1(buffer)),
|
||||
None => parent.post_message(&message, origin),
|
||||
};
|
||||
sent.map_err(|e| js_error(&e, "couldn't post the message"))
|
||||
}
|
||||
Transport::Page { canvas } => {
|
||||
let detail = message(fields).ok_or_else(|| "couldn't build the event detail".to_string())?;
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_bubbles(false);
|
||||
init.set_detail(&detail);
|
||||
let custom =
|
||||
web_sys::CustomEvent::new_with_event_init_dict(event, &init).map_err(|e| js_error(&e, "couldn't create the event"))?;
|
||||
canvas.dispatch_event(&custom).map_err(|e| js_error(&e, "couldn't dispatch the event"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The host page's end of the bridge (cheap to clone; one per page).
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
transport: Transport,
|
||||
/// What the host sent since the last frame, oldest first.
|
||||
incoming: Rc<RefCell<Vec<Incoming>>>,
|
||||
dirty: Rc<RefCell<DirtyReport>>,
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
/// The parent bridge for `?host=parent`. `None` when the page isn't framed, its origin is
|
||||
/// opaque, or the parent is on another origin (exports then keep downloading).
|
||||
pub fn new() -> Option<Self> {
|
||||
let window = web_sys::window()?;
|
||||
let parent = window.parent().ok().flatten()?;
|
||||
if js_sys::Object::is(&parent, &window) {
|
||||
return None;
|
||||
}
|
||||
// the document's own origin (`window.origin`), not the URL's: a sandboxed iframe keeps
|
||||
// its URL but runs with the opaque origin "null"
|
||||
let origin = window.origin();
|
||||
if !origin_is_usable(&origin) {
|
||||
return None;
|
||||
}
|
||||
// Reading another origin's location throws, so this is `None` for a cross-origin parent.
|
||||
if parent.location().origin().ok().as_deref() != Some(origin.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { transport: Transport::Parent { parent, origin }, incoming: Rc::default(), dirty: Rc::default() })
|
||||
}
|
||||
|
||||
/// The page bridge for `data-host="page"`: the host page runs LightCraft in its own
|
||||
/// document and hears the app's DOM `CustomEvent`s on this canvas.
|
||||
pub fn for_page(canvas: &web_sys::HtmlCanvasElement) -> Self {
|
||||
Self { transport: Transport::Page { canvas: canvas.clone() }, incoming: Rc::default(), dirty: Rc::default() }
|
||||
}
|
||||
|
||||
/// The bridge for the mode the page opted into (`host::transport_for`): page mode needs
|
||||
/// its canvas, and parent mode falls back to `None` as [`Bridge::new`] always did.
|
||||
pub fn for_mode(mode: Mode, canvas: Option<&web_sys::HtmlCanvasElement>) -> Option<Self> {
|
||||
match mode {
|
||||
Mode::Page => canvas.map(Self::for_page),
|
||||
Mode::Parent => Self::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hear the host from now on; a message wakes the app for the next frame.
|
||||
pub fn listen(&self, ctx: egui::Context) {
|
||||
match &self.transport {
|
||||
Transport::Parent { parent, origin } => {
|
||||
let parent = parent.clone();
|
||||
let origin = origin.clone();
|
||||
let incoming = self.incoming.clone();
|
||||
let on_message = Closure::<dyn Fn(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
|
||||
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
|
||||
return;
|
||||
}
|
||||
deliver(&incoming, &ctx, &event.data(), None);
|
||||
});
|
||||
if web_sys::window().is_some_and(|w| w.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok()) {
|
||||
// the listener lives as long as the page
|
||||
on_message.forget();
|
||||
}
|
||||
}
|
||||
Transport::Page { canvas } => {
|
||||
// non-bubbling events: the page dispatches on the canvas, the canvas listens
|
||||
for kind in ["lightcraft:open", "lightcraft:cmd"] {
|
||||
let incoming = self.incoming.clone();
|
||||
let ctx = ctx.clone();
|
||||
let event_type = kind.to_string();
|
||||
// `Fn`, not `FnMut`: a page event is dispatched synchronously, and a host
|
||||
// that answers one event with another would re-enter an `FnMut` listener.
|
||||
let on_custom = Closure::<dyn Fn(web_sys::Event)>::new(move |event: web_sys::Event| {
|
||||
let Some(custom) = event.dyn_ref::<web_sys::CustomEvent>() else { return };
|
||||
deliver(&incoming, &ctx, &custom.detail(), Some(event_type.as_str()));
|
||||
});
|
||||
if canvas.add_event_listener_with_callback(kind, on_custom.as_ref().unchecked_ref()).is_ok() {
|
||||
// the listener lives as long as the page
|
||||
on_custom.forget();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the parent sent since the last frame, oldest first.
|
||||
pub fn take_incoming(&self) -> Vec<Incoming> {
|
||||
std::mem::take(&mut *self.incoming.borrow_mut())
|
||||
}
|
||||
|
||||
/// Post a message; false if it couldn't be sent.
|
||||
pub fn post(&self, m: &Outgoing) -> bool {
|
||||
let fields = m.fields();
|
||||
// every message names its type first (tested natively); the rest go to the transport
|
||||
let Some((_, Field::Str(event))) = fields.first() else { return false };
|
||||
let event = event.clone();
|
||||
let rest: Vec<(&str, JsValue)> = fields.into_iter().skip(1).map(|(k, v)| (k, field(&v))).collect();
|
||||
self.transport.send(&event, &rest, None).is_ok()
|
||||
}
|
||||
|
||||
/// Tell the parent whether closing now would lose something, when that changed.
|
||||
/// The new state is recorded before the send: page mode dispatches synchronously, and a
|
||||
/// host that reports another state from that event wins. A failed send is forgotten
|
||||
/// only when nothing else recorded one, so the next frame retries it.
|
||||
pub fn report_dirty(&self, dirty: bool) {
|
||||
let (message, previous) = self.dirty.borrow_mut().prepare(dirty);
|
||||
if let Some(m) = message
|
||||
&& !self.post(&m)
|
||||
{
|
||||
self.dirty.borrow_mut().restore_if_unchanged(dirty, previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand a file to the parent instead of downloading it (`lightcraft:save`).
|
||||
pub fn save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = save_name(path);
|
||||
let buffer = js_sys::Uint8Array::from(bytes).buffer();
|
||||
self.transfer(&name, buffer)
|
||||
}
|
||||
|
||||
/// [`Bridge::save`] for a blob built outside the wasm heap (the library backup).
|
||||
pub async fn save_blob(&self, name: String, blob: web_sys::Blob) -> Result<(), String> {
|
||||
let buffer = wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await.map_err(|e| format!("{e:?}"))?;
|
||||
self.transfer(&name, buffer.unchecked_into::<js_sys::ArrayBuffer>())
|
||||
}
|
||||
|
||||
fn transfer(&self, name: &str, buffer: js_sys::ArrayBuffer) -> Result<(), String> {
|
||||
self.transport.send("lightcraft:save", &[("name", name.into()), ("bytes", buffer.clone().into())], Some(&buffer))?;
|
||||
log::info!("handed {name} to the page");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A message from the host (the `data` of a window message, or the `detail` of a page-mode
|
||||
/// `CustomEvent`), read with the same field code both transports share, and pushed for the
|
||||
/// next frame.
|
||||
fn deliver(incoming: &Rc<RefCell<Vec<Incoming>>>, ctx: &egui::Context, data: &JsValue, event_type: Option<&str>) {
|
||||
// moved, not cloned: an accepted photo can be hundreds of MB
|
||||
let (bytes, oversize) = match bytes(data) {
|
||||
Some(Ok(b)) => (Some(b), None),
|
||||
Some(Err(len)) => (None, Some(len)),
|
||||
None => (None, None),
|
||||
};
|
||||
let raw = Raw {
|
||||
kind: super::incoming_kind(event_type, string(data, "type")),
|
||||
name: string(data, "name"),
|
||||
bytes,
|
||||
id: string(data, "id"),
|
||||
params: string(data, "params"),
|
||||
oversize,
|
||||
};
|
||||
if let Some(m) = Incoming::parse(raw) {
|
||||
incoming.borrow_mut().push(m);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
fn field(v: &Field) -> JsValue {
|
||||
match v {
|
||||
Field::Str(s) => s.as_str().into(),
|
||||
Field::Bool(b) => (*b).into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
|
||||
let m = js_sys::Object::new();
|
||||
for (key, value) in fields {
|
||||
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
fn string(data: &JsValue, key: &str) -> Option<String> {
|
||||
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
|
||||
}
|
||||
|
||||
/// `bytes` as an `ArrayBuffer` or `Uint8Array`.
|
||||
/// `bytes` as an `ArrayBuffer` or `Uint8Array`, copied only when within the size cap
|
||||
/// ([`open_size_error`]); `Err(len)` for an oversize one, never copied into the app's memory.
|
||||
fn bytes(data: &JsValue) -> Option<Result<Vec<u8>, u64>> {
|
||||
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
|
||||
let array = if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
|
||||
array.clone()
|
||||
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
|
||||
js_sys::Uint8Array::new(&bytes)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let len = u64::from(array.byte_length());
|
||||
Some(if open_size_error(len).is_some() { Err(len) } else { Ok(array.to_vec()) })
|
||||
}
|
||||
|
||||
/// A `JsValue` error as a string, after `what` went wrong.
|
||||
fn js_error(e: &JsValue, what: &str) -> String {
|
||||
format!("{what}: {}", e.as_string().unwrap_or_else(|| format!("{e:?}")))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn raw(kind: &str) -> Raw {
|
||||
Raw { kind: Some(kind.into()), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_needs_bytes_and_names_a_nameless_photo() {
|
||||
let mut m = raw("lightcraft:open");
|
||||
assert_eq!(Incoming::parse(m.clone()), None, "no bytes, nothing to add");
|
||||
m.bytes = Some(vec![1, 2, 3]);
|
||||
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
|
||||
m.name = Some(" ".into());
|
||||
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Open { name: DEFAULT_OPEN_NAME.into(), bytes: vec![1, 2, 3] }));
|
||||
m.name = Some("IMG_0001.CR2".into());
|
||||
assert_eq!(Incoming::parse(m), Some(Incoming::Open { name: "IMG_0001.CR2".into(), bytes: vec![1, 2, 3] }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_needs_an_id_and_defaults_its_params() {
|
||||
let mut m = raw("lightcraft:cmd");
|
||||
assert_eq!(Incoming::parse(m.clone()), None);
|
||||
m.id = Some("library.info".into());
|
||||
assert_eq!(Incoming::parse(m.clone()), Some(Incoming::Cmd { id: "library.info".into(), params: "{}".into() }));
|
||||
m.params = Some(r#"{"rating": 5}"#.into());
|
||||
assert_eq!(Incoming::parse(m), Some(Incoming::Cmd { id: "library.info".into(), params: r#"{"rating": 5}"#.into() }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversize_open_is_refused_not_copied() {
|
||||
let max = crate::backup::MAX_BYTES;
|
||||
assert!(open_size_error(max).is_none());
|
||||
assert!(open_size_error(max + 1).is_some_and(|e| e.contains("too large")));
|
||||
let m = Raw { name: Some("big.tif".into()), oversize: Some(max + 1), ..raw("lightcraft:open") };
|
||||
assert!(matches!(Incoming::parse(m), Some(Incoming::Refused(e)) if e.contains("too large")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_pages_messages_are_not_ours() {
|
||||
for kind in ["deckcraft:open", "lightcraft:save", "lightcraft:ready", ""] {
|
||||
let m = Raw { bytes: Some(vec![1]), id: Some("x".into()), ..raw(kind) };
|
||||
assert_eq!(Incoming::parse(m), None, "{kind:?}");
|
||||
}
|
||||
assert_eq!(Incoming::parse(Raw::default()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_messages_name_their_type_first() {
|
||||
let ready = Outgoing::Ready.fields();
|
||||
assert_eq!(ready[0], ("type", Field::Str("lightcraft:ready".into())));
|
||||
assert_eq!(ready[1].0, "version");
|
||||
assert_eq!(Outgoing::Failed("boom".into()).fields()[1], ("error", Field::Str("boom".into())));
|
||||
assert_eq!(Outgoing::Dirty(true).fields(), vec![("type", Field::Str("lightcraft:dirty".into())), ("dirty", Field::Bool(true))]);
|
||||
let r = Outgoing::Response { ok: false, value: "no such command".into() }.fields();
|
||||
assert_eq!(r[1], ("ok", Field::Bool(false)));
|
||||
assert_eq!(r[2], ("value", Field::Str("no such command".into())));
|
||||
}
|
||||
|
||||
/// The parent hears `dirty` when it changes, not every frame, and again if a send failed.
|
||||
#[test]
|
||||
fn dirty_is_reported_on_change_only() {
|
||||
let mut d = DirtyReport::default();
|
||||
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)), "the first state is news");
|
||||
d.sent(false);
|
||||
assert_eq!(d.change(false), None);
|
||||
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
|
||||
// not marked sent (the post failed): still owed
|
||||
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
|
||||
d.sent(true);
|
||||
assert_eq!(d.change(true), None);
|
||||
assert_eq!(d.change(false), Some(Outgoing::Dirty(false)));
|
||||
}
|
||||
|
||||
/// A failed send is retried. A report that lands during the send (page mode dispatches
|
||||
/// synchronously) is the one that stays.
|
||||
#[test]
|
||||
fn a_failed_dirty_send_is_retried_unless_a_later_report_landed() {
|
||||
let mut d = DirtyReport::default();
|
||||
let (message, previous) = d.prepare(true);
|
||||
assert_eq!(message, Some(Outgoing::Dirty(true)));
|
||||
d.restore_if_unchanged(true, previous);
|
||||
assert_eq!(d.change(true), Some(Outgoing::Dirty(true)));
|
||||
|
||||
let (message, previous) = d.prepare(true);
|
||||
assert!(message.is_some());
|
||||
let (later, _) = d.prepare(false);
|
||||
assert_eq!(later, Some(Outgoing::Dirty(false)));
|
||||
d.restore_if_unchanged(true, previous);
|
||||
assert_eq!(d.change(false), None);
|
||||
}
|
||||
|
||||
/// A canvas event is named for its type; the detail does not have to repeat it.
|
||||
#[test]
|
||||
fn a_page_event_is_named_for_its_type() {
|
||||
assert_eq!(incoming_kind(Some("lightcraft:open"), None).as_deref(), Some("lightcraft:open"));
|
||||
assert_eq!(incoming_kind(Some("lightcraft:cmd"), Some("lightcraft:open".into())).as_deref(), Some("lightcraft:cmd"));
|
||||
assert_eq!(incoming_kind(None, Some("lightcraft:open".into())).as_deref(), Some("lightcraft:open"));
|
||||
assert_eq!(incoming_kind(None, None), None);
|
||||
}
|
||||
|
||||
/// A sandboxed iframe or a `data:` page has the opaque origin `"null"`, which any other such
|
||||
/// window shares: no bridge there, so the origin check keeps meaning something.
|
||||
#[test]
|
||||
fn an_opaque_origin_gets_no_bridge() {
|
||||
assert!(origin_is_usable("https://photos.example"));
|
||||
assert!(origin_is_usable("http://localhost:8080"));
|
||||
assert!(!origin_is_usable("null"));
|
||||
assert!(!origin_is_usable(" null "));
|
||||
assert!(!origin_is_usable(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_files_are_handed_over_by_file_name() {
|
||||
assert_eq!(save_name("exports/2026/IMG_0001.jpg"), "IMG_0001.jpg");
|
||||
assert_eq!(save_name("IMG_0001.jpg"), "IMG_0001.jpg");
|
||||
assert_eq!(save_name("lightcraft-library-backup-2026-10-19.zip"), "lightcraft-library-backup-2026-10-19.zip");
|
||||
}
|
||||
|
||||
/// Page mode is opt-in by the exact attribute value, parent mode by the query, and parent
|
||||
/// mode wins when a page asks for both.
|
||||
#[test]
|
||||
fn page_mode_is_opt_in_and_parent_mode_wins_when_both_are_set() {
|
||||
assert_eq!(transport_for(Some("page"), ""), Some(Mode::Page));
|
||||
assert_eq!(transport_for(Some("page"), "?host=parent"), Some(Mode::Parent), "parent mode wins");
|
||||
// only the exact value opts in; anything else falls back to the query, or to standalone
|
||||
for not_page in ["Page", " page", "page ", "parent", "host"] {
|
||||
assert_eq!(transport_for(Some(not_page), "?host=parent"), Some(Mode::Parent), "{not_page:?}");
|
||||
assert_eq!(transport_for(Some(not_page), ""), None, "{not_page:?}");
|
||||
}
|
||||
assert_eq!(transport_for(None, ""), None);
|
||||
assert_eq!(transport_for(None, "?store=idb"), None);
|
||||
assert_eq!(transport_for(None, "?host="), None);
|
||||
assert_eq!(transport_for(None, "?host=Parent"), None);
|
||||
assert_eq!(transport_for(None, "?xhost=parent"), None);
|
||||
}
|
||||
|
||||
/// The query is read the way the URL options always read it: the first `host` parameter wins,
|
||||
/// and only a value of exactly `parent` counts.
|
||||
#[test]
|
||||
fn the_query_asks_for_the_parent_bridge() {
|
||||
assert!(host_parent_requested("?host=parent"));
|
||||
assert!(host_parent_requested("host=parent"));
|
||||
assert!(host_parent_requested("?host=parent&store=idb"));
|
||||
assert!(host_parent_requested("?store=idb&host=parent"));
|
||||
assert!(!host_parent_requested(""));
|
||||
assert!(!host_parent_requested("?"));
|
||||
assert!(!host_parent_requested("?host"));
|
||||
assert!(!host_parent_requested("?host="));
|
||||
assert!(host_parent_requested("?host=parent&host=id"), "the first host parameter wins");
|
||||
assert!(!host_parent_requested("?host=id&host=parent"));
|
||||
assert!(!host_parent_requested("?hosts=parent"));
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,10 @@
|
||||
//! console (see [`bench`]) on the generated demo photos in an unsaved library (it implies `?store=memory`, so it never edits
|
||||
//! the library in browser storage); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
|
||||
//! persistence and `?workers=0` renders on the main thread.
|
||||
//! `?host=parent` speaks to a same-origin page framing LightCraft (see [`host`]): it hands
|
||||
//! photos in, receives what would be downloaded and hears about unsaved changes. A page can also
|
||||
//! host LightCraft in its own document, no iframe: `data-host="page"` on the canvas opts in, and
|
||||
//! the same messages travel as DOM `CustomEvent`s on the canvas.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -25,6 +29,7 @@ pub mod bench;
|
||||
#[cfg(any(test, target_arch = "wasm32"))]
|
||||
mod drop_gate;
|
||||
pub mod files;
|
||||
pub mod host;
|
||||
pub mod store;
|
||||
pub mod wire;
|
||||
|
||||
|
||||
@@ -149,10 +149,14 @@ pub fn download_blob(name: &str, blob: &web_sys::Blob) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where a finished backup goes: the browser's downloads ([`download_blob`]), or the page framing
|
||||
/// LightCraft (`?host=parent`). Awaited, so the backup counts as done only once it is handed over.
|
||||
pub type Deliver = Box<dyn FnOnce(String, web_sys::Blob) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>>>>>;
|
||||
|
||||
/// File ▸ Back Up Library…: a zip of the library files (as the app has them, saved or not) and
|
||||
/// every original in storage, built entry by entry into the browser's memory (outside the wasm
|
||||
/// heap) and downloaded. `names`: content hash → the photo's file name.
|
||||
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>) -> Result<(usize, f64), String> {
|
||||
/// heap) and handed to `deliver`. `names`: content hash → the photo's file name.
|
||||
pub async fn backup(files: Files, backend: Backend, names: HashMap<String, String>, deliver: Deliver) -> Result<(usize, f64), String> {
|
||||
let parts = js_sys::Array::new();
|
||||
let mut zip = ZipWriter::default();
|
||||
let mut bytes = 0f64;
|
||||
@@ -190,7 +194,7 @@ pub async fn backup(files: Files, backend: Backend, names: HashMap<String, Strin
|
||||
opts.set_type("application/zip");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(|e| format!("{e:?}"))?;
|
||||
let day: String = String::from(js_sys::Date::new_0().to_iso_string()).chars().take(10).collect();
|
||||
download_blob(&format!("lightcraft-library-backup-{day}.zip"), &blob)?;
|
||||
deliver(format!("lightcraft-library-backup-{day}.zip"), blob).await?;
|
||||
Ok((originals, bytes + tail.len() as f64))
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use lightcraft_engine::files::{load_bytes_with, probe_bytes};
|
||||
use lightcraft_engine::files::{load_bytes_decoded, probe_bytes};
|
||||
use lightcraft_engine::media::{FileLoader, FileProbe};
|
||||
|
||||
/// Prefix of the catalog paths of files kept in browser storage.
|
||||
@@ -146,9 +146,9 @@ impl Originals {
|
||||
let s = self.clone();
|
||||
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
|
||||
// whether it decodes in a worker or inline when workers are unavailable)
|
||||
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, _dcp: Option<&lightcraft_engine::media::DcpProfile>| {
|
||||
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, with: lightcraft_engine::media::RawDecode<'_>| {
|
||||
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
|
||||
load_bytes_with(&bytes, max_edge, None)
|
||||
load_bytes_decoded(&bytes, max_edge, lightcraft_engine::media::RawDecode { dcp: None, outliers: with.outliers })
|
||||
});
|
||||
let s = self.clone();
|
||||
let probe: FileProbe = Arc::new(move |path: &str| {
|
||||
@@ -285,15 +285,15 @@ mod tests {
|
||||
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
|
||||
};
|
||||
assert_ne!(
|
||||
load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
|
||||
load_bytes_with(&dng, 64, None).unwrap().0.data,
|
||||
lightcraft_engine::files::load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
|
||||
lightcraft_engine::files::load_bytes_with(&dng, 64, None).unwrap().0.data,
|
||||
"the profile changes a raw's colour where it is applied"
|
||||
);
|
||||
let store = Originals::default();
|
||||
store.insert("h1", Arc::from(dng));
|
||||
let (loader, _) = store.hooks();
|
||||
let with = loader("web/h1/a.dng", 64, Some(&profile)).unwrap();
|
||||
let without = loader("web/h1/a.dng", 64, None).unwrap();
|
||||
let with = loader("web/h1/a.dng", 64, lightcraft_engine::media::RawDecode { dcp: Some(&profile), outliers: false }).unwrap();
|
||||
let without = loader("web/h1/a.dng", 64, Default::default()).unwrap();
|
||||
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
|
||||
}
|
||||
|
||||
|
||||
+176
-20
@@ -2,14 +2,14 @@
|
||||
//! `<canvas id="lightcraft_canvas">`, wires the file picker and drag-and-drop, and turns exports
|
||||
//! into downloads.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_engine::Session;
|
||||
use lightcraft_engine::catalog::Source;
|
||||
use lightcraft_engine::library::LibraryStores;
|
||||
use lightcraft_ui_egui::{LightcraftApp, Services, UiState};
|
||||
use lightcraft_ui_egui::{LightcraftApp, Services, UiState, WriteFn};
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
@@ -18,6 +18,7 @@ use crate::backend::Backend;
|
||||
use crate::backup::{ACTIVE_LIBRARY, DEFAULT_LIBRARY_DIR, valid_library_dir};
|
||||
use crate::bench::Bench;
|
||||
use crate::files::{Files, FlushOp, LIBRARY_FILES};
|
||||
use crate::host::{Incoming, Outgoing};
|
||||
use crate::safety::{self, notice};
|
||||
use crate::store::{Originals, content_hash, download_name, storage_key};
|
||||
use crate::wire::ThumbIndex;
|
||||
@@ -68,13 +69,15 @@ pub(crate) fn request_repaint() {
|
||||
});
|
||||
}
|
||||
|
||||
/// URL options (`?bench&store=idb&workers=2&reset`).
|
||||
/// URL options (`?bench&store=idb&workers=2&reset&host=parent`).
|
||||
struct Options {
|
||||
bench: bool,
|
||||
/// "opfs" (default: OPFS, falling back to IndexedDB), "idb" or "memory".
|
||||
store: String,
|
||||
workers: Option<usize>,
|
||||
reset: bool,
|
||||
/// The raw query string, for the host mode ([`crate::host::transport_for`]).
|
||||
query: String,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
@@ -98,6 +101,7 @@ impl Options {
|
||||
store: if bench { "memory".into() } else { get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()) },
|
||||
workers: get("workers").and_then(|v| v.parse().ok()).map(|n: usize| n.min(crate::workers::MAX_WORKERS)),
|
||||
reset: get("reset").is_some(),
|
||||
query: q,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,12 +175,75 @@ fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep egui's hidden text field content-box, so host page CSS cannot misplace typed text:
|
||||
/// eframe (0.36 web) types through a hidden `<input type="text">` it inserts as the canvas's
|
||||
/// next sibling, and a host page's global `* { box-sizing: border-box }` reaches it and leaves it
|
||||
/// no content box, so the next key lands before text just committed by an input method or a
|
||||
/// paste-like insert. Inline style beats any host stylesheet rule without `!important`, so the
|
||||
/// property is set on the element itself, in every host mode, and retried on the next animation
|
||||
/// frames while eframe hasn't inserted the field yet.
|
||||
fn fix_text_field_box_sizing() {
|
||||
/// How many animation frames the fix may wait for eframe to insert its hidden text field.
|
||||
const MAX_FRAMES: u32 = 120;
|
||||
|
||||
/// True when the field was found and set: the canvas's next sibling, or an
|
||||
/// `input[type=text]` in the canvas's parent.
|
||||
fn fix_once() -> bool {
|
||||
let Some(doc) = window().and_then(|w| w.document()) else { return false };
|
||||
let Some(canvas) = doc.get_element_by_id("lightcraft_canvas") else { return false };
|
||||
let input = canvas.next_element_sibling().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()).or_else(|| {
|
||||
canvas
|
||||
.parent_element()
|
||||
.and_then(|p| p.query_selector("input[type=text]").ok())
|
||||
.flatten()
|
||||
.and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok())
|
||||
});
|
||||
input.is_some_and(|i| i.style().set_property("box-sizing", "content-box").is_ok())
|
||||
}
|
||||
|
||||
// the closure reschedules itself until the field is fixed or the frames run out; done, it is
|
||||
// left parked in its slot (dropping it from inside itself would free its own state, and the
|
||||
// slot holds the only reference) — a one-off leak, like the forgotten listeners
|
||||
let tries = Rc::new(Cell::new(MAX_FRAMES));
|
||||
let slot: Rc<RefCell<Option<Closure<dyn FnMut()>>>> = Rc::default();
|
||||
let own = Rc::clone(&slot);
|
||||
*slot.borrow_mut() = Some(Closure::new(move || {
|
||||
if fix_once() || tries.get() <= 1 {
|
||||
return; // done: stop rescheduling
|
||||
}
|
||||
tries.set(tries.get() - 1);
|
||||
let again = own.borrow_mut().take();
|
||||
if let Some(again) = again {
|
||||
let _ = window().and_then(|w| w.request_animation_frame(again.as_ref().unchecked_ref()).ok());
|
||||
// put the same closure back, now that the frame it was handed to has its own reference
|
||||
*own.borrow_mut() = Some(again);
|
||||
}
|
||||
}));
|
||||
let first = slot.borrow_mut().take();
|
||||
if let Some(first) = first {
|
||||
let _ = window().and_then(|w| w.request_animation_frame(first.as_ref().unchecked_ref()).ok());
|
||||
*slot.borrow_mut() = Some(first);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the browser host's `Services`: library backup/restore through browser storage and a
|
||||
/// download, asynchronous file picking, downloads for writes, and PNG encoding. Desktop-only
|
||||
/// services (native pickers, reveal, model folders) stay unset.
|
||||
fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen: Rc<Cell<bool>>, ctx: egui::Context) -> Services {
|
||||
let (backup_backend, backup_files) = (backend.clone(), files);
|
||||
fn services(
|
||||
originals: Originals,
|
||||
backend: Option<Backend>,
|
||||
files: Files,
|
||||
frozen: Rc<Cell<bool>>,
|
||||
ctx: egui::Context,
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
) -> Services {
|
||||
let (backup_backend, backup_files, backup_bridge) = (backend.clone(), files, bridge.clone());
|
||||
let restore_backend = backend.clone();
|
||||
// what would be downloaded goes to the page framing LightCraft instead, when there is one
|
||||
let write: WriteFn = match bridge {
|
||||
Some(bridge) => Box::new(move |path: &str, bytes: &[u8]| bridge.save(path, bytes)),
|
||||
None => Box::new(download),
|
||||
};
|
||||
Services {
|
||||
local_places: None,
|
||||
picker: None,
|
||||
@@ -197,9 +264,18 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
|
||||
})
|
||||
.collect();
|
||||
let files = backup_files.clone();
|
||||
notice("Backing up the library… (the download starts when it's ready)");
|
||||
// awaited by `backup`: "backed up" is said only once the page has the file
|
||||
let deliver: safety::Deliver = match backup_bridge.clone() {
|
||||
Some(bridge) => Box::new(move |name: String, blob: web_sys::Blob| Box::pin(async move { bridge.save_blob(name, blob).await })),
|
||||
None => Box::new(|name: String, blob: web_sys::Blob| Box::pin(async move { safety::download_blob(&name, &blob) })),
|
||||
};
|
||||
notice(if backup_bridge.is_some() {
|
||||
"Backing up the library… (handed to the page when it's ready)"
|
||||
} else {
|
||||
"Backing up the library… (the download starts when it's ready)"
|
||||
});
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match safety::backup(files, b, names).await {
|
||||
match safety::backup(files, b, names, deliver).await {
|
||||
Ok((n, bytes)) => notice(format!(
|
||||
"Library backed up: {n} original{} ({:.1} MB). Keep the file somewhere safe.",
|
||||
if n == 1 { "" } else { "s" },
|
||||
@@ -237,7 +313,7 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
|
||||
save_slideshow_template: None,
|
||||
pick_print_templates: None,
|
||||
save_print_template: None,
|
||||
write: Some(Box::new(download)),
|
||||
write: Some(write),
|
||||
// the browser download path has no meaningful create-new file write; the control channel
|
||||
// (and therefore screenshot paths) is not available on the web
|
||||
write_new: None,
|
||||
@@ -289,7 +365,8 @@ async fn flush(files: Files, backend: Backend, dir: String, flushing: Rc<Cell<bo
|
||||
}
|
||||
}
|
||||
flushing.set(false);
|
||||
// the page title drops its unsaved • now, even when nothing else wakes the page
|
||||
// the page title drops its unsaved • now, and the page framing LightCraft hears `dirty: false`,
|
||||
// even when nothing else wakes the page
|
||||
request_repaint();
|
||||
}
|
||||
|
||||
@@ -301,12 +378,14 @@ struct Boot {
|
||||
index: ThumbIndex,
|
||||
/// The library folder in storage (`library`, or a restored backup's).
|
||||
lib_dir: String,
|
||||
/// The page framing LightCraft (`?host=parent`), when there is one.
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
/// Library files that exist but couldn't be read (#1507): the library isn't opened and
|
||||
/// nothing is saved, so the stored copy stays as it was.
|
||||
load_error: Option<String>,
|
||||
}
|
||||
|
||||
async fn boot(opts: Options) -> Boot {
|
||||
async fn boot(opts: Options, bridge: Option<crate::host::Bridge>) -> Boot {
|
||||
let t0 = perf_now();
|
||||
let backend = if opts.store == "memory" {
|
||||
None
|
||||
@@ -403,7 +482,7 @@ async fn boot(opts: Options) -> Boot {
|
||||
index.len(),
|
||||
index.total() as f64 / 1e6
|
||||
);
|
||||
Boot { opts, backend, files, index, lib_dir, load_error }
|
||||
Boot { opts, backend, files, index, lib_dir, bridge, load_error }
|
||||
}
|
||||
|
||||
struct WebApp {
|
||||
@@ -424,6 +503,7 @@ struct WebApp {
|
||||
title: String,
|
||||
last_save: f64,
|
||||
ui_written: Vec<u8>,
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
}
|
||||
|
||||
/// The browser host's drop queues, taken only through the shared gate: a prompt or blocking
|
||||
@@ -458,7 +538,7 @@ impl WebApp {
|
||||
/// browser storage (a read failure starts an empty session and a blocking `LibraryProblem`),
|
||||
/// load the stored UI state, start render workers and the optional benchmark.
|
||||
fn new(cc: &eframe::CreationContext<'_>, boot: Boot, chinese_font: Vec<u8>) -> Self {
|
||||
let Boot { opts, backend, files, index, lib_dir, load_error } = boot;
|
||||
let Boot { opts, backend, files, index, lib_dir, bridge, load_error } = boot;
|
||||
let originals = Originals::default();
|
||||
let t = perf_now();
|
||||
let mut session = Session::new();
|
||||
@@ -513,13 +593,16 @@ impl WebApp {
|
||||
session.media.preview_capacity = 3;
|
||||
// nothing is saved while the stored library couldn't be read
|
||||
let frozen = Rc::new(Cell::new(read_failed));
|
||||
let mut app = LightcraftApp::new(session, services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone()))
|
||||
.with_chinese_font(chinese_font);
|
||||
let services = services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone(), bridge.clone());
|
||||
let mut app = LightcraftApp::new(session, services).with_chinese_font(chinese_font);
|
||||
let ui_written = files.get("ui.json").unwrap_or_default();
|
||||
// an arrangement from an older docking version starts again from the default
|
||||
let mut saved = serde_json::from_slice::<serde_json::Value>(&ui_written).unwrap_or_default();
|
||||
if let Some(fields) = saved.as_object_mut() {
|
||||
lightcraft_ui_egui::docking::drop_outdated(fields);
|
||||
// a stored ui.json means an installation that has been run: due What's New, never
|
||||
// the first-run tour (the same migration the desktop settings loader runs)
|
||||
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
|
||||
}
|
||||
if let Ok(ui) = serde_json::from_value::<UiState>(saved) {
|
||||
app.ui = ui;
|
||||
@@ -547,6 +630,13 @@ impl WebApp {
|
||||
}
|
||||
log::info!("lightcraft: {n} render workers");
|
||||
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
|
||||
if let Some(b) = &bridge {
|
||||
// hear the page from now on, and tell it the app is listening
|
||||
b.listen(cc.egui_ctx.clone());
|
||||
if !b.post(&Outgoing::Ready) {
|
||||
log::warn!("lightcraft: the page framing LightCraft could not be told the app is ready");
|
||||
}
|
||||
}
|
||||
let origin = lightcraft_ui_egui::monotonic_ms();
|
||||
WebApp {
|
||||
app,
|
||||
@@ -563,9 +653,49 @@ impl WebApp {
|
||||
title: String::new(),
|
||||
last_save: 0.0,
|
||||
ui_written,
|
||||
bridge,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the page framing LightCraft sent since the last frame: photos to add (as if dropped
|
||||
/// on the window) and commands to run, each answered with `lightcraft:response`.
|
||||
fn run_host(&mut self, ctx: &egui::Context) {
|
||||
let Some(bridge) = self.bridge.clone() else { return };
|
||||
for m in bridge.take_incoming() {
|
||||
match m {
|
||||
Incoming::Open { name, bytes } => {
|
||||
wasm_bindgen_futures::spawn_local(store_file(self.originals.clone(), self.backend.clone(), name, bytes, ctx.clone()));
|
||||
}
|
||||
Incoming::Refused(error) => {
|
||||
if !bridge.post(&Outgoing::Failed(error)) {
|
||||
log::warn!("lightcraft: a refused open could not be reported to the page");
|
||||
}
|
||||
}
|
||||
Incoming::Cmd { id, params } => {
|
||||
let r = match crate::automation::params(¶ms) {
|
||||
Err(e) => Err(format!("{id}: {e}")),
|
||||
Ok(_) if id == "web.stats" => Ok(self.web_stats()),
|
||||
Ok(params) => self.app.run(&id, params),
|
||||
};
|
||||
let response = match r {
|
||||
Ok(v) => Outgoing::Response { ok: true, value: v.to_string() },
|
||||
Err(e) => Outgoing::Response { ok: false, value: e },
|
||||
};
|
||||
if !bridge.post(&response) {
|
||||
log::warn!("lightcraft: the answer to {id} could not reach the page");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether closing the page now would lose something: a write to browser storage still
|
||||
/// queued or running, or changes storage refused (quota). The page framing LightCraft hears
|
||||
/// when this changes (`lightcraft:dirty`), so it can ask before closing a window with edits.
|
||||
fn dirty_for_host(&self) -> bool {
|
||||
self.files.is_dirty() || self.flushing.get() || self.app.session.unsaved().is_some()
|
||||
}
|
||||
|
||||
/// Consume the drops the raw-input hook queued once (never re-read `raw.dropped_files` in a
|
||||
/// hidden logic tick), and add originals whose bytes have arrived.
|
||||
fn import_dropped(&mut self, ctx: &egui::Context) {
|
||||
@@ -742,6 +872,7 @@ impl eframe::App for WebApp {
|
||||
self.app.ui.toast = Some((text, now + NOTICE_SECS, None));
|
||||
}
|
||||
self.run_inbox();
|
||||
self.run_host(ctx);
|
||||
self.load_originals(ctx);
|
||||
if let Some(w) = &self.workers {
|
||||
// `library.preferences ▸ cacheMb` is read by the session; the worker index prunes on
|
||||
@@ -750,6 +881,9 @@ impl eframe::App for WebApp {
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
self.save();
|
||||
if let Some(b) = &self.bridge {
|
||||
b.report_dirty(self.dirty_for_host());
|
||||
}
|
||||
}
|
||||
|
||||
/// Pass the browser's raw input to the app hook before egui processes it, so prompt barriers
|
||||
@@ -837,6 +971,21 @@ pub fn start(chinese_font: Vec<u8>) {
|
||||
log::warn!("lightcraft: no Simplified Chinese font supplied; Chinese-only glyphs will show as boxes");
|
||||
}
|
||||
let opts = Options::from_url();
|
||||
// `?host=parent`: a same-origin page framing LightCraft hands photos in, stores what would
|
||||
// be downloaded and hears about unsaved changes (see `host`). `data-host="page"` on the
|
||||
// canvas opts a page in instead: it runs LightCraft in its own document and talks over DOM
|
||||
// `CustomEvent`s on the canvas. `?host=parent` wins when a page asks for both.
|
||||
let canvas = window()
|
||||
.and_then(|w| w.document())
|
||||
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
|
||||
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok());
|
||||
let mode = crate::host::transport_for(canvas.as_ref().and_then(|c| c.get_attribute("data-host")).as_deref(), &opts.query);
|
||||
let bridge = mode.and_then(|m| crate::host::Bridge::for_mode(m, canvas.as_ref()));
|
||||
if mode == Some(crate::host::Mode::Parent) && bridge.is_none() {
|
||||
log::warn!(
|
||||
"lightcraft: ?host=parent, but this page is not framed, has an opaque origin, or its parent is on another origin; exports keep downloading"
|
||||
);
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// one tab per library: two would each keep their own copy and overwrite each other's saves
|
||||
if opts.store != "memory" && safety::acquire_tab_lock().await == Some(false) {
|
||||
@@ -844,17 +993,19 @@ pub fn start(chinese_font: Vec<u8>) {
|
||||
"LightCraft is already open in another tab or window of this browser.\n\n\
|
||||
Switch to that tab, or close it and reload this page. (Two tabs would overwrite each other's changes.)",
|
||||
);
|
||||
if let Some(b) = &bridge {
|
||||
b.post(&Outgoing::Failed("LightCraft is already open in another tab or window of this browser".into()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(canvas) = window()
|
||||
.and_then(|w| w.document())
|
||||
.and_then(|d| d.get_element_by_id("lightcraft_canvas"))
|
||||
.and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok())
|
||||
else {
|
||||
let Some(canvas) = canvas else {
|
||||
log::error!("missing <canvas id=\"lightcraft_canvas\">");
|
||||
if let Some(b) = &bridge {
|
||||
b.post(&Outgoing::Failed("the page has no <canvas id=\"lightcraft_canvas\">".into()));
|
||||
}
|
||||
return;
|
||||
};
|
||||
let boot = boot(opts).await;
|
||||
let boot = boot(opts, bridge.clone()).await;
|
||||
let runner = eframe::WebRunner::new();
|
||||
let r = runner.start(canvas, eframe::WebOptions::default(), Box::new(move |cc| Ok(Box::new(WebApp::new(cc, boot, chinese_font))))).await;
|
||||
match r {
|
||||
@@ -862,10 +1013,15 @@ pub fn start(chinese_font: Vec<u8>) {
|
||||
if let Some(el) = window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id("lightcraft_loading")) {
|
||||
el.remove();
|
||||
}
|
||||
// the runner just started: egui's hidden text field exists from now on
|
||||
fix_text_field_box_sizing();
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("LightCraft failed to start: {e:?}");
|
||||
set_status(&format!("LightCraft failed to start: {e:?}"));
|
||||
if let Some(b) = &bridge {
|
||||
b.post(&Outgoing::Failed(format!("{e:?}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct WireJob {
|
||||
pub origin: Source,
|
||||
/// Decode the source at most this long.
|
||||
pub max_edge: usize,
|
||||
/// Resize an already decoded source exactly as the engine's cached-source path does.
|
||||
#[serde(default)]
|
||||
pub fit_edge: Option<usize>,
|
||||
pub raw: bool,
|
||||
#[serde(default)]
|
||||
pub relative_wb: bool,
|
||||
@@ -67,7 +70,8 @@ impl WireJob {
|
||||
/// `view`: the slot name, for jobs that keep a stage cache.
|
||||
pub fn from_job(job: &RenderJob, thumb_cached: bool, view: &str) -> WireJob {
|
||||
let max_edge = match &job.source {
|
||||
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } | SourceRef::Fit { max_edge, .. } => *max_edge,
|
||||
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } => *max_edge,
|
||||
SourceRef::Fit { from, .. } => from.image.width.max(from.image.height),
|
||||
SourceRef::Loaded(img) => img.image.width.max(img.image.height),
|
||||
SourceRef::Smart { .. } => 2560,
|
||||
};
|
||||
@@ -77,6 +81,10 @@ impl WireJob {
|
||||
level: job.level,
|
||||
origin: job.origin.clone(),
|
||||
max_edge,
|
||||
fit_edge: match &job.source {
|
||||
SourceRef::Fit { max_edge, .. } => Some(*max_edge),
|
||||
_ => None,
|
||||
},
|
||||
raw: job.info.raw,
|
||||
relative_wb: job.info.relative_wb,
|
||||
legacy_relative_wb: job.info.legacy_relative_wb,
|
||||
@@ -114,6 +122,7 @@ impl WireJob {
|
||||
RenderRequest {
|
||||
max_w: self.max_w,
|
||||
max_h: self.max_h,
|
||||
exact_size: false,
|
||||
quality: if self.draft { Quality::Draft } else { Quality::Full },
|
||||
apply_crop: self.apply_crop,
|
||||
overlay: lightcraft_engine::pipeline::Overlay::from_parts(self.overlay.0, self.overlay.1),
|
||||
@@ -129,7 +138,9 @@ impl WireJob {
|
||||
/// Identifies the decoded source this job needs.
|
||||
fn source_key(&self) -> String {
|
||||
match &self.origin {
|
||||
Source::File { path } => format!("{}:{:?}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge),
|
||||
Source::File { path } => {
|
||||
format!("{}:{:?}:{}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge, self.settings.removes_hot_pixels())
|
||||
}
|
||||
Source::Demo { scene } => format!("{}:{:?}:{}:demo:{scene}", self.cache_generation, self.source_identity, self.max_edge),
|
||||
}
|
||||
}
|
||||
@@ -181,8 +192,10 @@ impl WorkerCore {
|
||||
None => {
|
||||
let src = match (&job.origin, original) {
|
||||
(Source::File { .. }, Some(bytes)) => {
|
||||
let (image, info) = lightcraft_engine::files::load_bytes(bytes, job.max_edge)?;
|
||||
DecodedSource::new(Arc::new(image), Some(info))
|
||||
let outliers = job.settings.removes_hot_pixels();
|
||||
let with = lightcraft_engine::media::RawDecode { dcp: None, outliers };
|
||||
let (image, info) = lightcraft_engine::files::load_bytes_decoded(bytes, job.max_edge, with)?;
|
||||
DecodedSource { outliers, ..DecodedSource::new(Arc::new(image), Some(info)) }
|
||||
}
|
||||
(Source::File { path }, None) => return Err(format!("{path}: original not found in browser storage")),
|
||||
(origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge).load_source()?,
|
||||
@@ -192,6 +205,10 @@ impl WorkerCore {
|
||||
src
|
||||
}
|
||||
};
|
||||
let src = match job.fit_edge {
|
||||
Some(max_edge) => SourceRef::Fit { from: Box::new(src), max_edge }.load_source()?,
|
||||
None => src,
|
||||
};
|
||||
let info = src.info_or(job.info());
|
||||
let mut rendered = match &job.stages {
|
||||
Some(view) => {
|
||||
@@ -468,6 +485,7 @@ mod tests {
|
||||
level: SourceLevel::Thumb,
|
||||
origin,
|
||||
max_edge: 512,
|
||||
fit_edge: None,
|
||||
raw: false,
|
||||
relative_wb: false,
|
||||
legacy_relative_wb: false,
|
||||
|
||||
@@ -58,3 +58,6 @@ lightcraft-testkit = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# the colour profile of the monitor showing the window (`win_screen_profile`)
|
||||
lightcraft-wincolor = { workspace = true }
|
||||
raw-window-handle = "0.6"
|
||||
@@ -18,8 +18,6 @@ use std::time::Duration;
|
||||
const POLL: Duration = Duration::from_secs(3);
|
||||
/// A wait before trying again when colord isn't there (not installed, no system bus).
|
||||
const RETRY: Duration = Duration::from_secs(30);
|
||||
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
|
||||
const MAX_PROFILE: u64 = 16 << 20;
|
||||
|
||||
const SERVICE: &str = "org.freedesktop.ColorManager";
|
||||
const DEVICE: &str = "org.freedesktop.ColorManager.Device";
|
||||
@@ -72,7 +70,7 @@ fn read(conn: &zbus::blocking::Connection) -> Option<Vec<u8>> {
|
||||
}
|
||||
}
|
||||
let file = pick(&files)?;
|
||||
load(std::path::Path::new(file))
|
||||
crate::profile_file::load(std::path::Path::new(file))
|
||||
}
|
||||
|
||||
/// The profile to use for these displays' profile files: the one they share, `None` with none or
|
||||
@@ -83,15 +81,6 @@ fn pick(files: &[String]) -> Option<&str> {
|
||||
named.all(|f| f == first).then_some(first)
|
||||
}
|
||||
|
||||
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
|
||||
fn load(path: &std::path::Path) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
|
||||
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -105,21 +94,4 @@ mod tests {
|
||||
assert_eq!(pick(&s(&["/a.icc", "/b.icc"])), None, "which one the window is on isn't known");
|
||||
assert_eq!(pick(&s(&[""])), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_files_are_read_with_a_size_cap() {
|
||||
let dir = std::env::temp_dir().join(format!("colord-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let small = dir.join("small.icc");
|
||||
std::fs::write(&small, b"acsp").unwrap();
|
||||
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
|
||||
let empty = dir.join("empty.icc");
|
||||
std::fs::write(&empty, b"").unwrap();
|
||||
assert_eq!(load(&empty), None);
|
||||
assert_eq!(load(&dir.join("missing.icc")), None);
|
||||
let big = dir.join("big.icc");
|
||||
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
|
||||
assert_eq!(load(&big), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,12 @@ mod hdr_display;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
mod profile_file;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod screen_profile;
|
||||
#[cfg(windows)]
|
||||
mod win_screen_profile;
|
||||
mod window_gpu;
|
||||
|
||||
use dialog_filter::FileDialogExt as _;
|
||||
@@ -371,6 +375,7 @@ fn main() -> eframe::Result {
|
||||
app.notices.extend(launch_notices);
|
||||
app.notices.extend(window_notice);
|
||||
app.gpu_notice = true;
|
||||
app.disk_space_notice = true;
|
||||
// an empty library opens where Import is offered (a grid, with the sidebar); before
|
||||
// the snapshot below, so this alone isn't written to the settings file
|
||||
if problem.is_none() && files.is_empty() {
|
||||
|
||||
@@ -67,6 +67,11 @@ fn decode_saved_ui(bytes: &[u8]) -> Result<(UiState, bool), String> {
|
||||
if recovered {
|
||||
fields.remove("docking");
|
||||
}
|
||||
// A settings file from before the startup dialog existed has no `seenVersion` key: the file
|
||||
// is there, so this is an installation that has been run, due What's New — never the
|
||||
// first-run tour. Shared with the browser's loader, which runs the same migration on its
|
||||
// stored `ui.json` (`startup::migrate_legacy_seen_version` carries the full story).
|
||||
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
|
||||
let ui = serde_json::from_value(saved).map_err(|error| error.to_string())?;
|
||||
Ok((ui, recovered))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Reading a display's ICC profile file for the screen-profile services (`colord` on Linux,
|
||||
//! `win_screen_profile` on Windows).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
|
||||
pub const MAX_PROFILE: u64 = 16 << 20;
|
||||
|
||||
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
|
||||
pub fn load(path: &Path) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
|
||||
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
|
||||
}
|
||||
|
||||
/// A profile file read again only when it changes: the services are asked about once a second, and
|
||||
/// calibration software rewrites its profile under the same name.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
#[derive(Default)]
|
||||
pub struct Cached {
|
||||
/// The file last read: its path, length and modification time.
|
||||
stamp: Option<(PathBuf, u64, Option<SystemTime>)>,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
impl Cached {
|
||||
/// The bytes of profile file `path`, read again when it isn't the file read last time or has
|
||||
/// changed since (see [`load`]).
|
||||
pub fn read(&mut self, path: &Path) -> Option<Vec<u8>> {
|
||||
let stamp = std::fs::metadata(path).ok().map(|m| (path.to_path_buf(), m.len(), m.modified().ok()));
|
||||
if stamp.is_none() || stamp != self.stamp {
|
||||
self.bytes = stamp.as_ref().and_then(|_| load(path));
|
||||
self.stamp = stamp;
|
||||
}
|
||||
self.bytes.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn profile_files_are_read_with_a_size_cap() {
|
||||
let dir = std::env::temp_dir().join(format!("profile-file-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let small = dir.join("small.icc");
|
||||
std::fs::write(&small, b"acsp").unwrap();
|
||||
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
|
||||
let empty = dir.join("empty.icc");
|
||||
std::fs::write(&empty, b"").unwrap();
|
||||
assert_eq!(load(&empty), None);
|
||||
assert_eq!(load(&dir.join("missing.icc")), None);
|
||||
let big = dir.join("big.icc");
|
||||
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
|
||||
assert_eq!(load(&big), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cached_profile_is_read_again_when_the_file_changes() {
|
||||
let dir = std::env::temp_dir().join(format!("profile-cache-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (a, b) = (dir.join("a.icc"), dir.join("b.icc"));
|
||||
std::fs::write(&a, b"first").unwrap();
|
||||
std::fs::write(&b, b"other").unwrap();
|
||||
let mut cache = Cached::default();
|
||||
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
|
||||
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
|
||||
// another monitor's profile
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"other"[..]));
|
||||
// rewritten under the same name (a different length, so the change shows whatever the
|
||||
// file system's time resolution)
|
||||
std::fs::write(&b, b"calibrated").unwrap();
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"calibrated"[..]));
|
||||
// gone: nothing, then read again once it is back
|
||||
std::fs::remove_file(&b).unwrap();
|
||||
assert_eq!(cache.read(&b), None);
|
||||
std::fs::write(&b, b"back").unwrap();
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"back"[..]));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,11 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
|
||||
// Linux: the profile the desktop assigns in colord, read off the UI thread
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_profile: Some(colord::service()),
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
// Windows: the profile it uses for the window's monitor, unless it colour-manages the
|
||||
// desktop itself (HDR, Auto Color Management)
|
||||
#[cfg(windows)]
|
||||
screen_profile: win_screen_profile::service(cc),
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
|
||||
screen_profile: None,
|
||||
pick_display_profile: Some(Box::new(|| {
|
||||
let mut d = file_dialog()
|
||||
|
||||
@@ -223,6 +223,42 @@ fn memory_session_leaves_a_damaged_ui_json_alone() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A settings file from before the startup dialog existed (no `seenVersion`) belongs to an
|
||||
/// installation that has been run: its first launch after the update shows What's New, never
|
||||
/// the first-run tour. A file this version saved before the dialog was presented carries an
|
||||
/// explicit `null` and is not migrated; only a missing file stays a first run as well.
|
||||
#[test]
|
||||
fn legacy_ui_json_shows_whats_new_not_the_first_run_tour() {
|
||||
let d = dir("legacy-startup");
|
||||
let path = d.join("ui.json");
|
||||
std::fs::write(&path, br#"{"language":"en","settings":{"startupView":"detail"}}"#).unwrap();
|
||||
let (ui, warning, keep) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none() && !keep);
|
||||
let ui = ui.unwrap();
|
||||
assert_eq!(ui.seen_version.as_deref(), Some(lightcraft_ui_egui::startup::LEGACY_SEEN_VERSION));
|
||||
assert_eq!(
|
||||
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
|
||||
Some(lightcraft_ui_egui::startup::StartupDialog::WhatsNew)
|
||||
);
|
||||
// a file that already records the running version is migrated nowhere
|
||||
std::fs::write(&path, format!(r#"{{"seenVersion":"{}"}}"#, env!("CARGO_PKG_VERSION"))).unwrap();
|
||||
let (ui, warning, _) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none());
|
||||
assert_eq!(ui.unwrap().seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
|
||||
// an explicit `null` is this version's "not presented yet" (the launch chooser saves while
|
||||
// the tour still waits): it stays a first run, not a pre-feature file
|
||||
std::fs::write(&path, br#"{"language":"en","seenVersion":null}"#).unwrap();
|
||||
let (ui, warning, _) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none());
|
||||
let ui = ui.unwrap();
|
||||
assert_eq!(ui.seen_version, None);
|
||||
assert_eq!(
|
||||
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
|
||||
Some(lightcraft_ui_egui::startup::StartupDialog::FirstRun)
|
||||
);
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docking_survives_native_settings_file_reload() {
|
||||
use lightcraft_ui_egui::docking::Panel;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The ICC profile Windows assigns to the monitor showing LightCraft's window.
|
||||
//!
|
||||
//! On an SDR desktop Windows passes what an app draws to the monitor unchanged, so sRGB previews
|
||||
//! look oversaturated on a wide-gamut monitor and ignore a calibration. While no monitor profile is
|
||||
//! chosen in Settings ▸ Display, previews are shown through the profile Windows uses for the window's
|
||||
//! monitor (`Services::screen_profile`, see `lightcraft_wincolor`), followed when the window moves to
|
||||
//! another monitor or the profile changes in Windows' Color Management. When Windows colour-manages
|
||||
//! the desktop itself (HDR, Auto Color Management) previews stay sRGB, as Windows expects then.
|
||||
|
||||
use lightcraft_wincolor::MonitorColor;
|
||||
|
||||
/// The service the UI polls, for the window `cc` belongs to; `None` when its handle isn't a Win32 one.
|
||||
pub fn service(cc: &eframe::CreationContext<'_>) -> Option<lightcraft_ui_egui::ScreenProfileFn> {
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
let RawWindowHandle::Win32(handle) = cc.window_handle().ok()?.as_raw() else { return None };
|
||||
let hwnd = handle.hwnd.get();
|
||||
let mut file = crate::profile_file::Cached::default();
|
||||
let mut last: Option<MonitorColor> = None;
|
||||
Some(Box::new(move || {
|
||||
let answer = lightcraft_wincolor::monitor_color(hwnd);
|
||||
if last.as_ref() != Some(&answer) {
|
||||
log::info!("screen profile: {}", describe(&answer));
|
||||
last = Some(answer.clone());
|
||||
}
|
||||
match answer {
|
||||
MonitorColor::Profile(path) => file.read(&path),
|
||||
MonitorColor::ManagedByWindows | MonitorColor::NoProfile | MonitorColor::Unknown => None,
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// For the log: what the window's monitor answered.
|
||||
fn describe(answer: &MonitorColor) -> String {
|
||||
match answer {
|
||||
MonitorColor::Profile(path) => format!("the monitor's profile, {}", path.display()),
|
||||
MonitorColor::ManagedByWindows => "Windows colour-manages this monitor (HDR or Auto Color Management): previews are sRGB".into(),
|
||||
MonitorColor::NoProfile => "no profile is assigned to the monitor: previews are sRGB".into(),
|
||||
MonitorColor::Unknown => "not known for this monitor: previews are sRGB".into(),
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,10 @@ sync_github_name = true
|
||||
[people.ronibalthazar]
|
||||
sync_github_name = true
|
||||
|
||||
[people.esli1283]
|
||||
real_name = "Aaron Lopez"
|
||||
sync_github_name = false
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
+132
-28
@@ -25,6 +25,12 @@
|
||||
//! - a bad record **followed by good ones** is real damage: replay stops there, the log is kept
|
||||
//! as `catalog.log.damaged-<seq>`, and a fresh snapshot is written so the library stays usable.
|
||||
//!
|
||||
//! Segmentation grids are shared within a snapshot (issue #2154): each distinct grid is written
|
||||
//! once into `Catalog.grids` and the masks of the photo's develop settings, versions, history
|
||||
//! steps and import look refer to it by index, so an unchanged mask no longer repeats with every
|
||||
//! history step. The table lives only in the snapshot file; log records keep the full grids
|
||||
//! inline.
|
||||
//!
|
||||
//! **Background compaction** ([`Journal::snapshot_in_background`], when the store offers a
|
||||
//! [`Store::background_writer`]): a worker thread writes the snapshot of a copy of the catalog at
|
||||
//! op `N` while appends go on (durably, as always) to the same log. Once the snapshot is durable,
|
||||
@@ -57,6 +63,7 @@
|
||||
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
|
||||
//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) |
|
||||
//! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` |
|
||||
//! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` |
|
||||
//!
|
||||
//! Rules:
|
||||
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
|
||||
@@ -81,7 +88,7 @@ pub const LOG: &str = "catalog.log";
|
||||
const FORMAT: &str = "lightcraft-catalog";
|
||||
/// The catalog format this build writes (and the newest it reads). See the module docs →
|
||||
/// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added.
|
||||
pub const VERSION: u32 = 11;
|
||||
pub const VERSION: u32 = 12;
|
||||
|
||||
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -272,12 +279,18 @@ fn newer(what: String) -> CatalogError {
|
||||
CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older"))
|
||||
}
|
||||
|
||||
/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid
|
||||
/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start
|
||||
/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt
|
||||
/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps
|
||||
/// and reports, same state as before, minus the CPU.
|
||||
const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Start markers that `resync` decoded on this thread (test builds only; see the cost test).
|
||||
pub(crate) static RESYNC_CANDIDATES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Total bytes of candidate suffixes `resync` may decode per damaged line: every attempt reads
|
||||
/// the rest of the line, so trying every candidate of a crafted line would make
|
||||
/// [`Journal::open`] quadratic in the line length (CWE-407). The budget is far above any
|
||||
/// fragment-plus-retry a failed append can leave, but caps the stall; past it the line reads as
|
||||
/// damage, which is handled safely.
|
||||
pub(crate) const MAX_SCAN: usize = 64 << 20;
|
||||
|
||||
/// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed
|
||||
/// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns
|
||||
@@ -285,32 +298,70 @@ const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
|
||||
/// The record's CRC must match, so damage is never mistaken for it.
|
||||
fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> {
|
||||
const START: &[u8] = b"{\"seq\":";
|
||||
// One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and
|
||||
// one validation covers every candidate; only a line that is not wholly valid re-checks, and
|
||||
// then up to the budget rather than the suffix length times the candidate count.
|
||||
let whole = std::str::from_utf8(line).ok();
|
||||
let mut spent = 0usize;
|
||||
(1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| {
|
||||
let text = match &whole {
|
||||
Some(t) => &t[i..],
|
||||
None => {
|
||||
if spent >= RESYNC_BUDGET_BYTES {
|
||||
return None;
|
||||
}
|
||||
spent = spent.saturating_add(line.len() - i);
|
||||
std::str::from_utf8(&line[i..]).ok()?
|
||||
}
|
||||
// The retry record starts with the `{"seq":` marker, but that marker can also occur inside
|
||||
// the op body (a smart-album rule value such as `{"seq":1}`); then the last occurrence is
|
||||
// nested, not the record start, and decoding it rejects a valid retry. Scan every marker
|
||||
// once, left to right, then try them from the end. A candidate must match the record header
|
||||
// shape — `{"seq":<digits>,"crc":<digits>,"op":`, what `encode_record` writes — so a marker
|
||||
// nested inside the op body (followed by `}` or `,`) or plain junk never reaches
|
||||
// `decode_record`; only a real record start does. This imposes no fixed limit on how many
|
||||
// nested markers a valid record may contain. Each attempt then decodes the rest of the line,
|
||||
// so the scan budget bounds the total when a hostile line still holds many header-shaped
|
||||
// markers, keeping the work near-linear instead of quadratic. The fragment that precedes the
|
||||
// record stays to its left (`i > 0`).
|
||||
let digits = |b: &[u8]| b.iter().take_while(|x| x.is_ascii_digit()).count();
|
||||
let mut candidates: Vec<usize> = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(i) = line[from..].windows(START.len()).position(|w| w == START) {
|
||||
let pos = from + i;
|
||||
let Some(after) = line.get(pos + START.len()..) else { break };
|
||||
let seq_digits = digits(after);
|
||||
let crc_field = after.get(seq_digits..).and_then(|rest| rest.strip_prefix(b",\"crc\":"));
|
||||
let crc_digits = crc_field.map(digits).unwrap_or(0);
|
||||
let op_field = crc_field.and_then(|rest| rest.get(crc_digits..)).and_then(|rest| rest.strip_prefix(b",\"op\":"));
|
||||
if seq_digits > 0 && crc_digits > 0 && op_field.is_some() {
|
||||
candidates.push(pos);
|
||||
}
|
||||
from = pos + START.len();
|
||||
}
|
||||
let mut scanned = 0usize;
|
||||
for &i in candidates.iter().rev() {
|
||||
if i == 0 {
|
||||
break; // the record must follow a fragment
|
||||
}
|
||||
let Some(suffix) = line.get(i..) else { continue };
|
||||
scanned = match scanned.checked_add(suffix.len()) {
|
||||
Some(total) if total <= MAX_SCAN => total,
|
||||
_ => break, // the budget is spent: stop trying further candidates
|
||||
};
|
||||
let rec = decode_record(text.trim_end_matches('\r'))?;
|
||||
(rec.0 <= last.saturating_add(1)).then_some((i, rec))
|
||||
})
|
||||
let Ok(text) = std::str::from_utf8(suffix) else { continue };
|
||||
#[cfg(test)]
|
||||
RESYNC_CANDIDATES.with(|c| c.set(c.get() + 1));
|
||||
if let Some((seq, op)) = decode_record(text.trim_end_matches('\u{0D}'))
|
||||
&& seq <= last.saturating_add(1)
|
||||
{
|
||||
return Some((i, (seq, op)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no
|
||||
/// whole-file string). The bytes are exactly
|
||||
/// `{"format":"lightcraft-catalog","version":1,"seq":N,"catalog":<serde_json of the catalog>}\n`,
|
||||
/// as before streaming. Fills in the serialise / write+sync times and the size.
|
||||
/// as before streaming. Each distinct segmentation grid of the photos' settings holders (see
|
||||
/// `Photo::settings_holders`) is written once (`Catalog.grids`), with the masks referring to it
|
||||
/// by index, so an unchanged mask does not repeat with every history step (issue #2154). Fills
|
||||
/// in the serialise / write+sync times and the size.
|
||||
fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io::Result<SnapshotTiming> {
|
||||
write_snapshot_owned(store, seq, catalog.clone())
|
||||
}
|
||||
|
||||
/// The same write, taking the catalog by value: the background path hands over the copy it
|
||||
/// already made, so a snapshot in flight holds one catalog, not two ([`Catalog::clone`] copies
|
||||
/// the photo pointers and the small tables, and the derived indexes start empty — real work on a
|
||||
/// large library).
|
||||
fn write_snapshot_owned(store: &mut dyn Store, seq: u64, mut snapshot: Catalog) -> std::io::Result<SnapshotTiming> {
|
||||
let t0 = web_time::Instant::now();
|
||||
let mut serialize_ms = 0.0;
|
||||
let bytes = store.write_atomic_with(SNAPSHOT, &mut |w| {
|
||||
@@ -320,7 +371,35 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io
|
||||
// 1 MiB chunks go through the store's `dyn Write`
|
||||
let mut b = std::io::BufWriter::with_capacity(1 << 20, w);
|
||||
write!(b, "{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"catalog\":")?;
|
||||
serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?;
|
||||
// The shared grids, in first-appearance order. The pool is a serialization detail:
|
||||
// `snapshot` itself is never modified (log records, presets and XMP stay inline).
|
||||
let mut pool: Vec<String> = Vec::new();
|
||||
let mut index: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
|
||||
{
|
||||
let mut see = |s: &lightcraft_develop::DevelopSettings| {
|
||||
s.visit_seg_masks(&mut |m| {
|
||||
// borrowed lookup: a grid every history step shares is not cloned just to
|
||||
// find it already indexed (only a new grid is copied, into pool and table)
|
||||
if !m.data.is_empty() && !index.contains_key(m.data.as_str()) {
|
||||
index.insert(m.data.clone(), pool.len() as u32);
|
||||
pool.push(m.data.clone());
|
||||
}
|
||||
});
|
||||
};
|
||||
for p in snapshot.photos.values() {
|
||||
for settings in p.settings_holders() {
|
||||
see(settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
snapshot.grids = pool;
|
||||
match lightcraft_develop::with_grid_interner(index, || serde_json::to_writer(&mut b, &snapshot)) {
|
||||
// no interner can be active here (snapshot writes don't nest), so `None` is a bug:
|
||||
// fail the write rather than store a truncated or reference-less snapshot
|
||||
Some(Ok(())) => {}
|
||||
Some(Err(e)) => return Err(std::io::Error::other(e)),
|
||||
None => return Err(std::io::Error::other("nested grid interner while writing a snapshot")),
|
||||
}
|
||||
b.write_all(b"}\n")?;
|
||||
b.flush()?;
|
||||
serialize_ms = ms_since(t);
|
||||
@@ -607,7 +686,7 @@ impl Journal {
|
||||
let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) };
|
||||
let copy = catalog.clone();
|
||||
let seq = self.seq;
|
||||
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot(writer.as_mut(), seq, ©));
|
||||
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot_owned(writer.as_mut(), seq, copy));
|
||||
let worker = match spawned {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
@@ -792,4 +871,29 @@ mod tests_resync {
|
||||
// matches, so the double `Some` is only reached with `last >= 4`
|
||||
assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
|
||||
}
|
||||
|
||||
/// A retry record whose op body holds more than eight nested `{"seq":` markers (a
|
||||
/// `SetAlbumRules` with nine rule values of `{"seq":1}`) exhausts `resync`'s fixed
|
||||
/// `MAX_DECODES = 8` decode budget on the nested markers, so the outer record's real
|
||||
/// start is never decoded and the valid operation is truncated as damage.
|
||||
#[test]
|
||||
fn resync_recovers_retry_beyond_eight_nested_markers() {
|
||||
let mut c = Catalog::new();
|
||||
let album_id = c.alloc_album_id();
|
||||
let mut rules = Vec::new();
|
||||
for _ in 0..9 {
|
||||
rules.push(crate::Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) });
|
||||
}
|
||||
let retry_op = Op::SetAlbumRules {
|
||||
id: album_id,
|
||||
rules: Box::new(crate::Filter { rule_set: Some(crate::RuleSet { mode: crate::Match::All, rules }), ..Default::default() }),
|
||||
};
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let record = format!("{{\"seq\":5,\"crc\":{crc},\"op\":{body}}}");
|
||||
let mut line = Vec::from(b"torn fragment" as &[u8]);
|
||||
let fragment = line.len();
|
||||
line.extend_from_slice(record.as_bytes());
|
||||
assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
|
||||
}
|
||||
}
|
||||
@@ -289,6 +289,13 @@ pub struct Catalog {
|
||||
/// What the library keeps about its folders (folder identity → record), see [`folders`].
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
folder_records: BTreeMap<String, FolderRecord>,
|
||||
/// Segmentation grids shared by this snapshot's masks: each distinct grid's data once, in
|
||||
/// first-appearance order, referenced by index from the masks ([`lightcraft_develop::\
|
||||
/// SegMask::grid`] is a position here). A serialization detail of snapshots
|
||||
/// ([`journal`]): never held in the live catalog — [`Catalog::repair`] resolves the
|
||||
/// references and clears the table when a snapshot is read.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
grids: Vec<String>,
|
||||
/// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog
|
||||
/// changed, so what is keyed by the revision is out of date).
|
||||
#[serde(skip)]
|
||||
@@ -367,6 +374,25 @@ impl std::fmt::Debug for PlansMemo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`])
|
||||
/// against a snapshot's grid table: each referenced mask takes its
|
||||
/// grid's data and the reference is cleared. A reference past the table (a damaged snapshot)
|
||||
/// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the
|
||||
/// mask itself wins over a stray reference. Returns the dangling count added to `dangling`.
|
||||
fn resolve_grids(settings: &mut Arc<DevelopSettings>, grids: &[String], dangling: usize) -> usize {
|
||||
let mut dangling = dangling;
|
||||
Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| {
|
||||
if let Some(i) = m.grid.take() {
|
||||
match (m.data.is_empty(), grids.get(i as usize)) {
|
||||
(true, Some(data)) => m.data = data.clone(),
|
||||
(true, None) => dangling += 1,
|
||||
(false, _) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
dangling
|
||||
}
|
||||
|
||||
/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
|
||||
/// follow a small edit without being worked out again from every photo.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -1192,6 +1218,23 @@ impl Catalog {
|
||||
/// wrote).
|
||||
pub fn repair(&mut self) -> Vec<String> {
|
||||
let mut changed = Vec::new();
|
||||
// Segmentation grids shared by the snapshot this was read from (issue #2154): each
|
||||
// reference takes its grid's data, and the table is not kept — a live catalog always
|
||||
// stores the data inline, so masks render and serialize without the snapshot's table.
|
||||
// Resolving is the normal way a snapshot in this format reads (not reported); a
|
||||
// reference past the table is damage and is reported — that includes a reference into
|
||||
// an empty table, which is always dangling, so the table being empty does not skip it.
|
||||
let grids = std::mem::take(&mut self.grids);
|
||||
let mut dangling = 0usize;
|
||||
for p in self.photos.values_mut() {
|
||||
let photo = Arc::make_mut(p);
|
||||
for settings in photo.settings_holders_mut() {
|
||||
dangling = resolve_grids(settings, &grids, dangling);
|
||||
}
|
||||
}
|
||||
if dangling > 0 {
|
||||
changed.push(format!("{dangling} segmentation grid reference(s) pointed past the shared table: cleared"));
|
||||
}
|
||||
for (id, p) in self.photos.iter_mut() {
|
||||
if p.id != *id {
|
||||
changed.push(format!("photo {} was filed as {}", p.id.0, id.0));
|
||||
@@ -1488,6 +1531,8 @@ mod tests_folders;
|
||||
#[cfg(test)]
|
||||
mod tests_format_version;
|
||||
#[cfg(test)]
|
||||
mod tests_grids;
|
||||
#[cfg(test)]
|
||||
mod tests_index;
|
||||
#[cfg(test)]
|
||||
mod tests_journal;
|
||||
|
||||
@@ -238,6 +238,7 @@ impl Writer {
|
||||
return Ok(());
|
||||
}
|
||||
self.file = None;
|
||||
crate::store::check_regular_directory_entry(&self.path)?;
|
||||
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
|
||||
@@ -439,6 +439,23 @@ impl Photo {
|
||||
pub fn relative_wb(&self) -> bool {
|
||||
self.develops_raw() && relative_wb_camera(&self.format, &self.meta.camera)
|
||||
}
|
||||
/// Every settings holder of this photo that can carry segmentation grids: the develop
|
||||
/// settings, the versions', the history steps' and the import look. A snapshot's shared grid
|
||||
/// table ([`crate::Catalog`]'s `grids`) covers all of them, so a new holder belongs here.
|
||||
pub(crate) fn settings_holders(&self) -> impl Iterator<Item = &Arc<DevelopSettings>> {
|
||||
std::iter::once(&self.develop)
|
||||
.chain(self.versions.iter().map(|v| &v.settings))
|
||||
.chain(self.history.iter().map(|h| &h.settings))
|
||||
.chain(self.import_look.iter())
|
||||
}
|
||||
/// [`Photo::settings_holders`] with mutable access (resolving a snapshot's grid references).
|
||||
pub(crate) fn settings_holders_mut(&mut self) -> impl Iterator<Item = &mut Arc<DevelopSettings>> {
|
||||
let Photo { develop, versions, history, import_look, .. } = self;
|
||||
std::iter::once(develop)
|
||||
.chain(versions.iter_mut().map(|v| &mut v.settings))
|
||||
.chain(history.iter_mut().map(|h| &mut h.settings))
|
||||
.chain(import_look.as_mut())
|
||||
}
|
||||
/// The develop settings import gave this photo: [`Photo::camera_defaults`], or the user's
|
||||
/// default preset applied on top of them ([`Photo::import_look`]). Like the camera defaults,
|
||||
/// in the photo's own rendering process.
|
||||
|
||||
@@ -238,8 +238,9 @@ fn op_variants_are_versioned() {
|
||||
Op::SetHistoryCursor { .. } => 8,
|
||||
}
|
||||
}
|
||||
/// v11: `EmbeddedLens.source` (v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
|
||||
const NEWEST_FIELDS: u32 = 11;
|
||||
/// v12: `Catalog.grids` and `SegMask.grid`, shared by a snapshot's masks (#2154) (v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9:
|
||||
/// `Photo.preview_checked` and `Op::SetContent.preview_checked`).
|
||||
const NEWEST_FIELDS: u32 = 12;
|
||||
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
|
||||
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Issue #2154: a snapshot keeps each distinct segmentation grid once (`Catalog.grids`) and the
|
||||
//! masks of the develop settings, versions, history steps and import look refer to it by index,
|
||||
//! so an unchanged mask no longer repeats with every history step. In-memory catalogs and log
|
||||
//! records always hold the grids inline; older catalogs (inline everywhere) load and are upgraded.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape, SegMask};
|
||||
|
||||
use crate::journal::{LOG, SNAPSHOT, VERSION};
|
||||
use crate::*;
|
||||
|
||||
fn snapshot_version(m: &MemStore) -> u64 {
|
||||
let v: serde_json::Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap();
|
||||
v["version"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn open(m: &MemStore) -> (Journal, Catalog, LoadReport) {
|
||||
Journal::open(Box::new(m.clone())).unwrap()
|
||||
}
|
||||
|
||||
/// Develop settings with one AI mask over an object segmentation.
|
||||
fn settings_with_seg(seg: SegMask, exposure: f64) -> DevelopSettings {
|
||||
let mut s = DevelopSettings::default();
|
||||
s.light.exposure = exposure;
|
||||
s.masks.push(Mask {
|
||||
id: 1,
|
||||
components: vec![MaskComponent {
|
||||
name: None,
|
||||
op: MaskOp::Add,
|
||||
invert: false,
|
||||
shape: MaskShape::Object {
|
||||
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
|
||||
exclude: vec![],
|
||||
seg: Some(seg),
|
||||
detail: vec![],
|
||||
edge: 0.0,
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
s
|
||||
}
|
||||
|
||||
/// One mask (`id`) whose only component is an Object segmentation `seg`.
|
||||
fn object_mask(id: u32, seg: SegMask) -> Mask {
|
||||
Mask {
|
||||
id,
|
||||
components: vec![MaskComponent {
|
||||
name: None,
|
||||
op: MaskOp::Add,
|
||||
invert: false,
|
||||
shape: MaskShape::Object {
|
||||
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
|
||||
exclude: vec![],
|
||||
seg: Some(seg),
|
||||
detail: vec![],
|
||||
edge: 0.0,
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog of one photo whose history is `steps` slider edits over the same mask, plus the
|
||||
/// ops that built it (each step is one `SetDevelop` + one `PushHistory`, as the engine commits
|
||||
/// an edit) and the shared grid's bytes.
|
||||
fn masked_catalog(steps: usize) -> (Catalog, Vec<Op>, PhotoId, String) {
|
||||
let seg = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let blob = seg.data.clone();
|
||||
let mut c = Catalog::new();
|
||||
let id = c.alloc_photo_id();
|
||||
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::File { path: "/p/1.jpg".into() }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) };
|
||||
c.apply(add.clone()).unwrap();
|
||||
let mut ops = vec![add];
|
||||
for i in 1..=steps {
|
||||
let settings = Arc::new(settings_with_seg(seg.clone(), f64::from(i as u32) * 0.1));
|
||||
let op = Op::Batch {
|
||||
ops: vec![
|
||||
Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some(format!("t{i}")) },
|
||||
Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings } },
|
||||
],
|
||||
};
|
||||
c.apply(op.clone()).unwrap();
|
||||
ops.push(op);
|
||||
}
|
||||
(c, ops, id, blob)
|
||||
}
|
||||
|
||||
/// N history steps over one mask store the grid exactly once and load back identical.
|
||||
#[test]
|
||||
fn snapshot_deduplicates_shared_grid() {
|
||||
let (live, ops, id, blob) = masked_catalog(20);
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, report) = open(&m);
|
||||
assert!(report.created);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(snapshot_version(&m), u64::from(VERSION));
|
||||
assert_eq!(body.match_indices(&blob).count(), 1, "the grid is stored once for every step that shares it");
|
||||
let v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1);
|
||||
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!((report.replayed, report.upgraded_from, report.repaired.len()), (0, None, 0));
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
let p = loaded.photo(id).unwrap();
|
||||
assert_eq!(p.history.len(), 20);
|
||||
for h in &p.history {
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &h.settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), (blob.as_str(), None), "every step's grid is back inline");
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog written before the shared table (grids inline everywhere, format v9) loads as it
|
||||
/// was and its upgrade rewrite deduplicates.
|
||||
#[test]
|
||||
fn v9_catalog_with_inline_grids_loads_and_is_upgraded() {
|
||||
let (live, _, _, blob) = masked_catalog(3);
|
||||
let body = live.to_snapshot();
|
||||
assert!(body.contains(&blob), "a live catalog stores its grids inline");
|
||||
let m = MemStore::new();
|
||||
m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":2,\"catalog\":{body}}}\n").into_bytes());
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!((report.replayed, report.upgraded_from), (0, Some(9)));
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
// rewritten in this format before anything is appended, with the grid once
|
||||
assert_eq!(snapshot_version(&m), u64::from(VERSION));
|
||||
let rewritten_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let rewritten = std::str::from_utf8(&rewritten_bytes).unwrap();
|
||||
assert_eq!(rewritten.match_indices(&blob).count(), 1);
|
||||
assert!(rewritten.contains("\"grids\":["), "the shared table is in the file");
|
||||
}
|
||||
|
||||
/// The op log is not deduplicated: every record keeps the grids inline (a log never carries the
|
||||
/// shared table), and replaying it rebuilds the same state.
|
||||
#[test]
|
||||
fn log_records_keep_their_grids_inline() {
|
||||
let (live, ops, _, blob) = masked_catalog(2);
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
drop(j); // no snapshot: the log holds the whole state
|
||||
let log_bytes = m.get(LOG).unwrap();
|
||||
let log = std::str::from_utf8(&log_bytes).unwrap();
|
||||
assert_eq!(log.match_indices(&blob).count(), 4, "two edits, SetDevelop + PushHistory each, inline");
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.replayed, 3, "the photo and the two edits");
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A reference that points past the shared table is cleared (the mask renders nothing, like any
|
||||
/// damaged grid); a good reference resolves back to the full grid.
|
||||
#[test]
|
||||
fn shared_grid_references_resolve_or_are_repaired() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: the develop mask refers past the one-entry table
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":7", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"dHdv\"],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared, never a crash");
|
||||
// the history step's inline grid is untouched
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob);
|
||||
|
||||
// a good reference resolves (the normal way a snapshot in this format reads, so it is not
|
||||
// reported as a repair): the mask reads exactly as it was written
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"{blob}\"],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, resolved, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
assert_eq!(resolved.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// The background snapshot path shares the grids too (the interner is per thread).
|
||||
#[test]
|
||||
fn background_snapshot_deduplicates_shared_grid() {
|
||||
let (live, ops, _, blob) = masked_catalog(5);
|
||||
let mut m = MemStore::new();
|
||||
m.background = true;
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot_in_background(&live).unwrap();
|
||||
j.wait().unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&blob).count(), 1);
|
||||
let (_, loaded, _) = open(&m);
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A version (not only history steps) shares the grid: one photo with a snapshot version and a
|
||||
/// history step over the same mask stores the grid once.
|
||||
#[test]
|
||||
fn versions_share_the_grid_too() {
|
||||
let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]);
|
||||
let blob = seg.data.clone();
|
||||
let id = PhotoId(1);
|
||||
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "d.jpg", "JPEG", 60, 40, "2026-01-01")) };
|
||||
let settings = Arc::new(settings_with_seg(seg, 0.5));
|
||||
let versions =
|
||||
Op::SetVersions { id, versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }] };
|
||||
let history = Op::PushHistory { id, step: HistoryStep { label: "e".into(), settings } };
|
||||
let mut live = Catalog::new();
|
||||
for op in [&add, &versions, &history] {
|
||||
live.apply(op.clone()).unwrap();
|
||||
}
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&[add, versions, history]).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&blob).count(), 1, "the version and the step share the grid");
|
||||
let (_, loaded, _) = open(&m);
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// The import look (`Photo.import_look`, the settings a default preset gave the photo on import)
|
||||
/// can hold AI masks, and their grids can be grids the develop settings or a history step hold.
|
||||
/// Every settings holder shares the snapshot's table, so the look's masks are referenced and
|
||||
/// resolved on load like the others; a grid only the look holds is in the table too.
|
||||
#[test]
|
||||
fn import_look_masks_share_the_table_and_resolve_on_load() {
|
||||
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let look_only = SegMask::from_logits(64, &vec![-0.5f32; 64 * 64]);
|
||||
let mut look = DevelopSettings::default();
|
||||
look.masks.push(object_mask(1, shared.clone()));
|
||||
look.masks.push(object_mask(2, look_only.clone()));
|
||||
let mut edit = DevelopSettings::default();
|
||||
edit.light.exposure = 0.7;
|
||||
edit.masks.push(object_mask(1, shared.clone()));
|
||||
let edit = Arc::new(edit);
|
||||
|
||||
let id = PhotoId(1);
|
||||
let mut photo = Photo::new(id, Source::File { path: "/p/2.jpg".into() }, "2.jpg", "JPEG", 60, 40, "2026-01-01");
|
||||
photo.develop = edit.clone();
|
||||
photo.import_look = Some(Arc::new(look));
|
||||
photo.history.push(HistoryStep { label: "Exposure".into(), settings: edit });
|
||||
let add = Op::AddPhoto { photo: Box::new(photo) };
|
||||
let mut live = Catalog::new();
|
||||
live.apply(add.clone()).unwrap();
|
||||
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&[add]).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&shared.data).count(), 1, "the grid of the look and of the edit is stored once");
|
||||
assert_eq!(body.match_indices(&look_only.data).count(), 1);
|
||||
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
let p = loaded.photo(id).unwrap();
|
||||
let look_masks = &p.import_look.as_ref().unwrap().masks;
|
||||
assert_eq!(look_masks.len(), 2);
|
||||
for (mask, want) in look_masks.iter().zip([&shared, &look_only]) {
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &mask.components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), (want.data.as_str(), None), "the look's grid is back inline");
|
||||
}
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
let v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 2, "one table entry per distinct grid, the look's included");
|
||||
}
|
||||
|
||||
/// A `grid` that arrives from a document (a command's mask JSON, a preset, a merged partial) is
|
||||
/// not a reference and is never written as one: a snapshot must not resolve it to another mask's
|
||||
/// grid. Here photo two's mask carries `grid: 0` with empty data, while photo one's grid is the
|
||||
/// table's entry 0; before the fix the inline form wrote `"grid":0` and the load filled photo two
|
||||
/// with photo one's grid.
|
||||
#[test]
|
||||
fn stray_grid_from_a_document_is_not_written_as_a_reference() {
|
||||
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let stray: SegMask = serde_json::from_str(r#"{"side":64,"data":"","grid":0}"#).unwrap();
|
||||
assert_eq!(stray.grid, Some(0), "a document can set grid");
|
||||
let mut stray_settings = DevelopSettings::default();
|
||||
stray_settings.masks.push(object_mask(1, stray));
|
||||
|
||||
let (one, two) = (PhotoId(1), PhotoId(2));
|
||||
let photo = |id: PhotoId, name: &str| Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01");
|
||||
let ops = [
|
||||
Op::AddPhoto { photo: Box::new(photo(one, "1.jpg")) },
|
||||
Op::SetDevelop { id: one, settings: Arc::new(settings_with_seg(shared.clone(), 0.2)), label: "Exposure".into(), edited: Some("t1".into()) },
|
||||
Op::AddPhoto { photo: Box::new(photo(two, "2.jpg")) },
|
||||
Op::SetDevelop { id: two, settings: Arc::new(stray_settings), label: "Edit".into(), edited: Some("t2".into()) },
|
||||
];
|
||||
let mut live = Catalog::new();
|
||||
for op in &ops {
|
||||
live.apply(op.clone()).unwrap();
|
||||
}
|
||||
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &loaded.photo(two).unwrap().develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the stray reference is not resolved to photo one's grid");
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A snapshot whose shared grid table is empty (`grids: []`) but whose masks still refer into
|
||||
/// it: the table being empty must not skip the repair. A reference past an empty table is
|
||||
/// dangling, so it is cleared (the mask renders nothing, like any other damaged grid), the
|
||||
/// repair is reported, and a mask that carries its own grid inline is left untouched.
|
||||
#[test]
|
||||
fn empty_shared_grid_table_clears_dangling_references() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: an empty table, but the develop mask still refers to entry 0
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with an empty table");
|
||||
|
||||
// the history step carries its grid inline: nothing there to resolve, left as it was
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
|
||||
}
|
||||
|
||||
/// A snapshot that omits the shared grid table entirely (no `grids` key) but whose masks still
|
||||
/// refer into it: an absent table deserializes to an empty Vec, so a reference past it is
|
||||
/// dangling and is cleared and reported, just like the empty-table case.
|
||||
#[test]
|
||||
fn omitted_shared_grid_table_clears_dangling_references() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: no table at all, but the develop mask still refers to entry 0
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{{} }} }}\n", &body[1..body.len() - 1])
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with no table");
|
||||
|
||||
// the history step carries its grid inline: nothing there to resolve, left as it was
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::journal::LOG;
|
||||
use crate::journal::{LOG, RESYNC_CANDIDATES};
|
||||
use crate::*;
|
||||
|
||||
/// A store whose next append writes only a prefix of its data, then fails.
|
||||
@@ -224,3 +224,208 @@ fn fs_store_truncates_a_missing_file_quietly() {
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Issue #2124: `resync` must be linear in the line length, not quadratic. A line that is nothing
|
||||
/// but the start marker repeated 300k times must open fast, and a valid retry record placed after
|
||||
/// it must still be recovered.
|
||||
#[test]
|
||||
fn resync_is_not_quadratic_in_line_length() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
// Build a valid snapshot + an initial record so `j.seq()` is non-zero and the `seq <= last + 1`
|
||||
// gate in resync can be exercised.
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
let first = apply(&mut c, vec![add]);
|
||||
j.append(&first).unwrap();
|
||||
|
||||
let log = probe.get(LOG).unwrap();
|
||||
let base_len = log.len();
|
||||
|
||||
// A hostile 300k-repetition marker line (about 2.3 MB), then one valid retried record that
|
||||
// continues the log (seq == j.seq() + 1, so resync's gate accepts it).
|
||||
let marker = b"{\"seq\":";
|
||||
let mut hostile = Vec::with_capacity(marker.len() * 300_000 + log.len() + 256);
|
||||
hostile.extend_from_slice(&log[..base_len]);
|
||||
for _ in 0..300_000 {
|
||||
hostile.extend_from_slice(marker);
|
||||
}
|
||||
|
||||
// Encode the retry record the same way the journal writes records, so decode_record accepts it.
|
||||
let next_seq = j.seq() + 1;
|
||||
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
|
||||
hostile.extend_from_slice(retry.as_bytes());
|
||||
|
||||
probe.set(LOG, hostile);
|
||||
|
||||
// Count the start markers resync decodes instead of timing it: a slow worker must not fail this.
|
||||
RESYNC_CANDIDATES.with(|c| c.set(0));
|
||||
let (j2, _c2, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|c| c.get());
|
||||
assert!(candidates <= 1, "resync decoded {candidates} start markers of a hostile 2 MB line; only the last one may be decoded");
|
||||
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
|
||||
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
|
||||
}
|
||||
|
||||
/// A retry record whose op body holds a nested `{"seq":` (a smart-album rule value such as
|
||||
/// `{"seq":1}` on a `title isEmpty` rule) shadows the record's own start marker: `rposition` in
|
||||
/// `resync` picks the nested occurrence, `decode_record` rejects the suffix, and `Journal::open`
|
||||
/// truncates the final line instead of replaying the retry — the valid operation is lost.
|
||||
#[test]
|
||||
fn resync_preserves_retry_record_with_nested_start_marker() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
|
||||
let album_id = c.alloc_album_id();
|
||||
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
|
||||
j.append(&apply(&mut c, vec![add_album])).unwrap();
|
||||
|
||||
let retry_op = Op::SetAlbumRules {
|
||||
id: album_id,
|
||||
rules: Box::new(Filter {
|
||||
rule_set: Some(RuleSet {
|
||||
mode: Match::All,
|
||||
rules: vec![Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }],
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
apply(&mut c, vec![retry_op.clone()]);
|
||||
|
||||
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
|
||||
// resync finds its real start: `seq` continues the log and the CRC matches the body.
|
||||
let next_seq = j.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
|
||||
|
||||
// A torn fragment glued to the retry on the final line. The outer record start sits right
|
||||
// after the fragment, but the last `{"seq":` byte occurrence is the nested rule value.
|
||||
let mut log = probe.get(LOG).unwrap();
|
||||
log.extend_from_slice(b"torn fragment without a newline");
|
||||
log.extend_from_slice(retry.as_bytes());
|
||||
probe.set(LOG, log);
|
||||
|
||||
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
|
||||
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
|
||||
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be truncated as torn");
|
||||
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the recovered smart-album rule should be preserved");
|
||||
}
|
||||
|
||||
/// The maintainer's regression for issue #2124, with the damaged line as the file's LAST one: a
|
||||
/// torn fragment glued to a CRC-valid `SetAlbumRules` retry whose rules hold several nested
|
||||
/// `{"seq":1}` values. Picking the last raw `{"seq":` occurrence as the record start (as the
|
||||
/// original `rposition` scan did) lands in a nested value, rejects the whole record, and cuts the
|
||||
/// final line away — losing the valid operation. `resync` must recover the retry (its real start
|
||||
/// is followed by the `,"crc":` header no nested rule value has) and leave the log file whole.
|
||||
#[test]
|
||||
fn resync_recovers_rules_retry_with_many_nested_values_on_the_final_line() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
|
||||
let album_id = c.alloc_album_id();
|
||||
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
|
||||
j.append(&apply(&mut c, vec![add_album])).unwrap();
|
||||
|
||||
let rules =
|
||||
(0..12).map(|_| Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }).collect::<Vec<_>>();
|
||||
let retry_op =
|
||||
Op::SetAlbumRules { id: album_id, rules: Box::new(Filter { rule_set: Some(RuleSet { mode: Match::All, rules }), ..Default::default() }) };
|
||||
apply(&mut c, vec![retry_op.clone()]);
|
||||
|
||||
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
|
||||
// resync finds its real start: `seq` continues the log and the CRC matches the body.
|
||||
let next_seq = j.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}");
|
||||
|
||||
// The failed append's fragment glued to the retry, and nothing after: the damaged line is the
|
||||
// file's last, without a closing newline.
|
||||
let mut log = probe.get(LOG).unwrap();
|
||||
log.extend_from_slice(b"torn fragment without a newline");
|
||||
log.extend_from_slice(retry.as_bytes());
|
||||
let damaged = log.clone();
|
||||
probe.set(LOG, log);
|
||||
|
||||
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
assert_eq!(report.torn_fragments, 1, "the fragment must be reported and the retry recovered");
|
||||
assert_eq!(report.torn_bytes, 0, "the retry record must not be cut away as a torn tail");
|
||||
assert_eq!(j2.seq(), next_seq, "the retried SetAlbumRules must be recovered");
|
||||
assert_eq!(report.replayed, 3);
|
||||
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the smart-album rules must survive the reload");
|
||||
|
||||
// The log file is preserved: its bytes stay (plus only the newline that closes the final
|
||||
// line), instead of the damaged line being truncated away.
|
||||
let after = probe.get(LOG).unwrap();
|
||||
assert_eq!(after.len(), damaged.len() + 1, "the log must keep the fragment and the recovered record");
|
||||
assert_eq!(&after[..damaged.len()], &damaged[..]);
|
||||
}
|
||||
|
||||
/// A crafted final line of many header-shaped markers (`{"seq":1,"crc":2,"op":`) passes the
|
||||
/// record-header filter, so every marker becomes a resync candidate, and each attempt decodes the
|
||||
/// whole rest of the line: trying all of them is quadratic in the line length, a stall of
|
||||
/// `Journal::open` on a hostile log (CWE-407). The per-line scan budget must bound the candidate
|
||||
/// decodes (counted, not timed) and open must still finish safely. A CRC-valid retry placed after
|
||||
/// the junk must stay recoverable: it is the last candidate, so the scan reaches it first.
|
||||
#[test]
|
||||
fn resync_scan_budget_bounds_a_line_of_header_shaped_markers() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
let good = probe.get(LOG).unwrap();
|
||||
|
||||
const MARKERS: usize = 5_000;
|
||||
let marker: &[u8] = b"{\"seq\":1,\"crc\":2,\"op\":";
|
||||
let mut hostile = good.clone();
|
||||
hostile.extend_from_slice(b"torn fragment"); // so no marker sits at line position 0
|
||||
for _ in 0..MARKERS {
|
||||
hostile.extend_from_slice(marker);
|
||||
}
|
||||
let hostile_len = (hostile.len() - good.len()) as u64;
|
||||
probe.set(LOG, hostile);
|
||||
|
||||
RESYNC_CANDIDATES.with(|count| count.set(0));
|
||||
let (j2, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
|
||||
assert!(
|
||||
candidates < MARKERS,
|
||||
"resync tried all {candidates} candidates of a hostile {hostile_len}-byte line; the scan budget must bound the work"
|
||||
);
|
||||
assert!(report.damaged.is_none(), "{report:?}");
|
||||
assert_eq!(report.torn_fragments, 0);
|
||||
assert_eq!(report.torn_bytes, hostile_len, "the hostile line must be dropped as a torn tail");
|
||||
assert_eq!(j2.seq(), 1, "the records before the hostile line must survive");
|
||||
assert_eq!(probe.get(LOG).unwrap().len(), good.len(), "the log must be cut back to the last good record");
|
||||
|
||||
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
|
||||
let next_seq = j2.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let mut log = good.clone();
|
||||
for _ in 0..MARKERS {
|
||||
log.extend_from_slice(marker);
|
||||
}
|
||||
log.extend_from_slice(format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n").as_bytes());
|
||||
probe.set(LOG, log);
|
||||
|
||||
RESYNC_CANDIDATES.with(|count| count.set(0));
|
||||
let (j3, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
|
||||
assert_eq!(candidates, 1, "the retry is the last candidate and must decode first");
|
||||
assert_eq!(j3.seq(), next_seq, "the retried record after the junk must be recovered");
|
||||
assert_eq!(report.torn_fragments, 1, "the junk before the retry is one skipped fragment");
|
||||
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be cut away");
|
||||
}
|
||||
@@ -862,3 +862,210 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`crate::decode_jpeg_srgb8_fit`]: a plain 8-bit sRGB JPEG decoded (DCT-scaled when that still
|
||||
/// covers the box) and area-averaged in linear light straight into 8-bit sRGB, without the
|
||||
/// float image the general path builds (for a 45 MP camera preview fitted to 2560 px that float
|
||||
/// image and its conversions were half the time). `Ok(None)` for anything else.
|
||||
pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(lightcraft_raster::Rgba8, u16)>> {
|
||||
// (a Samsung SEF trailer read as the file it stands for, as the general decode does: CodeRabbit on #3583)
|
||||
let bytes = &*without_sef_trailer(bytes);
|
||||
let Some(m) = parse_markers(bytes) else { return Ok(None) };
|
||||
let plain = matches!(m.components, 1 | 3)
|
||||
&& m.precision == 8
|
||||
&& matches!(m.sof, 0xC0..=0xC2)
|
||||
&& m.icc.is_none()
|
||||
&& !m.icc_invalid
|
||||
&& m.adobe_transform.is_none();
|
||||
let summary = m.exif.as_deref().map(exif::summarize).unwrap_or_default();
|
||||
if !plain || summary.adobe_rgb_hint || max_w == 0 || max_h == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let budget = DecodeOptions::default();
|
||||
check_size(F, m.width as u64, m.height as u64, &budget)?;
|
||||
// as in the general decode: the decoders below walk every APP1 again
|
||||
if m.app1 > MAX_APP1 {
|
||||
return Err(Error::Malformed(F, "too many APP1 markers".into()));
|
||||
}
|
||||
let scale_to = (m.width >= max_w.saturating_mul(2) || m.height >= max_h.saturating_mul(2)).then_some((max_w, max_h));
|
||||
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
|
||||
let raw =
|
||||
if scale_to.is_some() || non_interleaved { decode_jpeg_decoder(bytes, &m, scale_to, &budget)? } else { decode_zune(bytes, &m, &budget)? };
|
||||
let Buf::U8(px) = &raw.buf else { return Ok(None) };
|
||||
let ch = match raw.model {
|
||||
Model::Rgb => 3,
|
||||
Model::Gray => 1,
|
||||
Model::Cmyk => return Ok(None),
|
||||
};
|
||||
let (w, h) = (raw.width, raw.height);
|
||||
if w == 0 || h == 0 || px.len() < w.saturating_mul(h).saturating_mul(ch) {
|
||||
return Err(Error::Malformed(F, "short output".into()));
|
||||
}
|
||||
// the size `lightcraft_raster::resample::fit` gives: within the box, aspect kept, never larger
|
||||
let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0);
|
||||
let tw = ((w as f64 * s).round() as usize).clamp(1, w);
|
||||
let th = ((h as f64 * s).round() as usize).clamp(1, h);
|
||||
let orientation = summary.orientation.filter(|o| (1..=8).contains(o)).unwrap_or(1);
|
||||
Ok(Some((area_average_srgb8(px, w, h, ch, tw, th), orientation)))
|
||||
}
|
||||
|
||||
/// Source pixels and weights each output pixel along one axis covers: a box of the scale's width
|
||||
/// (`n` source pixels onto `out`), partly covered pixels at its ends weighted by their share.
|
||||
fn box_taps(n: usize, out: usize) -> Vec<(usize, Vec<f32>)> {
|
||||
let scale = n as f64 / out as f64;
|
||||
(0..out)
|
||||
.map(|o| {
|
||||
let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n as f64));
|
||||
let first = (a.floor() as usize).min(n - 1);
|
||||
let last = ((b.ceil() as usize).max(first + 1)).min(n);
|
||||
let ws: Vec<f32> =
|
||||
(first..last).map(|j| ((b.min(j as f64 + 1.0) - a.max(j as f64)).max(0.0) / (b - a).max(f64::MIN_POSITIVE)) as f32).collect();
|
||||
(first, ws)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `px` (`w × h`, `ch` = 1 or 3 interleaved 8-bit sRGB samples) averaged over boxes in linear
|
||||
/// light into `tw × th` opaque 8-bit sRGB pixels. A copy when the size doesn't change.
|
||||
fn area_average_srgb8(px: &[u8], w: usize, h: usize, ch: usize, tw: usize, th: usize) -> lightcraft_raster::Rgba8 {
|
||||
use lightcraft_color::transfer::{decode_srgb8, encode_srgb8};
|
||||
let mut out = lightcraft_raster::Rgba8::new(tw, th);
|
||||
let sample = |x: usize, y: usize, c: usize| px.get((y * w + x) * ch + if ch == 3 { c } else { 0 }).copied().unwrap_or(0);
|
||||
if (tw, th) == (w, h) {
|
||||
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = [sample(x, y, 0), sample(x, y, 1), sample(x, y, 2), 255];
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
let lut: [f32; 256] = std::array::from_fn(|i| decode_srgb8(i as u8));
|
||||
let xs = box_taps(w, tw);
|
||||
let ys = box_taps(h, th);
|
||||
// one source row filtered across into linear RGB at the output width
|
||||
let across = |sy: usize, buf: &mut Vec<[f32; 3]>| {
|
||||
buf.clear();
|
||||
let Some(src) = px.get(sy * w * ch..(sy + 1) * w * ch) else {
|
||||
buf.resize(tw, [0.0; 3]);
|
||||
return;
|
||||
};
|
||||
for (x0, wx) in &xs {
|
||||
let mut a = [0f32; 3];
|
||||
if let Some(span) = src.get(x0 * ch..(x0 + wx.len()) * ch) {
|
||||
for (p, &k) in span.chunks_exact(ch).zip(wx) {
|
||||
match p {
|
||||
[r, g, b] => {
|
||||
a[0] += lut[*r as usize] * k;
|
||||
a[1] += lut[*g as usize] * k;
|
||||
a[2] += lut[*b as usize] * k;
|
||||
}
|
||||
[v] => {
|
||||
let l = lut[*v as usize] * k;
|
||||
a = [a[0] + l, a[1] + l, a[2] + l];
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
buf.push(a);
|
||||
}
|
||||
};
|
||||
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
|
||||
let Some((y0, wy)) = ys.get(y) else { return };
|
||||
let mut acc = vec![[0f32; 3]; tw];
|
||||
let mut line = Vec::with_capacity(tw);
|
||||
for (dy, &k) in wy.iter().enumerate() {
|
||||
across(y0 + dy, &mut line);
|
||||
for (a, l) in acc.iter_mut().zip(&line) {
|
||||
a[0] += l[0] * k;
|
||||
a[1] += l[1] * k;
|
||||
a[2] += l[2] * k;
|
||||
}
|
||||
}
|
||||
for (o, a) in row.iter_mut().zip(&acc) {
|
||||
*o = [encode_srgb8(a[0]), encode_srgb8(a[1]), encode_srgb8(a[2]), 255];
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod srgb8_fit_tests {
|
||||
use super::*;
|
||||
|
||||
fn jpeg(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
|
||||
let data: Vec<[u8; 4]> = (0..w * h)
|
||||
.map(|i| {
|
||||
let [r, g, b] = f(i % w, i / w);
|
||||
[r, g, b, 255]
|
||||
})
|
||||
.collect();
|
||||
let img = lightcraft_raster::Rgba8 { width: w, height: h, data };
|
||||
crate::encode_jpeg(&crate::EncodeImage::rgba8(&img), 95, crate::ChromaSubsampling::S420, &crate::EncodeMeta::default()).unwrap()
|
||||
}
|
||||
|
||||
/// The fast path shows what the general decode shows for a plain sRGB JPEG, at the same size.
|
||||
#[test]
|
||||
fn matches_the_general_decode_within_a_few_levels() {
|
||||
let b = jpeg(1203, 801, |x, y| [((x * 7) ^ (y * 3)) as u8, (x / 5 + y / 3) as u8, ((x * y) % 251) as u8]);
|
||||
for (mw, mh) in [(300u32, 300u32), (640, 640), (1203, 801), (5000, 5000), (500, 120)] {
|
||||
let (fast, o) = srgb8_fit(&b, mw, mh).unwrap().unwrap();
|
||||
let slow = crate::decode(&b, DecodeOptions::fit(mw, mh)).unwrap().to_srgb8();
|
||||
assert_eq!((fast.width, fast.height), (slow.width, slow.height), "box {mw}×{mh}");
|
||||
assert_eq!(o, 1);
|
||||
let diff: Vec<u32> =
|
||||
fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect();
|
||||
let mean = diff.iter().sum::<u32>() as f64 / diff.len() as f64;
|
||||
assert!(mean < 3.0, "box {mw}×{mh}: mean difference {mean}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Anything but plain 8-bit sRGB goes the general way; junk is an error or `None`, never a panic.
|
||||
#[test]
|
||||
fn declines_what_it_does_not_cover_and_never_panics() {
|
||||
let b = jpeg(64, 48, |x, _| [x as u8, 0, 0]);
|
||||
assert!(srgb8_fit(&b, 0, 10).unwrap().is_none());
|
||||
assert!(srgb8_fit(b"not a jpeg", 10, 10).unwrap().is_none());
|
||||
for cut in [0, 2, 20, b.len() / 2, b.len() - 3] {
|
||||
let _ = srgb8_fit(&b[..cut], 32, 32);
|
||||
}
|
||||
// a 1-pixel-wide image into a box much smaller in one axis
|
||||
let thin = jpeg(1, 300, |_, y| [y as u8, y as u8, y as u8]);
|
||||
let (img, _) = srgb8_fit(&thin, 10, 10).unwrap().unwrap();
|
||||
assert_eq!((img.width, img.height), (1, 10));
|
||||
}
|
||||
|
||||
/// An incomplete ICC_PROFILE sequence (chunk 1 of 2) is "has a profile we can't read", not
|
||||
/// "plain sRGB": the general decode handles it, as the doc says (CodeRabbit on #3577).
|
||||
#[test]
|
||||
fn an_incomplete_icc_sequence_goes_the_general_way() {
|
||||
let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]);
|
||||
let mut seg = vec![0xFF, 0xE2, 0, 0];
|
||||
seg.extend_from_slice(b"ICC_PROFILE | ||||