From 2f7f61b8a9b9b1b4367b576a5fb762557cf1e77c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:24:19 +0200 Subject: [PATCH 001/625] LR-META-EXIF-FULL: preserve shutter precision through import and export (#1619) Share lossless duration formatting between catalog import and All Metadata. Keep the catalog schema unchanged and cover persisted metadata round trips. Co-authored-by: Codex --- crates/engine/src/files.rs | 23 ++++++++++++++++++++++- crates/meta/src/lib.rs | 31 +++++++++++++++++++++++++------ crates/meta/src/tags.rs | 24 +++++++++++++++++++++++- docs/parity-checklist.md | 5 +++-- 4 files changed, 73 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index e2144eb859..f26e0b2307 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -14,7 +14,7 @@ use lightcraft_raster::resample::{Filter, fit}; use crate::media::{DenoiseSpec, FileLoader, FileProbe, PairLoader, PreviewLoader, ProbeInfo}; fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { - let shutter = m.exposure_time.map(|t| if t >= 1.0 { format!("{t:.0}") } else { format!("1/{:.0}", 1.0 / t) }).unwrap_or_default(); + let shutter = m.exposure_display().map(|s| s.trim_end_matches('″').to_string()).unwrap_or_default(); let camera = [m.make.clone().unwrap_or_default(), m.model.clone().unwrap_or_default()].join(" ").trim().to_string(); let meta = Meta { camera, @@ -1049,6 +1049,27 @@ impl crate::Session { #[cfg(test)] mod tests { + #[test] + fn imported_shutter_times_survive_catalog_and_export_metadata() { + use lightcraft_catalog::{Catalog, Photo, PhotoId}; + for t in [0.3, 0.4, 0.6, 0.8, 1.3, 1.6, 2.5, 3.2, 0.625, 1.0 / 2.8, 0.003, 1.0 / 250.0] { + let original = lightcraft_meta::Metadata { exposure_time: Some(t), ..Default::default() }; + let (meta, _) = meta_of(&original); + assert_eq!(lightcraft_catalog::parse_shutter_seconds(&meta.shutter), Some(t)); + // Exercise the persisted string, not a value kept alongside it in memory. + let meta: Meta = serde_json::from_str(&serde_json::to_string(&meta).unwrap()).unwrap(); + let mut photo = Photo::new(PhotoId(1), lightcraft_catalog::Source::Demo { scene: 0 }, "capture.jpg", "JPEG", 2, 2, ""); + photo.meta = meta; + let exported = crate::export::export_metadata(&photo, &Catalog::new(), &crate::export::ExportOptions::default()).unwrap(); + assert_eq!(exported.exposure_time, Some(t)); + let bytes = + crate::export::encode_with_metadata(&lightcraft_raster::Rgba8::new(2, 2), &crate::export::ExportOptions::default(), Some(&exported)) + .unwrap(); + let back = lightcraft_meta::extract(&bytes); + assert!((back.exposure_time.unwrap() - t).abs() < 0.000001, "{t}: {:?}", back.exposure_time); + } + } + /// Keywords from a file keep their hierarchy: the paths of `lr:hierarchicalSubject`, not the /// flat names of `dc:subject` that LightCraft's exports (and Lightroom Classic) write besides /// them; an exported `travel|Italy|Rome` comes back as itself. diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 31a35cc652..772c3900c8 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -222,18 +222,21 @@ impl Metadata { } } - /// Exposure time formatted like cameras show it: `1/250`, `0.5`, `2″`. + /// Exposure time without rounding away capture metadata: `1/250`, `0.625`, `1.3″`. pub fn exposure_display(&self) -> Option { let t = self.exposure_time?; - if t.is_nan() || t <= 0.0 { + if !t.is_finite() || t <= 0.0 { return None; } - Some(if t < 0.3 { - format!("1/{}", (1.0 / t).round()) + let denominator = (1.0 / t).round(); + // Only use a reciprocal when parsing it recovers the original duration. + // Decimal thirds of a stop and unusual camera rationals must not be quantized. + Some(if t < 0.3 && denominator.is_finite() && 1.0 / denominator == t { + format!("1/{denominator}") } else if t < 1.0 { - format!("{}", (t * 10.0).round() / 10.0) + t.to_string() } else { - format!("{}″", (t * 10.0).round() / 10.0) + format!("{t}″") }) } @@ -306,6 +309,22 @@ mod tests { assert_eq!(parse_number("inf"), None); } + #[test] + fn exposure_display_preserves_duration() { + for t in [0.3, 0.4, 0.6, 0.8, 1.3, 1.6, 2.5, 3.2, 0.625, 1.0 / 2.8, 0.003, 1.0 / 250.0] { + let text = Metadata { exposure_time: Some(t), ..Default::default() }.exposure_display().unwrap(); + let number = text.trim_end_matches('″'); + let actual = match number.split_once('/') { + Some((n, d)) => n.parse::().unwrap() / d.parse::().unwrap(), + None => number.parse::().unwrap(), + }; + assert_eq!(actual, t, "{text}"); + } + for t in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(Metadata { exposure_time: Some(t), ..Default::default() }.exposure_display().is_none()); + } + } + #[test] fn exposure_display() { let mut m = Metadata { exposure_time: Some(1.0 / 250.0), ..Default::default() }; diff --git a/crates/meta/src/tags.rs b/crates/meta/src/tags.rs index 39e26097d6..d69b25735f 100644 --- a/crates/meta/src/tags.rs +++ b/crates/meta/src/tags.rs @@ -237,7 +237,11 @@ fn value_text(group: &str, tag: u16, v: &Value) -> String { // exposure time as a fraction of a second let (n, d) = a[0]; let s = n as f64 / d as f64; - if s >= 1.0 || n == 0 { format!("{} s", rational(n as f64, d as f64)) } else { format!("1/{} s", (1.0 / s).round()) } + let display = crate::Metadata { exposure_time: Some(s), ..Default::default() }.exposure_display(); + match display { + Some(text) => format!("{} s", text.trim_end_matches('″')), + None => format!("{} s", rational(n as f64, d as f64)), + } } Value::Rational(a) if tag == 0x829d && group != "GPS" && a.len() == 1 => format!("f/{}", rational(a[0].0 as f64, a[0].1 as f64)), Value::Rational(a) if tag == 0x920a && group != "GPS" && a.len() == 1 => format!("{} mm", rational(a[0].0 as f64, a[0].1 as f64)), @@ -355,6 +359,24 @@ pub fn file_tag_rows(bytes: &[u8]) -> Vec { #[cfg(test)] mod tests { + #[test] + fn exposure_rows_do_not_round_third_stop_times() { + for (n, d, expected) in [ + (3, 10, "0.3 s"), + (4, 10, "0.4 s"), + (6, 10, "0.6 s"), + (8, 10, "0.8 s"), + (13, 10, "1.3 s"), + (16, 10, "1.6 s"), + (25, 10, "2.5 s"), + (32, 10, "3.2 s"), + (5, 8, "0.625 s"), + (1, 250, "1/250 s"), + ] { + assert_eq!(value_text("EXIF", 0x829a, &Value::Rational(vec![(n, d)])), expected); + } + } + use super::*; #[test] diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 7bb187811c..f7a4b2b381 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -168,7 +168,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-META-LOCATION | Location editing | P2 | 🟡 | `cmd:photo.setMeta` (`location`, `city`, `state`, `country`, `gps`), `cmd:metadata.reverseGeocode` | place fields and GPS (decimal or degrees / minutes / seconds) edited in Info, read/written as IPTC Core / Photoshop / EXIF XMP; Show on Map opens OpenStreetMap; Fill Location fills empty City / State / Country from GPS offline (GeoNames, downloaded on request: `cmd:metadata.downloadPlaceNames`); no embedded map | | LR-META-COPYPASTE | Copy / paste metadata | P2 | ✅ | `cmd:photo.copyMetadata`, `cmd:photo.pasteMetadata` | title, caption, alt text, extended description, copyright (notice, status, usage terms, info URL), creator, place fields, keywords; `fields` picks a subset | | LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; saving merges into an existing sidecar (`crates/meta/src/xmp_merge.rs`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte, an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`.xmp` for all but the raw); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934) | -| LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; metadata presets | +| LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; metadata presets Exposure durations retain their precision in imported catalog metadata and All Metadata (#1619). | ## F. Edit panel — global adjustments (EDIT) @@ -393,7 +393,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EXP-COLORSPACE | Output colour space | P0 | ✅ | `cmd:app.export` (`colorSpace`), `crates/pipeline/src/output.rs`, `crates/engine/src/export.rs` | sRGB, Display P3, Adobe RGB (1998) compatible, ProPhoto RGB, Rec. 2020: rendered from the working space with gamut mapping into the target gamut (CPU + GPU), own ICC profile embedded; AVIF stays sRGB (muxer has no ICC); lossy JPEG XL declares sRGB / P3 / Rec. 2020 (Adobe RGB and ProPhoto written as Rec. 2020), lossless JPEG XL embeds the profile | | LR-EXP-HDR | HDR output | P2 | 🟡 | `cmd:app.export`, `crates/ui-egui/src/panels/dialogs.rs` | HDR output checkbox in the export dialog: gain map JPEG, PQ or HLG AVIF, PQ PNG, PQ JPEG XL, float TIFF; no HDR presets yet | | LR-EXP-SHARPEN | Output sharpening | P1 | ✅ | `cmd:app.export` (`sharpen`, `sharpenAmount`) | | -| LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | | +| LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | Exposure durations survive catalog serialization and export without import-time reciprocal or whole-second rounding (#1619); previously rounded catalog values require reloading metadata from the original. | | LR-EXP-WATERMARK | Watermark | P1 | ✅ | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (`image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | | LR-EXP-NAMING | File naming | P1 | ✅ | `cmd:app.export` (`naming`, `startNumber`), `crates/engine/src/rename.rs` (`expand_tokens`) | one template language for export, Rename Photos and import renaming: `{name}`, `{num}` (number at the end of the name), `{seq}` / `{seq:N}`, `{date}` / `{date:%Y-%m-%d}`, `{folder}`, `{camera}`, `{lens}`, `{iso}`, `{rating}`, `{title}`, `{creator}`, `{ext}`; free-form template rather than a list of named schemes | | LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/panels/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) | @@ -790,6 +790,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-14 | patch | LR-META-EXIF-FULL, LR-EXP-METADATA: preserve shutter duration through import, display and export (#1619); no catalog schema change. Statuses and feature counts unchanged. | | 2026-10-13 | patch | LR-VIEW-COMPARE, LRC-LIB-COMPARE: ⌘/Ctrl- and Shift-clicks on the filmstrip in Compare change the selection as in the grid; the two photos shown stay selected and the active photo is unchanged (#187); statuses unchanged | | 2026-10-13 | minor | KEYC-SELECTONLYACTIVE: Edit → Select Only Active Photo (⌘⇧D) lands as a new row; status 🟡 (headless-tested, native macOS menu path unverified) | | 2026-10-13 | patch | LRC-LIB-CATALOG-IMPORT: a catalog whose tables are all still in its `-wal` file (main file schema format 0) opens instead of failing as an unsupported schema format; status unchanged | From ac12fad9c8f8367657f2fe21469e7bb274a0b3ab Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Thu, 15 Oct 2026 15:11:52 +0200 Subject: [PATCH 002/625] Plain labels are no longer drag-selectable, as in Lightroom (fixes #1885) --- crates/ui-egui/src/theme.rs | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 57ee987d1d..a42912896f 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -445,6 +445,9 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { s.text_styles.insert(egui::TextStyle::Small, FontId::proportional(11.0)); s.text_styles.insert(egui::TextStyle::Heading, FontId::new(16.0, FontFamily::Name(FONT_SEMIBOLD.into()))); s.animation_time = 0.08; + // Captions and headings are not text to select (#1885); text meant for copying opts in + // with `Label::selectable(true)`. + s.interaction.selectable_labels = false; }); } @@ -466,6 +469,46 @@ mod tests { } } + /// Drag the pointer across `label` from end to end, press Copy, and return what egui copied. + fn drag_and_copy(label: impl Fn() -> egui::Label) -> Option { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::default()); + let frame = |events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), + events, + ..Default::default() + }; + let mut rect = egui::Rect::NOTHING; + let mut out = ctx.run_ui(input, |ui| rect = ui.add(label()).rect); + out.textures_delta.clear(); + (out.platform_output.commands, rect) + }; + let (_, rect) = frame(vec![]); + let (from, to) = (rect.left_center() + egui::vec2(1.0, 0.0), rect.right_center() - egui::vec2(1.0, 0.0)); + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let mut commands = Vec::new(); + for events in [ + vec![egui::Event::PointerMoved(from)], + vec![button(from, true)], + vec![egui::Event::PointerMoved(to)], + vec![button(to, false)], + vec![egui::Event::Copy], + ] { + commands.extend(frame(events).0); + } + commands.into_iter().find_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text) } else { None }) + } + + /// #1885: a panel caption is not text to select, as in Lightroom; text a dialog offers for + /// copying (a path) opts in and still copies. + #[test] + fn static_labels_cannot_be_drag_selected_but_opted_in_text_can() { + assert_eq!(drag_and_copy(|| egui::Label::new("Exposure")), None, "a plain label was selected and copied"); + assert_eq!(drag_and_copy(|| egui::Label::new("/Users/me/Pictures").selectable(true)).as_deref(), Some("/Users/me/Pictures")); + } + /// #736: the release input must carry Thai, not silently skip the check with an older pin. /// Exercise the Thai characters of the reported folder name through every egui family. #[test] From 357b16b8d81b69bff6677b85860947177f4ab679 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:03:03 +0200 Subject: [PATCH 003/625] M12: SAM 3 on the CPU ~3x faster: encode ~37 -> ~11 s, a description ~6 -> ~2 s On the CPU, candle runs elementwise ops and layout copies on one thread, batched matmuls one batch element after another (each spread over all threads) and transposed convolutions one output channel at a time. In the 32-layer ViT that was more than half of the ~37 s encode on a 12-core Ryzen 9 3900X; a text prompt spent most of its ~6 s in the DETR encoder's attention over 5184 tokens. crates/segment/src/cpu.rs, used on the CPU only (Metal keeps the tensor ops): - fused parallel kernels for the bias adds with GELU / ReLU / residual add, the ViT's window partition + head split + RoPE (with the 1/8 score scale moved to q, exact for a power of two) and head merge, the detector's box relative-position bias and the pixel decoder's GroupNorm + ReLU: the same float operations in the same order, bit-identical results; - sdpa as one rayon task per (batch, head, block of query rows), with 256 KB score blocks that stay in the core's cache (4 MB blocks were 3x slower for the detector's 8 heads of 32); - the necks' 2x2 stride-2 transposed convolutions as one matmul plus a reordering. The last two change how gemm blocks its sums, so results move by float rounding only, as between two CPUs (gemm picks its blocking from the cache sizes). Against the unchanged code on a real photo: backbone 1.1e-5 relative, click mask 1e-5 with no pixel changing side, text masks <= 7e-4 with at most 6 of 16.6M pixels changing side, the same kept instances. Ryzen 9 3900X, 24 threads: encode ~37 -> ~11 s, preparing clicks ~2.3 -> ~0.9 s, a description ~6 -> ~2.1 s (the first one on a photo also builds the detector's features: ~8.8 -> ~2.9 s). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/segment/Cargo.toml | 2 + crates/segment/src/clip.rs | 2 +- crates/segment/src/cpu.rs | 551 +++++++++++++++++++++++++++++++++ crates/segment/src/detector.rs | 21 +- crates/segment/src/lib.rs | 2 + crates/segment/src/neck.rs | 5 +- crates/segment/src/nn.rs | 50 ++- crates/segment/src/vit.rs | 113 ++++++- docs/ai-masks.md | 26 +- 10 files changed, 741 insertions(+), 32 deletions(-) create mode 100644 crates/segment/src/cpu.rs diff --git a/Cargo.lock b/Cargo.lock index 4b6d54289f..f94a68a2ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3465,6 +3465,7 @@ dependencies = [ "lightcraft-fetch", "lightcraft-testkit", "log", + "rayon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index b4614a81d8..77f6353524 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -19,6 +19,8 @@ log = { workspace = true } candle-core = { workspace = true } candle-nn = { workspace = true } lightcraft-fetch = { workspace = true } +# the CPU kernels share candle's thread pool +rayon = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] candle-core = { workspace = true, features = ["metal"] } diff --git a/crates/segment/src/clip.rs b/crates/segment/src/clip.rs index b69c148a4f..18a82b3dd0 100644 --- a/crates/segment/src/clip.rs +++ b/crates/segment/src/clip.rs @@ -74,7 +74,7 @@ impl TextEncoder { let h = l.ln1.forward(&x)?; x = (&x + l.attn.forward(&h, &h, &h, Some(&bias))?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } Ok(self.final_ln.forward(&x)?) } diff --git a/crates/segment/src/cpu.rs b/crates/segment/src/cpu.rs new file mode 100644 index 0000000000..ffbd0bde6c --- /dev/null +++ b/crates/segment/src/cpu.rs @@ -0,0 +1,551 @@ +//! Fused CPU kernels for the model's elementwise work, attention and upsampling. +//! +//! On the CPU, candle runs bias adds, activations, the rotary encoding and layout copies (window +//! partitioning, splitting and merging heads) one element at a time on one thread, batched matrix +//! products one pair at a time and transposed convolutions one output channel at a time: in the +//! 32-layer ViT that was more than half of the encode time on a 12-core CPU, and most of a text +//! prompt went to attention over 5184 tokens. The elementwise kernels do the same arithmetic in +//! the same order (bit-identical results), fused into fewer passes over memory and spread over +//! the rayon pool that candle's matrix products use. Attention in cache-sized blocks and the +//! transposed convolutions as one product change how gemm blocks its sums: those results move +//! by float rounding (as they do between two CPUs, gemm picking its blocking from the caches). + +use std::f32::consts::FRAC_1_SQRT_2; + +use candle_core::cpu::erf::erf_f32; +use candle_core::{CpuStorage, CustomOp1, CustomOp2, CustomOp3, D, IndexOp, Layout, Shape, Tensor, bail}; +use candle_nn::{ConvTranspose2d, Linear}; +use rayon::prelude::*; + +use crate::{Error, Result}; + +/// A `b × h × w` token grid (row-major, `heads × head_dim` channels) attended in non-overlapping +/// `win × win` windows, or as a whole when `win` is 0. +#[derive(Clone, Copy, Debug)] +pub struct Grid { + pub b: usize, + pub h: usize, + pub w: usize, + pub win: usize, + pub heads: usize, + pub head_dim: usize, +} + +impl Grid { + /// Window height and width. + fn window(&self) -> (usize, usize) { + if self.win == 0 { (self.h, self.w) } else { (self.win, self.win) } + } + + /// Windows per image (down, across). + fn per_image(&self) -> (usize, usize) { + let (wh, ww) = self.window(); + (self.h / wh, self.w / ww) + } + + fn windows(&self) -> usize { + let (nh, nw) = self.per_image(); + self.b * nh * nw + } + + fn tokens(&self) -> usize { + let (wh, ww) = self.window(); + wh * ww + } + + fn channels(&self) -> usize { + self.heads * self.head_dim + } + + fn check(&self) -> candle_core::Result<()> { + let (wh, ww) = self.window(); + if wh == 0 || ww == 0 || !self.h.is_multiple_of(wh) || !self.w.is_multiple_of(ww) || !self.head_dim.is_multiple_of(2) { + bail!("grid {self:?}: windows must tile the grid"); + } + Ok(()) + } + + /// The grid row (token index in row-major order) of token `t` of window `win`. + fn row(&self, win: usize, t: usize) -> usize { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (win / (nh * nw), win % (nh * nw)); + let (y, x) = (i / nw * wh + t / ww, i % nw * ww + t % ww); + (b * self.h + y) * self.w + x + } + + /// The window and the token within it of grid row `row`. + fn window_of(&self, row: usize) -> (usize, usize) { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (row / (self.h * self.w), row % (self.h * self.w)); + let (y, x) = (i / self.w, i % self.w); + ((b * nh + y / wh) * nw + x / ww, y % wh * ww + x % ww) + } +} + +/// The contiguous `f32` values of a CPU tensor. +fn values<'a>(s: &'a CpuStorage, l: &Layout) -> candle_core::Result<&'a [f32]> { + match (s, l.contiguous_offsets()) { + (CpuStorage::F32(v), Some((start, end))) => match v.get(start..end) { + Some(v) => Ok(v), + None => bail!("layout outside its storage"), + }, + _ => bail!("fused kernels take contiguous f32 tensors"), + } +} + +/// `x · Wᵀ` over the rows of `x` (`[…, K]`) as `[rows, N]`: `Linear::forward` without the bias. +fn product(x: &Tensor, l: &Linear) -> Result { + let k = x.dim(D::Minus1)?; + Ok(x.reshape(((), k))?.matmul(&l.weight().t()?)?) +} + +fn bias(l: &Linear) -> Result<&Tensor> { + l.bias().ok_or_else(|| Error::Model("fused linear without a bias".into())) +} + +/// `gelu_erf(x · Wᵀ + b)` (`gelu`) or `relu(x · Wᵀ + b)`: `[rows, N]`. +pub fn linear_act(x: &Tensor, l: &Linear, gelu: bool) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &BiasAct { gelu })?) +} + +/// `residual + (x · Wᵀ + b)`, shaped like `residual`. +pub fn linear_add(x: &Tensor, l: &Linear, residual: &Tensor) -> Result { + Ok(product(x, l)?.apply_op3_no_bwd(bias(l)?, &residual.contiguous()?, &BiasAdd)?) +} + +/// The projection `x · Wᵀ + b` of the grid's tokens (`x`: `[b, h, w, C]`), split into heads per +/// window: `[windows, heads, tokens, head_dim]`, with the rotary encoding (`cos`, `sin`: +/// `[tokens, head_dim]`) applied when given, then multiplied by `scale`. +pub fn heads(x: &Tensor, l: &Linear, grid: Grid, rope: Option<(&[f32], &[f32])>, scale: f32) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &Heads { grid, rope, scale })?) +} + +/// Attention scores computed per task (elements): a block of query rows against all keys, +/// small enough (256 KB) to stay in a core's L2 cache between the two products and the softmax. +/// 4 MB blocks were 3× slower for the detector's 5184-token attention (8 heads of 32). +const SCORE_TILE: usize = 1 << 16; + +/// `nn::sdpa` on `[B, H, L, d]` tensors (`bias` `[B or 1, H or 1, Lq or 1, Lk]`): the same +/// operations (scores × `scale` unless it is 1, plus the bias, softmax, × v), but candle +/// multiplies batched matrices one pair after another, each spread over all threads, which is +/// slow for 9 windows × 16 heads of 576 tokens or 8 heads of 5184; here every (batch, head, +/// block of query rows) is a task of its own. +pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + let (b, h, lq, _) = q.dims4()?; + let (lk, dv) = (k.dim(2)?, v.dim(3)?); + let bias = match bias { + Some(t) => Some((t, t.dims4()?)), + None => None, + }; + let rows = (SCORE_TILE / lk.max(1)).clamp(1, lq.max(1)); + let tasks: Vec<(usize, usize, usize)> = (0..b * h).flat_map(|i| (0..lq).step_by(rows).map(move |r| (i / h, i % h, r))).collect(); + let out = tasks + .par_iter() + .map(|&(bi, hi, r)| -> Result { + let n = rows.min(lq - r); + let mut att = q.i((bi, hi))?.narrow(0, r, n)?.matmul(&k.i((bi, hi))?.t()?)?; + if scale != 1.0 { + att = (att * scale)?; + } + if let Some((t, (tb, th, tq, _))) = bias { + let t = t.i((if tb == 1 { 0 } else { bi }, if th == 1 { 0 } else { hi }))?; + att = att.broadcast_add(&if tq == 1 { t } else { t.narrow(0, r, n)? })?; + } + Ok(candle_nn::ops::softmax_last_dim(&att)?.matmul(&v.i((bi, hi))?)?) + }) + .collect::>>()?; + Ok(Tensor::cat(&out, 0)?.reshape((b, h, lq, dv))?) +} + +/// Attention over `q`, `k`, `v` from [`heads`] (`q` already scaled), merged back to the grid: +/// `[b, h, w, C]`. +pub fn attention(q: &Tensor, k: &Tensor, v: &Tensor, grid: Grid) -> Result { + Ok(sdpa(q, k, v, None, 1.0)?.apply_op1_no_bwd(&Merge { grid })?) +} + +/// `ConvTranspose2d` with a 2 × 2 kernel and stride 2 (the neck's upsampling) on `x` +/// `[1, Cin, H, W]`, then GELU when `gelu`: `[1, Cout, 2H, 2W]`. The kernel windows don't overlap, +/// so this is one product `[H·W, Cin] × [Cin, Cout·4]` and a reordering with the bias; candle +/// computes it one output channel at a time (~50 GFLOP/s here). +pub fn upsample2(x: &Tensor, ct: &ConvTranspose2d, gelu: bool) -> Result { + let (b, cin, h, w) = x.dims4()?; + let (wi, cout, kh, kw) = ct.weight().dims4()?; + let c = ct.config(); + if b != 1 || wi != cin || (kh, kw, c.stride, c.padding, c.output_padding, c.dilation) != (2, 2, 2, 0, 0, 1) { + return Err(Error::Model(format!("upsample2: {:?} with a {:?} kernel", x.dims(), ct.weight().dims()))); + } + let y = x.reshape((cin, h * w))?.t()?.matmul(&ct.weight().reshape((cin, cout * 4))?)?; + let bias = match ct.bias() { + Some(b) => b.clone(), + None => Tensor::zeros(cout, candle_core::DType::F32, x.device())?, + }; + Ok(y.apply_op2_no_bwd(&bias, &Unpatch { h, w, gelu })?) +} + +/// `relu(group_norm(x))` over `[B, C, …]` with `groups` groups and per-channel `weight`, `bias`. +/// candle's `GroupNorm` makes eight single-threaded passes over the 288² pixel decoder maps. +pub fn group_norm_relu(x: &Tensor, weight: &Tensor, bias: &Tensor, groups: usize, eps: f64) -> Result { + Ok(x.contiguous()?.apply_op3_no_bwd(weight, bias, &GroupNormRelu { groups, eps })?) +} + +/// The detector's box relative-position bias `[1, heads, 1 + queries, side²]` from its row and +/// column terms `ey`, `ex` (`[queries, side, heads]`): `ey[q, y, h] + ex[q, x, h]` at `y·side + x`, +/// after a row of zeros (the presence token). +pub fn box_bias(ey: &Tensor, ex: &Tensor) -> Result { + Ok(ey.contiguous()?.apply_op2_no_bwd(&ex.contiguous()?, &BoxBias)?) +} + +/// Rows of `x` (`[rows, N]`) with a bias `[N]`. +fn rows(x: &[f32], b: &[f32]) -> candle_core::Result { + if b.is_empty() || !x.len().is_multiple_of(b.len()) { + bail!("bias of {} for {} values", b.len(), x.len()); + } + Ok(b.len()) +} + +struct BiasAct { + gelu: bool, +} + +impl CustomOp2 for BiasAct { + fn name(&self) -> &'static str { + if self.gelu { "bias-gelu-erf" } else { "bias-relu" } + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b) = (values(s1, l1)?, values(s2, l2)?); + let n = rows(x, b)?; + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).for_each(|(o, x)| { + for ((o, x), b) in o.iter_mut().zip(x).zip(b) { + let v = x + b; + // candle's `gelu_erf` and `relu` + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v.max(0f32) }; + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +struct BiasAdd; + +impl CustomOp3 for BiasAdd { + fn name(&self) -> &'static str { + "bias-residual-add" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b, r) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let n = rows(x, b)?; + if r.len() != x.len() { + bail!("residual of {} for {} values", r.len(), x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).zip(r.par_chunks(n)).for_each(|((o, x), r)| { + for (((o, x), b), r) in o.iter_mut().zip(x).zip(b).zip(r) { + *o = r + (x + b); + } + }); + Ok((CpuStorage::F32(out), l3.shape().clone())) + } +} + +struct Heads<'a> { + grid: Grid, + rope: Option<(&'a [f32], &'a [f32])>, + scale: f32, +} + +impl CustomOp2 for Heads<'_> { + fn name(&self) -> &'static str { + "split-heads-rope" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let (x, bias) = (values(s1, l1)?, values(s2, l2)?); + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if bias.len() != c || x.len() != g.b * g.h * g.w * c { + bail!("heads: {} values with a bias of {} for {g:?}", x.len(), bias.len()); + } + if let Some((cos, sin)) = self.rope + && (cos.len() != n * d || sin.len() != n * d) + { + bail!("rotary tables of {} and {} for {n} tokens", cos.len(), sin.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n * d).enumerate().for_each(|(i, o)| { + let (win, head) = (i / g.heads, i % g.heads); + let bias = &bias[head * d..][..d]; + for (t, o) in o.chunks_exact_mut(d).enumerate() { + let x = &x[g.row(win, t) * c + head * d..][..d]; + for ((o, x), b) in o.iter_mut().zip(x).zip(bias) { + *o = x + b; + } + if let Some((cos, sin)) = self.rope { + // x·cos + rotate_pairwise(x)·sin, rotate_pairwise mapping (a, b) to (−b, a) + let (cos, sin) = (&cos[t * d..][..d], &sin[t * d..][..d]); + for ((o, cos), sin) in o.as_chunks_mut::<2>().0.iter_mut().zip(cos.as_chunks::<2>().0).zip(sin.as_chunks::<2>().0) { + let [a, b] = *o; + *o = [a * cos[0] + -b * sin[0], b * cos[1] + a * sin[1]]; + } + } + for o in o.iter_mut() { + *o *= self.scale; + } + } + }); + let shape = Shape::from((g.windows(), g.heads, n, d)); + Ok((CpuStorage::F32(out), shape)) + } +} + +struct GroupNormRelu { + groups: usize, + eps: f64, +} + +impl CustomOp3 for GroupNormRelu { + fn name(&self) -> &'static str { + "group-norm-relu" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, w, b) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let dims = l1.shape().dims(); + let (batch, c) = match dims { + [batch, c, _, ..] => (*batch, *c), + _ => bail!("group norm of {dims:?}"), + }; + if c == 0 || self.groups == 0 || !c.is_multiple_of(self.groups) || w.len() != c || b.len() != c || x.is_empty() { + bail!("group norm: {dims:?} in {} groups, {} weights", self.groups, w.len()); + } + let hw = x.len() / (batch * c); + let per = c / self.groups * hw; + // mean and σ per (image, group), as candle computes them (f32 sums in order) + let n = (1.0 / per as f64) as f32; + let stats: Vec<(f32, f32)> = x + .par_chunks(per) + .map(|g| { + let mean = g.iter().fold(0f32, |s, v| s + v) * n; + let var = g.iter().fold(0f32, |s, v| s + (v - mean) * (v - mean)) * n; + (mean, (var + self.eps as f32).sqrt()) + }) + .collect(); + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(hw).zip(x.par_chunks(hw)).enumerate().for_each(|(row, (o, x))| { + let ch = row % c; + let (mean, sd) = stats[row / c * self.groups + ch / (c / self.groups)]; + for (o, x) in o.iter_mut().zip(x) { + *o = ((x - mean) / sd * w[ch] + b[ch]).max(0f32); + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +/// `[H·W, Cout·2·2]` patches (+ bias, then GELU) to `[1, Cout, 2H, 2W]`. +struct Unpatch { + h: usize, + w: usize, + gelu: bool, +} + +impl CustomOp2 for Unpatch { + fn name(&self) -> &'static str { + "unpatch-2x2" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (y, bias) = (values(s1, l1)?, values(s2, l2)?); + let (h, w, cout) = (self.h, self.w, bias.len()); + if y.len() != h * w * cout * 4 { + bail!("unpatch: {} values for {h} × {w} × {cout} × 4", y.len()); + } + let mut out = vec![0f32; y.len()]; + // one output row (channel c, row 2·r + i) at a time + out.par_chunks_mut(2 * w).enumerate().for_each(|(row, o)| { + let (c, r, i) = (row / (2 * h), row % (2 * h) / 2, row % 2); + for (x, o) in o.as_chunks_mut::<2>().0.iter_mut().enumerate() { + let p = &y[(r * w + x) * cout * 4 + c * 4 + i * 2..][..2]; + for (o, p) in o.iter_mut().zip(p) { + let v = p + bias[c]; + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v }; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, cout, 2 * h, 2 * w)))) + } +} + +struct BoxBias; + +impl CustomOp2 for BoxBias { + fn name(&self) -> &'static str { + "box-relative-position-bias" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (ey, ex) = (values(s1, l1)?, values(s2, l2)?); + let (q, side, heads) = l1.shape().dims3()?; + if l2.shape() != l1.shape() { + bail!("box bias terms {:?} and {:?}", l1.shape(), l2.shape()); + } + let n = side * side; + let mut out = vec![0f32; heads * (q + 1) * n]; + // row 0 of each head (the presence token) stays zero + out.par_chunks_mut(n).enumerate().filter(|(i, _)| i % (q + 1) != 0).for_each(|(i, o)| { + let (h, q) = (i / (q + 1), i % (q + 1) - 1); + for (y, o) in o.chunks_exact_mut(side).enumerate() { + let ey = ey[(q * side + y) * heads + h]; + for (x, o) in o.iter_mut().enumerate() { + *o = ey + ex[(q * side + x) * heads + h]; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, heads, q + 1, n)))) + } +} + +struct Merge { + grid: Grid, +} + +impl CustomOp1 for Merge { + fn name(&self) -> &'static str { + "merge-heads" + } + + fn cpu_fwd(&self, s: &CpuStorage, l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let x = values(s, l)?; + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if x.len() != g.windows() * g.heads * n * d { + bail!("merge: {} values for {g:?}", x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(c).enumerate().for_each(|(row, o)| { + let (win, t) = g.window_of(row); + for (head, o) in o.chunks_exact_mut(d).enumerate() { + o.copy_from_slice(&x[((win * g.heads + head) * n + t) * d..][..d]); + } + }); + Ok((CpuStorage::F32(out), Shape::from((g.b, g.h, g.w, c)))) + } +} + +#[cfg(test)] +mod tests { + use candle_core::Device; + use candle_nn::{ConvTranspose2dConfig, Module}; + + use super::*; + + fn randn(shape: &[usize]) -> Tensor { + Tensor::randn(0f32, 1.0, shape, &Device::Cpu).unwrap() + } + + /// The kernels against candle's tensor operations: equal up to float rounding (on x86-64 most + /// are bit-identical; the matrix products may block differently). + fn close(name: &str, got: &Tensor, want: &Tensor) { + assert_eq!(got.dims(), want.dims(), "{name}: shape"); + let (got, want): (Vec, Vec) = (got.flatten_all().unwrap().to_vec1().unwrap(), want.flatten_all().unwrap().to_vec1().unwrap()); + let scale = want.iter().fold(1e-6f32, |m, v| m.max(v.abs())); + let err = got.iter().zip(&want).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(err <= 1e-5 * scale, "{name}: max error {err} (scale {scale})"); + } + + #[test] + fn sdpa_matches_the_tensor_ops() { + // 1000 keys: blocks of 65 query rows, the last one short + let (q, k, v) = (randn(&[2, 3, 150, 8]), randn(&[2, 3, 1000, 8]), randn(&[2, 3, 1000, 5])); + let biases = + [None, Some(randn(&[1, 1, 1, 1000])), Some(randn(&[1, 3, 150, 1000])), Some(randn(&[2, 1, 150, 1000])), Some(randn(&[2, 3, 1, 1000]))]; + for (i, bias) in biases.iter().enumerate() { + for scale in [0.35, 1.0] { + let got = sdpa(&q, &k, &v, bias.as_ref(), scale).unwrap(); + let want = crate::nn::sdpa_tensors(&q, &k, &v, bias.as_ref(), scale).unwrap(); + close(&format!("bias {i}, scale {scale}"), &got, &want); + } + } + } + + #[test] + fn fused_linears_match_the_tensor_ops() { + let x = randn(&[3, 5, 7]); + let l = Linear::new(randn(&[6, 7]), Some(randn(&[6]))); + let y = l.forward(&x).unwrap().reshape((15, 6)).unwrap(); + close("gelu", &linear_act(&x, &l, true).unwrap(), &y.gelu_erf().unwrap()); + close("relu", &linear_act(&x, &l, false).unwrap(), &y.relu().unwrap()); + let r = randn(&[3, 5, 6]); + close("residual", &linear_add(&x, &l, &r).unwrap(), &(&r + l.forward(&x).unwrap()).unwrap()); + assert!(linear_act(&x, &Linear::new(randn(&[6, 7]), None), true).is_err()); + } + + #[test] + fn box_bias_matches_the_tensor_ops() { + let (ey, ex) = (randn(&[4, 5, 3]), randn(&[4, 5, 3])); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((4, 25, 3)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap().unsqueeze(0).unwrap(); + close("box bias", &box_bias(&ey, &ex).unwrap(), &want); + } + + #[test] + fn upsampling_matches_the_transposed_convolution() { + let x = randn(&[1, 6, 3, 4]); + let cfg = ConvTranspose2dConfig { stride: 2, ..Default::default() }; + let ct = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), Some(randn(&[5])), cfg); + let want = ct.forward(&x).unwrap(); + close("upsample", &upsample2(&x, &ct, false).unwrap(), &want); + close("upsample + gelu", &upsample2(&x, &ct, true).unwrap(), &want.gelu_erf().unwrap()); + let other = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), None, ConvTranspose2dConfig::default()); + assert!(upsample2(&x, &other, false).is_err()); + } + + #[test] + fn group_norm_matches_candle() { + let x = randn(&[2, 6, 4, 5]); + let (w, b) = (randn(&[6]), randn(&[6])); + let want = candle_nn::GroupNorm::new(w.clone(), b.clone(), 6, 3, 1e-5).unwrap().forward(&x).unwrap().relu().unwrap(); + close("group norm", &group_norm_relu(&x, &w, &b, 3, 1e-5).unwrap(), &want); + assert!(group_norm_relu(&x, &w, &b, 4, 1e-5).is_err()); + } + + #[test] + fn window_indexing_round_trips() { + for win in [0, 3] { + let g = Grid { b: 2, h: 6, w: 9, win, heads: 1, head_dim: 2 }; + g.check().unwrap(); + let mut seen = vec![false; g.b * g.h * g.w]; + for w in 0..g.windows() { + for t in 0..g.tokens() { + let row = g.row(w, t); + assert_eq!(g.window_of(row), (w, t)); + seen[row] = true; + } + } + assert!(seen.iter().all(|s| *s)); + } + assert!(Grid { b: 1, h: 6, w: 9, win: 4, heads: 1, head_dim: 2 }.check().is_err()); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index 7c4eccbd33..70c623570b 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -7,12 +7,14 @@ //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. use candle_core::{D, Device, IndexOp, Module, Tensor}; -use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, LayerNorm, Linear, VarBuilder}; +use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, Linear, VarBuilder}; use crate::clip::TextEncoder; use crate::neck::{FPN, Neck}; -use crate::nn::{Attention, DecoderMlp, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec}; -use crate::{Error, Prediction, Result}; +use crate::nn::{ + Attention, DecoderMlp, GroupNormRelu, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec, +}; +use crate::{Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; @@ -89,7 +91,7 @@ pub struct Detector { prompt_attn: Attention, prompt_ln: LayerNorm, pixel_convs: Vec, - pixel_norms: Vec, + pixel_norms: Vec, instance_proj: Conv2d, mask_embedder: Vec, } @@ -153,7 +155,7 @@ impl Detector { prompt_attn: Attention::new(HIDDEN, HIDDEN, HEADS, m.pp("prompt_cross_attn"))?, prompt_ln: ln(HIDDEN, TORCH_LN_EPS, m.pp("prompt_cross_attn_norm"))?, pixel_convs: (0..3).map(|i| Ok(candle_nn::conv2d(HIDDEN, HIDDEN, 3, conv3, p.pp(format!("conv_layers.{i}")))?)).collect::>()?, - pixel_norms: (0..3).map(|i| Ok(candle_nn::group_norm(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))?)).collect::>()?, + pixel_norms: (0..3).map(|i| GroupNormRelu::new(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))).collect::>()?, instance_proj: candle_nn::conv2d(HIDDEN, HIDDEN, 1, Conv2dConfig::default(), m.pp("instance_projection"))?, mask_embedder: (0..3).map(|i| linear(HIDDEN, HIDDEN, m.pp(format!("mask_embedder.layers.{i}")))).collect::>()?, }) @@ -183,6 +185,9 @@ impl Detector { let dx = log_scale(coords.broadcast_sub(&pick(0, 2)?)?)?; let ey = self.rpb_y.forward(&dy)?; // [200, side, heads] let ex = self.rpb_x.forward(&dx)?; + if self.device.is_cpu() { + return cpu::box_bias(&ey, &ex); + } let m = ey.unsqueeze(2)?.broadcast_add(&ex.unsqueeze(1)?)?; // [200, side, side, heads] let m = m.reshape((QUERIES, side * side, HEADS))?.permute((2, 0, 1))?; // [heads, 200, side²] let m = m.pad_with_zeros(1, 1, 0)?; // the presence token attends everywhere @@ -217,7 +222,7 @@ impl Detector { let h = l.ln2.forward(&x)?; x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; let h = l.ln3.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } let memory = x; @@ -236,7 +241,7 @@ impl Detector { h = l.text_ln.forward(&(&h + l.text_attn.forward(&q, &text, &text, Some(&text_bias))?)?)?; let q = (&h + &qpos)?; h = l.vision_ln.forward(&(&h + l.vision_attn.forward(&q, &key_pos, &memory, Some(&bias))?)?)?; - h = l.mlp_ln.forward(&(&h + l.mlp.forward(&h)?)?)?; + h = l.mlp_ln.forward(&l.mlp.forward_add(&h, &h)?)?; let qh = self.out_ln.forward(&h.narrow(1, 1, QUERIES)?)?; boxes = candle_nn::ops::sigmoid(&(self.box_head.forward(&qh)? + inverse_sigmoid(&boxes)?)?)?; let p = self.presence_head.forward(&self.presence_ln.forward(&h.narrow(1, 0, 1)?)?)?; @@ -265,7 +270,7 @@ impl Detector { let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { return Err(Error::Model("pixel decoder".into())); }; - prev = norm.forward(&conv.forward(&prev)?)?.relu()?; + prev = norm.forward(&conv.forward(&prev)?)?; } let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] let (_, c, mh, mw) = inst.dims4()?; diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6d488a919a..61cac2e63b 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -29,6 +29,8 @@ #[cfg(not(target_arch = "wasm32"))] mod clip; #[cfg(not(target_arch = "wasm32"))] +mod cpu; +#[cfg(not(target_arch = "wasm32"))] mod detector; #[cfg(not(target_arch = "wasm32"))] pub mod fetch; diff --git a/crates/segment/src/neck.rs b/crates/segment/src/neck.rs index c4f716dd6f..46cbebf1e5 100644 --- a/crates/segment/src/neck.rs +++ b/crates/segment/src/neck.rs @@ -8,8 +8,8 @@ use candle_core::{Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, ConvTranspose2d, ConvTranspose2dConfig, VarBuilder}; -use crate::Result; use crate::vit::HIDDEN; +use crate::{Result, cpu}; pub const FPN: usize = 256; @@ -64,8 +64,11 @@ impl Neck { pub fn forward(&self, x: &Tensor, n: usize) -> Result> { let mut out = Vec::with_capacity(n); for l in self.levels.iter().take(n) { + let cpu = x.device().is_cpu(); let y = match &l.scale { + Scale::Up4(a, b) if cpu => cpu::upsample2(&cpu::upsample2(x, a, true)?, b, false)?, Scale::Up4(a, b) => b.forward(&a.forward(x)?.gelu_erf()?)?, + Scale::Up2(a) if cpu => cpu::upsample2(x, a, false)?, Scale::Up2(a) => a.forward(x)?, Scale::Same => x.clone(), Scale::Down2 => x.max_pool2d(2)?, diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 540196e5d8..0749d9c72a 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -7,7 +7,7 @@ use candle_core::{D, DType, Device, Module, Tensor}; use candle_nn::{LayerNorm, Linear, VarBuilder}; -use crate::Result; +use crate::{Result, cpu}; /// `nn.LayerNorm(d)` (PyTorch's default eps). pub const TORCH_LN_EPS: f64 = 1e-5; @@ -25,8 +25,17 @@ pub fn linear(i: usize, o: usize, vb: VarBuilder) -> Result { const SCORE_BLOCK: usize = 64 << 20; /// Scaled dot-product attention on `[B, H, L, d]` tensors, with an optional additive bias -/// broadcastable to `[B, H, Lq, Lk]`. Heads are processed in groups to bound memory. +/// broadcastable to `[B, H, Lq, Lk]` (on the CPU: [`cpu::sdpa`]). pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + if q.device().is_cpu() && bias.is_none_or(|t| t.rank() == 4) { + return cpu::sdpa(q, k, v, bias, scale); + } + sdpa_tensors(q, k, v, bias, scale) +} + +/// [`sdpa`] with candle's tensor operations (any device). Heads are processed in groups to bound +/// memory. +pub fn sdpa_tensors(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { let (b, h, lq, _) = q.dims4()?; let lk = k.dim(2)?; let per_head = b.saturating_mul(lq).saturating_mul(lk).max(1); @@ -97,6 +106,11 @@ impl Attention { Ok(self.o.forward(x)?) } + /// The q, k, v and output projections. + pub fn projections(&self) -> [&Linear; 4] { + [&self.q, &self.k, &self.v, &self.o] + } + /// `q`, `k`, `v`: `[B, L, hidden]`; `bias` broadcastable to `[B, heads, Lq, Lk]`. pub fn forward(&self, q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>) -> Result { let (b, lq, _) = q.dims3()?; @@ -132,6 +146,14 @@ impl Mlp { let x = if self.gelu { x.gelu_erf()? } else { x.relu()? }; Ok(self.fc2.forward(&x)?) } + + /// `residual + forward(x)`; on the CPU with the bias adds, activation and residual add fused. + pub fn forward_add(&self, x: &Tensor, residual: &Tensor) -> Result { + if !x.device().is_cpu() { + return Ok((residual + self.forward(x)?)?); + } + cpu::linear_add(&cpu::linear_act(x, &self.fc1, self.gelu)?, &self.fc2, residual) + } } /// `Sam3DecoderMLP`: `layer1 … layerN` with ReLU between (2 or 3 layers). @@ -188,6 +210,30 @@ impl FeedForward { } } +/// `nn.GroupNorm` followed by ReLU (the pixel decoder's), fused on the CPU. +pub struct GroupNormRelu { + norm: candle_nn::GroupNorm, + weight: Tensor, + bias: Tensor, + groups: usize, + eps: f64, +} + +impl GroupNormRelu { + pub fn new(groups: usize, channels: usize, eps: f64, vb: VarBuilder) -> Result { + let (weight, bias) = (vb.get(channels, "weight")?, vb.get(channels, "bias")?); + let norm = candle_nn::GroupNorm::new(weight.clone(), bias.clone(), channels, groups, eps)?; + Ok(Self { norm, weight, bias, groups, eps }) + } + + pub fn forward(&self, x: &Tensor) -> Result { + if x.device().is_cpu() { + return cpu::group_norm_relu(x, &self.weight, &self.bias, self.groups, self.eps); + } + Ok(self.norm.forward(x)?.relu()?) + } +} + /// Layer norm over the channel axis of an NCHW tensor (`Sam3TrackerLayerNorm`, channels_first). pub fn ln_channels(x: &Tensor, norm: &LayerNorm) -> Result { let x = x.permute((0, 2, 3, 1))?; diff --git a/crates/segment/src/vit.rs b/crates/segment/src/vit.rs index 16b09a729b..1f356ad547 100644 --- a/crates/segment/src/vit.rs +++ b/crates/segment/src/vit.rs @@ -8,8 +8,8 @@ use candle_core::{D, Device, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, VarBuilder}; -use crate::nn::{Attention, Mlp, ln, sdpa}; -use crate::{Error, Result}; +use crate::nn::{Attention, Mlp, ln, sdpa_tensors}; +use crate::{Error, Result, cpu}; pub const IMAGE: usize = 1008; pub const PATCH: usize = 14; @@ -19,14 +19,26 @@ pub const HIDDEN: usize = 1024; const HEADS: usize = 16; const HEAD_DIM: usize = HIDDEN / HEADS; const LAYERS: usize = 32; +const INTERMEDIATE: usize = 4736; const WINDOW: usize = 24; const GLOBAL: [usize; 4] = [7, 15, 23, 31]; const PRETRAIN_GRID: usize = 336 / PATCH; const EPS: f64 = 1e-6; +/// The attention score scale, `HEAD_DIM^-0.5`. A power of two, so scaling the queries instead +/// of the scores (on the CPU) gives the same scores, bit for bit. +const SCALE: f32 = 0.125; +const _: () = assert!(HEAD_DIM == 64); + +/// Cosine and sine tables `[N, head_dim]`, also as plain values for the CPU kernels. +struct Rope { + cos: Tensor, + sin: Tensor, + values: (Vec, Vec), +} /// Cosine and sine tables `[N, head_dim]` for a `side × side` grid whose coordinates are scaled /// by `scale` (`Sam3ViTRotaryEmbedding`: x frequencies then y, each duplicated pairwise). -fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tensor)> { +fn rope_tables(side: usize, scale: f64, device: &Device) -> Result { let spatial = HEAD_DIM / 2; let inv: Vec = (0..spatial).step_by(2).map(|i| 1.0 / 10000f64.powf(i as f64 / spatial as f64)).collect(); let n = side * side; @@ -44,7 +56,7 @@ fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tens } } } - Ok((Tensor::from_vec(cos, (n, HEAD_DIM), device)?, Tensor::from_vec(sin, (n, HEAD_DIM), device)?)) + Ok(Rope { cos: Tensor::from_slice(&cos, (n, HEAD_DIM), device)?, sin: Tensor::from_slice(&sin, (n, HEAD_DIM), device)?, values: (cos, sin) }) } /// `x·cos + rotate_pairwise(x)·sin`, where rotate_pairwise maps (a, b) pairs to (−b, a). @@ -71,7 +83,12 @@ struct Layer { impl Layer { /// `x`: `[B, H, W, C]`. - fn forward(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn forward(&self, x: &Tensor, rope: &Rope) -> Result { + if x.device().is_cpu() { self.forward_cpu(x, rope) } else { self.forward_tensors(x, rope) } + } + + /// With candle's tensor operations (any device). + fn forward_tensors(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let y = self.ln1.forward(x)?; let y = match (h.checked_div(self.window), w.checked_div(self.window)) { @@ -90,21 +107,37 @@ impl Layer { Ok((x + y)?) } + /// [`Self::forward`] on the CPU: the same arithmetic, with the window partitioning, head + /// split, rotary encoding, bias adds, GELU and residual adds in fused parallel kernels. + fn forward_cpu(&self, x: &Tensor, rope: &Rope) -> Result { + let (b, h, w, _) = x.dims4()?; + let grid = cpu::Grid { b, h, w, win: self.window, heads: HEADS, head_dim: HEAD_DIM }; + let y = self.ln1.forward(x)?; + let [q, k, v, o] = self.attn.projections(); + let table = Some((rope.values.0.as_slice(), rope.values.1.as_slice())); + let q = cpu::heads(&y, q, grid, table, SCALE)?; + let k = cpu::heads(&y, k, grid, table, 1.0)?; + let v = cpu::heads(&y, v, grid, None, 1.0)?; + let att = cpu::attention(&q, &k, &v, grid)?; + let x = cpu::linear_add(&att, o, x)?; + self.mlp.forward_add(&self.ln2.forward(&x)?, &x) + } + /// RoPE self-attention over `[B, H, W, C]`. - fn attend(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attend(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let seq = x.reshape((b, h * w, c))?; Ok(self.attn_rope(&seq, rope)?.reshape((b, h, w, c))?) } - fn attn_rope(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attn_rope(&self, x: &Tensor, rope: &Rope) -> Result { let (b, n, _) = x.dims3()?; let split = |t: Tensor| -> Result { Ok(t.reshape((b, n, HEADS, HEAD_DIM))?.transpose(1, 2)?.contiguous()?) }; let (q, k, v) = self.attn.qkv(x)?; - let q = apply_rope(&split(q)?, &rope.0, &rope.1)?; - let k = apply_rope(&split(k)?, &rope.0, &rope.1)?; + let q = apply_rope(&split(q)?, &rope.cos, &rope.sin)?; + let k = apply_rope(&split(k)?, &rope.cos, &rope.sin)?; let v = split(v)?; - let o = sdpa(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; + let o = sdpa_tensors(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; let o = o.transpose(1, 2)?.reshape((b, n, HIDDEN))?; self.attn.out(&o) } @@ -115,8 +148,8 @@ pub struct Vit { pos: Tensor, ln_pre: LayerNorm, layers: Vec, - rope_window: (Tensor, Tensor), - rope_global: (Tensor, Tensor), + rope_window: Rope, + rope_global: Rope, } impl Vit { @@ -141,7 +174,7 @@ impl Vit { ln1: ln(HIDDEN, EPS, l.pp("layer_norm1"))?, attn: Attention::new(HIDDEN, HIDDEN, HEADS, l.pp("attention"))?, ln2: ln(HIDDEN, EPS, l.pp("layer_norm2"))?, - mlp: Mlp::new(HIDDEN, 4736, true, l.pp("mlp"))?, + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, l.pp("mlp"))?, window: if GLOBAL.contains(&i) { 0 } else { WINDOW }, }); } @@ -168,3 +201,57 @@ impl Vit { Ok(x.permute((0, 3, 1, 2))?.contiguous()?) } } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use candle_core::DType; + + use super::*; + + /// A layer with random weights. + fn layer(window: usize) -> Layer { + let d = Device::Cpu; + let mut t = HashMap::new(); + let mut add = |name: String, shape: &[usize], mean: f32| { + t.insert(name, Tensor::randn(mean, 0.05f32, shape, &d).unwrap()); + }; + for n in ["layer_norm1", "layer_norm2"] { + add(format!("{n}.weight"), &[HIDDEN], 1.0); + add(format!("{n}.bias"), &[HIDDEN], 0.0); + } + for n in ["q_proj", "k_proj", "v_proj", "o_proj"] { + add(format!("attention.{n}.weight"), &[HIDDEN, HIDDEN], 0.0); + add(format!("attention.{n}.bias"), &[HIDDEN], 0.0); + } + add("mlp.fc1.weight".into(), &[INTERMEDIATE, HIDDEN], 0.0); + add("mlp.fc1.bias".into(), &[INTERMEDIATE], 0.0); + add("mlp.fc2.weight".into(), &[HIDDEN, INTERMEDIATE], 0.0); + add("mlp.fc2.bias".into(), &[HIDDEN], 0.0); + let vb = VarBuilder::from_tensors(t, DType::F32, &d); + Layer { + ln1: ln(HIDDEN, EPS, vb.pp("layer_norm1")).unwrap(), + attn: Attention::new(HIDDEN, HIDDEN, HEADS, vb.pp("attention")).unwrap(), + ln2: ln(HIDDEN, EPS, vb.pp("layer_norm2")).unwrap(), + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, vb.pp("mlp")).unwrap(), + window, + } + } + + #[test] + fn cpu_kernels_match_the_tensor_ops() { + // two images each: 12 × 24 tokens in 6 × 6 windows, and 12 × 12 with global attention + for (window, (h, w), side, scale) in [(6, (12, 24), 6, 1.0), (0, (12, 12), 12, 0.5)] { + let x = Tensor::randn(0f32, 1.0, (2, h, w, HIDDEN), &Device::Cpu).unwrap(); + let (l, rope) = (layer(window), rope_tables(side, scale, &Device::Cpu).unwrap()); + let want = l.forward_tensors(&x, &rope).unwrap().flatten_all().unwrap().to_vec1::().unwrap(); + let got = l.forward_cpu(&x, &rope).unwrap(); + assert_eq!(got.dims(), x.dims()); + let got = got.flatten_all().unwrap().to_vec1::().unwrap(); + let err = want.iter().zip(&got).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + // the same arithmetic (one attention block per window here): equal on x86-64 + assert!(err <= 1e-5, "window {window}: max error {err}"); + } + } +} diff --git a/docs/ai-masks.md b/docs/ai-masks.md index b02912abc1..37cd9c1639 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -29,13 +29,13 @@ In the Masking panel (M): so small objects get 5–10× finer edges than one pass over the whole photo gives. The first Object or Describe on a photo analyzes it (the image encoder runs once per photo and -look: ~3 s on an Apple M4 Pro, plus a one-time ~6 s for compiling GPU kernels and loading the -model after launch). That starts in the background as soon as you pick Object; after it, each -click takes ~35 ms and each description ~0.6 s. Everything the model does runs on its own worker -thread: the window stays responsive, a click shows its dot at once and the selection follows -when it's computed ("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is -unloaded after 10 minutes without use (it takes several GB of memory) and loaded again when -needed. +look: ~3 s on an Apple M4 Pro, ~11 s on the CPU of a 12-core Ryzen 9 3900X, plus a one-time ~6 s +for compiling GPU kernels and loading the model after launch). That starts in the background as +soon as you pick Object; after it, each click takes ~35 ms and each description ~0.6 s (~0.15 s +and ~2 s on that CPU). Everything the model does runs on its own worker thread: the window stays +responsive, a click shows its dot at once and the selection follows when it's computed +("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is unloaded after 10 +minutes without use (it takes several GB of memory) and loaded again when needed. The result is stored with the mask: the model's 288 × 288 mask logits over the uncropped photo (quantized, compressed, ~10–30 KB). Renders and exports sample them at any resolution and never @@ -230,6 +230,18 @@ wait and return the result (when built with the `sam` feature; the default CLI h - Accuracy: `crates/segment/tests/reference.rs` compares every stage against the Python reference (`tools/sam3_reference.py`); on Metal the backbone matches to 7e-5 relative error and masks to ~5e-5. f16 was tried and rejected (overflow, ~7 % faster). +- Speed on the CPU: candle runs elementwise operations and layout copies on one thread, batched + matrix products one pair after another and transposed convolutions one output channel at a + time. `cpu.rs` fuses the bias adds, activations, rotary encoding, window partitioning, head + split/merge, the detector's box bias and the pixel decoder's GroupNorm into parallel kernels + (the same operations in the same order: bit-identical), runs attention as one task per batch, + head and block of query rows (256 KB of scores, so they stay in the core's cache), and the + necks' 2 × 2 transposed convolutions as one matrix product each. Those two change how gemm + blocks its sums, so results move by float rounding only, as they do between two CPUs (gemm + picks its blocking from the cache sizes): against the tensor operations the backbone differs + by 1e-5 relative and the masks by at most 7e-4, and fewer than 4e-7 of the mask pixels change + side. On a 12-core Ryzen 9 3900X: encode ~37 → ~11 s, a description ~6 → ~2 s, getting ready + for clicks ~2.3 → ~0.8 s. - The engine feature `sam` (on in the desktop app, off for web and CLI) gates the model; without it the commands report that the build has no AI masks. From edfcc2f1653b28dc4269c63d9a380674125e7229 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:10:53 +0300 Subject: [PATCH 004/625] Workspace: bump rust-version to 1.95 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index ac8cbeca13..cf83258614 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ members = ["crates/*", "apps/*", "xtask"] version = "0.8.0" edition = "2024" license = "MIT OR Apache-2.0" -rust-version = "1.90" +rust-version = "1.95" repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] From 887752ff94410469da95e9b803b5f15416e0e0d9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:51:55 +0200 Subject: [PATCH 005/625] LR-1619: one shutter formatter for display, exact time kept for export Show near-exact 1/n second as `1/n` and round everything else to four significant digits through lightcraft_meta::format_exposure_time, used by the catalog `shutter` text, the Info panel (which shows it) and All Metadata. The catalog keeps the exact duration in an optional `exposure_time` beside it (older catalogs read unchanged), and export, auto-stacking, smart-collection shutter rules and Match Total Exposures read it through Meta::shutter_seconds while the text still matches it. --- crates/catalog/src/model.rs | 42 +++++++++++++++ crates/catalog/src/rules.rs | 2 +- crates/catalog/src/stacks.rs | 2 +- crates/engine/src/cmd/convert.rs | 1 + crates/engine/src/cmd/develop.rs | 5 +- crates/engine/src/export.rs | 2 +- crates/engine/src/files.rs | 27 ++++++++-- crates/meta/src/lib.rs | 91 +++++++++++++++++++++++--------- crates/meta/src/tags.rs | 9 ++-- docs/parity-checklist.md | 6 +-- 10 files changed, 145 insertions(+), 42 deletions(-) diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 6ac3544ee7..2c6f5cab08 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -171,7 +171,13 @@ pub struct Meta { pub lens: String, pub focal_mm: Option, pub aperture: Option, + /// Shutter speed for display, from [`lightcraft_meta::format_exposure_time`] (`1/3`, `0.3571`, `2.5`). pub shutter: String, + /// The file's exact exposure time in seconds, kept beside the rounded `shutter` text so export + /// writes the original duration; read through [`Meta::shutter_seconds`]. Left out of the catalog + /// JSON when unknown, so older catalogs read unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exposure_time: Option, pub iso: Option, /// Place (sublocation, e.g. a landmark). pub location: String, @@ -206,6 +212,16 @@ pub struct Meta { pub focus: Option, } +impl Meta { + /// Shutter speed in seconds: the exact [`Meta::exposure_time`] while `shutter` still shows it, + /// otherwise whatever `shutter` says (set by hand, or a catalog from before the exact time was kept). + pub fn shutter_seconds(&self) -> Option { + self.exposure_time + .filter(|t| lightcraft_meta::format_exposure_time(*t).is_some_and(|text| text == self.shutter.trim())) + .or_else(|| parse_shutter_seconds(&self.shutter)) + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Version { pub name: String, @@ -678,3 +694,29 @@ mod edited_tests { } } } + +#[cfg(test)] +mod shutter_tests { + use super::*; + + #[test] + fn shutter_seconds_prefers_the_exact_time_while_the_text_still_shows_it() { + let mut m = Meta { shutter: "0.3571".into(), exposure_time: Some(1.0 / 2.8), ..Default::default() }; + assert_eq!(m.shutter_seconds(), Some(1.0 / 2.8)); + m.shutter = "1/3".into(); + m.exposure_time = Some(1.0 / 3.0); + assert_eq!(m.shutter_seconds(), Some(1.0 / 3.0)); + // the text no longer matches the stored time (edited elsewhere): the text wins + m.shutter = "1/250".into(); + assert_eq!(m.shutter_seconds(), Some(1.0 / 250.0)); + // an older catalog without the exact time + m.exposure_time = None; + m.shutter = "2.5".into(); + assert_eq!(m.shutter_seconds(), Some(2.5)); + // the exact time stays out of the JSON when unknown, and round-trips when known + assert!(!serde_json::to_string(&m).unwrap().contains("exposure_time")); + m.exposure_time = Some(2.5); + let back: Meta = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap(); + assert_eq!(back.exposure_time, Some(2.5)); + } +} diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index a87c9effc0..42112c65f4 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -887,7 +887,7 @@ impl Rule { "captureDate" => date_op(op, p.captured.as_deref(), value), "importDate" => date_op(op, Some(&p.imported), value), "editDate" => date_op(op, p.edited.as_deref(), value), - "shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)), + "shutterSpeed" => num_op(op, m.shutter_seconds(), &shutter_value(value)), "iso" => num_op(op, m.iso.map(|v| v as f64), value), "aperture" => num_op(op, m.aperture.map(|v| v as f64), value), "focalLength" => num_op(op, m.focal_mm.map(|v| v as f64), value), diff --git a/crates/catalog/src/stacks.rs b/crates/catalog/src/stacks.rs index eb7e89ef4e..a3e9282370 100644 --- a/crates/catalog/src/stacks.rs +++ b/crates/catalog/src/stacks.rs @@ -260,7 +260,7 @@ impl Catalog { .filter(|p| !p.deleted && !merged(p)) .filter_map(|p| { let t = iso_seconds(p.captured.as_deref()?)?; - let s = crate::model::parse_shutter_seconds(&p.meta.shutter)?; + let s = p.meta.shutter_seconds()?; let n = p.meta.aperture.filter(|n| n.is_finite() && *n > 0.0).unwrap_or(1.0) as f64; let iso = p.meta.iso.filter(|i| *i > 0).unwrap_or(100) as f64; Some((t, p.file_name.as_str(), p.id, s, (s * iso / (n * n)).log2())) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index eae955cce4..12c4c4ab4c 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -235,6 +235,7 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P } if m.shutter.is_empty() { m.shutter = src.shutter.clone(); + m.exposure_time = src.exposure_time; } m.focal_mm = m.focal_mm.or(src.focal_mm); m.aperture = m.aperture.or(src.aperture); diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index e3d59c5672..54adb7f3f7 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -934,10 +934,7 @@ pub fn specs() -> Vec { // log2 of the light the photo gathered (shutter s × ISO / f-number²) let gathered = |s: &Session, id: PhotoId| -> Option { let m = &s.catalog.photo(id)?.meta; - let t = match m.shutter.split_once('/') { - Some((a, b)) => a.trim().parse::().ok()? / b.trim().parse::().ok()?, - None => m.shutter.trim().trim_end_matches('s').trim().parse::().ok()?, - }; + let t = m.shutter_seconds()?; let (n, iso) = (m.aperture? as f64, m.iso? as f64); (t > 0.0 && n > 0.0 && iso > 0.0).then(|| (t * iso / (n * n)).log2()) }; diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index e9d1cbc585..4d5a07cc45 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1532,7 +1532,7 @@ pub fn export_metadata(photo: &lightcraft_catalog::Photo, catalog: &lightcraft_c out.lens_model = text(&m.lens); out.focal_length = m.focal_mm.map(f64::from); out.f_number = m.aperture.map(f64::from); - out.exposure_time = lightcraft_catalog::parse_shutter_seconds(&m.shutter); + out.exposure_time = m.shutter_seconds(); out.iso = m.iso; } Some(out) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 4111c02267..35a0c52ba3 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -14,7 +14,8 @@ use lightcraft_raster::resample::{Filter, fit}; use crate::media::{DenoiseSpec, FileLoader, FileProbe, PairLoader, PreviewLoader, ProbeInfo}; fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { - let shutter = m.exposure_display().map(|s| s.trim_end_matches('″').to_string()).unwrap_or_default(); + let exposure_time = m.exposure_time.filter(|t| t.is_finite() && *t > 0.0); + let shutter = exposure_time.and_then(lightcraft_meta::format_exposure_time).unwrap_or_default(); let camera = [m.make.clone().unwrap_or_default(), m.model.clone().unwrap_or_default()].join(" ").trim().to_string(); let meta = Meta { camera, @@ -23,6 +24,7 @@ fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { focal_mm: m.focal_length.map(|f| f as f32), aperture: m.f_number.map(|f| f as f32), shutter, + exposure_time, iso: m.iso, location: m.sublocation.clone().unwrap_or_default(), city: m.city.clone().unwrap_or_default(), @@ -1112,11 +1114,28 @@ pub(crate) mod tests { #[test] fn imported_shutter_times_survive_catalog_and_export_metadata() { use lightcraft_catalog::{Catalog, Photo, PhotoId}; - for t in [0.3, 0.4, 0.6, 0.8, 1.3, 1.6, 2.5, 3.2, 0.625, 1.0 / 2.8, 0.003, 1.0 / 250.0] { + for (t, shown) in [ + (0.3, "0.3"), + (0.4, "0.4"), + (0.6, "0.6"), + (0.8, "0.8"), + (1.3, "1.3"), + (1.6, "1.6"), + (2.5, "2.5"), + (3.2, "3.2"), + (30.0, "30"), + (0.625, "0.625"), + (1.0 / 2.8, "0.3571"), + (1.0 / 3.0, "1/3"), + (0.003, "0.003"), + (1.0 / 250.0, "1/250"), + (1.0 / 8000.0, "1/8000"), + ] { let original = lightcraft_meta::Metadata { exposure_time: Some(t), ..Default::default() }; let (meta, _) = meta_of(&original); - assert_eq!(lightcraft_catalog::parse_shutter_seconds(&meta.shutter), Some(t)); - // Exercise the persisted string, not a value kept alongside it in memory. + // the catalog shows a short shutter speed, never the raw f64 (`0.35714285714285715`) + assert_eq!(meta.shutter, shown, "{t}"); + // Exercise the persisted catalog JSON, not a value kept alongside it in memory. let meta: Meta = serde_json::from_str(&serde_json::to_string(&meta).unwrap()).unwrap(); let mut photo = Photo::new(PhotoId(1), lightcraft_catalog::Source::Demo { scene: 0 }, "capture.jpg", "JPEG", 2, 2, ""); photo.meta = meta; diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 64307d9b06..1edfe9f312 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -157,6 +157,29 @@ macro_rules! overlay { ($self:ident, $o:ident, $($f:ident),*) => { $( if $o.$f.is_some() { $self.$f = $o.$f.clone(); } )* }; } +/// How far (relative) a duration may be from an exact `1/n` second and still be shown as `1/n`: +/// absorbs decimal EXIF rationals such as `3333/10000` for 1/3 s without turning 0.3 s or +/// 1/2.8 s into a reciprocal they aren't. +pub const RECIPROCAL_TOLERANCE: f64 = 1e-3; + +/// The one shutter-speed formatter for display (catalog `shutter`, Info panel, All Metadata): +/// a near-exact `1/n` second as `1/n` (`1/3`, `1/250`), anything else rounded to four +/// significant digits with trailing zeros dropped (`0.3`, `0.3571`, `2.5`, `30`). Display only: +/// export writes the exact duration. `None` for a time that isn't positive and finite. +pub fn format_exposure_time(t: f64) -> Option { + if !t.is_finite() || t <= 0.0 { + return None; + } + let n = (1.0 / t).round(); + if n >= 2.0 && n.is_finite() && (1.0 / (n * t) - 1.0).abs() <= RECIPROCAL_TOLERANCE { + return Some(format!("1/{n}")); + } + // four significant digits; whole seconds never lose digits + let decimals = (3 - t.log10().floor() as i32).max(0) as usize; + let text = format!("{t:.decimals$}"); + Some(if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.').to_string() } else { text }) +} + impl Metadata { /// Fill every empty field of `self` from `other`. pub fn fill_missing(&mut self, other: &Metadata) { @@ -231,22 +254,10 @@ impl Metadata { } } - /// Exposure time without rounding away capture metadata: `1/250`, `0.625`, `1.3″`. + /// Exposure time formatted like cameras show it: `1/250`, `0.3571`, `2.5″` (see [`format_exposure_time`]). pub fn exposure_display(&self) -> Option { let t = self.exposure_time?; - if !t.is_finite() || t <= 0.0 { - return None; - } - let denominator = (1.0 / t).round(); - // Only use a reciprocal when parsing it recovers the original duration. - // Decimal thirds of a stop and unusual camera rationals must not be quantized. - Some(if t < 0.3 && denominator.is_finite() && 1.0 / denominator == t { - format!("1/{denominator}") - } else if t < 1.0 { - t.to_string() - } else { - format!("{t}″") - }) + format_exposure_time(t).map(|text| if t >= 1.0 { format!("{text}″") } else { text }) } /// Human name of the metering mode. @@ -342,18 +353,46 @@ mod tests { } #[test] - fn exposure_display_preserves_duration() { - for t in [0.3, 0.4, 0.6, 0.8, 1.3, 1.6, 2.5, 3.2, 0.625, 1.0 / 2.8, 0.003, 1.0 / 250.0] { - let text = Metadata { exposure_time: Some(t), ..Default::default() }.exposure_display().unwrap(); - let number = text.trim_end_matches('″'); - let actual = match number.split_once('/') { - Some((n, d)) => n.parse::().unwrap() / d.parse::().unwrap(), - None => number.parse::().unwrap(), - }; - assert_eq!(actual, t, "{text}"); + fn exposure_time_formats_reciprocals_and_significant_digits() { + for (t, want) in [ + (1.0 / 3.0, "1/3"), + (1.0 / 250.0, "1/250"), + (1.0 / 8000.0, "1/8000"), + (0.5, "1/2"), + (0.3, "0.3"), + (0.4, "0.4"), + (1.0 / 2.8, "0.3571"), + (0.625, "0.625"), + (0.003, "0.003"), + (1.0, "1"), + (1.3, "1.3"), + (2.5, "2.5"), + (30.0, "30"), + (9.99996, "10"), + (1800.0, "1800"), + ] { + assert_eq!(format_exposure_time(t).as_deref(), Some(want), "{t}"); } for t in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - assert!(Metadata { exposure_time: Some(t), ..Default::default() }.exposure_display().is_none()); + assert_eq!(format_exposure_time(t), None, "{t}"); + } + } + + #[test] + fn exposure_time_reciprocal_tolerance() { + // a camera's decimal rational for 1/3 s, and times just inside the tolerance either side + assert_eq!(format_exposure_time(3333.0 / 10000.0).as_deref(), Some("1/3")); + // a microsecond-level rational error still reads as 1/8000; above ~1/1000 s every time is + // within the tolerance of some 1/n, which is how cameras show those speeds anyway + assert_eq!(format_exposure_time(1.0 / 8000.0 * (1.0 + 1e-5)).as_deref(), Some("1/8000")); + for n in [3.0, 10.0, 250.0] { + let inside = 0.9 * RECIPROCAL_TOLERANCE; + let outside = 1.1 * RECIPROCAL_TOLERANCE; + let want = format!("1/{n}"); + assert_eq!(format_exposure_time(1.0 / n * (1.0 + inside)).as_deref(), Some(want.as_str()), "{n} +inside"); + assert_eq!(format_exposure_time(1.0 / n * (1.0 - inside)).as_deref(), Some(want.as_str()), "{n} -inside"); + assert_ne!(format_exposure_time(1.0 / n * (1.0 + outside)).as_deref(), Some(want.as_str()), "{n} +outside"); + assert_ne!(format_exposure_time(1.0 / n * (1.0 - outside)).as_deref(), Some(want.as_str()), "{n} -outside"); } } @@ -362,7 +401,9 @@ mod tests { let mut m = Metadata { exposure_time: Some(1.0 / 250.0), ..Default::default() }; assert_eq!(m.exposure_display().as_deref(), Some("1/250")); m.exposure_time = Some(0.5); - assert_eq!(m.exposure_display().as_deref(), Some("0.5")); + assert_eq!(m.exposure_display().as_deref(), Some("1/2")); + m.exposure_time = Some(0.3); + assert_eq!(m.exposure_display().as_deref(), Some("0.3")); m.exposure_time = Some(2.0); assert_eq!(m.exposure_display().as_deref(), Some("2″")); m.exposure_time = Some(0.0); diff --git a/crates/meta/src/tags.rs b/crates/meta/src/tags.rs index 8fb339edf6..faedf04fe5 100644 --- a/crates/meta/src/tags.rs +++ b/crates/meta/src/tags.rs @@ -238,9 +238,8 @@ fn value_text(group: &str, tag: u16, v: &Value) -> String { // exposure time as a fraction of a second let (n, d) = a[0]; let s = n as f64 / d as f64; - let display = crate::Metadata { exposure_time: Some(s), ..Default::default() }.exposure_display(); - match display { - Some(text) => format!("{} s", text.trim_end_matches('″')), + match crate::format_exposure_time(s) { + Some(text) => format!("{text} s"), None => format!("{} s", rational(n as f64, d as f64)), } } @@ -384,7 +383,11 @@ mod tests { (25, 10, "2.5 s"), (32, 10, "3.2 s"), (5, 8, "0.625 s"), + (1, 3, "1/3 s"), + (10, 28, "0.3571 s"), (1, 250, "1/250 s"), + (1, 8000, "1/8000 s"), + (30, 1, "30 s"), ] { assert_eq!(value_text("EXIF", 0x829a, &Value::Rational(vec![(n, d)])), expected); } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 10421430dc..4dfd3007b7 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -171,7 +171,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-META-LOCATION | Location editing | P2 | 🟡 | `cmd:photo.setMeta` (`location`, `city`, `state`, `country`, `gps`), `cmd:metadata.reverseGeocode` | place fields and GPS (decimal or degrees / minutes / seconds) edited in Info, read/written as IPTC Core / Photoshop / EXIF XMP; Show on Map opens OpenStreetMap; Fill Location fills empty City / State / Country from GPS offline (GeoNames, downloaded on request: `cmd:metadata.downloadPlaceNames`); no embedded map | | LR-META-COPYPASTE | Copy / paste metadata | P2 | ✅ | `cmd:photo.copyMetadata`, `cmd:photo.pasteMetadata` | title, caption, alt text, extended description, copyright (notice, status, usage terms, info URL), creator, place fields, keywords; `fields` picks a subset | | LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; saving merges into an existing sidecar (`crates/meta/src/xmp_merge.rs`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte, an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`.xmp` for all but the raw); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); radial masks (`Mask/CircularGradient`) keep Lightroom's inside / outside: `crs:Flipped="true"` is the effect-inside flag of current masks and of the legacy Radial Filter, `crs:MaskInverted` the inversion, checked against Lightroom Classic's renders (issue #1815); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934) | -| LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; metadata presets. Exposure durations retain their precision in imported catalog metadata and All Metadata (#1619). | +| LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; metadata presets. Shutter speeds in the catalog, Info and All Metadata use one formatter (`lightcraft_meta::format_exposure_time`): a near-exact 1/n s as `1/n`, otherwise four significant digits (#1619). | ## F. Edit panel — global adjustments (EDIT) @@ -398,7 +398,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EXP-COLORSPACE | Output colour space | P0 | ✅ | `cmd:app.export` (`colorSpace`), `crates/pipeline/src/output.rs`, `crates/engine/src/export.rs` | sRGB, Display P3, Adobe RGB (1998) compatible, ProPhoto RGB, Rec. 2020: rendered from the working space with gamut mapping into the target gamut (CPU + GPU), own ICC profile embedded; AVIF stays sRGB (muxer has no ICC); lossy JPEG XL declares sRGB / P3 / Rec. 2020 (Adobe RGB and ProPhoto written as Rec. 2020), lossless JPEG XL embeds the profile | | LR-EXP-HDR | HDR output | P2 | 🟡 | `cmd:app.export`, `crates/ui-egui/src/panels/dialogs.rs` | HDR output checkbox in the export dialog: gain map JPEG, PQ or HLG AVIF, PQ PNG, PQ JPEG XL, float TIFF; no HDR presets yet | | LR-EXP-SHARPEN | Output sharpening | P1 | ✅ | `cmd:app.export` (`sharpen`, `sharpenAmount`) | | -| LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | Exposure durations survive catalog serialization and export without import-time reciprocal or whole-second rounding (#1619); previously rounded catalog values require reloading metadata from the original. | +| LR-EXP-METADATA | Metadata policy | P1 | ✅ | `cmd:app.export` (`metadata`, `removeLocation`) | Export writes the exact exposure time kept in the catalog beside the rounded shutter text (#1619); previously rounded catalog values require reloading metadata from the original. | | LR-EXP-WATERMARK | Watermark | P1 | ✅ | `cmd:app.export` (`watermark`: text, or `{text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}`), `crates/engine/src/export.rs` (`Watermark`, `WATERMARK_PARAMS`) | text (`size` = height as a fraction of the short edge, 0.005..0.5, default 0.035; `color` sRGB `[r,g,b]`; `shadow`; Japanese vertical glyph forms and origins, tested by `biz_ud_vertical_watermarks_place_punctuation_at_the_top_right`; extended grapheme cells keep decomposed dakuten/handakuten and Latin accents together, tested by `vertical_watermarks_keep_combining_marks_in_one_cell` and `upright_watermark_cell_retains_multiple_glyphs` (see `docs/vertical-watermarks.md`)) or a graphic with transparency (`image` path, `imageWidth` = fraction of the photo's width, 0.01..1, converted to the output colour space); `anchor` (nine positions), `insetX` / `insetY` (margins from the side and from the top/bottom edges, each a fraction of the short edge, 0..0.4; the Export dialog's Horizontal and Vertical inset sliders, as in Lightroom Classic; the older single `inset` still reads as both; tested by `watermark_insets_are_horizontal_and_vertical`), `rotation` (0, 90, 180 or 270 degrees clockwise, the Export dialog's Rotate row, as Lightroom Classic's rotate buttons; sized before it is turned, placed and inset by the turned box; tested by `watermark_rotation_turns_the_text_in_its_corner` and `graphic_watermark_is_placed_scaled_and_blended`), `opacity` 0..1. Unknown keys and out-of-range values are errors (issue #183). The Export dialog previews it on the first exported photo's thumbnail (`draw_watermark_preview` scales the 6 px minimum text size to the preview so it matches the file), tested by `watermark_preview_scales_the_minimum_text_size` and `export_dialog_previews_the_watermark` | | LR-EXP-NAMING | File naming | P1 | ✅ | `cmd:app.export` (`naming`, `startNumber`), `crates/engine/src/rename.rs` (`expand_tokens`) | one template language for export, Rename Photos and import renaming: `{name}`, `{num}` (number at the end of the name), `{seq}` / `{seq:N}`, `{date}` / `{date:%Y-%m-%d}`, `{folder}`, `{camera}`, `{lens}`, `{iso}`, `{rating}`, `{title}`, `{creator}`, `{ext}`; free-form template rather than a list of named schemes | | LR-EXP-LOCATION | Destination folder | P0 | ✅ | `cmd:app.export` (`dir`, `destinationMode`: specificFolder / sameAsOriginal, `subfolder`, `conflict`: unique / overwrite / skip), `cmd:export.checkTarget`, `crates/ui-egui/src/panels/dialogs.rs` (Choose… folder picker), `crates/engine/src/originals.rs`, `crates/catalog/src/safe_file.rs` | folder picker on the desktop; Export to: Specific folder or Same folder as original photo (each photo into its original's folder + the subfolder; a demo/browser photo or a missing folder is that photo's error, issue #956); existing files get `-2`, `-3`… by default; the policy covers a file and its sidecars together; a catalogued original (or its sidecar) is never written over, whatever the policy or an exact `path` (export, `ui.render`, MCP `render_photo`, merge `previewPath`, `lightcraft-cli render`); files are written to a temp file and renamed into place (issue #93; not synced file by file — exports can be made again, issue #134) | @@ -797,7 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| -| 2026-10-14 | patch | LR-META-EXIF-FULL, LR-EXP-METADATA: preserve shutter duration through import, display and export (#1619); no catalog schema change. Statuses and feature counts unchanged. | +| 2026-10-14 | patch | LR-META-EXIF-FULL, LR-EXP-METADATA: shutter speeds shown as 1/n or four significant digits; the exact duration is kept in the catalog (optional `exposure_time`, older catalogs read unchanged) and written on export (#1619). Statuses and feature counts unchanged. | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | From 0ef612f518c91add53e32316c7cc83b637268c9f Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:24:45 -0400 Subject: [PATCH 006/625] LR-PROF-CAMERACOLOR: raw decoding keeps negative channels Decoding clamped each linear Rec.2020 channel at zero after the colour matrix. Near black those values are sensor noise, and the clamp kept only the positive half of each channel's noise: through a saturating camera matrix red and blue have the widest noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV: sRGB (64, 28, 65) in its darkest 40%, (2, 4, 4) now). Negative channels now pass through to noise reduction and the output gamut mapping, which already moves colours toward their luminance until in range; only non-finite values are zeroed. Moving each negative colour toward its luminance at decode instead still left it pink ((34, 14, 22)). RENDER_CACHE_VERSION 66. --- crates/engine/src/files.rs | 49 ++++++++++++++++++++++++++++++++++++-- crates/engine/src/media.rs | 2 +- docs/parity-checklist.md | 3 ++- docs/whats-new.md | 8 +++++++ 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 31bb930fbf..9c6f02852b 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -280,7 +280,7 @@ impl CameraColourModel<'_> { } 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)); + *p = finite([out[0][l], out[1][l], out[2][l]]); } } }); @@ -302,10 +302,22 @@ impl CameraColourModel<'_> { 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)) + finite(self.hue_sat.map_or(rgb, |h| h.apply(rgb))) } } +/// `rgb` (linear Rec.2020) as decoding leaves it for the stages after: negative channels kept, non-finite ones zero. +/// Near black, negative channels are sensor noise through the colour matrix, and keeping them keeps the noise zero-mean +/// until noise reduction and the output's gamut mapping (which moves a colour toward its luminance until it is in +/// range) deal with it. Clamping each channel at zero here kept only the positive half of every channel's noise: +/// through a saturating camera matrix (red row 3.5, −2.4, −0.1 on a NIKON D780 profile) red and blue have the widest +/// noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV rendered at sRGB (64, 28, 65) +/// in its darkest 40%, (2, 4, 4) without the clamp). Moving each such colour toward its luminance instead still left +/// it pink, at (34, 14, 22): any per-pixel rule that treats pixels by the sign of their noise biases the mean. +fn finite(rgb: [f32; 3]) -> [f32; 3] { + rgb.map(|v| if v.is_finite() { v } else { 0.0 }) +} + /// The white-balanced camera RGB that `model` (white-balanced camera RGB → linear Rec.2020) renders /// neutral, as bright as it renders `[1, 1, 1]`: what fully clipped highlights are rebuilt to, so they come out /// neutral whatever the colour model does to the camera's own neutral (a look fitted to the camera's JPEG or a @@ -1839,6 +1851,39 @@ pub(crate) mod tests { /// 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 decoding_keeps_negative_channels_and_zeroes_non_finite_ones() { + assert_eq!(finite([0.6, 0.05, -0.04]), [0.6, 0.05, -0.04]); + assert_eq!(finite([f32::NAN, -0.1, f32::INFINITY]), [0.0, -0.1, 0.0]); + } + + /// Dark sensor noise through a saturating camera matrix (a NIKON D780 profile's) averages to a neutral colour: the + /// per-channel clamp at zero decoding had kept red's and blue's wider positive halves and turned it magenta. + #[test] + fn dark_noise_through_a_saturating_matrix_stays_neutral() { + let matrix = lightcraft_color::Mat3([[3.48, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]); + let colour = CameraColourModel { wb: [1.0; 3], matrix, gain: 1.0, tables: None, hue_sat: None }; + // a grey 0.002 above black with ±0.004 of noise per channel (a deterministic sequence) + let mut state = 12345u32; + let mut noise = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + let mut img = Rgb32f::new(200, 200); + for p in img.data.iter_mut() { + *p = [0.002 + noise(), 0.002 + noise(), 0.002 + noise()]; + } + colour.apply(&mut img); + let mut mean = [0.0f64; 3]; + for p in &img.data { + for (m, v) in mean.iter_mut().zip(p) { + *m += f64::from(*v); + } + } + let (hi, lo) = (mean[0].max(mean[1]).max(mean[2]), mean[0].min(mean[1]).min(mean[2])); + assert!(lo > 0.0 && hi / lo < 1.2, "mean {mean:?} is tinted"); + } + #[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(); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 22d76528d6..e6c438ad72 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 64; +pub const RENDER_CACHE_VERSION: u64 = 65; /// 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]; diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 4e05317933..18863969ad 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (LRC-PRINT-PAGE: Print Page Options) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** patch (LR-PROF-CAMERACOLOR: raw decoding keeps negative channels) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -801,6 +801,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | +| 2026-10-16 | patch | LR-PROF-CAMERACOLOR: raw decoding keeps negative channels (noise near black) instead of clipping each at zero, which turned pushed shadows magenta; status unchanged (🟡) | | 2026-10-12 | minor | LR-EDIT-OPTICS-PROFILE: Sony ARW shading, CA and distortion tables decoded with settings and provenance (raw IFD, `SR2SubIFD` fallback); applied corrections unchanged (ILCE-7RM4A and ILCE-7RM6 distortion); status unchanged (🟡) | | 2026-10-14 | minor | LR-IMP-CAMERA-COVERAGE: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277); status unchanged (🟡) | | 2026-10-13 | minor | LR-MERGE-PANO: a panorama's DNG takes its `AsShotNeutral` from the median of its frames' vendor white-balance multipliers (CR2, NEF, ARW…) instead of the first frame's tags, and frames now carry the multipliers (issue #1144); status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 2f02ffb91b..441b4889bc 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,13 @@ # What's new in LightCraft +## 2026-10-16 + +### Pushed shadows of raws no longer turn magenta +- Raw decoding no longer clips each colour channel at zero. Near black, sensor noise through the camera's colour + matrix has negative values, and clipping kept only the positive half of each channel's noise, so dark areas + pushed up came out purple or magenta (a lens-cap frame pushed 4 EV rendered magenta; it is now black). Shadows + pushed with Exposure or Shadows keep their real colour, most visibly with saturating camera profiles. + ## 2026-10-14 ### Model downloads time out on a name that doesn't resolve From 3886c765827587f4d76f8fde870cbf443e9dd9f2 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:31:39 +0200 Subject: [PATCH 007/625] LR-LIB-CULL: Assisted Culling can stack each burst, best photo on top (#2277) photo.analyze takes stackGroups (default false): every burst becomes one collapsed stack topped by its sharpest photo, in the same undo step as the analysis and flags. Photos already in a stack are left alone (like stack.auto); the rest of the burst is stacked when two or more remain. Duplicate ids are measured once. The dialog gets a "Stack each burst, best photo on top" checkbox, remembered for the session; German translation, parity row and revision history updated. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 55 ++++++++++++-- crates/engine/src/tests_import.rs | 110 +++++++++++++++++++++++++++ crates/ui-egui/locales/de.json | 1 + crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/panels/dialogs.rs | 9 ++- crates/ui-egui/src/state.rs | 9 ++- docs/parity-checklist.md | 5 +- 7 files changed, 178 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 92a9c3b7cb..71db71c990 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -1,7 +1,7 @@ //! Assisted culling: score photos for focus and clipping, group similar shots taken close //! together (bursts) and mark the sharpest of each group; optionally reject blurry ones and pick -//! each group's best. Scores are kept on the photos (rules / smart albums: `sharpness`, -//! `bestOfGroup`). +//! each group's best, and stack each burst with its best photo on top. Scores are kept on the +//! photos (rules / smart albums: `sharpness`, `bestOfGroup`). use lightcraft_catalog::{Analysis, Flag, Op, PhotoId}; use serde_json::{Value, json}; @@ -22,10 +22,17 @@ fn secs(iso: &str) -> Option { } fn analyze(s: &mut Session, p: &Value) -> Result { - let ids: Vec = if p.get("ids").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + let mut ids: Vec = if p.get("ids").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + // a photo named twice is measured (and stacked) once + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); 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); let (gap, same) = burst_params(p)?; + let stack_groups = match p.get("stackGroups") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", "`stackGroups` must be true or false"))?, + }; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -80,10 +87,48 @@ fn analyze(s: &mut Session, p: &Value) -> Result { } out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best})); } + let mut stacks = 0; + if stack_groups { + // Photos already in a stack stay where they are (like `stack.auto`): a burst is stacked + // from its other photos when two or more remain, with the sharpest of those on top. + let index = s.catalog.stack_index(); + let mut members: std::collections::BTreeMap> = Default::default(); + for (i, g) in group_of.iter().enumerate() { + if let (Some(g), Some(r)) = (g, rows.get(i)) + && !index.contains_key(&r.0) + && s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) + { + members.entry(*g).or_default().push((r.0, r.2)); + } + } + for group in members.values() { + let Some(top) = group.iter().fold(None::<(PhotoId, f32)>, |b, m| if b.is_none_or(|b| m.1 > b.1) { Some(*m) } else { b }) else { + continue; + }; + let photos: Vec = group.iter().map(|m| m.0).collect(); + if photos.len() >= 2 + && let Some(op) = s.catalog.group_ops(top.0, &photos, true) + { + ops.push(op); + stacks += 1; + } + } + } if !ops.is_empty() { s.commit("Assisted Culling", Op::Batch { ops })?; } - Ok(json!({"photos": out, "groups": best.len(), "rejected": rejected, "picked": picked, "failed": failed})) + if stacks > 0 { + // a photo now hidden inside a collapsed stack must not stay the active one + let vis = s.visible_cloned(); + if let Some(a) = s.selection.active + && !vis.contains(&a) + && let Some(st) = s.catalog.stack_of(a) + { + let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); + s.selection = crate::Selection::single(top); + } + } + Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) } /// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before @@ -152,7 +197,7 @@ pub fn specs() -> Vec { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos and pick each group's best; one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, rejected, picked}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain); one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, stacks, rejected, picked, failed}", always, analyze ), diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index f581f11dda..101fe43431 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -870,6 +870,116 @@ fn assisted_culling_burst_limits_are_adjustable() { let _ = std::fs::remove_dir_all(&dir); } +/// Assisted culling with `stackGroups` (#2277): each burst becomes one collapsed stack with its +/// sharpest photo on top, an unrelated photo stays loose, analysis and stack are one undo step, +/// and a second run neither makes another stack nor splits the existing one. +#[test] +fn assisted_culling_stacks_each_burst_best_on_top() { + let dir = temp_dir("cull-stack"); + let scene = lightcraft_scenes::demo_library()[0].render(480, 320); + let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out + }; + let save = |img: &lightcraft_raster::Rgb32f, name: &str| { + let data: Vec<[u8; 4]> = img + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(dir.join(name), png).unwrap(); + }; + save(&soften(&scene, 3), "a_soft.png"); + save(&scene, "b_sharp.png"); + save(&soften(&scene, 6), "c_softer.png"); + save(&lightcraft_scenes::demo_library()[7].render(480, 320), "d_other.png"); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).collect(); + let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + for (i, n) in ["a_soft.png", "b_sharp.png", "c_softer.png", "d_other.png"].iter().enumerate() { + let id = by_name(&s, n); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T10:00:0{i}")) }).unwrap(); + } + let (soft, sharp, softer, other) = + (by_name(&s, "a_soft.png"), by_name(&s, "b_sharp.png"), by_name(&s, "c_softer.png"), by_name(&s, "d_other.png")); + // a photo named twice is measured and stacked once + let mut twice = ids.clone(); + twice.push(sharp.0); + let r = s.execute("photo.analyze", &json!({"ids": twice, "stackGroups": true})).unwrap(); + assert_eq!((r["stacks"].clone(), r["groups"].clone()), (json!(1), json!(1)), "{r}"); + let st = s.catalog.stack_of(sharp).unwrap().clone(); + assert!(st.collapsed && st.top() == sharp, "the sharpest photo tops the stack"); + let mut members = st.photos.clone(); + members.sort(); + let mut want = vec![soft, sharp, softer]; + want.sort(); + assert_eq!(members, want); + assert!(s.catalog.stack_of(other).is_none(), "the unrelated photo stays loose"); + assert!(s.catalog.photo(sharp).unwrap().analysis.is_some_and(|a| a.best)); + // one undo step removes the stack and the analysis together + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.stacks().next().is_none()); + assert!(s.catalog.photo(sharp).unwrap().analysis.is_none()); + // without `stackGroups` nothing is stacked + let r = s.execute("photo.analyze", &json!({"ids": ids})).unwrap(); + assert_eq!(r["stacks"], 0, "{r}"); + assert!(s.catalog.stacks().next().is_none()); + s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(s.catalog.stacks().count(), 1); + // a second run leaves the stack as it is + let before = s.catalog.stack_of(sharp).unwrap().clone(); + let commits = s.commits(); + let r = s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 0, "{r}"); + assert_eq!(s.catalog.stacks().count(), 1); + assert_eq!(s.catalog.stack_of(sharp).unwrap(), &before); + assert!(s.commits() > commits); + // a burst partly stacked already: the loose photos are stacked among themselves when two remain + let mut s2 = Session::new().with_fs(); + s2.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + for (i, n) in ["a_soft.png", "b_sharp.png", "c_softer.png", "d_other.png"].iter().enumerate() { + let id = by_name(&s2, n); + s2.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T10:00:0{i}")) }).unwrap(); + } + let (soft, sharp, softer, other) = + (by_name(&s2, "a_soft.png"), by_name(&s2, "b_sharp.png"), by_name(&s2, "c_softer.png"), by_name(&s2, "d_other.png")); + let ids: Vec = [soft, sharp, softer, other].iter().map(|p| p.0).collect(); + s2.execute("stack.group", &json!({"ids": [soft.0, other.0]})).unwrap(); + let r = s2.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 1, "{r}"); + assert!(s2.catalog.stack_of(soft).unwrap().photos.contains(&other), "the existing stack is untouched"); + let st = s2.catalog.stack_of(sharp).unwrap(); + assert!(st.top() == sharp && st.photos.len() == 2 && st.photos.contains(&softer)); + // a non-boolean value is refused before anything changes + let n = s2.commits(); + assert!(s2.execute("photo.analyze", &json!({"ids": ids, "stackGroups": "yes"})).is_err()); + assert_eq!(s2.commits(), n); + let _ = std::fs::remove_dir_all(&dir); +} + /// Find Dust Spots: soft dark spots on a smooth sky are found and healed (one undo step). #[test] fn dust_spots_are_found_and_healed() { diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 9d2d756800..4d08cbd4a4 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1205,6 +1205,7 @@ "Refresh View": "Ansicht aktualisieren", "Reject": "Ablehnen", "Reject below focus": "Unter Schärfegrenzwert ablehnen", + "Stack each burst, best photo on top": "Jede Serie stapeln, bestes Foto oben", "Burst: shots at most this far apart": "Serie: Aufnahmen höchstens so weit auseinander", "Burst: how alike (loose … strict)": "Serie: wie ähnlich (locker … streng)", "Lower it when a panning or moving burst splits into several groups.": "Senken, wenn eine Mitzieher- oder Bewegungsserie in mehrere Gruppen zerfällt.", diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 229b34dc6a..41df245a78 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1444,7 +1444,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option open_original_in(app, &ctx, p), "dialog.cull" => { let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, burst_gap, similarity }); + app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, stack_groups: app.ui.cull_stack, burst_gap, similarity }); Ok(Value::Null) } "app.whatsNew" => { diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index 26e198133a..575ba09cd3 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -336,7 +336,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), ); } - Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); @@ -346,6 +346,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { ui.label(egui::RichText::new(crate::i18n::tr(if *reject_below > 0.0 { "Blurry photos below the score are flagged as rejects." } else { "0: nothing is rejected." })).color(t.text_dim)); let r = ui.checkbox(pick_best, crate::i18n::tr("Pick the sharpest photo of each burst")); crate::widgets::register(ui.ctx(), "check:cullPick", r.rect); + let r = ui.checkbox(stack_groups, crate::i18n::tr("Stack each burst, best photo on top")); + crate::widgets::register(ui.ctx(), "check:cullStack", r.rect); ui.add_space(6.0); let r = ui.add( egui::Slider::new(burst_gap, 1.0..=600.0) @@ -1918,9 +1920,10 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); - let mut p = json!({"pickBest": pick_best, "burstGap": burst_gap, "similarity": similarity}); + app.ui.cull_stack = *stack_groups; + let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity}); if *reject_below > 0.0 { p["rejectBelow"] = json!(reject_below); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3388bad3b1..f97a4b44dd 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -732,6 +732,9 @@ pub struct UiState { /// session; `None` until the dialog is first confirmed (then 10 s, 0.93). #[serde(skip)] pub cull_burst: Option<(f32, f32)>, + /// Whether Assisted Culling stacked its bursts the last time it was confirmed (this session). + #[serde(skip)] + pub cull_stack: bool, /// "More" faces the user hid with ×, for this session: (photo, region index). #[serde(skip)] pub dismissed_faces: std::collections::HashSet<(u64, usize)>, @@ -1093,11 +1096,12 @@ pub enum Dialog { /// Help ▸ What's New. WhatsNew, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best - /// of each burst; shots at most `burst_gap` seconds apart and at least `similarity` alike are - /// a burst. + /// of each burst (and stack each burst, best on top, with `stack_groups`); shots at most + /// `burst_gap` seconds apart and at least `similarity` alike are a burst. Cull { reject_below: f32, pick_best: bool, + stack_groups: bool, burst_gap: f32, similarity: f32, }, @@ -1321,6 +1325,7 @@ impl Default for UiState { person_from: None, last_person: None, cull_burst: None, + cull_stack: false, dismissed_faces: Default::default(), unnamed_selected: Default::default(), unnamed_name: String::new(), diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9cce61b9a6..32488a4dda 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: adjustable burst limits) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: bursts can be stacked, best on top) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -116,7 +116,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked; reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs` | “Copy N” badge, stacked with the original, same albums, no XMP writes; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling can stack each burst collapsed with its best photo on top (dialog checkbox, `photo.analyze` `stackGroups`; #2277). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling's burst gap and similarity are adjustable (dialog, `photo.analyze` `burstGap` / `similarity`; #2275). Statuses and feature counts unchanged. | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | From 76dfb0df11079a9b38e61f879bd38d8657cf3ea6 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:47:17 +0200 Subject: [PATCH 008/625] LR-LIB-CULL: stacking bursts keeps the rest of the selection (#2277) When the active photo goes into a collapsed burst stack, the stack's top becomes active and the other selected photos stay selected, instead of the selection collapsing to one photo. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 9 +++++++-- crates/engine/src/tests_import.rs | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 71db71c990..4266790edd 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -118,14 +118,19 @@ fn analyze(s: &mut Session, p: &Value) -> Result { s.commit("Assisted Culling", Op::Batch { ops })?; } if stacks > 0 { - // a photo now hidden inside a collapsed stack must not stay the active one + // a photo now hidden inside a collapsed stack must not stay the active one: its stack's + // top takes over, and the rest of the selection (what was culled) stays selected let vis = s.visible_cloned(); if let Some(a) = s.selection.active && !vis.contains(&a) && let Some(st) = s.catalog.stack_of(a) { let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); - s.selection = crate::Selection::single(top); + s.selection.ids.retain(|id| vis.contains(id)); + if !s.selection.ids.contains(&top) { + s.selection.ids.push(top); + } + s.selection.active = Some(top); } } Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 101fe43431..170a9d245d 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -928,8 +928,12 @@ fn assisted_culling_stacks_each_burst_best_on_top() { // a photo named twice is measured and stacked once let mut twice = ids.clone(); twice.push(sharp.0); + s.selection = crate::Selection { ids: vec![soft, sharp, softer, other], active: Some(soft) }; let r = s.execute("photo.analyze", &json!({"ids": twice, "stackGroups": true})).unwrap(); assert_eq!((r["stacks"].clone(), r["groups"].clone()), (json!(1), json!(1)), "{r}"); + // the active photo went into the collapsed stack: its top takes over, the loose photo stays selected + assert_eq!(s.selection.active, Some(sharp)); + assert!(s.selection.ids.contains(&other) && s.selection.ids.contains(&sharp) && !s.selection.ids.contains(&soft), "{:?}", s.selection.ids); let st = s.catalog.stack_of(sharp).unwrap().clone(); assert!(st.collapsed && st.top() == sharp, "the sharpest photo tops the stack"); let mut members = st.photos.clone(); From c61d946ef32e5227ec48d061fa723038b84b5261 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:38:22 +0200 Subject: [PATCH 009/625] LR-LIB-CULL: bursts keep an order set by hand (catalog format 10) `Analysis.rank` is a photo's place in its burst once the person arranged the burst by hand (0 = the pick). `Catalog::burst_index` / `burst` / `bursts_among` give each burst pick first, and `next_burst_id` a number no photo uses. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/bursts.rs | 118 +++++++++++++++++++++ crates/catalog/src/journal.rs | 3 +- crates/catalog/src/lib.rs | 1 + crates/catalog/src/model.rs | 14 +++ crates/catalog/src/tests_format_version.rs | 31 +++++- 5 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 crates/catalog/src/bursts.rs diff --git a/crates/catalog/src/bursts.rs b/crates/catalog/src/bursts.rs new file mode 100644 index 0000000000..a5b393780b --- /dev/null +++ b/crates/catalog/src/bursts.rs @@ -0,0 +1,118 @@ +//! Bursts: the look-alike shots Assisted Culling groups ([`crate::Analysis::group`]), in the +//! order they are shown and arranged — the pick first. +//! +//! A burst culling made is ordered by what culling found: its best photo, then the sharper +//! shots, then capture time. Once the person arranges a burst by hand every member carries its +//! place ([`crate::Analysis::rank`]), and that order is kept. + +use std::collections::{HashMap, HashSet}; + +use crate::{Catalog, Photo, PhotoId}; + +/// A photo's place in its burst: hand-placed ones by their place, then the best, the sharper, +/// the earlier, the lower id. +fn order_key(p: &Photo) -> (u32, bool, i64, &str, PhotoId) { + let a = p.analysis.unwrap_or_default(); + // sharpness is 0..100: a fixed-point key keeps the sort total + (a.rank.unwrap_or(u32::MAX), !a.best, -((a.sharpness * 1000.0) as i64), p.captured.as_deref().unwrap_or("~"), p.id) +} + +impl Catalog { + /// Every burst: its number → its photos (deleted ones left out), pick first. + pub fn burst_index(&self) -> HashMap> { + let mut by: HashMap> = HashMap::new(); + for p in self.photos.values().filter(|p| !p.deleted) { + if let Some(g) = p.analysis.and_then(|a| a.group) { + by.entry(g).or_default().push(&**p); + } + } + by.into_iter() + .map(|(g, mut photos)| { + photos.sort_by(|a, b| order_key(a).cmp(&order_key(b))); + (g, photos.into_iter().map(|p| p.id).collect()) + }) + .collect() + } + + /// The photos of burst `group`, pick first (empty when there is no such burst). + pub fn burst(&self, group: u32) -> Vec { + self.burst_index().remove(&group).unwrap_or_default() + } + + /// The bursts `ids` meet, in the order their first photo appears in `ids`, each pick first. + /// Only photos in `scope` count as members (the photos of a view and the hidden members of + /// its collapsed stacks, say); `None` takes every photo of the burst. + pub fn bursts_among(&self, ids: &[PhotoId], scope: Option<&HashSet>) -> Vec<(u32, Vec)> { + let mut index = self.burst_index(); + let mut out = Vec::new(); + for id in ids { + let Some(g) = self.photo(*id).and_then(|p| p.analysis).and_then(|a| a.group) else { continue }; + if let Some(mut photos) = index.remove(&g) { + if let Some(scope) = scope { + photos.retain(|p| scope.contains(p)); + } + if !photos.is_empty() { + out.push((g, photos)); + } + } + } + out + } + + /// A burst number no photo uses (deleted ones included, so Undo never brings back a clash). + pub fn next_burst_id(&self) -> u32 { + self.photos.values().filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1 + } +} + +#[cfg(test)] +mod tests { + use crate::{Analysis, Catalog, Op, Photo, PhotoId, Source}; + + fn add(c: &mut Catalog, when: &str, a: Option) -> PhotoId { + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/p/{}.jpg", id.0) }, "p.jpg", "JPEG", 4, 3, "2026-01-01"); + p.captured = Some(when.into()); + p.analysis = a; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + } + + fn shot(group: u32, sharpness: f32, best: bool, rank: Option) -> Option { + Some(Analysis { sharpness, group: Some(group), best, rank, ..Default::default() }) + } + + #[test] + fn a_culled_burst_shows_its_best_then_the_sharper_shots() { + let mut c = Catalog::new(); + let a = add(&mut c, "2026-05-01T10:00:00", shot(1, 20.0, false, None)); + let b = add(&mut c, "2026-05-01T10:00:01", shot(1, 80.0, true, None)); + let d = add(&mut c, "2026-05-01T10:00:02", shot(1, 50.0, false, None)); + let loose = add(&mut c, "2026-05-01T10:00:03", Some(Analysis::default())); + assert_eq!(c.burst(1), vec![b, d, a]); + assert!(c.burst(2).is_empty()); + assert_eq!(c.bursts_among(&[a, loose, d], None), vec![(1, vec![b, d, a])]); + assert_eq!(c.next_burst_id(), 2); + } + + #[test] + fn a_burst_arranged_by_hand_keeps_its_order() { + let mut c = Catalog::new(); + // the pick by hand is the softest shot + let a = add(&mut c, "2026-05-01T10:00:00", shot(3, 20.0, true, Some(0))); + let b = add(&mut c, "2026-05-01T10:00:01", shot(3, 80.0, false, Some(2))); + let d = add(&mut c, "2026-05-01T10:00:02", shot(3, 50.0, false, Some(1))); + let other = add(&mut c, "2026-05-01T11:00:00", shot(7, 50.0, true, None)); + let other2 = add(&mut c, "2026-05-01T11:00:01", shot(7, 40.0, false, None)); + assert_eq!(c.burst(3), vec![a, d, b]); + // in the order the view meets them; a scope keeps a burst's members within it + assert_eq!(c.bursts_among(&[other, b], None), vec![(7, vec![other, other2]), (3, vec![a, d, b])]); + let scope = [b, d, other].into_iter().collect(); + assert_eq!(c.bursts_among(&[b, other], Some(&scope)), vec![(3, vec![d, b]), (7, vec![other])]); + assert_eq!(c.next_burst_id(), 8); + // deleted photos are no member + c.apply(Op::SetDeleted { id: d, deleted: true }).unwrap(); + assert_eq!(c.burst(3), vec![a, b]); + assert_eq!(c.next_burst_id(), 8); + } +} diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index edcfae22ae..a3421661d4 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -52,6 +52,7 @@ //! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` | //! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` | //! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` | +//! | 10 | bursts arranged by hand in Assisted Culling | `Analysis.rank` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -76,7 +77,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 9; +pub const VERSION: u32 = 10; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 1776c895c1..b3791a6d95 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -13,6 +13,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bursts; pub mod dates; pub mod folders; mod index; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 6ac3544ee7..1a3e03ea82 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -321,6 +321,20 @@ pub struct Analysis { pub group: Option, /// The best photo of its group. pub best: bool, + /// Set when the person arranged this photo's burst by hand (Window ▸ Bursts, or + /// `photo.moveToBurst`): its place in [`Analysis::group`], 0 being the pick, or `Some(0)` for + /// a photo taken out of every burst. Culling run again keeps such a photo's burst, place and + /// pick (unless asked to regroup). `None` while the burst is as culling made it; left out of the + /// catalog JSON then, so older catalogs read unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rank: Option, +} + +impl Analysis { + /// Whether the person placed this photo by hand (see [`Analysis::rank`]). + pub fn by_hand(&self) -> bool { + self.rank.is_some() + } } /// Raw formats whose files carry vendor white-balance multipliers but no colour matrices: their starting diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index e31d7fe0c4..56ffc6e58d 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -192,6 +192,33 @@ fn bad_crc_is_still_a_torn_tail() { assert!(r.torn_bytes > 0 && r.damaged.is_none(), "{r:?}"); } +/// A v9 library (bursts as culling made them) reads every analysis as not arranged by hand and +/// is rewritten in the current format; a place set by hand survives the round trip, and none is +/// written for a photo left as culling placed it. +#[test] +fn v9_analysis_loads_unarranged_and_is_upgraded() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/p/a.jpg".into() }, "a.jpg", "JPEG", 160, 120, "2026-01-01"); + p.analysis = Some(Analysis { sharpness: 61.0, clipped: 0.01, group: Some(2), best: true, ..Default::default() }); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let snap = c.to_snapshot(); + assert!(!snap.contains("rank"), "nothing new is written for a burst culling made: {snap}"); + let m = MemStore::new(); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":1,\"catalog\":{snap}}}\n").into_bytes()); + let (_, loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + let a = loaded.photo(id).unwrap().analysis.unwrap(); + assert_eq!((a.group, a.best, a.rank, a.by_hand()), (Some(2), true, None, false)); + assert_eq!(r.upgraded_from, Some(9)); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + // a place set by hand round-trips + let mut c = loaded; + let b = Analysis { rank: Some(1), best: false, ..a }; + c.apply(Op::SetAnalysis { id, analysis: Some(b) }).unwrap(); + let again: Catalog = serde_json::from_str(&c.to_snapshot()).unwrap(); + assert_eq!(again.photo(id).unwrap().analysis, Some(b)); +} + /// Guard for the version rule (see `journal` → *Format versions*): adding an [`Op`] variant breaks /// this match. When it does, bump `journal::VERSION`, add a row to the format table, and add the /// variant here under the new version. A version that only adds serialized fields raises @@ -238,8 +265,8 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`. - const NEWEST_FIELDS: u32 = 9; + /// v10: `Analysis.rank`. + const NEWEST_FIELDS: u32 = 10; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } From 96a18539b9637289bfe52f37b94cfa16a33063f9 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:58:03 +0200 Subject: [PATCH 010/625] LR-LIB-CULL: photo.moveToBurst arranges bursts by hand; culling again keeps them `photo.moveToBurst {ids, burst?: n | "new" | null, index?}` moves photos within their burst, into another, into a new one or out of every burst. The first place is the pick: `best` (Best of Similar Shots), the Pick flag culling gave the old pick and the top of a stacked burst follow it. A burst a move leaves with one photo is no burst. One undo step. `photo.analyze` keeps the burst, place and pick of photos arranged by hand and only scores them again (`resetBursts` regroups them), and numbers new bursts after every burst that stays, so two runs on different photos no longer share burst numbers. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 247 +++++++++++++++++++++++++---- crates/engine/src/lib.rs | 2 + crates/engine/src/tests_bursts.rs | 250 ++++++++++++++++++++++++++++++ 3 files changed, 473 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/tests_bursts.rs diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 4266790edd..76725a968c 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -29,10 +29,14 @@ fn analyze(s: &mut Session, p: &Value) -> Result { 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); let (gap, same) = burst_params(p)?; - let stack_groups = match p.get("stackGroups") { - None | Some(Value::Null) => false, - Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", "`stackGroups` must be true or false"))?, + let flag_param = |key: &str| -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", format!("`{key}` must be true or false"))), + } }; + let stack_groups = flag_param("stackGroups")?; + let reset = flag_param("resetBursts")?; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -48,17 +52,25 @@ fn analyze(s: &mut Session, p: &Value) -> Result { } // bursts: consecutive (by capture time) look-alike shots rows.sort_by_key(|r| (r.1.unwrap_or(i64::MAX), r.0)); + // A photo whose burst was arranged by hand keeps it (burst, place, pick): only its scores + // are measured again. The others are grouped among themselves, in bursts numbered after + // every burst that stays (earlier runs on other photos, the ones arranged by hand). + let by_hand = |id: PhotoId| -> Option { s.catalog.photo(id).and_then(|p| p.analysis).filter(|a| !reset && a.by_hand()) }; + let kept: Vec> = rows.iter().map(|r| by_hand(r.0)).collect(); + let auto: Vec = (0..rows.len()).filter(|i| kept[*i].is_none()).collect(); + let regrouped: std::collections::HashSet = auto.iter().map(|i| rows[*i].0).collect(); + let mut next = s.catalog.photos().filter(|p| !regrouped.contains(&p.id)).filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1; let mut group_of: Vec> = vec![None; rows.len()]; - let mut next = 1u32; - for i in 1..rows.len() { - let (a, b) = (&rows[i - 1], &rows[i]); + for w in auto.windows(2) { + let (i, j) = (w[0], w[1]); + let (a, b) = (&rows[i], &rows[j]); let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y.saturating_sub(x)).unsigned_abs() as f64 <= gap); if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= same { - let g = *group_of[i - 1].get_or_insert_with(|| { + let g = *group_of[i].get_or_insert_with(|| { next += 1; next - 1 }); - group_of[i] = Some(g); + group_of[j] = Some(g); } } let mut best: std::collections::HashMap = Default::default(); @@ -74,9 +86,16 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let (mut rejected, mut picked) = (0, 0); let mut out = Vec::new(); for (i, (id, _, sharp, clip, _)) in rows.iter().enumerate() { - let g = group_of[i]; - let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); - ops.push(Op::SetAnalysis { id: *id, analysis: Some(Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best }) }); + let analysis = match kept[i] { + Some(k) => Analysis { sharpness: *sharp, clipped: *clip, ..k }, + None => { + let g = group_of[i]; + let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); + Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best, rank: None } + } + }; + let (g, is_best) = (analysis.group, analysis.best); + ops.push(Op::SetAnalysis { id: *id, analysis: Some(analysis) }); let flag = s.catalog.photo(*id).map(|p| p.flag).unwrap_or_default(); if reject_below.is_some_and(|t| *sharp < t) && flag != Flag::Reject { ops.push(Op::SetFlag { id: *id, flag: Flag::Reject }); @@ -85,7 +104,7 @@ fn analyze(s: &mut Session, p: &Value) -> Result { ops.push(Op::SetFlag { id: *id, flag: Flag::Pick }); picked += 1; } - out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best})); + out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best, "byHand": kept[i].is_some()})); } let mut stacks = 0; if stack_groups { @@ -118,22 +137,189 @@ fn analyze(s: &mut Session, p: &Value) -> Result { s.commit("Assisted Culling", Op::Batch { ops })?; } if stacks > 0 { - // a photo now hidden inside a collapsed stack must not stay the active one: its stack's - // top takes over, and the rest of the selection (what was culled) stays selected - let vis = s.visible_cloned(); - if let Some(a) = s.selection.active - && !vis.contains(&a) - && let Some(st) = s.catalog.stack_of(a) - { - let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); - s.selection.ids.retain(|id| vis.contains(id)); - if !s.selection.ids.contains(&top) { - s.selection.ids.push(top); + keep_active_shown(s); + } + let kept = kept.iter().filter(|k| k.is_some()).count(); + Ok(json!({"photos": out, "groups": best.len(), "kept": kept, "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) +} + +/// A photo now hidden inside a collapsed stack must not stay the active one: its stack's top +/// takes over, and the rest of the selection stays selected. +fn keep_active_shown(s: &mut Session) { + let vis = s.visible_cloned(); + if let Some(a) = s.selection.active + && !vis.contains(&a) + && let Some(st) = s.catalog.stack_of(a) + { + let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); + s.selection.ids.retain(|id| vis.contains(id)); + if !s.selection.ids.contains(&top) { + s.selection.ids.push(top); + } + s.selection.active = Some(top); + } +} + +/// Where `photo.moveToBurst` puts the photos. +#[derive(Clone, Copy, PartialEq)] +enum Dest { + Burst(u32), + New, + Nowhere, +} + +/// Arrange bursts by hand: `ids` go into a burst at `index` (0 = the pick), into a new burst, or +/// out of every burst. Every burst touched is then arranged by hand ([`Analysis::rank`]), so +/// culling run again keeps it. What marks a burst's pick follows its first photo: `best` (the +/// Best of Similar Shots rule), the Pick flag when culling's pick had it, and the top of the +/// burst's stack when the burst is stacked. One undo step. +fn move_to_burst(s: &mut Session, p: &Value) -> Result { + use std::collections::{BTreeMap, HashMap}; + const C: &str = "photo.moveToBurst"; + let mut ids = s.targets(p)?; + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); + if ids.is_empty() { + return Err(super::bad(C, "no photos")); + } + for id in &ids { + match s.catalog.photo(*id) { + Some(ph) if ph.deleted => return Err(super::bad(C, format!("“{}” is deleted", ph.file_name))), + Some(ph) if ph.analysis.is_none() => { + return Err(super::bad(C, format!("“{}” has no culling scores yet: run Assisted Culling on it first", ph.file_name))); } - s.selection.active = Some(top); + Some(_) => {} + None => return Err(super::bad(C, format!("no photo {}", id.0))), } } - Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) + let group = |s: &Session, id: PhotoId| s.catalog.photo(id).and_then(|p| p.analysis).and_then(|a| a.group); + let index = s.catalog.burst_index(); + let into = match p.get("burst") { + None => Dest::Burst(group(s, ids[0]).ok_or_else(|| super::bad(C, "the photo isn't in a burst: say which `burst` it goes to"))?), + Some(Value::Null) => Dest::Nowhere, + Some(Value::String(n)) if n == "new" => Dest::New, + Some(v) => match v.as_u64().and_then(|n| u32::try_from(n).ok()) { + Some(n) if index.contains_key(&n) => Dest::Burst(n), + Some(n) => return Err(super::bad(C, format!("there is no burst {n}"))), + None => return Err(super::bad(C, "`burst` must be a burst number, \"new\" or null")), + }, + }; + let at = match p.get("index") { + None | Some(Value::Null) => usize::MAX, + Some(v) => v.as_u64().map(|n| n as usize).ok_or_else(|| super::bad(C, "`index` must be a place in the burst: 0 (the pick), 1, …"))?, + }; + // the bursts touched, before and after + let target = match into { + Dest::Burst(g) => Some(g), + Dest::New => Some(s.catalog.next_burst_id()), + Dest::Nowhere => None, + }; + let mut old: BTreeMap> = BTreeMap::new(); + for g in ids.iter().filter_map(|id| group(s, *id)).chain(target) { + old.entry(g).or_insert_with(|| index.get(&g).cloned().unwrap_or_default()); + } + let mut new = old.clone(); + for members in new.values_mut() { + members.retain(|m| !ids.contains(m)); + } + if let Some(g) = target { + let members = new.entry(g).or_default(); + let at = at.min(members.len()); + members.splice(at..at, ids.iter().copied()); + } + // each photo's burst, place and pick: a burst a move leaves with one photo is no burst (the + // burst moved into stays one, so a new burst may start with one photo for more to join) + let remains = |g: u32, members: &Vec| members.len() >= 2 || (target == Some(g) && !members.is_empty()); + let mut placed: HashMap, u32, bool)> = ids.iter().map(|id| (*id, (None, 0, false))).collect(); + for (g, members) in &new { + let stays = remains(*g, members); + for (i, m) in members.iter().enumerate() { + placed.insert(*m, if stays { (Some(*g), i as u32, i == 0) } else { (None, 0, false) }); + } + } + let mut ops = Vec::new(); + let mut by_id: Vec<_> = placed.iter().collect(); + by_id.sort_by_key(|(id, _)| **id); + for (id, (g, rank, best)) in by_id { + let Some(was) = s.catalog.photo(*id).and_then(|p| p.analysis) else { continue }; + let now = Analysis { group: *g, rank: Some(*rank), best: *best, ..was }; + if now != was { + ops.push(Op::SetAnalysis { id: *id, analysis: Some(now) }); + } + } + // what the target burst holds now + let members: Option> = target.and_then(|g| new.get(&g).filter(|m| remains(g, m))).map(|m| m.iter().map(|p| p.0).collect()); + let report = |changed: bool| json!({"burst": members.as_ref().and(target), "pick": members.as_ref().and_then(|m| m.first()), "photos": members, "changed": changed}); + if ops.is_empty() { + return Ok(report(false)); + } + // the Pick culling gave a burst's pick goes to its new pick + let is_pick = |id: PhotoId| placed.get(&id).is_some_and(|p| p.2); + let flag = |s: &Session, id: PhotoId| s.catalog.photo(id).map(|p| p.flag).unwrap_or_default(); + let mut flags: BTreeMap = BTreeMap::new(); + for (g, before) in &old { + let Some(old_pick) = before.iter().copied().find(|m| s.catalog.photo(*m).and_then(|p| p.analysis).is_some_and(|a| a.best)) else { continue }; + let new_pick = new.get(g).filter(|m| remains(*g, m)).and_then(|m| m.first()).copied(); + if flag(s, old_pick) != Flag::Pick || new_pick == Some(old_pick) { + continue; + } + if !is_pick(old_pick) { + flags.insert(old_pick, Flag::None); + } + if let Some(n) = new_pick + && flag(s, n) == Flag::None + { + flags.insert(n, Flag::Pick); + } + } + ops.extend(flags.into_iter().map(|(id, flag)| Op::SetFlag { id, flag })); + // a stacked burst (a stack of exactly its photos, as culling stacks them) follows it: its stack + // shrinks, grows or goes, in the burst's order. Shrinking first: a photo is in one stack at a time. + let (mut shrink, mut grow) = (Vec::new(), Vec::new()); + let mut grows_target = false; + let mut followed = std::collections::HashSet::new(); + for (g, before) in old.iter().filter(|(_, m)| m.len() >= 2) { + let Some(st) = s.catalog.stack_of(before[0]).filter(|st| st.photos.len() == before.len() && before.iter().all(|m| st.photos.contains(m))) + else { + continue; + }; + followed.insert(st.id); + let after = new.get(g).filter(|m| m.len() >= 2); + match after { + None => shrink.push(Op::RemoveStack { id: st.id }), + Some(after) if after == &st.photos => {} + Some(after) => { + let op = Op::SetStack { id: st.id, photos: after.clone(), collapsed: st.collapsed }; + if after.iter().all(|m| st.photos.contains(m)) { + shrink.push(op) + } else { + grows_target = true; + grow.push(op) + } + } + } + } + if grows_target { + // photos joining a stacked burst leave any other stack they are in + let strays: Vec = ids.iter().copied().filter(|id| s.catalog.stack_of(*id).is_some_and(|st| !followed.contains(&st.id))).collect(); + shrink.extend(s.catalog.remove_from_stacks_ops(&strays)); + } + let restacked = !shrink.is_empty() || !grow.is_empty(); + ops.extend(shrink); + ops.extend(grow); + let same = matches!(into, Dest::Burst(g) if ids.iter().all(|id| group(s, *id) == Some(g))); + let label = match into { + Dest::Burst(_) if same && at == 0 => "Choose Burst Pick", + Dest::Burst(_) if same => "Rearrange Burst", + Dest::Burst(_) => "Move to Burst", + Dest::New => "New Burst", + Dest::Nowhere => "Remove from Burst", + }; + s.commit(label, Op::Batch { ops })?; + if restacked { + keep_active_shown(s); + } + Ok(report(true)) } /// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before @@ -202,9 +388,18 @@ pub fn specs() -> Vec { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain); one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, stacks, rejected, picked, failed}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93), resetBursts?: bool (false)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain). Photos whose burst was arranged by hand (`photo.moveToBurst`) keep their burst, place and pick and are only scored again, unless `resetBursts`; one undo step → {photos: [{id, sharpness, clipped, group, best, byHand}], groups, kept, stacks, rejected, picked, failed}", always, analyze ), + cmd!( + "photo.moveToBurst", + "Move to Burst", + [], + None, + "{ids?, burst?: number | \"new\" | null (default: the first photo's burst), index?: place (0 = the pick; default last)} — arrange Assisted Culling's bursts by hand (Window ▸ Bursts): the photos go into that burst at `index`, into a new burst, or (null) out of every burst; reordering within a burst is the same call. A burst left with one photo is no burst. The pick follows the first place: Best of Similar Shots, the Pick flag culling gave the old pick, and the top of the burst's stack. Every burst touched is kept as arranged when culling runs again (`photo.analyze` `resetBursts` forgets it). Photos must have been culled; one undo step → {burst, photos, pick, changed}", + always, + move_to_burst + ), ] } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 25e6ef52f8..7fc3195fd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1247,6 +1247,8 @@ mod tests_album_remove; #[cfg(test)] mod tests_albums_local; #[cfg(test)] +mod tests_bursts; +#[cfg(test)] mod tests_color; #[cfg(test)] mod tests_crop_angle; diff --git a/crates/engine/src/tests_bursts.rs b/crates/engine/src/tests_bursts.rs new file mode 100644 index 0000000000..f402fbffe8 --- /dev/null +++ b/crates/engine/src/tests_bursts.rs @@ -0,0 +1,250 @@ +//! Bursts arranged by hand (`photo.moveToBurst`): a photo moved within its burst, into another, +//! into a new one or out of every burst; the pick follows the first place, and with it the +//! Best of Similar Shots rule, the Pick flag culling set and the burst's stack. Culling run again +//! keeps what was arranged by hand. + +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source, Stack}; +use serde_json::{Value, json}; + +use crate::Session; + +/// A photo culled into `group` (`None`: culled, in no burst; `best`: its pick), or never culled. +fn add(s: &mut Session, name: &str, when: &str, culled: Option<(Option, f32, bool)>) -> PhotoId { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 40, 30, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(group, sharpness, best)| Analysis { sharpness, group, best, ..Default::default() }); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +fn an(s: &Session, id: PhotoId) -> Analysis { + s.catalog.photo(id).unwrap().analysis.unwrap() +} + +fn flag(s: &Session, id: PhotoId) -> Flag { + s.catalog.photo(id).unwrap().flag +} + +fn mv(s: &mut Session, p: Value) -> Value { + s.execute("photo.moveToBurst", &p).unwrap_or_else(|e| panic!("{p}: {e}")) +} + +/// Burst 1 (a best and picked, b, c), burst 2 (d best, e), x culled in no burst, y never culled. +fn library() -> (Session, [PhotoId; 7]) { + let mut s = Session::new(); + let a = add(&mut s, "a.jpg", "2026-05-01T10:00:00", Some((Some(1), 80.0, true))); + let b = add(&mut s, "b.jpg", "2026-05-01T10:00:01", Some((Some(1), 60.0, false))); + let c = add(&mut s, "c.jpg", "2026-05-01T10:00:02", Some((Some(1), 40.0, false))); + let d = add(&mut s, "d.jpg", "2026-05-01T11:00:00", Some((Some(2), 70.0, true))); + let e = add(&mut s, "e.jpg", "2026-05-01T11:00:01", Some((Some(2), 30.0, false))); + let x = add(&mut s, "x.jpg", "2026-05-01T12:00:00", Some((None, 50.0, false))); + let y = add(&mut s, "y.jpg", "2026-05-01T13:00:00", None); + s.catalog.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap(); + (s, [a, b, c, d, e, x, y]) +} + +#[test] +fn a_photo_dragged_to_the_front_of_its_burst_becomes_the_pick() { + let (mut s, [a, b, c, ..]) = library(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + let commits = s.commits(); + // the softest shot is the one the person likes best + let r = mv(&mut s, json!({"ids": [c.0], "index": 0})); + assert_eq!((r["burst"].clone(), r["photos"].clone(), r["pick"].clone()), (json!(1), json!([c.0, a.0, b.0]), json!(c.0)), "{r}"); + assert_eq!(s.catalog.burst(1), vec![c, a, b]); + assert!(an(&s, c).best && !an(&s, a).best); + assert_eq!([an(&s, c).rank, an(&s, a).rank, an(&s, b).rank], [Some(0), Some(1), Some(2)], "the whole burst is now arranged by hand"); + // the Pick culling gave the old best goes with it + assert_eq!((flag(&s, c), flag(&s, a)), (Flag::Pick, Flag::None)); + // and so does Best of Similar Shots + s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + let shown = s.visible_cloned(); + assert!(shown.contains(&c) && !shown.contains(&a), "{shown:?}"); + // one undo step + assert_eq!(s.commits(), commits + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + assert!(an(&s, a).best && an(&s, a).rank.is_none()); + assert_eq!((flag(&s, a), flag(&s, c)), (Flag::Pick, Flag::None)); + // reordering further back: the pick stays, the order is kept + mv(&mut s, json!({"ids": [b.0], "index": 2})); + assert_eq!(s.catalog.burst(1), vec![a, c, b]); + assert!(an(&s, a).best); + assert_eq!(flag(&s, a), Flag::Pick); + // placing a photo where it already is changes nothing and makes no undo step + let commits = s.commits(); + let r = mv(&mut s, json!({"ids": [a.0], "index": 0})); + assert_eq!(r["changed"], false, "{r}"); + assert_eq!(s.commits(), commits); +} + +#[test] +fn photos_move_between_bursts_into_new_ones_and_out() { + let (mut s, [a, b, c, d, e, x, y]) = library(); + // e joins burst 1 in second place; burst 2 keeps only d, which is then in no burst + let r = mv(&mut s, json!({"ids": [e.0], "burst": 1, "index": 1})); + assert_eq!(r["photos"], json!([a.0, e.0, b.0, c.0]), "{r}"); + assert_eq!(an(&s, e).group, Some(1)); + assert!(s.catalog.burst(2).is_empty()); + assert_eq!((an(&s, d).group, an(&s, d).best, an(&s, d).by_hand()), (None, false, true)); + // without an index it goes last; a culled loose photo can join too + mv(&mut s, json!({"ids": [x.0], "burst": 1})); + assert_eq!(s.catalog.burst(1), vec![a, e, b, c, x]); + // two photos make a new burst, in the order named + let r = mv(&mut s, json!({"ids": [c.0, b.0], "burst": "new"})); + let new = r["burst"].as_u64().unwrap() as u32; + assert_ne!(new, 1, "a number no photo uses: {r}"); + assert_eq!(s.catalog.burst(new), vec![c, b]); + assert!(an(&s, c).best); + assert_eq!(s.catalog.burst(1), vec![a, e, x]); + // out of every burst: the photo left alone in its burst is out too + let r = mv(&mut s, json!({"ids": [b.0], "burst": null})); + assert_eq!(r["burst"], Value::Null, "{r}"); + assert!(s.catalog.burst(new).is_empty()); + assert!([b, c].iter().all(|p| an(&s, *p).group.is_none() && !an(&s, *p).best && an(&s, *p).by_hand())); + // a whole burst dropped on another merges them, the target's pick first + mv(&mut s, json!({"ids": [b.0, c.0], "burst": "new"})); + let merged = s.catalog.burst(1); + let theirs = s.catalog.bursts_among(&[b], None)[0].clone(); + mv(&mut s, json!({"ids": theirs.1.iter().map(|p| p.0).collect::>(), "burst": 1})); + assert_eq!(s.catalog.burst(1), [merged, theirs.1].concat()); + assert!(s.catalog.burst(theirs.0).is_empty()); + // refused, with nothing changed: a photo never culled, a burst that isn't there, a bad index + let commits = s.commits(); + for (p, why) in [ + (json!({"ids": [y.0], "burst": 1}), "Assisted Culling"), + (json!({"ids": [a.0], "burst": 99}), "no burst 99"), + (json!({"ids": [a.0], "index": -1}), "index"), + (json!({"ids": [a.0], "burst": "first"}), "burst"), + (json!({"ids": [d.0]}), "isn't in a burst"), + (json!({"ids": []}), "no photos"), + ] { + let err = s.execute("photo.moveToBurst", &p).expect_err(&p.to_string()).to_string(); + assert!(err.contains(why), "{p}: {err}"); + } + assert_eq!(s.commits(), commits); + // a new burst may start with one photo, for more to join + let r = mv(&mut s, json!({"ids": [d.0], "burst": "new"})); + let solo = r["burst"].as_u64().unwrap() as u32; + assert_eq!(s.catalog.burst(solo), vec![d]); + assert!(an(&s, d).best); + mv(&mut s, json!({"ids": [x.0], "burst": solo, "index": 0})); + assert_eq!(s.catalog.burst(solo), vec![x, d]); +} + +#[test] +fn a_stacked_burst_follows_its_pick_and_its_members() { + let (mut s, [a, b, c, d, e, ..]) = library(); + // as Assisted Culling with "Stack each burst" leaves them: collapsed, the best on top + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(1), photos: vec![a, b, c], collapsed: true } }).unwrap(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(2), photos: vec![d, e], collapsed: true } }).unwrap(); + mv(&mut s, json!({"ids": [c.0], "index": 0})); + let st = s.catalog.stack_of(c).unwrap(); + assert_eq!((st.photos.clone(), st.collapsed), (vec![c, a, b], true), "the new pick tops the stack"); + // d moves into burst 1: its stack (now just e) goes, burst 1's stack takes it in + s.selection = crate::Selection::single(d); + mv(&mut s, json!({"ids": [d.0], "burst": 1, "index": 1})); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, d, a, b]); + assert!(s.catalog.stack_of(e).is_none()); + // d is hidden in the collapsed stack now: the stack's top is the active photo + assert_eq!(s.selection.active, Some(c)); + // one undo brings both stacks back as they were + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![d, e]); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, a, b]); + // a photo stacked with something else than its burst keeps that stack when it goes to an unstacked burst + let (mut s, [a, b, c, _, e, x, _]) = library(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(5), photos: vec![x, e], collapsed: false } }).unwrap(); + mv(&mut s, json!({"ids": [e.0], "burst": 1})); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![x, e]); + assert_eq!(s.catalog.burst(1), vec![a, b, c, e]); +} + +/// Look-alike PNGs (a scene and two softer copies) for the culling runs below. +fn burst_files(tag: &str, scene: usize) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lc-bursts-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_scenes::demo_library()[scene].render(480, 320); + let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out + }; + for (name, im) in [("1_sharp.png", img.clone()), ("2_soft.png", soften(&img, 3)), ("3_softer.png", soften(&img, 6))] { + let data: Vec<[u8; 4]> = im + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: im.width, height: im.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(dir.join(format!("s{scene}_{name}")), png).unwrap(); + } + dir +} + +#[test] +fn culling_again_keeps_bursts_arranged_by_hand() { + let (one, two) = (burst_files("keep-1", 0), burst_files("keep-2", 7)); + let mut s = Session::new().with_fs(); + let import = |s: &mut Session, dir: &std::path::Path, hour: u32| -> Vec { + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let mut ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).map(PhotoId).collect(); + ids.sort_by_key(|id| s.catalog.photo(*id).unwrap().file_name.clone()); + for (i, id) in ids.iter().enumerate() { + s.commit("t", Op::SetCaptured { id: *id, captured: Some(format!("2026-05-01T{hour:02}:00:0{i}")) }).unwrap(); + } + ids + }; + let first = import(&mut s, &one, 10); + let second = import(&mut s, &two, 14); + let ids = |v: &[PhotoId]| v.iter().map(|p| p.0).collect::>(); + // two runs on different photos number their bursts apart + s.execute("photo.analyze", &json!({"ids": ids(&first), "pickBest": true})).unwrap(); + s.execute("photo.analyze", &json!({"ids": ids(&second)})).unwrap(); + let (g1, g2) = (an(&s, first[0]).group.unwrap(), an(&s, second[0]).group.unwrap()); + assert_ne!(g1, g2, "each run's bursts get numbers of their own"); + assert_eq!(s.catalog.burst(g1), first, "sharpest first"); + // the softest is the person's pick + let softest = first[2]; + mv(&mut s, json!({"ids": [softest.0], "index": 0})); + assert_eq!(flag(&s, softest), Flag::Pick); + // culling the whole view again keeps that burst as arranged, with fresh scores + let r = s.execute("photo.analyze", &json!({"ids": ids(&[first.clone(), second.clone()].concat()), "pickBest": true})).unwrap(); + assert_eq!(r["kept"], 3, "{r}"); + assert_eq!(s.catalog.burst(g1), vec![first[2], first[0], first[1]]); + assert!(an(&s, softest).best && !an(&s, first[0]).best); + assert_eq!(flag(&s, first[0]), Flag::None, "pickBest picks the pick chosen by hand, not the sharpest"); + let g2_again = an(&s, second[0]).group.unwrap(); + assert_ne!(g2_again, g1, "an automatic burst never takes a hand-made burst's number"); + assert_eq!(s.catalog.burst(g2_again), second); + // asked to regroup, culling forgets the order set by hand + s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": true})).unwrap(); + let g = an(&s, first[0]).group.unwrap(); + assert_eq!(s.catalog.burst(g), first); + assert!(first.iter().all(|p| !an(&s, *p).by_hand())); + assert!(s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": "yes"})).is_err()); + let _ = std::fs::remove_dir_all(&one); + let _ = std::fs::remove_dir_all(&two); +} From 74ded5b14fbb6fb7697b81fce58c6c171c38a457 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:04:54 +0200 Subject: [PATCH 011/625] =?UTF-8?q?LR-LIB-CULL:=20Window=20=E2=96=B8=20Bur?= =?UTF-8?q?sts=20arranges=20bursts=20by=20drag=20and=20drop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A right-hand panel (`panel.bursts`) shows the bursts of the photos in view, with the hidden members of collapsed stacks, each a row of thumbnails with its pick first. Drag a photo to another place in its burst (first: it becomes the pick), into another burst, onto New burst or Not in a burst; drag a burst by its title onto another to merge them. Photos dragged from the grid drop here too. The drag is the grid's photo drag (its label says what a drop does); each drop is one `photo.moveToBurst`. Photos culling never scored are refused. The Assisted Culling dialog gets "Regroup bursts I arranged by hand" (`resetBursts`) and a hint pointing to Window ▸ Bursts. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menubar.rs | 2 + crates/ui-egui/src/menus.rs | 14 +- crates/ui-egui/src/panels/bursts.rs | 271 +++++++++++++++++++++++++++ crates/ui-egui/src/panels/dialogs.rs | 9 +- crates/ui-egui/src/panels/left.rs | 2 +- crates/ui-egui/src/panels/mod.rs | 1 + crates/ui-egui/src/panels/right.rs | 9 +- crates/ui-egui/src/state.rs | 7 +- crates/ui-egui/src/tests_bursts.rs | 207 ++++++++++++++++++++ 10 files changed, 518 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/panels/bursts.rs create mode 100644 crates/ui-egui/src/tests_bursts.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb290bd86e..4c43ec8a69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -60,6 +60,8 @@ mod tests_before_after; #[cfg(test)] mod tests_browse_active; #[cfg(test)] +mod tests_bursts; +#[cfg(test)] mod tests_button; #[cfg(test)] mod tests_canvas_keys; @@ -1625,6 +1627,8 @@ mod drop_tests { #[derive(Default)] pub struct Caches { keyword_tree: Option<(u64, std::sync::Arc>)>, + /// The Bursts panel's bursts, by the view's generation. + bursts: Option<(u64, panels::bursts::Shown)>, /// The Keywording box's read-only names (with containing keywords, or Will Export), by library /// revision, selection and view. keyword_names: Option<(u64, u64, std::sync::Arc>)>, diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index c5e4e45c77..4c2a7e4b6e 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -236,6 +236,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "panel.activity", "panel.info", "panel.keywords", + "panel.bursts", "---", "@Edit Sections", "@Tools", @@ -367,6 +368,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "panel.activity" => panel(RightPanel::Activity), "panel.info" => panel(RightPanel::Info), "panel.keywords" => panel(RightPanel::Keywords), + "panel.bursts" => panel(RightPanel::Bursts), "panel.presets" => Some(u.presets), "library.toggleAutoWriteXmp" => Some(app.session.xmp.auto_write), _ => None, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 41df245a78..01fbd49216 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -145,6 +145,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("panel.keywords", "Keywords", Some("K"), "Window"), ("panel.versions", "Versions", Some("Shift+V"), "Window"), ("panel.activity", "History", None, "Window"), + ("panel.bursts", "Bursts", None, "Window"), ("panel.close", "Close Panel", None, ""), // {solo?}: true opens just that section (⌥-click on its header); otherwise opens or closes it ("section.light", "Light", Some("Cmd+1"), "Window>Edit Sections"), @@ -1157,6 +1158,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { + panel(app, &ctx, RightPanel::Bursts, "Bursts"); + Ok(Value::Null) + } "panel.presets" => { app.ui.presets = !app.ui.presets || !crate::docking::exposed(app, crate::docking::Panel::Presets); if app.ui.presets && app.ui.view != ViewMode::Detail { @@ -1444,7 +1449,14 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option open_original_in(app, &ctx, p), "dialog.cull" => { let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, stack_groups: app.ui.cull_stack, burst_gap, similarity }); + app.ui.dialog = Some(Dialog::Cull { + reject_below: 0.0, + pick_best: true, + stack_groups: app.ui.cull_stack, + burst_gap, + similarity, + reset_bursts: false, + }); Ok(Value::Null) } "app.whatsNew" => { diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs new file mode 100644 index 0000000000..8a6d17fd9d --- /dev/null +++ b/crates/ui-egui/src/panels/bursts.rs @@ -0,0 +1,271 @@ +//! Window ▸ Bursts: Assisted Culling's bursts among the photos in view (with the hidden members of +//! their collapsed stacks), each a row of thumbnails with its pick first, to put right by hand. +//! +//! Drag a photo to another place in its burst (to the front, and it becomes the pick), into +//! another burst, onto *New burst* or onto *Not in a burst*; drag a burst by its title onto +//! another to merge them. Photos dragged from the grid drop here too. A drag is the grid's photo +//! drag ([`crate::state::UiState::dragging_photos`]: its label, Esc and release), and a drop is one +//! `photo.moveToBurst`, so one undo step. +//! +//! Widgets: `burst:{n}` (a burst's title, `n` its number), `burstPhoto:{id}`, `burstPick:{n}`, +//! `burst:new`, `burst:none`. + +use std::collections::HashSet; +use std::sync::Arc; + +use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use lightcraft_catalog::{Flag, PhotoId}; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::theme::Tokens; +use crate::widgets::register; + +/// Thumbnail cells: side, gap, row inset. +const CELL: f32 = 68.0; +const GAP: f32 = 6.0; +const INSET: f32 = 20.0; +/// A burst's title row. +const TITLE_H: f32 = 30.0; + +/// The bursts shown, by the view's generation (which follows every catalog change). +pub type Shown = Arc)>>; + +/// The bursts among the photos in view and the hidden members of their stacks, in view order. +fn bursts(app: &mut LightcraftApp) -> Shown { + let (generation, ids) = app.session.visible_shared(); + if let Some((g, b)) = &app.caches.bursts + && *g == generation + { + return b.clone(); + } + let cat = &app.session.catalog; + let mut scope: HashSet = ids.iter().copied().collect(); + for id in ids.iter() { + if let Some(st) = cat.stack_of(*id) { + scope.extend(st.photos.iter().copied()); + } + } + let b: Shown = Arc::new(cat.bursts_among(&ids, Some(&scope))); + app.caches.bursts = Some((generation, b.clone())); + b +} + +/// Where a drop under the pointer would put the dragged photos. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Target { + /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included). + Burst(u32, usize), + New, + Nowhere, +} + +pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + egui::ScrollArea::vertical().id_salt("bursts-scroll").auto_shrink([false, false]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + super::left::drag_auto_scroll(app, ui); + super::right::header(ui, "Bursts"); + let shown = bursts(app); + let dragged: Option> = app.ui.dragging_photos.as_ref().map(|v| v.iter().copied().map(PhotoId).collect()); + let pointer = ui.input(|i| i.pointer.latest_pos()).filter(|p| ui.clip_rect().contains(*p)); + let mut target: Option<(Target, Option)> = None; + let width = ui.available_width(); + let explain = if shown.is_empty() { + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand." + } else { + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them." + }; + egui::Frame::NONE.inner_margin(egui::Margin { left: INSET as i8, right: INSET as i8, top: 0, bottom: 10 }).show(ui, |ui| { + ui.set_width(width - 2.0 * INSET); + ui.label(egui::RichText::new(crate::i18n::tr(explain)).color(t.text_dim).size(12.0)); + }); + let cols = (((width - 2.0 * INSET + GAP) / (CELL + GAP)).floor() as usize).max(1); + for (k, (g, photos)) in shown.iter().enumerate() { + // the title: a drop there puts the photos last; dragged, it takes the burst along + let (title, resp) = ui.allocate_exact_size(vec2(width, TITLE_H), Sense::click_and_drag()); + register(ui.ctx(), format!("burst:{g}"), title); + let p = ui.painter(); + let name = format!("{} {}", crate::i18n::tr("Burst"), k + 1); + p.text(pos2(title.left() + INSET, title.center().y), Align2::LEFT_CENTER, name, t.semibold(12.5), t.text); + let n = photos.len(); + let count = crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n); + p.text(pos2(title.right() - INSET, title.center().y), Align2::RIGHT_CENTER, count, t.font(11.5), t.text_dim); + if resp.hovered() && dragged.is_none() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + if resp.drag_started() { + app.ui.dragging_photos = Some(photos.iter().map(|p| p.0).collect()); + } + if pointer.is_some_and(|p| title.contains(p)) { + target = Some((Target::Burst(*g, n), None)); + } + // the photos, in rows + let rows = n.div_ceil(cols); + let (area, _) = ui.allocate_exact_size(vec2(width, rows as f32 * (CELL + GAP) + GAP), Sense::hover()); + let cell_at = |i: usize| { + let (r, c) = (i / cols, i % cols); + Rect::from_min_size(pos2(area.left() + INSET + c as f32 * (CELL + GAP), area.top() + r as f32 * (CELL + GAP)), vec2(CELL, CELL)) + }; + for (i, id) in photos.iter().enumerate() { + let r = cell_at(i); + if let Some(badge) = photo_cell(app, ui, *id, r) { + register(ui.ctx(), format!("burstPick:{g}"), badge); + } + // a drop on a photo's left half goes before it, on its right half after it + if let Some(p) = pointer + && r.expand(GAP / 2.0).contains(p) + { + let slot = if p.x < r.center().x { i } else { i + 1 }; + let edge = if slot == i { r.left() - GAP / 2.0 } else { r.right() + GAP / 2.0 }; + target = Some((Target::Burst(*g, slot), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); + } + } + if target.is_none() + && let Some(p) = pointer + && area.contains(p) + { + // the room after the last photo: last + let last = cell_at(n.saturating_sub(1)); + target = Some((Target::Burst(*g, n), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); + } + if dragged.is_some() && matches!(target, Some((Target::Burst(tg, _), _)) if tg == *g) { + ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); + } + } + // drop places for a new burst and for none: there while there are bursts, or a drag + if !shown.is_empty() || dragged.is_some() { + ui.add_space(8.0); + for (key, label, tgt) in [("burst:new", "New burst", Target::New), ("burst:none", "Not in a burst", Target::Nowhere)] { + let (row, _) = ui.allocate_exact_size(vec2(width, 40.0), Sense::hover()); + let zone = row.shrink2(vec2(INSET, 4.0)); + register(ui.ctx(), key, zone); + let over = dragged.is_some() && pointer.is_some_and(|p| zone.contains(p)); + let stroke = if over { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.divider) }; + ui.painter().rect_stroke(zone, 6.0, stroke, StrokeKind::Inside); + ui.painter().text(zone.center(), Align2::CENTER_CENTER, crate::i18n::tr(label), t.font(12.0), if over { t.text } else { t.text_dim }); + if over { + target = Some((tgt, None)); + } + } + } + if let Some(ids) = dragged + && let Some((tgt, mark)) = target + { + drop_on(app, ui, &shown, &ids, tgt, mark); + } + ui.add_space(12.0); + }); +} + +/// One photo of a burst: its thumbnail, the pick's badge (returned), the active photo's outline; +/// a click selects it, a drag takes it along. +fn photo_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect) -> Option { + let t = Tokens::get(ui.ctx()); + let photo = app.session.catalog.photo(id).cloned()?; + let pick = photo.analysis.is_some_and(|a| a.best); + let resp = ui.interact(r, egui::Id::new(("burst-photo", id.0)), Sense::click_and_drag()); + register(ui.ctx(), format!("burstPhoto:{}", id.0), r); + // Any thumbnail will do at this size: one is asked for only when there is none, so the grid's + // larger ones are never asked again at this size (and back) every frame. Above the grid's own + // priorities: a member hidden in a collapsed stack isn't in the grid, which evicts the rest. + if app.renderer.thumb(id).is_none() && !app.renderer.is_pending(crate::render::Slot::Thumb(id)) { + let px = (CELL * ui.ctx().pixels_per_point()).ceil() as usize; + super::grid::request_thumb(app, id, px, 12); + } + let p = ui.painter(); + p.rect_filled(r, 3.0, Color32::from_gray(30)); + let shown = match app.renderer.thumb(id) { + Some(tex) => { + let fit = super::detail::fit_texture_rect(r, tex.size); + p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + fit + } + None => r, + }; + if photo.flag == Flag::Reject { + p.rect_filled(shown, 0.0, Color32::from_black_alpha(110)); + } + let state = app.session.selection.state_of(id); + if state == lightcraft_engine::SelectionState::Active { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::WHITE), StrokeKind::Outside); + } else if state != lightcraft_engine::SelectionState::NotSelected { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::from_gray(170)), StrokeKind::Outside); + } + let badge = pick.then(|| { + let g = p.layout_no_wrap(crate::i18n::tr("Pick").into(), t.semibold(9.5), Color32::WHITE); + let badge = Rect::from_min_size(r.min + vec2(3.0, 3.0), vec2(g.size().x + 10.0, 14.0)); + p.rect_filled(badge, 7.0, t.accent); + p.galley(pos2(badge.left() + 5.0, badge.center().y - g.size().y / 2.0), g, Color32::WHITE); + badge + }); + if photo.flag == Flag::Pick { + crate::icons::paint( + p, + Rect::from_min_size(pos2(r.right() - 16.0, r.bottom() - 16.0), vec2(13.0, 13.0)), + crate::icons::Icon::FlagPick, + t.pick, + ); + } + let focus = photo.analysis.map(|a| a.sharpness.round() as i32).unwrap_or_default(); + let resp = resp.on_hover_text(format!("{} · {} {focus}", photo.file_name, crate::i18n::tr("Focus"))); + if resp.clicked() { + let _ = app.run("library.select", json!({"ids": [id.0]})); + } + if resp.drag_started() { + app.ui.dragging_photos = Some(vec![id.0]); + } + badge +} + +/// Photos dragged over `tgt`: the mark where they would go, the label saying what a drop does, +/// and on release the move. +fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[PhotoId], tgt: Target, mark: Option) { + let t = Tokens::get(ui.ctx()); + let released = ui.input(|i| i.pointer.any_released()); + // only photos culling scored can be in a burst + if ids.iter().any(|id| app.session.catalog.photo(*id).is_none_or(|p| p.analysis.is_none())) { + ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); + let why = if ids.len() == 1 { "Run Assisted Culling on it first" } else { "Run Assisted Culling on these photos first" }; + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(why).into()); + if released { + app.toast( + ui.ctx(), + crate::i18n::tr("Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first"), + ); + app.ui.dragging_photos = None; + } + return; + } + let (params, hint) = match tgt { + Target::Burst(g, slot) => { + let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); + // the place once the dragged photos have left theirs + let index = members.iter().take(slot).filter(|m| !ids.contains(m)).count(); + let whole = shown.iter().any(|(n, m)| *n != g && m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); + let hint = if whole { + "Merge into this burst" + } else if index == 0 && slot < members.len() { + if ids.len() == 1 { "Make it the pick" } else { "Put first: the first is the pick" } + } else if ids.iter().all(|id| members.contains(id)) { + "Move here" + } else { + "Move to this burst" + }; + let index = if slot >= members.len() { Value::Null } else { json!(index) }; + (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": g, "index": index}), hint) + } + Target::New => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": "new"}), "New burst"), + Target::Nowhere => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": null}), "Take out of its burst"), + }; + if let Some(mark) = mark { + ui.painter().rect_filled(mark, 1.5, t.accent); + } + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(hint).into()); + if released { + if let Err(e) = app.run("photo.moveToBurst", params) { + app.toast(ui.ctx(), e); + } + app.ui.dragging_photos = None; + } +} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index 575ba09cd3..d55e38e4ce 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -336,7 +336,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), ); } - Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } => { let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); @@ -360,6 +360,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let r = ui.add(egui::Slider::new(similarity, 0.70..=0.99).text(crate::i18n::tr("Burst: how alike (loose … strict)")).step_by(0.01).fixed_decimals(2)); crate::widgets::register(ui.ctx(), "field:cullSimilar", r.rect); ui.label(egui::RichText::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).color(t.text_dim)); + let r = ui.checkbox(reset_bursts, crate::i18n::tr("Regroup bursts I arranged by hand")); + crate::widgets::register(ui.ctx(), "check:cullResetBursts", r.rect); + ui.label(egui::RichText::new(crate::i18n::tr("Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.")).color(t.text_dim)); ui.label(egui::RichText::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots.")).color(t.text_dim)); } Dialog::WhatsNew => { @@ -1920,10 +1923,10 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); app.ui.cull_stack = *stack_groups; - let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity}); + let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity, "resetBursts": reset_bursts}); if *reject_below > 0.0 { p["rejectBelow"] = json!(reject_below); } diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 3bb8deba2e..1b83e709c4 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -1273,7 +1273,7 @@ pub fn auto_scroll_speed(y: f32, top: f32, bottom: f32) -> f32 { /// While an album, or photos from the grid, are dragged over the sidebar: scrolls it when the /// pointer is near its top or bottom edge, so rows beyond the visible part can be reached. Call /// inside the scroll area. -fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { +pub(crate) fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { if app.ui.dragging_album.is_none() && app.ui.dragging_photos.is_none() && app.ui.dragging_section.is_none() { return; } diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 2fcb36663c..9b9eebc1c5 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -2,6 +2,7 @@ pub mod activity; pub mod bottombar; +pub mod bursts; pub mod chips; pub mod compare; pub mod crop_overlay; diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 5373308102..b17d3dd8f1 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -1,5 +1,5 @@ //! The right-hand panel next to the tool strip: Edit, Crop, Remove, Masking, Red Eye, Info, -//! Keywords, Versions, Activity. +//! Keywords, Versions, Activity, Bursts. use egui::{Align2, Rect, Sense, pos2, vec2}; use lightcraft_catalog::PhotoId; @@ -15,6 +15,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)); frame.show(ui, |ui| { + // the bursts are the view's, not a photo's: they are there without a selection + if app.ui.right == RightPanel::Bursts { + super::bursts::show(app, ui); + return; + } // (taken on every pass the panel is drawn; one from earlier than the pass before is forgotten) let held = held_offset(ui.ctx()); let Some(id) = app.session.active() else { @@ -66,7 +71,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { RightPanel::Keywords => keywords(app, ui, id), RightPanel::Versions => versions(app, ui, id), RightPanel::Activity => activity(app, ui, id), - RightPanel::None => {} + RightPanel::Bursts | RightPanel::None => {} } }); ui.data_mut(|d| d.insert_temp(egui::Id::new(AREA), scrolled.id)); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f97a4b44dd..783ccd0b4f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -37,6 +37,8 @@ pub enum RightPanel { Info, /// The profile browser (part of Edit). Profiles, + /// Assisted Culling's bursts, to arrange by hand (Window ▸ Bursts). + Bursts, } impl RightPanel { @@ -1097,13 +1099,16 @@ pub enum Dialog { WhatsNew, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best /// of each burst (and stack each burst, best on top, with `stack_groups`); shots at most - /// `burst_gap` seconds apart and at least `similarity` alike are a burst. + /// `burst_gap` seconds apart and at least `similarity` alike are a burst. Bursts arranged by + /// hand (Window ▸ Bursts) are kept unless `reset_bursts`. Cull { reject_below: f32, pick_best: bool, stack_groups: bool, burst_gap: f32, similarity: f32, + #[serde(default)] + reset_bursts: bool, }, /// Help ▸ System Info: (label, value) rows. DenoiseModel { diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs new file mode 100644 index 0000000000..e7ce2858ba --- /dev/null +++ b/crates/ui-egui/src/tests_bursts.rs @@ -0,0 +1,207 @@ +//! Window ▸ Bursts: Assisted Culling's bursts as rows of thumbnails, pick first. A photo dragged +//! to the front of its burst becomes the pick; dragged into another burst, onto New Burst or Not +//! in a Burst it moves there; a burst dragged by its title merges into another; photos dragged +//! from the grid drop here too. Each drop is one undo step. + +use egui::{Pos2, Rect, pos2}; +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::RightPanel; +use crate::{LightcraftApp, Services}; + +/// Burst 1: a (picked by culling), b, c; burst 2: d, e; f never culled. The grid, with the +/// Bursts panel open. +fn app() -> (Headless, [PhotoId; 6]) { + let mut session = lightcraft_engine::Session::new(); + let mut add = |name: &str, when: &str, culled: Option<(u32, f32, bool)>| { + let id = session.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 300, 200, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(g, sharpness, best)| Analysis { sharpness, group: Some(g), best, ..Default::default() }); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let ids = [ + add("a.jpg", "2026-05-01T10:00:00", Some((1, 80.0, true))), + add("b.jpg", "2026-05-01T10:00:01", Some((1, 60.0, false))), + add("c.jpg", "2026-05-01T10:00:02", Some((1, 40.0, false))), + add("d.jpg", "2026-05-01T11:00:00", Some((2, 70.0, true))), + add("e.jpg", "2026-05-01T11:00:01", Some((2, 30.0, false))), + add("f.jpg", "2026-05-01T12:00:00", None), + ]; + session.catalog.apply(Op::SetFlag { id: ids[0], flag: Flag::Pick }).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid"}), std::time::Duration::from_secs(10)); + assert_eq!(r["ok"], true, "{r}"); + h.app.run("panel.bursts", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert_eq!(h.app.ui.right, RightPanel::Bursts); + (h, ids) +} + +fn widget(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| { + panic!("no {id} in {:?}", h.app.widgets.iter().filter(|(w, _)| w.starts_with("burst")).map(|(w, _)| w).collect::>()) + }) +} + +fn cell(h: &Headless, id: PhotoId) -> Rect { + widget(h, &format!("burstPhoto:{}", id.0)) +} + +fn press(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerMoved(at)); + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + h.step(); +} + +fn glide(h: &mut Headless, from: Pos2, to: Pos2) { + for i in 1..=8 { + h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.step(); + } + // (synthetic input arrives a frame or two behind) + for _ in 0..3 { + h.step(); + } +} + +fn release(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + h.step(); +} + +fn drag(h: &mut Headless, from: Pos2, to: Pos2) { + press(h, from); + glide(h, from, to); +} + +fn hint(h: &Headless) -> Option { + h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::new("drag-photos-hint"))).map(|(_, text)| text) +} + +fn best(h: &Headless, id: PhotoId) -> bool { + h.app.session.catalog.photo(id).unwrap().analysis.unwrap().best +} + +#[test] +fn bursts_show_their_pick_first() { + let (h, [a, b, c, d, e, f]) = app(); + // a row per burst, its pick first + let (one, two) = (widget(&h, "burst:1"), widget(&h, "burst:2")); + assert!(one.bottom() <= cell(&h, a).top() && cell(&h, e).top() >= two.bottom(), "each title above its photos"); + assert!(cell(&h, a).left() < cell(&h, b).left() && cell(&h, b).left() < cell(&h, c).left()); + assert!(cell(&h, d).left() < cell(&h, e).left()); + widget(&h, "burstPick:1"); + assert!(widget(&h, "burstPick:1").intersects(cell(&h, a)), "the pick is marked"); + // a photo culling never saw has no row; the drop places for a new burst and for none are there + assert!(!h.app.widgets.iter().any(|(w, _)| w == &format!("burstPhoto:{}", f.0))); + widget(&h, "burst:new"); + widget(&h, "burst:none"); +} + +#[test] +fn a_photo_dragged_to_the_front_becomes_the_pick() { + let (mut h, [a, b, c, ..]) = app(); + let to = pos2(cell(&h, a).left() + 4.0, cell(&h, a).center().y); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + assert_eq!(h.app.ui.dragging_photos, Some(vec![c.0])); + assert_eq!(hint(&h).as_deref(), Some("Make it the pick")); + release(&mut h, to); + assert!(h.app.ui.dragging_photos.is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![c, a, b]); + assert!(best(&h, c) && !best(&h, a)); + assert_eq!(h.app.session.catalog.photo(c).unwrap().flag, Flag::Pick, "culling's Pick follows the pick"); + // the panel shows the new order + h.step(); + assert!(cell(&h, c).left() < cell(&h, a).left()); + // one undo step + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c]); + assert!(best(&h, a)); +} + +#[test] +fn photos_move_between_bursts_and_bursts_merge() { + let (mut h, [a, b, c, d, e, _]) = app(); + let group = |h: &Headless, id: PhotoId| h.app.session.catalog.photo(id).unwrap().analysis.unwrap().group; + // e onto burst 1 between a and b; burst 2 is left with d alone: no burst any more + let to = pos2(cell(&h, b).left() + 4.0, cell(&h, b).center().y); + let from = cell(&h, e).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c]); + assert!(h.app.session.catalog.burst(2).is_empty() && group(&h, d).is_none()); + h.step(); + // d dragged from the grid onto burst 1's title goes last + let title = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", d.0)).center(); + drag(&mut h, from, title); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, title); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c, d]); + h.step(); + // b onto New Burst: a burst of its own, which c then joins by its title + let new = widget(&h, "burst:new").center(); + let from = cell(&h, b).center(); + drag(&mut h, from, new); + assert_eq!(hint(&h).as_deref(), Some("New burst")); + release(&mut h, new); + let g = group(&h, b).expect("a new burst"); + assert_eq!(h.app.session.catalog.burst(g), vec![b]); + h.step(); + let to = widget(&h, &format!("burst:{g}")).center(); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(g), vec![b, c]); + h.step(); + // e onto Not in a Burst + let out = widget(&h, "burst:none").center(); + let from = cell(&h, e).center(); + drag(&mut h, from, out); + assert_eq!(hint(&h).as_deref(), Some("Take out of its burst")); + release(&mut h, out); + assert!(group(&h, e).is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d]); + h.step(); + // a burst dragged by its title onto another merges into it + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("burst:{g}")).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Merge into this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c]); + assert!(h.app.session.catalog.burst(g).is_empty()); +} + +#[test] +fn a_photo_never_culled_is_refused() { + let (mut h, [_, _, _, _, _, f]) = app(); + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", f.0)).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Run Assisted Culling on it first")); + let commits = h.app.session.commits(); + release(&mut h, to); + assert_eq!(h.app.session.commits(), commits); + let toast = h.app.ui.toast.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default(); + assert!(toast.contains("Assisted Culling"), "{toast}"); +} From 507d4d344075f1705121ea767874886bf0c88610 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:04:54 +0200 Subject: [PATCH 012/625] LR-LIB-CULL: German strings and checklist for bursts arranged by hand Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/de.json | 24 +++++++++++++++++++++++- docs/parity-checklist.md | 5 +++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 4d08cbd4a4..9a9f6eaed6 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2345,5 +2345,27 @@ "Checking the GPU…": "GPU wird geprüft …", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Ein Gesichtsmodell nutzt die GPU nur, wenn eine Prüfung zeigt, dass sie dieselben Ergebnisse schneller liefert.", - "Checking the GPU for faces": "GPU für Gesichter wird geprüft" + "Checking the GPU for faces": "GPU für Gesichter wird geprüft", + "Bursts": "Serien", + "Burst": "Serie", + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand.": "Foto → Unterstützte Fotoauswahl… fasst ähnliche Aufnahmen zu Serien zusammen. Hier lassen sie sich von Hand korrigieren.", + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them.": "Ziehe ein Foto an seinen Platz: Das erste einer Serie ist ihre Auswahl. Ziehe ein Foto in eine andere Serie oder eine Serie an ihrem Titel auf eine andere, um sie zusammenzuführen.", + "New burst": "Neue Serie", + "Not in a burst": "In keiner Serie", + "Run Assisted Culling on it first": "Zuerst die unterstützte Fotoauswahl darauf anwenden", + "Run Assisted Culling on these photos first": "Zuerst die unterstützte Fotoauswahl auf diese Fotos anwenden", + "Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first": "Nur Fotos, die die unterstützte Fotoauswahl bewertet hat, können in einer Serie sein: Wende zuerst Foto → Unterstützte Fotoauswahl… darauf an", + "Merge into this burst": "Mit dieser Serie zusammenführen", + "Make it the pick": "Zur Auswahl machen", + "Put first: the first is the pick": "An den Anfang: Das erste ist die Auswahl", + "Move here": "Hierher verschieben", + "Move to this burst": "In diese Serie verschieben", + "Take out of its burst": "Aus der Serie nehmen", + "Regroup bursts I arranged by hand": "Von Hand geordnete Serien neu gruppieren", + "Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.": "Serien lassen sich unter Fenster → Serien per Ziehen korrigieren: Das erste Foto einer Serie ist ihre Auswahl, und eine erneute Fotoauswahl behält, was du geordnet hast.", + "Choose Burst Pick": "Auswahl der Serie wählen", + "Rearrange Burst": "Serie umordnen", + "Move to Burst": "In Serie verschieben", + "New Burst": "Neue Serie", + "Remove from Burst": "Aus Serie nehmen" } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 32488a4dda..5d8c4f26fb 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: bursts can be stacked, best on top) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: bursts arranged by hand) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -116,7 +116,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `cmd:photo.moveToBurst`, `cmd:panel.bursts`, `crates/pipeline/src/cull.rs`, `crates/ui-egui/src/panels/bursts.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; bursts put right by hand in Window ▸ Bursts (drag a photo within its burst — first place is the pick, and the Pick flag culling set, Best of Similar Shots and a stacked burst's top follow — into another burst, a new one or none; drag a burst onto another to merge; kept when culling runs again unless *Regroup bursts I arranged by hand*); classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs` | “Copy N” badge, stacked with the original, same albums, no XMP writes; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-19 | patch | LR-LIB-CULL: bursts can be arranged by hand by drag and drop in Window ▸ Bursts; the first photo of a burst is its pick, and culling again keeps the arrangement (`photo.moveToBurst`, `panel.bursts`, `photo.analyze` `resetBursts`). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling can stack each burst collapsed with its best photo on top (dialog checkbox, `photo.analyze` `stackGroups`; #2277). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling's burst gap and similarity are adjustable (dialog, `photo.analyze` `burstGap` / `similarity`; #2275). Statuses and feature counts unchanged. | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | From 78a01f47dbe1c61f6bf533df0e258abc2a1efacf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 19 Oct 2026 11:29:52 +0000 Subject: [PATCH 013/625] #2270: a host bridge for pages framing the web build (?host=parent) A same-origin page that embeds LightCraft in an iframe can now speak to it over postMessage, with the protocol PdfCraft, GridCraft and DeckCraft share (deckcraft#983), under lightcraft: message types: - ready {version} / failed {error} at start-up; - open {name, bytes} from the page adds a photo, as one dropped on the window (the name gives the format); - save {name, bytes} replaces every download: exports, preset and keyword files, the library backup (handed over as a transferred ArrayBuffer); - dirty {dirty} whenever closing the page would start or stop losing something (a write to browser storage queued or running, or changes storage refused), so the page can ask before closing a window with edits; - cmd {id, params} runs a command like lightcraft.command(..) and is answered with response {ok, value}. Only the parent window on the page's own origin is heard or answered. There is no docClosed: LightCraft has a library, not documents. The message layer (apps/lightcraft-web/src/host.rs) is plain Rust with native tests; the postMessage part is wasm32 only. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AbegtYaPuwqZ81pGfELsFK --- apps/lightcraft-web/src/host.rs | 340 ++++++++++++++++++++++++++++++ apps/lightcraft-web/src/lib.rs | 3 + apps/lightcraft-web/src/safety.rs | 10 +- apps/lightcraft-web/src/web.rs | 112 ++++++++-- docs/web.md | 13 ++ docs/whats-new.md | 7 + 6 files changed, 469 insertions(+), 16 deletions(-) create mode 100644 apps/lightcraft-web/src/host.rs diff --git a/apps/lightcraft-web/src/host.rs b/apps/lightcraft-web/src/host.rs new file mode 100644 index 0000000000..8b6a5997db --- /dev/null +++ b/apps/lightcraft-web/src/host.rs @@ -0,0 +1,340 @@ +//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed +//! LightCraft in an `