Compare commits

...
Author SHA1 Message Date
Brandon ThomasandClaude Opus 5.5 5fe74557ec Skip CodeRabbit reviews on Dependabot PRs (#2407)
Adds .coderabbit.yaml so CodeRabbit no longer reviews or comments on PRs opened by dependabot[bot].

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-20 11:38:50 -04:00
Dylan M. Taylor 666f78432b docs: add SonarCloud and CodeRabbit badges to README (#2240)
* docs: add SonarCloud and CodeRabbit badges to README

* docs: put SonarCloud and CodeRabbit badges on their own line
2026-10-20 11:31:44 -04:00
Brandon ThomasandClaude Opus 5.5 a2a41383c4 Release 0.10.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 22:19:04 -04:00
FrancoisandClaude d999e382ba #1949: pt-BR for Include selected photos and the mask overlay modes (#2033)
Claude-Session: https://claude.ai/code/session_01AbegtYaPuwqZ81pGfELsFK

Co-authored-by: Claude <[email protected]>
2026-10-18 16:59:33 -06:00
Dylan M. Taylor fb7ac08b9a ci: configure Dependabot for Cargo and GitHub Actions
Co-authored-by: Dylan M. Taylor <[email protected]>
2026-10-18 12:31:40 -06:00
Dylan M. Taylor 31a677fe3d docs: drop references to competing commercial software (#2213) 2026-10-18 10:41:49 -04:00
Brandon Thomas a945533f63 Merge pull request #2236 from storytold/claude/integrate-batch-42
Integration batch 42: 31 community PRs
2026-10-18 10:39:21 -04:00
Brandon Thomas d43dd1fc8f Merge PR #1778: Model downloads: Time out and cancel the name lookup (#1532) 2026-10-18 10:05:47 -04:00
Brandon Thomas 6f5d662df3 Merge PR #2235: Georgian: a symbol Noto Sans Georgian cannot paint 2026-10-18 09:53:40 -04:00
Brandon ThomasandClaude Opus 5.5 70265ed17a Batch 42: #1893's heap test passes the Copy DecodeOptions without clone (clippy 1.99)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 09:53:39 -04:00
Michael Anderson 19008bdee9 Test cancelling a name lookup while it waits 2026-10-18 08:36:24 -05:00
Brandon Thomas 56c9b49634 Merge PR #1919: Hasselblad FFF: colour matrix from the embedded 3FR header
# Conflicts:
#	docs/parity-checklist.md
#	docs/raw-parity.md
2026-10-18 09:22:57 -04:00
Brandon Thomas 2c60d2ab27 Merge PR #1778: Model downloads: Time out and cancel the name lookup (#1532) 2026-10-18 09:22:41 -04:00
Brandon Thomas 4b6db59ade Merge PR #1903: LRC-PRINT-PAGE: Page Options print page numbers, page info and crop marks (gap 15)
# Conflicts:
#	docs/gaps.md
#	docs/parity-checklist.md
2026-10-18 09:22:40 -04:00
Brandon ThomasandClaude Opus 5.5 cbdbd50f84 Merge main into #1919 (main already dropped the drop(write) line)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 09:21:51 -04:00
Brandon ThomasandClaude Opus 5.5 fe7edd7b26 Model downloads: the What's New note gets its own heading
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 09:21:34 -04:00
Brandon ThomasandClaude Opus 5.5 1e4aa93d58 LRC-PRINT-PAGE: the preview draws no Page Options for a package, as the print doesn't
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 09:21:12 -04:00
Brandon Thomas 7614fb14f1 Merge PR #1902: docs: refresh README features, counts and setup requirements 2026-10-18 09:20:46 -04:00
Brandon Thomas 2983a40385 Merge PR #1960: Merged develop settings are kept in range, as XMP import keeps them 2026-10-18 09:20:45 -04:00
Brandon Thomas 583e3ceefc Merge PR #2091: Reject trailing text after a bracketed IPv6 host in Url::parse 2026-10-18 09:20:43 -04:00
Brandon Thomas 5b66a4825e Merge PR #2150: Keep face index records aligned after a torn or failed append 2026-10-18 09:20:42 -04:00
Brandon Thomas dee8358c38 Merge PR #1838: Drop out-of-range GPS coordinates read from XMP 2026-10-18 09:20:40 -04:00
Brandon Thomas 8d41bf69f7 Merge PR #1894: HEIF: max_pixels on uncropped SPS sizes and grid totals (#1518) 2026-10-18 09:20:39 -04:00
Brandon Thomas f4e7d07e9b Merge PR #1989: TIFF: read strips and tiles larger than 128 MiB 2026-10-18 09:20:37 -04:00
Brandon Thomas 4e77935e6e Merge PR #2070: Show the applied profile when hovering it in the profile browser (#2057) 2026-10-18 09:20:36 -04:00
Brandon Thomas 7134099101 Merge PR #1691: LR-EXP-TYPE: omit redundant alpha from opaque 8-bit exports (#1670) 2026-10-18 09:20:34 -04:00
Brandon Thomas ad22d059db Merge PR #1844: fix(import): keep Lightroom luminance ranges open at white, report unmapped local sliders
# Conflicts:
#	contributors/people.toml
2026-10-18 09:20:33 -04:00
Brandon Thomas 29384a0404 Merge PR #1898: LR-MERGE-HEADLESS: merge dialogs remember the last settings per kind 2026-10-18 09:20:21 -04:00
Brandon Thomas 70100a34c5 Merge PR #2144: Strip XML 1.0-forbidden characters from XMP sidecar output 2026-10-18 09:20:19 -04:00
Brandon Thomas 363dbbdd9f Merge PR #2224: X-Trans CMOS 4 bodies take the X-T3's spectral matrices 2026-10-18 09:20:17 -04:00
Brandon Thomas 80e2d0e64a Merge PR #1884: AI denoise: support 102 MP Bayer raws (#1880) 2026-10-18 09:20:16 -04:00
Brandon Thomas d3b6266d07 Merge PR #1964: Contributors: add Marco Arnulfo
# Conflicts:
#	contributors/people.toml
2026-10-18 09:20:09 -04:00
Brandon Thomas c9f383b368 Merge PR #2040: Ignore zero or negative ISO when importing XMP 2026-10-18 09:19:45 -04:00
Brandon Thomas 389be0f6a9 Merge PR #2105: l10n: unify zh-hant library term and contact sheet wording 2026-10-18 09:19:43 -04:00
Brandon Thomas f819c8439b Merge PR #2151: Make TIFF chunk-length inference and header-plan merging fast 2026-10-18 09:19:42 -04:00
Brandon Thomas e6a7501adc Merge PR #1416: Localize Info Overlay mode-change notices 2026-10-18 09:19:29 -04:00
Brandon Thomas 0a0cb19011 Merge PR #1893: JPEG XL: check dimensions during loading & bound tracked allocations (#1517) 2026-10-18 09:19:27 -04:00
Brandon Thomas 7b65a6a59f Merge PR #1911: Contributors: credit nledford by real name 2026-10-18 09:19:26 -04:00
Brandon Thomas d43889145b Merge PR #2046: Start crop drags in the zone the cursor showed at the press 2026-10-18 09:19:24 -04:00
Brandon ThomasandClaude Opus 5.5 6985cfa54c Drop the README notes: toast language is not README material
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 09:18:48 -04:00
Brandon Thomas 592cb335cb Merge PR #1935: raw: alias Canon EOS R6 Mark II to EOS R6m2 2026-10-18 09:18:21 -04:00
Brandon Thomas d6a9a2e8f9 Merge PR #1845: Match f:/aperture:/focal: search tokens at f32 precision 2026-10-18 09:18:19 -04:00
Brandon Thomas 11308a5c8a Merge PR #2035: Reject out-of-range start in photo.rename and photo.renamePreview 2026-10-18 09:18:17 -04:00
Brandon Thomas 9bf08f6ce6 Merge PR #2083: Reject signed hex digits in #rrggbb colour parsing 2026-10-18 09:18:16 -04:00
Brandon Thomas 5c85bc3ee4 Merge PR #2149: Refuse catalog snapshots with an out-of-range seq 2026-10-18 09:18:14 -04:00
Hamza 0c3c500ea4 Georgian: a symbol Noto Sans Georgian cannot paint
`cargo xtask ci` fails with the craft-fonts input supplied, which CLAUDE.md says
releases always build with:

    ka in Proportional (faces: ["Noto Sans Georgian"]) lack glyphs: ✕

Two strings in ka.json use ✕ (U+2715). Noto Sans Georgian has no glyph for it
and egui's bundled fonts do not either, so a Georgian reader gets a blank where
the text describes the activity stack's stop control. Without the fonts input
those twenty tests skip, so a plain `cargo xtask ci` is green and this stayed
invisible.

The two Georgian values use × (U+00D7) instead: it reads the same at text size
and every face has it. The English keys are untouched — they are the source text
from docs/whats-new.md, and the test checks values, which is the right scope. An
English reader's font covers ✕; the problem is a translation carrying it into a
script whose face does not.

`translated_catalogs_do_not_use_missing_menu_triangles` already forbids ▸ and ▾
in locale JSON for the same reason, so ✕ joins them in one list. That matters
because ✕ is in the English source of those two strings: every language that
translates them next would hit the same failure, and a cheap test now catches it
instead of the font-dependent one.
2026-10-18 18:12:18 +05:00
NetterSilverandClaude Haiku 5.5 601ddce6ef Match f:/aperture:/focal: search tokens at f32 precision
Found while testing crates/catalog/src/query.rs:130

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-18 13:49:17 +02:00
Marco Arnulfo b9159b0fce TIFF: keep the default 128 MiB intermediate buffer for small pixel budgets 2026-10-18 13:18:49 +02:00
Yorgos S. 863adcac6f X-Trans CMOS 4 bodies take the X-T3's spectral matrices
An X-T30 RAF shot in Acros embeds a black-and-white camera JPEG, so the
per-file look fits only the tone curve, and the colour came from the
neutral "camera RGB ~ sRGB" fallback: a grey sky and muted colours. The
raw decode (lossless compressed) was correct.

Add a hand-kept SAME_SENSOR alias list next to the generated
rawtoaces-data table: the 26.1 MP X-Trans CMOS 4 bodies (X-T30, X-T30 II,
X-Pro3, X100V, X-S10, X-E4) use the X-T3's measured matrices, and their
white balance reads in Kelvin through them.
2026-10-18 11:46:07 +02:00
Brandon ThomasandClaude Opus 5.5 4f0b110bcb Release 0.9.1: the release web build installs the wasm-bindgen CLI
Since the web zip moved from trunk to cargo xtask web (aeaf4154), packaging/web/package.sh needs the
wasm-bindgen CLI at Cargo.lock's version, and the shared release workflow installs only trunk, so
0.9.0's Web (wasm) job failed. In CI, install it first (as FilmCraft and EffectCraft do).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 23:16:37 -04:00
Brandon ThomasandClaude Opus 5.5 20ccedf56e Release 0.9.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 21:42:57 -04:00
Alex Chambers 43a47e5a3b Issue #1952: clip non-finite float image samples safely (#2071) 2026-10-17 18:40:14 -06:00
NetterSilverandClaude Haiku 5.5 cebb2be4d4 Keep the zone when shifting a capture time without seconds (#2146)
Found while testing crates/catalog/src/dates.rs:52 (shift_iso, tail = iso.trim().get(19..)); used by crates/engine/src/cmd/manage.rs:222

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-17 18:39:42 -06:00
NetterSilverandClaude Haiku 5.5 f48b2ad895 Search words with an unknown field prefix as plain text (#2099)
Found while testing crates/catalog/src/query.rs:146-177 (token_matches)

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-17 18:39:08 -06:00
NetterSilverandClaude Haiku 5.5 0d2c77c258 Fix Assisted Culling bursts that cross midnight at month end (#2095)
Found while testing crates/engine/src/cmd/cull.rs:17-20 (secs, used by the burst grouping at cull.rs:45)

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-17 18:38:33 -06:00
NetterSilverandClaude Haiku 5.5 5589827178 Fix offline reverse geocoding for cities at longitude exactly 180 (#2061)
Found while testing crates/geocode/src/lib.rs:105-108 (cell) vs lib.rs:189-192 (reverse)

Co-authored-by: Claude Haiku 5.5 <[email protected]>
2026-10-17 18:37:42 -06:00
skylar taylor-barrick 2218d97e89 Merge pull request #2199 from skylartaylor/open-original-media-gate
Open Original: only file types LightCraft reads reach the system opener
2026-10-17 17:07:18 -06:00
skylar taylor-barrick f9b0c8c8a1 Merge pull request #2175 from skylartaylor/linked-path-checks
Follow catalog paths only on this computer or the catalog's share
2026-10-17 12:14:13 -06:00
skylar taylor-barrick 2b173f0bee Build: take craft-docpath from the merged craft-libs rev
craft-libs#169 is merged, so the fork pin is no longer needed. Pinned to
storytold/craft-libs 82a24b006eefa036b43c09a67fb9a3fbd17ffe63 (main after the merge) rather than the older 12281d07,
which predates resolve_absolute and the Windows colon refusal.
2026-10-17 12:03:10 -06:00
skylar taylor-barrickandClaude e6587c3f82 chore: clear the rustc 1.96 clippy lints that fail cargo xtask ci
Unrelated to the #2135 security fix in the commit before this one: both lines
predate this branch and are rustc/clippy 1.96 lint churn. `cargo clippy
--workspace --all-targets` only warns about them, but `cargo xtask ci` runs it
with `-D warnings` (xtask/src/main.rs), so the gate fails before any test runs.

- `clippy::nonminimal_bool` in `slide_overlay::shadow` (reported twice, two
  overlapping suggestions on the one expression): `!(A && B) || !C || !D` is
  `!(A && B && C && D)` by De Morgan, which is what the line now says. The
  operands are pure float comparisons and `is_finite` guards with no side
  effects, so this is an exact rewrite — a NaN or infinite `mx0`/`my0` still
  makes `shadow` return without drawing, as before. (Clippy's second suggestion
  drops the `my0.is_finite()` term and is *not* equivalent; it is not used.)
- `clippy::drop_non_drop` on `drop(write)` in
  `same_folder_as_original_refuses_photos_without_a_folder`. The line is not
  dead: `write` is a closure holding a mutable borrow of `written`, and the
  `drop` ended that borrow so the next assertion could read it. The closure now
  lives in a block of its own instead, which ends the borrow at the brace
  rather than relying on `drop` of a non-`Drop` type. Every assertion of the
  test is unchanged.

Co-Authored-By: Claude <[email protected]>
2026-10-17 10:33:47 -06:00
skylar taylor-barrickandClaude d54673bb95 #2135: only file types LightCraft reads reach the system opener
Photo ▸ Edit In ▸ Open Original in Other Editor handed a photo's stored path
straight to `open` / `xdg-open` / `explorer.exe`, with `Path::is_file()` as the
only check, and Lightroom catalog import kept original paths exactly as the
catalog had them. A crafted `.lrcat` could therefore put `payload.exe`,
`start.lnk`, `run.bat`, `page.hta`, `Evil.app` or `go.command` into the library
and have it run on one user click.

- `lightcraft_engine::open_path`: one gate for every path that leaves
  LightCraft for the OS. The extension must be one LightCraft reads
  (`import::EXTENSIONS`, which already covers the Edit In copy formats
  `tif`/`tiff`/`psd`), it must be a regular file (so a `.app` bundle and any
  other folder are out), what a link resolves to must be a read type too, and
  what is handed over is the absolute path. A refusal is the sentence shown to
  the user.
- Open Original and Edit In go through it; a refused photo is listed in
  `skipped` with the reason, and the menu item is greyed out for a record that
  can never be opened (extension only, so no disk or share is touched while a
  menu is drawn).
- `lightroom_catalog::refuse_non_media` drops such images where the catalog is
  read and again where its photos become records, with a warning each, so a
  refused entry never becomes an openable library record. A virtual copy of a
  refused original goes with it.

Tests: a catalog naming a program (and a virtual copy of it) imports neither
while the catalog's real photos do; a library record naming a program is never
handed to the stub launcher, which records no invocation, and a program
selected beside a photo leaves only the photo, by absolute path. Both fail
before this change.

Co-Authored-By: Claude <[email protected]>
2026-10-17 10:18:47 -06:00
adrdsouzaandCodex a8bc882092 Correct JPEG XL test target guard & tracked-budget claims (#1517)
Pitch-Impact: none

Co-authored-by: Codex <[email protected]>
2026-10-17 21:13:49 +05:30
adrdsouzaandCodex 9c4fce176f Record CI-generated codecs test dependency lockfile
Co-authored-by: Codex <[email protected]>
2026-10-17 20:50:59 +05:30
adrdsouzaandCodex 16beb4db40 Bound JPEG XL input feeds through the final frame (#1517)
Retain the pre-frame size check and allocation budget while avoiding untracked input-sized buffers. Add the reported heap regression and container/progressive compatibility checks.

Co-authored-by: Codex <[email protected]>
2026-10-17 20:38:18 +05:30
NetterSilverandClaude Haiku 5.5 f6d465c72c Make TIFF chunk-length inference and header-plan merging fast
Fixes #2128

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 14:50:59 +02:00
NetterSilverandClaude Haiku 5.5 fafa70724b Keep face index records aligned after a torn or failed append
Fixes #2129

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 14:33:33 +02:00
NetterSilverandClaude Haiku 5.5 035d572ac8 Refuse catalog snapshots with an out-of-range seq
Fixes #2130

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-17 13:57:37 +02:00
NetterSilverandClaude Haiku 5.5 e0c02d5e89 Strip XML 1.0-forbidden characters from XMP sidecar output
Fixes #2131

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-17 13:12:52 +02:00
wly 8e268431e0 l10n: unify zh-hant library term and contact sheet wording
Use 照片庫 for "library" everywhere (it was split between 照片庫 and
圖庫), and 縮圖目錄 for the contact sheet progress label to match the
File menu item. Only translations change; English keys and format
placeholders are untouched.
2026-10-17 15:08:07 +08:00
aiongg 62eb6627a6 Build: use craft-docpath from craft-libs 2026-10-17 02:21:02 +00:00
NetterSilverandClaude Haiku 5.5 edc369565e Reject trailing text after a bracketed IPv6 host in Url::parse
Found while testing crates/fetch/src/http.rs:87-102

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-17 04:17:46 +02:00
NetterSilverandClaude Haiku 5.5 80e439f6dc Reject signed hex digits in #rrggbb colour parsing
Found while testing crates/slideshow/src/settings.rs:296-300 (parse_color); same pattern in crates/engine/src/slideshow.rs:117-122 (fadeColor)

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-17 00:45:25 +00:00
MarekSpodBiedry 5be931e48a Show the applied profile when hovering it in the profile browser (#2057) 2026-10-17 00:23:38 +02:00
aiongg 7b934ca2b2 Sidecars: write XMP only beside an existing local original 2026-10-16 17:57:30 +00:00
aiongg 346681561a Lightroom import: follow catalog paths only on this computer or the catalog's share 2026-10-16 17:44:52 +00:00
NetterSilverandClaude Haiku 5.5 3accb56196 Start crop drags in the zone the cursor showed at the press
Fixes #1930

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 16:32:19 +00:00
NetterSilverandClaude Haiku 5.5 0a9675c6d9 Ignore zero or negative ISO when importing XMP
Found while testing crates/meta/src/xmp.rs:509-512

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-16 14:54:06 +00:00
NetterSilverandClaude Haiku 5.5 312dd04830 Reject out-of-range start in photo.rename and photo.renamePreview
Found while testing crates/engine/src/rename.rs:919 (start parsed at crates/engine/src/cmd/manage.rs:12)

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-16 16:21:24 +02:00
Marco Arnulfo b67bb01952 TIFF: read strips and tiles larger than 128 MiB (fixes #1983) 2026-10-16 07:04:45 +02:00
skylar taylor-barrick f34c7a8a89 Merge pull request #967 from dylanmtaylor/refactor/dry-github-actions
ci: refactor workflows to use storytold/craft-common-actions
2026-10-15 21:34:12 -06:00
skylartaylor 3885b61e6b ci: retain LightCraft installer and package checks 2026-10-16 05:25:18 +02:00
Dylan M. Taylor 0802892132 ci: refactor workflows to use storytold/craft-common-actions 2026-10-15 21:19:37 -04:00
Marco Arnulfo c8f741fd0b Contributors: add my name for the About window 2026-10-16 02:20:02 +02:00
Marco Arnulfo c5deea05e4 Merged develop settings are kept in range, as XMP import keeps them (fixes #1946) 2026-10-16 00:23:44 +02:00
FredApps 9bec9db541 LR-1670: refresh opaque RGB export against main 2026-10-15 22:24:56 +02:00
skybluu fa715c8c94 Localize Info Overlay mode notices (#911) 2026-10-15 15:10:36 -05:00
Claude 6938be39e4 Engine tests: drop the drop() of a closure (clippy drop_non_drop)
Clippy 1.97 rejects `drop(write)` in the same-folder export test: the
closure has no Drop, so its borrow of `written` already ends at its last
use and the call did nothing. Removed, with a note on why the following
read of `written` compiles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J2NDVXA8jQQWeJb4YVTb6b
2026-10-15 19:17:57 +00:00
naryzach dde403946b raw: alias Canon EOS R6 Mark II to EOS R6m2
Canon EOS R6 Mark II writes its Exif model as 'Canon EOS R6 Mark II', which failed the spectral camera table lookup because the table registers the model as 'EOS R6m2'. Add the alias mapping and regression unit tests in lightcraft_raw and lightcraft_catalog.
2026-10-15 12:17:25 -07:00
Claude b5dc500c54 Hasselblad 3FR / FFF: uncompressed RGB embedded previews
These files carry no JPEG: their preview is an uncompressed 8-bit RGB
IFD (1217 x 913 in the H4D-40 FFF, 218 x 218 in the CFV 3FR). The
largest such image is handed on by embedded_preview as a small baseline
TIFF, which lightcraft_codecs::decode reads, so 3FR / FFF show a preview
in the grid and loupe before they are developed. No Orientation tag is
written: the raw file's applies, as for JPEG previews without one. The
FFF's 16-bit copy (with a TransferFunction of unknown meaning) is not
used.

decode_raw_preview applied a container-declared colour space by forcing
the JPEG decoder on any owned preview; it now checks for JPEG bytes, so
a wrapped TIFF (or a JPEG XL preview) goes to its own decoder.

Checked on the CC0 H4D-40 FFF and CFV 3FR through
embedded_preview_srgb: right colours, the 3FR upright through its
Rotate90. Tests cover the wrap, the choice among RGB images, a short
strip and truncated files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J2NDVXA8jQQWeJb4YVTb6b
2026-10-15 18:58:05 +00:00
Claude 0f67225e83 Hasselblad FFF: colour matrix from the embedded 3FR header
An FFF (a 3FR converted on the desktop) has no colour matrix of its own:
the camera's stays in the original 3FR header the FFF carries as a
complete TIFF in private IFD0 tag 0xC51B. The new vendor::hasselblad
reader decodes 3FR / FFF through dng::decode_as and, when the file has
no matrix, takes the matrices from that header, so an FFF no longer
develops with the "camera RGB = sRGB" fallback (H4D-40 as-shot white
moves from xy 0.279, 0.356 to 0.325, 0.336).

RGGB checked against the camera preview on the CC0 H4D-40 FFF and CFV
3FR (raw.pixls.us 931 and 709). Synthetic tests cover the embedded
matrix, an own matrix winning, a missing or damaged header, and
truncated files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J2NDVXA8jQQWeJb4YVTb6b
2026-10-15 18:19:15 +00:00
Nathaniel LedfordandClaude d020c55062 Contributors: credit nledford by real name
Co-Authored-By: Claude <[email protected]>
2026-10-15 11:39:17 -04:00
Michael Anderson 25d466fd69 Merge remote-tracking branch 'upstream/main' into fix/1532-dns-deadline
# Conflicts:
#	docs/whats-new.md
2026-10-15 09:14:06 -05:00
Lucas LepskiandGPT-6.1 Sol 7ac6dd81fe DOC-README: refresh current features and setup requirements
Align feature descriptions, counts, exports and language options with the
current code. Distinguish model-dependent features and implemented Print
and slideshow workflows from their remaining gaps.

Co-Authored-By: GPT-6.1 Sol <[email protected]>
2026-10-15 15:40:53 +02:00
Marco Arnulfo 79d726f856 LRC-PRINT-PAGE: Page Options print page numbers, page info and crop marks (gap 15)
The Print dialog's Page section gets Lightroom's Page Options for Single Image
and Contact Sheet: the page number at the bottom right, the print settings line
(sharpening, profile, resolution) at the bottom left, and crop marks at the
corners of each photo. They are `print.set {page: {pageNumbers, pageInfo,
cropMarks}}`, saved with templates, drawn in the preview and composed into the
PDF; marks and text turn white on a dark page.
2026-10-15 15:38:03 +02:00
Matthew James SivakandClaude Opus 5.5 a43cb68593 LR-MERGE-HEADLESS: merge dialogs remember the last settings per kind
The HDR / Panorama / HDR Panorama dialogs now open with the options of the
last merge of that kind instead of the defaults, and those options are kept
in the library's prefs.json (Session::last_merge) so they survive a restart.
"With Last Settings" and HDR for Each Bracket Set read the same store.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 14:04:14 +02:00
Adrian D'souzaandClaude Opus 5.5 8a4d6f2ebf HEIF: hold uncropped SPS sizes and a grid's tiles together to max_pixels (#1518)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 17:23:19 +05:30
Adrian D'souzaandClaude Opus 5.5 112e202fed JPEG XL: check the size from the header before reading frames, under an allocation budget (#1517)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 17:23:18 +05:30
justinjohn0306 de038ca3d4 #1880: allow 102 MP AI denoise inputs 2026-10-15 16:31:06 +05:30
Brandon Thomas 0da998f24d Merge pull request #1867 from storytold/claude/integrate-batch-40
Integration batch 40: 3 rebased community PRs (GPU face detection, soft-proof zoom windows, faster folder sync) and restored tracker rows
2026-10-15 04:00:13 -04:00
Brandon ThomasandClaude Opus 5.5 e8856c828c Batch 40: raw-parity action 3 (verify popular Nikon, Fujifilm, Canon CR2 and Pentax bodies) is done (#1045, #1081)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:45:11 -04:00
Brandon ThomasandClaude Opus 5.5 b17483a3ce Batch 40: tracker rows that earlier batches' doc merges dropped are back
Batches 36's doc conflicts kept main's side of rows both sides had touched; for some, main had not changed the row,
so the PR's update was lost. Restored: LR-VIEW-FILMSTRIP (#1482), KEYC-COMPARE (#1491 + #1555), LR-IMP-LOCAL
(#1547 + #1820), LR-LIB-STACK (#1556), gaps 28 (#1555), 2 (#1029) and 23 (#1038), ROADMAP UI/UX (#1038). The
raw-parity by-maker and by-use tables are re-measured with coverage.py (545 verified, ~94% / ~85%).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:45:00 -04:00
Brandon ThomasandClaude Opus 5.5 e6dceb9f89 Batch 40: #1027's LR-VIEW-ZOOM row (✅, mask and proof zoom windows) kept; parity summary refreshed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:43:21 -04:00
Brandon Thomas 5e9f7f1a65 Merge PR #1027 (rebased)
# Conflicts:
#	ROADMAP.md
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/target-app-parity.md
2026-10-15 03:40:37 -04:00
Brandon Thomas 9ddb8d1824 Merge PR #1663 (rebased)
# Conflicts:
#	crates/ui-egui/locales/de.json
#	crates/ui-egui/locales/es.json
#	crates/ui-egui/locales/fr.json
#	crates/ui-egui/locales/ja.json
#	crates/ui-egui/locales/pt-br.json
#	crates/ui-egui/locales/ru.json
#	crates/ui-egui/locales/uk.json
#	crates/ui-egui/locales/zh-hans.json
#	crates/ui-egui/locales/zh-hant.json
2026-10-15 03:40:17 -04:00
Brandon Thomas 8291f08ab7 Merge PR #1602 (rebased) 2026-10-15 03:40:15 -04:00
Brandon ThomasandClaude Opus 5.5 1d7699056e Merge PR #1027
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:36:18 -04:00
Brandon ThomasandClaude Opus 5.5 2179473536 Merge PR #1663
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:24:51 -04:00
Brandon Thomas 132b0e3ac8 Merge pull request #1865 from storytold/claude/integrate-batch-39
Integration batch 39: 4 rebased community PRs (Georgian, slider scrub and reset hints, straight brush lines) and the Windows ARM64 font pin
2026-10-15 03:08:47 -04:00
Brandon ThomasandClaude Opus 5.5 00dced3dae Batch 39: #1829's straight brush lines carry pen pressure as the author merged them with #1033 (the whole masks.rs from the PR head)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:07:35 -04:00
Brandon ThomasandClaude Opus 5.5 4212907656 Merge PR #1602
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:02:56 -04:00
Brandon Thomas fd80e4eb2f Merge PR #1829 (updated head) 2026-10-15 03:01:12 -04:00
Brandon ThomasandClaude Opus 5.5 d6f63f244f Batch 39: parity summary refreshed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 03:00:59 -04:00
Brandon ThomasandClaude Opus 5.5 fd9d045c75 CI: the packaging scripts check out the craft-fonts revision release.yml pins (3d9ab3a, with Noto Sans Thai)
Windows ARM64 on main failed since batch 36: #1479's scripts pinned 8dcdacd, which predates the Thai face #1311
made required.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:57:33 -04:00
Brandon ThomasandClaude Opus 5.5 a22f9a6d46 Batch 39: hang guards of the slideshow PDF export and slow-import tests allow a loaded machine (both pass in seconds alone)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:51:35 -04:00
Brandon ThomasandClaude Opus 5.5 51d8018e27 Merge PR #1823 (rebased)
Georgian next to Italian in the language table, menus, catalogs list and docs; ka-formats.json lists the format
strings other PRs added, in English until translated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:39:01 -04:00
Brandon ThomasandClaude Opus 5.5 f0b5f0339a Batch 39: #1474's hint test expects the value hint #1604 gave the scrubbable value
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:38:20 -04:00
Brandon Thomas 88ca6ed572 Merge PR #1474 (rebased)
# Conflicts:
#	crates/ui-egui/src/widgets.rs
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 02:32:41 -04:00
Brandon Thomas 780872b158 Merge PR #1604 (rebased)
# Conflicts:
#	docs/parity-checklist.md
2026-10-15 02:32:16 -04:00
Brandon Thomas 809259a37d Merge PR #1829 (rebased)
# Conflicts:
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 02:32:15 -04:00
Brandon ThomasandClaude Opus 5.5 bc39923608 Merge PR #1604
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:28:24 -04:00
Brandon ThomasandClaude Opus 5.5 d9ed118c1d Merge PR #1474
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:13:45 -04:00
Michael Anderson fc6719d1db Merge remote-tracking branch 'upstream/main' into feat/brush-shift-click
# Conflicts:
#	docs/whats-new.md
2026-10-15 01:07:50 -05:00
Michael Anderson 888a54f52a Merge remote-tracking branch 'upstream/main' into fix/1532-dns-deadline
# Conflicts:
#	docs/whats-new.md
2026-10-15 01:05:38 -05:00
Brandon Thomas a82a001d20 Merge pull request #1857 from storytold/claude/integrate-batch-38
Integration batch 38: 6 rebased community PRs (Nikon camera profiles, lens-corrected colour, HDR frame order, focus points)
2026-10-15 02:00:39 -04:00
Brandon Thomas 2f1acef58f Merge PR #1595 (updated head) 2026-10-15 02:00:04 -04:00
Brandon ThomasandClaude Opus 5.5 a39e85da72 Merge PR #1829
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:00:02 -04:00
Brandon ThomasandClaude Opus 5.5 a94fc6bc84 Batch 38: What's New lists the Nikon profile and lens-corrected colour notes once
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:59:50 -04:00
Brandon Thomas 3f69729d69 Merge PR #1595 (updated head) 2026-10-15 01:59:36 -04:00
Brandon Thomas 0270d30eda Merge PR #1592 (updated head) 2026-10-15 01:59:36 -04:00
Brandon Thomas 956420ea5f Merge PR #1586 (updated head) 2026-10-15 01:59:36 -04:00
Brandon ThomasandClaude Opus 5.5 e44e7157fc Batch 38: rustfmt and parity summary after the merges
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:58:56 -04:00
Michael Anderson c877e8e9ee Merge remote-tracking branch 'origin/feat/nikon-z6ii-camera-profile' into feat/nikon-z8-d5300-profiles
# Conflicts:
#	README.md
#	README.zh-hans.md
#	crates/engine/src/camera_preview.rs
#	crates/engine/src/tests_xmp.rs
#	docs/camera-preview-colour.md
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 00:58:42 -05:00
Michael Anderson 296e2ce73c Merge remote-tracking branch 'origin/fix/colour-fit-lens-geometry' into feat/nikon-z6ii-camera-profile
# Conflicts:
#	crates/engine/src/camera_preview.rs
#	crates/engine/src/tests_xmp.rs
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 00:55:18 -05:00
Michael Anderson a77eafb32a Merge remote-tracking branch 'upstream/main' into feat/brush-shift-click
# Conflicts:
#	docs/whats-new.md
2026-10-15 00:54:23 -05:00
Michael Anderson aed214da7e Merge remote-tracking branch 'upstream/main' into fix/1532-dns-deadline
# Conflicts:
#	docs/whats-new.md
2026-10-15 00:50:50 -05:00
Brandon ThomasandClaude Opus 5.5 73ee54fe62 Batch 38: format catalogs list the strings this batch adds, in English until translated
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:48:46 -04:00
Brandon Thomas 11351ef141 Merge PR #1834 (rebased)
# Conflicts:
#	crates/ui-egui/locales/cs-formats.json
#	crates/ui-egui/locales/pl-formats.json
#	crates/ui-egui/src/lib.rs
2026-10-15 01:48:46 -04:00
Brandon ThomasandClaude Opus 5.5 202fcbb525 Merge PR #1823
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:48:43 -04:00
Michael Anderson 9ad2c1766b Merge remote-tracking branch 'upstream/main' into fix/colour-fit-lens-geometry
# Conflicts:
#	crates/engine/src/camera_preview.rs
#	crates/engine/src/files.rs
#	docs/whats-new.md
2026-10-15 00:48:09 -05:00
Brandon Thomas d5b2cd1474 Merge PR #1595 (rebased)
# Conflicts:
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 01:48:05 -04:00
Brandon Thomas 97959610be Merge PR #1592 (rebased)
# Conflicts:
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 01:47:46 -04:00
Brandon Thomas 99eba2e069 Merge PR #1586 (rebased)
# Conflicts:
#	crates/engine/src/camera_preview.rs
#	crates/engine/src/files.rs
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 01:45:53 -04:00
Brandon Thomas 0fb809c671 Merge PR #1614 (rebased)
# Conflicts:
#	crates/merge/src/hdr.rs
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-15 01:44:24 -04:00
Brandon Thomas e4519aa710 Merge PR #1487 (rebased)
# Conflicts:
#	docs/parity-checklist.md
2026-10-15 01:43:02 -04:00
Brandon ThomasandClaude Opus 5.5 26e43cd691 Merge PR #1595
Stacked on rb/1592: LOOK_VERSION 8 -> 9; the PR's corpus-profile helper is the base's corpus_uses_the_bundled_profile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:42:11 -04:00
Brandon ThomasandClaude Opus 5.5 480e96c030 Merge PR #1592
Stacked on rb/1586: LOOK_VERSION 7 -> 8; README lists the base's ILCA-99M2 profile too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:42:11 -04:00
Brandon ThomasandClaude Opus 5.5 2756414f46 Merge PR #1586
Resolved against rb-base-36: LOOK_VERSION 6 -> 7; starting_colour_tags passes no lens (merge frames arrive without it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:42:11 -04:00
Brandon ThomasandClaude Opus 5.5 3c0300fcbb Merge PR #1614
Resolved against rb-base-36: docs combine the 1 px clip neighbourhood and frame order with the base's moving-highlight rule and 2048 px deghost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:42:11 -04:00
Brandon ThomasandClaude Opus 5.5 b5733c7649 Merge PR #1487
Resolved against rb-base-36: Scanned keeps the base's rewrite flag next to magic and tag; Exif keeps the Panasonic lens fallback; locale catalogs merged (one duplicate key dropped).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:42:11 -04:00
Brandon Thomas 3d003e8c64 Merge pull request #1852 from storytold/claude/integrate-batch-37
Integration batch 37: 20 rebased community PRs (print module, decode speed-ups, camera coverage, Italian)
2026-10-15 01:37:33 -04:00
Brandon ThomasandClaude Opus 5.5 a981538d05 Batch 37: the #1506 What's New entry once
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:36:59 -04:00
Brandon Thomas c870c32ce5 Merge PR #1469 (updated head) 2026-10-15 01:36:27 -04:00
Brandon Thomas 81849a499e Merge PR #1773 (updated head) 2026-10-15 01:36:27 -04:00
Brandon ThomasandClaude Opus 5.5 2a4b53f86c Batch 37: parity summary refreshed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:34:43 -04:00
Brandon ThomasandClaude Opus 5.5 b00d7c0267 Batch 37: the contact-sheet export test's deadline is a hang guard (it queues behind other tests' demo scenes)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:33:01 -04:00
cookingwithsimonandClaude Opus 5.5 77a37683bc LR-IMP-PROFILES: merge main into presets-apply-imported-profile (#1469)
Resolves conflicts with integration batch 36 (local adjustment presets):
the preset.import help and docs now describe both the mask-effect import
and the profile a preset names; both sides' tests are kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01GitCXGGRfeWqEhhnzH6s6D
2026-10-15 05:31:03 +00:00
Brandon ThomasandClaude Opus 5.5 dec7fd4eb2 Merge PR #1834
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:26:47 -04:00
Brandon Thomas 51a784cd95 Merge PR #1475 (rebased)
# Conflicts:
#	crates/raw/examples/rawinfo.rs
#	crates/raw/src/lib.rs
#	crates/raw/src/vendor/arw.rs
#	crates/raw/src/vendor/erf.rs
#	crates/raw/src/vendor/mef.rs
#	crates/raw/src/vendor/nef.rs
#	crates/raw/tests/lossy_dng.rs
#	crates/raw/tests/robust.rs
2026-10-15 01:13:36 -04:00
Brandon ThomasandClaude Opus 5.5 52a3b0ed84 Batch 37: #1471's test mosaic sets #1176's lens_metadata
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:12:03 -04:00
Brandon Thomas cf0002b484 Merge PR #1471 (rebased)
# Conflicts:
#	docs/parity-checklist.md
2026-10-15 01:10:17 -04:00
Brandon ThomasandClaude Opus 5.5 e5cc449bd1 Batch 37: the contact-sheet export and batch-merge tests wait longer on a busy machine (they pass alone, timed out under the full test run)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:10:07 -04:00
Brandon ThomasandClaude Opus 5.5 edfd4bc80a Batch 37: conflict markers left in three tracker headers by the #1327 merge resolved
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:07:22 -04:00
Brandon Thomas 66a0cd826c Merge PR #1475
# Conflicts:
#	crates/merge/src/output.rs
#	crates/raw/src/vendor/nef.rs
2026-10-15 01:05:31 -04:00
Brandon Thomas 7f7401713a Merge PR #1471
# Conflicts:
#	crates/engine/src/camera_preview.rs
#	crates/engine/src/merge.rs
#	crates/merge/src/frame.rs
#	crates/merge/src/hdr.rs
#	docs/parity-checklist.md
2026-10-15 00:56:52 -04:00
Brandon Thomas fbb9583d41 Merge PR #1810 (rebased)
# Conflicts:
#	docs/whats-new.md
2026-10-15 00:56:51 -04:00
Brandon ThomasandClaude Opus 5.5 3c489dc408 Batch 37: the print commands (#1215) take the Result that Session::targets returns since #1773
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:56:44 -04:00
Brandon ThomasandClaude Opus 5.5 4468917a1b Merge PR #1810
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:54:13 -04:00
Brandon ThomasandClaude Opus 5.5 60b938ab52 Batch 37: format catalogs list the strings this batch adds, in English until translated
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:53:53 -04:00
Brandon Thomas 3b6d15355b Merge PR #1298 (rebased)
# Conflicts:
#	crates/ui-egui/src/panels/dialogs.rs
2026-10-15 00:53:53 -04:00
Brandon Thomas 9ca113defa Merge PR #1135 (rebased)
# Conflicts:
#	xtask/src/main.rs
2026-10-15 00:53:45 -04:00
Brandon Thomas 76881c977e Merge PR #1327 (rebased)
# Conflicts:
#	ROADMAP.md
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/target-app-parity.md
2026-10-15 00:53:22 -04:00
Brandon Thomas 02000d98a4 Merge PR #1198 (rebased)
# Conflicts:
#	crates/ui-egui/src/panels/keyword_list.rs
2026-10-15 00:52:53 -04:00
Brandon Thomas 8591cdfa6b Merge PR #1469 (rebased)
# Conflicts:
#	crates/engine/src/lib.rs
#	docs/parity-checklist.md
2026-10-15 00:52:33 -04:00
Brandon Thomas 0af2d36442 Merge PR #1320 (rebased) 2026-10-15 00:52:32 -04:00
Brandon Thomas cab59313fd Merge PR #1316 (rebased) 2026-10-15 00:52:32 -04:00
Brandon Thomas b3012745d5 Merge PR #1215 (rebased)
# Conflicts:
#	docs/gaps.md
#	docs/parity-checklist.md
2026-10-15 00:52:31 -04:00
Brandon Thomas f7204aa8dd Merge PR #1176 (rebased) 2026-10-15 00:52:31 -04:00
Brandon Thomas 8b73a2ec2f Merge PR #1138 (rebased)
# Conflicts:
#	docs/gaps.md
2026-10-15 00:52:30 -04:00
Brandon Thomas 05aa012f37 Merge PR #1802 (rebased)
# Conflicts:
#	docs/whats-new.md
2026-10-15 00:52:30 -04:00
Brandon Thomas a690478e52 Merge PR #1773 (rebased)
# Conflicts:
#	docs/whats-new.md
2026-10-15 00:52:29 -04:00
Brandon Thomas 2f58918162 Merge PR #1762 (rebased)
# Conflicts:
#	crates/ui-egui/src/lib.rs
2026-10-15 00:52:29 -04:00
Brandon Thomas 7c5f36bd8c Merge PR #1761 (rebased)
# Conflicts:
#	docs/whats-new.md
2026-10-15 00:52:29 -04:00
Brandon Thomas 30168d759d Merge PR #1755 (rebased) 2026-10-15 00:52:28 -04:00
Brandon Thomas bc7abfae14 Merge PR #1708 (rebased) 2026-10-15 00:52:28 -04:00
Brandon Thomas 7b49657a26 Merge PR #1705 (rebased) 2026-10-15 00:52:27 -04:00
Brandon Thomas 12eab11cf5 Merge PR #1469
# Conflicts:
#	crates/engine/src/cmd/preset_files.rs
#	crates/engine/src/tests_import.rs
#	docs/parity-checklist.md
#	docs/xmp-interop.md
2026-10-15 00:50:08 -04:00
Michael Anderson dc562c654a Merge remote-tracking branch 'upstream/main' into feat/brush-shift-click
# Conflicts:
#	crates/engine/src/cmd/masks.rs
#	crates/ui-egui/src/panels/detail.rs
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-14 23:45:14 -05:00
Brandon Thomas f27ca795c7 Merge PR #1327
# Conflicts:
#	ROADMAP.md
#	crates/raw/tests/corpus.rs
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/raw-parity.md
#	docs/raw/coverage.tsv
#	docs/raw/evidence.tsv
#	docs/target-app-parity.md
2026-10-15 00:44:42 -04:00
Brandon ThomasandClaude Opus 5.5 81a9569301 Batch 36: rustfmt after merging #1802
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:42:56 -04:00
Brandon ThomasandClaude Opus 5.5 1e49095146 Merge PR #1802
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:42:40 -04:00
Michael Anderson e48d5d428d Merge remote-tracking branch 'upstream/main' into fix/1506-explicit-targets
# Conflicts:
#	crates/engine/src/cmd/library.rs
#	crates/engine/src/tests.rs
#	crates/ui-egui/src/panels/grid.rs
#	crates/ui-egui/src/panels/keywording.rs
#	crates/ui-egui/src/panels/right.rs
#	docs/whats-new.md
2026-10-14 23:38:19 -05:00
Brandon Thomas 372f39f8f7 Merge PR #1320
# Conflicts:
#	crates/engine/src/files.rs
#	crates/raw/src/demosaic/ahd.rs
2026-10-15 00:38:16 -04:00
Brandon Thomas af8843bf01 Merge PR #1316
# Conflicts:
#	crates/engine/src/camera_preview.rs
#	crates/engine/src/media.rs
2026-10-15 00:33:33 -04:00
Brandon ThomasandClaude Opus 5.5 2475cf5e32 Merge PR #1773
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:31:26 -04:00
Ege Gursel 31f4ad43fe contributors: re-add my people.toml entry lost in the merge 2026-10-15 00:29:43 -04:00
Michael Anderson ef216d2110 Merge remote-tracking branch 'upstream/main' into fix/1532-dns-deadline
# Conflicts:
#	docs/whats-new.md
2026-10-14 23:29:27 -05:00
Brandon Thomas ab96593df5 Merge PR #1298
# Conflicts:
#	crates/ui-egui/locales/de.json
#	crates/ui-egui/locales/es.json
#	crates/ui-egui/locales/fr.json
#	crates/ui-egui/locales/pt-br.json
#	crates/ui-egui/locales/ru.json
#	crates/ui-egui/locales/uk.json
#	crates/ui-egui/src/panels/dialogs.rs
#	crates/ui-egui/src/panels/faces.rs
#	crates/ui-egui/src/shortcuts.rs
2026-10-15 00:29:27 -04:00
Michael Anderson bcffde1a06 Merge remote-tracking branch 'upstream/main' into feat/nikon-z8-d5300-profiles
# Conflicts:
#	README.md
#	README.zh-hans.md
#	crates/engine/src/camera_preview.rs
#	docs/camera-preview-colour.md
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-14 23:28:25 -05:00
Michael Anderson 68ef6ff3b3 Merge remote-tracking branch 'upstream/main' into feat/nikon-z6ii-camera-profile
# Conflicts:
#	README.md
#	README.zh-hans.md
#	crates/engine/src/camera_preview.rs
#	docs/camera-preview-colour.md
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-14 23:26:01 -05:00
Ege Gursel f906998174 Merge branch 'main' into fix/xmp-import-local-grain-luminance-range 2026-10-15 00:25:35 -04:00
Ege Gursel 1130bda456 fix(import): keep Lightroom luminance ranges open at white, report unmapped local sliders
Two of the three problems reported in #1840:

- A luminance range at full strength up to white (LumRange "a b 1 1",
  a typical highlights mask) ended at our scene white (0 EV) with no
  feather, so anything brighter (the sun, speculars, a sky after a
  positive exposure) fell out of the mask along a hard edge. That end
  now stays open.
- Correction sliders we have no counterpart for (LocalGrain, ...) were
  dropped silently. They are now listed in `unmapped` as
  "Mask: LocalGrain"; LocalCurveRefineSaturation 100 counts as neutral.

Adobe base looks, the third problem, are handled by #1469.

Also adds my entry to contributors/people.toml.
2026-10-15 00:23:41 -04:00
Michael Anderson f9076514e7 Merge remote-tracking branch 'upstream/main' into fix/colour-fit-lens-geometry
# Conflicts:
#	crates/engine/src/camera_preview.rs
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-14 23:22:42 -05:00
Brandon Thomas b29a1a8cc2 Merge PR #1215
# Conflicts:
#	crates/engine/src/lib.rs
#	crates/engine/src/pdf.rs
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/menus.rs
#	crates/ui-egui/src/panels/dialogs.rs
#	crates/ui-egui/src/state.rs
#	docs/gaps.md
#	docs/parity-checklist.md
2026-10-15 00:22:08 -04:00
Brandon Thomas 7af7b31af6 Merge pull request #1843 from storytold/claude/integrate-batch-36
Integration batch 36: 110 reviewed community PRs (slideshow, camera verification, translations, never-crash, UI)
2026-10-15 00:16:05 -04:00
Brandon ThomasandClaude Opus 5.5 b333199eb1 Merge PR #1762
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:09:51 -04:00
Brandon Thomas 57503c9a4e Merge PR #1198
# Conflicts:
#	ROADMAP.md
#	assets/ATTRIBUTION.md
#	crates/ui-egui/src/i18n.rs
#	crates/ui-egui/src/menus.rs
#	crates/ui-egui/src/panels/keyword_list.rs
#	crates/ui-egui/src/panels/settings.rs
#	docs/localization-parity.md
#	docs/localization.md
2026-10-15 00:04:52 -04:00
Brandon ThomasandClaude Opus 5.5 1a120a86a2 Merge PR #1761
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:59:13 -04:00
Brandon Thomas f613aeba59 Merge PR #1176
# Conflicts:
#	crates/raw/src/vendor/arw.rs
#	docs/parity-checklist.md
#	docs/sony-lens-corrections.md
2026-10-14 23:54:06 -04:00
Brandon ThomasandClaude Opus 5.5 a0b55e66bb Merge PR #1755
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:48:20 -04:00
Brandon Thomas e6b2e6eefb Merge PR #1138
# Conflicts:
#	crates/catalog/src/lib.rs
#	crates/catalog/src/query.rs
#	crates/engine/src/cmd/library.rs
#	crates/ui-egui/src/tests_keywording.rs
#	docs/gaps.md
2026-10-14 23:46:16 -04:00
Brandon ThomasandClaude Opus 5.5 a0401d6949 Merge PR #1708
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:33:18 -04:00
Brandon Thomas 9ca3cd0926 Merge PR #1135
# Conflicts:
#	Cargo.lock
#	Cargo.toml
#	README.md
#	crates/raw/Cargo.toml
#	crates/ui-egui/src/theme.rs
#	xtask/src/main.rs
2026-10-14 23:23:18 -04:00
NetterSilverandClaude Haiku 5.5 48d69bfae5 Drop out-of-range GPS coordinates read from XMP
Found while testing crates/meta/src/xmp.rs:364 (parse_gps_coord, used at xmp.rs:539-544)

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 05:21:00 +02:00
Brandon ThomasandClaude Opus 5.5 b8c5913afe Merge PR #1705
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:11:45 -04:00
Michael Anderson 2953b63576 Merge remote-tracking branch 'upstream/main' into feat/brush-shift-click
# Conflicts:
#	docs/parity-checklist.md
2026-10-14 21:05:05 -05:00
Michael Anderson 15becc9eb4 Merge remote-tracking branch 'upstream/main' into feat/nikon-z8-d5300-profiles
# Conflicts:
#	docs/parity-checklist.md
2026-10-14 20:56:06 -05:00
Michael Anderson a68da45fc3 Merge remote-tracking branch 'upstream/main' into fix/colour-fit-lens-geometry
# Conflicts:
#	docs/parity-checklist.md
2026-10-14 20:55:01 -05:00
Michael Anderson 35f347397d Merge remote-tracking branch 'upstream/main' into feat/nikon-z6ii-camera-profile
# Conflicts:
#	docs/parity-checklist.md
2026-10-14 20:54:03 -05:00
Nathaniel LedfordandClaude Opus 5.5 62da9e8581 LRC-LIB-LIBFOLDERS: drag photos from the grid onto a Folders row to move them there
Photos dragged from the grid onto a Folders row move there on disk and in the library
(`photo.moveToFolder`: files and XMP sidecars, virtual copies follow, never overwrites, one undo
step), as Move Selected Photos Here in the row's menu does.
- The row lights up, and the label following the pointer says where they go: "Move 2 photos to
  “Porto”" (onto an album the same gesture only adds them, so the two read apart).
- A closed folder held under the pointer for 0.7 s opens, so a folder inside it can be reached.
- Refused, with the reason on release and a not-allowed pointer: a row that covers several disks,
  and Local photos (not in the library). Photos already there say "Already in “Porto”".
- A drop asks first, as Lightroom Classic does: "Move 2 photos to “Porto”?" (their files and
  XMP sidecars move on disk; Edit → Undo moves them back), with Don't ask again, kept in Settings
  as "Confirm before moving photos to another folder on disk" (on by default). The menu's Move
  Selected Photos Here, chosen by name, goes at once. A question left open while another library
  opens (the menu bar and agents reach past a dialog) moves nothing: photo ids are per library.
- The toast says how many moved and that Edit → Undo moves them back; the menu item says the same.
- Photos that leave the view leave the selection, so a Delete or edit next can't reach them unseen.

For NAS and network shares: the copy across volumes now streams (it read the whole file into
memory, a problem for a large raw or video) into a free hidden name that takes the photo's name only
once complete (a share dropping mid-copy left a truncated file under the photo's name, which a
retry reported as the photo already there). New engine tests cover a share going away:
Undo with the share offline or read-only is refused with the reason and kept until it can run,
nothing is deleted and the library stays linked; a connection lost partway through a move puts
back what moved; a file the share can't give back rolls the whole Undo back; and a real
move across devices where the machine has a second file system (`/dev/shm`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 20:58:08 -04:00
Michael Anderson e5c6e17bdb LR-MASK-BRUSH: Shift-click draws a straight brush stroke from the last one
A Shift-click with the brush paints a straight line from where the last stroke ended, tapering size, feather and flow when they changed in between, as one undo step. mask.brushStroke takes connect: true for it.
2026-10-14 19:11:34 -05:00
Nathaniel LedfordandClaude Opus 5.5 d0a9ca09dd Buttons: one component with kinds, sizes and icons
Buttons were egui's plain one, a fill set by hand where one had to stand out (a dialog's confirm,
About's Discord link), with no hover or press shade on a filled one and no shared sizes.

- `crate::button::Button`: what it is for (`Kind`: Primary filled with the accent, Secondary
  with a neutral fill and a border, Danger filled red, Ghost with no fill until hovered), how
  big (`Size`: Small 24, Medium 30, Large 36 points, each with its padding, text and icon size),
  and what it shows (text, an icon before the text, or an icon alone, which takes a name for
  screen readers and its tooltip).
- Hover and press darken it; disabled (or in a disabled part of the window) fades it and takes
  no click, its tooltip or name still shown; a focused one shows an accent ring. A filled kind's
  fill is darkened as little as needed for white to read at 4.5:1 (the light themes' accent and
  the red would be too pale), in every state. Drawn within its own rectangle.
- Named for screen readers, registered for scripts and tests (`.widget(id)`). Its egui id comes
  from the widget id (salted with `.id_salt`, e.g. the dialog's kind, so the keyboard's place
  doesn't carry from one dialog to the next) or from its place in the ui, moved on so buttons
  with the same text side by side stay apart.
- Dialogs' footers (Cancel, the confirm; at least 72 points wide) and About's Discord link use
  it. The Export dialog's expected height in `tests_dialog_fit` grows by the 8 points of its
  footer's 30-point buttons.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 17:57:58 -04:00
Nathaniel LedfordandClaude Opus 5.5 f50372d808 Dialogs: the confirm button is on the right, filled when it is the next step
A design critique of the first run found the import review's "Import N Photos" a plain button at
the bottom left beside Cancel, though the welcome before it had taught that blue means go.

- Every dialog's footer is right-aligned: the confirm on the right, Cancel to its left, added in
  that order so the keyboard goes through them as the eye does. The row spans the width the
  window gives its content this frame, so it reaches the window's edge without widening it.
- The confirm is filled with the accent when it makes or brings in something (`confirm_style`);
  Delete and Remove, and an informational dialog's Close, stay plain. Which dialogs only show
  something is one list (`only_shows`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 17:11:36 -04:00
Davit MatchakhelidzeandClaude Opus 5.5 fb2a460532 i18n(ka): bring the Georgian catalog up to date
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:38:48 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 9b9a96a1b5 i18n(ka): bring the Georgian catalog up to date
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:22:36 +04:00
Michael Anderson e65b97e239 Model downloads: Time out and cancel the name lookup (#1532)
The host name lookup blocked with no deadline before the cancel check, and each address then got the full connect timeout. The lookup now runs on a helper thread under the connect deadline, which all addresses share.
2026-10-14 13:56:34 -05:00
Michael Anderson 9ef40b9886 Commands: Refuse malformed photo ids instead of using the selection (#1506)
A wrongly typed id or ids fell back to the selection, or kept only the valid part of the list. Session::targets now returns an error for those, and callers pass it on.
2026-10-14 13:56:33 -05:00
Davit MatchakhelidzeandClaude Opus 5.5 af0c1638fe i18n: Georgian (ka) interface language
Adds Georgian (ქართული, code ka, system tags ka / ka-GE / ka_GE) with
complete plain and formats catalogs, the Edit > Language command and the
Settings choice. Sentence-cased messages go through i18n::upper_first,
which leaves Georgian letters alone (upper-casing Mkhedruli would turn it
into Mtavruli). The Settings language choices wrap now that eleven
endonyms no longer fit on one line, and the face-model Remove button goes
through tr().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-14 22:50:28 +04:00
Nathaniel LedfordandClaude Opus 5.5 18e808c08f LR-BEHAV-EMPTY-STATES: an empty library leads to Import
A library with no photos opened on the Detail view, whose empty state said "Choose a photo in
the grid or filmstrip" while the grid was empty and hidden: the only screen that mentioned
import was off screen, and Import itself was nowhere but the File menu and its shortcut.

- An empty library (no photos, or only deleted or browsed ones) opens on the Photo Grid with the
  sidebar (Square Grid stays as it is), in the desktop app and in `lightcraft-cli snapshot`. The
  desktop app switches before it notes what its settings file holds, so the switch alone isn't
  saved.
- The grid and the Detail view show "Your library is empty" with Import Photos… (primary) and
  Import Lightroom Catalog… (not on the web) as buttons, and a line saying photos and folders
  can be dropped into the window, with the key Import Photos… is bound to now (`⌘⇧I` on macOS,
  `Ctrl+Shift+I` elsewhere, or a remapped one). Not while a folder is browsed under Local or
  Recently Deleted is shown: their photos aren't in the library but are on screen.
- The right-hand panel says "No photos yet / Import photos to get started" there instead of
  "Select a photo to edit".
- The top bar has an Import button beside Export in every library. The centred search field's
  reserve grows by both sides' share (620, and a 190 minimum), so the filter icon stays clear of
  the icons on the right at every window width, also with macOS's title bar in the window. The
  top bar's icons are named for screen readers, and a refused click says why in a toast.
- `empty_state` is `empty_message` with buttons that do the next step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 14:03:50 -04:00
Marco Arnulfo 6f9aae0445 LR-PROF-DROPDOWN: a long profile name no longer widens the Edit panel (fixes #1759) 2026-10-14 20:02:11 +02:00
Nathaniel LedfordandClaude Opus 5.5 2b635bb167 LRC-LIB-KEYWORDS: control requests wait for a frame's first pass; a hold lasts one pass
A pass drawn again after a discard still has the widgets of the pass
thrown away, so a control request answered there found a row where it no
longer is; it also added a 240 fps sample to perf.fps. Control requests
and the fps sample now run on a frame's first pass only. The Keyword
List's hold is kept for the pass right after it was asked for, so it
never moves a panel that was not drawn in between.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 12:41:48 -04:00
Nathaniel LedfordandClaude Opus 5.5 648b1b5a93 LRC-LIB-KEYWORDS: the Keyword List holds its place as the Keywords box above it changes
Scrolled down a long Keyword List, ticking or unticking a keyword grew or
shrank the Keywords box above it (a row of chips, suggestions) and slid
the tree under the pointer. The panel now moves its scroll offset by the
same amount and draws the pass again, so the list stays put. It holds
only while the box's top is scrolled out of sight and the change does not
come from the box itself (the pointer on it, or typing in its field).

The offset is set on the scroll area as the redrawn pass starts, from the
offset the pass before started at: a scroll asked for during a pass lands
a frame later, and egui pulls a shrunken panel's offset back by the end
of a pass. Ticks clicked one after another (a script, a quick hand) then
land on the rows clicked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 12:38:02 -04:00
Claude ac17c580f5 Merge storytold/lightcraft main into LR-MERGE-HDR (frame order, clipped pixels)
Brings in #1423 (HDR merges keep the lens corrections), which landed in batch 35 / v0.8.0. hdr.rs merged cleanly:
the result's lens corrections come from the reference frame after the brightness ordering. Conflicts only in docs:
the LR-MERGE-HDR row keeps main's lens-correction text plus this branch's two items, and this branch's What's New
entry moves to the 2026-10-14 section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015gRtdWF1E9358FfzhzYqCS
2026-10-14 16:22:37 +00:00
Jason Baldwin 2b766142bc Merge origin/main into focus-point (tracker header/summary/change log, whats-new entry moved under 2026-10-14) 2026-10-14 14:33:49 +02:00
Michael Anderson ead24aded9 LR-PROF-CAMERACOLOR: Add a bundled Nikon D5300 camera profile
Fitted with lightcraft-cli calibrate to 264 of my own D5300 photos.
2026-10-14 07:32:56 -05:00
Michael Anderson 975b08c334 LR-PROF-CAMERACOLOR: Add a bundled Nikon Z 6II camera profile
Fitted with lightcraft-cli calibrate to 296 of my own Z 6II photos.
2026-10-14 07:32:56 -05:00
Michael Anderson 2bc2f60277 LR-PROF-CAMERACOLOR: Add a bundled Nikon Z 8 camera profile
Fitted with lightcraft-cli calibrate to 261 of my own Z 8 photos.
2026-10-14 07:32:56 -05:00
Michael Anderson c854e172e4 LR-PROF-CAMERACOLOR: Match the camera look against lens-corrected JPEGs
The fit compared the uncorrected raw with the corrected JPEG. It now warps the raw with the file's own lens correction when that lines up better.
2026-10-14 07:32:47 -05:00
Nathaniel LedfordandClaude Opus 5.5 540a281ccd PERF-SYNC: a Synchronize Folder scan reads off the folder's listing whether a photo and its sidecar are there
The scan asked the disk about every library photo in the folder: is its
file there, and has it a sidecar under any of four names. On a network
share each question is a round trip, and the scan had just listed the
folder. Measured on a hard disk over SMB, for unchanged folders of 1,600
to 2,400 photos: 4.6 to 7.1 s of questions after a listing of 4 to 5 s.

- The walk hands each folder's listing over (`walk::files_in_noting`:
  every entry's name and kind, hidden ones too, and whether that is all of
  them). The scan walks the folder once, then checks the photos beside
  the probing of new files.
- `sync::Listing` answers "is it there" / "is it a file" where that holds
  on any file system: a name the folder lists is there; a plain ASCII name
  is not there when the folder was listed to its end, all its names are
  ASCII and none is that name in another case. Everything else is asked
  of the disk as before (a link, a name Windows reads another way, a
  folder that was not walked, and every name not listed in a folder that
  holds a name outside ASCII).

Now under 0.05 s for those folders. Two things differ on purpose: a file
the folder lists is there though it can't be opened by its path (a folder
that may be listed but not searched, an over-long path), where such
photos were listed as missing; and the answers are the folder as the
walk saw it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 07:45:43 -04:00
Marco Arnulfo 0f398f6dba Edit panel: the histogram clipping buttons stay clear of the hovered scroll bar (fixes #1640) 2026-10-14 12:33:09 +02:00
Sergio PereaandClaude Opus 5.5 3c907e0c9d fix(export): a metadata/sharpen/conflict value that passes validation is the one exported
`ExportOptions::validate` accepted `metadata`, `sharpen`, `sharpenAmount` and
`conflict` case-insensitively, but `from_json` read them with serde's
exact-case names and silently fell back to the default when that failed.
`{"format": "jpeg", "metadata": "NONE"}` therefore passed validation and
exported with `MetadataPolicy::All`: GPS, location and camera data went out
in a file the caller asked to carry none. MCP, the control channel and the
CLI all go through `from_params`, so all were affected.

Each of the four enums gets a case-insensitive `parse` (the pattern
`HdrCurve::parse` and `JxlEffort::parse` already use), and both `validate`
and `from_json` call it, so validation and conversion can no longer
disagree. Accepted inputs, error messages, defaults and `to_json` output are
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 12:08:36 +02:00
Andrew FrahnandClaude Opus 5.5 61ec5c596c Docs: restore upstream's header notes in gaps and parity checklist
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 20:02:09 +11:00
Andrew FrahnandClaude Opus 5.5 f625c74c7a Faces: whole networks on the GPU, batched faces, CPU-only switch, paced GPU use
Activations stay on the device between layers (net/program.rs lowers the graph; every
operator is a WGSL kernel, one submission and read-back per run); faces of a photo go
in batches of up to 16; Settings > Faces shows each model's device and a CPU-only
switch (faces.gpu); the scan's pace limits GPU use; the GPU check is an activity row.
YuNet 58 -> 21 ms, SFace 40 -> 9.6 ms, AuraFace 295 -> 71 ms (heavily loaded machine).

Sources: own design.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 19:43:44 +11:00
FredAppsandCodex 2b86ca0537 LR-EXP-TYPE: omit redundant alpha from opaque 8-bit exports (#1670)
Preserve real transparency, pixels and embedded metadata. Cover RGB PNG,
TIFF compression modes and WebP, plus real-alpha round trips.

Co-authored-by: Codex <[email protected]>
2026-10-14 10:23:40 +02:00
Andrew FrahnandClaude Opus 5.5 d598c304aa Merge upstream/main into pr/zoom-detail
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 19:20:53 +11:00
Andrew FrahnandClaude Opus 5.5 e5cd0c7ada Merge upstream/main into i18n-911-dialogs-toasts
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 18:12:25 +11:00
Alex ChambersandClaude Opus 5.5 8feda7a997 LR-IMP-FORMATS: the TIFF reader's next-IFD pointer no longer overflows on huge BigTIFF entry counts
Pre-existing on main. The reader computed the position of a directory's next-IFD pointer before it
checked that every declared entry had been read: a saturating multiplication of the declared count,
then an unchecked addition. A 44-byte BigTIFF declaring u64::MAX entries therefore panicked with
overflow checks on. The position is now computed only for a directory read whole, with checked
arithmetic.

32-bit note: the same guard compared the counts after narrowing the declared one to usize, so on
wasm32 a BigTIFF declaring 4,294,967,297 entries but holding one passed for a whole directory and its
next pointer was followed. The counts now compare as 64-bit numbers (reads_every_entry). On wasm32 the
old comparison followed all six malformed test chains and the new one follows none; 64-bit results
are unchanged for every directory whose count is read whole.

Regression tests (crates/tiff/src/reader.rs):
a_bigtiff_directory_declaring_u64_max_entries_parses_without_overflow, which panicked before;
a_bigtiff_count_past_u32_max_never_follows_the_next_pointer (the whole chain, on every target); and
only_a_directory_read_whole_has_a_next_pointer (the comparison itself, on every target).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 08:40:42 +02:00
Alex ChambersandCodex c03eb8222f LR-IMP-CAMERA-COVERAGE: verify 30 public camera models
Recheck all 54 files in the 41-model shortlist on main 25ef65c8.
Pin 40 accepted files by SHA-256 and full decoded sensor FNV-1a,
and record their camera-image correlation. Exclude eleven candidate
models after checking identity, camera module, provenance and references.

Update generated coverage and tracking documents to 265 verified models.
Keep Nikon coding limits and the own-matrix DNG rendering issue explicit.

Co-Authored-By: Codex <[email protected]>
2026-10-14 08:21:44 +02:00
Alex ChambersandClaude Opus 5.5 ac677a2624 LR-EDIT-OPTICS-PROFILE: decode Sony shading, CA and distortion tables with settings and provenance; apply nothing new
Sony ARWs record shading, lateral chromatic aberration and distortion as a camera setting plus a radial
table in the raw image IFD (0x7031-0x7037), with copies in the encrypted SR2SubIFD (0x797c-0x7982).
They are now decoded for every body that records them and carried through RawInfo and RawImage as
`lens_metadata.sony` (types in crates/raw/src/lens_metadata.rs, decoder in
crates/raw/src/vendor/arw_lens.rs):

- Raw-IFD fields are the ones the TIFF reader parsed, which is what the image itself uses. A scan of
  the directory adds diagnostics only: repeated tags, and why an entry the reader skipped was dropped
  (values outside the file, an unknown type, past the reader's limits). SR2SubIFD fields are read
  from their first entry. Only the exact layouts are accepted: SHORT[1] or non-negative SSHORT[1]
  settings, SSHORT[17] headed by 16 for shading and distortion, SSHORT[33] headed by 32 for CA.
  Nothing is allocated from a count in the file.
- The raw IFD's copy wins. The SR2SubIFD copy fills in only for a tag the raw IFD lacks, never for a
  malformed one, and the two copies' agreement is recorded.
- Settings keep their number and their documented meaning, Unknown(value) otherwise (never Off).
- Framing evidence (stored frame, Sony and default crops, reference rectangle, coding, 3:2) and a
  per-component status. Only Applied components become opcodes.

Applied corrections are unchanged: the ILCE-7RM4A distortion conversion receives exactly the table it
received before, and no other body or component gains a correction. The ILCE-7CR distortion misses its
camera JPEG at 24 mm, and shading and CA semantics are not validated on any body; see
docs/sony-lens-corrections.md.

Locating the SR2SubIFD, now done for every ARW that has one, selects the SR2Private offset, length and
key with the TIFF reader's own rules, which lightcraft-tiff now exposes and builds its reader on
(directory_entries, entry_span, ParseOptions::budget_for, decode_value). Only each field's first value
is decoded, so the directory's other entries cost no memory sized by the file: a 16 MiB file whose
SR2Private holds eight fields aliasing it peaks at 37 kB. DirectoryEntries keeps its layout private,
and its positions() iterator uses checked arithmetic.

Tests: synthetic decoder tests; a differential test of the SR2Private selection against the TIFF
reader's in both byte orders (0 to 8,193 filler entries, unreadable and unusual first occurrences of
each field, a used-up value budget); a dhat peak-heap test; public-corpus checks against the values
ExifTool prints, with pinned and anchored SHA-256s (LIGHTCRAFT_CORPUS_REQUIRED=1 makes absent files
fail); and an opt-in local inventory check (crates/raw/tests/sony_lens_inventory.rs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 08:19:21 +02:00
Andrew FrahnandClaude Opus 5.5 0242a75b5a Faces: run the networks' convolutions on the GPU (wgpu) when it agrees with the CPU and is faster
An accelerator hook in the face interpreter takes Conv nodes; lightcraft-gpu implements it with a WGSL
implicit-GEMM convolution (any stride, padding, grouping; split-K for small maps; a direct kernel for depthwise
layers), each model's weights resident on a device of its own. After loading, detection and recognition check
the GPU in the background (agreement within 1e-3 and faster than the CPU) and otherwise stay on the CPU, which
remains the reference; the first GPU error drops it. Sources: own design.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 12:22:50 +11:00
Andrew FrahnandClaude Opus 5.5 80a8acaa30 Merge upstream/main into pr/zoom-detail
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 07:52:45 +11:00
Andrew FrahnandClaude Opus 5.5 ee5ae8fa1d Merge upstream/main into i18n-911-dialogs-toasts
Resolves the export dialog HDR AVIF colour-space label against upstream's PQ/HLG curve choice (now tr_format!) and three-way merges the locale catalogs.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 07:48:41 +11:00
good-news-everyoneandClaude Opus 5.5 ab64e9a563 KEY-SLIDER-SCRUB: drag a slider's value sideways to scrub it
As over Lightroom's values, a press on the number next to a slider's name
that moves sideways now changes the value as dragging the thumb would: the
pointer's travel over the track's width, a tenth as far with Shift, on the
control's steps and range, as one undo step. A press that moves less than
3 points sideways is still a click that opens the value for typing
(KEY-SLIDER-TYPE), and the pointer over the value is the horizontal-resize
cursor. The tooltip says both ("Click to type a value, drag to change it"),
translated in every catalog.

Tests: scrub distance and direction, Shift, clamping, steps, one interaction
per scrub, no field or draft left behind, a jittery click still types, a
disabled slider doesn't scrub. The readout test that drags away from the
value now drags straight down, so it still checks that a cancelled press
keeps neither a value nor the keyboard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 19:55:17 +03:00
Jason Baldwin fdad5a4ad4 LR-VIEW-FOCUSPOINT: read focus points for photos already in the library, header-only in the background (#1480)
Photos imported before focus points were read got one only through Reload from Disk, which
hashes whole files on the UI thread. Now:

- lightcraft_meta::focus::read_header reads only what the decoder looks at: IFD0 (Make,
  Model), the Exif IFD, the maker note's IFD and the focus tags' values (a JPEG: its segments
  up to the Exif one), walked round by round and decoded with the whole-file code from a
  buffer of the file's length holding just those ranges. Bounded rounds, bytes (2 MB) and
  size (1 GB). One 32 KB read per α1 / A7S III ARW; on 109 real files (83 with a point)
  it gives the whole-file read's point for every one.
- A background job (crates/engine/src/focus_scan.rs) reads photos with no point from a
  supported body (by the stored camera; nothing else is opened), ARW or JPEG, one at a
  time in path order, with a "Reading focus points" activity row (Cancel::Flag). The UI's
  per-frame focus.pump gives it the face scan's pace (paused while dragging or typing) and
  starts it once per library opening. Commits every 200 photos or 3 s as system ops (no
  undo step, no sidecar write), only meta.focus, only on photos that still have none at the
  same path. "Looked, none" goes to focus-scanned.bin beside the library, headed by the
  decoder's tag so a decoder knowing more bodies starts afresh; unreadable files are retried
  at the next opening.
- photo.readFocusPoints {ids?, wait?} (Photo > Read Focus Points) runs it on demand.

Measured cold on a 5400 rpm USB drive: 200 α1 / A7S III ARWs in 1.9 s (~100 photos/s,
32 KB each), so 58,796 raws take about 10 minutes instead of re-reading 2.25 TB.
2026-10-13 16:06:06 +02:00
Jason Baldwin ac84cd31ee LR-VIEW-FOCUSPOINT: show the camera's focus point (Sony) and zoom to it (#1480)
Read the autofocus point from Sony maker notes (FocusLocation 0x2027, FocusFrameSize
0x2037, FocusMode 0x201b, AFAreaModeSetting 0x201c, AFTracking 0x2021 and the area mode
used from the enciphered 0x9402 block), for the ILCE-1 and ILCE-7SM3, whose layout was
checked against ExifTool's output on 333 real ARWs. Manual focus, centre-only Multi
reports and unchecked bodies give no point. The box is stored on the upright photo as
Meta.focus (omitted when unknown; no catalog format change), filled at import and by
Reload from Disk.

View > Show Focus Point (Alt+F) draws it in Detail, Compare and Survey through rotation
and crop; View > Zoom to Focus Point (on by default) makes Toggle Zoom centre on it; the
Info panel shows "AF-C · Wide · Animal Eye Tracking". photo.inspect returns meta.focus.
2026-10-13 13:14:24 +02:00
dev-null-undefinedandClaude Opus 5.5 6467d54325 Perf: camera-look colour step 1.5-1.9x faster on full-size raws, same pixels
The hue/saturation table of a fitted camera look (ILCE-7RM4A, APS-C ILCE-7RM6, ...) ran
HsvTable::apply pixel by pixel: branches on the data (largest channel, hue sector),
saturating float-to-usize casts and bounds-checked table reads, ~550 instructions and 1.2
branch misses per pixel. CameraColourModel::apply now runs it 16 pixels at a time
(HueSat::apply_lanes -> HsvTable::apply_lanes, structure of arrays): per pixel the same IEEE
operations in the same order, with the branches turned into selects and the table indices
computed as exact f32 integers, so the compiler vectorises everything but the table reads,
powf and the rare rem_euclid, which run lane by lane. DNG profile tables and the other colour
models keep the per-pixel path.

Measured on a Core Ultra 9 185H P-core (busy machine, min of N):
- HsvTable alone, 72x5x5 fitted-look-shaped table, random colours, one thread:
  243 -> 106 cycles (57 -> 26 ns) per pixel.
- Colour stage of a full-size load, one thread: 60 MP ILCE-7RM4A 3.80 -> 1.99 s,
  26 MP APS-C ILCE-7RM6 HQ 1.88 -> 0.98 s; 4 CPUs: 1.02 -> 0.67 s, 0.56 -> 0.30 s.

Exactness: new tests compare the lanes with the one-by-one path bit for bit (to_bits) on tens
of thousands of colours (every combination of zero, -0, tiny, negative, around 1, huge, NaN and
+-inf components; grey; hues at the 0/360 degree wrap; near-black noise in the restore's blend)
for fitted, value-scaled, 2D, many-turn and degenerate tables, 16 and 5 lanes, and on an image
whose rows aren't a whole number of lanes. Stage fingerprints (decode, AHD, 2560 px and
full-size loads) of 7 Sony raws are identical to origin/main.

Sources: own design.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 12:03:21 +02:00
radialmonster 2dad18d2ec LR-RAW-NEF: stretch non-square pixels (D1X/D1H) to square
The D1X/D1H raw SubIFD is 4028x1324 with XResolution 600 / YResolution 300:
the pixel is twice as tall as it is wide. Nothing read that, so the
picture came out about 3:1. Add a pixel aspect to RawImage/RawInfo, read
it from the raw IFD resolution ratio (NEF) and from DefaultScale (DNG),
accept only 1.5..4, and resample the rows after demosaic. developed_size()
reports the stretched size, binning is off for non-square pixels, and the
catalog and lens-profile sizing use developed_size().
2026-10-13 06:01:40 -04:00
Claude 951d52788a LR-MERGE-HDR: pixels next to clipped ones don't tint HDR merges
Measured against the darkest frame on real ARW brackets, each frame is linear to 1 % up to the clip far from
clipped pixels, but within 2 px of them the +2 EV frame's green reads 3–5 % low: demosaicing interpolates it from
clipped photosites. That frame carries the most weight (k = 4) and those pixels were unclipped themselves, so they
kept it, and bright windows took a magenta tinge.

A frame's weight now goes by its brightest channel within 1 px (3 × 3; wider margins changed nothing more). On two
real interior brackets (ILCE-7M3, 0 / −2 / +2 EV), bright pixels whose green against red and blue is over 10 % below
the darkest frame's, in camera RGB: dining room 0.32 % → 0.08 %, kitchen 2.86 % → 0.28 %. Rendered at −3 EV with
main's colour tags (#1123), window pixels with G < 0.85·min(R, B) go 50 → 3 and 16 → 10 (the darkest frame alone:
2 and 205); most of the visible magenta those brackets showed before came from the missing colour tags. Test: a
bracket whose +2 EV frame has 5 % less green next to its clipped pixels merges without the deficit (fails before:
−1.96 %).

Docs: docs/merge.md, the LR-MERGE-HDR row, docs/whats-new.md (also for the frame-order fix).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015gRtdWF1E9358FfzhzYqCS
2026-10-13 09:51:11 +00:00
eliets2 0cd7513a8d LR-MERGE-HDR: an HDR merge of raws keeps the as-shot white balance of its inputs (#1144)
The HDR merge has the same cause as the panorama: its result took the
reference frame's colour tags, and a raw whose white balance is only in the
vendor's multipliers (CR2, NEF, ARW...) has no AsShotNeutral in them.

merge_hdr now takes the median multipliers of all its inputs (the rule of
consensus_multipliers: the mean of the middle two for an even count; missing,
non-finite and non-positive values do not vote) and sets the result's
AsShotNeutral to their reciprocal, as stitch does. With no multipliers (DNG
sources) the reference frame's tags are kept, as before. HdrResult carries the
multipliers so that the brackets of an HDR panorama vote as frames of their own
when the merged brackets are stitched (the engine passes them on).

In the app and the CLI the neutral from starting_colour_tags (#965) is already
there for frames balanced alike, so those renders do not change.

Tests: an HDR merge of raw-style frames gets the median AsShotNeutral (odd and
even counts, missing and unusable multipliers ignored) and the written DNG says
it; without multipliers the reference frame's colour is unchanged.
2026-10-13 12:23:36 +03:00
eliets2 25314aaacf LR-MERGE-PANO: a panorama of raws keeps the as-shot white balance of its frames (#1144)
A raw whose white balance is only in the vendor's multipliers (CR2, NEF, ARW...)
has no AsShotNeutral of its own. Loading a frame dropped the multipliers and
stitch copied the first frame's colour tags, so a panorama of frames that reach
the stitcher without a neutral wrote a DNG with neither AsShotNeutral nor
AsShotWhiteXY, and a viewer had no white to start from (a strong colour cast
until White Balance > Auto).

Frames now carry the multipliers (Frame::wb_multipliers, filled from the decoded
raw; load_frame_with is split so a decoded raw can be tested without a file).
stitch takes the median R/G and B/G of the multipliers of the frames that are in
the panorama (the mean of the middle two for an even count; frames without
multipliers, or with non-finite or non-positive ones, do not vote) and sets the
result's AsShotNeutral to their reciprocal, green = 1. The source's
AsShotWhiteXY is dropped with it: a reader takes it before the neutral and the
DNG spec makes the two exclusive. With no multipliers anywhere (DNG sources) the
first frame's tags are kept, as before.

In the app and the CLI a raw without colour matrices already gets a neutral from
starting_colour_tags (#965). For frames balanced alike the new neutral renders
the same (checked in the engine crate); it differs when the camera balanced the
frames differently: the panorama follows the median instead of the first frame.

Tests: the frame carries the multipliers; the consensus for odd and even counts,
with missing and unusable values; stitching raw-style frames gives the median
AsShotNeutral, ignores frames outside the panorama and leaves the colour as it
was without multipliers; the written DNG, read back with the raw reader, has the
reciprocal AsShotNeutral and the white balance the source's multipliers give.
2026-10-13 12:23:36 +03:00
cookingwithsimonandClaude Opus 5.5 d9cea1404a LR-IMP-PROFILES: presets apply the imported profile they name (#1001)
A Lightroom preset's crs:Look (name, group, UUID, amount; the Look table
in .lrtemplate files) is kept as profile.look and resolved against the
user's imported profiles by name, the group breaking ties. Lightroom's six
basic profiles map to ours; its own creative/camera profiles and profiles
not imported yet are reported per preset. References are resolved again
after profile.import / profile.deleteImported, so profiles and presets can
be imported in either order.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FxP2xEy623xzWGqCWXVwtb
2026-10-13 09:08:53 +00:00
dev-null-undefinedandClaude bc1f138ee3 Perf: ARW6 decode another 20-34 % faster, same samples
- The two halves of each stream are independent bit streams: they now decode in parallel
  (`decode_stream`) instead of one after the other inside each of a tile's 13 streams.
- The vertical inverse 5/3 runs its rows in parallel. The horizontal pass lifts each row in place
  (`lift_row`, scratch space reused per thread), rows in parallel, instead of allocating two vectors
  per row and copying the result back; a test checks it against the vertical pass, row by row.

Best of 3 on 4 CPUs, previous and new decoder alternating: ILCE-7RM6 FF HQ 0.60 → 0.48 s
(process CPU 1.14 → 0.87 s), FF Compressed 0.62 → 0.48 s, APS-C HQ 0.34 → 0.23 s, APS-C
Compressed 0.31 → 0.24 s (docs/arw6-compression.md → Timings). The decoded mosaic is identical
(hash of every sample) on the 8 ARW6 files of the RawDB ILCE-7RM6 set and 3 private A7R VI photos.

Co-Authored-By: Claude <[email protected]>
2026-10-13 10:00:33 +02:00
dev-null-undefinedandClaude Opus 5.5 79ab54e167 Perf: ARW6 decode 20-33 % faster, same samples
- The vertical inverse 5/3 lifts whole rows at once (`inverse_lift` with samples `w` values wide)
  instead of gathering each column through a strided iterator and scattering it back: the same
  integer arithmetic, sequential memory. The horizontal pass is the same function with w = 1.
- `0^n 1` codes are counted with one `leading_zeros` over the next MAX_DPT + 1 bits instead of bit by
  bit (same bits consumed, same errors); each line reserves its values up front.
- Colour reconstruction reads plane rows as slices and runs over rows in parallel (it was one
  thread per tile: 4 threads on a full-frame file whatever the machine).

Best of 5 on 4 CPUs, previous and new decoder alternating: ILCE-7RM6 FF HQ 0.56 → 0.46 s,
FF Compressed 0.54 → 0.38 s, APS-C HQ 0.34 → 0.23 s, APS-C Compressed 0.35 → 0.24 s
(docs/arw6-compression.md → Timings). The decoded mosaic is identical (hash of every sample) on
the 8 ARW6 corpus files and 2 private full-frame photos (ISO 100, ISO 12800); the pinned corpus
sums still match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 10:00:33 +02:00
dev-null-undefinedandClaude Opus 5.5 f407813569 Perf: AHD demosaic 1.7× faster and 0.8 GB lighter on a 64 MP raw, same pixels
Three changes, each leaving the output bit for bit as it was:
- Each step runs only where the tile's output depends on it (choice ±0, homogeneity ±1, Lab ±2,
  greens ±3, mosaic ±5 inside the 6 px margin), with direct neighbour indices instead of an
  index clamped on every read; the clamped values at the buffer edge never reached the output.
- A candidate pixel is built in registers before its Lab conversion: writing its channels
  through an index and reading the pixel back stalled on store forwarding (the hottest
  instructions of the profile).
- Tiles are written into the output one band at a time, instead of all 64 MP of tiles being
  collected and then copied (797 MB held twice). Tiles inside the image copy their mosaic rows
  instead of reflecting and taking a modulo per sample.

Sony ILCE-7RM6 9984 × 6656 Compressed HQ raw, demosaic only, best of 5 on 4 cores:
1.85 s → 1.05 s wall, 6.3 s → 4.0 s CPU. Verified identical (f32 bits) on 7 real raws
(ILCE-7RM6 FF/APS-C, ARW6 HQ/C and lossless, ILCE-7RM4A) and, against the previous code, on
random mosaics of all four Bayer layouts at 1 × 1 … 300 × 7, 257 × 130 (tile edges, reflection).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 10:00:33 +02:00
dev-null-undefinedandClaude Opus 5.5 5f2f013c8e Perf: a full-size raw decode no longer copies its 64 MP image to "fit" it
`load_bytes_now` ran every development through `resample::fit`, which returns a clone when the
image already fits. At full size (1:1 zoom, export) that cloned the whole picture: 797 MB and
~0.3 s for a 9984 × 6656 Sony ILCE-7RM6 raw. It now fits only when the image is larger, as the
other preview paths in files.rs already do. Output unchanged (same pixels, by construction).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 10:00:12 +02:00
Atmik Shetty cb8b797cd4 KEY-SLIDER-RESET: a slider's name and thumb say a double-click resets it (fixes #1436)
A double-click on a slider's name or thumb already reset it, but nothing said so: only the value had a
tooltip. Resting the pointer on the name or on the thumb now shows "Exposure — double-click to reset
it", the wording (and translations) the curve channels already use. The rest of the track, which is
clicked and dragged, gets no tooltip, and the value keeps "Click to type a value".

The first click of a double-click on the thumb moved the value to where the pointer landed, a few
points off its centre: one history step, then the reset another. A click on the thumb now leaves the
value alone, so the reset is one undo step, as from the name. A disabled slider's name no longer
resets it.

No per-slider reset button: Lightroom has none, and the double-click it documents is now shown where
it works. Tests: tests_slider_reset.rs (name and thumb reset Exposure and Contrast in one undo step,
the hints, a click on the thumb keeps the value, typing a value still works) and
widgets/tests_slider_reset.rs (a disabled slider's name).
2026-10-13 13:16:08 +05:30
Atmik Shetty 63f68f5044 Merge remote-tracking branch 'upstream/main' into feat/print-color
# Conflicts:
#	crates/engine/src/lib.rs
2026-10-13 12:08:59 +05:30
Atmik Shetty 6e5cd82ce7 Merge remote-tracking branch 'upstream/main' into feat/print-color
# Conflicts:
#	docs/gaps.md
#	docs/parity-checklist.md
2026-10-13 12:00:45 +05:30
Claude 146cb7b975 LR-MERGE-HDR: the merge no longer depends on the order the frames come in
The same bracket merged in another order gave a different result: on real ARW brackets, the app's selection
order and the CLI's file order differed on 0.6 % of the pixels (up to 102 levels), while the same order gave
byte-identical files. Alignment seeds were the frames' input positions, and sums, deghost masks and brightness
ties followed them too.

merge_hdr now puts the frames in brightness order first (ties by median, then a content fingerprint, never by
position), runs everything in that order, and returns the per-frame results (EV, alignment, reference index)
in the caller's order. Test: every permutation of a bracket gives the same radiance and deghost overlay bit for
bit, and the same per-frame results (fails before: "the radiance differs").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015gRtdWF1E9358FfzhzYqCS
2026-10-13 05:57:13 +00:00
radialmonster 0391362f2f Format the DNG tone fit with rustfmt 2026-10-12 12:48:47 -04:00
radialmonster f89b70e1c1 Tone-only DNG fit: train on dark pixels, compare highlights with the camera preview too 2026-10-12 12:37:45 -04:00
radialmonster 1a5c4665da Fit a DNG's tone to its embedded preview when the file defines none
For a DNG with its own colour matrix, an identity or absent ProfileToneCurve, no
LookTable and no ProfileGainTableMap, fit only the tone and chroma curves to the
camera JPEG, with the file's colour model untouched (profile tables and embedded
vignetting applied to the sensor proxy as the loader renders it). The fit is used
only when the preview is at least 90% of the raw's long edge, shows the same
picture (structure gate), passes the existing held-out acceptance, and does not
put more of the photo near white than the plain render (highlight gate, at 2x
proxy luminance). Otherwise the render is unchanged. Other formats and
catalogued photos are untouched. Render cache version 62.
2026-10-12 12:37:45 -04:00
Andrew FrahnandClaude Opus 5.5 6a5158d4ed i18n: translate dialog notes, toasts and tooltips (Contact Sheet, HDR export, slideshow, auto advance, import tokens)
Refs #911

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-13 03:01:31 +11:00
Atmik Shetty 64e0395c95 LRC-PRINT-JOB: Print Job colour controls in the Print dialog
The Print dialog's Print Job panel, under Resolution:

- Profile: Managed by Printer (sRGB), Managed by Printer (Adobe RGB), or Other… to pick a printer /
  paper .icc / .icm with the colour-profile file picker the soft proof uses; the picked profile's
  name is shown.
- Intent: Perceptual / Relative; Black Point Compensation (enabled for Relative).
- Print Adjustment: Brightness and Contrast, -100..100.
- Sharpening: Off / Low / Standard / High; Media: Matte / Glossy (enabled while sharpening is on).
- 16 bits per channel.
- A summary line: PDF, profile, depth, current edits.

Each control sends print.set {job: {color}}, so the dialog, CLI, control channel, MCP and print
templates share the settings. UI test: every control reaches the job (the Print Job panel is
scrolled into view first, as a person would), Other… picks a profile from the picker, and the PDF
printed with it carries the output intent at 8 bits.
2026-10-12 15:40:04 +05:30
Atmik Shetty 5cbaf64579 LRC-PRINT-GUIDES: the Print preview stops re-rendering thumbnails every frame
A thumbnail is kept at one size. The page preview asked for each cell's photo at the cell's size
on every frame, and the library grid behind the dialog asked for its own size, so the two replaced
each other's request: while the Print dialog was open a thumbnail render was always in flight and
about two render jobs were rebuilt per frame, keeping a core busy. The preview now uses the
photo's thumbnail when there is one and asks for one only when there is none.

Regression test: with the dialog open in Contact Sheet, Picture Package (the same photo in cells of
different sizes) and Single Image, the dialog settles, no render is in flight and no thumbnail job
is rebuilt over 60 idle frames. Before the fix the job count rose by about 100 every 50 frames.
The Print dialog's UI tests now finish in seconds (they were waiting out each settle timeout).
2026-10-12 15:39:08 +05:30
Atmik Shetty 65775b4716 LRC-PRINT-JOB: colour-managed print PDFs (printer profiles, intent, black point compensation, print adjustment, print sharpening)
print.exportPdf now converts each composed page to the job's colour target and writes it into a
print-ready PDF:

- PrintJob gains `color` (PrintColorSettings): Managed by Printer (sRGB / Adobe RGB, profile
  embedded, no output intent) or a printer / paper .icc / .icm converted here and named as the
  document's output intent; perceptual or relative colorimetric with black point compensation;
  Print Adjustment brightness / contrast; print sharpening Low / Standard / High for Matte or
  Glossy; 16 or 8 bits per component. print.set / print.get and print templates carry it;
  out-of-range values are refused when set.
- Each photo is sharpened for the paper right after it renders at its print size.
- print/output.rs converts and Flate-compresses one page at a time (memory holds one page's device
  samples) into ICC-tagged images through engine::pdf; the PDF is 1.6. The 256 MiB cap counts the
  compressed pages.
- A printer profile that can't be used (missing, too large, not a profile) fails the print before
  anything renders, naming the file.
- contact_sheet's PDF writer goes back to private: only the contact sheet uses it.

Tests: a printer profile reaches the PDF as ICCBased images plus an output intent, a junk profile
fails naming the file, colour settings validate with the job, sharpening and media round-trip
through print.set / print.get, a missing profile fails before rendering with no activity row;
the existing print and CLI tests follow the PDF 1.6 output. Docs: LRC-PRINT-JOB and gap 15.
2026-10-12 15:16:32 +05:30
Atmik Shetty 9bc76a4e58 LRC-PRINT-JOB: print job colour settings: profile, intent, print adjustment, print sharpening, depth
engine::print_color turns composed pages into a print-ready PDF:

- Profile: Managed by Printer sends the page in sRGB or Adobe RGB with that profile embedded and
  no output intent (the driver converts); a printer / paper .icc / .icm converts the page to the
  device's values here and becomes the document's output intent (named by the profile's
  description), so the driver must not convert again. Profiles over the size cap, unreadable or
  invalid files are errors that name the file.
- Intent (perceptual / relative colorimetric), black point compensation and print adjustment
  brightness / contrast, through codecs::print.
- Print sharpening Off / Low / Standard / High for Matte or Glossy paper, per photo at its print
  size, with the export sharpener.
- 16 bits per component by default, 8 for smaller files.

PrintColorSettings is serde (camelCase, defaults for missing fields) so print templates can save
it. Page sizes are checked with overflow-safe arithmetic. Not wired to the print layout yet.
2026-10-12 15:15:57 +05:30
Atmik Shetty d289fafbe2 LRC-PRINT-JOB: PDF writer for print output (ICC-tagged 8 / 16-bit images, output intent)
engine::pdf writes print-ready documents: pages of any size in points with raster images placed
on them, each image tagged with its ICC profile as an ICCBased colour space (RGB, CMYK or grey),
stored losslessly with Flate at 8 or 16 bits per component (16-bit samples big-endian), or copied
as a JPEG stream where file size matters more. A profile shared by several images is written once.
An optional output intent names the printer / paper profile the file was made for (PDF/X-style
/OutputIntents in the catalog); the Info dictionary carries the title, as UTF-16 when it isn't
plain ASCII.

PDF 1.6 (16-bit images need 1.5), classic cross-reference table, deterministic bytes. Pages, images
per page, page and image sizes are capped; bad sizes, placements, sample counts and component
counts are errors, never panics. Tests read the files back through the xref table: image samples
and profiles inflate to what went in, placements reach the content streams, one profile object is
shared. Not wired to the print job yet.
2026-10-12 15:15:57 +05:30
Atmik Shetty 068caf361c LRC-PRINT-JOB: print colour transform (printer / paper profiles, intent, black point compensation, print adjustment)
codecs::print converts a composed print page (16-bit RGB in the Rec2020 output encoding) to the
samples a print-ready file carries:

- PrintTarget::Profile(icc): a printer / paper profile, RGB, CMYK or grey, matrix or LUT based,
  converted with moxcms; PrintTarget::Managed(space): the printer manages colour and the page goes
  in sRGB or Adobe RGB with that profile embedded.
- Perceptual or relative colorimetric (ProofIntent, as soft proofing).
- Black point compensation for relative colorimetric: the device's darkest is measured by a round
  trip of black through the profile and linear values are scaled to land the page's black there
  (Y' = Y(1 - Yb) + Yb, the published mapping for a neutral destination black), so shadows below
  the ink's black no longer clip to one value. Perceptual tables keep their own black mapping.
- Print adjustment brightness / contrast (-100..100) on the sRGB-encoded values, black and white
  held, monotonic at every setting.

Everything before the profile is per channel and folds into one 16-bit table; pages convert in
bounded batches (parallel with the `parallel` feature). Hostile profiles, half pixels and NaN
settings are errors or neutral, never panics. Not wired to the print job yet.
2026-10-12 15:15:57 +05:30
Atmik Shetty 32b5aefc5b LRC-PRINT-GUIDES: the Print dialog (File → Print…) with page preview, rulers, guides and cell editing
File → Print… (⌘P) opens the Print module as a dialog: settings on the left,
the page drawn to scale on the right with the photos as they will print (fit
or Zoom to Fill, turned by Rotate to Fit, Photo Border, Inner Stroke, page
background).

Settings column: templates (save, apply, delete), layout style, image
settings, grid / package cell controls (standard and custom cell sizes, Auto
Layout, New Page, Clear Layout), rulers and guides (units in/cm/mm/pt, snap
off/cells/grid, grid size, margins, bleed, page grid, image cells,
dimensions), page setup (paper, orientation, margins), page background and
the print job.

Preview: rulers in the chosen unit, dashed margins and bleed, page grid,
dimension labels, page navigation. In the package styles cells are selected,
dragged (print.cell.move) and resized from a corner handle
(print.cell.resize) with the guides' snapping, arranged from the inspector
row or a context menu, and given a photo (Custom Package). Every change is a
print.* command; the drag is measured from where the pointer went down so
the click-versus-drag slop is not lost.

Print to PDF… picks a file and renders on a background thread with an
activity-stack row, cancellation and original protection, like the contact
sheet, which keeps working unchanged.

Headless tests drive the dialog with real pointer input through the control
channel (print:cell:N, print:resize:N, button:print*): styles and checkboxes,
add / drag / resize / arrange / delete, snapping to a neighbour, Auto Layout
and pages, templates, the PDF, the activity row, and that the dialog and its
buttons fit the window.
2026-10-12 15:15:33 +05:30
Atmik Shetty 3b32f82e9e LRC-PRINT-LAYOUTSTYLE: print.* commands for the layout styles, cells, templates and PDF
The Print module's state lives in the session (Session::print), so the app,
CLI, control channel and MCP share one print: layout style (Single Image,
Contact Sheet, Picture Package, Custom Package), page setup, grid, image
settings, page background, guides and job. 18 commands, none journaled
(nothing here touches the catalog):

  print.get / set / reset      set merges a partial patch, validates the whole
                               result and changes nothing on error; a new
                               paper or margin pulls cells back inside
  print.cell.add|move|resize|delete|stack|photo|page
  print.layout.autoLayout|newPage|clear
  print.exportPdf {path, ids?} composes and writes the PDF with an activity
                               row, refuses to replace an original
  print.template.list|save|apply|delete

Templates keep layout, image settings, page and job (not the photos assigned
to cells, not the guides) and are saved in the library's prefs.json next to
the export presets. They are stored as JSON and checked when applied, so a
template from another version or a hostile one is an error on use and never
makes the preferences file unreadable.

Tests drive every command through the dispatcher (hostile numbers, unknown
keys, caps, persistence across reopening a library) and a CLI end-to-end test
chains set / add cells / Auto Layout / PDF in one run.
2026-10-12 14:35:03 +05:30
Atmik Shetty 8336f06d28 LRC-PRINT-IMAGESETTINGS: compose print pages (fit / Zoom to Fill, Rotate to Fit, border, stroke, background)
print/compose.rs turns a layout and its photos into PageRasters: 16-bit
interleaved RGB encoded in Rec. 2020 at the job's pixel density. Each cell's
photo is rendered with the export pipeline at exactly the size the cell needs,
then fitted (whole photo, centred) or zoomed to fill (centre crop), turned a
quarter clockwise when Rotate to Fit makes it print larger (or crop less),
framed by the Photo Border (package styles only) and finished with the Inner
Stroke drawn inside the photo edge. The page background, border and stroke
colours are given in sRGB and converted to the page encoding.

Photos go to cells by layout style: Single Image and Contact Sheet paginate
the selection, Picture Package repeats the first photo, Custom Package prints
each cell's own photo. The job is prepared on the session and run off it with
progress and cancellation, like the contact sheet; page and job pixel counts
and page counts are capped so a hostile resolution or paper cannot exhaust
memory.

print/output.rs holds the interim PDF writer (Rec. 2020 to 8-bit sRGB JPEG
pages sized to the paper in points) through the contact sheet's Pdf, now
pub(crate). PrintJob carries the print resolution (72 to 720 ppi, 240 default).

Tests draw on synthetic images for exact pixels (borders, strokes, crop,
rotation direction, resampling) and on the demo library for whole pages.
2026-10-12 14:28:40 +05:30
Atmik Shetty 4f1ed6df65 LRC-PRINT-LAYOUT: the print layout model (paper, margins, grid, package cells, packer, snapping)
crates/engine/src/print/layout.rs is the pure page model the Print module
builds on: ten named papers plus custom, orientation, margins and the
printable area; Single Image, Contact Sheet (grid with spacing and square
cells), Picture Package and Custom Package styles; package cells with a
stacking order (send to back / backward / forward / bring to front); a
deterministic MaxRects packer behind Auto Layout (largest first, earlier
pages filled before a new one opens, a cell turned a quarter only when it
fits nowhere as given); snap-to-cells and snap-to-grid helpers; ruler units
and guide options.

All lengths are inches in page space, after orientation. Every number from
outside is checked (NaN, infinity, negative, oversized, cell and page caps)
and Layout::validate guards saved layouts.

No command or UI reaches it yet, so the parity rows keep their status.
2026-10-12 14:21:42 +05:30
GabrielePecchioliandClaude Opus 5.5 aec225b6ac Add Italian interface translation (#1192)
Italian (`it`) catalogs: 1,992 interface messages and all 246 format strings
(2,201 of 2,398 messages; What's New left in English like most languages).
410 labels reuse the PhotoCraft, VectorCraft, PdfCraft and WordCraft Italian
catalogs where the meaning fits a photo app; 46 were retranslated.

Counts follow a label ("Foto importate: 3") because Italian adjectives agree
with the number; the English plural suffix is consumed with {:.0}.

Language table entry, menu command, three tests mirroring Ukrainian's, the
button-fit test extended to Italian, and the Settings language buttons now
wrap so an eleventh language doesn't widen the dialog past a short window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 10:45:26 +02:00
Chad ElliottandClaude Opus 5.5 d79dad9ab1 docs(gaps): #1136 gap 26 notes indexed stack and album lookups at 100k
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:48:16 -05:00
Chad ElliottandClaude Opus 5.5 39c33a99d6 perf(ui): #1136 dialogs count once per library change, not every frame
Create Smart Album ran a full query for its count and Rename Keyword
scanned every photo on each frame the dialog was open; Merge Keywords
recomputed suggestions. They use Caches::dialog_count (keyed by catalog
revision and what is counted, and the minute for relative-date rules) and
the cached suggestions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:48:16 -05:00
Chad ElliottandClaude Opus 5.5 3f3ffa541a perf(engine): #1136 album order and album commands without per-photo scans
A manual album shown in its own order sorted with position() per photo
(O(n^2): 2.0 s for 20k photos, now 18 ms). album.addPhotos, removePhotos
and toggleTarget test membership with sets. The 100k scale test measures
all three.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:48:16 -05:00
Chad ElliottandClaude Opus 5.5 615d8a365e perf(catalog): #1136 index stacks and album membership, sort keys once per photo
stack_of, validate_stack and regular-album membership looked a photo up by
scanning every stack or the album's list, so an "In a Stack" or "Album"
smart album, or a query filtered to an album, cost photos x list length
(2.7 s and 0.6-0.8 s at 100k photos). Derived indexes (never saved) answer
them now: built on first use, kept current by the six ops that change
stacks or album photos in apply_inner, so undo, failed-batch rollback and
journal replay follow. A file with a photo in two stacks falls back to the
scan.

query() works out each sort key once (File Name was lower-cased twice per
comparison) and tests `only` as a set; smart-album passes prepare the
filter once; rules name flag, label and kind without formatting per photo.

A property test checks the indexes against a scan through random op
sequences, rollbacks, snapshots, replay, clones and undo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:48:16 -05:00
Chad ElliottandClaude Opus 5.5 dbf2dcbfbd docs: #1037 visible skips and the ci report
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:33:54 -05:00
Chad ElliottandClaude Opus 5.5 82045f4d2c feat(xtask): #1037 ci reports the machine, GPU adapters and skipped tests
`cargo xtask ci` points each test step at target/ci/skips-<step>.jsonl,
then probes the machine: OS, CPUs, RAM, toolchain, corpus and craft-fonts,
and the GPU through the ignored `gpu_probe` test of lightcraft-gpu (run
right after the workspace tests with --workspace, so it reuses their build;
xtask stays without wgpu). The run ends with the skips grouped by need and
reason and writes target/ci/report.json (schema 1: commit, dirty flag,
machine, capabilities, step results and times, skips) and
target/ci/summary.md for a PR (`--summary-md` prints it). `--hardware`
also runs the lightcraft-gpu tests once per backend that has a hardware
adapter. Nothing is uploaded; reasons are cut free of the workspace root
and home directory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:33:54 -05:00
Chad ElliottandClaude Opus 5.5 3e42f2e05c feat(testkit): #1037 tests record why they skip
libtest has no skipped status and hides the output of passing tests, so a
test that returns early without a GPU, a corpus file, a craft-fonts face or
a model passed silently. `lightcraft-testkit` (the testkit slot the layering
table already reserves, dev-dependency only, std only) adds
`skip!(Need, "reason")`: it prints the note as before and, when
LIGHTCRAFT_SKIP_LOG names a file, appends one JSON line (need, reason, test,
binary, file:line). Plain `cargo test` is unchanged. The 61 existing skip
sites use it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:33:54 -05:00
Andrew FrahnandClaude Opus 5.5 c78b457c0d LR-VIEW-ZOOM: soft proofing at 1:1 renders a zoom window; 1:1 pixels tested equal to export
Soft proof is per-pixel, so the After window carries the proof like the
whole-frame render under it (the proof key is part of the tile's look).
New tests: a 1:1 window of a 24 MP photo equals the full-size export to
within one level; soft proofing at 1:1 is a canvas-sized frame plus a
native window. profile_slider_drag gains a soft-proof case. Gap 4 closed,
checklist row to done with measured Linux latencies.

Sources: own design.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-12 03:37:35 +11:00
Andrew FrahnandClaude Opus 5.5 76f12dcabd Issue #989: fill_box reads its buffer with as_chunks::<3>() (clippy 1.99)
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-12 03:37:35 +11:00
327 changed files with 36858 additions and 1983 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
reviews:
auto_review:
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
ignore_usernames:
- "dependabot[bot]"
+30
View File
@@ -0,0 +1,30 @@
version: 2
updates:
# Maintain Rust / Cargo dependencies
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
# Consolidate updates into a single PR rather than one PR per crate
groups:
cargo-dependencies:
patterns:
- "*"
commit-message:
prefix: "chore(deps)"
# Maintain GitHub Actions workflows
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
groups:
actions:
patterns:
- "*"
commit-message:
prefix: "ci(deps)"
+19 -38
View File
@@ -1,16 +1,23 @@
# Builds and tests the workspace on FreeBSD, inside a FreeBSD VM on a Linux runner
# (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter.
# FreeBSD build and package check in a QEMU VM.
name: FreeBSD
on:
push:
branches: [main]
pull_request:
paths:
- Cargo.toml
- Cargo.lock
- "**/Cargo.toml"
- .github/workflows/freebsd.yml
- ".github/workflows/freebsd.yml"
- "packaging/freebsd/**"
- "Cargo.toml"
- "Cargo.lock"
- "crates/**"
pull_request:
branches: [main]
paths:
- ".github/workflows/freebsd.yml"
- "packaging/freebsd/**"
- "Cargo.toml"
- "Cargo.lock"
- "crates/**"
workflow_dispatch:
concurrency:
@@ -22,34 +29,8 @@ permissions:
jobs:
freebsd:
name: FreeBSD 14 (build + test)
runs-on: ubuntu-latest
timeout-minutes: 300
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Optional font build input, so the Japanese font tests run (they skip without it).
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
path: craft-fonts
- name: Build and test in a FreeBSD VM
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1.5.9
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Nothing to bring back; copying the target dir out of the VM fails on large builds.
copyback: false
prepare: |
pkg install -y git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2 alsa-lib
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
run: |
. "$HOME/.cargo/env"
# The checkout is synced in under another owner; let tests that call git read it.
git config --global --add safe.directory "*"
rustc --version
export CRAFT_FONTS_DIR="$PWD/craft-fonts" CRAFT_FONTS_REQUIRED=1
CARGO_PROFILE_DEV_DEBUG=0 cargo build --workspace --all-targets --locked
CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
require-craft-fonts: true
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
+6 -62
View File
@@ -1,7 +1,5 @@
# Quick checks for the release pipeline (no Rust build): workflow syntax, packaging
# shell/PowerShell scripts, and the Linux desktop/AppStream/Flatpak metadata (seconds), plus a
# Windows job that builds and installs throwaway per-user MSI probes for the install-folder
# searches (a few minutes).
# Quick static checks for the release pipeline (seconds, no Rust build): workflow syntax,
# packaging shell/PowerShell scripts, and the Linux desktop/AppStream/Flatpak metadata.
name: Packaging lint
on:
@@ -21,64 +19,10 @@ concurrency:
jobs:
lint:
timeout-minutes: 15
runs-on: ubuntu-latest
env:
ACTIONLINT_VERSION: 1.7.12
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends shellcheck desktop-file-utils appstream libxml2-utils python3-yaml
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz -C "$RUNNER_TEMP" actionlint
- name: actionlint
run: |
"$RUNNER_TEMP/actionlint" -color
- name: shellcheck
run: shellcheck packaging/*.sh packaging/*/*.sh
- name: PowerShell
shell: pwsh
run: |
foreach ($f in Get-ChildItem packaging/windows/*.ps1) {
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) | Out-Null
if ($errors) { $errors | ForEach-Object { Write-Output "::error file=$($f.Name)::$_" }; exit 1 }
Write-Output "ok $($f.Name)"
}
- name: XML, desktop entry, AppStream, Flatpak manifest
run: |
xmllint --noout packaging/windows/lightcraft.wxs packaging/macos/*.plist* packaging/linux/*.xml*
# Windows Installer needs Icon ids ending in .ico or .exe, or shortcuts show a blank icon.
if grep -oE '<Icon Id="[^"]*"' packaging/windows/lightcraft.wxs | grep -vE '\.(ico|exe)"$'; then
echo "::error::Icon Id must end in .ico or .exe"; exit 1
fi
# The interactive installer asks where to install and ends on a completion page (issues #18, #399).
for want in '<UIRef Id="LightcraftUI" />' 'Value="InstallDirDlg"' '<Property Id="WIXUI_INSTALLDIR" Value="INSTALLFOLDER" />' \
'Key="Software\LightCraft" Name="InstallFolder"' 'Value="LaunchLightcraft"'; do
grep -qF "$want" packaging/windows/lightcraft.wxs || { echo "::error::lightcraft.wxs lost: $want"; exit 1; }
done
# The completion page the Publish events point at must actually exist: a Publish alone
# does not pull the dialog fragment into the MSI, and without the DialogRef the
# installer finishes silently (issues #790, #892).
grep -qF '<DialogRef Id="ExitDialog" />' packaging/windows/lightcraft.wxs \
|| { echo "::error::ExitDialog is not referenced; installs and removes end without a completion dialog"; exit 1; }
desktop-file-validate packaging/linux/ai.storyteller.lightcraft.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.lightcraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.lightcraft.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.lightcraft.metainfo.xml"
python3 - <<'EOF'
import yaml
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.lightcraft.yml"))
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.lightcraft.bundle.yml"))
for m in (src, bundle):
assert m["id"] == "ai.storyteller.lightcraft" and m["command"] == "lightcraft", m["id"]
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
print("Flatpak manifests ok")
EOF
- name: FreeBSD tarball layout (stub binaries)
run: bash packaging/freebsd/package.sh --dry-run
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
with:
extra-checks-script: packaging/check-app-specific.sh
windows-install-folder:
runs-on: windows-latest
+25 -479
View File
@@ -1,13 +1,5 @@
# Release pipeline: every push to `release` builds platform artifacts (signed where credentials
# are configured) and creates or updates the draft GitHub Release "LightCraft v<version>".
# See docs/releasing.md.
#
# The signing jobs (macOS, Windows) and the draft-release job run in the `release` environment
# (restricted to the `release` branch), which holds the signing secrets. Every secret is optional:
# missing ones produce unsigned artifacts and a warning, never a failed build. The jobs that sign
# nothing (version, Linux, Linux riscv64, Flatpak, FreeBSD, web) run without it, so a dispatch on
# any branch is a dry run of them; the release job needs the signed jobs, so a branch run never
# drafts a release.
# Release pipeline: every push to `release` builds signed installers for every platform and
# creates or updates the draft GitHub Release "LightCraft v<version>". See docs/releasing.md.
name: Release
on:
@@ -21,479 +13,33 @@ on:
default: ""
permissions:
contents: read
contents: write
concurrency:
group: release-${{ github.ref }}
# Never cancel a run mid-notarization or mid-upload; a newer push waits its turn.
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
LIGHTCRAFT_BUILD_SHA: ${{ github.sha }}
INPUT_VERSION: ${{ inputs.version }}
jobs:
version:
timeout-minutes: 10
name: version
runs-on: ubuntu-latest
# No `environment: release` here or on the other jobs that sign nothing: no release secrets.
outputs:
version: ${{ steps.v.outputs.version }}
date: ${{ steps.v.outputs.date }}
prerelease: ${{ steps.v.outputs.prerelease }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- id: v
name: Resolve version
run: |
. packaging/env.sh
v="${INPUT_VERSION#v}"
v="${v:-$VERSION}"
if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1"
exit 1
fi
case "$v" in *-*) pre=true ;; *) pre=false ;; esac
{
echo "version=$v"
echo "date=$(date -u +%Y-%m-%d)"
echo "prerelease=$pre"
} >>"$GITHUB_OUTPUT"
echo "### LightCraft v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
macos:
timeout-minutes: 90
name: macOS universal
needs: version
runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend)
environment: release
env:
LIGHTCRAFT_VERSION: ${{ needs.version.outputs.version }}
LIGHTCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Fonts (optional build input; required for releases): see craftrules standards/fonts.md.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 # bump deliberately
path: craft-fonts
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: aarch64-apple-darwin, x86_64-apple-darwin
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-macos-universal
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$LIGHTCRAFT_VERSION"
- name: Import signing certificate
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: packaging/macos/import-cert.sh
- name: Build, sign, notarize
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: packaging/macos/package.sh --arch universal
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-macos
path: dist/release/*
if-no-files-found: error
- name: Remove temporary keychain
if: always()
run: |
if [ -n "${MACOS_KEYCHAIN:-}" ]; then security delete-keychain "$MACOS_KEYCHAIN" || true; fi
windows:
timeout-minutes: 90
name: Windows ${{ matrix.arch }}
needs: version
runs-on: windows-latest
environment: release
strategy:
fail-fast: false
matrix:
include:
- { arch: x64, target: x86_64-pc-windows-msvc }
- { arch: x86, target: i686-pc-windows-msvc }
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
# .github/workflows/windows-arm64.yml installs and runs it on ARM64 hardware.
- { arch: arm64, target: aarch64-pc-windows-msvc }
env:
LIGHTCRAFT_VERSION: ${{ needs.version.outputs.version }}
LIGHTCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Fonts (optional build input; required for releases): see craftrules standards/fonts.md.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 # bump deliberately
path: craft-fonts
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-windows-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
shell: bash
run: cargo xtask version set "$LIGHTCRAFT_VERSION"
# package.ps1 adds the matching WixToolset.UI/Util.wixext (5.0.2) to the global extension cache.
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build, sign, package
shell: pwsh
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-windows-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
linux:
timeout-minutes: 90
name: Linux ${{ matrix.arch }}
needs: version
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-22.04, deb: amd64 }
- { arch: aarch64, runner: ubuntu-22.04-arm, deb: arm64 }
env:
LIGHTCRAFT_VERSION: ${{ needs.version.outputs.version }}
LIGHTCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
NFPM_VERSION: 2.47.0
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Fonts (optional build input; required for releases): see craftrules standards/fonts.md.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 # bump deliberately
path: craft-fonts
- name: Install build and packaging tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev \
desktop-file-utils appstream python3-yaml zsync
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-linux-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$LIGHTCRAFT_VERSION"
- name: Build and package (AppImage, deb, rpm, tar.gz)
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/linux/package.sh
- name: Check the packages
run: |
dpkg-deb --info dist/release/*.deb
dpkg-deb --contents dist/release/*.deb | grep -E 'usr/bin/lightcraft$|metainfo|applications'
ldd target/release/lightcraft
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.lightcraft.yml')); assert m['id'] == 'ai.storyteller.lightcraft'"
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
# Update information is embedded, and the .zsync for delta updates sits beside it.
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
test -s "$appimage.zsync"
done
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-linux-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
flatpak:
timeout-minutes: 90
name: Flatpak ${{ matrix.arch }}
needs: [version, linux]
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-24.04 }
- { arch: aarch64, runner: ubuntu-24.04-arm }
env:
LIGHTCRAFT_VERSION: ${{ needs.version.outputs.version }}
LIGHTCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Install flatpak-builder
run: |
sudo apt-get update
# librsvg2-common: the SVG pixbuf loader. flatpak-builder runs the host's
# `appstreamcli compose`, which renders the scalable icon and fails without it.
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- name: Build the Flatpak bundle
run: packaging/linux/flatpak-bundle.sh "dist/linux/lightcraft-$LIGHTCRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-flatpak-${{ matrix.arch }}
path: dist/release/*.flatpak
if-no-files-found: error
linux-riscv64:
timeout-minutes: 90
name: Linux riscv64
needs: version
# Cross-compiled on x86_64 (no hosted RISC-V runners) against the runner's own Ubuntu release
# from ports.ubuntu.com, so the binaries need that release's glibc (24.04: 2.39). 22.04's
# riscv64 ports lag its amd64 updates, which breaks the multiarch install. tar.gz only; the
# CLI is smoke-tested under QEMU.
runs-on: ubuntu-24.04
# No `environment: release`: this job signs nothing, so it gets no release secrets.
env:
LIGHTCRAFT_VERSION: ${{ needs.version.outputs.version }}
LIGHTCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Fonts (optional build input; required for releases): see craftrules standards/fonts.md.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 # bump deliberately
path: craft-fonts
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: riscv64gc-unknown-linux-gnu
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-linux-riscv64
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$LIGHTCRAFT_VERSION"
- name: Install cross-compilation dependencies
run: |
. /etc/os-release
sudo dpkg --add-architecture riscv64
# Pin the existing (archive.ubuntu.com) sources to amd64; riscv64 comes from ports.
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
sudo sed -i '/^Types: deb/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
fi
if [ -f /etc/apt/sources.list ]; then
sudo sed -i 's/^deb /deb [arch=amd64] /g' /etc/apt/sources.list
sudo sed -i 's/^deb-src /deb-src [arch=amd64] /g' /etc/apt/sources.list
fi
for suite in "$VERSION_CODENAME" "$VERSION_CODENAME-updates" "$VERSION_CODENAME-security"; do
echo "deb [arch=riscv64] http://ports.ubuntu.com/ubuntu-ports $suite main universe restricted multiverse"
done | sudo tee /etc/apt/sources.list.d/riscv64.list
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
gcc-riscv64-linux-gnu binutils-riscv64-linux-gnu libc6-dev-riscv64-cross libc6-dev:riscv64 qemu-user \
libxkbcommon-dev:riscv64 libwayland-dev:riscv64 libx11-dev:riscv64 libxrandr-dev:riscv64 \
libxi-dev:riscv64 libgl1-mesa-dev:riscv64
- name: Build and package (tar.gz)
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER: riscv64-linux-gnu-gcc
PKG_CONFIG_SYSROOT_DIR: /
PKG_CONFIG_PATH: /usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig
PKG_CONFIG_ALLOW_CROSS: "1"
CROSS_ARCH: riscv64
CROSS_TARGET: riscv64gc-unknown-linux-gnu
CROSS_COMPILE: riscv64-linux-gnu-
EMULATOR: qemu-riscv64
QEMU_LD_PREFIX: /usr/riscv64-linux-gnu
run: packaging/linux/package.sh --formats tar
- name: Check the tarball
run: |
tar -tzf dist/release/lightcraft-*-linux-riscv64.tar.gz \
| grep -E '/bin/lightcraft$|/bin/lightcraft-cli$|/share/applications/ai\.storyteller\.lightcraft\.desktop$'
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-linux-riscv64
path: dist/release/*.tar.gz
if-no-files-found: error
freebsd:
name: FreeBSD x86_64
needs: version
# GitHub has no FreeBSD runners: build in a FreeBSD 14.3 VM, the same image and packages as
# .github/workflows/freebsd.yml.
runs-on: ubuntu-latest
timeout-minutes: 180
env:
LIGHTCRAFT_VERSION: ${{ needs.version.outputs.version }}
LIGHTCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Fonts (optional build input; required for releases): see craftrules standards/fonts.md.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 # bump deliberately
path: craft-fonts
- name: Build and package in a FreeBSD VM (tar.gz)
# vmactions/freebsd-vm v1.5.9, pinned by commit (it runs our build).
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1.5.9
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Passed into the VM by name; never templated into the script below.
envs: "LIGHTCRAFT_VERSION LIGHTCRAFT_BUILD_DATE LIGHTCRAFT_BUILD_SHA INPUT_VERSION"
# The FreeBSD CI packages, plus bash for the packaging script.
prepare: |
pkg install -y bash git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2 alsa-lib
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
run: |
set -e
. "$HOME/.cargo/env"
git config --global --add safe.directory "$PWD"
# Build outside the checkout so only dist/ is copied back out of the VM (copying the
# target dir back fails on large builds). 4 jobs: more runs the VM out of memory.
export CARGO_TARGET_DIR=/var/tmp/lightcraft-target CARGO_BUILD_JOBS=4
if [ -n "$INPUT_VERSION" ]; then cargo xtask version set "$LIGHTCRAFT_VERSION"; fi
# craft-fonts was checked out next to the sources and synced into the VM with them.
export CRAFT_FONTS_DIR="$PWD/craft-fonts" CRAFT_FONTS_REQUIRED=1
bash packaging/freebsd/package.sh
tar -tzf dist/release/lightcraft-*-freebsd-x86_64.tar.gz \
| grep -E '/bin/lightcraft$|/bin/lightcraft-cli$|/share/applications/ai\.storyteller\.lightcraft\.desktop$|/share/doc/lightcraft/LICENSE-MIT$'
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-freebsd-x86_64
path: dist/release/*
if-no-files-found: error
web:
timeout-minutes: 90
name: Web (wasm)
needs: version
runs-on: ubuntu-latest
env:
LIGHTCRAFT_VERSION: ${{ needs.version.outputs.version }}
LIGHTCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
WASM_BINDGEN_VERSION: 0.2.129
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Fonts (optional build input; required for releases): see craftrules standards/fonts.md.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 # bump deliberately
path: craft-fonts
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-web
- name: Install wasm-bindgen CLI
run: |
# Must match the wasm-bindgen version in Cargo.lock exactly (cargo xtask web checks it).
if ! { command -v wasm-bindgen >/dev/null && wasm-bindgen --version | grep -q "$WASM_BINDGEN_VERSION"; }; then
cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked
fi
wasm-bindgen --version
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$LIGHTCRAFT_VERSION"
- name: Build and zip
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/web/package.sh
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-web
path: dist/release/*
if-no-files-found: error
release:
timeout-minutes: 10
name: Draft GitHub Release
needs: [version, macos, windows, linux, linux-riscv64, flatpak, freebsd, web]
runs-on: ubuntu-latest
environment: release
permissions:
contents: write
env:
VERSION: ${{ needs.version.outputs.version }}
PRERELEASE: ${{ needs.version.outputs.prerelease }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Checksums
working-directory: artifacts
run: |
sha256sum -- * | tee SHA256SUMS.txt
- name: Create or update the draft release
working-directory: artifacts
run: |
tag="v$VERSION"
title="LightCraft v$VERSION"
pre=()
if [ "$PRERELEASE" = true ]; then pre=(--prerelease); fi
if draft="$(gh release view "$tag" --json isDraft --jq .isDraft 2>/dev/null)"; then
if [ "$draft" != "true" ]; then
echo "::error::Release $tag is already published. Bump the version (cargo xtask version set) before pushing to release."
exit 1
fi
echo "Updating draft $tag: replacing its assets"
gh release view "$tag" --json assets --jq '.assets[].name' | while read -r asset; do
gh release delete-asset "$tag" "$asset" --yes
done
gh release edit "$tag" --draft --title "$title" --target "$GITHUB_SHA" --prerelease="$PRERELEASE"
gh release upload "$tag" --clobber -- *
else
echo "Creating draft $tag"
gh release create "$tag" --draft --title "$title" --target "$GITHUB_SHA" --generate-notes "${pre[@]}" -- *
fi
{
echo "Draft release **$title** at \`${GITHUB_SHA::9}\`:"
echo
sed 's/^/ /' SHA256SUMS.txt
} >>"$GITHUB_STEP_SUMMARY"
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
app-name: lightcraft
app-title: LightCraft
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
version: ${{ inputs.version }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
+24 -79
View File
@@ -1,22 +1,27 @@
# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64
# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed
# binaries are ARM64, run the CLI natively, and uninstall. (A native ARM64 `cargo test` job is left
# out for now: PdfCraft saw an intermittent access violation in egui UI tests there.)
# Windows ARM64 build and smoke test.
#
# Release packages on arm64-windows are produced on x64 runners via cross-compilation
# (target: aarch64-pc-windows-msvc) using MSVC's ARM64 cross tools, then installed and run
# on GitHub Actions' native windows-11-arm runner.
name: Windows ARM64
on:
push:
branches: [main]
pull_request:
paths:
- Cargo.toml
- Cargo.lock
- "**/Cargo.toml"
- "**/build.rs"
- .github/workflows/windows-arm64.yml
- packaging/windows/**
schedule:
- cron: "41 4 * * 1" # weekly, so drift in the runner images shows up
- ".github/workflows/windows-arm64.yml"
- "packaging/windows/**"
- "Cargo.toml"
- "Cargo.lock"
- "crates/**"
pull_request:
branches: [main]
paths:
- ".github/workflows/windows-arm64.yml"
- "packaging/windows/**"
- "Cargo.toml"
- "Cargo.lock"
- "crates/**"
workflow_dispatch:
concurrency:
@@ -26,70 +31,10 @@ concurrency:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
jobs:
package:
name: package (cross-compiled on x64)
runs-on: windows-latest
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: aarch64-pc-windows-msvc
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: windows-arm64-package
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build and package (unsigned)
shell: pwsh
env:
DIST: ${{ github.workspace }}\dist\arm64
run: ./packaging/windows/package.ps1 -Arch arm64
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: lightcraft-windows-arm64
path: dist/arm64/*
if-no-files-found: error
retention-days: 7
install:
name: install and run on ARM64
needs: package
runs-on: windows-11-arm
timeout-minutes: 30
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: lightcraft-windows-arm64
path: dist
- name: Install the MSI, check it, run it, uninstall it
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$msi = (Get-ChildItem dist/*.msi | Select-Object -First 1).FullName
$p = Start-Process msiexec.exe -ArgumentList '/i', "`"$msi`"", '/qn', '/l*v', 'install.log' -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; throw "msiexec /i exited $($p.ExitCode)" }
$dir = Join-Path $env:ProgramFiles 'LightCraft'
foreach ($exe in 'lightcraft.exe', 'lightcraft-cli.exe') {
$path = Join-Path $dir $exe
if (-not (Test-Path $path)) { throw "$exe not installed in $dir" }
$bytes = [System.IO.File]::ReadAllBytes($path)
$machine = [BitConverter]::ToUInt16($bytes, [BitConverter]::ToInt32($bytes, 0x3C) + 4)
if ($machine -ne 0xAA64) { throw "$exe is for machine 0x$('{0:X}' -f $machine), not ARM64" }
Write-Output "ok $path (ARM64)"
}
# The installed CLI runs natively on ARM64.
$cli = Join-Path $dir 'lightcraft-cli.exe'
$out = & $cli --version 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { Write-Output $out; throw "lightcraft-cli --version exited $LASTEXITCODE" }
Write-Output "ok lightcraft-cli --version: $($out.Trim())"
$p = Start-Process msiexec.exe -ArgumentList '/x', "`"$msi`"", '/qn' -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "msiexec /x exited $($p.ExitCode)" }
if (Test-Path (Join-Path $dir 'lightcraft.exe')) { throw 'uninstall left lightcraft.exe behind' }
Write-Output 'ok uninstalled'
windows-arm64:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
with:
app-name: lightcraft
app-dir: LightCraft
+5 -1
View File
@@ -125,11 +125,15 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
## Map of the code
`geom`, `color`, `raster`, `tiff` (L0) → `raw`, `codecs`, `meta`, `develop` (L1) → `pipeline` → `catalog` → `engine`
→ `ui-egui`, `mcp` (L5) → apps `lightcraft` (desktop), `lightcraft-cli` (render/commands/MCP). `scenes` generates demo
photos. `xtask` = tooling (`ci`, `layers`, `assets`, `parity`, `wasm`, `corpus`, `stats`). `flake.nix` +
photos. `xtask` = tooling (`ci`, `layers`, `assets`, `parity`, `wasm`, `corpus`, `stats`); `testkit` = test helpers
(dev-dependency only). `flake.nix` +
`nix/package.nix` = the Nix package (`nix build` builds both binaries with the craft-fonts input, installs the
desktop file/icons/AppStream metadata and runs `cargo test --workspace`; `nix develop` = dev shell). Community-maintained; CI only
evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the workspace; see README → Quick start.
+5 -1
View File
@@ -133,11 +133,15 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
## Map of the code
`geom`, `color`, `raster`, `tiff` (L0) → `raw`, `codecs`, `meta`, `develop` (L1) → `pipeline` → `catalog` → `engine`
→ `ui-egui`, `mcp` (L5) → apps `lightcraft` (desktop), `lightcraft-cli` (render/commands/MCP). `scenes` generates demo
photos. `xtask` = tooling (`ci`, `layers`, `assets`, `parity`, `wasm`, `corpus`, `stats`). `flake.nix` +
photos. `xtask` = tooling (`ci`, `layers`, `assets`, `parity`, `wasm`, `corpus`, `stats`); `testkit` = test helpers
(dev-dependency only). `flake.nix` +
`nix/package.nix` = the Nix package (`nix build` builds both binaries with the craft-fonts input, installs the
desktop file/icons/AppStream metadata and runs `cargo test --workspace`; `nix develop` = dev shell). Community-maintained; CI only
evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the workspace; see README → Quick start.
Generated
+53 -32
View File
@@ -1072,6 +1072,11 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63"
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -3073,7 +3078,7 @@ dependencies = [
[[package]]
name = "lightcraft"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"eframe",
"egui",
@@ -3081,6 +3086,7 @@ dependencies = [
"lightcraft-engine",
"lightcraft-raster",
"lightcraft-sysmem",
"lightcraft-testkit",
"lightcraft-ui-egui",
"log",
"muda",
@@ -3097,7 +3103,7 @@ dependencies = [
[[package]]
name = "lightcraft-catalog"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"crc32fast",
"lightcraft-develop",
@@ -3114,7 +3120,7 @@ dependencies = [
[[package]]
name = "lightcraft-cli"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"dhat",
"lightcraft-codecs",
@@ -3130,10 +3136,11 @@ dependencies = [
[[package]]
name = "lightcraft-codecs"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"avif-serialize",
"bytemuck",
"dhat",
"image",
"image-webp",
"jixel",
@@ -3144,6 +3151,7 @@ dependencies = [
"lightcraft-geom",
"lightcraft-heif",
"lightcraft-raster",
"lightcraft-testkit",
"moxcms 0.9.1",
"png",
"proptest",
@@ -3159,7 +3167,7 @@ dependencies = [
[[package]]
name = "lightcraft-color"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-geom",
"proptest",
@@ -3168,7 +3176,7 @@ dependencies = [
[[package]]
name = "lightcraft-denoise"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"faer-core",
"lightcraft-denoise-core",
@@ -3185,7 +3193,7 @@ dependencies = [
[[package]]
name = "lightcraft-denoise-core"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-raster",
"miniz_oxide 0.8.9",
@@ -3200,7 +3208,7 @@ dependencies = [
[[package]]
name = "lightcraft-develop"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-color",
"lightcraft-geom",
@@ -3212,9 +3220,10 @@ dependencies = [
[[package]]
name = "lightcraft-engine"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"ab_glyph",
"craft-docpath",
"harfrust",
"jxl-oxide",
"libc",
@@ -3240,6 +3249,7 @@ dependencies = [
"lightcraft-scenes",
"lightcraft-segment",
"lightcraft-slideshow",
"lightcraft-testkit",
"lightcraft-tiff",
"log",
"miniz_oxide 0.8.9",
@@ -3253,8 +3263,9 @@ dependencies = [
[[package]]
name = "lightcraft-faces"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-testkit",
"matrixmultiply",
"ndarray",
"proptest",
@@ -3267,7 +3278,7 @@ dependencies = [
[[package]]
name = "lightcraft-fetch"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"log",
"rustls",
@@ -3278,7 +3289,7 @@ dependencies = [
[[package]]
name = "lightcraft-geocode"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"miniz_oxide 0.8.9",
"serde",
@@ -3286,7 +3297,7 @@ dependencies = [
[[package]]
name = "lightcraft-geom"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"proptest",
"serde",
@@ -3294,17 +3305,19 @@ dependencies = [
[[package]]
name = "lightcraft-gpu"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"bytemuck",
"lightcraft-color",
"lightcraft-denoise",
"lightcraft-develop",
"lightcraft-faces",
"lightcraft-geom",
"lightcraft-pipeline",
"lightcraft-raster",
"lightcraft-raw",
"lightcraft-scenes",
"lightcraft-testkit",
"log",
"pollster 1.0.1",
"wgpu",
@@ -3312,7 +3325,7 @@ dependencies = [
[[package]]
name = "lightcraft-heif"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"heic-rs",
"rayon",
@@ -3320,14 +3333,14 @@ dependencies = [
[[package]]
name = "lightcraft-inpaint"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"rayon",
]
[[package]]
name = "lightcraft-lensdb"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-develop",
"lightcraft-geom",
@@ -3336,7 +3349,7 @@ dependencies = [
[[package]]
name = "lightcraft-mcp"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-codecs",
"lightcraft-engine",
@@ -3347,7 +3360,7 @@ dependencies = [
[[package]]
name = "lightcraft-merge"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-codecs",
"lightcraft-color",
@@ -3363,7 +3376,7 @@ dependencies = [
[[package]]
name = "lightcraft-meta"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-geom",
"lightcraft-tiff",
@@ -3375,7 +3388,7 @@ dependencies = [
[[package]]
name = "lightcraft-pipeline"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"image",
"lightcraft-color",
@@ -3393,7 +3406,7 @@ dependencies = [
[[package]]
name = "lightcraft-preview"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"jpeg-encoder",
"lightcraft-raster",
@@ -3405,7 +3418,7 @@ dependencies = [
[[package]]
name = "lightcraft-raster"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"libc",
"lightcraft-color",
@@ -3417,14 +3430,16 @@ dependencies = [
[[package]]
name = "lightcraft-raw"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"dhat",
"jpeg-encoder",
"jxl-oxide",
"lightcraft-color",
"lightcraft-geom",
"lightcraft-meta",
"lightcraft-raster",
"lightcraft-testkit",
"lightcraft-tiff",
"miniz_oxide 0.8.9",
"proptest",
@@ -3439,7 +3454,7 @@ dependencies = [
[[package]]
name = "lightcraft-scenes"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"image",
"lightcraft-color",
@@ -3450,11 +3465,12 @@ dependencies = [
[[package]]
name = "lightcraft-segment"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"candle-core",
"candle-nn",
"lightcraft-fetch",
"lightcraft-testkit",
"log",
"serde",
"serde_json",
@@ -3463,7 +3479,7 @@ dependencies = [
[[package]]
name = "lightcraft-slideshow"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"lightcraft-raster",
"serde",
@@ -3472,11 +3488,15 @@ dependencies = [
[[package]]
name = "lightcraft-sysmem"
version = "0.8.0"
version = "0.10.0"
[[package]]
name = "lightcraft-testkit"
version = "0.10.0"
[[package]]
name = "lightcraft-tiff"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"proptest",
"serde",
@@ -3485,7 +3505,7 @@ dependencies = [
[[package]]
name = "lightcraft-ui-egui"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"craft-ui",
"egui",
@@ -3504,6 +3524,7 @@ dependencies = [
"lightcraft-preview",
"lightcraft-raster",
"lightcraft-slideshow",
"lightcraft-testkit",
"log",
"serde",
"serde_json",
@@ -3513,7 +3534,7 @@ dependencies = [
[[package]]
name = "lightcraft-web"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"crc32fast",
"eframe",
@@ -6983,7 +7004,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.8.0"
version = "0.10.0"
dependencies = [
"brotli",
"flate2",
+4 -2
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.8.0"
version = "0.10.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.90"
@@ -11,6 +11,7 @@ repository = "https://github.com/storytold/lightcraft"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
# internal
lightcraft-denoise-core = { path = "crates/denoise-core" }
lightcraft-denoise = { path = "crates/denoise", default-features = false }
@@ -40,6 +41,7 @@ lightcraft-heif = { path = "crates/heif" }
lightcraft-segment = { path = "crates/segment" }
lightcraft-geocode = { path = "crates/geocode" }
lightcraft-slideshow = { path = "crates/slideshow" }
lightcraft-testkit = { path = "crates/testkit" }
# foundation
thiserror = "2"
@@ -53,7 +55,7 @@ bytemuck = { version = "1", features = ["derive"] }
crc32fast = "1"
siphasher = "1"
libc = "0.2" # dev-only: process CPU time in benches
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap); never in default builds
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
# formats
quick-xml = "0.38"
+70 -26
View File
@@ -18,7 +18,7 @@
</p>
<p align="center">
<b>Photo library and raw development; an open-source, clean-room reimplementation of Adobe Lightroom, rebuilt in pure Rust.</b><br>
<b>Photo library and raw development; an open-source, non-destructive photo library and raw developer, built in pure Rust.</b><br>
Native on macOS, Windows and Linux. In the browser via WebAssembly. Drivable end to end by AI agents over MCP.
</p>
@@ -28,6 +28,9 @@
<img alt="MCP server included" src="https://img.shields.io/badge/MCP-ready-8a5800?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-8a5800?style=flat-square">
<a href="ROADMAP.md"><img alt="Status: young and moving fast" src="https://img.shields.io/badge/status-young%20%26%20moving%20fast-f2a516?style=flat-square"></a>
<br>
<a href="https://sonarcloud.io/project/overview?id=storytold_lightcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/lightcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
</p>
<p align="center">
@@ -129,7 +132,7 @@ Split-tone shadows, midtones and highlights independently with drag-anywhere col
## Before & after
Hold <kbd>\\</kbd> to peek at the original, press <kbd>Y</kbd> for side by side, or <kbd>Shift</kbd>+<kbd>Y</kbd> for a
Press <kbd>\\</kbd> to toggle the Before view, <kbd>Y</kbd> for side by side, or <kbd>Shift</kbd>+<kbd>Y</kbd> for a
split view. Every image below is a real screenshot of LightCraft, captured automatically by an agent through the
[control channel](#built-for-agents).
@@ -150,9 +153,13 @@ split view. Every image below is a real screenshot of LightCraft, captured autom
Paint with a **Brush** (size, feather, flow, density, erase), drop **Linear** and **Radial Gradients** with draggable
pins, or select by **Luminance Range**, **Color Range**, **Sky**, **Subject** and **Background**. Combine components
with **Add / Subtract / Intersect**, invert any of them, and dial in 15 local adjustments per mask (Temp, Tint,
Exposure, Contrast, Highlights, Shadows, Whites, Blacks, Texture, Clarity, Dehaze, Hue, Saturation, Sharpness, Noise)
plus an overall Amount.
with **Add / Subtract / Intersect**, invert any of them, and dial in 17 local adjustments per mask (Temp, Tint,
Exposure, Contrast, Highlights, Shadows, Whites, Blacks, Texture, Clarity, Dehaze, Hue, Saturation, Sharpness, Noise,
Moiré, Defringe), plus an overall Amount.
Desktop **Object** and **Describe** masks use SAM 3 for click-based and text-prompt selection, with a separately
installed model; see [model setup and terms](docs/ai-masks.md). Subject, Sky and Background selections still use
classical heuristics. Existing model-generated masks render and export without the model installed.
<p align="center">
<img src="docs/images/masking.jpg" alt="Masking panel with a linear Sky mask and a radial Sun glow mask; the radial gradient is drawn as a red overlay around the sun on a lake scene" width="100%">
@@ -164,7 +171,7 @@ plus an overall Amount.
## Presets, profiles & the Color Mixer
Eighteen hand-built presets ship in the box (*Golden Hour, Teal & Orange, Faded Matte, Selenium Tone, Crisp
Forty-one hand-built presets ship in the box (*Golden Hour, Teal & Orange, Faded Matte, Selenium Tone, Crisp
Landscape* and more), each with an **Amount** slider from 0 to 200 %. Save your own from any group of settings, mark
favourites, and copy, paste or sync edits across a whole selection with exactly the groups you choose.
@@ -209,6 +216,10 @@ A library that stays out of your way: **All Photos**, **Recently Added**, **Pick
import date, edit date, name, rating, size or at random (a stable shuffle; View → Sort → Reshuffle for a new one). The justified **Photo Grid** and **Square Grid** views are virtualized,
so they stay smooth whether you have forty photos or forty thousand.
The **People** view groups named faces, including names read from XMP; face boxes can be edited in the loupe.
On desktop, automatic detection and recognition use optional models installed through **Settings → Faces**; no weights are
bundled. See [face models and setup](docs/faces.md).
<table>
<tr>
<td width="50%"><img src="docs/images/grid-demo.jpg" alt="Justified Photo Grid of 24 demo photos with ratings and flags, and a sidebar of nested albums under a Travel 2026 folder"><br><sub>Photo Grid with albums nested in a folder, ratings and flags. <i>Demo library.</i></sub></td>
@@ -268,6 +279,26 @@ lightcraft --control 7980 ~/Pictures/trip
with the same font coverage as watermarks (CJK requires craft-fonts), with long names shortened in the middle.
This is a contact-sheet workflow,
not a printer-driver or custom picture-package layout editor.
- **Print layouts (native app / CLI):** **File → Print…** opens the Print module's layout editor: Single Image,
Contact Sheet, Picture Package (Auto Layout packs cells onto pages) and Custom Package (drag and resize cells,
stacking order, snap to cells or a grid), Zoom to Fill / Rotate to Fit, Photo Border and Inner Stroke, paper
sizes from 4 × 6 to 13 × 19 and A3 to A5 or custom, margins, rulers in in/cm/mm/pt, page background, 72–720 ppi,
and saved templates. **Print to PDF…** renders in the background. Everything is a `print.*` command
(`print.get`, `print.set`, `print.cell.add`, `print.layout.autoLayout`, `print.exportPdf`,
`print.template.save`…), so the CLI and MCP drive it too:
```sh
lightcraft-cli run --import ~/Pictures/shoot print.set 'layout={"style":"picturePackage","page":{"paper":"8x10"}}' \
print.cell.add width=5 height=7 print.cell.add width=2.5 height=3.5 print.layout.autoLayout print.exportPdf path=Package.pdf
```
The Print Job panel supports printer/paper ICC profiles, rendering intent, black point compensation,
print adjustment, sharpening and 8/16-bit PDF output. Direct printing through an OS print dialog and page
overlays (identity plate, watermark, page numbers) are not there yet.
- **Slideshows:** **View → Slideshow** plays the photos in view full screen, with fades, repeat and random order.
**Settings → Slideshow** configures layouts, templates, backgrounds, overlays and title screens. Native exports
support PDF, JPEG sequences and AV1 video in MP4 or WebM; music and a dedicated Slideshow module editor remain
missing. See [docs/slideshow.md](docs/slideshow.md).
- **Every widget is addressable** (`ui.widgets`) and clickable by name, so agents operate the real UI, not a
side door.
- The screenshots in this README were produced end to end by the [`docs/showcase/`](docs/showcase/) scripts.
@@ -279,7 +310,7 @@ lightcraft --control 7980 ~/Pictures/trip
- **Pure Rust, no C.** Our own RAW decoders (DNG, Canon CR2/CR3, Sony ARW, Nikon NEF, Fujifilm RAF incl. X-Trans,
Panasonic RW2 / Leica RWL, Pentax PEF, Olympus ORF), our own colour science, our own pipeline. JPEG, PNG, TIFF, WebP,
PSD composites and JPEG XL open today; HEIC/HEIF photos too with `--features heif` (HEVC is a build-time choice,
PSD composites, JPEG XL, GIF (first frame) and BMP open today; HEIC/HEIF photos too with `--features heif` (HEVC is a build-time choice,
as in PhotoCraft).
- **Scene-referred & wide-gamut.** Linear Rec.2020 float internally, Bradford-adapted white balance, gamut mapping
instead of clipping, a filmic shoulder for raw and pixel-exact pass-through for JPEGs you haven't touched.
@@ -305,17 +336,21 @@ lightcraft --control 7980 ~/Pictures/trip
LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (details in the [roadmap](ROADMAP.md) and
[docs/target-app-parity.md](docs/target-app-parity.md)):
- **By feature count we're at ~81%** of Lightroom (core features 98%), tracked row by row in
- **By feature count we're at ~82%** (core features 98%), tracked row by row in
[docs/parity-checklist.md](docs/parity-checklist.md).
- **As a day-to-day Lightroom replacement we're nearer 61% for the whole product, ~51% for a typical working photographer and ~65% for
- **As a day-to-day tool we're nearer 61% for the whole product, ~51% for a typical working photographer and ~65% for
casual use.** It's great for JPEG/DNG and most Sony / Panasonic /
Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera.
- **The biggest gaps:**
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, X-H2S and X-T4 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix;
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix;
- **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
- **AI masks and denoise:** subject and sky selection are classical heuristics;
- **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);
- **network libraries:** a preview reads the raw's header — or, for a CR3 or a TIFF raw whose preview tag sits past it, exactly the ranges the sparse planner names — and its embedded JPEG only (56.5 MB → 5.9 MB, 10 s → 1 s on the test share), but the *developed* picture still needs the sensor data over the wire; see [docs/raw-preview-reads.md](docs/raw-preview-reads.md);
- **on-screen HDR display, video and the Classic Print / Book / Map modules.**
- **on-screen HDR display, video import/editing, and the Book / Map module views.** Print layouts and
colour-managed PDF output work; direct printer output and page overlays remain missing. Slideshow playback
and export work, with a dedicated module editor and music still missing.
- **What's next:** see [the ranked gaps](docs/gaps.md) and [the roadmap](docs/roadmap.md).
| Area | Status |
@@ -323,16 +358,16 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
| Library: albums, folders, smart albums, stacks (incl. auto-stack), virtual copies, ratings, flags, labels, filter bar, search, sort, grids, filmstrip | ✅ |
| Culling: Compare (synced zoom) and Survey views, auto-advance, instant previews | ✅ |
| Light, Color, Effects (vignette styles), Tone Curve (+ refine saturation, targeted adjustment), Color Mixer (+ targeted), Point Color, Color Grading, Calibration, B&W | ✅ |
| Masking: brush, linear, radial, luminance/colour range, add/subtract/intersect | ✅ (AI subject/sky use classical heuristics for now) |
| Masking: brush, linear, radial, luminance/colour range, add/subtract/intersect; Object and Describe selections | ✅ · Object/Describe require optional SAM 3; Subject/Sky remain heuristic ([details](docs/ai-masks.md)) |
| Crop, straighten tool + auto straighten, flip, rotate, aspect ratios, overlays | ✅ |
| Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ |
| Camera colour: DNG files use their own matrices | ✅ DNG · 🚧 own Sony/Fujifilm profiles; measured calibration database missing |
| 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)) |
| Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights), Super Resolution ⬜ |
| Remove / Heal / Clone spots (auto source), Visualize Spots, Red Eye and Pet Eye (auto pupil detection, catchlight) | ✅ · content-aware fill, spot pin editing 🚧 |
| Export: JPEG / PNG / TIFF / WebP / AVIF / DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ |
| HDR: HDR editing with a headroom limit, SDR rendition, Visualize HDR; export as ISO 21496-1 gain map JPEG, PQ AVIF or 32-bit float TIFF | ✅ · HDR display ⬜ |
| 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 | ✅ |
| HDR: HDR editing with a headroom limit, SDR rendition, Visualize HDR; gain map JPEG, PQ/HLG AVIF, PQ PNG/JPEG XL and float TIFF export | ✅ · HDR display ⬜ |
| Library persistence (crash-safe op log + snapshots, background compaction, failed saves reported), disk thumbnail cache | ✅ |
| Import: Add in place / Copy / Move, rename and folder templates, devices, duplicate detection, watched folders; Local folder browsing | ✅ |
| MCP server (headless or live app, persistent libraries), CLI, control channel | ✅ |
@@ -340,7 +375,11 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
| Optics (distortion, vignetting, auto + manual CA, defringe, lens corrections embedded in DNG files, Panasonic / Leica RW2 / RWL distortion data and Nikon Z 6II / Z 8 / Z f distortion data), Geometry (transforms, Constrain Crop), Upright (Auto/Level/Vertical/Full/Guided) | ✅ · camera lens profiles (our own) ⬜ |
| Photo Merge: HDR (auto-align, deghost), Panorama (spherical/cylindrical/perspective, boundary warp, auto crop), HDR Panorama → DNG | ✅ |
| GPU pipeline (wgpu compute, CPU-exact within 1/255), CPU fallback on device limits / errors | ✅ · WebGPU in the browser 🚧 |
| AI: segmentation masks, AI denoise, super resolution, faces; video | 🚧 (see [gaps](docs/gaps.md)) |
| People view, XMP face names and editable face boxes; automatic face detection and recognition | ✅ · detection/recognition require optional models ([setup](docs/faces.md)) |
| GPX tracklog auto-tagging and offline reverse geocoding | ✅ · place names require the GeoNames dataset; Map view ⬜ |
| Print layouts, picture packages, templates and colour-managed PDF export | ✅ layouts/PDF · 🚧 direct printer output and page overlays |
| Slideshow playback, layouts, overlays, templates and PDF/JPEG/AV1 export | ✅ playback · 🚧 dedicated module editor and music ([details](docs/slideshow.md)) |
| Video import/editing and Book module | ⬜ |
| Web build (same UI in the browser via WASM): persistent library in OPFS/IndexedDB, Web Worker rendering, export downloads | ✅ · WebGPU, Safari/Firefox testing 🚧 |
<sub>✅ works today · 🚧 in progress · ⬜ not started</sub>
@@ -359,7 +398,7 @@ cargo run --release -p lightcraft -- --memory # a throwaway in-memory
cargo run --release -p lightcraft -- --control 7980 # with the automation channel
cargo xtask web --serve # the same app in the browser: http://127.0.0.1:8080/
cargo run --release -p lightcraft-cli -- render photo.jpg -o out.jpg --set light.exposure=0.5
cargo xtask ci # fmt, clippy, tests, layering, wasm checks
cargo xtask ci # fmt, clippy, HEIF, tests, parity, layers, assets, WASM
```
CI defaults to line-table debug information and one build job per 1.5 GB of RAM
@@ -395,6 +434,13 @@ information combined with LTO and one codegen unit on low-memory builders. A PKG
its own profile settings can override inherited variables; adjust the packaging recipe locally or
contact its maintainer rather than assuming an environment prefix on `makepkg` will take precedence.
Tests that need a GPU, the corpus, the craft-fonts faces or a model pass without checking anything when
those are missing (libtest has no "skipped" status), so `cargo xtask ci` lists them: tests record a skip
with `lightcraft_testkit::skip!`, and the run ends with what the machine offered (OS, CPUs, RAM, GPU
adapters per backend, corpus, fonts) and every skip by reason. It writes `target/ci/report.json` and
`target/ci/summary.md`, a block to paste into a PR (`--summary-md` prints it); `--hardware` also runs the
GPU tests on every backend that has a hardware adapter. Nothing is uploaded.
**Chinese and Japanese text** need the shared font repo, an optional build input (official releases always include it):
```sh
@@ -405,7 +451,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft
Without it LightCraft builds and runs the same, but Chinese and Japanese text have no glyphs. Fonts are never committed to this
repo — the standard for what goes there lives with it: see the [craft-fonts README](https://github.com/storytold/craft-fonts#readme).
**Interface language:** **Edit → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Čeština) or **Settings → General →
**Interface language:** **Edit → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Polski, Čeština, Italiano, ქართული) or **Settings → General →
Language**; the choice applies immediately and persists. See [docs/localization.md](docs/localization.md).
**Logs:** the desktop app writes its log to standard error and to `logs/lightcraft.log` in its settings folder
@@ -470,9 +516,9 @@ egui frontend is one swappable crate; nothing below it knows a UI exists. `mcp`
Humans and agents follow the same rules, so read [AGENTS.md](AGENTS.md) first. The short version:
- **Clean-room.** Never read Adobe binaries or GPL raw/photo code (darktable, RawTherapee, LibRaw, rawspeed, dcraw…);
- **Clean-room.** Never read proprietary binaries or GPL raw/photo code (darktable, RawTherapee, LibRaw, rawspeed, dcraw…);
work from public specs and black-box observation.
- **No Adobe assets, ever:** no icons, screenshots, presets, profiles, LUTs or fonts from Adobe products. Every
- **No proprietary assets, ever:** no icons, screenshots, presets, profiles, LUTs or fonts from commercial products. Every
image, icon and font in the repo is original, public domain, Creative Commons, OFL or permissively licensed, and has
an entry in [assets/ATTRIBUTION.md](assets/ATTRIBUTION.md) added in the same commit. New fonts go to
[storytold/craft-fonts](https://github.com/storytold/craft-fonts), not here.
@@ -515,7 +561,7 @@ option to start it. For unattended installs: `msiexec /i lightcraft-<ver>-window
| Format | x86_64 | aarch64 (ARM64) | Notes |
|---|---|---|---|
| AppImage | `lightcraft-<ver>-linux-x86_64.AppImage` | `lightcraft-<ver>-linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) |
| AppImage | `lightcraft-<ver>-linux-x86_64.AppImage` | `lightcraft-<ver>-linux-aarch64.AppImage` | Portable; updates with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) |
| Flatpak | `lightcraft-<ver>-linux-x86_64.flatpak` | `lightcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `lightcraft-<ver>-linux-x86_64.deb` | `lightcraft-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `lightcraft-<ver>-linux-x86_64.rpm` | `lightcraft-<ver>-linux-aarch64.rpm` | |
@@ -602,8 +648,6 @@ ArtCraft Team and are not covered by this license. They may be used only unmodif
part of this repository and LightCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
<sub>Adobe, Photoshop, Illustrator, Premiere Pro, Lightroom, Acrobat, After Effects and InDesign are trademarks or registered trademarks of Adobe Inc. in the United States and/or other countries. LightCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Adobe Inc.; these names are used only to describe the workflows it is compatible with.</sub>
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
+6 -8
View File
@@ -18,7 +18,7 @@
</p>
<p align="center">
<b>照片图库与 raw 显影;Adobe Lightroom 的开源净室实现,用纯 Rust 重建。</b><br>
<b>照片图库与 raw 显影;开源、非破坏性的照片图库与 raw 显影工具,用纯 Rust 构建。</b><br>
在 macOS、Windows 和 Linux 上原生运行,也可通过 WebAssembly 在浏览器中使用,并能由 AI 智能体经 MCP 端到端驱动。
</p>
@@ -299,12 +299,12 @@ lightcraft --control 7980 ~/Pictures/trip
LightCraft 很年轻,而且进展很快。**我们如实所处的位置**(细节见[路线图](ROADMAP.md#where-we-stand)):
- **按功能数量算,我们达到了 Lightroom 的约 79%**(核心功能 98%),逐行记录在
- **按功能数量算,我们达到了约 79%**(核心功能 98%),逐行记录在
[docs/parity.md](docs/parity.md)。
- **作为日常替代 Lightroom 的工具,我们更接近 60–70%。** 在单台机器上处理 JPEG/DNG 以及大多数尼康/索尼/
- **作为日常使用的工具,我们更接近 60–70%。** 在单台机器上处理 JPEG/DNG 以及大多数尼康/索尼/
较老佳能的 raw 都很出色。
- **最大的缺口:**
- **相机色彩校准:** 索尼、尼康、松下、富士和佳能 CR3 的 raw 会从各自的相机 JPEG 得到受保护的估计值,内置 ILCA-99M2、ILCE-7CR、ILCE-7M4、X-H2S 和 X-T4 配置文件;实测校准仍然缺失,其他 raw 或被拒绝的拟合会保留中性矩阵;
- **相机色彩校准:** 索尼、尼康、松下、富士和佳能 CR3 的 raw 会从各自的相机 JPEG 得到受保护的估计值,内置 ILCA-99M2、ILCE-7CR、ILCE-7M4、X-H2S、X-T4、尼康 Z 6II、Z 8 和 D5300 配置文件;实测校准仍然缺失,其他 raw 或被拒绝的拟合会保留中性矩阵;
- **压缩的奥林巴斯 raw 和不受支持的 CR3 变体:** 这些在有内嵌 JPEG 预览时使用预览。富士无损/有损压缩 RAF 现在能解码传感器数据;[验证与已有图库重新加载说明](docs/raf-compression.md);
- **AI 蒙版与降噪:** 主体和天空选择目前是经典启发式算法;
- **屏幕上的 HDR 显示、视频,以及经典版式中的打印/画册/地图模块。**
@@ -453,9 +453,9 @@ egui 前端是一个可替换的 crate;它下面没有任何东西知道 UI
人和智能体遵循同样的规则,所以请先读 [AGENTS.md](AGENTS.md)。简短版本:
- **净室。** 绝不阅读 Adobe 的二进制文件或 GPL 的 raw/照片代码(darktable、RawTherapee、LibRaw、rawspeed、dcraw……);
- **净室。** 绝不阅读专有软件的二进制文件或 GPL 的 raw/照片代码(darktable、RawTherapee、LibRaw、rawspeed、dcraw……);
只依据公开规范和黑盒观察来工作。
- **绝不使用 Adobe 资源:** 不使用 Adobe 产品的图标、截图、预设、配置文件、LUT 或字体。仓库中的每一个
- **绝不使用专有资源:** 不使用商业产品的图标、截图、预设、配置文件、LUT 或字体。仓库中的每一个
图像、图标和字体都是原创、公有领域、知识共享、OFL 或宽松许可的,并在同一提交中
于 [assets/ATTRIBUTION.md](assets/ATTRIBUTION.md) 添加条目。新字体提交到
[storytold/craft-fonts](https://github.com/storytold/craft-fonts),而不是这里。
@@ -579,8 +579,6 @@ ArtCraft 团队的商标,不在本许可范围内。它们只能在未修改
本仓库和 LightCraft 的一部分,按 [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt) 使用。
分支和修改版本必须移除它们。
<sub>Adobe、Photoshop、Illustrator、Premiere Pro、Lightroom、Acrobat、After Effects 和 InDesign 是 Adobe Inc. 在美国和/或其他国家的商标或注册商标。LightCraft 是一个独立的开源项目,与 Adobe Inc. 无隶属关系,也未获其赞助或认可;这些名称仅用于说明它所兼容的工作流。</sub>
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>由 <a href="https://getartcraft.com/">ArtCraft</a> 团队和社区制作。</sub>
+14 -7
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~14 points and ~340–600 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (RAW: 82% of Adobe's models decode, 36% verified) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
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
@@ -12,7 +12,7 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are
| | Value | Kind |
|---|---:|---|
| **Feature breadth** (checklist) | **81.1%** of 517 rows (P0 98.0%, P1 95.1%, P2 46.9%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount |
| **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 |
| **Mainstream practitioner** | **~51%** (46–56%) | estimated |
@@ -45,8 +45,8 @@ Hours are calibrated on this repo's PR history; see
| Dimension | Ready | Breadth | Remaining | Doc |
|---|---:|---:|---:|---|
| Features | ~61% | ~77% (checklist 81.1%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) |
| ↳ RAW cameras, colour, lens profiles | ~60% | 82% of 1,446 Adobe models decode, 36% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
| UI/UX fidelity | ~70% | ~85% | 34–58 h | [ui-parity](docs/ui-parity.md) |
| ↳ RAW cameras, colour, lens profiles | ~60% | 83% of 1,446 Adobe models decode, 38% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
| UI/UX fidelity | ~70% | ~85% | 32–54 h | [ui-parity](docs/ui-parity.md) |
| File formats (non-raw) | ~70% | ~85% | 30–55 h | [file-format-parity](docs/file-format-parity.md) |
| Hardware | ~40% | ~50% | 40–80 h | [hardware-parity](docs/hardware-parity.md) |
| Localization | ~55% of the 12 key languages | 7 of 12 present | 130–210 h (+145–255 h new scripts) | [localization-parity](docs/localization-parity.md) |
@@ -61,7 +61,7 @@ Hours are calibrated on this repo's PR history; see
| Area | Ready | Breadth | Remaining |
|---|---:|---:|---:|
| Import and library | 80% | 90% | 25–45 h |
| RAW decoding and camera coverage | 77% | 81% | 120–220 h |
| RAW decoding and camera coverage | 77% | 82% | 120–220 h |
| Colour, camera profiles, render fidelity | 35% | 65% | 80–150 h |
| Global develop adjustments | 70% | 93% | 30–60 h |
| Optics, lens profiles, crop and geometry | 50% | 80% | 40–80 h |
@@ -96,7 +96,7 @@ while lower-layer errors stay English. Detail: [localization-parity.md](docs/loc
| Korean | ko | 0% | none (no Hangul face) |
| Vietnamese | vi | 0% | none |
Also shipped: Traditional Chinese (87%), Russian (74%), Ukrainian (99%).
Also shipped: Traditional Chinese (87%), Russian (74%), Ukrainian (99%), Italian (92%), Georgian (100%).
## Upcoming
@@ -105,7 +105,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
1. Camera colour of our own: measured calibration for the popular models (50–90 h)
2. CR3 for every Canon body (25–45 h)
3. Render-fidelity suite against Lightroom, then tuning (30–60 h)
4. Full-resolution zoom (8–15 h)
4. ~~Full-resolution zoom~~ (done 2026-10-12)
5. AI masks: Subject / Sky / People (40–70 h + model decision)
6. Compressed ORF and HE NEF (28–55 h)
7. Lens profile database of our own (40–80 h)
@@ -114,6 +114,9 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
## Progress log
- 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor
hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking
identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277.
- 2026-10-14: 97 Canon CR2, Pentax and Ricoh models verified, one CC0 raw.pixls.us file each pinned and
checked against the camera JPEG (`crates/raw/tests/canon_pentax_corpus.rs`). 334 models verified, ~50% of
photographers on a verified body; headline numbers unchanged.
@@ -180,6 +183,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| Date | Change | Summary |
|---|---|---|
| 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged |
| 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged |
| 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled |
| 2026-10-14 | minor | 21 Sony and Leica models verified (258 models, 18%); headline numbers unchanged |
@@ -187,7 +191,10 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| 2026-10-14 | minor | 17 uncompressed Olympus and Samsung models verified on one CC0 file each (254 models verified, 18%); headline numbers unchanged |
| 2026-10-12 | minor | Mamiya MEF decoded and imported: ZD verified (241); headline numbers unchanged |
| 2026-10-12 | minor | Epson ERF decoded: 3 more verified models (240); headline numbers unchanged |
| 2026-10-12 | minor | Georgian (`ka`) interface language added (every catalog message) |
| 2026-10-14 | minor | Full-resolution zoom (gap 4) closed: soft proofing gets zoom windows; headline numbers unchanged |
| 2026-10-12 | minor | UI/UX remaining 40–70 h → 34–58 h (accessibility audit landed); headline numbers unchanged |
| 2026-10-14 | minor | Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277); headline numbers unchanged |
| 2026-10-12 | minor | 22 more CR3 bodies verified, EOS R6 Mark III white balance: RAW decoding 77% → 83%, RAW ~56% → ~60%; mainstream 49% → 51%, essentials 64% → 65%; full unchanged at ~61% |
| 2026-10-12 | minor | 117 Nikon and Fujifilm bodies verified (354 models, 24%); headline numbers unchanged |
| 2026-10-11 | minor | EOS R5 Mark II CR3 verified: CR3 on four verified bodies, RAW decoding 76% → 77%; headline numbers unchanged |
+2
View File
@@ -828,6 +828,8 @@ fn snapshot(args: &[String]) -> Result<(), String> {
// before the first frame can start background adapter discovery.
// This UI state is session-local: the CLI neither loads nor saves desktop ui.json.
app.ui.settings.gpu = false;
// as the desktop app opens it: an empty library on the grid, where Import is offered
lightcraft_ui_egui::panels::empty_library::open_on_empty_library(&mut app);
let mut h = Headless::new(app, size, scale);
let timeout = Duration::from_secs(60);
let mut shots = 0usize;
+42
View File
@@ -47,6 +47,48 @@ fn contact_sheet_exports_pdf_and_protects_originals() {
assert_eq!(std::fs::read(&out).unwrap(), prior, "failed export changed prior output");
}
#[test]
fn print_commands_chain_into_a_picture_package_pdf() {
let input = tmp("print-input.png");
gradient_png(&input);
let out = tmp("print.pdf");
let (ok, lines, err) = run_cli(
&[
"--import",
input.to_str().unwrap(),
"print.set",
r#"layout={"style":"picturePackage","page":{"paper":"4x6","orientation":"landscape"}}"#,
r#"image={"zoomToFill":true,"borderEnabled":true,"borderWidth":0.05}"#,
"job={\"ppi\":72}",
"print.cell.add",
"width=1.5",
"height=1",
"print.cell.add",
"width=1.5",
"height=1",
"print.layout.autoLayout",
"print.exportPdf",
&format!("path={}", out.display()),
],
None,
);
assert!(ok, "{err}: {lines:?}");
let export = lines.last().unwrap();
assert_eq!((export["result"]["pages"].as_u64(), export["result"]["photos"].as_u64()), (Some(1), Some(1)));
let bytes = std::fs::read(&out).unwrap();
assert!(bytes.starts_with(b"%PDF-"));
let text = String::from_utf8_lossy(&bytes);
let at = text.find("/MediaBox [").unwrap() + "/MediaBox [".len();
let nums: Vec<f64> = text[at..].split(']').next().unwrap().split_whitespace().map(|v| v.parse().unwrap()).collect();
assert_eq!((nums[2], nums[3]), (432.0, 288.0), "6 x 4 in");
// a bad setting fails the run and writes nothing new
let before = std::fs::read(&out).unwrap();
let (ok, _, _) =
run_cli(&["--import", input.to_str().unwrap(), "print.set", "job={\"ppi\":5}", "print.exportPdf", &format!("path={}", out.display())], None);
assert!(!ok);
assert_eq!(std::fs::read(&out).unwrap(), before);
}
fn tmp(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lightcraft-cli-test-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
+4
View File
@@ -48,3 +48,7 @@ muda = { workspace = true }
objc2 = { workspace = true }
objc2-app-kit = { workspace = true }
objc2-foundation = { workspace = true }
[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
lightcraft-testkit = { workspace = true }
+5
View File
@@ -978,6 +978,11 @@ fn main() -> eframe::Result {
app.notices.extend(launch_notices);
app.notices.extend(window_notice);
app.gpu_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() {
lightcraft_ui_egui::panels::empty_library::open_on_empty_library(&mut app);
}
// what's on disk now: only changes are written
let writer = PrefsWriter {
path: if in_memory { None } else { prefs_path() },
+2 -2
View File
@@ -278,11 +278,11 @@ mod tests {
..wgpu::InstanceDescriptor::new_without_display_handle()
});
let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else {
eprintln!("no GPU adapter: skipped");
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
return;
};
let Ok((device, _queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else {
eprintln!("no GPU device: skipped");
lightcraft_testkit::skip!(Gpu, "no GPU device");
return;
};
install_error_handler(&device);
+5
View File
@@ -15,6 +15,9 @@ covers a whole directory), or if a licence file referenced in the Licence column
| `assets/camera-profiles/ILCA-99M2.json` | Sony ILCA-99M2 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by @PiMinusMax | original work: fitted by `lightcraft-cli calibrate` to 144 usable ILCA-99M2 ARWs (of 150, seven shooting days, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-11 | none |
| `assets/camera-profiles/ILCE-7CR.json` | Sony ILCE-7CR camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by @AlexChambers | original work: fitted by `lightcraft-cli calibrate` to 125 usable ILCE-7CR ARWs (of 131, September 2025 to September 2026, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-09 | none |
| `assets/camera-profiles/X-H2S.json`, `assets/camera-profiles/X-T4.json` | Fujifilm camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by Sebastian Pfluegelmeier | original work: fitted by `lightcraft-cli calibrate` to 201 X-H2S and 545 X-T4 RAFs and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-08 | none |
| `assets/camera-profiles/NIKON_Z_6_2.json` | Nikon Z 6II camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 296 usable Z 6II NEFs of my own (of 299, 2024 to 2026, Standard and Auto picture controls; NIKKOR Z 20mm f/1.8 S, Z 24-70mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_Z_8.json` | Nikon Z 8 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 261 usable Z 8 NEFs of my own (of 278, 2023 and 2026, nearly all Standard picture control, lossless 14-bit; NIKKOR Z 24-120mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix |
| `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none |
| `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a |
@@ -29,6 +32,8 @@ covers a whole directory), or if a licence file referenced in the Licence column
| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular | The Noto Project Authors (Arabic and Thai); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-<family>.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the manifest fonts (all official releases); the web build embeds BIZ UDPGothic Regular and Noto Sans Thai Regular and ships Noto Sans CJK SC Regular as a separate font file |
| `crates/ui-egui/locales/uk.json`, `crates/ui-egui/locales/uk-formats.json` | Ukrainian interface catalogs | @dmatviichuk with Codex; PhotoCraft, FilmCraft and VectorCraft translation contributors for reused labels | original translations from English source; 337 initial English-key matches reviewed from [PhotoCraft 69c41f3](https://github.com/storytold/photocraft/blob/69c41f3523e147eb215da8c7b4c29b18b35d1c63/crates/ui-egui/src/i18n/uk.tsv), [FilmCraft 4854c27](https://github.com/storytold/filmcraft/blob/4854c277536fe8118257362304b6a7d82d8e704b/crates/ui-egui/src/i18n/uk.tsv), [VectorCraft 4b44265](https://github.com/storytold/vectorcraft/blob/4b44265965fdd6ffedfd6182a892c1a6c360d344/crates/ui-egui/src/i18n/uk.tsv) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-09 | adapted to LightCraft photo-development context, completed catalogs, reviewed spelling and placeholders |
| `crates/ui-egui/locales/cs.json`, `crates/ui-egui/locales/cs-formats.json` | Czech interface catalogs | @Losminek with AI assistance (Codex) | original work: translations of English source phrases, reviewed against the app UI conventions; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-11 | catalog coverage, Czech dates and count-neutral wording; independent scope/terminology review; native-speaker proofreading pending |
| `crates/ui-egui/locales/it.json`, `crates/ui-egui/locales/it-formats.json` | Italian interface catalogs | @GabrielePecchioli with Claude Code; PhotoCraft, VectorCraft, PdfCraft and WordCraft translation contributors for reused labels | original translations from English source; 410 initial English-key matches reviewed from [PhotoCraft da3da09](https://github.com/storytold/photocraft/blob/da3da0942c14c1159f40c652afcf33584332c733/crates/ui-egui/src/i18n/it.tsv), [VectorCraft 5432821](https://github.com/storytold/vectorcraft/blob/543282148007bcb5633c493a5374cd26b0339c8d/crates/ui-egui/src/i18n/it.tsv), [PdfCraft e8e275c](https://github.com/storytold/pdfcraft/blob/e8e275cbd40ccd0dc6b56f82b16a575571043702/crates/ui-egui/src/i18n/it.tsv) and the Italian WordCraft catalog ([storytold/wordcraft#598](https://github.com/storytold/wordcraft/pull/598)); 46 of them retranslated where the sibling's meaning didn't fit a photo app | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-12 | adapted to LightCraft photo-development context, count-neutral labels for Italian plural agreement, reviewed placeholders |
| `crates/ui-egui/locales/ka.json`, `crates/ui-egui/locales/ka-formats.json` | Georgian interface catalogs | Davit Matchakhelidze with Claude; WordCraft, GridCraft, PhotoCraft, FilmCraft and VectorCraft Georgian catalogs for reused labels | original translations from the English source (meaning-based, no vendor localization used); 450 English-key matches reused from the sibling Craft apps' Georgian catalogs | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-12 | adapted to LightCraft photo-library and raw-development context; count-neutral numerals; placeholders checked |
Notes
- Fonts authored or published by Adobe (Source Sans/Serif/Code, Source Han, …) are not used, even though some are
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+12
View File
@@ -45,3 +45,15 @@ sync_github_name = true
[people.Silvertree2010]
display_name = "Netter"
sync_github_name = false
[people.nledford]
real_name = "Nathaniel Ledford"
[people.marcoarnulfo]
real_name = "Marco Arnulfo"
display_name = "Marco Arnulfo"
sync_github_name = false
[people.egegl]
real_name = "Ege Gursel"
sync_github_name = true
@@ -0,0 +1,8 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc b91df6f4f23ec90cae3c0fb934b04b806181b61570f00ba25826e2232b7e1932 # shrinks to steps = [(3, 0, 0, false)]
cc b11415bdf5e4133b65e00645d4051129c71bf927747d6384aa50107440e92e07 # shrinks to steps = [(0, 10, 166, false), (7, 1, 0, false), (1, 14, 0, false)]
+12 -1
View File
@@ -49,7 +49,9 @@ pub fn shift_iso(iso: &str, secs: i64) -> Option<String> {
if !(first..=last).contains(&t) {
return None;
}
let tail = iso.trim().get(19..).unwrap_or("");
let iso = iso.trim();
// the seconds are optional (`10:00+02:00`): without them the tail starts right after the minutes
let tail = iso.get(if iso.get(16..17) == Some(":") { 19 } else { 16 }..).unwrap_or("");
Some(format!("{}{tail}", civil(t)))
}
@@ -222,6 +224,15 @@ mod tests {
assert_eq!(normalize_iso("2026-02-30"), None);
}
#[test]
fn shift_keeps_the_zone_of_a_time_without_seconds() {
assert_eq!(shift_iso("2026-01-01T10:00+02:00", 3600).as_deref(), Some("2026-01-01T11:00:00+02:00"));
assert_eq!(shift_iso("2026-01-01T10:00Z", 60).as_deref(), Some("2026-01-01T10:01:00Z"));
assert_eq!(shift_iso("2026-01-01T10:00", 3600).as_deref(), Some("2026-01-01T11:00:00"));
assert_eq!(shift_iso("2026-01-01T10:00:00.5-05:00", 3600).as_deref(), Some("2026-01-01T11:00:00.5-05:00"));
assert_eq!(iso_seconds("2026-01-01T10:00+02:00"), iso_seconds("2026-01-01T10:00"));
}
#[test]
fn runs_by_day_month_year_keep_stacks_together() {
let mut c = Catalog::new();
+101
View File
@@ -0,0 +1,101 @@
//! Lookups derived from the catalog's own data, so questions asked once per photo of a big library
//! don't scan a list each time: which stack a photo is in, whether a regular album holds it.
//!
//! They are never saved (the on-disk format is unchanged). Each is built on first use from what
//! the catalog holds, so a catalog read from a snapshot, replayed from the journal or cloned starts
//! without them and builds them when asked. Once built, [`crate::Catalog::apply`] keeps them up to
//! date: the ops that change stacks or album photos (`AddStack`, `RemoveStack`, `SetStack`,
//! `AddAlbum`, `RemoveAlbum`, `SetAlbumPhotos`) update them as they apply, inverses and the
//! rollback of a failed batch included, as those are ops too.
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use crate::{AlbumId, Catalog, PhotoId, StackId};
#[derive(Default)]
pub(crate) struct Indexes {
/// Photo → the stack it is in; `None` when the catalog was read with a photo in two stacks
/// (only a hand-edited file can hold that: ops refuse it), where a scan says which one counts.
stacks: OnceLock<Option<HashMap<PhotoId, StackId>>>,
/// Album → its photos (regular albums; a smart album's list is empty).
albums: OnceLock<HashMap<AlbumId, HashSet<PhotoId>>>,
}
/// A copy builds its own when asked (copies are made to be saved, not queried).
impl Clone for Indexes {
fn clone(&self) -> Self {
Indexes::default()
}
}
/// Derived from the rest of the catalog: two catalogs with the same data are equal whatever was
/// built.
impl PartialEq for Indexes {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl std::fmt::Debug for Indexes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let stacks = self.stacks.get().map(|m| m.as_ref().map(HashMap::len));
f.debug_struct("Indexes").field("stacks", &stacks).field("albums", &self.albums.get().map(HashMap::len)).finish()
}
}
impl Indexes {
/// Stack `id` held `old` and holds `new` now (empty: it was added, or is gone).
pub(crate) fn stack_changed(&mut self, id: StackId, old: &[PhotoId], new: &[PhotoId]) {
let Some(Some(m)) = self.stacks.get_mut() else { return };
for p in old {
if m.get(p) == Some(&id) {
m.remove(p);
}
}
for p in new {
m.insert(*p, id);
}
}
/// Album `id` holds `photos` now (`None`: it is gone).
pub(crate) fn album_changed(&mut self, id: AlbumId, photos: Option<&[PhotoId]>) {
let Some(m) = self.albums.get_mut() else { return };
match photos {
Some(photos) => {
m.insert(id, photos.iter().copied().collect());
}
None => {
m.remove(&id);
}
}
}
}
impl Catalog {
/// The stack photo `photo` is in, by the index (built on first use).
pub(crate) fn stack_id_of(&self, photo: PhotoId) -> Option<StackId> {
let m = self.index.stacks.get_or_init(|| {
let mut m = HashMap::new();
for s in self.stacks.values() {
for p in &s.photos {
if m.insert(*p, s.id).is_some_and(|other| other != s.id) {
return None;
}
}
}
Some(m)
});
match m {
Some(m) => m.get(&photo).copied(),
// in id order, the first stack listing the photo has it
None => self.stacks.values().find(|s| s.photos.contains(&photo)).map(|s| s.id),
}
}
/// Whether album `album`'s own list holds `photo`, by the index (built on first use).
pub(crate) fn album_lists(&self, album: AlbumId, photo: PhotoId) -> bool {
let m = self.index.albums.get_or_init(|| self.albums.values().map(|a| (a.id, a.photos.iter().copied().collect())).collect());
m.get(&album).is_some_and(|s| s.contains(&photo))
}
}
+11 -4
View File
@@ -271,7 +271,7 @@ fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> {
const START: &[u8] = b"{\"seq\":";
(1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| {
let rec = std::str::from_utf8(&line[i..]).ok().map(|l| l.trim_end_matches('\r')).and_then(decode_record)?;
(rec.0 <= last + 1).then_some((i, rec))
(rec.0 <= last.saturating_add(1)).then_some((i, rec))
})
}
@@ -298,6 +298,9 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io
Ok(SnapshotTiming { serialize_ms, write_sync_ms: (ms_since(t0) - serialize_ms).max(0.0), bytes, ..Default::default() })
}
/// The highest `seq` a snapshot may hold; beyond it the counter is treated as corrupt, far from overflow.
const MAX_SEQ: u64 = u64::MAX / 2;
/// Just the identification of `catalog.snap` (read before the catalog itself).
#[derive(serde::Deserialize)]
struct SnapHeader {
@@ -331,6 +334,10 @@ impl Journal {
return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version)));
}
let s: SnapFile = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?;
// a seq this high can't come from real use; the next record's seq would wrap
if s.seq > MAX_SEQ {
return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: seq {} is out of range", s.seq)));
}
let mut catalog = s.catalog;
report.repaired = catalog.repair();
for r in &report.repaired {
@@ -392,7 +399,7 @@ impl Journal {
let _ = op;
report.stale += 1;
}
Some((seq, op)) if seq == j.seq + 1 => {
Some((seq, op)) if j.seq.checked_add(1) == Some(seq) => {
if catalog.apply(op).is_err() {
report.failed += 1;
} else {
@@ -476,7 +483,7 @@ impl Journal {
let mut buf = String::new();
let mut seq = self.seq;
for op in ops {
seq += 1;
seq = seq.checked_add(1).ok_or_else(|| CatalogError::Corrupt(format!("{LOG}: op counter overflow")))?;
buf.push_str(&encode_record(seq, op));
buf.push('\n');
}
@@ -527,7 +534,7 @@ impl Journal {
log::warn!("catalog: background snapshot failed ({e}); writing one now");
}
let t0 = web_time::Instant::now();
let seq = self.seq + unlogged;
let seq = self.seq.checked_add(unlogged).ok_or_else(|| CatalogError::Corrupt(format!("{SNAPSHOT}: op counter overflow")))?;
let mut timing = match write_snapshot(self.store.as_mut(), seq, catalog) {
Ok(t) => t,
Err(e) => {
+40 -8
View File
@@ -15,6 +15,7 @@
pub mod dates;
pub mod folders;
mod index;
pub mod journal;
pub mod keywords;
pub mod local;
@@ -289,6 +290,9 @@ pub struct Catalog {
/// Which photos the latest ops touched ([`Catalog::touched_since`]).
#[serde(skip)]
changes: Changes,
/// Lookups derived from the above (never saved), see [`index`].
#[serde(skip)]
index: index::Indexes,
}
/// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a
@@ -435,13 +439,18 @@ impl Catalog {
/// no smart album).
pub fn album_contains(&self, id: AlbumId, p: &Photo) -> bool {
match self.albums.get(&id) {
// guarded: a smart album testing smart albums can't loop or recurse without end
Some(Album { smart: Some(rules), .. }) => !p.deleted && rules::smart_album_holds(id, p.id, || rules.matches(p, self)),
Some(a) => a.photos.contains(&p.id),
Some(Album { smart: Some(rules), .. }) => self.smart_album_has(id, rules, &rules.prepare_one(), p),
Some(a) => self.album_lists(a.id, p.id),
None => false,
}
}
/// Whether smart album `id` with `rules` (as [`Filter::prepare`]d) holds `p`.
fn smart_album_has(&self, id: AlbumId, rules: &Filter, prepared: &query::Prepared, p: &Photo) -> bool {
// guarded: a smart album testing smart albums can't loop or recurse without end
!p.deleted && rules::smart_album_holds(id, p.id, || rules.matches_in(p, self, prepared))
}
/// Whether smart album `from` tests `to`, directly or through the smart albums it tests (the
/// rules of `from` would then change when those of `to` do). Loops in saved rules end the
/// search, they don't repeat it.
@@ -489,7 +498,10 @@ impl Catalog {
/// The photos of an album: the stored list, or a smart album's current matches (id order).
pub fn album_photos(&self, id: AlbumId) -> Vec<PhotoId> {
match self.albums.get(&id) {
Some(Album { smart: Some(_), .. }) => self.photos.values().filter(|p| self.album_contains(id, p)).map(|p| p.id).collect(),
Some(Album { smart: Some(rules), .. }) => {
let prepared = rules.prepare();
self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).map(|p| p.id).collect()
}
Some(a) => a.photos.clone(),
None => Vec::new(),
}
@@ -499,7 +511,10 @@ impl Catalog {
pub fn album_count(&self, id: AlbumId) -> usize {
match self.albums.get(&id) {
// counted in place: no id list is built just for its length
Some(Album { smart: Some(_), .. }) => self.photos.values().filter(|p| self.album_contains(id, p)).count(),
Some(Album { smart: Some(rules), .. }) => {
let prepared = rules.prepare();
self.photos.values().filter(|p| self.smart_album_has(id, rules, &prepared, p)).count()
}
Some(a) => a.photos.iter().filter(|p| self.photos.get(p).is_some_and(|p| !p.deleted)).count(),
None => 0,
}
@@ -750,6 +765,7 @@ impl Catalog {
}
let id = album.id;
self.next_album = self.next_album.max(id.0.saturating_add(1));
self.index.album_changed(id, Some(&album.photos));
self.albums.insert(id, album);
Op::RemoveAlbum { id }
}
@@ -758,6 +774,7 @@ impl Catalog {
return Err(CatalogError::Invalid("folder is not empty".into()));
}
let a = self.albums.remove(&id).ok_or(CatalogError::NoAlbum(id))?;
self.index.album_changed(id, None);
Op::AddAlbum { album: a }
}
Op::RenameAlbum { id, name } => {
@@ -797,13 +814,16 @@ impl Catalog {
Op::SetAlbumOrder { id, order: std::mem::replace(&mut a.order, order) }
}
Op::SetAlbumPhotos { id, photos } => {
let a = self.album_mut(id)?;
// the field, not `album_mut`: the index is updated while the album is borrowed
let a = self.albums.get_mut(&id).ok_or(CatalogError::NoAlbum(id))?;
if (a.folder || a.smart.is_some()) && !photos.is_empty() {
return Err(CatalogError::Invalid(
if a.folder { "folders can't hold photos" } else { "smart albums update automatically" }.into(),
));
}
Op::SetAlbumPhotos { id, photos: std::mem::replace(&mut a.photos, photos) }
let old = std::mem::replace(&mut a.photos, photos);
self.index.album_changed(id, Some(&a.photos));
Op::SetAlbumPhotos { id, photos: old }
}
Op::SetAlbumCover { id, cover } => {
let a = self.album_mut(id)?;
@@ -824,11 +844,13 @@ impl Catalog {
self.validate_stack(stack.id, &stack.photos)?;
let id = stack.id;
self.next_stack = self.next_stack.max(id.0.saturating_add(1));
self.index.stack_changed(id, &[], &stack.photos);
self.stacks.insert(id, stack);
Op::RemoveStack { id }
}
Op::RemoveStack { id } => {
let s = self.stacks.remove(&id).ok_or(CatalogError::NoStack(id))?;
self.index.stack_changed(id, &s.photos, &[]);
Op::AddStack { stack: s }
}
Op::SetStack { id, photos, collapsed } => {
@@ -837,7 +859,9 @@ impl Catalog {
}
self.validate_stack(id, &photos)?;
let s = self.stacks.get_mut(&id).ok_or(CatalogError::NoStack(id))?;
let old = Op::SetStack { id, photos: std::mem::replace(&mut s.photos, photos), collapsed: s.collapsed };
let old_photos = std::mem::replace(&mut s.photos, photos);
self.index.stack_changed(id, &old_photos, &s.photos);
let old = Op::SetStack { id, photos: old_photos, collapsed: s.collapsed };
s.collapsed = collapsed;
old
}
@@ -1075,6 +1099,10 @@ impl Catalog {
self.next_album = self.next_album.max(album);
self.next_stack = self.next_stack.max(stack);
}
if !changed.is_empty() {
// stacks and albums changed outside `apply`: the lookups are built again when asked
self.index = index::Indexes::default();
}
changed
}
@@ -1124,6 +1152,8 @@ mod tests_folders;
#[cfg(test)]
mod tests_format_version;
#[cfg(test)]
mod tests_index;
#[cfg(test)]
mod tests_journal;
#[cfg(test)]
mod tests_local;
@@ -1132,4 +1162,6 @@ mod tests_lock;
#[cfg(test)]
mod tests_repair;
#[cfg(test)]
mod tests_scale;
#[cfg(test)]
mod tests_torn_append;
+6
View File
@@ -199,6 +199,11 @@ pub struct Meta {
/// Left out of the catalog JSON when empty (most photos), so older catalogs read unchanged.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub regions: Vec<lightcraft_meta::Region>,
/// Where the camera focused (read from the file's maker notes at import or Reload from Disk; Sony
/// bodies whose files have been checked), on the upright (EXIF-oriented) photo. Read-only: never
/// written to XMP. Left out of the catalog JSON when unknown, so older catalogs read unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub focus: Option<lightcraft_meta::FocusPoint>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -638,6 +643,7 @@ mod edited_tests {
("NIKON CORPORATION NIKON D850", "NEF", false),
("Canon Canon EOS 5D Mark III", "CR2", false),
("Canon Canon EOS R6m2", "CR3", false),
("Canon Canon EOS R6 Mark II", "CR3", false),
("Canon Canon EOS R7", "CR3", true),
("FUJIFILM X-T4", "RAF", false),
("ILCE-7M3", "ARW", false),
+52 -20
View File
@@ -135,6 +135,12 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 {
mix64(mix64(seed) ^ id.0)
}
/// What [`Filter::prepare`] works out once for a pass over many photos.
pub(crate) struct Prepared {
root: Option<String>,
only: Option<std::collections::HashSet<PhotoId>>,
}
fn token_matches(p: &Photo, tok: &str) -> bool {
let t = tok.to_lowercase();
if let Some((field, val)) = t.split_once(':') {
@@ -151,13 +157,20 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
Some((_, v)) => (x - v).abs() < 1e-9,
None => false,
};
// Fields stored as `f32` compare at f32 precision: 2.8f32 widened to f64 is not 2.8.
let cmp32 = |x: f32, s: &str| match num(s) {
Some(('>', v)) => x > v as f32,
Some(('<', v)) => x < v as f32,
Some((_, v)) => x == v as f32,
None => false,
};
return match field {
"rating" | "stars" => cmp(p.rating as f64, val),
"flag" => Flag::parse(val) == Some(p.flag),
"label" | "color" => p.label.is_some_and(|l| format!("{l:?}").eq_ignore_ascii_case(val)),
"iso" => p.meta.iso.is_some_and(|i| cmp(i as f64, val)),
"f" | "aperture" => p.meta.aperture.is_some_and(|a| cmp(a as f64, val)),
"focal" => p.meta.focal_mm.is_some_and(|a| cmp(a as f64, val)),
"f" | "aperture" => p.meta.aperture.is_some_and(|a| cmp32(a, val)),
"focal" => p.meta.focal_mm.is_some_and(|a| cmp32(a, val)),
"camera" => p.meta.camera.to_lowercase().contains(val),
"lens" => p.meta.lens.to_lowercase().contains(val),
"keyword" | "kw" => p.meta.keywords.iter().any(|k| crate::keywords::is_under(k, val)),
@@ -167,11 +180,18 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
"date" => p.captured.as_deref().is_some_and(|c| c.starts_with(val)),
"copy" | "virtual" => (val == "true" || val == "yes") == p.copy_of.is_some(),
"name" | "file" => p.file_name.to_lowercase().contains(val),
_ => false,
// Not a known field: the colon is part of a plain word ("10:30", "Re:").
_ => text_matches(p, &t),
};
}
text_matches(p, &t)
}
/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, location,
/// format or a keyword of `p`.
fn text_matches(p: &Photo, t: &str) -> bool {
let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format];
hay.iter().any(|h| h.to_lowercase().contains(&t)) || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(&t))
hay.iter().any(|h| h.to_lowercase().contains(t)) || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t))
}
/// Whether `p` has a named face region called `name` (case-insensitive).
@@ -257,7 +277,18 @@ impl Filter {
}
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
self.matches_in(p, cat, self.library_root().as_deref())
self.matches_in(p, cat, &self.prepare_one())
}
/// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed).
pub(crate) fn prepare_one(&self) -> Prepared {
Prepared { root: self.library_root(), only: None }
}
/// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than
/// once per photo: the library folder's identity and the `only` ids as a set.
pub(crate) fn prepare(&self) -> Prepared {
Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()) }
}
/// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice.
@@ -267,9 +298,9 @@ impl Filter {
self.library_folder.as_deref().filter(|d| !d.trim().is_empty()).map(folder_key)
}
/// [`Filter::matches`] with the library folder already turned into its identity, so a query
/// over a big library does that once, not once per photo.
fn matches_in(&self, p: &Photo, cat: &Catalog, root: Option<&str>) -> bool {
/// [`Filter::matches`] with what [`Filter::prepare`] works out done already, so a query over a
/// big library does that once, not once per photo.
pub(crate) fn matches_in(&self, p: &Photo, cat: &Catalog, prepared: &Prepared) -> bool {
if p.deleted != self.deleted {
return false;
}
@@ -308,7 +339,7 @@ impl Filter {
if !self.labels.is_empty() && !p.label.is_some_and(|l| self.labels.contains(&l)) {
return false;
}
if !self.only.is_empty() && !self.only.contains(&p.id) {
if !self.only.is_empty() && !prepared.only.as_ref().map_or_else(|| self.only.contains(&p.id), |only| only.contains(&p.id)) {
return false;
}
if let Some(want) = &self.merged {
@@ -348,7 +379,7 @@ impl Filter {
{
return false;
}
if let Some(root) = root
if let Some(root) = prepared.root.as_deref()
&& !photo_in_root(p, root)
{
return false;
@@ -398,12 +429,13 @@ impl Catalog {
/// album's rules, the filter bar), as long as they are still where the view looks (`within`: in the library,
/// the album, the folder; not deleted).
pub fn query_keeping(&self, filter: &Filter, sort: &Sort, keep: &std::collections::HashSet<PhotoId>, within: &Filter) -> Vec<PhotoId> {
let root = filter.library_root();
let within_root = within.library_root();
let prepared = filter.prepare();
// `within` only decides for the few kept photos: worked out per photo, not hashed
let within_prepared = within.prepare_one();
let mut v: Vec<&Photo> = self
.photos()
.map(|p| p.as_ref())
.filter(|p| filter.matches_in(p, self, root.as_deref()) || (keep.contains(&p.id) && within.matches_in(p, self, within_root.as_deref())))
.filter(|p| filter.matches_in(p, self, &prepared) || (keep.contains(&p.id) && within.matches_in(p, self, &within_prepared)))
.collect();
v.sort_by(|a, b| sort.order(a, b));
v.into_iter().map(|p| p.id).collect()
@@ -417,11 +449,11 @@ impl Catalog {
pub fn follow(&self, was: &[PhotoId], touched: &[PhotoId], filter: &Filter, sort: &Sort, within: Option<&Filter>) -> Vec<PhotoId> {
let listed: std::collections::HashSet<PhotoId> = was.iter().copied().filter(|id| touched.binary_search(id).is_ok()).collect();
let mut ids: Vec<PhotoId> = was.iter().copied().filter(|id| !listed.contains(id)).collect();
let (root, within_root) = (filter.library_root(), within.and_then(Filter::library_root));
let (prepared, within_prepared) = (filter.prepare_one(), within.map(Filter::prepare_one));
for id in touched {
let Some(p) = self.photo(*id) else { continue };
let kept = within.is_some_and(|w| listed.contains(id) && w.matches_in(p, self, within_root.as_deref()));
if filter.matches_in(p, self, root.as_deref()) || kept {
let kept = within.zip(within_prepared.as_ref()).is_some_and(|(w, wp)| listed.contains(id) && w.matches_in(p, self, wp));
if filter.matches_in(p, self, &prepared) || kept {
// (the list is in order without the touched photos, and stays so as each is put back)
let at = ids.partition_point(|other| self.photo(*other).is_some_and(|o| sort.order(o, p).is_lt()));
ids.insert(at, *id);
@@ -432,8 +464,8 @@ impl Catalog {
/// How many photos match `filter`: [`Catalog::query`]'s length without its sorting.
pub fn count(&self, filter: &Filter) -> usize {
let root = filter.library_root();
self.photos().filter(|p| filter.matches_in(p, self, root.as_deref())).count()
let prepared = filter.prepare();
self.photos().filter(|p| filter.matches_in(p, self, &prepared)).count()
}
/// Year → month → day counts for the "By Date" section (newest first).
@@ -489,8 +521,8 @@ impl Catalog {
pub fn people_in(&self, filter: &Filter) -> Vec<Person> {
let filter = Filter { person: None, ..filter.clone() };
let mut m: std::collections::HashMap<String, (Person, f64)> = Default::default();
let root = filter.library_root();
for p in self.photos().filter(|p| filter.matches_in(p, self, root.as_deref())) {
let prepared = filter.prepare();
for p in self.photos().filter(|p| filter.matches_in(p, self, &prepared)) {
let mut seen: Vec<String> = Vec::new();
for r in p.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) {
let Some(name) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue };
+33 -4
View File
@@ -598,6 +598,35 @@ pub fn now() -> String {
}
}
/// A flag as rules name it (its variant, lower case), without building a string per photo.
fn flag_name(f: crate::Flag) -> &'static str {
match f {
crate::Flag::None => "none",
crate::Flag::Pick => "pick",
crate::Flag::Reject => "reject",
}
}
/// A colour label's colour as rules name it (lower case).
fn label_colour(l: crate::ColorLabel) -> &'static str {
match l {
crate::ColorLabel::Red => "red",
crate::ColorLabel::Yellow => "yellow",
crate::ColorLabel::Green => "green",
crate::ColorLabel::Blue => "blue",
crate::ColorLabel::Purple => "purple",
}
}
/// A media kind as rules name it (lower case).
fn kind_name(k: crate::MediaKind) -> &'static str {
match k {
crate::MediaKind::Image => "image",
crate::MediaKind::Raw => "raw",
crate::MediaKind::Video => "video",
}
}
fn lower(v: &Value) -> String {
match v {
Value::String(s) => s.trim().to_lowercase(),
@@ -778,16 +807,16 @@ impl Rule {
match field {
"rating" => num_op(op, Some(p.rating as f64), value),
"flag" => {
let f = format!("{:?}", p.flag).to_lowercase();
let f = flag_name(p.flag);
(f == want || (want == "picked" && f == "pick") || (want == "rejected" && f == "reject")) == (op == "is")
}
"label" => {
let l = p.label.map(|l| format!("{l:?}").to_lowercase()).unwrap_or_else(|| "none".into());
let l = p.label.map_or("none", label_colour);
// custom label names count too
let named = p.label.is_some_and(|l| cat.label_name(l).to_lowercase() == want);
let named = p.label.is_some_and(|l| cat.custom_label_name(l).map_or(label_colour(l) == want, |n| n.to_lowercase() == want));
(l == want || named) == (op == "is")
}
"kind" => (format!("{:?}", p.kind).to_lowercase() == want) == (op == "is"),
"kind" => (kind_name(p.kind) == want) == (op == "is"),
"edited" => yes(p.is_edited()),
"hasGps" => yes(m.gps.is_some()),
"virtualCopy" => yes(p.copy_of.is_some()),
+4 -3
View File
@@ -21,7 +21,7 @@ impl Catalog {
}
/// The stack a photo belongs to.
pub fn stack_of(&self, photo: PhotoId) -> Option<&Stack> {
self.stacks.values().find(|s| s.photos.contains(&photo))
self.stack_id_of(photo).and_then(|id| self.stacks.get(&id))
}
/// Photo → (stack, position in the stack), for every stacked photo.
pub fn stack_index(&self) -> HashMap<PhotoId, (StackId, usize)> {
@@ -41,7 +41,7 @@ impl Catalog {
return Err(CatalogError::NoPhoto(*p));
}
}
if self.stacks.values().any(|s| s.id != id && s.photos.iter().any(|p| seen.contains(p))) {
if photos.iter().any(|p| self.stack_id_of(*p).is_some_and(|s| s != id)) {
return Err(CatalogError::Invalid("a photo can be in only one stack".into()));
}
Ok(())
@@ -294,7 +294,8 @@ pub fn iso_seconds(s: &str) -> Option<i64> {
if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
return None;
}
let (hh, mm, ss) = if s.len() >= 16 { (num(11, 13)?, num(14, 16)?, num(17, 19).unwrap_or(0)) } else { (0, 0, 0) };
let (hh, mm, ss) =
if s.len() >= 16 { (num(11, 13)?, num(14, 16)?, if s.get(16..17) == Some(":") { num(17, 19).unwrap_or(0) } else { 0 }) } else { (0, 0, 0) };
// days from civil (proleptic Gregorian)
let y2 = if m <= 2 { y - 1 } else { y };
let era = y2.div_euclid(400);
+64
View File
@@ -123,6 +123,48 @@ fn filter_search_sort() {
assert_eq!(c.keywords(), vec![("ocean".to_string(), 1), ("summer".to_string(), 1)]);
}
/// A search word with a colon whose left part is not a known field ("10:30", "Re:") is plain
/// text, not a fielded token that matches nothing.
#[test]
fn free_text_with_a_colon_searches_the_text_fields() {
let mut c = Catalog::new();
let a = photo(&mut c, "meeting.jpg", "2026-05-01T10:00:00");
let _b = photo(&mut c, "other.jpg", "2026-04-01T10:00:00");
let mut m = c.photo(a).unwrap().meta.clone();
m.caption = "Meeting at 10:30 with Re: notes".into();
m.iso = Some(1600);
c.apply(Op::SetMeta { id: a, meta: Box::new(m) }).unwrap();
let q = |text: &str| c.query(&Filter { text: text.into(), ..Default::default() }, &Sort::default());
assert_eq!(q("meeting"), vec![a]);
assert_eq!(q("10:30"), vec![a], "a free-text token with a colon");
assert_eq!(q("re:"), vec![a]);
assert_eq!(q("RE: notes"), vec![a], "case-insensitive, one token per word");
assert_eq!(q("iso:>800"), vec![a], "known fields stay fielded");
assert_eq!(q("iso:>2000"), Vec::<PhotoId>::new());
assert_eq!(q("11:45"), Vec::<PhotoId>::new(), "an unknown field matching no text finds nothing");
}
/// `f:`/`aperture:` and `focal:` are stored as `f32`; a typed value that isn't exact in binary
/// (2.8, 5.6) must still match, and `<`/`>` must not count the photo's own value.
#[test]
fn search_tokens_match_f32_aperture_and_focal() {
let mut c = Catalog::new();
let a = photo(&mut c, "a.jpg", "2026-05-01T10:00:00");
let mut m = c.photo(a).unwrap().meta.clone();
m.aperture = Some(2.8);
m.focal_mm = Some(5.6);
c.apply(Op::SetMeta { id: a, meta: Box::new(m) }).unwrap();
let q = |t: &str| c.query(&Filter { text: t.into(), ..Default::default() }, &Sort::default());
assert_eq!(q("f:2.8"), vec![a], "f:2.8");
assert_eq!(q("aperture:=2.8"), vec![a], "aperture:=2.8");
assert_eq!(q("focal:5.6"), vec![a], "focal:5.6");
assert!(q("f:2.9").is_empty(), "f:2.9");
assert!(q("f:<2.8").is_empty(), "f:<2.8");
assert!(q("f:>2.8").is_empty(), "f:>2.8");
assert!(q("focal:<5.6").is_empty(), "focal:<5.6");
assert_eq!(q("f:>2.7"), vec![a], "f:>2.7");
}
/// A `captured` string that is not ASCII (the Lightroom importer copies `captureTime` into an
/// `AddPhoto` op verbatim, and a JSON snapshot is valid UTF-8 whatever it holds) must not be
/// sliced on a byte index in `date_groups`: grouping counts the well-formed dates and ignores
@@ -425,6 +467,28 @@ fn empty_regions_are_not_serialized_and_default_when_missing() {
assert_eq!(back, with);
}
/// The camera's focus point is optional camera data: absent from the catalog JSON when unknown (so a
/// catalog from before it existed reads with none, and writes the same), kept exactly when known.
#[test]
fn focus_point_is_not_serialized_when_unknown_and_round_trips() {
let m = Meta { camera: "SONY ILCE-1".into(), ..Default::default() };
let v = serde_json::to_value(&m).unwrap();
assert!(v.get("focus").is_none(), "{v}");
let back: Meta = serde_json::from_value(v).unwrap();
assert!(back.focus.is_none());
let mut with = m.clone();
with.focus = Some(lightcraft_meta::FocusPoint {
rect: lightcraft_meta::Rect { x0: 0.36, y0: 0.33, x1: 0.38, y1: 0.36 },
mode: Some("AF-C".into()),
area: Some("Wide".into()),
tracking: None,
});
let json = serde_json::to_string(&with).unwrap();
assert!(json.contains("\"focus\"") && !json.contains("tracking"), "{json}");
let back: Meta = serde_json::from_str(&json).unwrap();
assert_eq!(back, with);
}
// ---- random sort: Given a seed, the order is a stable, reproducible shuffle of the matching photos
fn many(c: &mut Catalog, n: usize) -> Vec<PhotoId> {
+211
View File
@@ -0,0 +1,211 @@
//! The derived indexes ([`crate::index`]) answer as a scan of the catalog would, through every op,
//! inverse, failed batch, snapshot, replay and clone; and the faster query paths give the same
//! results as before.
use proptest::prelude::*;
use super::*;
const PHOTOS: u64 = 8;
fn library() -> Catalog {
let mut c = Catalog::new();
for i in 0..PHOTOS {
let p = Photo::new(PhotoId(i + 1), Source::Demo { scene: 1 }, &format!("p{i}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00");
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
}
c
}
/// What the indexes must say, worked out by scanning (as the catalog did before it had them).
fn scanned(c: &Catalog) -> (Vec<Option<StackId>>, Vec<Vec<bool>>) {
let photos: Vec<PhotoId> = (1..=PHOTOS + 1).map(PhotoId).collect();
let stacks = photos.iter().map(|p| c.stacks().find(|s| s.photos.contains(p)).map(|s| s.id)).collect();
let albums = (1..=4)
.map(|a| {
photos
.iter()
.map(|p| c.photo(*p).is_some() && c.album(AlbumId(a)).is_some_and(|al| al.smart.is_none() && al.photos.contains(p)))
.collect()
})
.collect();
(stacks, albums)
}
/// What the indexes say.
fn indexed(c: &Catalog) -> (Vec<Option<StackId>>, Vec<Vec<bool>>) {
let photos: Vec<PhotoId> = (1..=PHOTOS + 1).map(PhotoId).collect();
let stacks = photos.iter().map(|p| c.stack_of(*p).map(|s| s.id)).collect();
let albums = (1..=4)
.map(|a| {
photos
.iter()
.map(|p| c.album(AlbumId(a)).is_some_and(|al| al.smart.is_none()) && c.photo(*p).is_some_and(|ph| c.album_contains(AlbumId(a), ph)))
.collect()
})
.collect();
(stacks, albums)
}
/// Photo ids from bits (the extra id names a photo that isn't there: such ops fail).
fn ids(bits: u16) -> Vec<PhotoId> {
(0..=PHOTOS).filter(|i| bits & (1 << i) != 0).map(|i| PhotoId(i + 1)).collect()
}
fn op(c: &Catalog, kind: u8, n: u64, bits: u16, collapsed: bool) -> Op {
match kind % 8 {
0 => Op::AddStack { stack: Stack { id: StackId(n % 4 + 1), photos: ids(bits), collapsed } },
1 => Op::RemoveStack { id: StackId(n % 4 + 1) },
2 => Op::SetStack { id: StackId(n % 4 + 1), photos: ids(bits), collapsed },
3 => {
let mut a = Album::new(AlbumId(n % 4 + 1), "A");
a.photos = ids(bits);
Op::AddAlbum { album: a }
}
4 => Op::RemoveAlbum { id: AlbumId(n % 4 + 1) },
5 => Op::SetAlbumPhotos { id: AlbumId(n % 4 + 1), photos: ids(bits) },
// a batch whose last op fails half the time: what it did is rolled back
6 => Op::Batch {
ops: vec![
Op::SetAlbumPhotos { id: AlbumId(n % 4 + 1), photos: ids(bits) },
Op::SetStack { id: StackId(n % 4 + 1), photos: ids(bits.rotate_left(3)), collapsed },
Op::AddStack { stack: Stack { id: StackId(n % 4 + 1), photos: ids(!bits), collapsed } },
],
},
// as the engine deletes a photo: out of its albums and stacks too, in one batch
_ => c.delete_permanently_ops(PhotoId(n % (PHOTOS + 1) + 1)),
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn indexes_agree_with_a_scan(steps in proptest::collection::vec((0u8..8, 0u64..16, 0u16..512, any::<bool>()), 1..40)) {
let mut c = library();
let start = c.to_snapshot();
// built before the ops, so every op has to keep them up to date
prop_assert_eq!(indexed(&c), scanned(&c));
let mut log = String::new();
let mut inverses = Vec::new();
for (kind, n, bits, collapsed) in steps {
let op = op(&c, kind, n, bits, collapsed);
if let Ok(inv) = c.apply(op.clone()) {
log.push_str(&Catalog::op_to_log_line(&op));
inverses.push(inv);
}
prop_assert_eq!(indexed(&c), scanned(&c));
}
// a snapshot, a replayed journal and a clone build their own
let snap = Catalog::from_snapshot(&c.to_snapshot()).unwrap();
prop_assert_eq!(indexed(&snap), scanned(&c));
let mut replayed = Catalog::from_snapshot(&start).unwrap();
prop_assert_eq!(indexed(&replayed), scanned(&replayed));
replayed.replay(&log).unwrap();
prop_assert_eq!(indexed(&replayed), scanned(&c));
prop_assert_eq!(indexed(&c.clone()), scanned(&c));
prop_assert!(c.clone() == c, "the indexes don't take part in equality");
// undone step by step
for inv in inverses.into_iter().rev() {
c.apply(inv).unwrap();
prop_assert_eq!(indexed(&c), scanned(&c));
}
prop_assert!(c.stacks().next().is_none() && c.albums().next().is_none(), "all undone");
}
}
#[test]
fn a_photo_in_another_stack_is_refused_by_the_index() {
let mut c = library();
c.apply(Op::AddStack { stack: Stack { id: StackId(1), photos: vec![PhotoId(1), PhotoId(2)], collapsed: false } }).unwrap();
let e = c.apply(Op::AddStack { stack: Stack { id: StackId(2), photos: vec![PhotoId(2), PhotoId(3)], collapsed: false } }).unwrap_err();
assert_eq!(e, CatalogError::Invalid("a photo can be in only one stack".into()));
// its own stack may keep it
c.apply(Op::SetStack { id: StackId(1), photos: vec![PhotoId(2), PhotoId(1), PhotoId(3)], collapsed: true }).unwrap();
assert_eq!(c.stack_of(PhotoId(3)).map(|s| s.id), Some(StackId(1)));
}
/// The sort keys are worked out once per photo now; the order is the one the comparisons gave.
#[test]
fn sorted_queries_keep_their_order() {
let mut c = Catalog::new();
let names = ["b.jpg", "A.jpg", "a.jpg", "Été.jpg", "été.jpg", "C.JPG", "b.jpg"];
for (i, n) in names.iter().enumerate() {
let mut p = Photo::new(PhotoId(i as u64 + 1), Source::Demo { scene: 1 }, n, "JPEG", 60, 40, &format!("2026-01-0{}T00:00:00", 7 - i % 3));
p.captured = (i % 2 == 0).then(|| format!("2025-0{}-01T00:00:00", 1 + i % 4));
p.rating = (i % 3) as u8;
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
}
let all = Filter::default();
for key in [SortKey::CaptureDate, SortKey::ImportDate, SortKey::EditDate, SortKey::FileName, SortKey::Rating, SortKey::FileSize, SortKey::Random]
{
for ascending in [true, false] {
let sort = Sort { key, ascending, seed: 7, ..Default::default() };
// the comparison the query sorts by
let mut want: Vec<&Photo> = c.photos().map(|p| p.as_ref()).collect();
want.sort_by(|a, b| sort.order(a, b));
let want: Vec<PhotoId> = want.iter().map(|p| p.id).collect();
assert_eq!(c.query(&all, &sort), want, "{key:?} ascending {ascending}");
}
}
// `only` as a set gives the photos it names
let only = Filter { only: vec![PhotoId(3), PhotoId(1), PhotoId(3)], ..Default::default() };
assert_eq!(c.query(&only, &Sort { key: SortKey::FileName, ascending: true, ..Default::default() }), vec![PhotoId(3), PhotoId(1)]);
}
/// Rules name flags, labels and kinds as their variants in lower case (what `{:?}` gave).
#[test]
fn rule_names_are_the_variants_in_lower_case() {
let mut c = Catalog::new();
let mut n = 0;
for flag in [Flag::None, Flag::Pick, Flag::Reject] {
for label in
[None, Some(ColorLabel::Red), Some(ColorLabel::Yellow), Some(ColorLabel::Green), Some(ColorLabel::Blue), Some(ColorLabel::Purple)]
{
for kind in [MediaKind::Image, MediaKind::Raw, MediaKind::Video] {
n += 1;
let mut p = Photo::new(PhotoId(n), Source::Demo { scene: 1 }, "x.jpg", "JPEG", 60, 40, "2026-01-01T00:00:00");
(p.flag, p.label, p.kind) = (flag, label, kind);
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
}
}
}
c.apply(Op::SetLabelName { label: ColorLabel::Blue, name: Some("Sky".into()) }).unwrap();
let count = |field: &str, value: String| {
let rules: RuleSet =
serde_json::from_value(serde_json::json!({"match": "all", "rules": [{"field": field, "op": "is", "value": value}]})).unwrap();
c.query(&Filter { rule_set: Some(rules), ..Default::default() }, &Sort::default()).len()
};
for flag in [Flag::None, Flag::Pick, Flag::Reject] {
assert_eq!(count("flag", format!("{flag:?}").to_lowercase()), 18, "{flag:?}");
}
assert_eq!(count("flag", "picked".into()), 18);
for label in ColorLabel::ALL {
assert_eq!(count("label", format!("{label:?}").to_uppercase()), 9, "{label:?}");
}
assert_eq!(count("label", "sky".into()), 9, "a custom name");
assert_eq!(count("label", "none".into()), 9);
for kind in [MediaKind::Image, MediaKind::Raw, MediaKind::Video] {
assert_eq!(count("kind", format!("{kind:?}")), 18, "{kind:?}");
}
}
/// A hand-edited file can put a photo in two stacks (ops refuse it): loading repairs it (the photo
/// stays in the first) and the stack index gives the answers a scan of the stacks gives, before
/// and after either stack goes.
#[test]
fn a_photo_in_two_stacks_read_from_a_file_answers_as_a_scan() {
let mut c = library();
c.apply(Op::AddStack { stack: Stack { id: StackId(1), photos: vec![PhotoId(1), PhotoId(2)], collapsed: false } }).unwrap();
c.apply(Op::AddStack { stack: Stack { id: StackId(2), photos: vec![PhotoId(3), PhotoId(4)], collapsed: false } }).unwrap();
let mut v: serde_json::Value = serde_json::from_str(&c.to_snapshot()).unwrap();
v["stacks"]["2"]["photos"] = serde_json::json!([2, 3, 4]);
let mut c = Catalog::from_snapshot(&v.to_string()).unwrap();
assert_eq!(indexed(&c), scanned(&c));
assert_eq!(c.stack_of(PhotoId(2)).map(|s| s.id), Some(StackId(1)));
// the second stack can't be changed to keep it, as before
assert!(c.apply(Op::SetStack { id: StackId(2), photos: vec![PhotoId(2), PhotoId(3)], collapsed: false }).is_err());
c.apply(Op::RemoveStack { id: StackId(1) }).unwrap();
assert_eq!(indexed(&c), scanned(&c));
assert_eq!(c.stack_of(PhotoId(2)).map(|s| s.id), None, "the repair took it out of the second stack");
}
+15
View File
@@ -376,3 +376,18 @@ fn a_damaged_process_value_loads_as_v1_with_the_edits() {
let d = &loaded.photo(id).unwrap().develop;
assert_eq!((d.process, d.light.exposure), (ProcessVersion::V1, 0.8));
}
/// A snapshot whose `seq` is near `u64::MAX` is refused as corrupt: the next record's seq would
/// wrap (and every later edit would be skipped as stale on reopen) or overflow-panic in debug.
#[test]
fn snapshot_with_seq_near_u64_max_is_corrupt() {
for seq in [u64::MAX, u64::MAX - 1, u64::MAX / 2 + 1] {
let m = MemStore::new();
m.set(
SNAPSHOT,
format!("{{\"format\":\"lightcraft-catalog\",\"version\":1,\"seq\":{seq},\"catalog\":{}}}\n", Catalog::new().to_snapshot()).into_bytes(),
);
let e = Journal::open(Box::new(m)).err();
assert!(matches!(e, Some(CatalogError::Corrupt(_))), "seq {seq}: {e:?}");
}
}
+92
View File
@@ -0,0 +1,92 @@
//! What library queries cost at 100k photos (ignored:
//! `cargo test --release -p lightcraft-catalog --lib scale_100k -- --ignored --nocapture`).
use std::time::Instant;
use serde_json::json;
use super::*;
/// 100k photos, 10k two-photo stacks, a 20k-photo album, keywords and flags.
fn library(n: u64) -> (Catalog, AlbumId) {
let mut c = Catalog::new();
let mut ops: Vec<Op> = (0..n)
.map(|i| {
let mut p = Photo::new(
PhotoId(i + 1),
Source::Demo { scene: (i % 20) as u32 },
&format!("IMG_{:06}.jpg", mix64(i) % 1_000_000),
"JPEG",
6000,
4000,
"2026-01-01T00:00:00",
);
p.captured = Some(format!("20{:02}-{:02}-{:02}T{:02}:00:00", 10 + i % 16, 1 + i % 12, 1 + i % 28, i % 24));
p.rating = (i % 6) as u8;
p.flag = if i % 7 == 0 { Flag::Pick } else { Flag::None };
p.meta.keywords = vec![format!("kw{}", i % 500), "travel|italy".into()];
Op::AddPhoto { photo: Box::new(p) }
})
.collect();
ops.extend(
(0..n / 10)
.map(|s| Op::AddStack { stack: Stack { id: StackId(s + 1), photos: vec![PhotoId(s * 10 + 1), PhotoId(s * 10 + 2)], collapsed: false } }),
);
let album = AlbumId(1);
let mut a = Album::new(album, "Big");
a.photos = (0..n).step_by(5).map(|i| PhotoId(i + 1)).collect();
ops.push(Op::AddAlbum { album: a });
let t = Instant::now();
c.apply(Op::Batch { ops }).unwrap();
eprintln!("build {n} photos, {} stacks: {:.0} ms", n / 10, t.elapsed().as_secs_f64() * 1e3);
(c, album)
}
fn smart(c: &mut Catalog, id: u64, rules: serde_json::Value) -> AlbumId {
let mut a = Album::new(AlbumId(id), format!("Smart {id}"));
a.smart = Some(Box::new(Filter { rule_set: Some(serde_json::from_value(rules).unwrap()), ..Default::default() }));
c.apply(Op::AddAlbum { album: a }).unwrap();
AlbumId(id)
}
/// Best of five runs (the machine may be busy with other work).
fn time<T>(what: &str, f: impl Fn() -> T) -> T {
let mut best = f64::MAX;
let mut r = None;
for _ in 0..5 {
let t = Instant::now();
r = Some(f());
best = best.min(t.elapsed().as_secs_f64() * 1e3);
}
eprintln!("{what}: {best:.1} ms");
r.unwrap()
}
#[test]
#[ignore]
fn scale_100k() {
let (mut c, album) = library(100_000);
let all = Filter::default();
time("query, capture date", || c.query(&all, &Sort::default()));
time("query, file name", || c.query(&all, &Sort { key: SortKey::FileName, ..Default::default() }));
time("query, text", || c.query(&Filter { text: "kw42".into(), ..Default::default() }, &Sort::default()));
time("query, album of 20k", || c.query(&Filter { album: Some(album), ..Default::default() }, &Sort::default()));
let only: Vec<PhotoId> = (0..5000).map(|i| PhotoId(i * 7 + 1)).collect();
time("query, only 5k ids", || c.query(&Filter { only: only.clone(), ..Default::default() }, &Sort::default()));
let stacked = smart(&mut c, 10, json!({"match": "all", "rules": [{"field": "stacked", "op": "is", "value": true}]}));
let flagged = smart(
&mut c,
11,
json!({"match": "all", "rules": [{"field": "flag", "op": "is", "value": "pick"}, {"field": "kind", "op": "is", "value": "image"}]}),
);
let keyword = smart(&mut c, 12, json!({"match": "all", "rules": [{"field": "keywords", "op": "contains", "value": "kw42"}]}));
let in_album = smart(&mut c, 13, json!({"match": "all", "rules": [{"field": "album", "op": "is", "value": album.0}]}));
let recent = smart(&mut c, 14, json!({"match": "all", "rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 2, "unit": "years"}}]}));
for (what, a) in [("stacked", stacked), ("flag + kind", flagged), ("keyword", keyword), ("in album", in_album), ("in the last 2 years", recent)] {
let n = time(&format!("smart album count, {what}"), || c.album_count(a));
eprintln!(" = {n}");
}
time("albums_of", || c.albums_of(PhotoId(6)));
time("arrange stacks", || c.arrange_stacks(&c.query(&all, &Sort::default())));
time("stack_of × 1000", || (0..1000u64).filter(|i| c.stack_of(PhotoId(i * 97 + 1)).is_some()).count());
}
+5
View File
@@ -48,8 +48,13 @@ heif = ["dep:lightcraft-heif"]
avif = ["dep:ravif", "dep:rav1e", "dep:avif-serialize"]
[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
lightcraft-testkit = { workspace = true }
# JPEG XL tests read encoded samples without our colour conversion
jxl-oxide = { workspace = true }
proptest = { workspace = true }
# Lossless synthetic HEIC files for the `heif` feature's tests.
lightcraft-heif = { workspace = true, features = ["testdata"] }
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
dhat = { workspace = true }
+4
View File
@@ -73,6 +73,10 @@ ICC profiles are parsed with `moxcms` (v2/v4, `curv`/`para` TRCs, `chad`); sRGB,
Adobe RGB (1998), ProPhoto (ROMM) and Rec.2020 are recognised by colorants. `icc::write_matrix_trc`
emits v4 display profiles (D50 PCS, Bradford `chad`) for export embedding.
Before colour conversion, positive-infinity float samples become 1.0; NaN and negative infinity
become 0.0. This also applies to alpha. Finite samples keep their existing range: matrix/TRC paths
preserve values above 1.0 and below 0.0, while CMS inputs and alpha remain bounded to 0..1.
## Dependencies and licences
All pure Rust, verified with `cargo info` / `cargo tree`:
+14 -5
View File
@@ -44,11 +44,23 @@ impl Buf {
match self {
Buf::U8(v) => v[i] as f32 / 255.0,
Buf::U16(v) => v[i] as f32 / 65535.0,
Buf::F32(v) => v[i],
Buf::F32(v) => normalize_float(v[i]),
}
}
}
/// Clip non-finite device samples before colour conversion, preserving finite extended range.
#[inline]
fn normalize_float(value: f32) -> f32 {
if value == f32::INFINITY {
1.0
} else if value.is_finite() {
value
} else {
0.0
}
}
/// Interleaved device samples as produced by a format decoder.
pub(crate) struct Raw {
pub width: usize,
@@ -218,10 +230,7 @@ fn linearize(raw: &Raw, ch: usize, trc: &[Trc; 3]) -> Rgb32f {
par_rows(&mut img.data, w, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
let i = (y * w + x) * ch;
let s = |c: usize| {
let val = v[i + c];
if val.is_finite() { val } else { 0.0 }
};
let s = |c: usize| normalize_float(v[i + c]);
*o = if gray {
let l = if lin { s(0) } else { trc[1].to_linear(s(0)) };
[l, l, l]
+53 -3
View File
@@ -8,7 +8,7 @@ use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::space::{NamedSpace, SourceSpace, SpaceOrigin, Trc};
use crate::{DecodeOptions, Decoded, Error, Format, Result};
use jxl_oxide::color::{ColourSpace, EnumColourEncoding, Primaries, RenderingIntent, TransferFunction, WhitePoint};
use jxl_oxide::{AuxBoxData, JxlImage};
use jxl_oxide::{AllocTracker, AuxBoxData, InitializeResult, JxlImage};
const F: Format = Format::Jxl;
@@ -16,10 +16,60 @@ fn err(e: impl std::fmt::Display) -> Error {
Error::Malformed(F, e.to_string())
}
/// Tracked allocation budget per allowed pixel for frames, extra channels and modular trees.
/// This bounds allocations covered by `AllocTracker`, not every allocation made by the decoder (#1517).
const TRACKED_BYTES_PER_PIXEL: u64 = 4 * 4 * 8;
/// The allocation budget never drops below this, so small images keep the decoder's fixed
/// overhead (group buffers, entropy tables) whatever `max_pixels` is.
const MIN_TRACKED_BYTES: u64 = 64 << 20;
/// Bytes handed to the decoder at a time (the size `JxlImageBuilder::read` reads in).
const INPUT_CHUNK: usize = 4096;
/// Initializes from bounded input, checks dimensions before rendering, then loads remaining frames
/// within a tracked allocation budget.
fn open(bytes: &[u8], opts: &DecodeOptions) -> Result<JxlImage> {
let budget = opts.max_pixels.saturating_mul(TRACKED_BYTES_PER_PIXEL).max(MIN_TRACKED_BYTES);
let tracker = AllocTracker::with_limit(usize::try_from(budget).unwrap_or(usize::MAX));
let mut uninit = JxlImage::builder().alloc_tracker(tracker).build_uninit();
// Initialization can load already-buffered frame data, so small feeds limit work before
// dimension checking.
let mut rest = bytes;
let mut window = INPUT_CHUNK;
let mut img = loop {
let consumed = uninit.feed_bytes(rest.get(..window).unwrap_or(rest)).map_err(err)?;
rest = rest.get(consumed..).unwrap_or_default();
match uninit.try_init().map_err(err)? {
InitializeResult::Initialized(img) => break img,
InitializeResult::NeedMoreData(more) => uninit = more,
}
if consumed == 0 {
// the parser wants more than the window holds at once
if window >= rest.len() {
return Err(err("truncated JPEG XL header"));
}
window = window.saturating_mul(2);
}
};
check_size(F, img.width() as u64, img.height() as u64, opts)?;
// Match `JxlImageBuilder::read`: bounded feeds until the final frame, not merely the first
// keyframe. `feed_bytes` copies codestream data into an untracked Vec, including any tail
// after the last frame; feeding the remaining file at once bypasses the allocation budget.
while !img.is_loading_done() && !rest.is_empty() {
let consumed = img.feed_bytes(rest.get(..INPUT_CHUNK).unwrap_or(rest)).map_err(err)?;
if consumed == 0 {
break;
}
rest = rest.get(consumed..).unwrap_or_default();
}
img.finalize().map_err(err)?;
Ok(img)
}
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
let mut img = JxlImage::builder().read(std::io::Cursor::new(bytes)).map_err(err)?;
let mut img = open(bytes, opts)?;
let (w, h) = (img.width(), img.height());
check_size(F, w as u64, h as u64, opts)?;
let header = img.image_header();
let bits = header.metadata.bit_depth.bits_per_sample() as u8;
let float = matches!(header.metadata.bit_depth, jxl_oxide::image::BitDepth::FloatSample { .. });
+1
View File
@@ -32,6 +32,7 @@ mod jxl;
mod jxl_encode;
mod other;
mod png_codec;
pub mod print;
pub mod proof;
mod psd;
mod sniff;
+375
View File
@@ -0,0 +1,375 @@
//! Print colour: a composed print page (16-bit RGB encoded with the BT.2020 / BT.709 curve, as the
//! `Rec2020` output space renders it) to the samples a print-ready file carries, in the colour space
//! of the chosen printer / paper profile.
//!
//! - **Target**: a printer / paper ICC profile (RGB, CMYK or grey; matrix or LUT based) converts the
//! page to the device's own values. When the printer manages colour instead, the page is sent in a
//! well-known RGB space (sRGB, Adobe RGB) and that space's profile travels with it.
//! - **Rendering intent**: perceptual or relative colorimetric, as for soft proofing ([`ProofIntent`]).
//! - **Black point compensation** (relative colorimetric only): the darkest colour the device holds is
//! measured by a round trip of black through the profile, and the page's linear values are scaled
//! so its black lands there instead of every shadow below it clipping to the same ink. Linear
//! Rec.2020 is linear in XYZ, so with source black 0 and white 1 this is the published BPC mapping
//! `Y' = Y·(1 − Yb) + Yb` for a neutral destination black. Perceptual tables carry their own black
//! mapping and are left alone.
//! - **Print adjustment**: brightness and contrast (−100..100) for prints that come out darker or
//! flatter than the screen, on the sRGB-encoded values with black and white held. It is not shown
//! on screen (the print is what it corrects).
//!
//! Everything before the profile conversion is per channel, so it folds into one 65,536-entry table
//! indexed by the 16-bit sample; the conversion itself is moxcms's.
//!
//! Sources: ICC.1:2022 (rendering intents, profile classes); Adobe Systems, "Adobe Black Point
//! Compensation" (2006, public white paper) for the black point mapping. Own design otherwise.
use std::sync::Arc;
use moxcms::{ColorProfile, DataColorSpace, Layout, RenderingIntent, TransformExecutor, TransformOptions};
use crate::display::MAX_PROFILE_BYTES;
use crate::proof::ProofIntent;
use crate::space::{NamedSpace, Trc};
/// Where a print's colours go.
#[derive(Clone, Debug, PartialEq)]
pub enum PrintTarget {
/// The printer manages colour: the page is sent in this RGB space, with its profile embedded.
Managed(NamedSpace),
/// A printer / paper ICC profile: the page is converted to the device's values.
Profile(Arc<Vec<u8>>),
}
/// How the page is rendered into the target.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PrintColor {
pub intent: ProofIntent,
/// Map the page's black to the device's darkest (relative colorimetric only).
pub black_point_compensation: bool,
/// −100..100; 0 leaves the page as rendered.
pub brightness: f32,
/// −100..100; 0 leaves the page as rendered.
pub contrast: f32,
}
impl Default for PrintColor {
fn default() -> Self {
PrintColor { intent: ProofIntent::Perceptual, black_point_compensation: true, brightness: 0.0, contrast: 0.0 }
}
}
/// Pixels per conversion batch: bounds the temporary float buffers whatever the page size.
const BATCH: usize = 1 << 16;
/// The darkest black point compensation will lift the page's black to. A profile whose round trip
/// says more is broken or not a print profile; leave the page alone rather than wash it out.
const MAX_BLACK: f32 = 0.5;
type Executor = Arc<dyn TransformExecutor<f32> + Send + Sync>;
/// A page conversion, built once per print job and applied to every page.
pub struct PrintTransform {
forward: Executor,
layout: Layout,
channels: usize,
icc: Arc<Vec<u8>>,
/// 16-bit sample → linear Rec.2020 after the print adjustment and black point compensation.
pre: Vec<f32>,
black: f32,
description: Option<String>,
}
impl std::fmt::Debug for PrintTransform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PrintTransform")
.field("channels", &self.channels)
.field("black", &self.black)
.field("description", &self.description)
.finish_non_exhaustive()
}
}
fn guarded<T>(f: impl FnOnce() -> Option<T>) -> Option<T> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok().flatten()
}
fn rendering_intent(intent: ProofIntent) -> RenderingIntent {
match intent {
ProofIntent::Perceptual => RenderingIntent::Perceptual,
ProofIntent::Relative => RenderingIntent::RelativeColorimetric,
}
}
/// A slider value as a finite fraction in −1..1 (NaN and infinities count as 0).
fn amount(v: f32) -> f32 {
if v.is_finite() { (v / 100.0).clamp(-1.0, 1.0) } else { 0.0 }
}
/// The print adjustment on one sRGB-encoded value (0..1): brightness bends the mid-tones with a
/// power curve, contrast steepens (or flattens) them with `e − k·sin(2πe)/2π`, which keeps black,
/// mid grey and white where they are and stays monotonic for |k| < 1.
pub fn print_adjust(e: f32, brightness: f32, contrast: f32) -> f32 {
let e = if e.is_finite() { e.clamp(0.0, 1.0) } else { 0.0 };
let (b, c) = (amount(brightness), amount(contrast));
let e = if b != 0.0 { e.powf(2f32.powf(-0.5 * b)) } else { e };
let k = 0.6 * c;
let tau = std::f32::consts::TAU;
(e - k * (tau * e).sin() / tau).clamp(0.0, 1.0)
}
impl PrintTransform {
/// Build the conversion for a target. Errors say what's wrong with the profile; nothing here
/// panics on a hostile one.
pub fn new(target: &PrintTarget, color: &PrintColor) -> Result<PrintTransform, String> {
let icc = match target {
PrintTarget::Managed(n) => Arc::new(crate::icc::write_named(*n)),
PrintTarget::Profile(bytes) => Arc::clone(bytes),
};
if icc.len() > MAX_PROFILE_BYTES {
return Err("the profile is too large".into());
}
let dev = guarded(|| ColorProfile::new_from_slice(&icc).ok()).ok_or("not a valid ICC profile")?;
let (layout, channels) = match dev.color_space {
DataColorSpace::Rgb => (Layout::Rgb, 3),
DataColorSpace::Cmyk => (Layout::Rgba, 4),
DataColorSpace::Gray => (Layout::Gray, 1),
_ => return Err("only RGB, CMYK and grey printer profiles can be printed to".into()),
};
let lin = crate::icc::linear_rec2020_profile();
let opts = |i| TransformOptions { rendering_intent: i, ..TransformOptions::default() };
let forward: Executor = guarded(|| lin.create_transform_f32(Layout::Rgb, &dev, layout, opts(rendering_intent(color.intent))).ok())
.ok_or("can't convert to this profile")?;
let black = if color.black_point_compensation && color.intent == ProofIntent::Relative {
let back: Executor = guarded(|| dev.create_transform_f32(layout, &lin, Layout::Rgb, opts(RenderingIntent::RelativeColorimetric)).ok())
.ok_or("can't convert from this profile")?;
device_black(&forward, &back, channels)
} else {
0.0
};
let decode = Trc::Rec709.lut16();
let (b, c) = (color.brightness, color.contrast);
let adjust = amount(b) != 0.0 || amount(c) != 0.0;
let pre = decode
.iter()
.map(|&lin| {
let lin = if adjust {
let e = lightcraft_color::transfer::linear_to_srgb(lin.clamp(0.0, 1.0));
lightcraft_color::transfer::srgb_to_linear(print_adjust(e, b, c))
} else {
lin.clamp(0.0, 1.0)
};
lin * (1.0 - black) + black
})
.collect();
let description = crate::icc::parse(&icc).and_then(|i| i.description);
Ok(PrintTransform { forward, layout, channels, icc, pre, black, description })
}
/// Samples per pixel of the converted page: 3 (RGB), 4 (CMYK) or 1 (grey).
pub fn channels(&self) -> usize {
self.channels
}
/// The profile the converted samples are in: embed it with them.
pub fn icc(&self) -> &Arc<Vec<u8>> {
&self.icc
}
/// Whether the samples are CMYK (PDF readers show CMYK images inverted unless told otherwise,
/// so writers need to know).
pub fn is_cmyk(&self) -> bool {
self.layout == Layout::Rgba
}
/// The linear black black point compensation lifts the page's black to (0 when off).
pub fn black(&self) -> f32 {
self.black
}
/// The profile's description, for the job's settings and error messages.
pub fn description(&self) -> Option<&str> {
self.description.as_deref()
}
/// Convert a page: `rgb` is interleaved 16-bit RGB in the BT.2020 / BT.709 encoding; the result
/// is interleaved 16-bit device samples ([`PrintTransform::channels`] per pixel).
pub fn apply(&self, rgb: &[u16]) -> Result<Vec<u16>, String> {
if !rgb.len().is_multiple_of(3) {
return Err("the page isn't whole RGB pixels".into());
}
let pixels = rgb.len() / 3;
let ch = self.channels;
let out_len = pixels.checked_mul(ch).ok_or("the page is too large")?;
let mut out = vec![0u16; out_len];
let run = |src: &[u16], dst: &mut [u16]| -> Option<()> {
let lin: Vec<f32> = src.iter().map(|&v| self.pre.get(usize::from(v)).copied().unwrap_or(0.0)).collect();
let mut dev = vec![0f32; dst.len()];
self.forward.transform(&lin, &mut dev).ok()?;
for (d, v) in dst.iter_mut().zip(dev) {
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
*d = (v * 65535.0 + 0.5) as u16;
}
Some(())
};
let src = rgb.chunks(BATCH * 3);
let dst = out.chunks_mut(BATCH * ch);
#[cfg(feature = "parallel")]
let ok = {
use rayon::prelude::*;
let pairs: Vec<_> = src.zip(dst).collect();
pairs.into_par_iter().all(|(s, d)| guarded(|| run(s, d)).is_some())
};
#[cfg(not(feature = "parallel"))]
let ok = src.zip(dst).all(|(s, d)| guarded(|| run(s, d)).is_some());
if ok { Ok(out) } else { Err("the profile's tables can't be applied".into()) }
}
}
/// The darkest the device holds, as linear Rec.2020 luminance: black there and back, relative
/// colorimetric both ways (for a device that reaches true black, 0).
fn device_black(forward: &Executor, back: &Executor, channels: usize) -> f32 {
let mut device = vec![0f32; channels];
let mut lin = [0f32; 3];
let ok = guarded(|| {
forward.transform(&[0.0; 3], &mut device).ok()?;
back.transform(&device, &mut lin).ok()
});
if ok.is_none() {
return 0.0;
}
// BT.2020 luminance weights
let y = 0.2627 * lin[0] + 0.6780 * lin[1] + 0.0593 * lin[2];
if y.is_finite() { y.clamp(0.0, MAX_BLACK) } else { 0.0 }
}
#[cfg(test)]
mod tests {
use super::*;
use moxcms::ToneReprCurve;
/// A page of one 16-bit pixel per linear grey level.
fn greys(levels: &[f32]) -> Vec<u16> {
levels.iter().flat_map(|&l| [(Trc::Rec709.from_linear(l) * 65535.0).round() as u16; 3]).collect()
}
fn convert(target: &PrintTarget, color: PrintColor, levels: &[f32]) -> Vec<u16> {
PrintTransform::new(target, &color).unwrap().apply(&greys(levels)).unwrap()
}
/// An RGB print profile whose ink can't get darker than linear 0.03: device 0 is 3 % grey.
fn raised_black_profile() -> Arc<Vec<u8>> {
let mut p = ColorProfile::new_from_slice(&crate::icc::write_named(NamedSpace::Srgb)).unwrap();
let (g, e) = (2.2f32, 0.03f32);
let a = (1.0 - e).powf(1.0 / g);
// ICC parametric type 4: Y = (aX + b)^g + e for X >= d, Y = cX + f below
let trc = ToneReprCurve::Parametric(vec![g, a, 0.0, 0.0, 0.0, e, e]);
p.red_trc = Some(trc.clone());
p.green_trc = Some(trc.clone());
p.blue_trc = Some(trc);
Arc::new(p.encode().unwrap())
}
#[test]
fn managed_srgb_keeps_black_grey_and_white() {
let t = PrintTransform::new(&PrintTarget::Managed(NamedSpace::Srgb), &PrintColor::default()).unwrap();
assert_eq!(t.channels(), 3);
assert_eq!(crate::icc::parse(t.icc()).and_then(|i| i.named), Some(NamedSpace::Srgb));
let out = t.apply(&greys(&[0.0, 0.18, 1.0])).unwrap();
let mid = (lightcraft_color::transfer::linear_to_srgb(0.18) * 65535.0) as i32;
assert!(out[..3].iter().all(|&v| v < 64), "{out:?}");
assert!(out[3..6].iter().all(|&v| (i32::from(v) - mid).abs() < 300), "{out:?} vs {mid}");
assert!(out[6..].iter().all(|&v| v > 65400), "{out:?}");
}
#[test]
fn adobe_rgb_target_embeds_its_profile() {
let t = PrintTransform::new(&PrintTarget::Managed(NamedSpace::AdobeRgb), &PrintColor::default()).unwrap();
assert_eq!(crate::icc::parse(t.icc()).and_then(|i| i.named), Some(NamedSpace::AdobeRgb));
// a saturated Rec.2020 green is outside Adobe RGB: it comes out at the space's edge, not wrapped
let px = [0u16, 65535, 0];
let out = t.apply(&px).unwrap();
assert!(out[1] > 60000 && out[0] < 8000 && out[2] < 8000, "{out:?}");
}
#[test]
fn brightness_lifts_the_mid_tones_and_holds_the_ends() {
let target = PrintTarget::Managed(NamedSpace::Srgb);
let levels = [0.0, 0.18, 1.0];
let plain = convert(&target, PrintColor::default(), &levels);
let bright = convert(&target, PrintColor { brightness: 50.0, ..PrintColor::default() }, &levels);
let dark = convert(&target, PrintColor { brightness: -50.0, ..PrintColor::default() }, &levels);
assert!(bright[3] > plain[3] + 2000 && dark[3] + 2000 < plain[3], "{dark:?} {plain:?} {bright:?}");
for v in [&plain, &bright, &dark] {
assert!(v[0] < 64 && v[6] > 65400, "{v:?}");
}
}
#[test]
fn contrast_spreads_shadows_and_highlights_and_stays_monotonic() {
let target = PrintTarget::Managed(NamedSpace::Srgb);
let levels = [0.03, 0.6];
let plain = convert(&target, PrintColor::default(), &levels);
let more = convert(&target, PrintColor { contrast: 60.0, ..PrintColor::default() }, &levels);
assert!(more[0] < plain[0] && more[3] > plain[3], "{plain:?} {more:?}");
for c in [-100.0, 100.0] {
for b in [-100.0, 100.0] {
let ramp: Vec<f32> = (0..=64).map(|i| i as f32 / 64.0).map(|e| print_adjust(e, b, c)).collect();
assert!(ramp.windows(2).all(|w| w[1] >= w[0]), "b {b} c {c}: {ramp:?}");
assert!(ramp[0] == 0.0 && (ramp[64] - 1.0).abs() < 1e-6);
}
}
}
#[test]
fn black_point_compensation_keeps_shadow_detail_above_the_inks_black() {
let target = PrintTarget::Profile(raised_black_profile());
let shadows = [0.0, 0.006, 0.012, 0.018, 0.024, 0.5, 1.0];
let relative = PrintColor { intent: ProofIntent::Relative, black_point_compensation: false, ..PrintColor::default() };
let clipped = convert(&target, relative, &shadows);
let kept = convert(&target, PrintColor { black_point_compensation: true, ..relative }, &shadows);
let reds = |v: &[u16]| v.chunks(3).map(|p| p[0]).collect::<Vec<_>>();
let (clipped, kept) = (reds(&clipped), reds(&kept));
// everything below the ink's black prints as (within rounding) the same device value without
// compensation …
assert!(clipped[..5].iter().all(|&v| v <= clipped[0] + 16), "{clipped:?}");
// … and as distinct, rising values with it; white still prints as white
assert!(kept[..5].windows(2).all(|w| w[1] > w[0]) && kept[4] > kept[0] + 1000, "{kept:?}");
assert!(kept[6] > 65400 && clipped[6] > 65400, "{kept:?} {clipped:?}");
let t = PrintTransform::new(&target, &PrintColor { black_point_compensation: true, ..relative }).unwrap();
assert!((t.black() - 0.03).abs() < 0.01, "{}", t.black());
}
#[test]
fn black_point_compensation_is_relative_colorimetric_only() {
let target = PrintTarget::Profile(raised_black_profile());
let levels = [0.0, 0.01, 0.2];
let with = convert(&target, PrintColor { intent: ProofIntent::Perceptual, black_point_compensation: true, ..PrintColor::default() }, &levels);
let without =
convert(&target, PrintColor { intent: ProofIntent::Perceptual, black_point_compensation: false, ..PrintColor::default() }, &levels);
assert_eq!(with, without);
let t = PrintTransform::new(&target, &PrintColor { intent: ProofIntent::Perceptual, ..PrintColor::default() }).unwrap();
assert_eq!(t.black(), 0.0);
}
#[test]
fn hostile_input_is_an_error_not_a_panic() {
let color = PrintColor::default();
assert!(PrintTransform::new(&PrintTarget::Profile(Arc::new(vec![])), &color).is_err());
assert!(PrintTransform::new(&PrintTarget::Profile(Arc::new(vec![0u8; 400])), &color).is_err());
assert!(PrintTransform::new(&PrintTarget::Profile(Arc::new(vec![0u8; MAX_PROFILE_BYTES + 1])), &color).is_err());
let good = crate::icc::write_named(NamedSpace::DisplayP3);
for i in (0..good.len()).step_by(7) {
let mut b = good.clone();
b[i] ^= 0x5a;
if let Ok(t) = PrintTransform::new(&PrintTarget::Profile(Arc::new(b)), &PrintColor { intent: ProofIntent::Relative, ..color }) {
let _ = t.apply(&greys(&[0.0, 0.5, 1.0]));
}
}
let t = PrintTransform::new(&PrintTarget::Managed(NamedSpace::Srgb), &PrintColor { brightness: f32::NAN, contrast: f32::INFINITY, ..color })
.unwrap();
assert!(t.apply(&[1, 2]).is_err(), "half a pixel");
assert_eq!(t.apply(&greys(&[0.18])).unwrap(), convert(&PrintTarget::Managed(NamedSpace::Srgb), color, &[0.18]));
assert!(print_adjust(f32::NAN, 50.0, 50.0).is_finite());
}
}
+5
View File
@@ -95,6 +95,11 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
fn limits(opts: &DecodeOptions) -> Limits {
let mut limits = Limits::default();
limits.decoding_buffer_size = opts.max_pixels.saturating_mul(4 * 8).min(usize::MAX as u64) as usize;
// A strip or tile whose declared byte count exceeds this is refused: the default 128 MiB refuses a
// single-strip uncompressed 16-bit export of ~22 MP (#1983). Raised to the decoded image's cap
// (32 bytes per allowed pixel), never lowered: a strip or tile can outgrow the pixels it shows
// (JPEG headers, padding to the tile size).
limits.intermediate_buffer_size = limits.intermediate_buffer_size.max(limits.decoding_buffer_size);
limits.ifd_value_size = 32 << 20;
limits
}
+4 -4
View File
@@ -31,7 +31,7 @@ fn files(dir: &Path) -> Vec<PathBuf> {
fn corpus_images_decode() {
let dir = corpus_root().join("images");
if !dir.is_dir() {
eprintln!("skip: {} absent", dir.display());
lightcraft_testkit::skip!(Corpus, "{} absent", dir.display());
return;
}
let (mut ok, mut unsupported) = (0, 0);
@@ -57,7 +57,7 @@ fn corpus_images_decode() {
fn corpus_pngsuite() {
let dir = corpus_root().join("pngsuite");
if !dir.is_dir() {
eprintln!("skip: {} absent", dir.display());
lightcraft_testkit::skip!(Corpus, "{} absent", dir.display());
return;
}
let mut n = 0;
@@ -83,7 +83,7 @@ fn corpus_pngsuite() {
fn corpus_raw_is_routed() {
let dir = corpus_root().join("raw");
if !dir.is_dir() {
eprintln!("skip: {} absent", dir.display());
lightcraft_testkit::skip!(Corpus, "{} absent", dir.display());
return;
}
for p in files(&dir) {
@@ -103,7 +103,7 @@ fn system_icc_profiles() {
use lightcraft_codecs::icc::{IccColorModel, IccKind, parse};
let dir = Path::new("/System/Library/ColorSync/Profiles");
if !dir.is_dir() {
eprintln!("skip: no system ICC profiles");
lightcraft_testkit::skip!(System, "no system ICC profiles");
return;
}
let expect = [
+128
View File
@@ -0,0 +1,128 @@
//! Non-finite samples in procedural 32-bit float TIFFs (issue #1952, item 6).
use lightcraft_codecs::{icc, *};
fn tiff(samples: &[f32], channels: u8, profile: Option<&[u8]>) -> Vec<u8> {
encode_tiff(
&EncodeImage::new((samples.len() / channels as usize) as u32, 1, channels, Samples::F32(samples)),
TiffCompression::None,
&EncodeMeta { icc: profile, ..Default::default() },
)
.unwrap()
}
#[test]
fn float_tiff_nonfinite_rgb_clips_without_losing_finite_hdr() {
let samples =
[[f32::INFINITY; 3], [f32::NAN; 3], [f32::NEG_INFINITY; 3], [-0.25; 3], [0.25, 0.5, 0.75], [2.0, 4.0, 8.0], [f32::INFINITY, 0.5, f32::NAN]];
let bytes = tiff(samples.as_flattened(), 3, None);
let decoded = decode(&bytes, DecodeOptions::default()).unwrap();
assert!(decoded.float);
assert_eq!(decoded.bit_depth, 32);
assert_eq!(decoded.image.data, [[1.0; 3], [0.0; 3], [0.0; 3], [-0.25; 3], [0.25, 0.5, 0.75], [2.0, 4.0, 8.0], [1.0, 0.5, 0.0]]);
let display = decoded.to_srgb8();
assert_eq!(display.data[0], [255; 4]);
for pixel in &display.data[1..4] {
assert_eq!(*pixel, [0, 0, 0, 255]);
}
assert_eq!(display.data[6], [255, 188, 0, 255]);
assert!(decoded.to_working().data.iter().flatten().all(|v| v.is_finite()));
// A box-filtered pair must average clipped white with its ordinary neighbor.
let pair = tiff(&[f32::INFINITY, f32::INFINITY, f32::INFINITY, 0.25, 0.25, 0.25], 3, None);
let small = decode(&pair, DecodeOptions::fit(1, 1)).unwrap();
assert_eq!(small.image.data, [[0.625; 3]]);
}
#[test]
fn float_tiff_nonfinite_gray_and_icc_curves_match_clipped_samples() {
let samples = [f32::INFINITY, f32::NAN, f32::NEG_INFINITY, 0.25, 1.0, 2.0, -0.25];
let clipped = [1.0, 0.0, 0.0, 0.25, 1.0, 2.0, -0.25];
let profiles = [
None,
Some(icc::write_matrix_trc(&lightcraft_color::SRGB, &Trc::Linear)),
Some(icc::write_named(NamedSpace::Srgb)),
Some(icc::write_matrix_trc(&lightcraft_color::SRGB, &Trc::Gamma(2.0))),
Some(icc::write_matrix_trc(&lightcraft_color::SRGB, &Trc::Table(vec![0, 16384, 65535]))),
Some(moxcms::ColorProfile::new_gray_with_gamma(2.0).encode().unwrap()),
Some(b"invalid ICC profile".to_vec()),
];
for channels in [1, 3] {
let samples: Vec<_> = samples.iter().flat_map(|v| std::iter::repeat_n(*v, channels as usize)).collect();
let clipped: Vec<_> = clipped.iter().flat_map(|v| std::iter::repeat_n(*v, channels as usize)).collect();
for profile in &profiles {
let profile = profile.as_deref();
let decoded = decode(&tiff(&samples, channels, profile), DecodeOptions::default()).unwrap();
let reference = decode(&tiff(&clipped, channels, profile), DecodeOptions::default()).unwrap();
assert_eq!(decoded.grayscale, channels == 1);
assert_eq!(decoded.image, reference.image, "channels={channels}, space={:?}", decoded.space);
assert_eq!(decoded.to_srgb8(), reference.to_srgb8());
assert!(decoded.image.data[5].iter().all(|v| *v > 1.0), "finite HDR survives the curve");
assert!(decoded.image.data[6].iter().all(|v| *v < 0.0), "finite negative samples survive the curve");
}
}
}
#[test]
fn float_tiff_nonfinite_alpha_is_finite_and_bounded() {
let samples = [
[f32::INFINITY, f32::INFINITY, f32::INFINITY, f32::INFINITY],
[f32::NAN, f32::NEG_INFINITY, 0.5, f32::NAN],
[0.25, 0.5, 2.0, f32::NEG_INFINITY],
[2.0, 3.0, 4.0, 0.5],
];
let decoded = decode(&tiff(samples.as_flattened(), 4, None), DecodeOptions::default()).unwrap();
assert_eq!(decoded.alpha.as_ref().unwrap().data, [1.0, 0.0, 0.0, 0.5]);
assert_eq!(decoded.image.data, [[1.0; 3], [0.0, 0.0, 0.5], [0.25, 0.5, 2.0], [2.0, 3.0, 4.0]]);
assert!(decoded.to_working().data.iter().flatten().all(|v| v.is_finite()));
// Associated alpha takes the same path before unpremultiplication.
let mut cursor = std::io::Cursor::new(Vec::new());
{
use tiff::encoder::{TiffEncoder, colortype};
let mut encoder = TiffEncoder::new(&mut cursor).unwrap();
let mut image = encoder.new_image::<colortype::RGBA32Float>(2, 1).unwrap();
image.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[1u16][..]).unwrap();
image.write_data(&[f32::INFINITY, f32::NAN, f32::NEG_INFINITY, 0.5, 1.0, 2.0, 3.0, 0.5]).unwrap();
}
let decoded = decode(&cursor.into_inner(), DecodeOptions::default()).unwrap();
assert_eq!(decoded.alpha.as_ref().unwrap().data, [0.5, 0.5]);
assert_eq!(decoded.image.data, [[2.0, 0.0, 0.0], [2.0, 4.0, 6.0]]);
}
fn lut_profile() -> Vec<u8> {
use moxcms::{ColorProfile, LutMultidimensionalType, LutWarehouse, Matrix3d, ToneReprCurve, Vector3d, Xyzd};
let mut profile = ColorProfile::new_srgb();
profile.cicp = None;
profile.red_colorant = Xyzd::default();
profile.green_colorant = Xyzd::default();
profile.blue_colorant = Xyzd::default();
profile.red_trc = None;
profile.green_trc = None;
profile.blue_trc = None;
// A procedural mAB profile without a CLUT: linear RGB to D50 XYZ, then identity curves.
profile.lut_a_to_b_colorimetric = Some(LutWarehouse::Multidimensional(LutMultidimensionalType {
num_input_channels: 3,
num_output_channels: 3,
grid_points: [0; 16],
clut: None,
a_curves: vec![],
m_curves: vec![ToneReprCurve::Parametric(vec![1.0]); 3],
matrix: Matrix3d { v: NamedSpace::Srgb.to_xyz_d50().0.map(|r| r.map(|v| v * 32768.0 / 65535.0)) },
b_curves: vec![ToneReprCurve::Parametric(vec![1.0]); 3],
bias: Vector3d::default(),
}));
profile.encode().unwrap()
}
#[test]
fn float_tiff_nonfinite_cms_samples_match_clipped_samples() {
let profile = lut_profile();
let samples = [f32::INFINITY, f32::NAN, f32::NEG_INFINITY, 0.25, 0.5, 0.75];
let clipped = [1.0, 0.0, 0.0, 0.25, 0.5, 0.75];
let decoded = decode(&tiff(&samples, 3, Some(&profile)), DecodeOptions::default()).unwrap();
let reference = decode(&tiff(&clipped, 3, Some(&profile)), DecodeOptions::default()).unwrap();
assert_eq!(decoded.space.origin, SpaceOrigin::IccCms);
assert_eq!(decoded.image, reference.image);
assert!(decoded.to_working().data.iter().flatten().all(|v| v.is_finite()));
}
+98
View File
@@ -0,0 +1,98 @@
#![cfg(all(feature = "jxl", not(target_arch = "wasm32")))]
use lightcraft_codecs::exif::minimal_exif;
use lightcraft_codecs::*;
use lightcraft_raster::Rgba8;
fn codestream(bytes: &[u8]) -> Vec<u8> {
if bytes.starts_with(b"\xff\x0a") {
return bytes.to_vec();
}
let mut raw = Vec::new();
let mut at = 12;
while at + 8 <= bytes.len() {
let len = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) as usize;
let end = if len == 0 { bytes.len() } else { at + len };
match &bytes[at + 4..at + 8] {
b"jxlc" => raw.extend_from_slice(&bytes[at + 8..end]),
b"jxlp" => raw.extend_from_slice(&bytes[at + 12..end]),
_ => {}
}
at = end;
}
assert!(raw.starts_with(b"\xff\x0a"));
raw
}
fn box_bytes(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&u32::try_from(data.len() + 8).unwrap().to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
}
#[test]
fn metadata_in_final_feed_matches_builder() {
let pixels = Rgba8::from_fn(8, 8, |x, y| [(x * 20) as u8, (y * 20) as u8, 80, 255]);
let encoded = encode_jxl(&EncodeImage::rgba8(&pixels), &JxlOptions { lossless: true, ..Default::default() }, &EncodeMeta::default()).unwrap();
let raw = codestream(&encoded);
let exif = minimal_exif(1);
let mut exif_box = vec![0; 4]; // TIFF header offset, relative to the end of this field
exif_box.extend_from_slice(&exif);
// Split the codestream across two feeds, with Exif and XMP following its last frame.
let mut bytes = b"\0\0\0\x0cJXL \x0d\x0a\x87\x0a".to_vec();
box_bytes(&mut bytes, b"ftyp", b"jxl \0\0\0\0jxl ");
let split = raw.len() / 2;
let mut part = 0u32.to_be_bytes().to_vec();
part.extend_from_slice(&raw[..split]);
box_bytes(&mut bytes, b"jxlp", &part);
let padding = vec![0; 4096 - bytes.len() - 8];
box_bytes(&mut bytes, b"free", &padding);
let mut part = 0x8000_0001u32.to_be_bytes().to_vec();
part.extend_from_slice(&raw[split..]);
box_bytes(&mut bytes, b"jxlp", &part);
box_bytes(&mut bytes, b"Exif", &exif_box);
box_bytes(&mut bytes, b"xml ", b"<xmp/>");
assert!(bytes.len() < 8192, "metadata must fit in the completing input chunk");
let old = jxl_oxide::JxlImage::builder().read(bytes.as_slice()).unwrap();
let old_exif = match old.aux_boxes().first_exif().unwrap() {
jxl_oxide::AuxBoxData::Data(ex) => ex.payload().to_vec(),
_ => panic!("builder must preserve Exif in its final feed"),
};
let old_xml = match old.aux_boxes().first_xml() {
jxl_oxide::AuxBoxData::Data(xml) => xml.to_vec(),
_ => panic!("builder must preserve XMP in its final feed"),
};
let decoded = decode(&bytes, DecodeOptions::default()).unwrap();
assert_eq!(decoded.exif.as_deref(), Some(old_exif.as_slice()));
assert_eq!(decoded.xmp.as_deref(), Some(std::str::from_utf8(&old_xml).unwrap()));
assert_eq!(decoded.to_srgb8(), pixels);
}
#[test]
fn progressive_truncation_matches_builder() {
let pixels = Rgba8::from_fn(96, 64, |x, y| {
let mut seed = (y * 96 + x + 1) as u32;
let mut rgb = [0; 4];
for channel in &mut rgb[..3] {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
*channel = seed as u8;
}
rgb[3] = 255;
rgb
});
for lossless in [false, true] {
let encoded =
encode_jxl(&EncodeImage::rgba8(&pixels), &JxlOptions { lossless, progressive: true, ..Default::default() }, &EncodeMeta::default())
.unwrap();
let raw = codestream(&encoded);
assert!(raw.len() > 4096, "fixture must exercise post-header feeds");
for cut in [0, 1, 2, 12, 4095, 4096, 4097, raw.len() / 2, raw.len() - 1, raw.len()] {
let bytes = &raw[..cut];
// `finalize` permits partial images: rendering determines whether frame 0 is usable.
let old_ok = jxl_oxide::JxlImage::builder().read(bytes).is_ok_and(|image| image.render_frame(0).is_ok());
assert_eq!(decode(bytes, DecodeOptions::default()).is_ok(), old_ok, "lossless={lossless}, cut={cut}/{}", raw.len());
}
}
}
+43
View File
@@ -0,0 +1,43 @@
#![cfg(all(feature = "jxl", not(target_arch = "wasm32")))]
use lightcraft_codecs::*;
use lightcraft_raster::Rgba8;
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
fn codestream(bytes: &[u8]) -> Vec<u8> {
if bytes.starts_with(b"\xff\x0a") {
return bytes.to_vec();
}
let mut raw = Vec::new();
let mut at = 12;
while at + 8 <= bytes.len() {
let len = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) as usize;
let end = if len == 0 { bytes.len() } else { at + len };
match &bytes[at + 4..at + 8] {
b"jxlc" => raw.extend_from_slice(&bytes[at + 8..end]),
b"jxlp" => raw.extend_from_slice(&bytes[at + 12..end]),
_ => {}
}
at = end;
}
assert!(raw.starts_with(b"\xff\x0a"));
raw
}
#[test]
fn tiny_jxl_tail_does_not_allocate_a_tail_sized_buffer() {
let image = Rgba8::from_fn(8, 8, |x, y| [(x * 20) as u8, (y * 20) as u8, 80, 255]);
let encoded = encode_jxl(&EncodeImage::rgba8(&image), &JxlOptions { lossless: true, ..Default::default() }, &EncodeMeta::default()).unwrap();
let mut raw = codestream(&encoded);
let opts = DecodeOptions { max_pixels: 64, ..Default::default() };
decode(&raw, opts).unwrap();
raw.resize(raw.len() + (1 << 20), 0);
let _profiler = dhat::Profiler::builder().testing().build();
let decoded = decode(&raw, opts).unwrap();
assert_eq!((decoded.width, decoded.height), (8, 8));
let peak = dhat::HeapStats::get().max_bytes;
eprintln!("peak heap bytes: {peak}");
assert!(peak < (128 << 10), "tiny image used {peak} heap bytes");
}
+99
View File
@@ -263,6 +263,90 @@ fn tiff_cmyk_and_orientation() {
assert!(red[0] > 0.99 && red[1] < 0.01 && red[2] < 0.01, "{red:?}");
}
/// An uncompressed 16-bit RGB export in a single strip, the shape of the file in #1983 (3923 × 5877,
/// 138 MB). Its one strip is larger than the `tiff` crate's default 128 MiB intermediate buffer, so
/// the thumbnail (and the full decode) failed with "decoder limits exceeded".
#[test]
fn tiff_single_strip_larger_than_128_mib() {
use tiff::encoder::{TiffEncoder, colortype};
let (w, h) = (3923u32, 5877u32);
let mut cur = std::io::Cursor::new(Vec::new());
{
let mut enc = TiffEncoder::new(&mut cur).unwrap();
let mut im = enc.new_image::<colortype::RGB16>(w, h).unwrap();
im.rows_per_strip(h).unwrap();
im.write_data(&vec![0x8000u16; (w * h * 3) as usize]).unwrap();
}
let bytes = cur.into_inner();
assert!(bytes.len() > 128 << 20);
let t = decode_thumbnail(&bytes, 256).unwrap();
assert_eq!((t.source_width, t.source_height), (w, h));
let px = t.image.get(10, 10);
assert!(px[0].abs_diff(128) <= 2 && px[0] == px[1] && px[1] == px[2], "{px:?}");
}
/// A little-endian TIFF with one IFD of single-value `(tag, type, value)` entries, followed by `data`.
fn ifd_tiff(entries: &[(u16, u16, u32)], data: &[u8]) -> Vec<u8> {
let mut b = b"II*\0".to_vec();
b.extend(8u32.to_le_bytes());
b.extend((entries.len() as u16).to_le_bytes());
for &(tag, ty, value) in entries {
b.extend(tag.to_le_bytes());
b.extend(ty.to_le_bytes());
b.extend(1u32.to_le_bytes());
b.extend(value.to_le_bytes());
}
b.extend(0u32.to_le_bytes());
b.extend_from_slice(data);
b
}
/// A strip or tile can be larger than the pixels it shows (a JPEG header, padding to the tile size), so
/// a small `max_pixels` must not shrink the intermediate buffer below the `tiff` crate's 128 MiB
/// default. Both files below were refused with "decoder limits exceeded" when the buffer was capped at
/// 32 bytes per allowed pixel. Fixtures from AlexChambers' review of #1989.
#[test]
fn tiff_small_pixel_budget_reads_headers_and_padded_tiles() {
let opts = |max_pixels| DecodeOptions { max_size: None, max_pixels };
// 1 × 1 gray, one JPEG-compressed strip (~400 bytes for one pixel), with a one-pixel budget.
let mut jpeg = Vec::new();
jpeg_encoder::Encoder::new(&mut jpeg, 90).encode(&[128], 1, 1, jpeg_encoder::ColorType::Luma).unwrap();
let at = 8 + 2 + 10 * 12 + 4;
let entries = [
(256, 4, 1),
(257, 4, 1),
(258, 3, 8),
(259, 3, 7),
(262, 3, 1),
(273, 4, at),
(277, 3, 1),
(278, 4, 1),
(279, 4, jpeg.len() as u32),
(284, 3, 1),
];
let d = decode(&ifd_tiff(&entries, &jpeg), opts(1)).unwrap();
assert_eq!((d.image.width, d.image.height), (1, 1));
// 16 × 16 gray stored in one 256 × 256 tile (64 KiB), with a budget of exactly 256 pixels.
let at = 8 + 2 + 11 * 12 + 4;
let entries = [
(256, 4, 16),
(257, 4, 16),
(258, 3, 8),
(259, 3, 1),
(262, 3, 1),
(277, 3, 1),
(284, 3, 1),
(322, 4, 256),
(323, 4, 256),
(324, 4, at),
(325, 4, 65536),
];
let d = decode(&ifd_tiff(&entries, &[128; 65536]), opts(256)).unwrap();
assert_eq!((d.image.width, d.image.height), (16, 16));
}
/// A one-strip, uncompressed, single-sample TIFF (little-endian) whose samples are `bits` wide and
/// already packed into `strip`, one padded row after another.
fn packed_tiff(width: u16, height: u16, bits: u16, photometric: u16, strip: &[u8]) -> Vec<u8> {
@@ -734,6 +818,21 @@ fn jxl_lossless_exact_with_metadata() {
assert!(max_diff(&d.image, &want.image) < 1e-5, "16-bit lossless differs by {}", max_diff(&d.image, &want.image));
}
/// #1517: the pixel limit rejects an oversized image; selected truncations never panic.
#[test]
#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))]
fn jxl_size_limit_and_truncation() {
let b = encode_jxl(&EncodeImage::rgba8(&gradient(97, 61)), &JxlOptions { lossless: true, ..Default::default() }, &EncodeMeta::default()).unwrap();
let r = decode(&b, DecodeOptions { max_pixels: 97 * 61 - 1, ..Default::default() });
assert!(matches!(r, Err(Error::TooLarge(97, 61))), "{r:?}");
let d = decode(&b, DecodeOptions { max_pixels: 97 * 61, ..Default::default() }).unwrap();
assert_eq!((d.width, d.height), (97, 61));
for cut in [0, 1, 2, 5, 12, 40, b.len() / 2, b.len() - 1] {
let _ = decode(&b[..cut], DecodeOptions::default());
}
assert!(decode(&b[..12.min(b.len())], DecodeOptions::default()).is_err());
}
#[test]
#[cfg(feature = "jxl")]
fn jxl_lossy_quality_and_effort() {
+11 -2
View File
@@ -180,8 +180,8 @@ pub struct Rgb8(pub u8, pub u8, pub u8);
impl Rgb8 {
pub fn from_hex(s: &str) -> Option<Rgb8> {
let s = s.trim_start_matches('#');
if s.len() != 6 {
let s = s.strip_prefix('#').unwrap_or(s);
if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let v = u32::from_str_radix(s, 16).ok()?;
@@ -196,6 +196,15 @@ impl Rgb8 {
mod tests {
use super::*;
#[test]
fn rgb8_from_hex_rejects_signs_and_extra_hashes() {
assert_eq!(Rgb8::from_hex("#0f0f0f"), Some(Rgb8(15, 15, 15)));
assert_eq!(Rgb8::from_hex("ff8000"), Some(Rgb8(255, 128, 0)));
for bad in ["+12345", "#+12345", "#+f+f+f", "-12345", "##123456", "#12345", ""] {
assert_eq!(Rgb8::from_hex(bad), None, "{bad}");
}
}
#[test]
fn srgb_matrix_matches_standard() {
let m = SRGB.to_xyz();
+16 -1
View File
@@ -14,7 +14,7 @@ use crate::manifest::Gain;
use crate::tiles::{starts, weight};
/// Most pixels one picture may have (guards the allocations that follow from its size).
pub const MAX_PIXELS: usize = 100_000_000;
pub const MAX_PIXELS: usize = 110_000_000;
/// A tile whose mean signal is below this (white = 1) is too dark to measure its scale from.
const MIN_SIGNAL: f32 = 0.003;
@@ -642,4 +642,19 @@ mod tests {
assert!(matches!(denoise_bayer(&[0.5; 16], 4, 4, layout, &Bad(vec![0.0; 5]), &p, &Control::default()), Err(Error::Model(_))));
assert!(matches!(denoise_bayer(&[0.5; 16], 4, 4, layout, &Bad(vec![f32::NAN; 3 * 64 * 64]), &p, &Control::default()), Err(Error::Model(_))));
}
#[test]
fn accepts_102_mp_inputs_and_rejects_inputs_above_the_limit() {
let layout = Layout { dx: 0, dy: 0 };
let model = Mock { tile: 32, scale: 1.0 };
let p = params(32, 8, Gain::None);
assert!(matches!(
denoise_bayer(&[], 11_648, 8_736, layout, &model, &p, &Control::default()),
Err(Error::Input(message)) if message == "the mosaic does not have width × height samples"
));
assert!(matches!(
denoise_bayer(&[], MAX_PIXELS + 1, 1, layout, &model, &p, &Control::default()),
Err(Error::Input(message)) if message == "the picture has no size, or is too large"
));
}
}
+50 -1
View File
@@ -41,7 +41,7 @@ impl DevelopSettings {
/// Merge a partial JSON object into these settings (fields not mentioned are kept). A white balance that
/// names no [`WbScale`] keeps the meaning it always had (`Legacy`), whatever scale these settings were on: a
/// partial from before the scale existed, or one that never said, must not become Kelvin by landing on
/// Kelvin settings.
/// Kelvin settings. Out-of-range values are brought back into range ([`DevelopSettings::keep_in_range`]).
pub fn merged(&self, partial: &Value) -> Result<DevelopSettings, serde_json::Error> {
let mut v = self.to_json();
presets::deep_merge(&mut v, partial);
@@ -52,9 +52,34 @@ impl DevelopSettings {
{
out.wb.scale = WbScale::Legacy;
}
out.keep_in_range(self);
Ok(out)
}
/// What crs XMP import does to the values it reads, for settings that arrive as JSON (presets, `develop.merge`,
/// `render --settings`; issue #1946): every slider clamped through its control spec, point curves in 0..1, and a
/// crop with no area left as it was in `before`. Unrotated, the crop is clipped to the photo first; a turned crop
/// may reach past 0..1 and is left to the crop tools, which know the photo's size.
fn keep_in_range(&mut self, before: &DevelopSettings) {
for c in controls::CONTROLS {
if let Some(v) = controls::get(self, c.id) {
controls::set(self, c.id, v);
}
}
let c = &mut self.curve;
for p in [&mut c.master, &mut c.red, &mut c.green, &mut c.blue].into_iter().flatten() {
*p = lightcraft_geom::Point::new(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0));
}
let g = &mut self.crop.geometry;
if g.angle == 0.0 {
g.rect = g.rect.intersect(&lightcraft_geom::Rect::UNIT);
}
if g.rect.is_empty() {
let old = before.crop.geometry.rect;
g.rect = if old.is_empty() { lightcraft_geom::Rect::UNIT } else { old };
}
}
/// Stable 64-bit hash of the settings (FNV-1a over canonical JSON), for preview cache keys.
pub fn hash64(&self) -> u64 {
let s = serde_json::to_string(self).unwrap_or_default();
@@ -255,6 +280,30 @@ mod tests {
assert_eq!(m.light.exposure, 0.0);
}
#[test]
fn merged_settings_are_kept_in_range() {
// issue #1946: `develop.merge`, `render --settings` and presets stored whatever the JSON said
let mut base = DevelopSettings::default();
base.crop.geometry.rect = lightcraft_geom::Rect::new(0.1, 0.2, 0.8, 0.9);
let m = base
.merged(&json!({"light": {"exposure": 1e308}, "vignette": {"amount": -1e308}, "geometry": {"scale": 0}, "optics": {"distortion": 1e308}}))
.unwrap();
assert_eq!((m.light.exposure, m.vignette.amount, m.geometry.scale, m.optics.distortion), (5.0, -100.0, 50.0, 100.0));
// point curves stay in 0..1, as an imported XMP curve does
let m = base.merged(&json!({"curve": {"master": [{"x": -3, "y": 0}, {"x": 1, "y": 1e308}]}})).unwrap();
assert_eq!(m.curve.master, vec![lightcraft_geom::Point::new(0.0, 0.0), lightcraft_geom::Point::new(1.0, 1.0)]);
// a crop with no area is left out, as XMP import leaves out one whose edges are inverted
for rect in
[json!({"x0": 0.9, "x1": 0.1, "y0": 0, "y1": 1}), json!({"x0": 1e308, "x1": -1e308, "y0": 0, "y1": 1}), json!({"x0": 0.5, "x1": 0.5})]
{
let m = base.merged(&json!({"crop": {"geometry": {"rect": rect}}})).unwrap();
assert_eq!(m.crop.geometry.rect, base.crop.geometry.rect, "{rect}");
}
// unrotated, the crop stays inside the photo
let m = base.merged(&json!({"crop": {"geometry": {"rect": {"x0": -1e308, "y0": 0.25, "x1": 1e308, "y1": 0.75}}}})).unwrap();
assert_eq!(m.crop.geometry.rect, lightcraft_geom::Rect::new(0.0, 0.25, 1.0, 0.75));
}
#[test]
fn unedited_and_reset() {
let mut s = DevelopSettings::default();
+2 -8
View File
@@ -184,17 +184,11 @@ fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value {
}
/// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped
/// through the control specs.
/// through the control specs, as every merge does ([`DevelopSettings::merged`]).
pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings {
let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json(), partial, amount)) };
// (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`)
let mut out = s.merged(&patch).unwrap_or_else(|_| s.clone());
for c in crate::controls::CONTROLS {
if let Some(v) = crate::controls::get(&out, c.id) {
crate::controls::set(&mut out, c.id, v);
}
}
out
s.merged(&patch).unwrap_or_else(|_| s.clone())
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+4
View File
@@ -9,6 +9,8 @@ description = "LightCraft engine: session, command registry, history, render job
workspace = true
[dependencies]
# Paths stored in a Lightroom catalog are followed only to local files or the catalog's share.
craft-docpath = { workspace = true }
lightcraft-geom = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-raster = { workspace = true }
@@ -52,6 +54,8 @@ denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime", "lightcraft-g
rawnind-model = ["denoise", "lightcraft-denoise/rawnind-model", "lightcraft-denoise-core/rawnind-model"]
[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
lightcraft-testkit = { workspace = true }
# HDR JPEG XL tests read the file's colour encoding
jxl-oxide = { workspace = true }
# Lossless synthetic HEIC files (the import test; decoded when the codecs' `heif` feature is on).
+47
View File
@@ -0,0 +1,47 @@
//! What a Synchronize Folder scan costs on a folder whose photos are all in the library and
//! unchanged: the walk, and the check of every photo and its sidecar. Reads the folder; writes
//! nothing there, and probes no file (the library is made from the folder's own listing).
//!
//! `cargo run --release -p lightcraft-engine --example sync_scan_bench -- <folder>`
use std::time::Instant;
use lightcraft_catalog::{Op, Photo, Source};
use lightcraft_engine::Session;
use lightcraft_engine::sync::{SyncInput, SyncProgress, scan_with};
fn main() {
let Some(folder) = std::env::args().nth(1) else {
eprintln!("usage: sync_scan_bench <folder>");
return;
};
let mut s = Session::new();
let t = Instant::now();
let files = lightcraft_engine::import::expand(std::slice::from_ref(&folder), None);
println!("{} files listed in {:.1} s (the library is made of them)", files.len(), t.elapsed().as_secs_f64());
for f in &files {
let id = s.catalog.alloc_photo_id();
let name = std::path::Path::new(f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let p = Photo::new(id, Source::File { path: f.clone() }, &name, "JPEG", 6, 4, "2026-01-01T00:00:00");
if s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).is_err() {
eprintln!("could not add {name}");
}
}
for run in 0..2 {
let input = match SyncInput::new(&mut s, &folder, true) {
Ok(input) => input,
Err(e) => {
eprintln!("{e}");
return;
}
};
let t = Instant::now();
let changes = scan_with(input, &SyncProgress::default());
println!(
"run {run}: scan {:.1} s ({} new, {} missing, {} with sidecar news)",
t.elapsed().as_secs_f64(),
changes.new.len(),
changes.missing.len(),
changes.metadata.len()
);
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ impl Unit {
pub struct TaskInfo {
pub id: u64,
/// A stable id: `import`, `export`, `scan`, `previews`, `smartPreviews`, `lightroom`, `merge`, `download`,
/// `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`.
/// `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`.
pub kind: &'static str,
/// English; the frontend translates it.
pub label: String,
File diff suppressed because it is too large. Load diff
+7 -2
View File
@@ -28,6 +28,9 @@ pub const BUNDLED: &[(&str, &str)] = &[
("ILCA-99M2", include_str!("../../../assets/camera-profiles/ILCA-99M2.json")),
("ILCE-7CR", include_str!("../../../assets/camera-profiles/ILCE-7CR.json")),
("ILCE-7M4", include_str!("../../../assets/camera-profiles/ILCE-7M4.json")),
("NIKON D5300", include_str!("../../../assets/camera-profiles/NIKON_D5300.json")),
("NIKON Z 6_2", include_str!("../../../assets/camera-profiles/NIKON_Z_6_2.json")),
("NIKON Z 8", include_str!("../../../assets/camera-profiles/NIKON_Z_8.json")),
("X-H2S", include_str!("../../../assets/camera-profiles/X-H2S.json")),
("X-T4", include_str!("../../../assets/camera-profiles/X-T4.json")),
];
@@ -195,10 +198,12 @@ impl Pool {
/// NEF or RAF without colour matrices, no usable camera JPEG, too little colour).
pub fn add(&mut self, bytes: &[u8]) -> Result<Option<String>, String> {
let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?;
// colour only: geometric lens corrections would stop the sensor proxy from binning
// colour only: geometric lens corrections would stop the sensor proxy from binning (the pairs still follow
// the warp the camera applied to its JPEG)
let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3);
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) };
let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes) else { return Ok(None) };
let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref()) else { return Ok(None) };
let step = pairs.len().div_ceil(PAIRS_PER_FILE).max(1);
let entry = self.models.entry(model.to_owned()).or_default();
entry.0 += 1;
+2 -2
View File
@@ -224,7 +224,7 @@ fn forget_local(s: &mut Session, p: &Value) -> Result<Value> {
/// The browsed photos among `ids` (default: the selection) become library photos.
fn add_to_library(s: &mut Session, p: &Value) -> Result<Value> {
let ids: Vec<PhotoId> = s.targets(p).into_iter().filter(|id| s.catalog.photo(*id).is_some_and(|ph| ph.local)).collect();
let ids: Vec<PhotoId> = s.targets(p)?.into_iter().filter(|id| s.catalog.photo(*id).is_some_and(|ph| ph.local)).collect();
if ids.is_empty() {
return Ok(json!({"added": 0}));
}
@@ -410,7 +410,7 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result<Value> {
if !dir.is_dir() {
return Err(bad(C, format!("{folder} is not a folder (create it first with folder.create)")));
}
let ids = s.targets(p);
let ids = s.targets(p)?;
if ids.is_empty() {
return Err(bad(C, "no photos to move: select some or give ids"));
}
+30 -5
View File
@@ -59,7 +59,7 @@ pub(crate) fn write_dng_with(file_bytes: Option<&crate::merge::ByteReader>, path
fn convert(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "photo.convertToDng";
let ids = s.targets(p);
let ids = s.targets(p)?;
let mut ops = Vec::new();
let mut converted = Vec::new();
let mut skipped = Vec::new();
@@ -125,7 +125,7 @@ pub fn specs() -> Vec<CommandSpec> {
/// the library and stack it on top of the original. The host opens the file in the editor.
fn edit_external(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "photo.editExternal";
let mut ids = s.targets(p);
let mut ids = s.targets(p)?;
ids.dedup();
if ids.is_empty() {
return Err(bad(C, "no active photo"));
@@ -240,6 +240,10 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P
m.aperture = m.aperture.or(src.aperture);
m.iso = m.iso.or(src.iso);
m.gps = m.gps.or(src.gps);
// the camera's focus point: photos imported before it was read get it here
if m.focus.is_none() {
m.focus = src.focus.clone();
}
let mut ops = Vec::new();
if m != before {
ops.push(Op::SetMeta { id, meta: Box::new(m) });
@@ -311,7 +315,7 @@ pub(crate) fn reload_ops(
/// Re-read photos whose files changed on disk (an external editor saved them): new size,
/// dimensions and content hash, cached sources dropped. → {reloaded: [ids]}
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
let ids = s.targets(p);
let ids = s.targets(p)?;
let paths: Vec<(lightcraft_catalog::PhotoId, String)> = ids
.iter()
.filter_map(|id| match s.catalog.photo(*id).map(|ph| ph.source.clone()) {
@@ -340,7 +344,7 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "photo.duplicate";
let mut made = Vec::new();
for id in s.targets(p) {
for id in s.targets(p)? {
let Some(ph) = s.catalog.photo(id).map(|p| (**p).clone()) else { continue };
let Source::File { path } = &ph.source else { return Err(bad(C, "a generated demo photo has no file to duplicate")) };
let src = Path::new(path);
@@ -441,6 +445,27 @@ mod tests {
assert!(fill_missing_meta(PhotoId(1), &ph, &info).is_empty());
}
/// Reload from Disk gives a photo imported before focus points were read its camera focus point,
/// and never replaces one it has.
#[test]
fn reload_fills_a_missing_focus_point() {
let fp = |x: f64| lightcraft_meta::FocusPoint {
rect: lightcraft_meta::Rect { x0: x, y0: 0.4, x1: x + 0.02, y1: 0.42 },
mode: Some("AF-C".into()),
area: None,
tracking: None,
};
let mut ph = Photo::new(PhotoId(1), Source::File { path: "/x.arw".into() }, "x.arw", "ARW", 8640, 5760, "2026-10-06T00:00:00");
ph.captured = Some("2026-10-04T08:16:11".into());
let mut info = crate::media::ProbeInfo { captured: ph.captured.clone(), ..Default::default() };
info.meta.focus = Some(fp(0.3));
let ops = fill_missing_meta(PhotoId(1), &ph, &info);
let Some(Op::SetMeta { meta, .. }) = ops.first() else { panic!("{ops:?}") };
assert_eq!(meta.focus, Some(fp(0.3)));
ph.meta.focus = Some(fp(0.1));
assert!(fill_missing_meta(PhotoId(1), &ph, &info).is_empty(), "a known focus point is kept");
}
fn lens() -> lightcraft_develop::EmbeddedLens {
lightcraft_develop::EmbeddedLens {
warp: Some(lightcraft_develop::EmbeddedWarp { planes: [[1.0, -0.1, 0.03, 0.0, 0.0, 0.0]; 3], ..Default::default() }),
@@ -514,7 +539,7 @@ mod tests {
.unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"));
let f = root.join("raw/rw2-panasonic-gx80.rw2");
if !f.exists() {
eprintln!("skip: {} absent", f.display());
lightcraft_testkit::skip!(Corpus, "{} absent", f.display());
return;
}
let mut s = Session::new().with_fs();
+2 -2
View File
@@ -16,11 +16,11 @@ const SAME: f32 = 0.93;
fn secs(iso: &str) -> Option<i64> {
let d = lightcraft_meta::DateTime::parse_iso(iso)?;
Some(((d.year as i64 * 372 + d.month as i64 * 31 + d.day as i64) * 24 + d.hour as i64) * 3600 + d.minute as i64 * 60 + d.second as i64)
Some(d.unix_seconds())
}
fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
let ids: Vec<PhotoId> = if p.get("ids").is_some() || s.selection.ids.len() > 1 { s.targets(p) } else { s.visible_cloned() };
let ids: Vec<PhotoId> = if p.get("ids").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() };
let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32);
let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false);
// measure (thumbnail-level sources: fast, and enough for focus at 512 px)
+8 -7
View File
@@ -254,7 +254,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
}),
cmd!("develop.reset", "Reset Edits", ["Photo"], Some("Cmd+Shift+R"), "{ids?}", has_selection, |s, p| {
let ids = s.targets(p);
let ids = s.targets(p)?;
let ops = ids
.iter()
.filter_map(|id| s.develop_of(*id).map(|d| (*id, d)))
@@ -304,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
let targets = match named_photos(s, p, C)? {
Some(ids) if !ids.iter().any(|id| outdated(s, *id)) => return Err(crate::EngineError::Disabled(C.into(), already_current())),
Some(ids) => ids,
None => s.targets(p),
None => s.targets(p)?,
};
let ops: Vec<Op> = targets
.into_iter()
@@ -811,7 +811,7 @@ pub fn specs() -> Vec<CommandSpec> {
s.previous_active.filter(|id| s.catalog.photo(*id).is_some_and(|ph| !ph.deleted)).ok_or_else(|| bad(c, "no previous photo"))?;
let groups = groups_param(p, c)?.unwrap_or_else(|| s.copy_groups.clone());
let partial = lightcraft_develop::extract_groups(&s.develop_of(prev).unwrap_or_default(), &groups);
let ids: Vec<PhotoId> = s.targets(p).into_iter().filter(|id| *id != prev).collect();
let ids: Vec<PhotoId> = s.targets(p)?.into_iter().filter(|id| *id != prev).collect();
let ops = ids
.iter()
.filter_map(|id| s.develop_of(*id).map(|d| (*id, d)))
@@ -838,7 +838,7 @@ pub fn specs() -> Vec<CommandSpec> {
let full = lightcraft_develop::apply_partial(&DevelopSettings::default(), &clip, 1.0);
clip = lightcraft_develop::extract_groups(&full, &only);
}
let ids = s.targets(p);
let ids = s.targets(p)?;
let ops = ids
.iter()
.filter_map(|id| s.develop_of(*id).map(|d| (*id, d)))
@@ -890,7 +890,7 @@ pub fn specs() -> Vec<CommandSpec> {
let delta = f64_req(p, "delta", c)?;
let label = format!("Quick Develop: {}", spec.label);
let ops: Vec<Op> = s
.targets(p)
.targets(p)?
.into_iter()
.filter_map(|id| s.develop_of(id).map(|d| (id, d)))
.filter_map(|(id, d)| {
@@ -943,7 +943,7 @@ pub fn specs() -> Vec<CommandSpec> {
};
let r_ev = gathered(s, reference).ok_or_else(|| bad(c, "the active photo has no shutter / aperture / ISO"))?;
let r_slider = s.develop_of(reference).map(|d| d.light.exposure).unwrap_or(0.0);
let ids: Vec<PhotoId> = s.targets(p).into_iter().filter(|x| *x != reference).collect();
let ids: Vec<PhotoId> = s.targets(p)?.into_iter().filter(|x| *x != reference).collect();
let (mut ops, mut skipped) = (Vec::new(), Vec::new());
for id in ids {
let (Some(ev), Some(d)) = (gathered(s, id), s.develop_of(id)) else {
@@ -978,7 +978,8 @@ pub fn specs() -> Vec<CommandSpec> {
let pid = str_param(p, "id").ok_or_else(|| bad("preset.apply", "missing id"))?;
let preset = s.presets.iter().find(|x| x.id == pid).cloned().ok_or_else(|| bad("preset.apply", format!("unknown preset `{pid}`")))?;
let amount = f64_or(p, "amount", 100.0).clamp(0.0, 200.0) / 100.0;
let ids = s.targets(p);
// `id` names the preset here: the photos are `ids`, else the selection
let ids = s.targets(&json!({"ids": p.get("ids")}))?;
let ops = ids
.iter()
.filter_map(|id| s.develop_of(*id).map(|d| (*id, d)))
+148 -12
View File
@@ -17,7 +17,7 @@ use lightcraft_faces::yunet::{Detector, Face, Options};
use lightcraft_meta::{Region, RegionKind};
use serde_json::{Value, json};
use super::{CommandSpec, bad, cmd, has_selection};
use super::{CommandSpec, always, bad, cmd, has_selection};
use crate::{AiModel, EngineError, Result, Session};
const C: &str = "faces.detect";
@@ -54,10 +54,12 @@ impl NoDetector {
}
}
/// The YuNet loaded last, and from where.
static LOADED: Mutex<Option<(PathBuf, Arc<Detector>)>> = Mutex::new(None);
/// The installed YuNet, loaded once and kept (a new one is loaded when the model folder changes).
/// (also used by the background scan, which aligns faces by the detector's landmarks and finds faces in photos that have none)
pub(crate) fn detector(s: &Session) -> std::result::Result<Arc<Detector>, NoDetector> {
static LOADED: Mutex<Option<(PathBuf, Arc<Detector>)>> = Mutex::new(None);
let home = s
.face_models_dir
.as_deref()
@@ -82,10 +84,133 @@ pub(crate) fn detector(s: &Session) -> std::result::Result<Arc<Detector>, NoDete
let d = Arc::new(
Detector::new(&bytes).map_err(|e| NoDetector::Unusable(format!("{e}: remove the detector in Settings > Faces and download it again")))?,
);
#[cfg(not(target_arch = "wasm32"))]
{
let net = d.clone();
offer_gpu(s, "detection", move |gpu| net.accelerate(gpu, true));
}
*loaded = Some((path, d.clone()));
Ok(d)
}
/// Where a face model runs, for Settings ▸ Faces and `faces.gpu`.
#[derive(Clone, Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct GpuState {
/// The background check is still running.
pub checking: bool,
/// The GPU it runs on; `None` when it runs on the CPU.
pub device: Option<String>,
/// Why it runs on the CPU.
pub why: Option<String>,
}
/// Each model's [`GpuState`], by what it does ("detection", "recognition").
static GPU_STATE: Mutex<Vec<(&'static str, GpuState)>> = Mutex::new(Vec::new());
pub(crate) fn gpu_state(what: &str) -> Option<GpuState> {
GPU_STATE.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(w, _)| *w == what).map(|(_, st)| st.clone())
}
fn set_gpu_state(what: &'static str, st: GpuState) {
let mut all = GPU_STATE.lock().unwrap_or_else(PoisonError::into_inner);
match all.iter_mut().find(|(w, _)| *w == what) {
Some((_, old)) => *old = st,
None => all.push((what, st)),
}
}
/// The user chose the CPU for face models (Settings ▸ Faces).
pub(crate) fn cpu_only(s: &Session) -> bool {
s.face_models_dir.as_deref().is_some_and(|d| super::face_models::read_settings(d).cpu_only)
}
/// Check in the background whether the GPU runs a face model faster than the CPU and gives its results; the model
/// runs on the CPU meanwhile, and stays there when the GPU is off, missing, wrong or slower, or the user chose the CPU.
/// The check shows in the activity stack while it runs.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn offer_gpu(
s: &Session,
what: &'static str,
attach: impl FnOnce(Arc<dyn lightcraft_faces::net::Accelerator>) -> std::result::Result<(), String> + Send + 'static,
) {
if cpu_only(s) {
set_gpu_state(what, GpuState { why: Some("the CPU is chosen in Settings".into()), ..GpuState::default() });
return;
}
let task = s.activity.start("facesGpu", "Checking the GPU for faces", crate::activity::Cancel::No);
task.detail(what);
set_gpu_state(what, GpuState { checking: true, ..GpuState::default() });
let spawned = std::thread::Builder::new().name(format!("faces-gpu-{what}")).spawn(move || {
let _task = task;
let gpu = match lightcraft_gpu::faces::accelerator() {
Ok(gpu) => gpu,
Err(why) => {
log::info!("faces: {what} runs on the CPU ({why})");
return set_gpu_state(what, GpuState { why: Some(why), ..GpuState::default() });
}
};
let device = lightcraft_faces::net::Accelerator::device(&*gpu);
match attach(gpu) {
Ok(()) => {
log::info!("faces: {what} runs on {device}");
set_gpu_state(what, GpuState { device: Some(device), ..GpuState::default() });
}
Err(why) => {
log::info!("faces: {what} stays on the CPU: {why}");
set_gpu_state(what, GpuState { why: Some(why), ..GpuState::default() });
}
}
});
if let Err(e) = spawned {
log::warn!("faces: could not check the GPU for {what}: {e}");
set_gpu_state(what, GpuState { why: Some(format!("could not check the GPU: {e}")), ..GpuState::default() });
}
}
/// `faces.gpu`: where the face models run, and the switch that keeps them on the CPU.
fn gpu(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "faces.gpu";
if let Some(cpu) = p.get("cpuOnly") {
let cpu = cpu.as_bool().ok_or_else(|| bad(C, "`cpuOnly` is true or false"))?;
let dir = s.face_models_dir.clone().ok_or_else(|| bad(C, "this build has nowhere to keep face models (the desktop app does)"))?;
super::face_models::set_cpu_only(&dir, cpu)?;
let detector = LOADED.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|(_, d)| d.clone());
#[cfg(not(target_arch = "wasm32"))]
let embedder = s.faces.embedder.as_ref().map(|(_, e)| e.clone());
#[cfg(target_arch = "wasm32")]
let embedder: Option<Arc<lightcraft_faces::runtime::Embedder>> = None;
if cpu {
for (what, net) in [("detection", detector.as_ref().map(|d| d.net())), ("recognition", embedder.as_ref().map(|e| e.net()))] {
if let Some(net) = net {
net.detach();
}
set_gpu_state(what, GpuState { why: Some("the CPU is chosen in Settings".into()), ..GpuState::default() });
}
} else {
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(d) = detector {
offer_gpu(s, "detection", move |gpu| d.accelerate(gpu, true));
}
if let Some(e) = embedder {
offer_gpu(s, "recognition", move |gpu| e.accelerate(gpu, true).map_err(|e| e.to_string()));
}
}
}
}
Ok(gpu_json(s))
}
/// What `faces.gpu` and `faces.models.list` say about the GPU.
pub(crate) fn gpu_json(s: &Session) -> Value {
json!({
"cpuOnly": cpu_only(s),
"detection": gpu_state("detection"),
"recognition": gpu_state("recognition"),
})
}
fn face_json(f: &Face) -> Value {
json!({
"rect": {"x0": f.x0, "y0": f.y0, "x1": f.x1, "y1": f.y1},
@@ -132,7 +257,7 @@ fn detect(s: &mut Session, p: &Value) -> Result<Value> {
let detector = detector(s).map_err(|e| e.into_error(C))?;
let started = Instant::now();
let (mut results, mut ops) = (Vec::new(), Vec::new());
for id in s.targets(p) {
for id in s.targets(p)? {
let (rgb, width, height) = match render_rgb(s, id, LOOK_EDGE) {
Ok(r) => r,
Err(e) => {
@@ -173,15 +298,26 @@ fn detect(s: &mut Session, p: &Value) -> Result<Value> {
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"faces.detect",
"Detect Faces",
["Photo"],
None,
"{ids?, apply?: bool (default true), score?: 0.6, nmsIou?: 0.3, maxFaces?} → {photos: [{id, faces: [{rect, score, landmarks}]}]}. Finds faces with the YuNet detector (download it first: `faces.models.download {id: \"yunet-2023mar\"}`) and, unless `apply` is false, adds them as unnamed face regions (one undo step), replacing earlier detections but never regions from XMP or ones you named; the sidecar is not touched",
has_selection,
detect
)]
vec![
cmd!(
"faces.detect",
"Detect Faces",
["Photo"],
None,
"{ids?, apply?: bool (default true), score?: 0.6, nmsIou?: 0.3, maxFaces?} → {photos: [{id, faces: [{rect, score, landmarks}]}]}. Finds faces with the YuNet detector (download it first: `faces.models.download {id: \"yunet-2023mar\"}`) and, unless `apply` is false, adds them as unnamed face regions (one undo step), replacing earlier detections but never regions from XMP or ones you named; the sidecar is not touched",
has_selection,
detect
),
cmd!(
query "faces.gpu",
"Face Models on the GPU",
[],
None,
"{cpuOnly?: bool} → {cpuOnly, detection, recognition}: where the face models run, each as {checking, device, why} (null until it is loaded). The GPU is used only after a background check shows it gives the CPU's results faster; `cpuOnly: true` keeps every face model on the CPU (Settings ▸ Faces), `false` checks the GPU again",
always,
gpu
),
]
}
#[cfg(test)]
+12
View File
@@ -27,6 +27,9 @@ pub(super) struct FaceSettings {
pub(super) enabled: bool,
/// The installed recogniser in use.
pub(super) embedder: Option<String>,
/// Keep every face model on the CPU, even when the GPU would be faster.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub(super) cpu_only: bool,
}
fn fail(what: &str, e: impl std::fmt::Display) -> EngineError {
@@ -57,6 +60,13 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
})
}
/// Keep the face models on the CPU (or let them use the GPU again).
pub(super) fn set_cpu_only(dir: &Path, on: bool) -> Result<()> {
let mut st = read_settings(dir);
st.cpu_only = on;
write_settings(dir, &st)
}
fn write_settings(dir: &Path, st: &FaceSettings) -> Result<()> {
std::fs::create_dir_all(dir).map_err(|e| fail("could not create the face models folder", e))?;
write_atomic(&dir.join("settings.json"), &serde_json::to_vec_pretty(st).map_err(|e| fail("settings", e))?)
@@ -195,6 +205,8 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
"dir": dir.as_ref().map(|d| d.display().to_string()),
"enabled": settings.enabled,
"embedder": settings.embedder,
// where the models run: {cpuOnly, detection, recognition} as `faces.gpu` gives it
"gpu": super::face_detect::gpu_json(s),
// Native builds always have the pure-Rust runner; model files/background scanning remain native-only.
"runtime": cfg!(not(target_arch = "wasm32")),
"models": models,
+6 -1
View File
@@ -321,6 +321,8 @@ mod imp {
return Ok(e.clone());
}
let embedder = Arc::new(Embedder::load(&dir.join(&id).join("model.onnx"), &installed.manifest).map_err(|e| bad(cmd, e.to_string()))?);
let net = embedder.clone();
super::super::face_detect::offer_gpu(s, "recognition", move |gpu| net.accelerate(gpu, true).map_err(|e| e.to_string()));
let dim = match installed.manifest.output {
lightcraft_faces::OutputSpec::Embedding { dim } => dim as usize,
_ => return Err(bad(cmd, "the chosen model is not a recognition model")),
@@ -672,6 +674,9 @@ mod imp {
if let Some(w) = &s.faces.worker {
w.allow(target, pace);
}
// the GPU is held back the same way: a light pace leaves it mostly free for the window's own renders
let (runs, share) = crate::faces_worker::gpu_pace(pace);
lightcraft_gpu::faces::set_pace(runs, share);
while target > 0 && s.faces.in_flight.len() < target + PREFETCH {
let Some(id) = s.faces.queue.pop() else { break };
let Some(job) = prepare(s, id, true) else { continue };
@@ -841,7 +846,7 @@ mod imp {
const C: &str = "faces.suggest";
let embedder = current(s, C)?;
collect(s);
let targets = s.targets(p);
let targets = s.targets(p)?;
let model_threshold = embedder.manifest().thresholds.match_cosine;
let num = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).map(|v| v as f32);
let threshold = num("threshold").or(model_threshold).unwrap_or(DEFAULT_THRESHOLD);
+50
View File
@@ -0,0 +1,50 @@
//! Focus points for photos already in the library: `photo.readFocusPoints` (Photo ▸ Read Focus Points) and the
//! per-frame `focus.pump` that keeps the background job going. The job itself is `crate::focus_scan`.
use serde_json::Value;
use super::{CommandSpec, cmd};
use crate::{Result, Session};
#[cfg(not(target_arch = "wasm32"))]
fn read_points(s: &mut Session, p: &Value) -> Result<Value> {
crate::focus_scan::read_points(s, p)
}
#[cfg(target_arch = "wasm32")]
fn read_points(_: &mut Session, _: &Value) -> Result<Value> {
Err(super::bad("photo.readFocusPoints", "reading focus points needs the photos' files on disk"))
}
#[cfg(not(target_arch = "wasm32"))]
fn pump(s: &mut Session, p: &Value) -> Result<Value> {
crate::focus_scan::pump(s, p)
}
#[cfg(target_arch = "wasm32")]
fn pump(_: &mut Session, _: &Value) -> Result<Value> {
Ok(serde_json::json!({"active": false}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"photo.readFocusPoints",
"Read Focus Points",
["Photo"],
None,
"{ids?, wait?: false} → {queued, running, last?: {total, done, found, none, unavailable, bytesRead, seconds, cancelled}} — read the camera's focus point for photos imported before it was read (Sony α1 and A7S III raws and JPEGs), from the few KB of each file that hold it, on a background job with a row in the activity stack. Without `ids`, every photo in the library not looked at yet; with `ids`, those photos, looked at again. Photos that have a point keep it. No undo step and no sidecar write. `wait: true` returns when all are read (scripts)",
super::always,
read_points
),
cmd!(
query "focus.pump",
"Read Focus Points in the Background",
[],
None,
"{pace?: pause | light | normal} → {active, running?: {done, total, found}, last?, lookedAt} — cheap to call every frame (the app does): takes in what the background focus-point reader has read and commits it in batches; reads nothing new while paused and rests between files when light. Starts the reader by itself once per library opening when photos are left to look at",
super::always,
pump
),
]
}
+1 -1
View File
@@ -115,7 +115,7 @@ fn fill(meta: &mut lightcraft_catalog::Meta, place: &lightcraft_geocode::Place,
fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "metadata.reverseGeocode";
let overwrite = bool_or(p, "overwrite", false);
let ids = s.targets(p);
let ids = s.targets(p)?;
let todo: Vec<(PhotoId, LatLon)> = ids
.iter()
.filter_map(|id| {
+3 -3
View File
@@ -256,7 +256,7 @@ pub fn specs() -> Vec<CommandSpec> {
let Some(k) = current_keywords(s).get(i as usize - 1).cloned().filter(|k| !k.is_empty()) else {
return Ok(json!({"changed": 0}));
};
let ids = s.targets(p);
let ids = s.targets(p)?;
let all = !ids.is_empty()
&& ids.iter().all(|id| {
s.catalog
@@ -288,7 +288,7 @@ pub fn specs() -> Vec<CommandSpec> {
always,
|s, p| {
let mut current: Vec<String> = Vec::new();
for id in s.targets(p) {
for id in s.targets(p)? {
if let Some(ph) = s.catalog.photo(id) {
current.extend(ph.meta.keywords.iter().cloned());
}
@@ -336,7 +336,7 @@ pub fn specs() -> Vec<CommandSpec> {
Some(parent) => format!("{parent}|{name}"),
None => name,
});
let photos = if bool_or(p, "addToSelected", false) { s.targets(p) } else { Vec::new() };
let photos = if bool_or(p, "addToSelected", false) { s.targets(p)? } else { Vec::new() };
let op = s
.catalog
.create_keyword_ops(&path, info_from(p, KeywordInfo::default()), &photos)
+22 -17
View File
@@ -182,7 +182,7 @@ fn mark_deleted(s: &mut Session, ids: &[PhotoId], label: &str) -> Result<usize>
/// Apply one op per target as a single undo step.
fn for_targets(s: &mut Session, p: &Value, label: &str, f: impl Fn(PhotoId) -> Option<Op>) -> Result<Value> {
let targets = s.targets(p);
let targets = s.targets(p)?;
let ops: Vec<Op> = targets.iter().filter_map(|id| f(*id)).collect();
let n = ops.len();
if n > 0 {
@@ -194,7 +194,7 @@ fn for_targets(s: &mut Session, p: &Value, label: &str, f: impl Fn(PhotoId) -> O
/// Adjust each target's own rating; unchanged bounds do not create an undo step.
fn change_rating(s: &mut Session, p: &Value, delta: i8, label: &str) -> Result<Value> {
let mut ops = Vec::new();
for id in s.targets(p) {
for id in s.targets(p)? {
let old = s.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?.rating;
let rating = (i16::from(old) + i16::from(delta)).clamp(0, 5) as u8;
if rating != old {
@@ -213,7 +213,7 @@ fn change_rating(s: &mut Session, p: &Value, delta: i8, label: &str) -> Result<V
/// raising/lowering clamps on reject < unflagged < pick. Unchanged photos make no history step.
fn change_flag(s: &mut Session, p: &Value, label: &str, step: impl Fn(Flag) -> Flag) -> Result<Value> {
let mut ops = Vec::new();
for id in s.targets(p) {
for id in s.targets(p)? {
let old = s.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?.flag;
let flag = step(old);
if flag != old {
@@ -258,7 +258,7 @@ fn row_step(p: &Value) -> isize {
}
fn rotate(s: &mut Session, p: &Value, cw: bool) -> Result<Value> {
let targets = s.targets(p);
let targets = s.targets(p)?;
let mut ops = Vec::new();
for id in targets {
if let Some(d) = s.develop_of(id) {
@@ -277,7 +277,7 @@ fn rotate(s: &mut Session, p: &Value, cw: bool) -> Result<Value> {
}
fn flip(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {
let targets = s.targets(p);
let targets = s.targets(p)?;
let mut ops = Vec::new();
for id in targets {
if let Some(d) = s.develop_of(id) {
@@ -883,7 +883,7 @@ pub fn specs() -> Vec<CommandSpec> {
// ---- delete / restore
cmd!("photo.delete", "Delete Photo", ["Photo"], Some("Delete"), "{ids?} — moves to Recently Deleted", has_selection, |s, p| {
let before = s.visible_cloned();
let targets = s.targets(p);
let targets = s.targets(p)?;
let n = mark_deleted(s, &targets, "Delete")?;
select_after_deletion(s, &before);
Ok(json!({"changed": n}))
@@ -912,7 +912,7 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!("photo.deletePermanently", "Delete Permanently", ["Photo"], None, "{ids?}", has_selection, |s, p| {
let before = s.visible_cloned();
let t = s.targets(p);
let t = s.targets(p)?;
let op = s.catalog.delete_photos_permanently_ops(&t);
s.commit("Delete Permanently", op)?;
select_after_deletion(s, &before);
@@ -929,7 +929,7 @@ pub fn specs() -> Vec<CommandSpec> {
|s, p| {
let strs =
|k: &str| p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect::<Vec<_>>());
let targets = s.targets(p);
let targets = s.targets(p)?;
// GPS: "lat, lon" (decimal or 51°30'26"N 0°7'39"W), [lat, lon], or null / "" to clear
let gps: Option<Option<(f64, f64)>> = match p.get("gps") {
None => None,
@@ -1027,8 +1027,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
let folder = bool_or(p, "folder", false);
let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId);
let (photos, skipped) =
if !folder && bool_or(p, "addSelected", false) { album_targets(s, s.targets(&Value::Null)) } else { (vec![], 0) };
let (photos, skipped) = if !folder && bool_or(p, "addSelected", false) { album_targets(s, s.selected()) } else { (vec![], 0) };
let id = s.catalog.alloc_album_id();
let cover = photos.first().copied();
s.commit(
@@ -1268,7 +1267,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_library_selection,
|s, p| {
let id = album_param(p, "id", "album.addPhotos")?;
let targets = ids_param(p).unwrap_or_else(|| s.targets(&Value::Null));
let targets = ids_param(p).unwrap_or_else(|| s.selected());
let al = s.catalog.album(id).ok_or_else(|| bad("album.addPhotos", "no such album"))?;
if al.is_smart() || al.folder {
return Err(bad("album.addPhotos", "smart albums and folders can't hold photos"));
@@ -1276,8 +1275,10 @@ pub fn specs() -> Vec<CommandSpec> {
let (targets, skipped) = album_targets_or_err(s, "album.addPhotos", targets)?;
let mut photos = al.photos.clone();
let before = photos.len();
// looked up, not searched for: adding thousands to a big album stays linear
let mut held: std::collections::HashSet<PhotoId> = photos.iter().copied().collect();
for t in targets {
if !photos.contains(&t) {
if held.insert(t) {
photos.push(t);
}
}
@@ -1295,7 +1296,7 @@ pub fn specs() -> Vec<CommandSpec> {
"{ids?} — B: adds the photos to the target album (the Quick Collection unless one is set), or removes them when they're all in it → {album, added, skipped}; Local photos are skipped",
has_library_selection,
|s, p| {
let targets = album_targets_or_err(s, "album.toggleTarget", ids_param(p).unwrap_or_else(|| s.targets(&Value::Null)))?;
let targets = album_targets_or_err(s, "album.toggleTarget", ids_param(p).unwrap_or_else(|| s.selected()))?;
let (targets, skipped) = targets;
let target = s.target_album.filter(|a| s.catalog.album(*a).is_some_and(|al| !al.is_smart() && !al.folder));
let id = match target.or_else(|| s.catalog.quick_collection()) {
@@ -1308,11 +1309,14 @@ pub fn specs() -> Vec<CommandSpec> {
}
};
let al = s.catalog.album(id).ok_or_else(|| bad("album.toggleTarget", "no target album"))?;
let all_in = !targets.is_empty() && targets.iter().all(|t| al.photos.contains(t));
// looked up, not searched for: thousands toggled in a big album stay linear
let mut held: std::collections::HashSet<PhotoId> = al.photos.iter().copied().collect();
let all_in = !targets.is_empty() && targets.iter().all(|t| held.contains(t));
let photos: Vec<PhotoId> = if all_in {
let targets: std::collections::HashSet<PhotoId> = targets.iter().copied().collect();
al.photos.iter().copied().filter(|x| !targets.contains(x)).collect()
} else {
al.photos.iter().copied().chain(targets.iter().copied().filter(|t| !al.photos.contains(t))).collect()
al.photos.iter().copied().chain(targets.iter().copied().filter(|t| held.insert(*t))).collect()
};
let name = al.name.clone();
let cover = al.cover.filter(|c| photos.contains(c)).or(photos.first().copied());
@@ -1454,7 +1458,7 @@ pub fn specs() -> Vec<CommandSpec> {
_ => return Err(bad("album.removePhotos", "no album: pass `id` or show an album")),
},
};
let targets = ids_param(p).unwrap_or_else(|| s.targets(&Value::Null));
let targets = ids_param(p).unwrap_or_else(|| s.selected());
let al = s.catalog.album(id).ok_or_else(|| bad("album.removePhotos", "no such album"))?;
if al.is_smart() {
return Err(bad("album.removePhotos", "smart albums update automatically: change their rules"));
@@ -1463,6 +1467,7 @@ pub fn specs() -> Vec<CommandSpec> {
return Err(bad("album.removePhotos", "album folders don't hold photos"));
}
let name = al.name.clone();
let targets: std::collections::HashSet<PhotoId> = targets.into_iter().collect();
let photos: Vec<PhotoId> = al.photos.iter().copied().filter(|x| !targets.contains(x)).collect();
let removed = al.photos.len().saturating_sub(photos.len());
if removed > 0 {
@@ -1483,7 +1488,7 @@ pub fn specs() -> Vec<CommandSpec> {
always, |_, p| {
let path = str_param(p,"path").ok_or_else(|| bad("library.inspectLightroom","missing path"))?;
let data = crate::lightroom_catalog::read(std::path::Path::new(path)).map_err(|e| bad("library.inspectLightroom",e))?;
Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !std::path::Path::new(&p.path).is_file()).map(|p|&p.path).collect::<Vec<_>>(),"warnings":data.warnings}))
Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !p.original_is_file()).map(|p|&p.path).collect::<Vec<_>>(),"warnings":data.warnings}))
}),
cmd!(
"library.importLightroom",
@@ -77,6 +77,7 @@ fn relative_ratings_and_history_use_auto_write() {
std::fs::create_dir_all(&dir).unwrap();
// Metadata-only fixtures: no import, image decoding or model/service dependency.
for id in 1..=4 {
std::fs::write(dir.join(format!("{id}.jpg")), b"original").unwrap();
s.catalog
.apply(Op::SetFile {
id: PhotoId(id),
+3
View File
@@ -135,6 +135,8 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
imported.push(json!({"id": id, "name": display, "group": group}));
}
s.save_prefs()?;
// presets that name these profiles use them now
crate::profile_refs::refresh(s);
Ok(json!({"imported": imported, "failed": failed}))
}
@@ -160,6 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
lightcraft_pipeline::lut::unregister(&id);
s.save_prefs()?;
crate::profile_refs::refresh(s);
Ok(json!({"deleted": id}))
}),
]
+9 -4
View File
@@ -9,8 +9,13 @@ use crate::Result;
fn rename_args(s: &crate::Session, p: &Value, c: &str) -> Result<(Vec<lightcraft_catalog::PhotoId>, String, usize)> {
let template = str_param(p, "template").ok_or_else(|| bad(c, "missing `template`"))?.to_string();
let start = p.get("start").and_then(Value::as_u64).unwrap_or(1) as usize;
Ok((s.targets(p), template, start))
let start = p.get("start").and_then(Value::as_u64).unwrap_or(1);
let ids = s.targets(p)?;
// every number of the sequence `start..start + n` must fit
let last = start.checked_add((ids.len() as u64).saturating_sub(1));
let start = last.and_then(|l| usize::try_from(l).ok()).and_then(|_| usize::try_from(start).ok());
let start = start.ok_or_else(|| bad(c, "start out of range"))?;
Ok((ids, template, start))
}
/// A named set of colour-label names (red, yellow, green, blue, purple; empty = the colour's name).
@@ -96,7 +101,7 @@ fn auto_tag_tracklog(s: &mut crate::Session, p: &Value) -> Result<Value> {
let (mut no_time, mut outside, mut has_gps, mut assumed_utc, mut interpolated) = (0, 0, 0, 0, 0);
let mut ops = Vec::new();
let mut photos = Vec::new();
for id in s.targets(p) {
for id in s.targets(p)? {
let Some(ph) = s.catalog.photo(id) else { continue };
if ph.meta.gps.is_some() && !replace {
has_gps += 1;
@@ -183,7 +188,7 @@ pub fn specs() -> Vec<CommandSpec> {
|s, p| {
use lightcraft_catalog::dates::{iso_seconds, normalize_iso, shift_iso};
let c = "photo.setCaptureTime";
let targets: Vec<_> = s.targets(p).into_iter().filter(|id| s.catalog.photo(*id).is_some()).collect();
let targets: Vec<_> = s.targets(p)?.into_iter().filter(|id| s.catalog.photo(*id).is_some()).collect();
if targets.is_empty() {
return Err(bad(c, "no photos"));
}
+80 -4
View File
@@ -150,6 +150,55 @@ fn masks_edit(s: &mut Session, c: &str, label: &str, f: impl FnOnce(&mut Vec<Mas
Ok(json!({"activeMask": active}))
}
/// Most pieces a tapered ⇧-click segment is cut into.
const MAX_TAPER_STEPS: usize = 64;
/// The strokes a ⇧-click adds: `to` drawn on from point `from`, the last point of stroke `last` (a straight segment
/// to `to`'s first point, then the rest of `to`). When the brush's size, feather or flow changed since `last`, the
/// segment is cut into pieces whose values step from `last`'s to `to`'s, so the line tapers; strokes combine by their
/// maximum, so the pieces join without building up.
fn connected_strokes(from: Point, last: &BrushStroke, to: BrushStroke) -> Vec<BrushStroke> {
let Some(&first) = to.points.first() else { return vec![to] };
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9;
// pen pressure along the line: the last dab's at its start, the click's at its end (none when neither has any)
let pressured = !last.pressure.is_empty() || !to.pressure.is_empty();
let (p_from, p_to) = (last.pressure_at(0), to.pressure_at(0));
if same(last.size, to.size) && same(last.feather, to.feather) && same(last.flow, to.flow) {
let mut points = Vec::with_capacity(to.points.len() + 1);
points.push(from);
points.extend(to.points.iter().copied());
let pressure = if pressured { std::iter::once(p_from).chain((0..to.points.len()).map(|i| to.pressure_at(i))).collect() } else { Vec::new() };
return vec![BrushStroke { points, pressure, ..to }];
}
// about 5% of size, or 2 points of feather or flow, per piece
let ratio = if last.size > 0.0 && to.size > 0.0 { (to.size / last.size).ln().abs() / 1.05f64.ln() } else { 0.0 };
let needed = [ratio, (to.feather - last.feather).abs() / 2.0, (to.flow - last.flow).abs() / 2.0]
.into_iter()
.filter(|v| v.is_finite())
.fold(1.0f64, f64::max);
let steps = (needed.ceil() as usize).clamp(1, MAX_TAPER_STEPS);
let lerp = |a: f64, b: f64, t: f64| a + (b - a) * t;
let at = |t: f64| Point::new(lerp(from.x, first.x, t), lerp(from.y, first.y, t));
let mut out: Vec<BrushStroke> = (0..steps)
.map(|i| {
let (t0, t1) = (i as f64 / steps as f64, (i + 1) as f64 / steps as f64);
let p = |t: f64| (f64::from(p_from) + (f64::from(p_to) - f64::from(p_from)) * t) as f32;
BrushStroke {
points: vec![at(t0), at(t1)],
size: lerp(last.size, to.size, t1),
feather: lerp(last.feather, to.feather, t1),
flow: lerp(last.flow, to.flow, t1),
pressure: if pressured { vec![p(t0), p(t1)] } else { Vec::new() },
..to.clone()
}
})
.collect();
if to.points.len() > 1 {
out.push(to);
}
out
}
fn mask_id(p: &Value, active: Option<u32>, c: &str) -> Result<u32> {
p.get("id").and_then(Value::as_u64).map(|v| v as u32).or(active).ok_or_else(|| bad(c, "no mask selected (give `id`)"))
}
@@ -233,7 +282,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Stroke",
[],
None,
"{id?: maskId, points: [[x,y],…] normalized, size?: fraction of long edge (0.03), feather?, flow?, density?, erase?: bool, autoMask?: bool, pressure?: [p,…] pen pressure 0..1 per point (scales each dab's size and flow; omitted: full)}",
"{id?: maskId, points: [[x,y],…] normalized, size?: fraction of long edge (0.03), feather?, flow?, density?, erase?: bool, autoMask?: bool, pressure?: [p,…] pen pressure 0..1 per point (scales each dab's size and flow; omitted: full), connect?: bool — start from the last point of the mask's last stroke (⇧-click), size / feather / flow tapering from that stroke's to these} → {activeMask, connected}",
has_active,
|s, p| {
let pts: Vec<Point> = p
@@ -255,10 +304,12 @@ pub fn specs() -> Vec<CommandSpec> {
auto_mask: bool_or(p, "autoMask", false),
pressure: pressure_list(p.get("pressure"), pts_len)?,
};
let connect = bool_or(p, "connect", false);
let mut connected = false;
let next = s.active().and_then(|id| s.develop_of(id)).map(|d| d.next_mask_id()).unwrap_or(1);
let want = p.get("id").and_then(Value::as_u64).map(|v| v as u32).or(s.active_mask);
let adjust = super::mask_effects::new_mask_adjust(s, "brush");
masks_edit(s, "mask.brushStroke", "Brush", |masks, active| {
let mut out = masks_edit(s, "mask.brushStroke", "Brush", |masks, active| {
let i = match want.and_then(|m| masks.iter().position(|x| x.id == m)) {
Some(i) => i,
None => {
@@ -271,7 +322,28 @@ pub fn specs() -> Vec<CommandSpec> {
if let Some(MaskComponent { shape: MaskShape::Brush { strokes }, .. }) =
m.components.iter_mut().rev().find(|c| matches!(c.shape, MaskShape::Brush { .. }))
{
strokes.push(stroke);
// the previous stroke's end and its brush values (not its points)
let anchor = strokes.last().filter(|_| connect).and_then(|l| {
Some((
*l.points.last()?,
BrushStroke {
points: Vec::new(),
size: l.size,
feather: l.feather,
flow: l.flow,
// the pressure the last dab was painted with, when the stroke recorded any
pressure: if l.pressure.is_empty() { Vec::new() } else { vec![l.pressure_at(l.points.len().saturating_sub(1))] },
..BrushStroke::default()
},
))
});
match anchor {
Some((from, last)) => {
strokes.extend(connected_strokes(from, &last, stroke));
connected = true;
}
None => strokes.push(stroke),
}
} else {
m.components.push(MaskComponent {
name: None,
@@ -281,7 +353,11 @@ pub fn specs() -> Vec<CommandSpec> {
});
}
Ok(())
})
})?;
if let Some(o) = out.as_object_mut() {
o.insert("connected".into(), json!(connected));
}
Ok(out)
}
),
cmd!("mask.update", "Update Mask Shape", [], None, "{id?, component?: index (0), shape: MaskShape JSON}", has_active, |s, p| {
+2 -2
View File
@@ -20,7 +20,7 @@ fn can_merge(s: &Session) -> std::result::Result<(), String> {
fn run(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
let (kind, finish) = crate::merge::parse(id, p)?;
let ids: Vec<PhotoId> = s.targets(p);
let ids: Vec<PhotoId> = s.targets(p)?;
if !bool_or(p, "preview", false) {
return s.merge_now(kind, finish, &ids);
}
@@ -45,7 +45,7 @@ fn run(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
fn run_batch(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "merge.hdrBatch";
let (kind, finish) = crate::merge::parse("merge.hdr", p)?;
let ids: Vec<PhotoId> = s.targets(p);
let ids: Vec<PhotoId> = s.targets(p)?;
let sets = s.catalog.bracket_sets(&ids);
if sets.is_empty() {
return Err(bad(ID, crate::merge::NO_BRACKET_SETS));
+5 -1
View File
@@ -19,6 +19,7 @@ pub(crate) mod face_detect;
mod face_models;
mod face_recognize;
pub mod filters;
mod focus;
pub mod geocode;
pub mod keywords;
pub mod library;
@@ -34,6 +35,7 @@ mod organize;
mod prefs;
mod preset_files;
pub mod previews;
mod print;
mod query;
pub mod recheck;
mod slideshow;
@@ -109,7 +111,7 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
/// can take (issue #684; Add to My Photos first).
pub fn has_library_selection(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
if s.targets(&serde_json::Value::Null).iter().any(|id| s.catalog.photo(*id).is_none_or(|p| !p.local)) { Ok(()) } else { Err(LOCAL_ONLY.into()) }
if s.selected().iter().any(|id| s.catalog.photo(*id).is_none_or(|p| !p.local)) { Ok(()) } else { Err(LOCAL_ONLY.into()) }
}
/// Why an album command refused a Local-only selection.
pub const LOCAL_ONLY: &str = "only Local photos: albums hold library photos (Add to My Photos first)";
@@ -160,6 +162,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(prefs::specs());
v.extend(slideshow::specs());
v.extend(export::specs());
v.extend(print::specs());
v.extend(before::specs());
v.extend(browse::specs());
v.extend(missing::specs());
@@ -172,6 +175,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(face_models::specs());
v.extend(face_detect::specs());
v.extend(face_recognize::specs());
v.extend(focus::specs());
v.extend(activity::specs());
v
})
+7 -7
View File
@@ -22,7 +22,7 @@ fn stacks_of(s: &Session, targets: &[PhotoId]) -> Vec<StackId> {
fn in_stack(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
if stacks_of(s, &s.targets(&Value::Null)).is_empty() { Err("no stacked photo selected".into()) } else { Ok(()) }
if stacks_of(s, &s.selected()).is_empty() { Err("no stacked photo selected".into()) } else { Ok(()) }
}
fn has_stacks(s: &Session) -> std::result::Result<(), String> {
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"{ids?, name?} → {ids: [new photo ids]} — a new catalog entry sharing the original file, with independent settings; stacked with its original and named `name` or \"Copy N\"",
has_selection,
|s, p| {
let targets = s.targets(p);
let targets = s.targets(p)?;
let name = str_param(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string);
let mut made = Vec::new();
for t in targets {
@@ -134,7 +134,7 @@ pub fn specs() -> Vec<CommandSpec> {
"{ids?, top?: photoId (default: the active photo), collapsed?: bool (default true)} — stacks the photos are already in are merged",
has_selection,
|s, p| {
let targets = s.targets(p);
let targets = s.targets(p)?;
let top = p
.get("top")
.and_then(Value::as_u64)
@@ -153,11 +153,11 @@ pub fn specs() -> Vec<CommandSpec> {
}
),
cmd!("stack.ungroup", "Ungroup Stack", ["Photo", "Stack"], Some("Cmd+Shift+G"), "{ids?}", in_stack, |s, p| {
let ops = s.catalog.ungroup_ops(&s.targets(p));
let ops = s.catalog.ungroup_ops(&s.targets(p)?);
Ok(json!({"ungrouped": commit_ops(s, "Ungroup Stack", ops)?}))
}),
cmd!("stack.remove", "Remove from Stack", ["Photo", "Stack"], None, "{ids?}", in_stack, |s, p| {
let ops = s.catalog.remove_from_stacks_ops(&s.targets(p));
let ops = s.catalog.remove_from_stacks_ops(&s.targets(p)?);
Ok(json!({"changed": commit_ops(s, "Remove from Stack", ops)?}))
}),
cmd!("stack.setTop", "Set as Top of Stack", ["Photo", "Stack"], Some("Shift+S"), "{id?} (default: the active photo)", in_stack, |s, p| {
@@ -189,7 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
),
cmd!("stack.toggle", "Expand/Collapse Stack", ["Photo", "Stack"], Some("S"), "{ids?, collapsed?: bool}", in_stack, |s, p| {
let stacks = stacks_of(s, &s.targets(p));
let stacks = stacks_of(s, &s.targets(p)?);
let first = stacks.first().and_then(|id| s.catalog.stack(*id)).map(|st| st.collapsed).unwrap_or(false);
let collapsed = bool_or(p, "collapsed", !first);
set_collapsed(s, stacks, collapsed, if collapsed { "Collapse Stack" } else { "Expand Stack" })
@@ -212,7 +212,7 @@ pub fn specs() -> Vec<CommandSpec> {
|s, p| {
let gap = f64_or(p, "gap", 60.0).max(0.0);
let explicit = p.get("ids").is_some();
let pool = if explicit || s.selection.ids.len() > 1 { s.targets(p) } else { s.visible_cloned() };
let pool = if explicit || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() };
let groups = s.catalog.auto_stack_groups(&pool, gap);
let photos: usize = groups.iter().map(Vec::len).sum();
if bool_or(p, "preview", false) {
+12 -2
View File
@@ -57,10 +57,20 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(g) = &group {
it.preset.group = g.clone();
}
// the profile it names (issue #1001): one the user imported, or ours for a basic one
let mut profile = Value::Null;
if let Some((r, _)) = crate::profile_refs::apply(&mut it.preset.settings, &s.lut_profiles) {
let look = it.preset.settings["profile"]["look"].clone();
it.unmapped.retain(|u| u != "Look");
it.unmapped.extend(crate::profile_refs::report(&look, &r));
profile = json!({"name": look["name"], "id": it.preset.settings["profile"].get("id")});
}
let (name, grp) = (it.preset.name.clone(), it.preset.group.clone());
let id = if dry { Some(it.preset.id.clone()) } else { s.add_presets(vec![it.preset]).pop() };
match id {
Some(id) => imported.push(json!({"id": id, "name": name, "group": grp, "file": f, "unmapped": it.unmapped})),
Some(id) => {
imported.push(json!({"id": id, "name": name, "group": grp, "file": f, "unmapped": it.unmapped, "profile": profile}))
}
None => skipped += 1,
}
}
@@ -108,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Presets",
[],
None,
"{paths: [file or folder], group?, dryRun?} — .lcpreset, XMP presets, .lrtemplate, photos carrying edits (DNG/JPEG/TIFF \"DNG presets\"), Luminar looks (.lmp, .mplumpack collections) and .zip bundles of these; folders give their name as group; crs: fields mapped per docs/xmp-interop.md; local adjustment presets (Lightroom .lrtemplate, Camera Raw local .xmp, .lceffect) become mask effects (`mask.effects`; divider presets become their groups) → {imported: [{id,name,group,file,unmapped}], skipped, failed, effects: [{name,group,file,unmapped}], effectDividers: [{name,group,file}]}",
"{paths: [file or folder], group?, dryRun?} — .lcpreset, XMP presets, .lrtemplate, photos carrying edits (DNG/JPEG/TIFF \"DNG presets\"), Luminar looks (.lmp, .mplumpack collections) and .zip bundles of these; folders give their name as group; crs: fields mapped per docs/xmp-interop.md; local adjustment presets (Lightroom .lrtemplate, Camera Raw local .xmp, .lceffect) become mask effects (`mask.effects`; divider presets become their groups); a profile the preset names applies when it was imported with profile.import (before or after) → {imported: [{id,name,group,file,unmapped,profile: {name, id}|null}], skipped, failed, effects: [{name,group,file,unmapped}], effectDividers: [{name,group,file}]}",
always,
import
),
+3 -3
View File
@@ -152,7 +152,7 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "a preview build is already running"));
}
// explicit ids, else the selection, else everything in view
let ids = if p.get("ids").is_some() || p.get("id").is_some() || !s.selection.ids.is_empty() { s.targets(p) } else { s.visible_cloned() };
let ids = if p.get("ids").is_some() || p.get("id").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() };
let jobs: Vec<Vec<RenderJob>> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect();
let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() });
s.preview_build = Some(state.clone());
@@ -324,7 +324,7 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
if background && s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) {
return Err(bad(C, "a preview build is already running"));
}
let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p) } else { s.visible_cloned() };
let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() };
let mut jobs: Vec<SmartJob> = Vec::new();
for id in ids {
let Some(ph) = s.catalog.photo(id).cloned() else { continue };
@@ -503,7 +503,7 @@ pub fn specs() -> Vec<CommandSpec> {
smart_location
),
cmd!(query "photo.smartPreview", "Smart Preview Status", [], None, "{id?} → {smartPreview: bool, originalOnline: bool}", always, |s, p| {
let id = s.targets(p).first().copied().ok_or_else(|| bad("photo.smartPreview", "no photo"))?;
let id = s.targets(p)?.first().copied().ok_or_else(|| bad("photo.smartPreview", "no photo"))?;
let online = match s.catalog.photo(id).map(|p| p.source.clone()) {
Some(lightcraft_catalog::Source::File { path }) => std::path::Path::new(&path).exists(),
_ => true,
+353
View File
@@ -0,0 +1,353 @@
//! `print.*`: the Print module as commands.
//!
//! The module's state is [`Session::print`] (layout, image settings, page, guides, job), so the
//! app, CLI, control channel and MCP share one print. Lengths are inches in page space (origin at
//! the top-left of the page as printed); cell ids and photo ids are numbers. Nothing here touches
//! the catalog, so none of it is journaled or undoable; saved templates live in prefs.json.
//!
//! * `print.get`, `print.set {layout?, image?, page?, guides?, job?}`, `print.reset`
//! * `print.cell.add|move|resize|delete|stack|photo|page`, `print.layout.autoLayout|newPage|clear`
//! * `print.exportPdf {path, ids?}`
//! * `print.template.list|save|apply|delete`
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, cmd, f64_req};
use crate::print::layout::{Layout, MAX_PAGES, Rect, Snap, Stack, paper_names, paper_size};
use crate::print::template::{MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name};
use crate::{Result, Session};
fn rect_json(r: &Rect) -> Value {
json!({"x": r.x, "y": r.y, "w": r.w, "h": r.h})
}
/// The state, with what a front end needs to draw it (page size, printable area, grid cells).
fn state(s: &Session, photos: usize) -> Value {
let l = &s.print.layout;
let mut out = json!({
"settings": s.print,
"papers": paper_names().filter_map(|n| paper_size(n).map(|(w, h)| json!({"name": n, "width": w, "height": h}))).collect::<Vec<_>>(),
"overlaps": l.has_overlaps(),
"photos": photos,
});
if let (Ok((w, h)), Ok(area), Some(o)) = (l.page_size(), l.printable(), out.as_object_mut()) {
o.insert("pageWidth".into(), json!(w));
o.insert("pageHeight".into(), json!(h));
o.insert("printable".into(), rect_json(&area));
o.insert("pageCount".into(), json!(l.page_count(photos)));
o.insert("cellsPerPage".into(), json!(l.cells_per_page()));
if !l.style.is_package() {
o.insert("gridCells".into(), json!(l.grid_rects().unwrap_or_default().iter().map(rect_json).collect::<Vec<_>>()));
}
}
out
}
fn reply(s: &Session) -> Result<Value> {
Ok(state(s, s.targets(&Value::Null)?.len()))
}
/// Applies `patch` over `dst`: objects merge key by key, anything else replaces.
fn merge(dst: &mut Value, patch: &Value, depth: usize) {
match (dst, patch) {
(Value::Object(d), Value::Object(p)) if depth < 8 => {
for (k, v) in p {
match d.get_mut(k) {
Some(slot) => merge(slot, v, depth + 1),
None => {
d.insert(k.clone(), v.clone());
}
}
}
}
(d, p) => *d = p.clone(),
}
}
fn get(s: &mut Session, p: &Value) -> Result<Value> {
Ok(state(s, s.targets(p)?.len()))
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.set";
let patch = p.as_object().ok_or_else(|| bad(ID, "params must be an object"))?;
if let Some(k) = patch.keys().find(|k| !matches!(k.as_str(), "layout" | "image" | "page" | "guides" | "job")) {
return Err(bad(ID, format!("unknown parameter `{k}` (one of layout, image, page, guides, job)")));
}
if let Some(l) = patch.get("layout").and_then(Value::as_object)
&& let Some(k) = l.keys().find(|k| matches!(k.as_str(), "cells" | "pages" | "nextId"))
{
return Err(bad(ID, format!("`layout.{k}` is changed with the print.cell.* and print.layout.* commands")));
}
let mut value = serde_json::to_value(&s.print).map_err(|e| bad(ID, e.to_string()))?;
merge(&mut value, p, 0);
let mut next: PrintSettings = serde_json::from_value(value).map_err(|e| bad(ID, e.to_string()))?;
// A new paper, orientation or margin may leave cells outside the page: pull them back.
if next.layout.page.printable().is_ok() {
next.layout.fit_cells().map_err(|e| bad(ID, e))?;
}
next.validate().map_err(|e| bad(ID, e))?;
s.print = next;
reply(s)
}
fn reset(s: &mut Session, _: &Value) -> Result<Value> {
s.print = PrintSettings::default();
reply(s)
}
fn cell_id(p: &Value, id: &str) -> Result<u32> {
p.get("id").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()).ok_or_else(|| bad(id, "missing cell `id`"))
}
fn opt_f64(p: &Value, key: &str, id: &str) -> Result<Option<f64>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_f64().map(Some).ok_or_else(|| bad(id, format!("`{key}` must be a number"))),
}
}
/// Snaps `r` (a cell being moved or resized) when the call asks for it.
fn snapped(l: &Layout, guides: &crate::print::layout::Guides, id: u32, r: Rect, p: &Value, resize: bool, cmd: &str) -> Result<Rect> {
let on = match p.get("snap") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(_) => return Err(bad(cmd, "`snap` must be true or false")),
};
if !on || guides.snap == Snap::Off {
return Ok(r);
}
let threshold = opt_f64(p, "threshold", cmd)?.unwrap_or(0.1);
let f = if resize { Layout::snap_resize } else { Layout::snap_move };
f(l, id, r, guides.snap, guides.grid_size, threshold).map_err(|e| bad(cmd, e))
}
fn cell_add(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.cell.add";
let (w, h) = (f64_req(p, "width", ID)?, f64_req(p, "height", ID)?);
let mut next = s.print.layout.clone();
let id = next.add_cell(w, h).map_err(|e| bad(ID, e))?;
if let (Some(x), Some(y)) = (opt_f64(p, "x", ID)?, opt_f64(p, "y", ID)?) {
if let Some(page) = p.get("page").and_then(Value::as_u64) {
let page = u32::try_from(page).map_err(|_| bad(ID, "`page` is too large"))?;
next.set_cell_page(id, page).map_err(|e| bad(ID, e))?;
}
next.move_cell(id, x, y).map_err(|e| bad(ID, e))?;
}
if let Some(v) = p.get("photo").filter(|v| !v.is_null()) {
let photo = v.as_u64().ok_or_else(|| bad(ID, "`photo` must be a photo id"))?;
next.set_cell_photo(id, Some(photo)).map_err(|e| bad(ID, e))?;
}
s.print.layout = next;
let cell = s.print.layout.cell(id).cloned();
Ok(json!({"id": id, "cell": cell, "pages": s.print.layout.pages}))
}
fn cell_move(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.cell.move";
let id = cell_id(p, ID)?;
let (x, y) = (f64_req(p, "x", ID)?, f64_req(p, "y", ID)?);
let mut next = s.print.layout.clone();
let size = next.cell(id).map(|c| c.rect).ok_or_else(|| bad(ID, format!("no cell {id}")))?;
let target = snapped(&next, &s.print.guides, id, Rect::new(x, y, size.w, size.h), p, false, ID)?;
let r = next.move_cell(id, target.x, target.y).map_err(|e| bad(ID, e))?;
s.print.layout = next;
Ok(json!({"id": id, "rect": r}))
}
fn cell_resize(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.cell.resize";
let id = cell_id(p, ID)?;
let mut next = s.print.layout.clone();
let cur = next.cell(id).map(|c| c.rect).ok_or_else(|| bad(ID, format!("no cell {id}")))?;
let want = Rect::new(
opt_f64(p, "x", ID)?.unwrap_or(cur.x),
opt_f64(p, "y", ID)?.unwrap_or(cur.y),
opt_f64(p, "width", ID)?.unwrap_or(cur.w),
opt_f64(p, "height", ID)?.unwrap_or(cur.h),
);
let target = snapped(&next, &s.print.guides, id, want, p, true, ID)?;
let r = next.resize_cell(id, target).map_err(|e| bad(ID, e))?;
s.print.layout = next;
Ok(json!({"id": id, "rect": r}))
}
fn cell_delete(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.cell.delete";
let id = cell_id(p, ID)?;
s.print.layout.delete_cell(id).map_err(|e| bad(ID, e))?;
Ok(json!({"deleted": id, "cells": s.print.layout.cells.len()}))
}
fn cell_stack(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.cell.stack";
let id = cell_id(p, ID)?;
let how = match p.get("order").and_then(Value::as_str) {
Some("toBack") => Stack::ToBack,
Some("backward") => Stack::Backward,
Some("forward") => Stack::Forward,
Some("toFront") => Stack::ToFront,
_ => return Err(bad(ID, "`order` must be toBack, backward, forward or toFront")),
};
s.print.layout.restack(id, how).map_err(|e| bad(ID, e))?;
Ok(json!({"order": s.print.layout.cells.iter().map(|c| c.id).collect::<Vec<_>>()}))
}
fn cell_photo(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.cell.photo";
let id = cell_id(p, ID)?;
let photo = match p.get("photo") {
None | Some(Value::Null) => None,
Some(v) => {
let n = v.as_u64().ok_or_else(|| bad(ID, "`photo` must be a photo id or null"))?;
if s.catalog.photo(lightcraft_catalog::PhotoId(n)).is_none() {
return Err(bad(ID, format!("no photo {n}")));
}
Some(n)
}
};
s.print.layout.set_cell_photo(id, photo).map_err(|e| bad(ID, e))?;
Ok(json!({"id": id, "photo": photo}))
}
fn cell_page(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.cell.page";
let id = cell_id(p, ID)?;
let page = p.get("page").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()).ok_or_else(|| bad(ID, "missing zero-based `page`"))?;
s.print.layout.set_cell_page(id, page).map_err(|e| bad(ID, e))?;
Ok(json!({"id": id, "page": page}))
}
fn auto_layout(s: &mut Session, _: &Value) -> Result<Value> {
s.print.layout.auto_layout().map_err(|e| bad("print.layout.autoLayout", e))?;
Ok(json!({"pages": s.print.layout.pages, "cells": s.print.layout.cells}))
}
fn new_page(s: &mut Session, _: &Value) -> Result<Value> {
let page = s.print.layout.new_page().map_err(|e| bad("print.layout.newPage", e))?;
Ok(json!({"page": page, "pages": s.print.layout.pages, "max": MAX_PAGES}))
}
fn clear(s: &mut Session, _: &Value) -> Result<Value> {
s.print.layout.clear();
Ok(json!({"pages": 1, "cells": 0}))
}
fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.exportPdf";
let path = p.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(ID, "missing path"))?;
if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !matches!(k.as_str(), "path" | "ids" | "id"))) {
return Err(bad(ID, format!("unknown parameter `{k}` (one of path, ids; change the print with print.set)")));
}
if p.get("ids").is_some_and(|v| v.as_array().is_none_or(|a| a.iter().any(|v| v.as_u64().is_none()))) {
return Err(bad(ID, "ids must be an array of photo ids"));
}
if p.get("id").is_some_and(|v| v.as_u64().is_none()) {
return Err(bad(ID, "id must be a photo id"));
}
s.check_write_target(path).map_err(|e| bad(ID, e))?;
let ids = s.targets(p)?;
let settings = s.print.clone();
// a printer profile that can't be used fails the print before anything renders
crate::print_color::PrintColorJob::new(&settings.job.color).map_err(|e| bad(ID, e))?;
let title = std::path::Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("Print").to_string();
let work = crate::print::compose::prepare(s, &settings, &ids).map_err(|e| bad(ID, e))?;
let total = work.len() as u64;
let row = s.activity.start("export", "Printing to PDF", crate::activity::Cancel::No);
row.progress(0, total);
let pages = work
.run(&mut |done, name| {
row.progress(done as u64, total);
row.detail(name);
true
})
.map_err(|e| bad(ID, e))?;
let bytes = crate::print::output::write(&pages, &settings.job, &title).map_err(|e| bad(ID, e))?;
s.check_write_target(path).map_err(|e| bad(ID, e))?;
crate::export::write_file(path, &bytes).map_err(|e| bad(ID, e))?;
Ok(json!({"path": path, "pages": pages.len(), "photos": ids.len(), "bytes": bytes.len()}))
}
// ---- templates ------------------------------------------------------------------------------
fn template_list(s: &Session) -> Value {
json!({"templates": s.print_templates.iter().map(|t| json!({"name": t.name, "style": t.settings.pointer("/layout/style"), "settings": t.settings})).collect::<Vec<_>>()})
}
fn template_name(p: &Value, id: &str) -> Result<String> {
clean_name(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing `name`"))?).map_err(|e| bad(id, e))
}
fn template_save(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.template.save";
let name = template_name(p, ID)?;
let t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?;
match s.print_templates.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(x) => *x = t,
None => {
if s.print_templates.len() >= MAX_TEMPLATES {
return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first")));
}
s.print_templates.push(t);
}
}
s.save_prefs()?;
Ok(template_list(s))
}
fn template_apply(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.template.apply";
let name = template_name(p, ID)?;
let t = s
.print_templates
.iter()
.find(|x| x.name.eq_ignore_ascii_case(&name))
.ok_or_else(|| bad(ID, format!("no print template `{name}` (see print.template.list)")))?;
s.print = t.settings(&s.print.guides).map_err(|e| bad(ID, e))?;
reply(s)
}
fn template_delete(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "print.template.delete";
let name = template_name(p, ID)?;
let before = s.print_templates.len();
s.print_templates.retain(|x| !x.name.eq_ignore_ascii_case(&name));
if s.print_templates.len() == before {
return Err(bad(ID, format!("no print template `{name}`")));
}
s.save_prefs()?;
Ok(template_list(s))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "print.get", "Print Settings", [], None,
"{ids?} → {settings: {layout, image, page, guides, job}, papers, pageWidth, pageHeight, printable, pageCount, cellsPerPage, gridCells?, overlaps}; lengths are inches",
always, get),
cmd!(query "print.set", "Set Print Settings", [], None,
"{layout?: {style: singleImage|contactSheet|picturePackage|customPackage, page: {paper, customWidth, customHeight, orientation: portrait|landscape, margins: {top,right,bottom,left}}, grid: {columns, rows, spacingX, spacingY, keepSquare}, spacing}, image?: {zoomToFill, rotateToFit, borderEnabled, borderWidth, borderColor: [r,g,b], strokeEnabled, strokeWidthPt, strokeColor}, page?: {background: [r,g,b], pageNumbers, pageInfo, cropMarks} (Page Options: single image and contact sheet only), guides?: {showRulers, units: in|cm|mm|pt, snap: off|cells|grid, gridSize, showMargins, showBleed, showPageGrid, showCells, showDimensions}, job?: {ppi: 72..720, color?: {profile: {kind: managed, space: srgb|adobeRgb} | {kind: icc, path}, intent: perceptual|relative, blackPointCompensation, brightness: -100..100, contrast: -100..100, sharpen: off|low|standard|high, media: matte|glossy, sixteenBit}}} — merges into the current print; cells and pages change with print.cell.* / print.layout.*; → print.get",
always, set),
cmd!(query "print.reset", "Reset Print Settings", [], None, "{} → print.get", always, reset),
cmd!(query "print.cell.add", "Add Print Cell", [], None,
"{width, height, x?, y?, page?, photo?} inches; picture/custom package → {id, cell, pages}; the cell goes to the first free spot unless x and y are given",
always, cell_add),
cmd!(query "print.cell.move", "Move Print Cell", [], None, "{id, x, y, snap?: bool, threshold?: inches} → {id, rect}; snap uses the guides' snap mode", always, cell_move),
cmd!(query "print.cell.resize", "Resize Print Cell", [], None,
"{id, width?, height?, x?, y?, snap?: bool, threshold?} → {id, rect}", always, cell_resize),
cmd!(query "print.cell.delete", "Delete Print Cell", [], None, "{id}", always, cell_delete),
cmd!(query "print.cell.stack", "Arrange Print Cell", [], None, "{id, order: toBack|backward|forward|toFront} → {order: cell ids back to front}", always, cell_stack),
cmd!(query "print.cell.photo", "Set Print Cell Photo", [], None, "{id, photo: photo id | null} (custom package: the photo printed in the cell)", always, cell_photo),
cmd!(query "print.cell.page", "Move Print Cell to Page", [], None, "{id, page: zero-based}", always, cell_page),
cmd!(query "print.layout.autoLayout", "Auto Layout", [], None, "{} — packs the package's cells onto as few pages as possible → {pages, cells}", always, auto_layout),
cmd!(query "print.layout.newPage", "New Print Page", [], None, "{} → {page, pages}", always, new_page),
cmd!(query "print.layout.clear", "Clear Print Layout", [], None, "{} — removes every cell and extra page", always, clear),
cmd!(query "print.exportPdf", "Print to PDF", [], None,
"{path, ids?: photo ids (default selection)} → {path, pages, photos, bytes}; prints the current print.get settings; replaces an existing output, never an original",
always, export_pdf),
cmd!(query "print.template.list", "Print Templates", [], None, "{} → {templates: [{name, style, settings}]}", always, |s, _| Ok(template_list(s))),
cmd!(query "print.template.save", "Save Print Template", [], None,
"{name} — saves the layout, image settings, page and job (not the cells' photos or the guides); an existing name (any case) is replaced → print.template.list",
always, template_save),
cmd!(query "print.template.apply", "Apply Print Template", [], None, "{name} → print.get", always, template_apply),
cmd!(query "print.template.delete", "Delete Print Template", [], None, "{name} → print.template.list", always, template_delete),
]
}
+2 -2
View File
@@ -12,7 +12,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
let mut merged = Vec::new();
let mut backups = Vec::new();
let mut failed = Vec::new();
let ids = s.targets(p);
let ids = s.targets(p)?;
let owners = crate::sidecar::StemOwners::among(&s.catalog, &ids);
for id in ids {
match s.save_sidecar_with(id, &owners) {
@@ -37,7 +37,7 @@ fn read(s: &mut Session, p: &Value) -> Result<Value> {
let mut read = Vec::new();
let mut failed = Vec::new();
let mut warnings = Vec::new();
for id in s.targets(p) {
for id in s.targets(p)? {
match s.read_sidecar_op_with_warnings(id) {
Ok(Some((op, from, mut photo_warnings))) => {
ops.push(op);
+1 -1
View File
@@ -83,7 +83,7 @@ pub fn prepare(session: &mut Session, p: &Value) -> Result<Prepared, String> {
if p.get("id").is_some_and(|v| v.as_u64().is_none()) {
return Err("id must be a photo id".into());
}
let ids = session.targets(p);
let ids = session.targets(p).map_err(|e| e.to_string())?;
if ids.is_empty() || ids.len() > 1000 {
return Err("select between 1 and 1000 photos".into());
}
+43 -1
View File
@@ -99,6 +99,21 @@ fn adjust(c: &XmpValue) -> Value {
Value::Object(a)
}
/// The correction's local sliders we have no counterpart for (e.g. `LocalGrain`), when set:
/// reported, never dropped silently.
fn unmapped_local(c: &XmpValue) -> Vec<String> {
let XmpValue::Struct(m) = c else { return Vec::new() };
m.keys()
.filter_map(|k| {
let field = k.strip_prefix("crs:").filter(|f| f.starts_with("Local"))?;
// 100 = "curve saturation unchanged", written with every correction
let neutral = if field == "LocalCurveRefineSaturation" { 100.0 } else { 0.0 };
let set = num(c, k).is_some_and(|v| v != neutral);
(set && !LOCAL.iter().any(|(crs, ..)| *crs == field)).then(|| field.to_string())
})
.collect()
}
/// Perceptual lightness 0..1 (how range masks store luminance) → our range scale: log
/// luminance on −8..+4 EV mapped to 0..1.
fn lightness_to_range(l: f64) -> f64 {
@@ -214,8 +229,12 @@ fn component(m: &XmpValue, container: &str, aspect: f64) -> Result<Value, String
Some("2") => {
let q: Vec<f64> = text(r, "crs:LumRange").unwrap_or("0 0 1 1").split_whitespace().filter_map(|v| v.parse().ok()).collect();
let [a, b, c, d] = q[..] else { return Err("luminance range".into()) };
// full strength at white (1, the top of their scale) takes in everything brighter: ours
// goes on above scene white, so that end stays open instead of cutting off at 0 EV
let open_top = c >= 1.0;
let (a, b, c, d) = (lightness_to_range(a), lightness_to_range(b), lightness_to_range(c), lightness_to_range(d));
json!({"kind": "luminanceRange", "lo": b, "hi": c, "lo_feather": (b - a).max(0.0), "hi_feather": (d - c).max(0.0)})
let (hi, hi_feather) = if open_top { (1.0, 0.0) } else { (c, (d - c).max(0.0)) };
json!({"kind": "luminanceRange", "lo": b, "hi": hi, "lo_feather": (b - a).max(0.0), "hi_feather": hi_feather})
}
Some("3") => {
let q: Vec<f64> = text(r, "crs:DepthRange").unwrap_or("0 0 1 1").split_whitespace().filter_map(|v| v.parse().ok()).collect();
@@ -252,6 +271,7 @@ pub fn masks(values: &Values, aspect: f64) -> (Vec<Value>, Vec<String>) {
if parts.is_empty() {
continue;
}
skipped.extend(unmapped_local(c));
// brush dabs of one correction are one brush component
let mut merged: Vec<Value> = Vec::new();
for p in parts {
@@ -506,6 +526,28 @@ mod tests {
assert_ne!(render(&DevelopSettings { light: s.light, ..Default::default() }), render(&s), "the masks change the picture");
}
#[test]
fn range_to_white_stays_open_and_unmapped_local_sliders_are_reported() {
// written for this test: a highlights range (full from 0.85 up to white) carrying a local slider we lack
let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/">
<crs:MaskGroupBasedCorrections><rdf:Seq>
<rdf:li><rdf:Description crs:What="Correction" crs:LocalClarity2012="-0.3" crs:LocalGrain="0.4" crs:LocalCurveRefineSaturation="100">
<crs:CorrectionMasks><rdf:Seq>
<rdf:li crs:What="Mask/RangeMask"><crs:CorrectionRangeMask crs:Type="2" crs:LumRange="0.6 0.85 1 1"/></rdf:li>
</rdf:Seq></crs:CorrectionMasks>
</rdf:Description></rdf:li>
</rdf:Seq></crs:MaskGroupBasedCorrections>
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
let d = lightcraft_meta::parse_xmp(x).unwrap();
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
let s = DevelopSettings::default().merged(&partial).expect("valid settings");
let MaskShape::LuminanceRange { hi, hi_feather, .. } = &s.masks[0].components[0].shape else { panic!() };
assert_eq!((*hi, *hi_feather), (1.0, 0.0), "brighter than scene white is still in the range");
assert_eq!(s.masks[0].adjust.clarity, -30.0);
assert_eq!(unmapped, ["Mask: LocalGrain"], "a refine saturation of 100 is neutral, not reported");
}
#[test]
fn lrtemplate_corrections() {
let t = r#"s = { title = "Grad", value = { settings = { Exposure2012 = 0.1, GradientBasedCorrections = {
+10
View File
@@ -30,6 +30,16 @@ pub fn load(s: &mut Session) {
creator: "LightCraft Demo".into(),
..Default::default()
};
// one demo photo carries a camera focus point (as a Sony raw would), on the bloom's centre, so
// View ▸ Show Focus Point and Zoom to Focus Point can be tried without a camera file
if sc.name == "Cosmos bloom" {
p.meta.focus = Some(lightcraft_meta::FocusPoint {
rect: lightcraft_geom::Rect { x0: 0.42, y0: 0.433, x1: 0.50, y1: 0.487 },
mode: Some("AF-S".into()),
area: Some("Flexible Spot".into()),
tracking: None,
});
}
p.rating = [0, 3, 4, 5, 2, 0, 4, 3][sc.id as usize % 8];
p.flag = match sc.id % 6 {
1 => Flag::Pick,
+63
View File
@@ -0,0 +1,63 @@
//! Paths stored in a file LightCraft reads but the user did not choose path by path, such as the
//! originals a Lightroom catalog lists.
//!
//! Such a path reaches the file system only through [`resolve`]: a relative path is taken from the
//! document's folder, and only local files, or files on the network share the document itself is
//! on, are looked at (see `craft_docpath`). A path that is not followed is handled like a missing
//! file.
use std::fmt;
use std::path::{Path, PathBuf};
pub use craft_docpath::Refused;
/// Why a stored path is not followed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotFollowed {
/// The path is on another computer (other than the document's share), names a device, is a
/// URL, or is not a usable path.
Refused(Refused),
/// The path is not an absolute path on this computer, such as a Windows drive path read on
/// macOS or Linux.
NotHere,
}
impl fmt::Display for NotFollowed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Refused(r) => r.fmt(f),
Self::NotHere => f.write_str("the path is not a path on this computer"),
}
}
}
impl std::error::Error for NotFollowed {}
/// The file to look at for `stored`, a path or `file:` URL stored in the document at `document`,
/// or why it is not followed. A relative `document` is taken from the working directory, where it
/// was opened from.
pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, NotFollowed> {
let document = document.map(|d| if d.is_relative() { std::path::absolute(d).unwrap_or_else(|_| d.to_path_buf()) } else { d.to_path_buf() });
let path = craft_docpath::resolve(stored, document.as_deref()).map_err(NotFollowed::Refused)?;
// A path that is still relative would be taken from the working directory, which the
// document does not choose.
if path.is_relative() {
return Err(NotFollowed::NotHere);
}
Ok(path)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relative_paths_are_taken_from_the_document_folder_and_other_computers_are_refused() {
let doc = std::env::temp_dir().join("lrcat").join("catalog.lrcat");
assert_eq!(resolve("Photos/a.jpg", Some(&doc)), Ok(std::env::temp_dir().join("lrcat").join("Photos").join("a.jpg")));
assert_eq!(resolve("a.jpg", None), Err(NotFollowed::NotHere));
assert_eq!(resolve(r"\\192.0.2.1\share\x.jpg", Some(&doc)), Err(NotFollowed::Refused(Refused::Network)));
assert_eq!(resolve("file://192.0.2.1/s/x.jpg", Some(&doc)), Err(NotFollowed::Refused(Refused::Network)));
assert_eq!(resolve(r"\\.\COM1", Some(&doc)), Err(NotFollowed::Refused(Refused::Device)));
}
}
+160 -13
View File
@@ -185,6 +185,17 @@ impl DestinationMode {
}
}
impl Conflict {
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"unique" => Some(Self::Unique),
"overwrite" => Some(Self::Overwrite),
"skip" => Some(Self::Skip),
_ => None,
}
}
}
/// A named set of `app.export` params.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExportPreset {
@@ -214,6 +225,18 @@ pub enum SharpenFor {
Glossy,
}
impl SharpenFor {
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"none" => Some(Self::None),
"screen" => Some(Self::Screen),
"matte" => Some(Self::Matte),
"glossy" => Some(Self::Glossy),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SharpenAmount {
@@ -223,6 +246,17 @@ pub enum SharpenAmount {
High,
}
impl SharpenAmount {
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"low" => Some(Self::Low),
"standard" => Some(Self::Standard),
"high" => Some(Self::High),
_ => None,
}
}
}
/// Where a watermark sits.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -537,6 +571,18 @@ pub enum MetadataPolicy {
None,
}
impl MetadataPolicy {
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"all" => Some(Self::All),
"allexceptcamera" => Some(Self::AllExceptCamera),
"copyright" => Some(Self::Copyright),
"none" => Some(Self::None),
_ => None,
}
}
}
/// Transfer curve of an HDR AVIF export (`hdrTransfer`): PQ (absolute, SDR white at 203 cd/m²) or
/// HLG (relative to the display; BT.2100 with SDR white at signal 0.75).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -814,6 +860,10 @@ impl ExportOptions {
let s = string(cmd, k, v)?;
if options.iter().any(|o| o.eq_ignore_ascii_case(s)) { Ok(()) } else { Err(bad(format!("`{k}` must be one of {}", options.join("|")))) }
};
// a choice `from_json` reads with the same `parse`, so what passes here is what gets exported
let parses = |k: &str, v: &Value, parse: fn(&str) -> bool, options: &[&str]| -> crate::Result<()> {
if parse(string(cmd, k, v)?) { Ok(()) } else { Err(bad(format!("`{k}` must be one of {}", options.join("|")))) }
};
for (k, v) in obj {
if v.is_null() {
continue;
@@ -869,10 +919,10 @@ impl ExportOptions {
"naming" | "subfolder" | "path" | "dir" | "preset" => {
string(cmd, k, v)?;
}
"sharpen" => one_of(k, v, &["none", "screen", "matte", "glossy"])?,
"sharpenAmount" => one_of(k, v, &["low", "standard", "high"])?,
"sharpen" => parses(k, v, |s| SharpenFor::parse(s).is_some(), &["none", "screen", "matte", "glossy"])?,
"sharpenAmount" => parses(k, v, |s| SharpenAmount::parse(s).is_some(), &["low", "standard", "high"])?,
"hdrTransfer" => one_of(k, v, &["pq", "hlg"])?,
"conflict" => one_of(k, v, &["unique", "overwrite", "skip"])?,
"conflict" => parses(k, v, |s| Conflict::parse(s).is_some(), &["unique", "overwrite", "skip"])?,
"destinationMode" => one_of(k, v, &["specificFolder", "sameAsOriginal"])?,
"tiffCompression" => one_of(k, v, &["none", "lzw", "zip", "deflate"])?,
"jxlEffort" => one_of(k, v, &["fast", "normal"])?,
@@ -880,7 +930,7 @@ impl ExportOptions {
serde_json::from_value::<DngCompression>(v.clone())
.map_err(|_| bad(format!("`{k}` must be one of lossless|deflate|uncompressed|lossy")))?;
}
"metadata" => one_of(k, v, &["all", "allExceptCamera", "copyright", "none"])?,
"metadata" => parses(k, v, |s| MetadataPolicy::parse(s).is_some(), &["all", "allExceptCamera", "copyright", "none"])?,
"colorSpace" => {
if OutputSpace::parse(string(cmd, k, v)?).is_none() {
return Err(bad(format!("`{k}` must be one of srgb|displayP3|adobeRgb|proPhoto|rec2020")));
@@ -982,13 +1032,13 @@ impl ExportOptions {
resize: Self::resize_from_json(p),
ppi: u("ppi").filter(|v| *v > 0).map_or(d.ppi, |v| v.min(u16::MAX as u64) as u16),
limit_kb: u("limitKb").filter(|v| *v > 0).map(|v| v.min(u32::MAX as u64) as u32),
sharpen: enm(p, "sharpen").unwrap_or(d.sharpen),
sharpen_amount: enm(p, "sharpenAmount").unwrap_or(d.sharpen_amount),
sharpen: s("sharpen").and_then(SharpenFor::parse).unwrap_or(d.sharpen),
sharpen_amount: s("sharpenAmount").and_then(SharpenAmount::parse).unwrap_or(d.sharpen_amount),
naming: s("naming").map_or(d.naming, str::to_string),
start_number: u("startNumber").map_or(d.start_number, |v| v.min(999_999) as u32),
destination_mode: s("destinationMode").and_then(DestinationMode::parse).unwrap_or(d.destination_mode),
subfolder: s("subfolder").map_or(d.subfolder, |v| v.trim().replace(['\\', ':', '\0'], "_")),
conflict: enm(p, "conflict").unwrap_or(d.conflict),
conflict: s("conflict").and_then(Conflict::parse).unwrap_or(d.conflict),
tiff_compression: match s("tiffCompression").map(str::to_ascii_lowercase).as_deref() {
Some("none") => TiffCompression::None,
Some("lzw") => TiffCompression::Lzw,
@@ -996,7 +1046,7 @@ impl ExportOptions {
_ => d.tiff_compression,
},
dng_compression: enm(p, "dngCompression").unwrap_or(d.dng_compression),
metadata: enm(p, "metadata").unwrap_or(d.metadata),
metadata: s("metadata").and_then(MetadataPolicy::parse).unwrap_or(d.metadata),
remove_location: p.get("removeLocation").and_then(Value::as_bool).unwrap_or(d.remove_location),
watermark: match p.get("watermark") {
Some(Value::String(t)) => Some(Watermark { text: t.clone(), ..Default::default() }),
@@ -1260,7 +1310,15 @@ pub fn encode_with_metadata(img: &Rgba8, o: &ExportOptions, meta: Option<&Metada
let exif = meta.map(lightcraft_meta::write_exif);
let xmp = meta.map(|m| lightcraft_meta::write_xmp(m, None));
let meta = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) };
let e = EncodeImage::rgba8(&img);
// Opaque photo exports need no alpha channel (#1670). Keep real transparency for
// callers of this encoder, and leave unrelated formats on their existing path.
let rgb: Option<Vec<u8>> = (matches!(o.format, ExportFormat::Png | ExportFormat::Tiff | ExportFormat::Webp)
&& img.data.iter().all(|p| p.last() == Some(&255)))
.then(|| img.data.iter().flat_map(|p| p.iter().take(3).copied()).collect());
let e = match &rgb {
Some(data) => EncodeImage::new(img.width as u32, img.height as u32, 3, Samples::U8(data)),
None => EncodeImage::rgba8(&img),
};
let r = match o.format {
ExportFormat::Jpeg => {
// 4:4:4 normally; 4:2:0 when targeting a file size (much smaller at equal visual quality).
@@ -2231,6 +2289,43 @@ mod tests {
img
}
/// Issue #1670: removing a redundant alpha channel preserves samples and metadata.
#[test]
fn opaque_eight_bit_exports_are_rgb() {
let img = test_image();
let metadata = Metadata { copyright: Some("Synthetic export test".into()), ..Default::default() };
for format in [ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp] {
for compression in [TiffCompression::None, TiffCompression::Lzw, TiffCompression::Deflate, TiffCompression::PackBits] {
let options = ExportOptions { format, tiff_compression: compression, ..Default::default() };
let bytes = encode_with_metadata(&img, &options, Some(&metadata)).unwrap();
let decoded = lightcraft_codecs::decode(&bytes, Default::default()).unwrap();
assert!(!decoded.has_alpha, "{format:?}/{compression:?} must be RGB");
assert_eq!((decoded.width, decoded.height, decoded.bit_depth), (96, 64, 8));
assert_eq!(decoded.to_srgb8().data, img.data, "{format:?}/{compression:?} pixels");
assert_eq!(decoded.icc.as_deref(), Some(icc::write_named(NamedSpace::Srgb).as_slice()));
assert!(decoded.xmp.as_deref().unwrap_or_default().contains("Synthetic export test"));
if format == ExportFormat::Png {
assert_eq!(bytes[25], 2, "PNG IHDR declares RGB");
}
if format != ExportFormat::Tiff {
break;
}
}
}
}
#[test]
fn eight_bit_exports_preserve_real_alpha() {
let mut img = test_image();
img.data[0][3] = 128;
for format in [ExportFormat::Png, ExportFormat::Tiff, ExportFormat::Webp] {
let bytes = encode_image(&img, &ExportOptions { format, ..Default::default() }).unwrap();
let decoded = lightcraft_codecs::decode(&bytes, Default::default()).unwrap();
assert!(decoded.has_alpha, "{format:?} must retain real alpha");
assert_eq!(decoded.to_srgb8().data, img.data, "{format:?} samples");
}
}
#[test]
fn formats_have_magic() {
let img = test_image();
@@ -2457,7 +2552,7 @@ mod tests {
fn biz_ud_vertical_watermarks_place_punctuation_at_the_top_right() {
use ab_glyph::Font;
let Some(entry) = crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "BIZ UDMincho") else {
eprintln!("skipped: built without BIZ UDMincho from craft-fonts");
lightcraft_testkit::skip!(Fonts, "built without BIZ UDMincho from craft-fonts");
return;
};
let font = ab_glyph::FontRef::try_from_slice(entry.bytes).unwrap();
@@ -2529,7 +2624,7 @@ mod tests {
compare(composed, decomposed, crate::fonts::CRAFT_FONTS);
}
} else {
eprintln!("skipped Japanese comparisons: built without BIZ UDMincho from craft-fonts");
lightcraft_testkit::skip!(Fonts, "Japanese comparisons: built without BIZ UDMincho from craft-fonts");
}
}
@@ -2553,7 +2648,7 @@ mod tests {
use ab_glyph::Font;
let fonts = watermark_fonts(crate::fonts::CRAFT_FONTS);
if fonts.len() < 2 {
eprintln!("skipped: built without CRAFT_FONTS_DIR, so there is no Japanese watermark face");
lightcraft_testkit::skip!(Fonts, "built without CRAFT_FONTS_DIR, so there is no Japanese watermark face");
return;
}
for c in "日本語の文字".chars() {
@@ -3182,6 +3277,58 @@ mod tests {
assert_eq!(ExportOptions::from_params(&ExportOptions::known_keys_only(&j)).unwrap(), o);
}
/// A choice the validation accepts is the one exported: `metadata: "NONE"` passed the
/// case-insensitive check, then failed the exact-case read and fell back to `all`, so GPS and
/// camera data went out in a file meant to carry none. `sharpen`, `sharpenAmount` and
/// `conflict` had the same gap.
#[test]
fn accepted_choices_are_the_ones_exported() {
use serde_json::json;
let read = |k: &str, v: &str| ExportOptions::from_params(&json!({ k: v })).map_err(|e| e.to_string());
let metadata = [
("all", MetadataPolicy::All),
("allExceptCamera", MetadataPolicy::AllExceptCamera),
("copyright", MetadataPolicy::Copyright),
("none", MetadataPolicy::None),
];
for (name, want) in metadata {
for v in [name.to_string(), name.to_ascii_uppercase(), name.to_ascii_lowercase()] {
assert_eq!(read("metadata", &v).unwrap().metadata, want, "metadata: {v}");
}
}
for (name, want) in [("none", SharpenFor::None), ("screen", SharpenFor::Screen), ("matte", SharpenFor::Matte), ("glossy", SharpenFor::Glossy)]
{
assert_eq!(read("sharpen", &name.to_ascii_uppercase()).unwrap().sharpen, want);
}
for (name, want) in [("low", SharpenAmount::Low), ("standard", SharpenAmount::Standard), ("high", SharpenAmount::High)] {
assert_eq!(read("sharpenAmount", &name.to_ascii_uppercase()).unwrap().sharpen_amount, want);
}
for (name, want) in [("unique", Conflict::Unique), ("overwrite", Conflict::Overwrite), ("skip", Conflict::Skip)] {
assert_eq!(read("conflict", &name.to_ascii_uppercase()).unwrap().conflict, want);
}
// an explicit value nothing reads as is an error, never the permissive default
for v in ["", " none", "nothing", "all-except-camera"] {
let e = read("metadata", v).unwrap_err();
assert!(e.contains("`metadata` must be one of all|allExceptCamera|copyright|none"), "{v:?}: {e}");
}
assert!(read("sharpenAmount", "max").unwrap_err().contains("`sharpenAmount` must be one of low|standard|high"));
assert!(read("conflict", "replace").unwrap_err().contains("`conflict` must be one of unique|overwrite|skip"));
// absent (or null) keeps the defaults
let d = ExportOptions::from_params(&json!({"metadata": null})).unwrap();
assert_eq!(
(d.metadata, d.sharpen, d.sharpen_amount, d.conflict),
(MetadataPolicy::All, SharpenFor::None, SharpenAmount::Standard, Conflict::Unique)
);
// `removeLocation` stays independent of the policy's spelling
let o = ExportOptions::from_params(&json!({"metadata": "AllExceptCamera", "removeLocation": true})).unwrap();
assert_eq!((o.metadata, o.remove_location), (MetadataPolicy::AllExceptCamera, true));
// stored settings (lenient `from_json`) read the same spellings
assert_eq!(ExportOptions::from_json(&json!({"metadata": "None"})).metadata, MetadataPolicy::None);
// and `to_json` still writes what the MCP schema lists
let j = ExportOptions { metadata: MetadataPolicy::AllExceptCamera, conflict: Conflict::Skip, ..Default::default() }.to_json();
assert_eq!((j["metadata"].as_str(), j["conflict"].as_str()), (Some("allExceptCamera"), Some("skip")));
}
/// Issue #183: the `watermark` object's keys, kinds and ranges are checked (and documented in
/// the `app.export` param string), instead of unknown keys passing and sizes clamping silently.
#[test]
@@ -3264,7 +3411,7 @@ mod tests {
#[test]
fn a_batch_reports_a_gpu_fallback_on_the_file_it_hit() {
if !lightcraft_gpu::available() {
eprintln!("skipped: no GPU adapter ({:?})", lightcraft_gpu::unavailable_reason());
lightcraft_testkit::skip!(Gpu, "no GPU adapter ({})", lightcraft_gpu::unavailable_reason().unwrap_or_default());
return;
}
let mut s = crate::Session::with_demo();
+93 -13
View File
@@ -167,6 +167,9 @@ impl Index {
self.entries.insert((photo, key), (emb.into(), view));
}
}
// a half-written last record (a crash while appending): written fresh at the next save, so later records are
// not appended after it and shifted
self.rewrite = !rest.is_empty();
}
fn header(&self) -> Vec<u8> {
@@ -201,12 +204,11 @@ impl Index {
return Ok(());
}
if self.file_matches && !self.rewrite {
let mut f = std::fs::OpenOptions::new().append(true).open(&path)?;
let mut buf = Vec::new();
for (k, e) in &self.unsaved {
buf.extend(self.record(k, e));
}
f.write_all(&buf)?;
append(&path, &buf)?;
} else {
let mut buf = self.header();
for (k, e) in &self.entries {
@@ -229,6 +231,22 @@ impl Drop for Index {
}
}
/// Append `buf` to the file at `path`. When the write fails (a full disk), the file is cut back to its old length so
/// the part that got in does not shift what is appended later.
fn append(path: &Path, buf: &[u8]) -> std::io::Result<()> {
let mut f = std::fs::OpenOptions::new().append(true).open(path)?;
let old_len = f.metadata()?.len();
let written = f.write_all(buf);
if written.is_err() {
drop(f);
// an append-only handle may not truncate (Windows): cut through a writable one
if let Ok(w) = std::fs::OpenOptions::new().write(true).open(path) {
let _ = w.set_len(old_len);
}
}
written
}
const SCAN_MAGIC: &[u8; 4] = b"LCFS";
const SCAN_VERSION: u8 = 1;
/// The detector a search was made with: a record made by another one is ignored (a better detector may find more).
@@ -238,7 +256,7 @@ const SCAN_MAX_FILE: u64 = 64 << 20;
/// The photos the detector has already searched for faces, so each is searched once, however many times LightCraft
/// starts. Kept beside the library (`face-scanned.bin`: a header naming the detector, then photo ids, appended to).
#[derive(Default)]
/// The focus-point backfill keeps its own record the same way ([`Scanned::new`] with its magic and decoder tag).
pub(crate) struct Scanned {
set: std::collections::HashSet<u64>,
unsaved: Vec<u64>,
@@ -246,9 +264,23 @@ pub(crate) struct Scanned {
file_matches: bool,
/// A photo was taken out ([`Scanned::remove`]): the record is written fresh at the next save.
rewrite: bool,
magic: [u8; 4],
/// What made the record: a file made by anything else is started afresh.
tag: String,
}
impl Default for Scanned {
fn default() -> Self {
Scanned::new(*SCAN_MAGIC, SCAN_TAG)
}
}
impl Scanned {
/// An empty record (in memory until [`Scanned::reset`] gives it a path) whose file starts with `magic` and `tag`.
pub fn new(magic: [u8; 4], tag: &str) -> Scanned {
Scanned { set: Default::default(), unsaved: Vec::new(), path: None, file_matches: false, rewrite: false, magic, tag: tag.to_string() }
}
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
@@ -292,12 +324,13 @@ impl Scanned {
}
}
fn header() -> Vec<u8> {
fn header(&self) -> Vec<u8> {
let mut h = Vec::new();
h.extend_from_slice(SCAN_MAGIC);
h.extend_from_slice(&self.magic);
h.push(SCAN_VERSION);
h.extend_from_slice(&(SCAN_TAG.len() as u16).to_le_bytes());
h.extend_from_slice(SCAN_TAG.as_bytes());
let tag = self.tag.as_bytes().get(..usize::from(u16::MAX)).unwrap_or(self.tag.as_bytes());
h.extend_from_slice(&(tag.len() as u16).to_le_bytes());
h.extend_from_slice(tag);
h
}
@@ -307,11 +340,14 @@ impl Scanned {
return;
}
let Ok(bytes) = std::fs::read(path) else { return };
let head = Self::header();
let head = self.header();
let Some(rest) = bytes.strip_prefix(head.as_slice()) else { return };
self.file_matches = true;
// a half-written last id (a crash while appending) is ignored
self.set.extend(rest.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c)));
// a half-written last id (a crash while appending) is ignored, and the record is written fresh at the next save
// so later ids are not appended after it and shifted
let (ids, torn) = rest.as_chunks::<8>();
self.set.extend(ids.iter().map(|c| u64::from_le_bytes(*c)));
self.rewrite = !torn.is_empty();
}
/// Write what was added since the last save: appended when the file is this detector's, else the whole record
@@ -326,11 +362,10 @@ impl Scanned {
return Ok(());
}
if self.file_matches && !self.rewrite {
let mut f = std::fs::OpenOptions::new().append(true).open(&path)?;
let buf: Vec<u8> = self.unsaved.iter().flat_map(|id| id.to_le_bytes()).collect();
f.write_all(&buf)?;
append(&path, &buf)?;
} else {
let mut buf = Self::header();
let mut buf = self.header();
buf.extend(self.set.iter().flat_map(|id| id.to_le_bytes()));
let part = path.with_extension("part");
std::fs::write(&part, &buf)?;
@@ -472,6 +507,51 @@ mod tests {
assert!(!t.contains(1) && t.contains(2) && t.contains(3));
let _ = std::fs::remove_dir_all(&dir);
}
/// A torn last record (a crash or a full disk while appending) does not shift the records appended after it
/// (issue #2129).
#[test]
fn records_appended_after_a_torn_tail_stay_aligned() {
let dir = std::env::temp_dir().join(format!("lc-faces-torn-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (emb, scan) = (dir.join("face-embeddings.bin"), dir.join("face-scanned.bin"));
let junk = |p: &Path| {
let mut f = std::fs::OpenOptions::new().append(true).open(p).unwrap();
f.write_all(&[0x3f; 5]).unwrap();
};
let mut a = Index::default();
a.reset("m@abc", 3, Some(emb.clone()));
a.insert(7, &rect(0.1), vec![1.0, 0.0, 0.5]);
a.save().unwrap();
drop(a);
junk(&emb);
let mut b = Index::default();
b.reset("m@abc", 3, Some(emb.clone()));
b.insert(9, &rect(0.5), vec![0.5, 0.25, 0.125]);
b.save().unwrap();
drop(b);
let mut c = Index::default();
c.reset("m@abc", 3, Some(emb));
assert_eq!(c.len(), 2);
assert_eq!(c.get(7, &rect(0.1)).map(|e| e.to_vec()), Some(vec![1.0, 0.0, 0.5]));
assert_eq!(c.get(9, &rect(0.5)).map(|e| e.to_vec()), Some(vec![0.5, 0.25, 0.125]));
let mut s = Scanned::default();
s.reset(Some(scan.clone()));
s.insert(42);
s.save().unwrap();
drop(s);
junk(&scan);
let mut t = Scanned::default();
t.reset(Some(scan.clone()));
t.insert(43);
t.save().unwrap();
drop(t);
let mut u = Scanned::default();
u.reset(Some(scan));
assert!(u.contains(42) && u.contains(43) && u.len() == 2);
let _ = std::fs::remove_dir_all(&dir);
}
}
/// What the recognition commands keep between calls: the loaded model and the embeddings made with it.
+21 -7
View File
@@ -127,6 +127,17 @@ fn pool_threads_for(cores: usize, pace: Pace, cap: Option<usize>) -> usize {
cap.map_or(n, |c| n.min(c.max(1)))
}
/// How much of the GPU face models may take at `pace`: face model runs at once, and the share of the time it may be
/// busy. Paused or light: one run at a time, busy a quarter of the time (the user is working, and the window renders
/// on the same GPU); normal: two at once, busy most of the time; full: as fast as it goes.
pub(crate) fn gpu_pace(pace: Pace) -> (usize, f32) {
match pace {
Pace::Pause | Pace::Light => (1, 0.25),
Pace::Normal => (2, 0.75),
Pace::Full => (4, 1.0),
}
}
/// One photo's faces to embed (and, if `detect`, to find first).
pub(crate) struct Prepared {
/// `<model id>@<sha256>` the embeddings are for.
@@ -201,7 +212,8 @@ pub(crate) fn process(p: Prepared, embedder: &Embedder) -> Done {
let img = Rgb { data: &rgb, width: w, height: h };
let (iw, ih) = embedder.input_size();
let scaled = |f: &Face| f.landmarks.map(|(x, y)| (x * w as f32, y * h as f32));
let mut results: Vec<(Rect, Option<Vec<f32>>, Rect)> = todo
// every face's crop first, then all of them through the model at once (one GPU dispatch for a group photo)
let mut faces: Vec<(Rect, Option<Vec<u8>>, Rect)> = todo
.into_iter()
.map(|rect| {
let best = found.iter().map(|f| (overlap(&rect, f), f)).filter(|(o, _)| *o >= MATCH_IOU).max_by(|a, b| a.0.total_cmp(&b.0));
@@ -218,20 +230,18 @@ pub(crate) fn process(p: Prepared, embedder: &Embedder) -> Done {
ih,
),
};
let v = crop.and_then(|c| embedder.embed(&c).ok());
// shown by the detector's box where it found this face: every face then has the same tightness
let view = best.and_then(|(_, f)| face_rect(f)).unwrap_or(rect);
(rect, v, view)
(rect, crop, view)
})
.collect();
// a photo with no face regions: what the detector is sure of becomes its faces, embedded in the same pass
let new_faces = if detect {
detected.map(|faces| {
detected.map(|found| {
let mut rects = Vec::new();
for f in faces.iter().filter(|f| f.score >= REGION_SCORE) {
for f in found.iter().filter(|f| f.score >= REGION_SCORE) {
let Some(rect) = face_rect(f) else { continue };
let v = align_to_template(&img, &scaled(f), iw, ih).and_then(|c| embedder.embed(&c).ok());
results.push((rect, v, rect));
faces.push((rect, align_to_template(&img, &scaled(f), iw, ih), rect));
rects.push(rect);
}
rects
@@ -239,6 +249,10 @@ pub(crate) fn process(p: Prepared, embedder: &Embedder) -> Done {
} else {
None
};
let crops: Vec<&[u8]> = faces.iter().filter_map(|(_, c, _)| c.as_deref()).collect();
let mut embedded = embedder.embed_batch(&crops).into_iter();
let results: Vec<(Rect, Option<Vec<f32>>, Rect)> =
faces.into_iter().map(|(rect, crop, view)| (rect, crop.and_then(|_| embedded.next().and_then(Result::ok)), view)).collect();
(results, new_faces)
}));
let (results, found) = run.unwrap_or_else(|_| (fallback(rects), None));
+81 -26
View File
@@ -41,6 +41,7 @@ fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option<String>) {
// paths from `lr:hierarchicalSubject`, names from `dc:subject` that aren't their levels
keywords: lightcraft_catalog::keywords::from_file(&m.keywords, &m.hierarchical_keywords),
regions: m.regions.clone(),
focus: m.focus.clone(),
};
(meta, m.capture_time.as_ref().map(|d| d.to_iso()))
}
@@ -159,10 +160,8 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
}
Err(Err(e)) => return Err(e),
};
let (mut w, mut h) = (raw.crop.width.max(1) as u32, raw.crop.height.max(1) as u32);
if w <= 1 || h <= 1 {
(w, h) = (raw.active_area.width as u32, raw.active_area.height as u32);
}
let (w, h) = raw.developed_size();
let (mut w, mut h) = (w.max(1) as u32, h.max(1) as u32);
if raw.orientation.swaps_axes() {
std::mem::swap(&mut w, &mut h);
}
@@ -267,19 +266,43 @@ impl CameraColourModel<'_> {
/// White balance, matrix, tables and baseline exposure, in place.
pub fn apply(&self, img: &mut Rgb32f) {
let (wb, m, gain) = (self.wb, self.matrix.to_f32(), self.gain);
img.map_in_place(|p| {
let c = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]];
let rgb = [
m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2],
m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2],
m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2],
];
let rgb = match self.tables {
Some(tables) => tables.apply(rgb, gain),
None => rgb.map(|v| v * gain),
};
self.hue_sat.map_or(rgb, |h| h.apply(rgb)).map(|v| v.max(0.0))
});
if let (None, Some(hue_sat)) = (self.tables, self.hue_sat) {
// a fitted camera look: `pixel`, `LANES` pixels at a time so the table step vectorises (same bits)
const LANES: usize = 16;
lightcraft_raster::par_rows(&mut img.data, img.width, |_, row| {
for chunk in row.chunks_mut(LANES) {
let mut rgb = [[0.0f32; LANES]; 3];
for (l, p) in chunk.iter().enumerate() {
let c = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]];
for (i, rgb) in rgb.iter_mut().enumerate() {
rgb[l] = (m[i][0] * c[0] + m[i][1] * c[1] + m[i][2] * c[2]) * gain;
}
}
let out = hue_sat.apply_lanes(rgb);
for (l, p) in chunk.iter_mut().enumerate() {
*p = [out[0][l], out[1][l], out[2][l]].map(|v| v.max(0.0));
}
}
});
return;
}
img.map_in_place(|p| self.pixel(&m, p));
}
/// [`Self::apply`] to one pixel; `m` is the matrix as `f32`.
fn pixel(&self, m: &[[f32; 3]; 3], p: [f32; 3]) -> [f32; 3] {
let (wb, gain) = (self.wb, self.gain);
let c = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]];
let rgb = [
m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2],
m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2],
m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2],
];
let rgb = match self.tables {
Some(tables) => tables.apply(rgb, gain),
None => rgb.map(|v| v * gain),
};
self.hue_sat.map_or(rgb, |h| h.apply(rgb)).map(|v| v.max(0.0))
}
}
@@ -401,12 +424,17 @@ fn load_bytes_now(
// (removed before the camera look's binned sensor proxy too, which needs an empty `OpcodeList3`).
let info = raw.info();
let lens = crate::lens_profiles::for_raw(&info, || lightcraft_meta::extract(&bytes));
// (the camera look still pairs the sensor with the camera JPEG through the warp the camera applied to it)
let lens_geometry = crate::camera_preview::lens_geometry(&raw.opcodes.list3);
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
// Which scale white balance is edited on, and the as-shot white on it, from the file's own colour tags or
// the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera)
let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
// the source's segmentation mattes (DNG semantic masks), read while the starting colour is fitted
let ((xy, t, camera_look), mattes) = rayon::join(|| crate::camera_preview::starting_colour(&mut raw, &bytes), || dng_mattes(&bytes, &info));
let ((xy, t, camera_look), mattes) = rayon::join(
|| crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref(), lens.as_ref()),
|| dng_mattes(&bytes, &info),
);
drop(bytes);
// Previews and thumbnails bin the mosaic straight to (about) the size they need; only
// larger levels (exports, 1:1) demosaic the whole sensor.
@@ -476,10 +504,11 @@ fn load_bytes_now(
// on top of it). A model's measured matrices never do: they only give the Kelvin scale its numbers, and the
// picture is adapted from the as-shot white as every fitted look is (so settings from before that scale
// existed render exactly as they did, `lightcraft_pipeline::local::legacy_white`).
let camera_color = (scale.own_matrix && !t.matrix_is_fallback && camera_look.is_none()).then(|| {
let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() };
Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy })
});
let camera_color = (scale.own_matrix && !t.matrix_is_fallback && (camera_look.is_none() || raw.format == lightcraft_raw::RawFormat::Dng))
.then(|| {
let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() };
Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy })
});
let camera_tone = camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve));
let local_tone = local_tone(&raw);
let (temp, tint) = scale.as_shot(xy);
@@ -678,8 +707,9 @@ pub(crate) fn decode_raw_preview(
covering: Option<usize>,
) -> Option<lightcraft_codecs::Decoded> {
let jpeg = stand_in_image(bytes, covering)?;
// the colour space is a property of the JPEG; a TIFF stand-in is read by the TIFF reader
let is_jpeg = matches!(jpeg, std::borrow::Cow::Owned(_));
// the colour space is a property of the JPEG; a TIFF stand-in (the file itself, or a Hasselblad RGB preview
// wrapped as a TIFF) and a JPEG XL preview are read by their own decoders
let is_jpeg = jpeg.starts_with(&[0xff, 0xd8]);
match lightcraft_raw::embedded_preview_color_space(bytes).filter(|_| is_jpeg) {
Some(space) => {
let space = match space {
@@ -1640,7 +1670,7 @@ pub(crate) mod tests {
.unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"))
.join("raw");
let Ok(gh1) = std::fs::read(dir.join("rw2-panasonic-gh1.rw2")) else {
eprintln!("skip: {} absent", dir.display());
lightcraft_testkit::skip!(Corpus, "{} absent", dir.display());
return;
};
assert_eq!(probe_bytes("gh1.rw2", &gh1).unwrap().embedded_lens, None, "correction off: nothing to apply");
@@ -1807,6 +1837,31 @@ pub(crate) mod tests {
lightcraft_color::Mat3([[0.42, 0.548, 0.04], [0.246, 0.728, 0.033], [-0.247, 0.679, 0.447]])
}
/// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the
/// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included.
#[test]
fn camera_look_in_lanes_matches_pixel_by_pixel() {
let data = (0..72 * 5 * 5).map(|i| [((i * 37) % 61) as f32 - 30.0, 0.6 + ((i * 11) % 13) as f32 / 13.0, 1.0]).collect();
let table = lightcraft_raw::profile::HsvTable { hue_divisions: 72, sat_divisions: 5, val_divisions: 5, data, srgb_value: true };
let hue_sat = crate::camera_preview::HueSat::new(&table).unwrap();
let colour = CameraColourModel { wb: [2.1, 1.0, 1.5], matrix: yellowing_look(), gain: 1.3, tables: None, hue_sat: Some(&hue_sat) };
let special = [0.0, -0.0, -0.01, 1e-30, 0.3, 1.0, 5.0, 1e30, f32::INFINITY, f32::NAN];
let img = Rgb32f::from_fn(37, 5, |x, y| {
let k = y * 37 + x;
if k % 5 == 0 {
[special[k % 10], special[k / 10 % 10], special[k / 100 % 10]]
} else {
[(x as f32 * 0.37).sin().abs(), ((x + y) as f32 * 0.11).cos().abs(), y as f32 / 4.0 - 0.05]
}
});
let mut lanes = img.clone();
colour.apply(&mut lanes);
let m = colour.matrix.to_f32();
for (p, got) in img.data.iter().zip(&lanes.data) {
assert_eq!(got.map(f32::to_bits), colour.pixel(&m, *p).map(f32::to_bits), "{p:?}");
}
}
#[test]
fn clipped_white_renders_neutral_through_the_colour_model() {
use lightcraft_color::{LUMA_2020, Mat3};
@@ -1991,7 +2046,7 @@ pub(crate) mod tests {
.unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"))
.join("raw");
let Ok(bytes) = std::fs::read(dir.join("arw-sony-a7rm4-14bit-compressed.arw")) else {
eprintln!("skip: {} absent", dir.display());
lightcraft_testkit::skip!(Corpus, "{} absent", dir.display());
return;
};
let (img, _) = load_bytes(&bytes, 1600).unwrap();
+432
View File
@@ -0,0 +1,432 @@
//! Reading the camera's focus point for photos already in the library (issue #1480).
//!
//! Import reads a photo's focus point ([`lightcraft_meta::focus`]); photos imported before that have none. This job
//! fills them in, cheaply enough to run over a whole library on a spinning disk: it opens only the photos from a body
//! whose focus data is decoded (by the camera the catalog stores, so nothing else is opened), and reads only the few
//! kilobytes of each file that hold the focus data ([`lightcraft_meta::focus::read_header`]: about 32 KB of a 75 MB α1
//! ARW), one file at a time on one worker thread.
//!
//! - **Commits** go in batches of [`COMMIT_EVERY`] photos (or every [`COMMIT_AFTER`]), as LightCraft's own bookkeeping
//! ([`Session::apply_system`]): no undo step, no sidecar write (the focus point is never written to XMP). Only
//! `meta.focus` changes, and only on a photo that still has none, still in the library at the same path.
//! - **"Looked, found nothing"** (manual focus, a centre-only Multi report) is kept beside the library in
//! `focus-scanned.bin` (photo ids, appended to, headed by the decoder's tag): it is cheap to append, never touches the
//! catalog, and a decoder that learns more bodies has another tag, so its record starts afresh and those photos are
//! looked at again. A photo whose file can't be read (offline drive, file gone or replaced mid-read) is not recorded:
//! it is tried again the next time the library opens.
//! - **Runs** off the UI thread with a row in the activity stack ("Reading focus points", n of N, ✕ stops it). The UI's
//! per-frame `focus.pump` gives it the pace: nothing new while the user drags, types or scrolls, a short rest between
//! files while they are around.
//! - **Starts** by itself once per library opening (from `focus.pump`) when photos are left to look at, and on demand
//! with `photo.readFocusPoints`.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use lightcraft_catalog::{Op, PhotoId, Source};
use lightcraft_meta::FocusPoint;
use lightcraft_meta::focus::HeaderRead;
use serde_json::{Value, json};
use crate::activity::{Cancel, TaskGuard};
use crate::faces_index::Scanned;
use crate::{Result, Session};
/// The record of photos looked at with nothing found, beside the library.
pub(crate) const RECORD_FILE: &str = "focus-scanned.bin";
const RECORD_MAGIC: [u8; 4] = *b"LCFP";
/// Photos committed at once.
pub(crate) const COMMIT_EVERY: usize = 200;
/// What has been read is committed at least this often, so points appear while a long run goes on.
const COMMIT_AFTER: Duration = Duration::from_secs(3);
/// The rest between files while the user is around (`light` pace): their own reads of the same disk go first.
const LIGHT_REST: Duration = Duration::from_millis(40);
/// How often a paused worker looks at its pace again.
const PAUSE_POLL: Duration = Duration::from_millis(50);
/// Results taken in per pump (the rest wait for the next frame).
const MAX_DRAIN: usize = 5000;
/// The file extensions read (Sony bodies also shoot HEIF, which carries no maker note this decoder reads).
const EXTENSIONS: [&str; 3] = ["arw", "jpg", "jpeg"];
/// How hard the worker may work, from what the user is doing (`focus.pump`'s `pace`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum Pace {
Pause = 0,
Light = 1,
Normal = 2,
}
impl Pace {
pub fn parse(name: Option<&str>) -> Pace {
match name {
Some("pause") => Pace::Pause,
Some("light") => Pace::Light,
_ => Pace::Normal,
}
}
}
/// The focus point in the file at `path`, read from its header only.
pub fn read_focus(path: &str) -> std::result::Result<HeaderRead, String> {
use std::io::{Read, Seek, SeekFrom};
let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
let len = file.metadata().map_err(|e| format!("{path}: {e}"))?.len();
lightcraft_meta::focus::read_header(len, &mut |off, buf| {
file.seek(SeekFrom::Start(off))?;
file.read_exact(buf)
})
.map_err(|e| format!("{path}: {e}"))
}
/// What the worker says about one photo.
enum Outcome {
/// The header was read: the point it holds, or none.
Read { id: PhotoId, focus: Option<FocusPoint>, bytes: u64 },
/// The file couldn't be read (offline, gone, changed under the read): tried again another time.
Unavailable,
}
/// What a run did (the last one is kept for `focus.status` and `photo.readFocusPoints {wait}`).
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Summary {
pub total: u64,
pub done: u64,
pub found: u64,
pub none: u64,
pub unavailable: u64,
pub bytes: u64,
pub seconds: f64,
pub cancelled: bool,
}
impl Summary {
fn json(&self) -> Value {
json!({
"total": self.total,
"done": self.done,
"found": self.found,
"none": self.none,
"unavailable": self.unavailable,
"bytesRead": self.bytes,
"seconds": self.seconds,
"cancelled": self.cancelled,
})
}
}
struct Job {
identity: Arc<()>,
cancel: Arc<AtomicBool>,
pace: Arc<AtomicU8>,
rx: mpsc::Receiver<(Outcome, String)>,
/// Its row in the activity stack (dropping the job removes it).
guard: TaskGuard,
/// The path each photo was read at: a photo moved or relinked since is left for another run.
paths: HashMap<PhotoId, String>,
pending: Vec<(PhotoId, Option<FocusPoint>)>,
committed_at: Instant,
started: Instant,
summary: Summary,
}
impl Drop for Job {
fn drop(&mut self) {
// the worker stops before its next file (and when it can't hand a result over)
self.cancel.store(true, Ordering::Relaxed);
}
}
/// The backfill's state in the session.
pub(crate) struct FocusScan {
record: Scanned,
/// The library opening the record and the automatic start belong to.
library: Option<Arc<()>>,
auto_checked: bool,
job: Option<Job>,
last: Option<Summary>,
/// The pace the UI last gave (a job started between two pumps starts at it).
pace: Pace,
}
impl Default for FocusScan {
fn default() -> Self {
FocusScan {
record: Scanned::new(RECORD_MAGIC, &lightcraft_meta::focus::decoder_tag()),
library: None,
auto_checked: false,
job: None,
last: None,
pace: Pace::Normal,
}
}
}
/// Follow the session's library: another one (or none) drops a running job (its results belong to the old library and
/// are read again there next time) and loads that library's record.
fn follow_library(s: &mut Session) {
if s.focus_scan.library.as_ref().is_some_and(|l| Arc::ptr_eq(l, &s.library_identity)) {
return;
}
s.focus_scan.job = None;
s.focus_scan.auto_checked = false;
let path = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join(RECORD_FILE));
s.focus_scan.record.reset(path);
s.focus_scan.library = Some(Arc::clone(&s.library_identity));
}
/// The photos to read: in the library, no focus point yet, from a body whose focus data is decoded, a raw or JPEG file;
/// with `ids`, those of them; without, every one not already looked at. In path order (neighbours on disk together).
fn candidates(s: &Session, ids: Option<&[PhotoId]>) -> Vec<(PhotoId, String)> {
let wanted = |ph: &lightcraft_catalog::Photo| -> Option<(PhotoId, String)> {
if !ph.in_library() || ph.meta.focus.is_some() || !lightcraft_meta::focus::camera_supported(&ph.meta.camera) {
return None;
}
let Source::File { path } = &ph.source else { return None };
let ext = std::path::Path::new(path).extension()?.to_str()?.to_ascii_lowercase();
EXTENSIONS.contains(&ext.as_str()).then(|| (ph.id, path.clone()))
};
let mut out: Vec<(PhotoId, String)> = match ids {
Some(ids) => ids.iter().filter_map(|id| s.catalog.photo(*id)).filter_map(|ph| wanted(ph)).collect(),
None => s.catalog.photos().filter(|ph| !s.focus_scan.record.contains(ph.id.0)).filter_map(|ph| wanted(ph)).collect(),
};
out.sort_by(|a, b| a.1.cmp(&b.1));
out.dedup_by_key(|c| c.0);
out
}
/// Start reading `list` on a worker thread.
fn start(s: &mut Session, list: Vec<(PhotoId, String)>, pace: Pace) -> std::result::Result<(), String> {
let cancel = Arc::new(AtomicBool::new(false));
let pace = Arc::new(AtomicU8::new(pace as u8));
let (tx, rx) = mpsc::channel();
let paths: HashMap<PhotoId, String> = list.iter().cloned().collect();
let total = list.len() as u64;
let (worker_cancel, worker_pace) = (cancel.clone(), pace.clone());
std::thread::Builder::new()
.name("focus-points".into())
.spawn(move || {
for (id, path) in list {
loop {
if worker_cancel.load(Ordering::Relaxed) {
return;
}
if worker_pace.load(Ordering::Relaxed) != Pace::Pause as u8 {
break;
}
std::thread::sleep(PAUSE_POLL);
}
if worker_pace.load(Ordering::Relaxed) == Pace::Light as u8 {
std::thread::sleep(LIGHT_REST);
}
// a decoder bug in one file is that file's problem, not the job's end
let outcome = match crate::guard::catch("reading a focus point", || read_focus(&path)) {
Ok(Ok(r)) => Outcome::Read { id, focus: r.focus, bytes: r.bytes_read },
Ok(Err(e)) => {
log::debug!("focus point: {e}");
Outcome::Unavailable
}
Err(_) => Outcome::Unavailable,
};
let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
if tx.send((outcome, name)).is_err() {
return;
}
}
})
.map_err(|e| format!("could not start reading focus points: {e}"))?;
let guard = s.activity.start("focus", "Reading focus points", Cancel::Flag(cancel.clone()));
guard.progress(0, total);
let now = Instant::now();
s.focus_scan.job = Some(Job {
identity: Arc::clone(&s.library_identity),
cancel,
pace,
rx,
guard,
paths,
pending: Vec::new(),
committed_at: now,
started: now,
summary: Summary { total, ..Default::default() },
});
Ok(())
}
/// Commit what has been read: the points found (one system op, no undo step, no sidecar write) and the photos with none
/// (to the record).
fn commit(s: &mut Session) {
let Some(job) = s.focus_scan.job.as_mut() else { return };
let pending = std::mem::take(&mut job.pending);
job.committed_at = Instant::now();
if !Arc::ptr_eq(&job.identity, &s.library_identity) {
return;
}
let mut ops = Vec::new();
let mut none = Vec::new();
for (id, focus) in pending {
let Some(ph) = s.catalog.photo(id) else { continue };
let same_file = matches!((&ph.source, job.paths.get(&id)), (Source::File { path }, Some(read)) if path == read);
// deleted, moved, relinked or given a point meanwhile: leave it
if !same_file || !ph.in_library() || ph.meta.focus.is_some() {
continue;
}
match focus {
Some(f) => {
let mut meta = ph.meta.clone();
meta.focus = Some(f);
ops.push(Op::SetMeta { id, meta: Box::new(meta) });
}
None => none.push(id.0),
}
}
for id in none {
s.focus_scan.record.insert(id);
}
if let Err(e) = s.focus_scan.record.save() {
log::warn!("could not save the list of photos read for focus points: {e}");
}
if ops.is_empty() {
return;
}
match s.apply_system(Op::Batch { ops }) {
// the focus point is never written to XMP: no sidecar is rewritten for it
Ok(()) => s.skip_auto_write = true,
Err(e) => log::warn!("could not store focus points: {e}"),
}
}
/// Take in what the worker has read, commit when a batch is due, and end the job when it is done or cancelled.
/// Returns whether a job is still running.
fn step(s: &mut Session, pace: Pace) -> bool {
let Some(job) = s.focus_scan.job.as_mut() else { return false };
job.pace.store(pace as u8, Ordering::Relaxed);
let mut finished = job.cancel.load(Ordering::Relaxed);
let mut last_name = None;
for _ in 0..MAX_DRAIN {
match job.rx.try_recv() {
Ok((outcome, name)) => {
job.summary.done += 1;
last_name = Some(name);
match outcome {
Outcome::Read { id, focus, bytes } => {
job.summary.bytes = job.summary.bytes.saturating_add(bytes);
if focus.is_some() {
job.summary.found += 1;
} else {
job.summary.none += 1;
}
job.pending.push((id, focus));
}
Outcome::Unavailable => job.summary.unavailable += 1,
}
}
Err(mpsc::TryRecvError::Empty) => break,
// the worker ended (all read, cancelled, or it could not go on)
Err(mpsc::TryRecvError::Disconnected) => {
finished = true;
break;
}
}
}
finished |= job.summary.done >= job.summary.total;
job.guard.progress(job.summary.done, job.summary.total);
if let Some(name) = last_name {
job.guard.detail(&name);
}
if finished || job.pending.len() >= COMMIT_EVERY || (!job.pending.is_empty() && job.committed_at.elapsed() >= COMMIT_AFTER) {
commit(s);
}
if finished && let Some(job) = s.focus_scan.job.take() {
let mut summary = job.summary.clone();
summary.cancelled = job.cancel.load(Ordering::Relaxed) && summary.done < summary.total;
summary.seconds = job.started.elapsed().as_secs_f64();
log::info!(
"focus points: read {} of {} photos ({} found, {} without, {} unavailable, {} KB) in {:.1} s",
summary.done,
summary.total,
summary.found,
summary.none,
summary.unavailable,
summary.bytes / 1024,
summary.seconds
);
s.focus_scan.last = Some(summary);
return false;
}
true
}
fn status(s: &Session) -> Value {
let running = s.focus_scan.job.as_ref().map(|j| json!({"done": j.summary.done, "total": j.summary.total, "found": j.summary.found}));
json!({"active": running.is_some(), "running": running, "last": s.focus_scan.last.as_ref().map(Summary::json), "lookedAt": s.focus_scan.record.len()})
}
/// `focus.pump {pace?}`: cheap to call every frame.
pub(crate) fn pump(s: &mut Session, p: &Value) -> Result<Value> {
follow_library(s);
let pace = Pace::parse(p.get("pace").and_then(Value::as_str));
s.focus_scan.pace = pace;
if !step(s, pace) && !s.focus_scan.auto_checked {
// once per library opening: start by itself when photos are left to look at (a few KB each)
s.focus_scan.auto_checked = true;
let list = candidates(s, None);
if !list.is_empty()
&& let Err(e) = start(s, list, pace)
{
log::warn!("{e}");
}
}
Ok(status(s))
}
/// `photo.readFocusPoints {ids?, wait?}`.
pub(crate) fn read_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "photo.readFocusPoints";
follow_library(s);
if s.focus_scan.job.is_some() {
return Ok(json!({"queued": 0, "running": true, "status": status(s)}));
}
let ids: Option<Vec<PhotoId>> = match p.get("ids") {
None | Some(Value::Null) => None,
Some(v) => Some(
v.as_array()
.ok_or_else(|| crate::cmd::bad(C, "`ids` must be a list of photo ids"))?
.iter()
.map(|v| v.as_u64().map(PhotoId).ok_or_else(|| crate::cmd::bad(C, "`ids` must be a list of photo ids")))
.collect::<Result<Vec<_>>>()?,
),
};
let list = candidates(s, ids.as_deref());
let queued = list.len();
if queued == 0 {
return Ok(json!({"queued": 0, "running": false}));
}
let wait = p.get("wait").and_then(Value::as_bool) == Some(true);
start(s, list, if wait { Pace::Normal } else { s.focus_scan.pace }).map_err(|e| crate::cmd::bad(C, e))?;
// a run asked for counts as this library opening's automatic one
s.focus_scan.auto_checked = true;
if !wait {
return Ok(json!({"queued": queued, "running": true}));
}
// a script's call: read them all now (the batches still commit as they come)
while step(s, Pace::Normal) {
std::thread::sleep(Duration::from_millis(5));
}
let last = s.focus_scan.last.as_ref().map(Summary::json).unwrap_or(Value::Null);
Ok(json!({"queued": queued, "running": false, "last": last}))
}
#[cfg(test)]
pub(crate) fn record_len(s: &Session) -> usize {
s.focus_scan.record.len()
}
#[cfg(test)]
pub(crate) fn record_contains(s: &Session, id: PhotoId) -> bool {
s.focus_scan.record.contains(id.0)
}
+27 -3
View File
@@ -382,6 +382,17 @@ pub fn expand(paths: &[String], skip: Option<&Path>) -> Vec<String> {
/// [`expand`] with the walk bounded by `limits` → (files, whether a walk stopped at a bound).
pub fn expand_within(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits) -> (Vec<String>, bool) {
expand_noting(paths, skip, limits, None)
}
/// [`expand_within`], handing the listing of every folder that is walked to `note`
/// ([`crate::walk::files_in_noting`]).
pub(crate) fn expand_noting(
paths: &[String],
skip: Option<&Path>,
limits: crate::walk::Limits,
mut note: Option<crate::walk::NoteFolder>,
) -> (Vec<String>, bool) {
let mut out = Vec::new();
let mut truncated = false;
for p in paths {
@@ -390,7 +401,10 @@ pub fn expand_within(paths: &[String], skip: Option<&Path>, limits: crate::walk:
continue;
}
if p.is_dir() {
let w = crate::walk::files_in(p, skip, limits, is_supported);
let w = match note.as_mut() {
Some(note) => crate::walk::files_in_noting(p, skip, limits, is_supported, &mut **note),
None => crate::walk::files_in(p, skip, limits, is_supported),
};
if w.truncated {
log::warn!(
"import: stopped looking in {} after {} entries (limits: {} entries, {} folder levels)",
@@ -638,6 +652,11 @@ impl ScanInput {
(input, paths.to_vec())
}
/// The folder a scan never enters (the library's own).
pub(crate) fn skip(&self) -> Option<&Path> {
self.skip.as_deref()
}
/// The library as the scan sees it (shared, for [`crate::sync`], which looks at the same one).
pub(crate) fn library(&self) -> std::sync::Arc<lightcraft_catalog::Catalog> {
std::sync::Arc::clone(&self.library)
@@ -656,9 +675,14 @@ pub fn scan(s: &mut Session, paths: &[String]) -> Vec<ImportCandidate> {
/// [`scan`] without the session, so it can run on a worker thread. Stops early (returning what it
/// has) when `progress.cancel` is set.
pub fn scan_with(mut input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput {
use std::sync::atomic::Ordering::Relaxed;
pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput {
let files = expand(paths, input.skip.as_deref());
scan_files(input, files, progress)
}
/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]).
pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &ScanProgress) -> ScanOutput {
use std::sync::atomic::Ordering::Relaxed;
let by_path = library_files(&input.library, &files);
let todo: Vec<String> = files.iter().filter(|f| !by_path.contains_key(Path::new(f))).cloned().collect();
progress.total.store(todo.len(), Relaxed);
+1 -2
View File
@@ -64,8 +64,7 @@ fn frame_crop_factor(camera: Option<f64>, focal: f64, focal_35mm: Option<f64>) -
pub fn for_raw(raw: &lightcraft_raw::RawInfo, meta: impl FnOnce() -> lightcraft_meta::Metadata) -> Option<EmbeddedLens> {
crate::files::embedded_lens(raw).or_else(|| {
let db = database()?;
let c = raw.crop.clipped(raw.active_area.width, raw.active_area.height);
let (w, h) = if c.width == 0 || c.height == 0 { (raw.active_area.width, raw.active_area.height) } else { (c.width, c.height) };
let (w, h) = raw.developed_size();
lookup(db, &meta(), w as f64, h as f64, raw.orientation)
})
}
+58 -9
View File
@@ -29,6 +29,7 @@ pub mod demo;
pub mod denoise;
pub mod devices;
pub mod display;
pub mod doc_path;
mod errors;
pub mod export;
pub mod face_download;
@@ -38,6 +39,8 @@ mod faces_index;
#[cfg(not(target_arch = "wasm32"))]
mod faces_worker;
pub mod files;
#[cfg(not(target_arch = "wasm32"))]
mod focus_scan;
pub mod fonts;
pub mod guard;
pub mod import;
@@ -54,11 +57,16 @@ pub mod media;
pub mod memory;
pub mod merge;
mod model_download;
pub mod open_path;
pub mod originals;
mod pdf;
pub mod preset_import;
pub mod preset_luminar;
pub mod presets;
pub mod print;
pub mod print_color;
pub mod print_pdf;
pub mod profile_refs;
pub mod proof;
pub mod rename;
pub mod segment;
@@ -248,6 +256,9 @@ pub struct Session {
/// The loaded recognition model and the face embeddings made with it.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) faces: faces_index::FacesState,
/// Reading focus points for photos imported before they were read (`photo.readFocusPoints`, `focus.pump`).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) focus_scan: focus_scan::FocusScan,
/// Copied develop settings (partial JSON) for Paste.
pub clipboard: Option<Value>,
/// The folder on disk the [`LibrarySource::Folder`] view browses.
@@ -289,8 +300,17 @@ pub struct Session {
pub xmp: sidecar::XmpPrefs,
/// Parameters of the last export (`app.export` params, minus targets), persisted in prefs.json.
pub last_export: Option<serde_json::Value>,
/// The options of the last Photo Merge started, per command (`merge.hdr`, `merge.panorama`,
/// `merge.hdrPanorama`): the merge dialog opens with them and "… with Last Settings" uses
/// them. Persisted in prefs.json.
pub last_merge: std::collections::BTreeMap<String, serde_json::Value>,
/// The user's export presets (built-ins: [`export::builtin_presets`]), persisted in prefs.json.
pub export_presets: Vec<export::ExportPreset>,
/// The Print module's current layout, image settings, page, guides and job (`print.*`). Lives
/// with the session, so the app, CLI, control channel and MCP all see the same print.
pub print: print::template::PrintSettings,
/// Saved print templates (`print.template.*`), persisted in prefs.json.
pub print_templates: Vec<print::template::PrintTemplate>,
/// Metadata presets (`metadata.*`), persisted in prefs.json.
pub metadata_presets: Vec<cmd::metadata::MetadataPreset>,
/// Saved filter-bar settings (`filter.*`), persisted in prefs.json.
@@ -422,6 +442,8 @@ impl Session {
face_catalog: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
faces: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
focus_scan: Default::default(),
clipboard: None,
meta_clipboard: None,
browse: None,
@@ -443,7 +465,10 @@ impl Session {
library_identity: Arc::new(()),
xmp: sidecar::XmpPrefs::default(),
last_export: None,
last_merge: Default::default(),
export_presets: Vec::new(),
print: Default::default(),
print_templates: Vec::new(),
metadata_presets: Vec::new(),
filter_presets: Vec::new(),
curve_presets: Vec::new(),
@@ -500,7 +525,11 @@ impl Session {
}
let empty = Value::Object(Default::default());
let params = if params.is_null() { &empty } else { params };
self.run_command(id, spec.journal.then_some(params), |s| (spec.run)(s, params))
self.run_command(id, spec.journal.then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e {
// a shared parameter check ([`Session::targets`]) names the command it ran for
EngineError::BadParams { cmd, msg } if cmd.is_empty() => EngineError::BadParams { cmd: id.to_string(), msg },
e => e,
})
}
/// Run `f` as command `id` with what [`Session::execute`] does around every command: the
@@ -1027,8 +1056,12 @@ impl Session {
&& !al.is_smart()
&& self.filter == Filter::default()
{
let order = al.photos.clone();
visible.sort_by_key(|id| order.iter().position(|x| x == id).unwrap_or(usize::MAX));
// each photo's place looked up, not searched for (a big album sorted in O(n log n))
let mut place: std::collections::HashMap<PhotoId, usize> = std::collections::HashMap::with_capacity(al.photos.len());
for (i, id) in al.photos.iter().enumerate() {
place.entry(*id).or_insert(i);
}
visible.sort_by_key(|id| place.get(id).copied().unwrap_or(usize::MAX));
if !self.sort.ascending {
visible.reverse();
}
@@ -1167,14 +1200,24 @@ impl Session {
(self.visible_gen, self.visible.clone())
}
/// Targets of photo commands: explicit `ids`/`id` param, else the selection.
pub fn targets(&self, p: &Value) -> Vec<PhotoId> {
if let Some(a) = p.get("ids").and_then(Value::as_array) {
return a.iter().filter_map(Value::as_u64).map(PhotoId).collect();
/// Targets of photo commands: the explicit `ids` (photo ids) or `id` (a photo id) param, else [`Self::selected`].
/// An `ids` or `id` that is there but isn't photo ids is an error, never the selection or part of the list
/// (issue #1506): a mistyped target mustn't turn a command meant for one photo into one for every selected photo.
pub fn targets(&self, p: &Value) -> Result<Vec<PhotoId>> {
let invalid = |what: &str| EngineError::BadParams { cmd: String::new(), msg: format!("`{what}` must be photo ids (whole numbers)") };
match p.get("ids") {
None | Some(Value::Null) => {}
Some(Value::Array(a)) => return a.iter().map(|v| v.as_u64().map(PhotoId).ok_or_else(|| invalid("ids"))).collect(),
Some(_) => return Err(invalid("ids")),
}
if let Some(id) = p.get("id").and_then(Value::as_u64) {
return vec![PhotoId(id)];
match p.get("id") {
None | Some(Value::Null) => Ok(self.selected()),
Some(v) => v.as_u64().map(|id| vec![PhotoId(id)]).ok_or_else(|| invalid("id")),
}
}
/// The photos commands act on when a call names none: the selection, else the active photo.
pub fn selected(&self) -> Vec<PhotoId> {
if self.selection.ids.is_empty() { self.selection.active.into_iter().collect() } else { self.selection.ids.clone() }
}
}
@@ -1221,6 +1264,8 @@ mod tests_face_recognize;
mod tests_face_tiles;
#[cfg(test)]
mod tests_filesystem_history;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_focus_scan;
#[cfg(test)]
mod tests_folders;
#[cfg(test)]
@@ -1246,6 +1291,8 @@ mod tests_mask_effects;
#[cfg(test)]
mod tests_merge;
#[cfg(test)]
mod tests_move_to_share;
#[cfg(test)]
mod tests_organize;
#[cfg(test)]
mod tests_persist;
@@ -1254,6 +1301,8 @@ mod tests_prefs;
#[cfg(test)]
mod tests_presets_scale;
#[cfg(test)]
mod tests_print;
#[cfg(test)]
mod tests_process;
#[cfg(test)]
mod tests_recheck;
+8
View File
@@ -207,8 +207,12 @@ struct PrefsFile {
/// Parameters of the last export (for Export with Previous).
#[serde(alias = "last_export")]
last_export: Option<serde_json::Value>,
/// Options of the last Photo Merge, per command.
last_merge: std::collections::BTreeMap<String, serde_json::Value>,
/// The user's export presets.
export_presets: Vec<crate::export::ExportPreset>,
/// Print templates.
print_templates: Vec<crate::print::template::PrintTemplate>,
/// Metadata presets.
metadata_presets: Vec<crate::cmd::metadata::MetadataPreset>,
/// Filter presets.
@@ -490,7 +494,9 @@ impl Session {
let prefs = settings.read::<PrefsFile>(files.as_mut(), "prefs.json").unwrap_or_default();
self.xmp = prefs.xmp;
self.last_export = prefs.last_export;
self.last_merge = prefs.last_merge;
self.export_presets = prefs.export_presets;
self.print_templates = prefs.print_templates;
self.metadata_presets = prefs.metadata_presets;
self.filter_presets = prefs.filter_presets;
self.curve_presets = prefs.curve_presets;
@@ -743,7 +749,9 @@ impl Session {
let v = serde_json::to_vec_pretty(&PrefsFile {
xmp: self.xmp,
last_export: self.last_export.clone(),
last_merge: self.last_merge.clone(),
export_presets: self.export_presets.clone(),
print_templates: self.print_templates.clone(),
metadata_presets: self.metadata_presets.clone(),
filter_presets: self.filter_presets.clone(),
curve_presets: self.curve_presets.clone(),
+2
View File
@@ -538,6 +538,7 @@ mod tests {
keywords: vec!["Trips|Goa".into()],
history: vec![BTreeMap::from([("text".into(), serde_json::json!("step")), ("curve".into(), serde_json::json!([0, 128, 255]))])],
snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("before"))])],
original: crate::lightroom_catalog::Original::Local,
};
CatalogImport {
source: "source.lrcat".into(),
@@ -621,6 +622,7 @@ mod tests {
keywords: Vec::new(),
history: vec![BTreeMap::from([("text".into(), serde_json::json!(format!("history-{index}-{}", "x".repeat(8 * 1024))))])],
snapshots: Vec::new(),
original: crate::lightroom_catalog::Original::Local,
})
.collect();
assert_eq!(store_best_effort(&path, &input).unwrap(), None);
+213 -23
View File
@@ -2,7 +2,7 @@
//! Lightroom, Python and a C SQLite runtime are not needed. Original paths stay in place.
//! Raw settings are archived before mutation; mapped edits are approximations, not Adobe renders.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use std::sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
@@ -146,6 +146,31 @@ pub struct CatalogPhoto {
pub keywords: Vec<String>,
pub history: Vec<Row>,
pub snapshots: Vec<Row>,
/// Whether `path` may be looked at (derived when the catalog is read; not archived).
#[serde(skip)]
pub original: Original,
}
/// Whether the original a catalog lists may be looked at. Its path is resolved with the catalog
/// as the document ([`crate::doc_path::resolve`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Original {
/// `path` is a local file path, or one on the network share the catalog is on.
Local,
/// `path` is not a path on this computer (a catalog made on another system): the photo is
/// kept as an offline record for later relinking, and the path is not looked at.
#[default]
NotHere,
/// `path` is refused (why): it is on another computer or a device, or its folder or file name
/// is an absolute path. The photo is reported missing and not added to the library.
Refused(String),
}
impl CatalogPhoto {
/// Whether the original is a file here; only a [`Original::Local`] path is looked at.
pub fn original_is_file(&self) -> bool {
self.original == Original::Local && Path::new(&self.path).is_file()
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -343,25 +368,36 @@ fn committed_wal_len(main: &[u8], wal: &[u8]) -> Result<usize, String> {
/// Where a root folder is when its `absolutePath` isn't a folder here (the catalog came from
/// another computer): `relativePathFromCatalog`, which Lightroom records for roots on the
/// catalog's volume, resolved against the catalog's folder, if that is a folder.
/// catalog's volume, resolved against the catalog's folder, if that is a folder. Both paths are
/// looked at only when [`crate::doc_path::resolve`] follows them.
fn relocated_root(absolute: &str, relative: &str, catalog: &Path) -> Option<PathBuf> {
if relative.is_empty() || !Path::new(relative).is_relative() || Path::new(absolute).is_dir() {
if relative.is_empty() || !Path::new(relative).is_relative() || crate::doc_path::resolve(absolute, Some(catalog)).is_ok_and(|p| p.is_dir()) {
return None;
}
let dir = std::path::absolute(catalog).ok()?.parent()?.join(relative);
let mut out = PathBuf::new();
for part in dir.components() {
match part {
Component::ParentDir => {
if !out.pop() {
return None;
}
}
Component::CurDir => {}
part => out.push(part),
}
crate::doc_path::resolve(relative, Some(catalog)).ok().filter(|dir| dir.is_dir())
}
/// Whether a folder path or file name from the catalog is absolute: `Path::join` would put it in
/// place of the root folder.
fn is_absolute_part(part: &str) -> bool {
let bytes = part.as_bytes();
part.starts_with(['/', '\\'])
|| (bytes.first().is_some_and(u8::is_ascii_alphabetic) && bytes.get(1) == Some(&b':'))
|| Path::new(part).is_absolute()
}
/// The path of an original under `root` and whether it may be looked at, resolved with the
/// catalog at `catalog` as the document.
fn original_path(root: &str, folder: &str, name: &str, catalog: &Path) -> (String, Original) {
let stored = Path::new(root).join(folder).join(name).to_string_lossy().to_string();
if is_absolute_part(folder) || is_absolute_part(name) {
return (stored, Original::Refused("its folder or file name is an absolute path".into()));
}
match crate::doc_path::resolve(&stored, Some(catalog)) {
Ok(found) => (found.to_string_lossy().to_string(), Original::Local),
Err(crate::doc_path::NotFollowed::NotHere) => (stored, Original::NotHere),
Err(crate::doc_path::NotFollowed::Refused(why)) => (stored, Original::Refused(why.to_string())),
}
out.is_dir().then_some(out)
}
/// Inspect `.lrcat` plus committed WAL pages without modifying either source file.
@@ -457,6 +493,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
out
};
let mut root_paths = HashMap::new();
let mut refused_roots = HashSet::new();
let mut root_ids: Vec<_> = roots.keys().copied().collect();
root_ids.sort_unstable();
for (id, root) in root_ids.iter().filter_map(|id| Some((*id, roots.get(id)?))) {
@@ -469,6 +506,11 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
}
None => absolute.to_string(),
};
if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(path)) {
warnings
.push(format!("root folder {}: {resolved} is not opened: {why}; its photos are listed as missing and not added", text(root, "name")));
refused_roots.insert(id);
}
root_paths.insert(id, resolved);
}
let mut history = group(optional_table("Adobe_libraryImageDevelopHistoryStep", &mut warnings)?);
@@ -487,13 +529,19 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
let file = files.get(&number(&image, "rootFile")).ok_or_else(|| format!("image {id}: missing file record"))?;
let folder = folders.get(&number(file, "folder")).ok_or_else(|| format!("image {id}: missing folder record"))?;
let root = roots.get(&number(folder, "rootFolder")).ok_or_else(|| format!("image {id}: missing root record"))?;
let root_path = root_paths.get(&number(root, "id_local")).map_or("", String::as_str);
let root_id = number(root, "id_local");
let root_path = root_paths.get(&root_id).map_or("", String::as_str);
let folder_path = text(folder, "pathFromRoot");
let name = text(file, "idx_filename");
if root_path.is_empty() || name.is_empty() {
return Err(format!("image {id}: incomplete original path"));
}
let path = Path::new(root_path).join(folder_path).join(name).to_string_lossy().to_string();
let (photo_path, original) = original_path(root_path, folder_path, name, path);
if let Original::Refused(why) = &original
&& !refused_roots.contains(&root_id)
{
out.warnings.push(format!("image {id}: {photo_path} is not opened: {why}; listed as missing and not added"));
}
let packet = match xmp(metadata.get(&id).and_then(|r| r.get("xmp"))) {
Ok(s) => s,
Err(e) => {
@@ -504,19 +552,64 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
out.photos.push(CatalogPhoto {
source_id: id,
uuid: text(&image, "id_global").into(),
path,
path: photo_path,
image,
settings: develops.get(&id).cloned().unwrap_or_default(),
xmp: packet,
keywords: keywords.remove(&id).unwrap_or_default(),
history: history.remove(&id).unwrap_or_default(),
snapshots: snapshots.remove(&id).unwrap_or_default(),
original,
});
}
refuse_non_media(&mut out);
ensure_read_active(cancel)?;
Ok(out)
}
/// Drop the catalog's images whose original is not a file type LightCraft reads, saying so in the
/// import's warnings.
///
/// The catalog decides these paths, and a record it leaves behind is one click from the system
/// opener (Photo ▸ Edit In ▸ Open Original in Other Editor). A record for `payload.exe`,
/// `start.lnk` or `Evil.app` would make a `.lrcat` someone was sent a way to have a program run
/// (issue #2135), so such an image never becomes a photo: not imported, not relinkable, not
/// openable. A virtual copy of a refused original goes with it — it has no original of its own.
///
/// Called where the catalog is read and again where its photos become records, so neither route
/// can keep one; the second pass finds nothing left to say.
pub(crate) fn refuse_non_media(data: &mut CatalogImport) {
// masters first: a virtual copy may come before its master in the table
let refused: HashSet<i64> = data
.photos
.iter()
.filter(|p| number(&p.image, "masterImage") == 0 && !crate::open_path::is_media(Path::new(&p.path)))
.map(|p| p.source_id)
.collect();
if refused.is_empty() {
return;
}
let mut warnings = Vec::new();
data.photos.retain(|p| {
let master = number(&p.image, "masterImage");
// `masterImage` is 0 for a master, so a refused id of 0 (a malformed catalog) must not
// take every master of the catalog with it
if master != 0 {
if !refused.contains(&master) {
return true;
}
warnings.push(format!("image {}: not imported; its original was not imported", p.source_id));
return false;
}
if !refused.contains(&p.source_id) {
return true;
}
warnings.push(format!("image {}: not imported; {} isn't one of the file types LightCraft reads", p.source_id, p.path));
false
});
data.warnings.extend(warnings);
}
fn ensure_read_active(cancel: &AtomicBool) -> Result<(), String> {
if cancel.load(Ordering::Relaxed) { Err("Lightroom import cancelled".into()) } else { Ok(()) }
}
@@ -665,11 +758,11 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) ->
let paths: Vec<_> = data
.photos
.iter()
.filter(|p| number(&p.image, "masterImage") == 0 && !existing.contains_key(&key(&p.path)) && Path::new(&p.path).is_file())
.filter(|p| number(&p.image, "masterImage") == 0 && !existing.contains_key(&key(&p.path)) && p.original_is_file())
.map(|p| p.path.clone())
.collect();
let missing_sources: HashSet<String> =
data.photos.iter().filter(|p| number(&p.image, "masterImage") == 0).filter(|p| !Path::new(&p.path).is_file()).map(|p| key(&p.path)).collect();
data.photos.iter().filter(|p| number(&p.image, "masterImage") == 0).filter(|p| !p.original_is_file()).map(|p| key(&p.path)).collect();
let files = crate::import::import(s, &paths, crate::import::ImportMode::Add)?;
let applied =
apply_prepared(s, data, ApplyPrepared { update_existing, files, index: &mut index, archive_path, missing_sources: &missing_sources, undo0 })?;
@@ -692,8 +785,10 @@ pub(crate) struct ApplyPrepared<'a> {
pub(crate) undo0: usize,
}
pub(crate) fn apply_prepared(s: &mut crate::Session, data: CatalogImport, context: ApplyPrepared<'_>) -> crate::Result<AppliedImport> {
pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, context: ApplyPrepared<'_>) -> crate::Result<AppliedImport> {
let ApplyPrepared { update_existing, files, index, archive_path, missing_sources, undo0 } = context;
// nothing but a file type LightCraft reads becomes a record, whichever route got here (#2135)
refuse_non_media(&mut data);
validate(&data).map_err(error)?;
let mut warnings = data.warnings.clone();
let duplicates: HashMap<_, _> = files.duplicates.iter().filter_map(|d| d.existing.map(|id| (key(&d.path), PhotoId(id)))).collect();
@@ -713,12 +808,18 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, data: CatalogImport, contex
let mut photos: Vec<_> = data.photos.iter().collect();
photos.sort_by_key(|p| number(&p.image, "masterImage") != 0);
let copy_masters: HashSet<_> = data.photos.iter().map(|p| number(&p.image, "masterImage")).filter(|id| *id != 0).collect();
let refused: HashSet<_> = data.photos.iter().filter(|p| matches!(p.original, Original::Refused(_))).map(|p| p.source_id).collect();
let mut planned: HashMap<PhotoId, Photo> = HashMap::new();
for src in photos {
let master = number(&src.image, "masterImage");
if master == 0 && missing_sources.contains(&key(&src.path)) {
missing.push(src.path.clone());
}
// A refused path must not become a library record the app would look at later; its
// virtual copies go with it.
if refused.contains(&src.source_id) || refused.contains(&master) {
continue;
}
let indexed = index
.photos
.get(&identity(&data, src))
@@ -940,6 +1041,7 @@ mod tests {
keywords: vec!["Travel|Goa".into()],
history: vec![row(json!({"text":"s = { Exposure2012 = 0.5 }"}))],
snapshots: Vec::new(),
original: Original::Local,
};
let mut copy = photo.clone();
copy.source_id = 2;
@@ -962,6 +1064,48 @@ mod tests {
warnings: Vec::new(),
}
}
/// A crafted `.lrcat` that names a program as a photo's original gets no record for it, so
/// Photo ▸ Edit In ▸ Open Original has nothing to hand the system opener (#2135). Its virtual
/// copies go with it; the catalog's real photos still import.
#[test]
fn a_catalog_original_that_is_not_a_photo_file_is_not_imported() {
let mut data = sample();
let mut exe = data.photos[1].clone();
exe.source_id = 3;
exe.uuid = "payload".into();
exe.path = "/Users/sky/Downloads/payload.exe".into();
exe.image = row(json!({"id_local":3,"fileFormat":"ARW","fileWidth":20,"fileHeight":10}));
let mut exe_copy = exe.clone();
exe_copy.source_id = 4;
exe_copy.uuid = "payload-copy".into();
exe_copy.path = "/Users/sky/Downloads/payload.exe".into();
exe_copy.image = row(json!({"id_local":4,"masterImage":3,"copyName":"Mono"}));
// the copy comes before its master, as a catalog's table order may have it
data.photos.insert(0, exe_copy);
data.photos.push(exe);
for bad in [r"C:\Users\sky\start.lnk", "/Applications/Evil.app", "/Users/sky/go.command", "/Users/sky/run.bat"] {
let mut one = data.clone();
one.photos.retain(|p| p.source_id < 3);
let mut planted = one.photos[1].clone();
planted.source_id = 5;
planted.uuid = "planted".into();
planted.path = bad.into();
planted.image = row(json!({"id_local":5,"fileFormat":"ARW"}));
one.photos.push(planted);
let mut s = crate::Session::new();
let r = apply(&mut s, one, false).unwrap();
assert_eq!(r["photos"], 2, "{bad} is not catalogued: {r}");
assert!(s.catalog.photos().all(|p| !matches!(&p.source, Source::File { path } if path == bad)), "{bad} became a library record");
}
let mut s = crate::Session::new();
let r = apply(&mut s, data, false).unwrap();
assert_eq!(r["photos"], 2, "only the real master and its copy: {r}");
assert!(s.catalog.photos().all(|p| !matches!(&p.source, Source::File { path } if path.ends_with(".exe"))), "the program was catalogued");
let warnings = r["warnings"].to_string();
assert!(warnings.contains("payload.exe") && warnings.contains("file types LightCraft reads"), "{warnings}");
assert!(warnings.contains("image 4: not imported"), "the virtual copy of the refused original goes with it: {warnings}");
}
#[test]
fn offline_local_master_and_copy_join_library_with_one_undo_step() {
let mut s = crate::Session::new();
@@ -1508,11 +1652,57 @@ mod tests {
// a relative path that leads nowhere keeps the recorded one
std::fs::write(&path, native_catalog(&photo_tables(("C:/Users/me/Project/RAW/", "../Elsewhere/")))).unwrap();
let catalog = read(&path).unwrap();
assert!(catalog.photos[0].path.starts_with("C:/Users/me/Project/RAW/"), "{}", catalog.photos[0].path);
assert!(Path::new(&catalog.photos[0].path).starts_with("C:/Users/me/Project/RAW/"), "{}", catalog.photos[0].path);
assert!(catalog.warnings.is_empty(), "{:?}", catalog.warnings);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn originals_on_other_computers_are_never_looked_at_or_added() {
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-remote-roots-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("Photos")).unwrap();
std::fs::write(dir.join("Photos/test.ARW"), b"original").unwrap();
let source = dir.join("source.lrcat");
let mut roots = vec![r"\\192.0.2.1\share\".to_string(), "file://192.0.2.1/s/".to_string()];
if cfg!(unix) {
// `//<local folder>/` is a local folder to Linux, but a network path to the resolver.
roots.push(format!("/{}/", dir.display()));
}
for root in &roots {
std::fs::write(&source, native_catalog(&photo_tables((root, "")))).unwrap();
let catalog = read(&source).unwrap();
assert!(matches!(catalog.photos[0].original, Original::Refused(_)), "{root}: {:?}", catalog.photos[0]);
assert!(catalog.warnings.iter().any(|w| w.contains("not opened")), "{root}: {:?}", catalog.warnings);
let mut s = crate::Session::new();
let probes = Arc::new(AtomicUsize::new(0));
let calls = probes.clone();
s.media.file_probe = Some(Arc::new(move |_| {
calls.fetch_add(1, Ordering::Relaxed);
Err("a refused original must not be probed".into())
}));
let report = import(&mut s, &source, false).unwrap();
assert_eq!(probes.load(Ordering::Relaxed), 0, "{root}");
assert_eq!(report["missing"].as_array().map(Vec::len), Some(1), "{root}: {report}");
assert!(s.catalog.is_empty(), "{root}");
}
// An absolute folder path would replace the root.
let mut tables = photo_tables((dir.to_str().unwrap(), ""));
tables[1].2[2] = SqlValue::Text(format!("{}/Photos/", dir.display()));
std::fs::write(&source, native_catalog(&tables)).unwrap();
assert!(matches!(read(&source).unwrap().photos[0].original, Original::Refused(_)));
// A root beside the catalog is followed.
std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap();
let catalog = read(&source).unwrap();
assert_eq!(catalog.photos[0].original, Original::Local);
assert!(catalog.photos[0].original_is_file());
// A root that moved is found through its path relative to the catalog.
std::fs::write(&source, native_catalog(&photo_tables((r"\\192.0.2.1\share\", "./")))).unwrap();
let catalog = read(&source).unwrap();
assert!(catalog.photos[0].original_is_file(), "{:?}", catalog.photos[0]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn oversized_optional_table_warns_and_is_skipped() {
let mut main = vec![0u8; 2 * 512];
+3 -1
View File
@@ -329,7 +329,7 @@ fn original_paths(data: &CatalogImport, cancel: &AtomicBool) -> crate::Result<(V
if !seen.insert(key.clone()) {
continue;
}
if Path::new(&photo.path).is_file() {
if photo.original_is_file() {
paths.push(photo.path.clone());
} else {
missing.insert(key);
@@ -393,6 +393,7 @@ mod tests {
keywords: Vec::new(),
history: Vec::new(),
snapshots: Vec::new(),
original: lightroom_catalog::Original::Local,
}],
collections: Vec::new(),
members: Vec::new(),
@@ -531,6 +532,7 @@ mod tests {
serde_json::json!(format!("history-{source_id}-{}", "x".repeat(8 * 1024))),
)])],
snapshots: Vec::new(),
original: lightroom_catalog::Original::Local,
}
})
.collect();
+35 -1
View File
@@ -62,7 +62,7 @@ impl SettingsHashes {
}
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 63;
pub const RENDER_CACHE_VERSION: u64 = 64;
/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
@@ -2189,6 +2189,40 @@ mod tests {
assert!(mean(&a) > mean(&b) + 10.0, "two stops brighter after: {} vs {}", mean(&a), mean(&b));
}
// LR-VIEW-ZOOM: what the loupe shows at 1:1 is what an export at full size writes. A window of
// the zoomed frame (the photo's own pixels) is pixel-for-pixel the export, at the centre and
// at a corner, with tone, colour and detail edits on a camera-sized photo
#[test]
fn one_to_one_window_pixels_are_export_pixels() {
use lightcraft_pipeline::{OutputDepth, OutputSpace, PixelWindow};
let mut s = crate::Session::with_demo();
let id = s.active().unwrap();
let p = s.catalog.photo(id).unwrap().clone();
let (w, h) = (p.width as usize, p.height as usize);
assert!(w.max(h) > 2560, "larger than the preview cap: {w}×{h}");
let mut d = (*s.develop_of(id).unwrap()).clone();
d.light.exposure = 0.7;
d.light.contrast = 25.0;
d.color.saturation = 20.0;
s.set_develop(id, d, "Edits").unwrap();
let export = s.render_export(id, w, h, OutputSpace::Srgb, OutputDepth::U8).unwrap().image;
assert_eq!((export.width, export.height), (w, h), "a full-size export");
for win in [PixelWindow { x: w / 2 - 256, y: h / 2 - 256, w: 512, h: 384 }, PixelWindow { x: 0, y: h - 300, w: 400, h: 300 }] {
let tile = s.region_job(id, w, h, win, true).unwrap().run().rendered.unwrap().image;
assert_eq!((tile.width, tile.height), (win.w, win.h));
let mut worst = 0u8;
for y in 0..win.h {
for x in 0..win.w {
let (a, b) = (tile.data[y * win.w + x], export.data[(win.y + y) * w + win.x + x]);
for k in 0..3 {
worst = worst.max(a[k].abs_diff(b[k]));
}
}
}
assert!(worst <= 1, "window {win:?}: the 1:1 view differs from the export by up to {worst} levels");
}
}
/// The thumbnail of a photo whose preview-level source is decoded is cut from it: the file (here
/// one nothing can decode) is not read again.
#[test]
+1
View File
@@ -191,6 +191,7 @@ impl MergeJob {
metadata: r.metadata,
baseline_exposure: r.baseline_exposure,
lens: Vec::new(),
wb_multipliers: r.wb_multipliers,
};
f.orient();
merged.push(f);
+117
View File
@@ -0,0 +1,117 @@
//! Whether a path the library holds may be handed to the operating system.
//!
//! A photo's `Source::File` path is not always something a user typed: it can come from an
//! imported Lightroom catalog, an `.lrcat` someone was sent, a relink or a synchronised folder.
//! Photo ▸ Edit In ▸ *Open Original in Other Editor* and the system default opener run whatever
//! the path names, so a record pointing at `payload.exe`, `thing.lnk`, `run.bat`, `page.hta`
//! (Windows) or `Evil.app`, `go.command` (macOS) would be executed on one click (issue #2135).
//!
//! [`openable`] is the one gate every such hand-over goes through: the path must be a regular
//! file whose extension is one LightCraft itself reads ([`crate::import::EXTENSIONS`], which
//! already covers the Edit In copy formats `tif`/`tiff`/`psd`), and what a link resolves to must
//! be one too, so a `photo.jpg` pointing at `/bin/sh` is refused as well. What comes back is the
//! absolute path to hand over; what comes back on refusal is the sentence to show the user.
//!
//! Nothing here opens, stats-for-content or reads the file: it only decides whether the path may
//! leave LightCraft. Catalog import applies the same test ([`crate::lightroom_catalog`]), so a
//! refused original never becomes a library record in the first place.
use std::path::Path;
/// The absolute path to hand to an opener or external editor, or the reason it is refused.
///
/// `label` names the thing in the error (a file name, a photo's name); an empty `label` uses
/// the path's own file name.
pub fn openable(path: &str, label: &str) -> Result<String, String> {
let p = Path::new(path);
let name = match label.trim() {
"" => p.file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().into_owned()),
l => l.to_string(),
};
if !is_media(p) {
return Err(format!("{name} isn't one of the file types LightCraft reads, so it isn't handed to another application"));
}
match std::fs::metadata(p) {
Ok(m) if m.is_file() => {}
Ok(_) => return Err(format!("{name} isn't a file, so it isn't handed to another application")),
Err(e) => return Err(format!("the original is missing: {path} ({e})")),
}
// a link may name a photo and point at a program; what runs is what it points at
if let Ok(target) = p.canonicalize()
&& !is_media(&target)
{
return Err(format!("{name} points at {}, which isn't a file type LightCraft reads", target.display()));
}
let absolute = std::path::absolute(p).map_err(|e| format!("{name}: {e}"))?;
Ok(absolute.to_string_lossy().into_owned())
}
/// Whether `path`'s extension is one LightCraft reads (the Edit In copy formats included).
pub fn is_media(path: &Path) -> bool {
crate::import::is_supported(path)
}
#[cfg(test)]
mod tests {
use super::*;
fn write(dir: &Path, name: &str) -> String {
let p = dir.join(name);
std::fs::write(&p, b"x").unwrap();
p.to_string_lossy().into_owned()
}
#[test]
fn only_file_types_lightcraft_reads_are_handed_over() {
let dir = std::env::temp_dir().join(format!("lc-openable-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
for good in ["DSC_1.NEF", "a.jpg", "copy-Edit.tif", "copy-Edit.psd"] {
let path = write(&dir, good);
assert_eq!(openable(&path, "").unwrap(), path, "{good} is a photo LightCraft reads");
}
for bad in ["payload.exe", "shortcut.lnk", "run.bat", "page.hta", "go.command", "no-extension"] {
let path = write(&dir, bad);
let e = openable(&path, "").unwrap_err();
assert!(e.contains(bad) && e.contains("file types LightCraft reads"), "{bad}: {e}");
}
// a bundle (macOS `.app`) and any other folder are not files
let bundle = dir.join("Evil.app");
std::fs::create_dir_all(&bundle).unwrap();
let e = openable(&bundle.to_string_lossy(), "").unwrap_err();
assert!(e.contains("isn't one of the file types") || e.contains("isn't a file"), "{e}");
let e = openable(&dir.join("gone.jpg").to_string_lossy(), "").unwrap_err();
assert!(e.contains("missing"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A relative path is made absolute: the opener runs with its own working directory.
#[test]
fn the_path_handed_over_is_absolute() {
let dir = std::env::temp_dir().join(format!("lc-openable-abs-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = write(&dir, "a.jpg");
let dotted = Path::new(&path).parent().unwrap().join(".").join("a.jpg");
let out = openable(&dotted.to_string_lossy(), "").unwrap();
assert!(Path::new(&out).is_absolute(), "{out}");
assert!(out.ends_with("a.jpg"), "{out}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A link named like a photo that points at a program is refused: what the opener runs is
/// the target, not the name.
#[cfg(unix)]
#[test]
fn a_link_to_a_program_is_refused() {
let dir = std::env::temp_dir().join(format!("lc-openable-link-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let target = write(&dir, "payload.command");
let link = dir.join("holiday.jpg");
std::os::unix::fs::symlink(&target, &link).unwrap();
let e = openable(&link.to_string_lossy(), "").unwrap_err();
assert!(e.contains("points at") && e.contains("payload.command"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
}
+31
View File
@@ -395,6 +395,20 @@ pub(crate) fn lua_settings_props(settings: &Lua) -> Result<(Props, crate::crs_ma
let mut values = crate::crs_masks::Values::new();
for (k, v) in fields {
let key = format!("crs:{k}");
// the profile a preset names: its fields as XMP's struct fields (`crs:Look/crs:Name`…)
if k == "Look"
&& let Lua::Table(_, look) = v
{
for (f, fv) in look {
let val = match fv {
Lua::Num(n) => format!("{n}"),
Lua::Str(s) => delocalize(s),
_ => continue,
};
props.insert(format!("crs:Look/crs:{f}"), vec![val]);
}
continue;
}
if crate::crs_masks::CONTAINERS.contains(&key.as_str()) {
values.insert(key.clone(), crate::crs_masks::from_lua(v));
}
@@ -497,6 +511,12 @@ pub(crate) fn build(props: &Props, values: &crate::crs_masks::Values, name: Stri
o.remove("wb");
}
}
// the profile it names, resolved against the user's imported profiles by `preset.import`
if let Some(look) = crate::profile_refs::look_ref(props)
&& let Some(o) = settings.as_object_mut()
{
o.insert("profile".into(), serde_json::json!({"look": look}));
}
if settings.as_object().is_none_or(Map::is_empty) {
return None;
}
@@ -684,6 +704,17 @@ text]], z = ZSTR "loc" }"#,
assert_eq!(d.light.exposure, 0.35);
}
#[test]
fn lrtemplate_keeps_the_profile_it_names() {
let t = r#"s = { title = "Film", value = { settings = { Exposure2012 = 0.2,
Look = { Name = "Portra 400", Amount = 0.5, UUID = "ABCD", Group = "$$$/Pack=Film Pack", Parameters = { Version = "14.0" } } } } }"#;
let v = read_presets("Film.lrtemplate", t.as_bytes(), None).unwrap();
assert_eq!(
v[0].preset.settings["profile"],
serde_json::json!({"look": {"name": "Portra 400", "amount": 50.0, "group": "Film Pack", "uuid": "abcd"}})
);
}
#[test]
fn old_process_version_fields_are_approximated() {
let t = "s = { title = \"Old\", value = { settings = { Exposure = 0.5, Contrast = 50, FillLight = 20, HighlightRecovery = 30, Clarity = 10, ToneCurve = { 0, 0, 64, 50, 255, 255 } } } }";
File diff suppressed because it is too large. Load diff
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more